diff --git a/Dockerfile b/Dockerfile index 151fd6ba..11a2d972 100644 --- a/Dockerfile +++ b/Dockerfile @@ -51,17 +51,18 @@ ARG JOBS= RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ build-essential nasm pkg-config ca-certificates curl xz-utils zlib1g-dev libdav1d-dev \ - libwebp-dev libopenh264-dev \ + libwebp-dev libopenh264-dev libvpx-dev libaom-dev libopus-dev \ && rm -rf /var/lib/apt/lists/* WORKDIR /tmp # Demuxers: media.cpp's kFormats whitelist. Decoders: what those containers carry -- still # images, H.264 and HEVC (MP4, MOV, HEIF), VP8 and VP9 (WebM, WebP), AV1 through dav1d (WebM, MP4, # AVIF), MPEG-1/2/4, Theora and the FLV/H.263 family. JPEG XL is recognised and refused by name # (its only decoder is libjxl's). Encoders: the image output formats of media.cpp encode_image -# (png, jpeg as mjpeg, webp through libwebp), and a generated video's MP4 (core/mm/mp4.cpp): H.264 -# through libopenh264 (BSD-licensed, so the build stays LGPL) and FFmpeg's own AAC, in the mp4 -# muxer. No protocols: media.cpp and mp4.cpp read and write memory through their own I/O -# contexts. +# (png, jpeg as mjpeg, webp through libwebp), and a generated video (core/mm/video_out.cpp): H.264 +# through libopenh264 and FFmpeg's own AAC in the mp4 muxer, and for WebM VP9 through libvpx and +# AV1 through libaom with Opus through libopus in the webm muxer -- libvpx, libaom and libopus are +# BSD, so, like libopenh264, the build stays LGPL. No protocols: media.cpp and video_out.cpp read +# and write memory through their own I/O contexts. RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ curl -fsSL "https://ffmpeg.org/releases/ffmpeg-${FFMPEG_VERSION}.tar.xz" -o ffmpeg.tar.xz \ && echo "${FFMPEG_SHA256} ffmpeg.tar.xz" | sha256sum -c - \ @@ -69,10 +70,11 @@ RUN echo 1000 > /proc/self/oom_score_adj 2>/dev/null || true; \ && ./configure --prefix=/opt/ffmpeg --enable-shared --disable-static --disable-debug \ --disable-programs --disable-doc --disable-network --disable-autodetect --disable-everything \ --disable-avdevice --disable-avfilter --enable-swresample \ - --enable-zlib --enable-libdav1d --enable-libwebp \ + --enable-zlib --enable-libdav1d --enable-libwebp --enable-libvpx --enable-libaom --enable-libopus \ --enable-demuxer=mov,matroska,avi,mpegts,flv,ogg,gif,apng,image2pipe,image_png_pipe,image_jpeg_pipe,image_jpegls_pipe,image_jpegxl_pipe,image_webp_pipe,image_bmp_pipe,image_tiff_pipe,image_qoi_pipe,image_pgm_pipe,image_ppm_pipe,image_pbm_pipe,image_pam_pipe,image_gif_pipe,wav,w64,mp3,flac,aac,aiff \ --enable-decoder=h264,hevc,vp8,vp9,libdav1d,mpeg4,mpeg1video,mpeg2video,mjpeg,jpegls,png,apng,gif,webp,bmp,tiff,qoi,pgm,ppm,pbm,pam,pgmyuv,theora,vp3,flv,h263,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_alaw,pcm_mulaw,mp3float,mp2float,flac,vorbis,opus,aac \ - --enable-encoder=png,mjpeg,libwebp,libopenh264,aac --enable-muxer=mp4 --enable-libopenh264 \ + --enable-encoder=png,mjpeg,libwebp,libopenh264,aac,libvpx-vp9,libaom-av1,libopus \ + --enable-muxer=mp4,webm,matroska --enable-libopenh264 \ --enable-parser=h264,hevc,vp8,vp9,av1,mpeg4video,mpegvideo,mjpeg,png,gif,bmp,webp,vp3,qoi,pnm,h263,jpegxl,mpegaudio,flac,aac,vorbis,opus \ && make -j"${JOBS:-$(nproc)}" \ && make install \ @@ -139,10 +141,12 @@ ARG JOBS= # g++-14 rather than the default 13: hipcc compiles device-side translation units against its # libstdc++, which is also the runtime image's. gawk: tools/ops_doc_check.sh uses gensub, which # mawk lacks. libdav1d7, libwebp7 and libopenh264-7 are the runtime libraries of the ffmpeg stage's -# AV1 decoder, WebP encoder and H.264 encoder; busybox-static goes into the runtime image. +# AV1 decoder, WebP encoder and H.264 encoder; libvpx9, libaom3 and libopus0 of its VP9, AV1 and +# Opus encoders (core/mm/video_out.cpp's WebM output); busybox-static goes into the runtime image. RUN apt-get update \ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ - cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \ + cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 \ + libvpx9 libaom3 libopus0 busybox-static \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg diff --git a/core/mm/mp4.h b/core/mm/mp4.h deleted file mode 100644 index 50f0ebb6..00000000 --- a/core/mm/mp4.h +++ /dev/null @@ -1,52 +0,0 @@ -/* mp4.h -- a video and its soundtrack written as an MP4 file in memory: H.264 video in yuv420p - * (BT.709, limited range) and AAC audio, the moov atom at the front so a player can start before - * the whole file has arrived. - * - * The frames arrive in order, in any number of calls; the soundtrack may come before, between or - * after them, whole or in pieces. Nothing is written until finish(), which encodes the soundtrack - * and interleaves it with the video: a video is at most tens of seconds, and its frames are - * encoded as they come so the RGB is never all held at once. - * - * The H.264 encoder is the best the linked libavcodec has: libx264 (constant quality), else - * libopenh264, else whatever encoder it registers for H.264. Without libavcodec every call - * returns RAD_E_UNSUPPORTED. - */ -#pragma once -#include "rad_core.h" - -#include -#include -#include - -namespace rad { -namespace mm { - -class Mp4Writer { -public: - Mp4Writer(); - ~Mp4Writer(); - Mp4Writer(const Mp4Writer&) = delete; - Mp4Writer& operator=(const Mp4Writer&) = delete; - - /* A video of `width` x `height` (even) at fps_num / fps_den frames a second, with a soundtrack - * of `channels` channels at `sample_rate` (0 channels: none). */ - int open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, int64_t sample_rate, - int64_t channels, std::string* why); - /* `n` frames, each [height, width, 3] u8 RGB, after those already added. */ - int add_frames(const uint8_t* rgb, int32_t n, std::string* why); - /* Samples interleaved over the channels, in [-1, 1], after those already added. */ - int add_audio(const float* samples, int64_t n_frames, std::string* why); - /* Flushes both encoders and writes the file into `out`. */ - int finish(std::string* out, std::string* why); - - /* The H.264 encoder in use, for the log. */ - const std::string& video_encoder() const { return venc_name_; } - -private: - struct Impl; - std::unique_ptr p_; - std::string venc_name_; -}; - -} /* namespace mm */ -} /* namespace rad */ diff --git a/core/mm/mp4.cpp b/core/mm/video_out.cpp similarity index 55% rename from core/mm/mp4.cpp rename to core/mm/video_out.cpp index 08548ea8..848f8d2f 100644 --- a/core/mm/mp4.cpp +++ b/core/mm/video_out.cpp @@ -1,5 +1,6 @@ -/* mp4.cpp -- Mp4Writer (mp4.h) over libavformat, libavcodec and libswscale. */ -#include "mm/mp4.h" +/* video_out.cpp -- VideoWriter (video_out.h) over libavformat, libavcodec, libswscale and + * libswresample. */ +#include "mm/video_out.h" #include #include @@ -10,7 +11,10 @@ extern "C" { #include #include #include +#include #include +#include +#include #include } #endif @@ -20,19 +24,20 @@ namespace mm { #ifndef RAD_HAVE_FFMPEG -struct Mp4Writer::Impl {}; -Mp4Writer::Mp4Writer() = default; -Mp4Writer::~Mp4Writer() = default; +struct VideoWriter::Impl {}; +VideoWriter::VideoWriter() = default; +VideoWriter::~VideoWriter() = default; static int no_ffmpeg(std::string* why) { if (why) *why = "this build has no libavcodec, so it writes no video"; return RAD_E_UNSUPPORTED; } -int Mp4Writer::open(int32_t, int32_t, int64_t, int64_t, int64_t, int64_t, std::string* why) { +int VideoWriter::open(int32_t, int32_t, int64_t, int64_t, int64_t, int64_t, std::string* why, + VideoFormat) { return no_ffmpeg(why); } -int Mp4Writer::add_frames(const uint8_t*, int32_t, std::string* why) { return no_ffmpeg(why); } -int Mp4Writer::add_audio(const float*, int64_t, std::string* why) { return no_ffmpeg(why); } -int Mp4Writer::finish(std::string*, std::string* why) { return no_ffmpeg(why); } +int VideoWriter::add_frames(const uint8_t*, int32_t, std::string* why) { return no_ffmpeg(why); } +int VideoWriter::add_audio(const float*, int64_t, std::string* why) { return no_ffmpeg(why); } +int VideoWriter::finish(std::string*, std::string* why) { return no_ffmpeg(why); } #else @@ -40,7 +45,8 @@ namespace { /* The file in memory. The MP4 muxer seeks back to patch sizes and, to put the moov atom first, * reopens its output for reading and moves the media data up (FFmpeg's shift_data): the reader is - * a second handle on the same bytes with a position of its own. */ + * a second handle on the same bytes with a position of its own. The WebM muxer only seeks within + * this one handle, so it never needs the reader. */ struct MemFile { std::string data; int64_t pos = 0; @@ -105,7 +111,7 @@ std::string av_why(const char* what, int e) { } /* namespace */ -struct Mp4Writer::Impl { +struct VideoWriter::Impl { MemFile file; AVFormatContext* oc = nullptr; AVCodecContext* vc = nullptr; @@ -113,13 +119,18 @@ struct Mp4Writer::Impl { AVStream* vs = nullptr; AVStream* as = nullptr; SwsContext* sws = nullptr; + SwrContext* swr = nullptr; /* soundtrack to 48 kHz for Opus; null otherwise */ AVFrame* vf = nullptr; AVFrame* af = nullptr; AVPacket* pkt = nullptr; int32_t w = 0, h = 0; int64_t channels = 0; int64_t next_frame = 0; - std::vector audio; /* interleaved, encoded at finish */ + int aframe = 0; /* the soundtrack frame length `af` is sized for */ + int in_rate = 0; /* the rate add_audio arrives at, for swr_get_delay */ + std::vector audio; /* interleaved at in_rate, encoded at finish */ + std::vector audio_out; /* interleaved at the encoder's rate after resampling */ + VideoFormat fmt = VideoFormat::Mp4; bool header = false; ~Impl() { @@ -133,6 +144,7 @@ struct Mp4Writer::Impl { avcodec_free_context(&vc); avcodec_free_context(&ac); sws_freeContext(sws); + swr_free(&swr); av_frame_free(&vf); av_frame_free(&af); av_packet_free(&pkt); @@ -158,7 +170,8 @@ struct Mp4Writer::Impl { } }; -/* The reader shift_data opens on the output's own URL; any other URL is refused. */ +/* The reader shift_data opens on the output's own URL; any other URL is refused. Only wired for + * MP4 -- WebM writes forward and never reopens. */ static int open_reader(AVFormatContext* s, AVIOContext** pb, const char*, int flags, AVDictionary**) { if (!(flags & AVIO_FLAG_READ) || (flags & AVIO_FLAG_WRITE)) return AVERROR(EINVAL); MemFile* f = static_cast(s->opaque); @@ -181,12 +194,13 @@ static int close_reader(AVFormatContext*, AVIOContext* pb) { return 0; } -Mp4Writer::Mp4Writer() : p_(std::make_unique()) {} -Mp4Writer::~Mp4Writer() = default; +VideoWriter::VideoWriter() : p_(std::make_unique()) {} +VideoWriter::~VideoWriter() = default; -int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, - int64_t sample_rate, int64_t channels, std::string* why) { +int VideoWriter::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, + int64_t sample_rate, int64_t channels, std::string* why, VideoFormat fmt) { Impl& p = *p_; + p.fmt = fmt; /* The encoders print their settings and a file's statistics at FFmpeg's info level, on stderr, * for every video; a failure comes back through the calls here, so only errors are let * through. */ @@ -199,14 +213,19 @@ int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_ p.w = width; p.h = height; p.channels = channels; - if (avformat_alloc_output_context2(&p.oc, nullptr, "mp4", nullptr) < 0 || !p.oc) { - if (why) *why = "this libavformat has no MP4 muxer"; + const bool mp4 = fmt == VideoFormat::Mp4; + const char* mux = mp4 ? "mp4" : "webm"; + const char* url = mp4 ? "radiance.mp4" : "radiance.webm"; + if (avformat_alloc_output_context2(&p.oc, nullptr, mux, nullptr) < 0 || !p.oc) { + if (why) *why = std::string("this libavformat has no ") + (mp4 ? "MP4" : "WebM") + " muxer"; return RAD_E_UNSUPPORTED; } - p.oc->url = av_strdup("radiance.mp4"); + p.oc->url = av_strdup(url); p.oc->opaque = &p.file; - p.oc->io_open = open_reader; - p.oc->io_close2 = close_reader; + if (mp4) { /* only MP4's faststart reopens the output for reading */ + p.oc->io_open = open_reader; + p.oc->io_close2 = close_reader; + } uint8_t* buf = static_cast(av_malloc(kIoBuf)); p.oc->pb = buf ? avio_alloc_context(buf, kIoBuf, 1, &p.file, nullptr, mem_write, mem_seek) : nullptr; @@ -219,12 +238,29 @@ int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_ /* ---- video */ const AVCodec* vcodec = nullptr; - for (const char* name : { "libx264", "libopenh264" }) - if ((vcodec = avcodec_find_encoder_by_name(name))) break; - if (!vcodec) vcodec = avcodec_find_encoder(AV_CODEC_ID_H264); - if (!vcodec) { - if (why) *why = "this libavcodec has no H.264 encoder"; - return RAD_E_UNSUPPORTED; + if (mp4) { + for (const char* name : { "libx264", "libopenh264" }) + if ((vcodec = avcodec_find_encoder_by_name(name))) break; + if (!vcodec) vcodec = avcodec_find_encoder(AV_CODEC_ID_H264); + if (!vcodec) { + if (why) *why = "this libavcodec has no H.264 encoder"; + return RAD_E_UNSUPPORTED; + } + } else if (fmt == VideoFormat::WebmVp9) { + if (!(vcodec = avcodec_find_encoder_by_name("libvpx-vp9"))) + vcodec = avcodec_find_encoder(AV_CODEC_ID_VP9); + if (!vcodec) { + if (why) *why = "this libavcodec has no VP9 encoder"; + return RAD_E_UNSUPPORTED; + } + } else { /* WebmAv1 */ + for (const char* name : { "libaom-av1", "libsvtav1" }) + if ((vcodec = avcodec_find_encoder_by_name(name))) break; + if (!vcodec) vcodec = avcodec_find_encoder(AV_CODEC_ID_AV1); + if (!vcodec) { + if (why) *why = "this libavcodec has no AV1 encoder"; + return RAD_E_UNSUPPORTED; + } } venc_name_ = vcodec->name; p.vs = avformat_new_stream(p.oc, nullptr); @@ -247,6 +283,24 @@ int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_ /* Constant quality, visually lossless for generated footage. */ av_opt_set(p.vc->priv_data, "preset", "medium", 0); av_opt_set(p.vc->priv_data, "crf", "18", 0); + } else if (fmt == VideoFormat::WebmVp9) { + /* Constant quality, and the speed/threading knobs that make a software VP9 usable: a row + * of tiles at a time, a good (not realtime) deadline, alternate references for the rate. */ + p.vc->bit_rate = 0; /* a zero bitrate + crf => constant quality for libvpx */ + av_opt_set(p.vc->priv_data, "crf", "32", 0); + av_opt_set(p.vc->priv_data, "cpu-used", "4", 0); + av_opt_set(p.vc->priv_data, "deadline", "good", 0); + av_opt_set(p.vc->priv_data, "row-mt", "1", 0); + av_opt_set(p.vc->priv_data, "auto-alt-ref", "1", 0); + } else if (fmt == VideoFormat::WebmAv1) { + /* libaom is slow; the realtime deadline and the highest cpu-used keep a short clip + * finishing in reasonable time. */ + p.vc->bit_rate = 0; + av_opt_set(p.vc->priv_data, "crf", "34", 0); + av_opt_set(p.vc->priv_data, "cpu-used", "8", 0); + av_opt_set(p.vc->priv_data, "deadline", "realtime", 0); + av_opt_set(p.vc->priv_data, "row-mt", "1", 0); + av_opt_set(p.vc->priv_data, "tiles", "2x2", 0); } else { /* An encoder without a quality mode: 0.2 bits a pixel, about 5 Mbit/s at 1344x768 x 24. */ p.vc->bit_rate = (int64_t)((double)width * height * fps_num / fps_den * 0.2); @@ -276,51 +330,76 @@ int Mp4Writer::open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_ sws_setColorspaceDetails(p.sws, sws_getCoefficients(SWS_CS_DEFAULT), 1, sws_getCoefficients(SWS_CS_ITU709), 0, 0, 1 << 16, 1 << 16); - /* ---- audio */ + /* ---- audio: AAC at the soundtrack's own rate for MP4, Opus at 48 kHz for WebM. */ if (channels > 0) { - const AVCodec* acodec = avcodec_find_encoder(AV_CODEC_ID_AAC); + const AVSampleFormat sfmt = mp4 ? AV_SAMPLE_FMT_FLTP : AV_SAMPLE_FMT_FLT; + const int64_t rate = mp4 ? sample_rate : 48000; + const AVCodec* acodec = + avcodec_find_encoder(mp4 ? AV_CODEC_ID_AAC : AV_CODEC_ID_OPUS); if (!acodec) { - if (why) *why = "this libavcodec has no AAC encoder"; + if (why) *why = std::string("this libavcodec has no ") + (mp4 ? "AAC" : "Opus") + + " encoder"; return RAD_E_UNSUPPORTED; } p.as = avformat_new_stream(p.oc, nullptr); p.ac = avcodec_alloc_context3(acodec); if (!p.as || !p.ac) return RAD_E_NOMEM; - p.ac->sample_fmt = AV_SAMPLE_FMT_FLTP; - p.ac->sample_rate = (int)sample_rate; + p.ac->sample_fmt = sfmt; + p.ac->sample_rate = (int)rate; av_channel_layout_default(&p.ac->ch_layout, (int)channels); p.ac->bit_rate = 96000 * channels; - p.ac->time_base = AVRational{ 1, (int)sample_rate }; + p.ac->time_base = AVRational{ 1, (int)rate }; if (p.oc->oformat->flags & AVFMT_GLOBALHEADER) p.ac->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; e = avcodec_open2(p.ac, acodec, nullptr); if (e < 0) { - if (why) *why = av_why("opening the AAC encoder", e); + if (why) *why = av_why(("opening the " + std::string(mp4 ? "AAC" : "Opus") + + " encoder").c_str(), e); return RAD_E_INVAL; } avcodec_parameters_from_context(p.as->codecpar, p.ac); p.as->time_base = p.ac->time_base; + p.aframe = p.ac->frame_size > 0 ? p.ac->frame_size : (mp4 ? 1024 : 960); p.af = av_frame_alloc(); if (!p.af) return RAD_E_NOMEM; - p.af->format = AV_SAMPLE_FMT_FLTP; + p.af->format = sfmt; p.af->sample_rate = p.ac->sample_rate; av_channel_layout_copy(&p.af->ch_layout, &p.ac->ch_layout); - p.af->nb_samples = p.ac->frame_size > 0 ? p.ac->frame_size : 1024; + p.af->nb_samples = p.aframe; if (av_frame_get_buffer(p.af, 0) < 0) return RAD_E_NOMEM; + /* Opus only encodes 8/12/16/24/48 kHz; resample any other rate to the 48 kHz it was opened + * at. Interleaved float in and out -- the same layout the samples already sit in. */ + p.in_rate = (int)sample_rate; + if (!mp4 && sample_rate > 0 && sample_rate != rate) { + AVChannelLayout in_lay{}, out_lay{}; + av_channel_layout_default(&in_lay, (int)channels); + av_channel_layout_default(&out_lay, (int)channels); + if (swr_alloc_set_opts2(&p.swr, &out_lay, AV_SAMPLE_FMT_FLT, (int)rate, &in_lay, + AV_SAMPLE_FMT_FLT, (int)sample_rate, 0, nullptr) < 0 || + swr_init(p.swr) < 0) { + av_channel_layout_uninit(&in_lay); + av_channel_layout_uninit(&out_lay); + if (why) *why = "libswresample cannot convert the soundtrack to 48 kHz"; + return RAD_E_UNSUPPORTED; + } + av_channel_layout_uninit(&in_lay); + av_channel_layout_uninit(&out_lay); + } } AVDictionary* opts = nullptr; - av_dict_set(&opts, "movflags", "+faststart", 0); + if (mp4) av_dict_set(&opts, "movflags", "+faststart", 0); e = avformat_write_header(p.oc, &opts); av_dict_free(&opts); if (e < 0) { - if (why) *why = av_why("writing the MP4 header", e); + if (why) *why = av_why(("writing the " + std::string(mp4 ? "MP4" : "WebM") + + " header").c_str(), e); return RAD_E_INVAL; } p.header = true; return RAD_OK; } -int Mp4Writer::add_frames(const uint8_t* rgb, int32_t n, std::string* why) { +int VideoWriter::add_frames(const uint8_t* rgb, int32_t n, std::string* why) { Impl& p = *p_; if (!p.header) { if (why) *why = "the writer is not open"; @@ -343,7 +422,7 @@ int Mp4Writer::add_frames(const uint8_t* rgb, int32_t n, std::string* why) { return RAD_OK; } -int Mp4Writer::add_audio(const float* samples, int64_t n_frames, std::string* why) { +int VideoWriter::add_audio(const float* samples, int64_t n_frames, std::string* why) { Impl& p = *p_; if (!p.header || !p.ac) { if (why) *why = "the writer has no soundtrack"; @@ -353,25 +432,59 @@ int Mp4Writer::add_audio(const float* samples, int64_t n_frames, std::string* wh return RAD_OK; } -int Mp4Writer::finish(std::string* out, std::string* why) { +int VideoWriter::finish(std::string* out, std::string* why) { Impl& p = *p_; if (!p.header) { if (why) *why = "the writer is not open"; return RAD_E_STATE; } if (p.ac) { - /* The soundtrack in the encoder's frames, deinterleaved; the last frame padded with - * silence, which the encoder's own length bookkeeping trims. */ - const int64_t total = (int64_t)p.audio.size() / p.channels; - const int fs = p.af->nb_samples; + /* The soundtrack at the encoder's rate: resampled whole for Opus (small, a few MB at most), + * the accumulated samples as they came for AAC. */ + const std::vector* buf = &p.audio; + if (p.swr) { + const int64_t ch = p.channels; + const int64_t in_n = (int64_t)p.audio.size() / ch; + const int64_t out_cap = av_rescale_rnd(swr_get_delay(p.swr, p.in_rate) + in_n, + p.ac->sample_rate, p.in_rate, AV_ROUND_UP) + 16; + std::vector tmp((size_t)(out_cap * ch)); + const uint8_t* in_plane[1] = { reinterpret_cast(p.audio.data()) }; + uint8_t* out_plane[1] = { reinterpret_cast(tmp.data()) }; + int got = swr_convert(p.swr, out_plane, (int)out_cap, in_plane, (int)in_n); + if (got < 0) { + if (why) *why = av_why("resampling the soundtrack", got); + return RAD_E_INVAL; + } + int64_t written = got; + out_plane[0] = reinterpret_cast(tmp.data() + written * ch); + int more = swr_convert(p.swr, out_plane, (int)(out_cap - written), nullptr, 0); + if (more > 0) written += more; + tmp.resize((size_t)(written * ch)); + p.audio_out.swap(tmp); + buf = &p.audio_out; + } + /* Frames of the encoder's length, in its sample format (planar for AAC, packed for Opus); + * the last frame padded with silence to a full frame, which Opus in particular requires and + * which the encoder's own length bookkeeping trims. */ + const int64_t total = (int64_t)buf->size() / p.channels; + const int fs = p.aframe; + const bool planar = p.ac->sample_fmt == AV_SAMPLE_FMT_FLTP; for (int64_t at = 0; at < total; at += fs) { if (av_frame_make_writable(p.af) < 0) return RAD_E_NOMEM; const int64_t k = std::min(fs, total - at); - p.af->nb_samples = (int)k; - for (int64_t c = 0; c < p.channels; ++c) { - float* d = reinterpret_cast(p.af->data[c]); - for (int64_t i = 0; i < k; ++i) - d[i] = p.audio[(size_t)((at + i) * p.channels + c)]; + if (planar) { + for (int64_t c = 0; c < p.channels; ++c) { + float* d = reinterpret_cast(p.af->data[c]); + for (int64_t i = 0; i < k; ++i) + d[i] = (*buf)[(size_t)((at + i) * p.channels + c)]; + } + p.af->nb_samples = (int)k; + } else { + float* d = reinterpret_cast(p.af->data[0]); + std::memcpy(d, buf->data() + at * p.channels, (size_t)(k * p.channels * sizeof(float))); + if (k < fs) + std::memset(d + k * p.channels, 0, (size_t)((fs - k) * p.channels * sizeof(float))); + p.af->nb_samples = fs; /* Opus: always a whole frame */ } p.af->pts = at; const int e = avcodec_send_frame(p.ac, p.af); @@ -389,7 +502,8 @@ int Mp4Writer::finish(std::string* out, std::string* why) { RAD_TRY(p.drain(p.vc, p.vs, why)); const int e = av_write_trailer(p.oc); if (e < 0) { - if (why) *why = av_why("finishing the MP4 file", e); + if (why) *why = av_why(("finishing the " + std::string(p.fmt == VideoFormat::Mp4 ? "MP4" + : "WebM") + " file").c_str(), e); return RAD_E_INVAL; } avio_flush(p.oc->pb); diff --git a/core/mm/video_out.h b/core/mm/video_out.h new file mode 100644 index 00000000..7cd99f2d --- /dev/null +++ b/core/mm/video_out.h @@ -0,0 +1,62 @@ +/* video_out.h -- a video and its soundtrack written to a file in memory, muxed into one of a few + * containers: MP4 (H.264 video in yuv420p + AAC, the moov atom first) or WebM (VP9 or AV1 video + + * Opus audio). The frames arrive in order, in any number of calls; the soundtrack may come before, + * between or after them, whole or in pieces. Nothing is written until finish(), which encodes the + * soundtrack and interleaves it with the video: a video is at most tens of seconds, and its frames + * are encoded as they come so the RGB is never all held at once. + * + * The video encoder is the best the linked libavcodec has for the format: MP4 prefers libx264 + * (constant quality), else libopenh264, else whatever it registers for H.264; WebM uses libvpx-vp9 + * or libaom-av1 (else the generic encoder for that codec). Audio is AAC for MP4 and Opus for WebM; + * since Opus only encodes at 48 kHz, a soundtrack at any other rate is resampled with libswresample + * (AAC takes the soundtrack's own rate). Without libavcodec every call returns RAD_E_UNSUPPORTED; + * without a format's encoder or muxer, open() returns it with a message naming what is missing. */ +#pragma once +#include "rad_core.h" + +#include +#include +#include + +namespace rad { +namespace mm { + +/* The container and codec pair open() writes. Mp4 is the default everywhere, so a caller that does + * not choose one gets the H.264 + AAC file Radiance has always produced. */ +enum class VideoFormat { + Mp4, /* H.264 + AAC, moov atom first */ + WebmVp9, /* VP9 + Opus */ + WebmAv1, /* AV1 + Opus */ +}; + +class VideoWriter { +public: + VideoWriter(); + ~VideoWriter(); + VideoWriter(const VideoWriter&) = delete; + VideoWriter& operator=(const VideoWriter&) = delete; + + /* A video of `width` x `height` (even) at fps_num / fps_den frames a second, with a soundtrack + * of `channels` channels at `sample_rate` (0 channels: none), written in `fmt`. `fmt` trails the + * error out-param and defaults to MP4 so the older MP4-only call sites keep compiling. */ + int open(int32_t width, int32_t height, int64_t fps_num, int64_t fps_den, int64_t sample_rate, + int64_t channels, std::string* why, VideoFormat fmt = VideoFormat::Mp4); + /* `n` frames, each [height, width, 3] u8 RGB, after those already added. */ + int add_frames(const uint8_t* rgb, int32_t n, std::string* why); + /* Samples interleaved over the channels, in [-1, 1], at the rate passed to open(), after those + * already added. */ + int add_audio(const float* samples, int64_t n_frames, std::string* why); + /* Flushes both encoders and writes the file into `out`. */ + int finish(std::string* out, std::string* why); + + /* The video encoder in use, for the log. */ + const std::string& video_encoder() const { return venc_name_; } + +private: + struct Impl; + std::unique_ptr p_; + std::string venc_name_; +}; + +} /* namespace mm */ +} /* namespace rad */ diff --git a/core/server/videos.cpp b/core/server/videos.cpp index 045e87e9..0c97224f 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -3,7 +3,8 @@ * * A video takes minutes, so it is a job, as OpenAI's API has it: POST /v1/videos queues one and * answers with the video object at once, GET /v1/videos/{id} reports its status and progress, and - * GET /v1/videos/{id}/content downloads the MP4 once it is completed (`variant` thumbnail gives + * GET /v1/videos/{id}/content downloads the finished file once it is completed -- an MP4 unless the + * request asked `format` webm (VP9) or webm-av1 (AV1); `variant` thumbnail gives * the first frame as WebP). GET /v1/videos lists the jobs, newest first, and DELETE removes one, * cancelling it when it is still running. A finished video is kept for `video_ttl_s` seconds * (`expires_at`), at most `max_videos` of them. @@ -35,7 +36,7 @@ #include "gen/video.h" #include "mm/media.h" -#include "mm/mp4.h" +#include "mm/video_out.h" #include "rad_internal.h" #include @@ -66,7 +67,8 @@ struct Server::VideoJob { int64_t completed_at = 0, expires_at = 0; bool failed = false; std::string err_code, err_message; - std::string mp4; + std::string blob; /* the finished file, in `fmt`'s container */ + mm::VideoFormat fmt = mm::VideoFormat::Mp4; std::vector first; /* the first frame, RGB, for the thumbnail */ /* Reference conditioning: the reference parts' names in conditioning order, empty for a * text-only job. */ @@ -90,6 +92,15 @@ std::string new_video_id() { return id; } +/* The `format` name a VideoFormat maps back to, for the object and the download's filename. */ +const char* format_name(mm::VideoFormat f) { + switch (f) { + case mm::VideoFormat::WebmVp9: return "webm"; + case mm::VideoFormat::WebmAv1: return "webm-av1"; + default: return "mp4"; + } +} + /* "1344x768" -> (1344, 768); false for anything else. */ bool parse_size(const std::string& s, int64_t* w, int64_t* h) { const size_t x = s.find_first_of("xX"); @@ -257,6 +268,9 @@ void Server::video_caps(json& caps, const IVideoGen* gen) { caps["video_max_ref_images"] = std::min(kMaxRefImages, (int32_t)info.max_ref_images); caps["video_max_ref_videos"] = std::min(kMaxRefVideos, (int32_t)info.max_ref_videos); caps["video_max_ref_audios"] = std::min(kMaxRefAudios, (int32_t)info.max_ref_audios); + /* The containers `format` accepts; mp4 is the default and always available, the webm codecs + * only when this build's libavcodec has the encoder and muxer for them. */ + caps["video_formats"] = json::array({ "mp4", "webm", "webm-av1" }); } HttpResponse Server::handle_video_create(const HttpRequest& req) { @@ -328,7 +342,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { } static const char* kKnown[] = { "model", "prompt", "seconds", "size", "input_reference", "seed", "num_inference_steps", - "task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", + "task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", "format", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; @@ -384,6 +398,22 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { return error_response(e, req.peer); } } + /* The output container and codec. mp4 (H.264 + AAC) is the default; webm is VP9 + Opus and + * webm-av1 is AV1 + Opus. Whether this build's libavcodec actually has the encoder and muxer is + * checked when the video is written, so an accepted name here can still fail to encode. */ + mm::VideoFormat fmt = mm::VideoFormat::Mp4; + if (has(body, "format")) { + const std::string f = body["format"].is_string() ? body["format"].get() : ""; + if (f == "mp4") fmt = mm::VideoFormat::Mp4; + else if (f == "webm") fmt = mm::VideoFormat::WebmVp9; + else if (f == "webm-av1") fmt = mm::VideoFormat::WebmAv1; + else { + ApiError e = err_unsupported("format", "the output is mp4 (H.264), webm (VP9) or " + "webm-av1 (AV1)"); + e.supported = { "mp4", "webm", "webm-av1" }; + return error_response(e, req.peer); + } + } if (has(body, "conditions") && (!body["conditions"].is_array() || !body["conditions"].empty())) return error_response(err_unsupported("conditions", takes_refs ? "reference media arrive as ref_* file parts; " @@ -740,6 +770,7 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { j->size = std::to_string(W) + "x" + std::to_string(H); j->created_at = unix_now(); j->seed = r->seed; + j->fmt = fmt; for (const gen::VideoRefMedia& m : r->refs) j->refs.push_back(m.name); j->ticket = std::make_shared(); r->ticket = j->ticket; @@ -782,10 +813,10 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { void Server::video_work(std::shared_ptr j) { gen::VideoTicket& t = *j->ticket; const VideoGenInfo& info = deps_.videos->info(); - mm::Mp4Writer mp4; + mm::VideoWriter vw; std::string why; - int st = mp4.open(t.width, t.height, info.fps_num, info.fps_den, t.sample_rate, t.channels, - &why); + int st = vw.open(t.width, t.height, info.fps_num, info.fps_den, t.sample_rate, t.channels, + &why, j->fmt); int32_t frames = 0; bool aborted = false; while (st >= 0) { @@ -806,7 +837,7 @@ void Server::video_work(std::shared_ptr j) { j->progress = t.steps > 0 ? (int)(90LL * e.steps_done / t.steps) : 0; } else if (e.kind == gen::VideoEvent::AUDIO) { if (t.channels > 0) - st = mp4.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why); + st = vw.add_audio(e.samples.data(), (int64_t)e.samples.size() / t.channels, &why); } else if (e.kind == gen::VideoEvent::FRAMES) { if (e.first == 0 && e.n > 0) { std::lock_guard lk(videos_m_); @@ -814,7 +845,7 @@ void Server::video_work(std::shared_ptr j) { j->w = t.width; j->h = t.height; } - st = mp4.add_frames(e.rgb.data(), e.n, &why); + st = vw.add_frames(e.rgb.data(), e.n, &why); frames += e.n; std::lock_guard lk(videos_m_); j->progress = 90 + (t.frames > 0 ? (int)(10LL * frames / t.frames) : 0); @@ -823,7 +854,7 @@ void Server::video_work(std::shared_ptr j) { if (st < 0) t.cancel.store(true); std::string file; if (st >= 0 && !aborted && t.status() >= 0 && frames == t.frames) - st = mp4.finish(&file, &why); + st = vw.finish(&file, &why); release(1); std::lock_guard lk(videos_m_); @@ -833,7 +864,7 @@ void Server::video_work(std::shared_ptr j) { j->progress = 100; j->completed_at = now; j->expires_at = now + opt_.video_ttl_s; - j->mp4 = std::move(file); + j->blob = std::move(file); auto sec = [](int64_t a, int64_t b) { return (double)(b - a) / 1e9; }; const std::string steps = t.t_upscaled_ns > 0 ? rad::fmt("small steps %.1f s, upscale %.2f s, full steps %.1f s", @@ -841,8 +872,8 @@ void Server::video_work(std::shared_ptr j) { sec(t.t_upscaled_ns, t.t_denoised_ns)) : rad::fmt("steps %.1f s", sec(t.t_cond_ns, t.t_denoised_ns)); RAD_INFO("video %s: completed, %.1f MB (%s), %.1f s: queue and prompt %.1f s, %s, " - "decode %.1f s", j->id.c_str(), (double)j->mp4.size() / 1e6, - mp4.video_encoder().c_str(), sec(t.t_submit_ns, t.t_done_ns), + "decode %.1f s", j->id.c_str(), (double)j->blob.size() / 1e6, + vw.video_encoder().c_str(), sec(t.t_submit_ns, t.t_done_ns), sec(t.t_submit_ns, t.t_cond_ns), steps.c_str(), sec(t.t_denoised_ns, t.t_done_ns)); } else { j->status = "failed"; @@ -923,6 +954,7 @@ json Server::video_json(const VideoJob& j) { o["seconds"] = j.seconds; o["size"] = j.size; o["seed"] = j.seed; + o["format"] = format_name(j.fmt); /* what /content will return */ if (j.refine > 0) { o["latent_upscale"] = j.upscale; o["upscale_refine_steps"] = j.refine; @@ -1062,8 +1094,11 @@ HttpResponse Server::handle_video_content(const HttpRequest& req) { (j->failed ? ": " + j->err_message : "")), req.peer); HttpResponse res; - res.content_type = "video/mp4"; - res.body = j->mp4; + const bool webm = j->fmt != mm::VideoFormat::Mp4; /* both webm variants share .webm */ + res.content_type = webm ? "video/webm" : "video/mp4"; + res.set_header("Content-Disposition", + std::string("attachment; filename=\"") + j->id + (webm ? ".webm\"" : ".mp4\"")); + res.body = j->blob; return res; } ApiError e = err_bad("id", "no video '" + id + "'; it may have expired"); diff --git a/tests/videos_test.cpp b/tests/videos_test.cpp index 6062c58e..0cbe3098 100644 --- a/tests/videos_test.cpp +++ b/tests/videos_test.cpp @@ -154,6 +154,8 @@ TEST(a_video_request_that_cannot_be_served_names_its_field) { std::string("num_inference_steps")); CHECK_EQ(v.refused(Videos::body({ { "input_reference", "file-1" } })), std::string("input_reference")); + /* `format` is a known field; a container it does not write names the field. */ + CHECK_EQ(v.refused(Videos::body({ { "format", "avi" } })), std::string("format")); /* fl2va is a valid task, but one that promises a first frame -- refused naming the missing * part, not the task. */ CHECK_EQ(v.refused(Videos::body({ { "task", "fl2va" } })), std::string("first_frame")); @@ -288,6 +290,7 @@ TEST(a_video_job_completes_and_serves_its_file) { CHECK(o["completed_at"].is_number()); CHECK(o["expires_at"].get() > o["completed_at"].get()); CHECK(o["error"].is_null()); + CHECK_EQ(str_at(o, "format"), std::string("mp4")); /* the default container */ HttpResponse c = v.f->get(("/v1/videos/" + id + "/content").c_str()); REQUIRE_EQ(c.status, 200); CHECK_EQ(c.content_type, std::string("video/mp4")); @@ -325,6 +328,43 @@ TEST(a_video_job_completes_and_serves_its_file) { CHECK_EQ(v.f->get(("/v1/videos/" + id + "/content").c_str()).status, 404); } +/* format=webm writes the same job as a WebM instead: an EBML header first, a VP9 video and an Opus + * soundtrack (the 32 kHz fake resampled to Opus's 48 kHz), served as video/webm under a .webm + * filename. The codecs are runtime-discovered, not a compile-time guarantee, so a build without a + * VP9/Opus encoder or a WebM muxer skips rather than fails. The capability block lists the + * containers format accepts. */ +TEST(a_video_can_be_written_as_webm) { + Videos v; + HttpResponse r = v.create(Videos::body({ { "format", "webm" } })); + REQUIRE_EQ(r.status, 200); + json o0 = json::parse(r.body, nullptr, false); + CHECK_EQ(str_at(o0, "format"), std::string("webm")); /* echoed before a byte is encoded */ + const std::string id = str_at(o0, "id"); + json o = v.wait(id); + if (str_at(o, "status") == "failed") { + const std::string m = str_at(o["error"], "message"); + if (has(m, "no libavcodec") || has(m, "VP9") || has(m, "Opus") || has(m, "WebM")) + SKIP("this build has no WebM encoder (VP9/Opus) to write the video with"); + } + REQUIRE_EQ(str_at(o, "status"), std::string("completed")); + HttpResponse c = v.f->get(("/v1/videos/" + id + "/content").c_str()); + REQUIRE_EQ(c.status, 200); + CHECK_EQ(c.content_type, std::string("video/webm")); + REQUIRE(c.body.size() > 64); + /* The EBML magic every WebM/Matroska file opens with. */ + CHECK(c.body.compare(0, 4, std::string("\x1a\x45\xDF\xA3", 4)) == 0); + bool named = false; + for (const auto& kv : c.headers) + if (kv.first == "Content-Disposition" && has(kv.second, ".webm")) named = true; + CHECK(named); + HttpRequest mq; + mq.method = "GET"; + mq.path = "/v1/models"; + json caps = + json::parse(v.f->srv->router().dispatch(mq).body, nullptr, false)["data"][0]["capabilities"]; + CHECK_EQ(caps["video_formats"], json::array({ "mp4", "webm", "webm-av1" })); +} + /* A request the generator fails is a failed job carrying the reason. */ TEST(a_failed_generation_is_a_failed_job_with_its_reason) { Videos v;