diff --git a/Dockerfile b/Dockerfile index 2ec6693a..d0c0c375 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,9 +11,8 @@ # # Stages: # ffmpeg FFmpeg with only the demuxers core/mm/media.cpp admits, the decoders their streams -# need (pictures, video, audio with swresample), the three encoders the images API writes -# (png, mjpeg, libwebp) and those the videos API writes (core/mm/video_out.cpp): H.264 + -# AAC for mp4, VP9 + AV1 + Opus for WebM; all BSD/Apache, no GPL; docs/DOCKER.md +# need (pictures, video, audio with swresample) and the three encoders the images API +# writes (png, mjpeg, libwebp); the distribution's build pulls ~200 unused packages # llvm ROCm's libLLVM rebuilt from ROCm's llvm-project at the commit the image's clang # reports, with docker/llvm-vopd-pairing.patch, which makes LLVM 24's device code # repeatable across builds (cmake/RadAddPlugin.cmake, rad_hip_repeatable) @@ -52,18 +51,17 @@ 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 libvpx-dev libaom-dev libopus-dev \ + libwebp-dev libopenh264-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 (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. +# (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. 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 - \ @@ -71,11 +69,10 @@ 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-libvpx --enable-libaom --enable-libopus \ + --enable-zlib --enable-libdav1d --enable-libwebp \ --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,libvpx-vp9,libaom-av1,libopus \ - --enable-muxer=mp4,webm,matroska --enable-libopenh264 \ + --enable-encoder=png,mjpeg,libwebp,libopenh264,aac --enable-muxer=mp4 --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 \ @@ -142,12 +139,10 @@ 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; 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. +# AV1 decoder, WebP encoder and H.264 encoder; 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 \ - libvpx9 libaom3 libopus0 busybox-static \ + cmake ninja-build pkg-config g++-14 gawk libdav1d7 libwebp7 libopenh264-7 busybox-static \ && rm -rf /var/lib/apt/lists/* COPY --from=ffmpeg /opt/ffmpeg /opt/ffmpeg diff --git a/core/mm/video_out.cpp b/core/mm/mp4.cpp similarity index 55% rename from core/mm/video_out.cpp rename to core/mm/mp4.cpp index 848f8d2f..08548ea8 100644 --- a/core/mm/video_out.cpp +++ b/core/mm/mp4.cpp @@ -1,6 +1,5 @@ -/* video_out.cpp -- VideoWriter (video_out.h) over libavformat, libavcodec, libswscale and - * libswresample. */ -#include "mm/video_out.h" +/* mp4.cpp -- Mp4Writer (mp4.h) over libavformat, libavcodec and libswscale. */ +#include "mm/mp4.h" #include #include @@ -11,10 +10,7 @@ extern "C" { #include #include #include -#include #include -#include -#include #include } #endif @@ -24,20 +20,19 @@ namespace mm { #ifndef RAD_HAVE_FFMPEG -struct VideoWriter::Impl {}; -VideoWriter::VideoWriter() = default; -VideoWriter::~VideoWriter() = default; +struct Mp4Writer::Impl {}; +Mp4Writer::Mp4Writer() = default; +Mp4Writer::~Mp4Writer() = 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 VideoWriter::open(int32_t, int32_t, int64_t, int64_t, int64_t, int64_t, std::string* why, - VideoFormat) { +int Mp4Writer::open(int32_t, int32_t, int64_t, int64_t, int64_t, int64_t, 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); } +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); } #else @@ -45,8 +40,7 @@ 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. The WebM muxer only seeks within - * this one handle, so it never needs the reader. */ + * a second handle on the same bytes with a position of its own. */ struct MemFile { std::string data; int64_t pos = 0; @@ -111,7 +105,7 @@ std::string av_why(const char* what, int e) { } /* namespace */ -struct VideoWriter::Impl { +struct Mp4Writer::Impl { MemFile file; AVFormatContext* oc = nullptr; AVCodecContext* vc = nullptr; @@ -119,18 +113,13 @@ struct VideoWriter::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; - 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; + std::vector audio; /* interleaved, encoded at finish */ bool header = false; ~Impl() { @@ -144,7 +133,6 @@ struct VideoWriter::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); @@ -170,8 +158,7 @@ struct VideoWriter::Impl { } }; -/* 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. */ +/* The reader shift_data opens on the output's own URL; any other URL is refused. */ 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); @@ -194,13 +181,12 @@ static int close_reader(AVFormatContext*, AVIOContext* pb) { return 0; } -VideoWriter::VideoWriter() : p_(std::make_unique()) {} -VideoWriter::~VideoWriter() = default; +Mp4Writer::Mp4Writer() : p_(std::make_unique()) {} +Mp4Writer::~Mp4Writer() = default; -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) { +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) { 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. */ @@ -213,19 +199,14 @@ int VideoWriter::open(int32_t width, int32_t height, int64_t fps_num, int64_t fp p.w = width; p.h = height; p.channels = channels; - 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"; + if (avformat_alloc_output_context2(&p.oc, nullptr, "mp4", nullptr) < 0 || !p.oc) { + if (why) *why = "this libavformat has no MP4 muxer"; return RAD_E_UNSUPPORTED; } - p.oc->url = av_strdup(url); + p.oc->url = av_strdup("radiance.mp4"); p.oc->opaque = &p.file; - if (mp4) { /* only MP4's faststart reopens the output for reading */ - p.oc->io_open = open_reader; - p.oc->io_close2 = close_reader; - } + 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; @@ -238,29 +219,12 @@ int VideoWriter::open(int32_t width, int32_t height, int64_t fps_num, int64_t fp /* ---- video */ const AVCodec* vcodec = nullptr; - 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; - } + 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; } venc_name_ = vcodec->name; p.vs = avformat_new_stream(p.oc, nullptr); @@ -283,24 +247,6 @@ int VideoWriter::open(int32_t width, int32_t height, int64_t fps_num, int64_t fp /* 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); @@ -330,76 +276,51 @@ int VideoWriter::open(int32_t width, int32_t height, int64_t fps_num, int64_t fp sws_setColorspaceDetails(p.sws, sws_getCoefficients(SWS_CS_DEFAULT), 1, sws_getCoefficients(SWS_CS_ITU709), 0, 0, 1 << 16, 1 << 16); - /* ---- audio: AAC at the soundtrack's own rate for MP4, Opus at 48 kHz for WebM. */ + /* ---- audio */ if (channels > 0) { - 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); + const AVCodec* acodec = avcodec_find_encoder(AV_CODEC_ID_AAC); if (!acodec) { - if (why) *why = std::string("this libavcodec has no ") + (mp4 ? "AAC" : "Opus") + - " encoder"; + if (why) *why = "this libavcodec has no AAC 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 = sfmt; - p.ac->sample_rate = (int)rate; + p.ac->sample_fmt = AV_SAMPLE_FMT_FLTP; + p.ac->sample_rate = (int)sample_rate; av_channel_layout_default(&p.ac->ch_layout, (int)channels); p.ac->bit_rate = 96000 * channels; - p.ac->time_base = AVRational{ 1, (int)rate }; + p.ac->time_base = AVRational{ 1, (int)sample_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 " + std::string(mp4 ? "AAC" : "Opus") + - " encoder").c_str(), e); + if (why) *why = av_why("opening the AAC encoder", 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 = sfmt; + p.af->format = AV_SAMPLE_FMT_FLTP; 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.aframe; + p.af->nb_samples = p.ac->frame_size > 0 ? p.ac->frame_size : 1024; 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; - if (mp4) av_dict_set(&opts, "movflags", "+faststart", 0); + 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 " + std::string(mp4 ? "MP4" : "WebM") + - " header").c_str(), e); + if (why) *why = av_why("writing the MP4 header", e); return RAD_E_INVAL; } p.header = true; return RAD_OK; } -int VideoWriter::add_frames(const uint8_t* rgb, int32_t n, std::string* why) { +int Mp4Writer::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"; @@ -422,7 +343,7 @@ int VideoWriter::add_frames(const uint8_t* rgb, int32_t n, std::string* why) { return RAD_OK; } -int VideoWriter::add_audio(const float* samples, int64_t n_frames, std::string* why) { +int Mp4Writer::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"; @@ -432,59 +353,25 @@ int VideoWriter::add_audio(const float* samples, int64_t n_frames, std::string* return RAD_OK; } -int VideoWriter::finish(std::string* out, std::string* why) { +int Mp4Writer::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 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; + /* 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; 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); - 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->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)]; } p.af->pts = at; const int e = avcodec_send_frame(p.ac, p.af); @@ -502,8 +389,7 @@ int VideoWriter::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 " + std::string(p.fmt == VideoFormat::Mp4 ? "MP4" - : "WebM") + " file").c_str(), e); + if (why) *why = av_why("finishing the MP4 file", e); return RAD_E_INVAL; } avio_flush(p.oc->pb); diff --git a/core/mm/mp4.h b/core/mm/mp4.h new file mode 100644 index 00000000..50f0ebb6 --- /dev/null +++ b/core/mm/mp4.h @@ -0,0 +1,52 @@ +/* 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/video_out.h b/core/mm/video_out.h deleted file mode 100644 index 7cd99f2d..00000000 --- a/core/mm/video_out.h +++ /dev/null @@ -1,62 +0,0 @@ -/* 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 1ce9e4d1..728fb5d4 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -3,8 +3,7 @@ * * 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 finished file once it is completed -- an MP4 unless the - * request asked `format` webm (VP9) or webm-av1 (AV1); `variant` thumbnail gives + * GET /v1/videos/{id}/content downloads the MP4 once it is completed (`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. @@ -51,7 +50,7 @@ #include "gen/video.h" #include "mm/imaging.h" #include "mm/media.h" -#include "mm/video_out.h" +#include "mm/mp4.h" #include "rad_internal.h" #include @@ -84,8 +83,7 @@ struct Server::VideoJob { int64_t completed_at = 0, expires_at = 0; bool failed = false; std::string err_code, err_message; - std::string blob; /* the finished file, in `fmt`'s container */ - mm::VideoFormat fmt = mm::VideoFormat::Mp4; + std::string blob; /* the finished 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. */ @@ -121,15 +119,6 @@ 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"); @@ -297,9 +286,6 @@ 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" }); /* The samplers `sampler` accepts; euler is the default and always available. */ caps["video_samplers"] = json::array({ "euler", "res_multistep" }); /* The schedule shift `shift` (video) and `audio_shift` accept: these are the model's trained @@ -384,7 +370,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", "format", + "task", "target", "conditions", "user", "latent_upscale", "upscale_refine_steps", "sampler", "shift", "audio_shift", "negative_prompt", "decoder", "loras", "lora", /* RadVideoGenBatch::guidance_h's order */ @@ -485,22 +471,6 @@ 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; " @@ -1024,7 +994,6 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) { j->sampler = r->sampler; j->shift_video = r->shift_video; j->shift_audio = r->shift_audio; - 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; @@ -1076,10 +1045,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::VideoWriter vw; + mm::Mp4Writer vw; std::string why; int st = vw.open(t.width, t.height, info.fps_num, info.fps_den, t.sample_rate, t.channels, - &why, j->fmt); + &why); int32_t frames = 0; bool aborted = false; while (st >= 0) { @@ -1220,7 +1189,6 @@ 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 */ o["sampler"] = j.sampler == RAD_SAMPLER_RES_MULTISTEP ? "res_multistep" : "euler"; if (j.shift_video > 0.0) o["shift"] = j.shift_video; /* 0: the model's trained shift */ if (j.shift_audio > 0.0) o["audio_shift"] = j.shift_audio; @@ -1374,10 +1342,7 @@ HttpResponse Server::handle_video_content(const HttpRequest& req) { (j->failed ? ": " + j->err_message : "")), req.peer); HttpResponse res; - 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.content_type = "video/mp4"; res.body = j->blob; return res; } diff --git a/docs/DOCKER.md b/docs/DOCKER.md index f1bd4e50..134ac407 100644 --- a/docs/DOCKER.md +++ b/docs/DOCKER.md @@ -40,7 +40,7 @@ The `Dockerfile` stages: | stage | what it does | |---|---| -| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits, the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263, and audio), the three encoders the images API writes (PNG, JPEG, WebP) and those the videos API writes through `core/mm/video_out.cpp` (H.264 + AAC for MP4; VP9, AV1 + Opus for WebM). The distribution's build brings about 200 packages the engine never uses | +| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits, the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263, and audio) and the three encoders the images API writes (PNG, JPEG, WebP). The distribution's build brings about 200 packages the engine never uses | | `llvm` | ROCm's `libLLVM` rebuilt from ROCm's llvm-project at the commit the image's `clang --version` names, configured as ROCm ships it, with `docker/llvm-vopd-pairing.patch` applied. ROCm 10.1's clang does not compile the same source to the same code twice (its VOPD pairing follows heap addresses); the patch makes it repeatable. This library is the only compiler file that changes | | `build` | `rocm/dev-ubuntu-24.04:10.1.0-full` plus cmake, ninja and g++-14. Device code is compiled by ROCm's clang from `/opt/rocm-repeatable`, a shadow of the ROCm tree whose `libLLVM` is the `llvm` stage's (`-DRAD_HIP_VOPD_REPEATABLE=ON`, `--rocm-path=/opt/rocm`); the HIP runtime and comgr in the image are ROCm's own. Configures with kernels for `GPU_TARGETS`, builds, and installs to `/opt/radiance` with the recipes. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle | | `test` | `docker/llvm-check.sh`, then `ctest -LE 'gpu\|oot'`: every suite that runs without a card. The check recompiles one kernel file four ways: with pairing off, the image's compiler must emit ROCm's device code byte for byte; with pairing on, two compiles must match the build's own object. The image is produced only if both pass | @@ -69,61 +69,6 @@ docker run --rm --device /dev/kfd --device /dev/dri --security-opt seccomp=uncon radiance-build ctest --test-dir /build -L gpu --output-on-failure ``` -## Video output: MP4 and WebM - -`/v1/videos` writes the file in the container the request's `format` asks for: `mp4` (the default, -H.264 video + AAC audio), `webm` (VP9 + Opus) and `webm-av1` (AV1 + Opus). The writer is -`core/mm/video_out.cpp`. It looks every encoder and the muxer up by name at run time -(`avcodec_find_encoder_by_name`, `avformat_alloc_output_context2`), so the image must actually hold -the codecs a format needs — there is no compile-time link to `radiance` itself that would force it. - -WebM is here for the same reason the reference workflow ships it: browsers play it and older CPUs -decode it. VP9 is the old-hardware-friendly default; AV1 is the codec the DaSiWa example prefers and -is opt-in (`webm-av1`) — slower to encode, but it decodes in software on an AVX2-only CPU, no -hardware block or AVX-512 required. - -For the image to emit WebM the `ffmpeg` stage must build in VP9, AV1 and Opus. That is already in the -`Dockerfile`: `--enable-libvpx --enable-libaom --enable-libopus` in the configure line, -`libvpx-vp9,libaom-av1,libopus` in `--enable-encoder`, `webm,matroska` in `--enable-muxer`, and -`libvpx-dev libaom-dev libopus-dev` in the stage's build packages. **Nothing GPL is pulled**: libvpx, -libaom and libopus are BSD, the same posture as `libopenh264` and the FFmpeg-native `aac`, so the -build turns on no `--enable-gpl` and does not use x264 (MP4 encodes through `libopenh264`). -`docker/licenses.sh` therefore needs no GPL entry for them; it only needs each package to carry a -`copyright` file, which all three do. - -These are **link-time** dependencies of `libavcodec` (they appear in its `ldd`), not loaded by -`dlopen`. So the `rootfs` stage — which resolves every ELF from inside a chroot of the tree and -fails the build on a library it cannot find — pulls `libvpx`, `libaom` and `libopus` in on its own, -exactly as it already does for `libdav1d7`, `libwebp7` and `libopenh264-7`. The runtime `apt-get` -installs their shared libraries by the Ubuntu 24.04 package names — **`libvpx9 libaom3 libopus0`** — -kept in the same list as those three. If a future base image bumps a SONAME, rename the package here -the way those were renamed before; a wrong or missing name fails the `rootfs` chroot check, so it -cannot ship silently broken. - -The graceful path is worth knowing even though the image should never need it: because the codecs are -found at run time, if one is ever absent the `mp4` default still writes and a `webm` request fails -that single request cleanly with an `encoding_failed` naming the missing encoder — the engine does not -crash. So the image is safe before the libraries land; WebM output simply does not work until they do. - -One non-obvious detail the writer handles so the build needs no extra flag: the model's audio is -stereo at **32 kHz**, which Opus cannot encode (it supports 8/12/16/24/48 kHz). For WebM the writer -resamples to 48 kHz through `libswresample` — already in the build for audio decode — while MP4 keeps -AAC at the native rate. That is why a WebM file reports `opus` at 48 kHz and an MP4 reports `aac` at -32 kHz. - -To confirm a built image ships the codecs, no card needed — look at what `libavcodec` links against: - -```sh -docker run --rm --entrypoint sh radiance -c \ - 'for l in $(find /opt/radiance -name "libavcodec.so*" 2>/dev/null); do ldd "$l"; done \ - | grep -E "vpx|aom|opus"' # libvpx / libaom / libopus must all appear -``` - -For a functional check, serve a model and request a three-second clip: `format=webm` then -`format=webm-av1`, and `ffprobe` the downloaded file — expect `vp9` + `opus` and `av1` + `opus` in a -`matroska,webm` container. The host `videos_test` already covers the router's format handling without -a card. - ## Run it The entrypoint is `radiance`. The other installed tools (`rad-convert`, `rad-info`, `rad-kbench`, diff --git a/tests/videos_test.cpp b/tests/videos_test.cpp index b2ec755b..c3e92e2b 100644 --- a/tests/videos_test.cpp +++ b/tests/videos_test.cpp @@ -164,7 +164,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. */ + /* The output is always the MP4: `format` is no longer a field and is refused as an unknown + * one, naming itself. */ CHECK_EQ(v.refused(Videos::body({ { "format", "avi" } })), std::string("format")); /* The keyframe tasks belong to a model with a video encoder; this one has none, so the name * is refused as a task. A model that encodes accepts it and is refused naming the missing @@ -382,7 +383,6 @@ 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")); @@ -420,43 +420,6 @@ 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;