Cinechroma

Licences

FFmpeg

Cinechroma reads AVI files, including DivX and Xvid, and other video your browser can’t decode, withFFmpeg8.1.2, compiled to WebAssembly. FFmpeg is licensed under theGNU Lesser General Public License, version 2.1or later. Cinechroma uses it unmodified, with no GPL parts enabled.

FFmpeg’s source: https://ffmpeg.org/releases/ffmpeg-8.1.2.tar.xz. To rebuild the decoder, or to link it with a modified FFmpeg, use Cinechroma’s code that calls FFmpeg and the script that builds it, below.

Fonts

PDFs can be set in these fonts, each licensed under theSIL Open Font License 1.1:

ffdec.c

// Reads frames from a video file for colour sampling, with FFmpeg, for what the browser can't do
// itself: AVI files (which Mediabunny can't read), and video browsers can't decode, such as DivX,
// Xvid and 10-bit H.264. Built to WebAssembly by build.sh and driven from a Web Worker by
// src/lib/ffmpeg/worker.ts.
//
// The file is never copied into memory: FFmpeg reads it through js_read, which reads the File the
// user chose, a slice at a time. One file is open at a time (each worker opens one).
#include <emscripten.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/display.h>
#include <libavutil/imgutils.h>
#include <libswscale/swscale.h>
#include <math.h>

// Copies up to `size` bytes of the file from `pos` into `buf`; returns the number copied.
EM_JS(int, js_read, (double pos, uint8_t *buf, int size), { return Module.readAt(pos, buf, size); });

#define IO_BUFFER_SIZE (256 * 1024)

static int64_t file_size, file_pos;
static AVFormatContext *fmt;
static AVCodecContext *dec;
static AVStream *stream;
static AVPacket *pkt;
static AVFrame *frame, *last;
static struct SwsContext *sws;
static uint8_t *rgba;
static int out_width, out_height;
// Where decoding has got to, in stream time; AV_NOPTS_VALUE when the next read must seek.
static int64_t position = AV_NOPTS_VALUE;

static int read_packet(void *opaque, uint8_t *buf, int size) {
	if (file_pos >= file_size) return AVERROR_EOF;
	int n = js_read((double)file_pos, buf, size);
	if (n <= 0) return AVERROR_EOF;
	file_pos += n;
	return n;
}

static int64_t seek(void *opaque, int64_t offset, int whence) {
	if (whence == AVSEEK_SIZE) return file_size;
	switch (whence & ~AVSEEK_FORCE) {
		case SEEK_SET: file_pos = offset; break;
		case SEEK_CUR: file_pos += offset; break;
		case SEEK_END: file_pos = file_size + offset; break;
		default: return -1;
	}
	return file_pos;
}

// Opens the file, detecting its format. 0 on success; -1 if it can't be read, -2 if it has no
// video, -3 if there's no decoder for its video (dec_codec_name still names it), -4 if the decoder
// won't open.
EMSCRIPTEN_KEEPALIVE int dec_open(double size) {
	file_size = (int64_t)size;
	file_pos = 0;
	uint8_t *buffer = av_malloc(IO_BUFFER_SIZE);
	AVIOContext *io = avio_alloc_context(buffer, IO_BUFFER_SIZE, 0, NULL, read_packet, NULL, seek);
	fmt = avformat_alloc_context();
	fmt->pb = io;
	fmt->flags |= AVFMT_FLAG_CUSTOM_IO;
	if (avformat_open_input(&fmt, NULL, NULL, NULL) < 0) return -1;
	if (avformat_find_stream_info(fmt, NULL) < 0) return -1;

	int index = av_find_best_stream(fmt, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
	if (index < 0) return -2;
	stream = fmt->streams[index];
	for (unsigned i = 0; i < fmt->nb_streams; i++) {
		if (i != (unsigned)index) fmt->streams[i]->discard = AVDISCARD_ALL;
	}

	const AVCodec *codec = avcodec_find_decoder(stream->codecpar->codec_id);
	if (!codec) return -3;
	dec = avcodec_alloc_context3(codec);
	avcodec_parameters_to_context(dec, stream->codecpar);
	dec->thread_count = 1;
	if (avcodec_open2(dec, codec, NULL) < 0) return -4;

	pkt = av_packet_alloc();
	frame = av_frame_alloc();
	last = av_frame_alloc();
	return 0;
}

// What dec_open found. The codec name is FFmpeg's (e.g. "mpeg4"); the tag is the container's
// FourCC for it (e.g. "XVID" in an AVI).
EMSCRIPTEN_KEEPALIVE const char *dec_codec_name(void) { return avcodec_get_name(stream->codecpar->codec_id); }
EMSCRIPTEN_KEEPALIVE unsigned dec_codec_tag(void) { return stream->codecpar->codec_tag; }
EMSCRIPTEN_KEEPALIVE int dec_width(void) { return stream->codecpar->width; }
EMSCRIPTEN_KEEPALIVE int dec_height(void) { return stream->codecpar->height; }

// Width of the picture as stored, stretched for non-square pixels (before any rotation).
EMSCRIPTEN_KEEPALIVE int dec_display_width(void) {
	AVRational sar = av_guess_sample_aspect_ratio(fmt, stream, NULL);
	int width = stream->codecpar->width;
	return sar.num > 0 && sar.den > 0 ? (int)av_rescale(width, sar.num, sar.den) : width;
}

// Degrees to turn the picture clockwise to show it upright: 0, 90, 180 or 270.
EMSCRIPTEN_KEEPALIVE int dec_rotation(void) {
	const AVPacketSideData *side = av_packet_side_data_get(stream->codecpar->coded_side_data,
	                                                       stream->codecpar->nb_coded_side_data, AV_PKT_DATA_DISPLAYMATRIX);
	if (!side) return 0;
	double degrees = -av_display_rotation_get((const int32_t *)side->data);
	if (isnan(degrees)) return 0;
	int turns = (int)lround(degrees / 90) % 4;
	return (turns + 4) % 4 * 90;
}

EMSCRIPTEN_KEEPALIVE double dec_duration(void) {
	if (stream->duration != AV_NOPTS_VALUE) return stream->duration * av_q2d(stream->time_base);
	return fmt->duration != AV_NOPTS_VALUE ? fmt->duration / (double)AV_TIME_BASE : 0;
}

// Frames are delivered as RGBA at this size (unrotated), into the buffer this returns.
EMSCRIPTEN_KEEPALIVE uint8_t *dec_set_size(int width, int height) {
	out_width = width;
	out_height = height;
	av_free(rgba);
	rgba = av_malloc((size_t)width * height * 4);
	return rgba;
}

// Converts `f` to RGBA in the output buffer. Untagged video uses the matrix for its size, as
// browsers do: BT.709 for HD, BT.601 for SD (nearly all DivX and Xvid).
static void convert(AVFrame *f) {
	sws = sws_getCachedContext(sws, f->width, f->height, f->format, out_width, out_height, AV_PIX_FMT_RGBA,
	                           SWS_AREA | SWS_ACCURATE_RND | SWS_FULL_CHR_H_INT, NULL, NULL, NULL);
	int matrix;
	switch (f->colorspace) {
		case AVCOL_SPC_BT709: matrix = SWS_CS_ITU709; break;
		case AVCOL_SPC_BT470BG:
		case AVCOL_SPC_SMPTE170M: matrix = SWS_CS_ITU601; break;
		default: matrix = f->height >= 720 ? SWS_CS_ITU709 : SWS_CS_ITU601;
	}
	const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(f->format);
	int full_range = f->color_range == AVCOL_RANGE_JPEG || (desc && strncmp(desc->name, "yuvj", 4) == 0);
	sws_setColorspaceDetails(sws, sws_getCoefficients(matrix), full_range, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
	                         1 << 16, 1 << 16);
	int stride = out_width * 4;
	sws_scale(sws, (const uint8_t *const *)f->data, f->linesize, 0, f->height, &rgba, &stride);
}

// Decodes the frame showing at `seconds` (the first at or after it, or the last frame if it's past
// the end) into the output buffer. 1 if there was a frame, 0 if not.
//
// Reads usually come in order, a few seconds apart. Decoding has to start from a keyframe, and
// these can be 10 s apart, so when the next keyframe isn't beyond where decoding has got to, it
// carries on from there rather than seeking back to the keyframe.
EMSCRIPTEN_KEEPALIVE int dec_read(double seconds) {
	int64_t start = stream->start_time != AV_NOPTS_VALUE ? stream->start_time : 0;
	int64_t target = start + llround(seconds / av_q2d(stream->time_base));

	int key = av_index_search_timestamp(stream, target, AVSEEK_FLAG_BACKWARD);
	int64_t key_time = key >= 0 ? avformat_index_get_entry(stream, key)->timestamp : AV_NOPTS_VALUE;
	if (position == AV_NOPTS_VALUE || target < position || (key_time != AV_NOPTS_VALUE && key_time > position)) {
		if (av_seek_frame(fmt, stream->index, target, AVSEEK_FLAG_BACKWARD) < 0) {
			av_seek_frame(fmt, stream->index, start, AVSEEK_FLAG_BACKWARD | AVSEEK_FLAG_ANY);
		}
		avcodec_flush_buffers(dec);
		av_frame_unref(last);
	}

	int draining = 0;
	for (;;) {
		int received = avcodec_receive_frame(dec, frame);
		if (received == 0) {
			int64_t t = frame->best_effort_timestamp;
			if (t == AV_NOPTS_VALUE || t >= target) {
				convert(frame);
				av_frame_unref(frame);
				position = t == AV_NOPTS_VALUE ? target : t;
				return 1;
			}
			av_frame_unref(last);
			av_frame_move_ref(last, frame);
			continue;
		}
		if (received == AVERROR_EOF || (received == AVERROR(EAGAIN) && draining)) break;

		// The decoder wants more data.
		if (av_read_frame(fmt, pkt) < 0) {
			avcodec_send_packet(dec, NULL);
			draining = 1;
			continue;
		}
		if (pkt->stream_index == stream->index) {
			position = pkt->pts != AV_NOPTS_VALUE ? pkt->pts : pkt->dts;
			// Damaged data is skipped, as a player would.
			avcodec_send_packet(dec, pkt);
		}
		av_packet_unref(pkt);
	}

	// Past the last frame: show the last one, then start afresh next time.
	position = AV_NOPTS_VALUE;
	if (!last->buf[0]) return 0;
	convert(last);
	av_frame_unref(last);
	return 1;
}

EMSCRIPTEN_KEEPALIVE void dec_close(void) {
	sws_freeContext(sws);
	av_free(rgba);
	av_frame_free(&frame);
	av_frame_free(&last);
	av_packet_free(&pkt);
	avcodec_free_context(&dec);
	if (fmt) {
		AVIOContext *io = fmt->pb;
		avformat_close_input(&fmt);
		if (io) av_freep(&io->buffer);
		avio_context_free(&io);
	}
}

build.sh

#!/bin/sh
# Builds src/lib/ffmpeg/ffdec.js and ffdec.wasm: FFmpeg's demuxers and decoders for video browsers
# can't decode, with ffdec.c, compiled to WebAssembly. The output is committed, so only rebuild
# after changing ffdec.c or this script. Needs Emscripten: install emsdk
# (https://emscripten.org/docs/getting_started/downloads.html), then `source emsdk_env.sh`.
#
# FFmpeg is LGPL 2.1+; this build enables no GPL parts. The site publishes this script, ffdec.c
# and a link to the FFmpeg source at /licenses (src/pages/licenses.astro), as the LGPL requires.
set -eu
cd "$(dirname "$0")"

FFMPEG_VERSION=8.1.2
FFMPEG_SHA256=464beb5e7bf0c311e68b45ae2f04e9cc2af88851abb4082231742a74d97b524c
# Outside the project, so the dev server doesn't watch thousands of FFmpeg files.
BUILD="${XDG_CACHE_HOME:-$HOME/.cache}/cinechroma-ffdec"
OUT=../../src/lib/ffmpeg

# Containers: AVI (which Mediabunny can't read), and MP4/MOV and MKV/WebM for video in them that
# the browser can't decode (10-bit H.264, HEVC without platform support, MPEG-2, ...).
CONFIGURE_FLAGS="
	--target-os=none --arch=x86_32 --enable-cross-compile
	--cc=emcc --cxx=em++ --ar=emar --ranlib=emranlib --nm=emnm
	--extra-cflags=-O3
	--disable-everything --disable-programs --disable-doc --disable-debug
	--disable-network --disable-pthreads --disable-runtime-cpudetect
	--disable-asm --disable-inline-asm --disable-x86asm --disable-autodetect
	--disable-avdevice --disable-avfilter --disable-swresample
	--enable-demuxer=avi,mov,matroska
	--enable-decoder=mpeg4,msmpeg4v1,msmpeg4v2,msmpeg4v3,h263,h264,hevc,mjpeg,mpeg1video,mpeg2video
	--enable-parser=mpeg4video,h263,h264,hevc,mjpeg,mpegvideo
"

mkdir -p "$BUILD"
SOURCE="$BUILD/ffmpeg-$FFMPEG_VERSION"
if [ ! -d "$SOURCE" ]; then
	curl -fL -o "$BUILD/ffmpeg.tar.xz" "https://ffmpeg.org/releases/ffmpeg-$FFMPEG_VERSION.tar.xz"
	echo "$FFMPEG_SHA256  $BUILD/ffmpeg.tar.xz" | shasum -a 256 -c -
	tar -xf "$BUILD/ffmpeg.tar.xz" -C "$BUILD"
fi

# FFmpeg is rebuilt whenever the flags change.
PREFIX="$BUILD/prefix"
STAMP="$PREFIX/configure-flags"
if [ ! -f "$STAMP" ] || [ "$(cat "$STAMP")" != "$CONFIGURE_FLAGS" ]; then
	rm -rf "$PREFIX"
	(
		cd "$SOURCE"
		make distclean >/dev/null 2>&1 || true
		# shellcheck disable=SC2086 # the flags are meant to split
		emconfigure ./configure --prefix="$PREFIX" $CONFIGURE_FLAGS
		emmake make -j"$(sysctl -n hw.ncpu 2>/dev/null || nproc)"
		emmake make install
	)
	printf '%s' "$CONFIGURE_FLAGS" >"$STAMP"
fi

emcc ffdec.c -O3 -I"$PREFIX/include" \
	"$PREFIX/lib/libavformat.a" "$PREFIX/lib/libavcodec.a" "$PREFIX/lib/libswscale.a" "$PREFIX/lib/libavutil.a" \
	-s MODULARIZE=1 -s EXPORT_ES6=1 -s EXPORT_NAME=createDecoder -s ENVIRONMENT=worker \
	-s ALLOW_MEMORY_GROWTH=1 -s INITIAL_MEMORY=33554432 -s FILESYSTEM=0 \
	-s EXPORTED_RUNTIME_METHODS=HEAPU8,UTF8ToString \
	-o "$OUT/ffdec.js"
ls -l "$OUT/ffdec.js" "$OUT/ffdec.wasm"