# Video

With easy-to-use API, the video module is a powerful tool developed to enhance and manipulate local multimedia videos. It makes complex video editing features available for developers without much coding some features are listed here:

* AI-based Denoising: Utilizing high-level Artificial intelligence to reduce noise in video effectively.
* Thumbnail generation: Preview of video is crucial, thumbnail generation gives you the preview image from the timeframe you need. &#x20;
* Trimming: Split the video to your desired size and remove unwanted material.
* Rotating: Make a video to the right orientation you need
* Concat or Merge: Seamlessly combine multiple videos to make a single long video, to merge the video
* Video Information: Extract video information such as resolution, duration, codec information, and other relevant metadata&#x20;

Primary Benefit\
This enhancement offers significant improvements to the developer experience in multiple aspects:

1. Streamlining the process of editing features like trimming and rotating seamlessly.
2. Providing the ability to specify desired features with a single function call, granting precise control.

Ease of use\
Facilitates focusing on targeted tasks such as:

1. Thumbnail generation
2. Noise clearance
3. Video editing

### Adding Module <a href="#adding-module" id="adding-module"></a>

{% tabs %}
{% tab title="Capacitor" %}
{% code overflow="wrap" %}

```json
npm install @trunpm/truvideo-capacitor-video-sdk --registry=https://registry.npmjs.org/ --//registry.npmjs.org/:_authToken=<YOUR_TOKEN>
```

{% endcode %}
{% endtab %}
{% endtabs %}

Import the following dependency in your file, here you will use these function.

{% tabs %}
{% tab title="Capacitor" %}

```tsx
import { 
    cleanNoise, 
    compareVideos, 
    ConcatBuilder, 
    editVideo, 
    EncodeBuilder, 
    FrameRate, 
    generateThumbnail, 
    getResultPath, 
    getVideoInfo, 
    MergeBuilder, 
    type BuilderResponse 
} from '@trunpm/truvideo-capacitor-video-sdk';
```

{% endtab %}
{% endtabs %}

### Video Information

* The `TruVideoVideoSdk` has a `getVideoInfo` function provides video info such as resolution, duration, codec information and relevant metadata.

{% tabs %}
{% tab title="JS" %}

```jsx
async function getVideoInformation() {
  try {
    const result : MediaInfo  = await getVideoInfo(payload);
    console.log("Get Video Info Response:", result);
  } catch (error) {
    console.error("❌ Failed to Get Video Info:", error);
  } 
}
```

{% endtab %}
{% endtabs %}

MediaInfo Type&#x20;

```tsx
interface MediaInfo {
  path : string;
  size : number;
  durationMillis : number;
  format : string;
  videoTracks : VideoTrack[];
  audioTracks : AudioTrack[];
}
interface VideoTrack {
  index : string;
  width : string;
  height : string;
  rotatedWidth : string;
  rotatedHeight : string;
  codec : string;
  codecTag : string;
  pixelFormat : string;
  bitrate : string;
  frameRate : string;
  rotation : string;
  durationMillis : string;
}
interface AudioTrack {
  index: string;
  bitrate: string;
  sampleRate: string;
  channels: string;
  codec: string;
  codecTag: string;
  durationMillis: string;
  channelLayout: string;
  sampleFormat: string;
}
```

### Compare Video

* The `TruVideoVideoSdk` has a `compareVideos` function compare multiple videos and returns the boolean accordingly as the concat video needs to have the same characteristics i.e it return true videos are compatible with concat otherwise[^1] not.

{% tabs %}
{% tab title="JS" %}

```jsx
async function videoComparison() {
  const videoPath = JSON.stringify(selectedVideos);
  try {
    const result = await compareVideos(videoPath);
    console.log("Comparison result:", result);
  } catch (error) {
    console.error("❌ Failed to Compare Videos:", error);
  } finally {
    
  }
}
```

{% endtab %}
{% endtabs %}

### Edit Video&#x20;

The `TruVideoVideoSdk` has a `editVideo` function that takes a filePath & resulthPath&#x20;

{% tabs %}
{% tab title="JS" %}

```jsx
async function videoEditing() {
  try {
    const resultPathResponse = await getResultPath(`${Date.now()}-editVideo`);
    const { result } = await editVideo(filePath, resultPathResponse.result);
    console.log("Edit Video Response:", result);
    if (result) toast.success('Edit successful!');
  } catch (error) {
    console.error("❌ Failed to Edit Video:", error);
  } finally {
    
  }
}
```

{% endtab %}
{% endtabs %}

### Thumbnail Generation

Preview of video is crucial, thumbnail generation gives you the preview image from the timeframe you need.

* The TruVideoVideoSdk has a generateThumbnail function this method takes the videoPath, resultPath, position, width, height as input and places the image at the resulting path.&#x20;

{% tabs %}
{% tab title="JS" %}

```tsx
async function generateVideoThumbnail() {
    
  try {
    const resultPathResponse = await getResultPath(`${Date.now()}-thumbnail`);
    const { result } = resultPathResponse; // output path

    const videoPath = safeFirstSelected; // input path
    const position = 1000;
    const width = 640;
    const height = 480;
    const precise = false;

    const { result: thumbnailPath } = await generateThumbnail(
      videoPath,
      result,
      position,
      width,
      height,
      precise
    );
    console.log("Thumbnail Generation Result:", thumbnailPath);
  } catch (error) {
    console.error("❌ Failed to Generate Thumbnail:", error);
  } finally {
    
  }
}
```

{% endtab %}
{% endtabs %}

### Noise Cancellation&#x20;

We are utilizing high-level Artificial intelligence for noise cancellation over the input video. It’s useful for video containing background noises.

* This function takes video path, result path, and callback and places a new video to the resulting path after clearing noise

{% tabs %}
{% tab title="JS" %}

```jsx
async function cleanVideoNoise() {
  try {
    const resultPathResponse = await getResultPath(`${Date.now()}-thumbnail`);
    const { result } = await cleanNoise(safeFirstSelected, resultPathResponse.result);
    console.log("Clean Noise Result:", result);
  } catch (error) {
    console.error("❌ Failed to Clean Noise:", error);
  } finally {
    
  }
},
```

{% endtab %}
{% endtabs %}

### Concat Videos

* Concatenation uses a specific algorithm to merge multiple videos one after another to make one video efficiently and make a completely new video. This method takes the video list, and result path to place a new video and place a new video and place the video at the given result path.

<pre data-overflow="wrap"><code>Note:
<strong>1. There are certain restrictions for concat to work, all the provided videos should be of the same character such as resolution, audio codec, video codec, pixel format, and many more. The difference could raise an exception. 
</strong><strong>2. To check whether videos are compatible use compare method first given above.
</strong></code></pre>

{% tabs %}
{% tab title="JS" %}

```jsx
async function concatVideos() {
  if (!safeFirstSelected || selectedVideos.length === 0) return;

  try {
    const resultPathResponse = await getResultPath(`${Date.now()}-concat`);

    const builder = new ConcatBuilder(
      JSON.stringify(selectedVideos), // input path
      resultPathResponse.result // output path
    );
    await builder.build();
    console.log("Success Builder Function");
    // process concatination
    const response : BuilderResponse = await builder.process();
    // to cancel processing 
    //await builder.cancel();
  } catch (error) {
    console.error("❌ Failed to Concat Videos:", error);
  }
}
```

{% endtab %}
{% endtabs %}

### Merge Videos

* The TruVideoVideoSdk has a mergeVideos function have  same functionality as concat to merge multiple videos to make one another video but there is an advantage over contact to merge all video does not have to be of same configuration.
* This method takes video URIs list, and result path to place a new video and place the video at the given result path

<pre data-overflow="wrap"><code>Note:
<strong>1 Any type of video resolution can be merged no exception will occur
</strong><strong>2 Unlike concat this method involves reencoding the input videos, making it less performant, and processing time may be considerable (depending on the device's processing power).
</strong><strong>3 It automatically calculates the resulting video resolution to ensure that all input videos can be displayed correctly
</strong></code></pre>

{% tabs %}
{% tab title="JS" %}

```jsx
async function mergeVideos() {
  try {
    const resultPathResponse = await getResultPath(`${Date.now()}-thumbnail.mp4`);
    const builder = new MergeBuilder(
      JSON.stringify(selectedVideos), // input path
      resultPathResponse.result // output path
    );
    builder.setHeight(720);
    builder.setWidth(1280);
    builder.setFrameRate(FrameRate.thirtyFps);

    await builder.build();
    const response : BuilderResponse = await builder.process();
    // to cancel processing 
    // await builder.cancel();
  } catch (error) {
    console.error("Failed to merge videos:", error);
  } 
}
```

{% endtab %}
{% endtabs %}

### Encode Video

The TruVideoVideoSdk has a encodeVideo function constructs to carry out a an encoding operation. This operation enables modification to a video by altering one or more of its attribute, such as:-

* Resolution via width and height parameters
* Video codec (options: .h264, .h265)
* Audio codec (options: .aac, .mp3, .ac3)
* Frame rate (options: 24fps, 25fps, 30fps, 50fps, 60fps)

{% tabs %}
{% tab title="JS" %}

```jsx
async function encodeVideo() {
  try {
    const resultPathResponse = await getResultPath(`${Date.now()}-thumbnail.mp4`);

    const builder = new EncodeBuilder(
      JSON.stringify(safeFirstSelected), // input path 
      resultPathResponse.result // output path
    );
    builder.setHeight(720);
    builder.setWidth(1280);
    builder.setFrameRate(FrameRate.thirtyFps);

    await builder.build();
    const response : BuilderResponse = await builder.process();
    // to cancel processing 
    // await builder.cancel();
  } catch (error) {
    console.error('Failed to Encode Video:', error);
  } finally {
   
  }
}
```

{% endtab %}
{% endtabs %}

### BuilderResponse

```tsx
interface BuilderResponse {
    id: string;
    createdAt: string;
    status: string;
    type: string;
    updatedAt: string;
}
```

### GetAllRequest

This function will provide all the requests created for Encode, Concat and Merge Builder

* Input Params&#x20;

```tsx
var videoStatus : VideoStatus | undefined = undefined // for all status 

// for specific status 
enum VideoStatus {
  processing,
  completed,
  idle,
  cancel,
  error,
}
```

* Function Utilisation&#x20;

```tsx
const requests : BuilderResponse[]  = await getAllRequest(videoStatus);
```

### GetRequestById

This function will return exact request associated with the id&#x20;

```tsx
const request : BuilderResponse = getRequestById(id : string);
```

[^1]:
