npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

cordova-plugin-video-helper

v2.0.3

Published

Compress Video and get video infos.

Downloads

8

Readme

npm version

This is a cordova plugin to assist in several video editing tasks such as:

  • Transcoding
  • Trimming
  • Creating thumbnails from a video file with specific time in the video
  • Getting info on a video - width, height, orientation, duration, size, & bitrate.

This plugin will address those concerns, hopefully.

Installation

cordova plugin add cordova-plugin-video-helper

VideoHelper will be available in the window after deviceready.

Usage

Transcode a video

// parameters passed to transcodeVideo
window.VideoHelper.transcodeVideo(
    success, // success cb
    error, // error cb
    {
        fileUri: 'file-uri-here', // the path to the video on the device
        outputFileName: 'output-name', // the file name for the transcoded video
        width: 340, // optional, see note below on width and height
        height: 640, // optional, see notes below on width and height
        videoBitrate: 5000000, // optional, bitrate in bits, defaults to 5 megabit (5000000),
        duration: 60, // optinal for triming while compressing
        type: 'ffmpeg' // optinal default for ffmpeg. You can use MediaCoder for compress(Only android)
    }
);

transcodeVideo example -

// this example uses the cordova media capture plugin
window.device.capture.captureVideo(
    videoCaptureSuccess,
    videoCaptureError,
    {
        limit: 1,
        duration: 20
    }
);

function videoCaptureSuccess(mediaFiles) {
    var outputFileName = (
        new Date().getTime()
    ).toString() + (
        outputFileName ? outputFileName : this.getFileNameFromURL(fileUrl)
    );
    const mediaSizeResult: {
        error: boolean,
        data: { bitrate: string, duration: string, height: string, orientation: string, size: number, width: string }
    } = this.getVideoInformation(fileUrl);

    const originalSize = Math.floor(+mediaSizeResult.data.size / 1024) / 1000 + 'MB';
    const originalBitrate = +mediaSizeResult.data.bitrate;
    const originalPath = fileUrl;
    let width: number = 360;
    let height: number = 640;
    if (maintainAspectRatio) {
        const aspectRatio: {
            width: number,
            height: number
        } = this.getAspectRatio(Math.floor(+mediaSizeResult.data.width), +mediaSizeResult.data.height);
        width = aspectRatio.width;
        height = aspectRatio.height;
    }

    window.VideoHelper.transcodeVideo(
        {
            fileUri,
            outputFileName,
            width,
            height,
            videoBitrate,
            duration,
            type
        },
        async (info: {
            progress: number,
            completed: boolean,
            error: boolean,
            data: string,
            message: string
        }): Promise<any> => {
            if (info.error) {
                return resolve({error: true, data: null, message: info.message});
            }
            if (info.completed) {
                const mediaSizeResult: {
                    error: boolean,
                    data: {
                        bitrate: string,
                        duration: string,
                        height: string,
                        orientation: string,
                        size: number,
                        width: string
                    }
                } = await this.getVideoInformation(info.data);
                return resolve({error: false, data: mediaSizeResult.data, message: null});
            } else {
                console.log('transCodeVideo - Progresss:', info);
            }
        },
        (error) => {
            console.error('Error transCodeVideo:', error);
            return resolve({error: true, data: null, message: error.message});
        }
    );
}

function getVideoInformation(videoPath: string) {
    return new Promise(async (resolve: <T>(value: {
        error: boolean,
        data: { bitrate: string, duration: string, height: string, orientation: string, size: number, width: string }
    }) => void): Promise<void> => {
        window.VideoHelper.getVideoInfo(
            videoPath,
            (info): any => {
                return resolve({error: false, data: info});
            },
            (error) => {
                console.error('Error fetching video info:', error);
                return resolve({error: true, data: null});
            }
        );
    });
}

function getAspectRatio(width: number, height: number, scaledWidth: number = 640, scaledHeight: number = 640) {
    const videoWidth = width > height ? height : width;
    const videoHeight = width > height ? width : height;
    const aspectRatio = videoWidth / videoHeight;

    const newWidth = scaledWidth && scaledHeight ? scaledHeight * aspectRatio : videoWidth;
    const newHeight = scaledWidth && scaledHeight ? newWidth / aspectRatio : videoHeight;

    return {width: newWidth, height: newHeight};
}

function getFileNameFromURL(url) {
    if (!url) {
        return (
            new Date().getTime()
        ).toString();
    }
    let fileName = url.substr(url.lastIndexOf('/') + 1);
    if (fileName.indexOf('?') != -1) {
        fileName = fileName.substr(0, fileName.indexOf('?'));
    }
    const split = fileName.split('.');
    if (split.length > 1) {
        fileName = split.slice(0, split.length - 1).join('_');
    } else if (split.length > 0) {
        fileName = split[0];
    }
    return fileName;
}

Trim a Video

VideoHelper.trim(
    {
        fileUri: 'file-uri-here', // path to input video
        duration: 15, // time to end trimming in seconds
        outputFileName: 'output-name', // output file name
    },
    trimSuccess,
    trimFail,
);

function trimSuccess(result) {
    // result is the path to the trimmed video on the device
    console.log('trimSuccess, result: ' + result);
}

function trimFail(err) {
    console.log('trimFail, err: ' + err);
}

Create a JPEG thumbnail from a video

VideoHelper.createThumbnail(
    {
        fileUri: 'file-uri-here', // the path to the video on the device
        outputFileName: 'output-name', // the file name for the JPEG image
        atTime: 2, // optional, location in the video to create the thumbnail (in seconds)
        width: 320, // optional, width of the thumbnail
        height: 480, // optional, height of the thumbnail
    },
    success, // success cb
    error, // error cb
);
// atTime will default to 0 if not provided
// width and height will be the same as the video input if they are not provided
// quality will default to 100 if not provided

A note on width and height used by createThumbnail

The aspect ratio of the thumbnail created will match that of the video input. This means you may not get exactly the width and height dimensions you give to createThumbnail for the jpeg. This for your convenience but let us know if it is a problem.

Get info on a video (width, height, orientation, duration, size, & bitrate)

VideoHelper.getVideoInfo(
    success, // success cb
    error, // error cb
    {
        fileUri: 'file-uri-here', // the path to the video on the device
    }
);
VideoHelper.getVideoInfo(
    getVideoInfoSuccess,
    getVideoInfoError,
    {
        fileUri: file.fullPath
    }
);

function getVideoInfoSuccess(info) {
    console.log('getVideoInfoSuccess, info: ' + JSON.stringify(info, null, 2));
    {
        /*
        width: 1920,
        height:1080,
        orientation:'landscape', // will be portrait or landscape
        duration:3.541, // duration in seconds
        size:6830126, // size of the video in bytes
        bitrate:15429777 // bitrate of the video in bits per second,
        videoMediaType: 'video/3gpp' // Media type of the video, android example: 'video/3gpp', ios example: 'avc1',
        audioMediaType: 'audio/mp4a-latm' // Media type of the audio track in video, android example: 'audio/mp4a-latm', ios example: 'aac',
         */
    }
}

On iOS

iOS Developer AVFoundation Documentation

Video compression in AVFoundation

AVFoundation slides - tips/tricks

AVFoundation slides #2

Bob McCune's AVFoundation Editor - ios app example

Saving videos after recording videos

On Android

Android Documentation

Android Media Stores

How to Port ffmpeg (the Program) to Android–Ideas and Thoughts

How to Build Android Applications Based on FFmpeg by An Example