GithubHelp home page GithubHelp logo

c4spar / deno-fast-forward Goto Github PK

View Code? Open in Web Editor NEW
47.0 3.0 4.0 364 KB

An easy to use ffmpeg module for Deno. ๐Ÿฆ•

License: MIT License

TypeScript 100.00%
deno ffmpeg ffprobe encoding

deno-fast-forward's Introduction

Fast Forward

An easy to use ffmpeg module for Deno.

Version Build status issues Deno version doc Licence
deno.land nest.land

โš ๏ธ Work In Progress! Expect breaking changes!

Contents

Installation

This is a Deno module and can be imported directly from the repo and from following registries.

Deno Registry

import { ffmpeg } from "https://deno.land/x/fast_forward@<version>/mod.ts";

Nest Registry

import { ffmpeg } from "https://x.nest.land/fast_forward@<version>/mod.ts";

Github

import { ffmpeg } from "https://raw.githubusercontent.com/c4spar/deno-fast-forward/<version>/mod.ts";

Usage

await ffmpeg("https://www.w3schools.com/html/mov_bbb.mp4")
  // Global encoding options (applied to all outputs).
  .audioBitrate("192k")
  .videoBitrate("1M")
  .width(480)
  .height(640)
  // Ouput 1.
  .output("output.mp4")
  .audioCodec("aac")
  .videoCodec("libx264")
  // Ouput 2.
  .output("output.webm")
  .audioCodec("libvorbis")
  .videoCodec("libvpx-vp9")
  // Start encoding.
  .encode();

console.log("All encodings done!");
$ deno run --allow-read --allow-run https://deno.land/x/fast_forward/examples/usage.ts

Getting Started

First create an instance of FFmpeg.

const encoder = ffmpeg("https://www.w3schools.com/html/mov_bbb.mp4");
// or using the constructor
const encoder = new FFmpeg("https://www.w3schools.com/html/mov_bbb.mp4");

Then you can define global options and events which will be applied to all defined outputs.

encoder
  .audioBitrate("192k")
  .videoBitrate("1M")
  .addEventListener(
    "progress",
    (event) => console.log("Progress: %s", event.progress),
  )
  .addEventListener("error", (event) => console.log(event.error));

The .output() method add's a new encoding object which inherits all global options and events. Multiple outputs can be added with additional options for each output.

encoder
  .output("output-x264.mp4")
  .videoCodec("libx264")
  .output("output-x265.mp4")
  .videoCodec("libx265");

To start the encoding just call the .encode() method and await the returned promise.

await encoder.encode();

To get more control over the encoding precesses you can use the encoder instance as async iterator to iterate over all encoding processes with a for await loop. The process instance is an wrapper around the deno process and has almost the same methods and properties. The encoding process can be started with the .run() method and must be closed with the .close() method after the process is finished or has failed.

There are to different ways to await the status. The first one is using the .status() method, same like with the deno process.

for await (const process: EncodingProcess of encoder) {
  process.run();
  const status: EncodingStatus = await process.status();
  if (!status.success) {
    process.close();
    throw new Error("Encoding failed.");
  }
  process.close();
}
console.log("All encodings done!");

The second one is using an async iterator. You can use the encoding process as async iterator to iterate over all encoding events. If no error occurs then the status is success, if the status is not success or any encoding error occurs an error event is emitted.

for await (const process: EncodingProcess of encoder) {
  process.run();
  for await (const event: EncodingEvent of process) {
    switch (event.type) {
      case "start":
        console.log("start encoding of: %s", event.encoding.output);
        return;
      case "info":
        console.log("Media info loaded: %o", event.info);
        return;
      case "progress":
        console.log(
          "Encoding progress of: %s - %n%",
          event.encoding.output,
          event.progress,
        );
        return;
      case "end":
        console.log("Encoding of %s done!", event.encoding.output);
        return;
      case "error":
        process.close();
        throw event.error;
    }
  }
  process.close();
}
console.log("All encodings done!");

Examples

Events

await ffmpeg("https://www.w3schools.com/html/mov_bbb.mp4")
  .audioBitrate("192k")
  .videoBitrate("1M")
  .width(480)
  .height(640)
  .addEventListener("start", (event) => console.log("Event: %s", event.type))
  .addEventListener("info", (event) => console.log("Event: %s", event.type))
  .addEventListener("progress", (event) => console.log("Event: %s", event.type))
  .addEventListener("end", (event) => console.log("Event: %s", event.type))
  .addEventListener("error", (error) => console.log("Event: %s", error.type))
  .output("output.mp4")
  .output("output.webm")
  .encode();

console.log("All encodings done!");
$ deno run --allow-read --allow-run https://deno.land/x/fast_forward/examples/events.ts

Process handling

const encoder = ffmpeg("https://www.w3schools.com/html/mov_bbb.mp4")
  .audioBitrate("192k")
  .videoBitrate("1M")
  .width(480)
  .height(640)
  .output("output.mp4")
  .output("output.mkv");

for await (const process: EncodingProcess of encoder) {
  process.run();
  const status: EncodingStatus = await process.status();
  process.close();
  if (!status.success) {
    throw new Error(
      `Encoding failed: ${process.encoding.output}\n${
        new TextDecoder().decode(await process.stderrOutput())
      }`,
    );
  }
  console.log("Encoding of %s done!", process.encoding.output);
}

console.log("All encodings done!");
$ deno run --allow-read --allow-run https://deno.land/x/fast_forward/examples/process-handling.ts

Event Stream

const spinner = wait({ text: "" });

const encoder = ffmpeg("https://www.w3schools.com/html/mov_bbb.mp4")
  .audioBitrate("192k")
  .videoBitrate("1M")
  .width(480)
  .height(640)
  .output("output.mp4")
  .output("output.webm");

for await (const process: EncodingProcess of encoder) {
  process.run();
  spinner.start();
  for await (const event: EncodingEvent of process) {
    switch (event.type) {
      case "start":
        spinner.text = `Loading meta data: ${event.encoding.output} ...`;
        break;
      case "info":
        spinner.text = `Start encoding: ${event.encoding.output} ...`;
        break;
      case "progress":
        spinner.text = `Encode: ${event.encoding.output} - ${event.progress}%`;
        break;
      case "end":
        spinner.stop();
        process.close();
        console.log(`โœ” Encode: ${process.encoding.output} - 100%`);
        break;
      case "error":
        spinner.stop();
        process.close();
        console.log(`โœ˜ Encode: ${process.encoding.output} - failed!`);
        throw event.error;
    }
  }
}

console.log("All encodings done!");
$ deno run --allow-read --allow-run --unstable https://deno.land/x/fast_forward/examples/event-stream.ts

Output Stream

export { copy } from "https://deno.land/std/io/util.ts";

const encoder = ffmpeg("https://www.w3schools.com/html/mov_bbb.mp4")
  .output("pipe:1")
  .format("mp4")
  .videoBitrate("933k")
  .audioBitrate("128k")
  .args(["-movflags", "frag_keyframe+empty_moov"]);

for await (const process: EncodingProcess of encoder) {
  process.run();
  if (process.stdout) {
    const outputFile: Deno.File = await Deno.open("output.mp4", {
      create: true,
      write: true,
    });
    const [status] = await Promise.all([
      process.status(),
      copy(process.stdout, outputFile),
    ]);
    console.log({ status });
  }
  process.close();
}

console.log("Encoding done!");
$ deno run --allow-read --allow-write --allow-run https://deno.land/x/fast_forward/examples/output-stream.ts

Todos

Options

  • output
    • support multiple outputs
  • input
    • support multiple inputs
  • cwd
  • binary
  • override
  • format
  • codec
  • audioCodec
  • videoCodec
  • audioBitrate
  • videoBitrate
  • minVideoBitrate
  • maxVideoBitrate
  • videoBufSize
  • width
  • height
  • rotate
  • noAudio
  • noVideo
  • noSubtitle
  • logLevel
  • args
  • seek
  • duration
  • loop
  • preset (name,path)
  • watermark
  • sampleRate
  • audioQuality
  • audioChannels
  • audioFilters
  • videoFilters
  • metadata
  • volume
  • frames
  • frameSize/size
  • fps/frameRate/rate
  • aspectRatio/aspect
  • loudnorm/normalize
  • autopad
  • keepDAR
  • map (map streams in container)
  • add input options
  • thumbnails
  • concat/merge (merge input files)
  • split (split output file by size/time)

Methods

  • getAvailableFilters()
  • getAvailableCodecs()
  • getAvailableEncoders()
  • getAvailableFormats()
  • validate()/checkCapabilities()
  • thumbnail()/thumbnails()
  • flipVertical/flipHorizontal
  • rotate()

Events

  • start
  • info/meta/metadata
  • progress
  • end
  • error
  • stderr (ffmpeg output)

Contributing

Any kind of contribution is welcome! Please take a look at the contributing guidelines.

License

MIT

deno-fast-forward's People

Contributors

c4spar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

deno-fast-forward's Issues

"Uncaught TypeError: Must be a file URL" in encoding_event_stream_test when trying to use module

I'm currently trying to use this module in my own script. When trying to run the simplest of tests on my script that uses fast forward, I get the following error:

import { ffmpeg } from "https://deno.land/x/[email protected]/mod.ts"
import { assert } from "https://deno.land/[email protected]/testing/asserts.ts"
Deno.test("fast_forward runs", async () => {
    await ffmpeg("<path to mkv>")
        .output("<path to mp4>")
        .encode()

    assert(true, "works")
})
error: Uncaught TypeError: Must be a file URL.
    throw new TypeError("Must be a file URL.");
          ^
    at fromFileUrl (https://deno.land/[email protected]/path/posix.ts:487:11)
    at https://deno.land/x/[email protected]/encoding_event_stream_test.ts:21:33
The terminal process "deno 'test', '--allow-all', '--unstable', '--filter', 'fast_forward runs', '.../transcodeDir_test.ts'" terminated with exit code: 1.

I'm new to Deno, so I might be overlooking something, but nothing about my input should be causing this error, especially in a global constant in a test file. I'm using deno 1.13.2.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.