Skip to content

Latest commit

Β 

History

History
424 lines (360 loc) Β· 10.9 KB

README.md

File metadata and controls

424 lines (360 loc) Β· 10.9 KB

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