Repository navigation
obs-ffmpeg: Write what the encoders hold back when a Custom FFmpeg Output stops - #1125
Merged
Merged
Conversation
…ording Encoders hold frames back (B-frames, lookahead: libx264, libvpx, SVT-AV1, and the AAC encoder's one frame of delay) and hand them out only once the end of the input is signalled with avcodec_send_frame(ctx, NULL). ffmpeg_deactivate() never sends it, so those frames are freed with the encoder, and it also frees the packets the write thread had not written yet. With libx264, libvpx-vp9 or FLV recordings through the Custom FFmpeg Output the last ~0.8 s of video is missing, with SVT-AV1 more than a second. test_ffmpeg_output_drain builds the real obs-ffmpeg-output.c into the test, wraps avcodec_send_frame() (-Wl,--wrap) to count the frames given to the encoder, records for 1.5 s and stops. Every frame encoded before obs_output_stop() was called was rendered before the stop time, so it must be in the file; the test counts the finished file's packets. RED: 3 of 4 cases fail. MPEG-4 with 3 B-frames: 41 of 44 frames in the file; libx264 (veryfast): 27 of 45; AAC in ADTS: 68 of 69. Guard, passing: FFV1 (no encoder delay) keeps all 44 and adds none. Without a display all cases skip. Refs obs-rust#1124. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tput stops On a stop, ffmpeg_deactivate() now writes the packets the write thread had not written yet, then drains each encoder (avcodec_send_frame(ctx, NULL), then every packet avcodec_receive_packet() returns) and writes those packets, before the trailer. The stop time still applies: packets from after it are left out, as before. When writing failed (the write thread's error path) nothing is drained, as before. GREEN: test_ffmpeg_output_drain 4/4 (MPEG-4 44/44, libx264 45/45, AAC one packet more than frames: the final padding frame; FFV1 45/45); test_ffmpeg_output_stop 2/2 and test_ffmpeg_output_alpha 3/3 still pass. Fixes obs-rust#1124. Co-Authored-By: Claude Opus 5.5 <[email protected]>
zackees
added a commit
that referenced
this pull request
Oct 16, 2026
…y builds #1125 added a static write_packet to obs-ffmpeg-output.c; obs-ffmpeg-mux.c already defines a write_packet (declared in obs-ffmpeg-mux.h), which a unity batch sees too. No test references the static.
chriscoveries
pushed a commit
to chriscoveries/obsrust-fork
that referenced
this pull request
Oct 16, 2026
…++ (obs-rust#1128) * build: Compile every target against one unified precompiled header ENABLE_PCH (default ON) gives each target one precompiled header per language from cmake/pch/: the C standard library, the libobs headers (obs-internal.h for libobs itself, obs-module.h and util/* for plugins), and for UI targets all of QtCore/QtGui/QtWidgets, plus the frontend headers most of obs-studio's sources include. set_target_properties_obs applies it at the end of the target's directory, after its platform files add sources. Sources that define a macro before their first #include keep compiling without the PCH. _GNU_SOURCE is defined in the PCH on Linux, since several sources request it after other includes. Fresh Linux tree, ccache off, -j16: CPU time 2416 s -> 1798 s (-26%); obs-studio 2799 s -> 1995 s of compile time. ENABLE_UNITY_BUILD (default OFF) adds unity builds on the same hook, for when the targets' file-local names are made unique. * libobs, plugins, frontend: Make file-local names unique per target A unity build compiles a target's sources as batches of one translation unit, so two sources' file-local names meet. Every collision on Linux: - static functions and variables with the same name in two sources of one target get a file-specific name (get_defaults in obs-encoder.c, obs-output.c, obs-service.c and obs-source.c; mix_a/mix_b in five transitions; the AV1 bit reader in rtmp-av1.c; nvenc-compat.c's copies of nvenc-properties.c's functions; ...). Struct fields keep their names. - file-scope macros that two sources define differently (do_log, blog, warn, get_weak, the compressor/expander/limiter settings, ...) are #undef'd at the end of the source that defines them. - frontend: the remux, importer and missing-files models' enums move into namespaces (their Count/State/EntryStateRole enumerators clashed, the TODO in MissingFilesModel.hpp), with using-declarations keeping the type names; MissingFilesPathItemDelegate.cpp includes MissingFilesModel.hpp instead of redeclaring its enum; the AutoConfig wizard's ListOpt is declared once in AutoConfigStreamPage.hpp; FillPropertyCombo is declared once, with its default argument, in ComboSelectToolbar.hpp. - mp4-mux's codec enumerators get an MP4_ prefix (flv-mux.h has its own CODEC_H264/HEVC/AV1); decklink-captions.h gets #pragma once. No behaviour change: renames of internal identifiers, #undefs at the end of a source, and declarations moved without changing them. * build: Unity builds for every first-party target, on by default on Linux PCH and unity settings are now applied in one pass at the end of the top-level CMakeLists.txt to every target outside deps/, test/ and rust/, including the shared static libraries (idian, the Qt wrappers, ...) that don't go through set_target_properties_obs. Qt targets that don't link libobs get a Qt-only precompiled header. ENABLE_UNITY_BUILD defaults to ON on Linux, where every target builds with it (batches of OBS_UNITY_BUILD_BATCH_SIZE=8). Sources that must be first in their translation unit (macros before includes) and whole-file duplicates (gl-wayland-egl.c next to gl-x11-egl.c, the legacy obs-slideshow.c) compile on their own; generator-expression sources are matched by file name. Windows and macOS keep it OFF until their own sources' collisions are renamed. Fresh Linux tree, ccache off, -j16 (baseline / PCH / PCH + unity): CPU time 2416 s / 1798 s / 1053 s (-56%) wall time 315 s / 322 s / 198 s (-37%) obs-studio 2799 s / 1995 s / 726 s of compile time * obs-filters: Keep expander-filter.c's static names for test_expander_unity test/cmocka/test_expander_unity.c includes expander-filter.c and calls its static gain_coefficient, so the expander keeps analyze_envelope, resize_env_buffer and gain_coefficient, and the compressor's copies take the compressor_ prefix instead. * ci: Tier 2's compile checks find sources inside unity batches With ENABLE_UNITY_BUILD a source is compiled inside a unity batch (<target>.dir/Unity/unity_N_c.c includes it), not as its own object. The ported-source check (libobs vs libobs-with-rust) and the obs-nvenc loader check now accept either. * build: Cache Linux C/C++ compiles with soldr's zccache; ccache keeps PCH hits zccache.cmake (Linux, ENABLE_ZCCACHE, default ON) uses soldr's host compiler wrapper (zccache-soldr <compiler> ...) as the C/C++ launcher when soldr is installed and nothing else chose a launcher; an explicit CMAKE_<LANG>_COMPILER_LAUNCHER or ENABLE_CCACHE wins. It caches the precompiled headers and unity batches as they are. Until soldr#3829 adds a stable launcher command, the wrapper is found below the soldr root. Fresh Linux tree, PCH + unity, -j16: no cache 198 s; zccache cold 191 s; zccache warm (clean rebuild, same tree) 26 s. With a ccache launcher, targets with a precompiled header now run it with CCACHE_SLOPPINESS extended by pch_defines,time_macros (and GCC gets -fpch-preprocess); without them ccache refuses those sources. * obs-ffmpeg: Rename obs-ffmpeg-output.c's static write_packet for unity builds obs-rust#1125 added a static write_packet to obs-ffmpeg-output.c; obs-ffmpeg-mux.c already defines a write_packet (declared in obs-ffmpeg-mux.h), which a unity batch sees too. No test references the static. * build: Keep _GNU_SOURCE out of the precompiled header Defining a feature macro in the PCH is not equivalent to the sources that request it: with glibc 2.43, _GNU_SOURCE makes strstr() return const char * for a const argument, and librtmp's parseurl.c failed the Linux CI build with -Werror=discarded-qualifiers. threading-posix.c and obs-nix.c, which define _GNU_SOURCE after other includes, compile without the PCH and outside unity batches instead. * build: Unity and PCH on Windows and macOS; cross-check their platform plugins ENABLE_UNITY_BUILD now defaults to ON everywhere. cmake/cross applies the same precompiled headers and unity batches and compiles, besides libobs, the platform-only plugins: win-capture (with graphics-hook and get-graphics-offsets), win-wasapi, win-dshow, obs-nvenc and coreaudio-encoder for win-x64; mac-capture, mac-avcapture, mac-videotoolbox and coreaudio-encoder for mac-arm64. OBS_CROSS_CMAKE_ARGS passes extra CMake arguments to cmake/cross/docker.sh; OBS_UNITY_BUILD_BATCH_SIZE=0 puts each target in one batch, so every pair of its sources meets. Windows, macOS and Linux build with batch size 0 and 8. - PCH: Xcode gives a target one prefix header for all languages, so targets that mix C++ with C or Objective-C compile without a PCH there (the macOS build failed on decklink's C sources seeing <algorithm>). The PCH restores WIN32_LEAN_AND_MEAN after the libobs headers (util/sse-intrin.h defines it on non-x86 Windows and broke obs-browser's winsock use on Windows arm64). Targets can name their profile (OBS_PCH_PROFILE). - Unity: graphics-hook and get-graphics-offsets opt out (one Direct3D version per source; d3d8.h and d3d9.h can't share a translation unit). Whole-file siblings compile on their own: window-capture.c, obs-nix-wayland.c, obs-ffmpeg-mpegts.c, media-playback's cache.c. Skip lists also match sources that INTERFACE libraries hand to a target. * libobs, plugins, frontend: Remove the file-local name collisions batching hid Compiling each target as a single unity batch (Linux, and cmake/cross for Windows and macOS) surfaced collisions the 8-source batches only kept apart by chance: - libobs: graphics.c #undef'd <windows.h>'s near/far for the rest of a batch (every later NEAR/FAR, DEFINE_GUID and commctrl.h use broke); it now saves and restores them with push_macro/pop_macro. obs-hotkey.c restores uthash's HASH_FUNCTION after switching it to an integer hash; effect.c undefines the min() it defines. Renamed statics: shader-parser, obs-source-transition, obs-scene, obs-source, dstr-libc, source-profiler (profiler.c keeps 'enabled' for the C oracle), obs-nix-hotkey-state, CoreAudio monitoring. - plugins: renames in win-capture (monitor/window/duplicator capture), linux-pipewire (screencast vs camera portal; the camera portal's global 'connection'), obs-filters (limiter, mask), obs-outputs (mp4-mux keeps free_packets for rtmp-stream.c's test), obs-ffmpeg (hls-mux), mac-capture (the two ScreenCaptureKit restart callbacks), obs-nvenc (nvenc-compat.c's copies of nvenc.c's create/name functions). obs-outputs' colour enums, duplicated in rtmp-stream.h and flv-output.c, move to color-enums.h. Include guards: rtmp-stream.h, mac-sck-common.h, window-utils.h and two mac-avcapture headers. enum-wasapi.hpp declares GUID_NULL (cguid.h) before audioclient.h pulls in ks.h, which redefines it as a macro. - cross-only fixes: graphics-hook's dummy window thread takes LPVOID (its LPTHREAD_START_ROUTINE signature), wasapi-notify.hpp includes mmdeviceapi.h in the SDK's lowercase. - frontend: per-file names for the duplicated color_from_int/color_to_int, GetCurrentScene/MoveItem, return_first_id, select_one, getNewSourceName, isHiddenInMixer, ... (BasicOutputHandler.cpp, which tests compile, keeps its names); MakeQFont keeps its default argument only in its definition. Names tests or the C oracle use keep theirs; only internal identifiers change. * build: Keep third-party and Objective-C sources out of unity batches The full Windows and macOS builds showed two kinds of source that must not share a translation unit with ours: - deps/ sources that reach a first-party target through an INTERFACE library (libdshowcapture in obs-virtualcam-module: its winsock2.h after another source's full <windows.h> redefined every winsock declaration on Windows arm64). They now compile on their own and without the PCH. - Objective-C sources: without the OBJC language enabled, CMake files .m under C, so Xcode compiled obs-cocoa.m and platform-cocoa.m inside a C unity batch (Foundation parsed as C on macOS). cmake/cross enables OBJC, which is why it didn't see this. Skip matching now also covers sources INTERFACE libraries hand a target.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #1124
What and why
A recording or stream through the Custom FFmpeg Output (
ffmpeg_output) now ends where it was stopped. Before, it lost what the encoders were still holding: about 0.8 s of video with libx264, libvpx-vp9 or FLV/H.264, about 1.3 s with SVT-AV1, and the last AAC frame. Found by our FFmpeg 8.1.3 A/B release check (check 67); the same in FFmpeg 8.1.2 and 8.1.3. Not from our #355: that only added the wait on the encode mutex, and the encoders were never drained before it either.Cause (
plugins/obs-ffmpeg/obs-ffmpeg-output.c)encode_video()andencode_audio()send a frame and take at most one packet. Encoders with B-frames or lookahead hold frames back until the end of the input is signalled withavcodec_send_frame(ctx, NULL), which nothing sent.ffmpeg_deactivate()freed the packets it had not written.ffmpeg_data_free()then wrote the trailer and freed the encoders with their frames still in them.In the release (0.1.0-beta.20261014 AppImage, headless, fresh profile, loopback only; check 67: Advanced output, Custom Output (FFmpeg) to a file, about 4.2 s per recording, each file decoded):
Every file decodes with 0 errors and the 1 kHz tone at 1000.0 Hz on both. The three replay buffer cases in the check use
obs-ffmpeg-muxand are unchanged.Fix
process_packet()is split:write_packet()writes one packet unless it is from after the stop time, as before, and frees it.ffmpeg_deactivate(output, drain): on a stop (ffmpeg_output_full_stop(),drain = true) it writes the packets still queued after the write thread has ended. Thendrain_encoders()sendsNULLto the video encoder and each audio encoder and writes every packet they return, all before the trailer. The stop time still applies, so packets from after it are left out.drain = false), the queued packets are freed and nothing is drained, as before.RED → GREEN
RED commit: 9e0154b
test/cmocka: Stopping a Custom FFmpeg Output loses the end of the recording.test_ffmpeg_output_drainbuilds the realobs-ffmpeg-output.cinto the test, liketest_ffmpeg_output_stop. It wrapsavcodec_send_frame()(-Wl,--wrap) to count the frames given to the encoder, records for 1.5 s, stops and counts the finished file's packets. Every frame encoded beforeobs_output_stop()was called must be in the file. 3 of 4 cases fail in both lanes:stop_writes_frames_held_by_video_encoder(MPEG-4 withbf=3, built into FFmpeg): 41 of 44 frames in the file;stop_writes_frames_held_by_x264_lookahead(libx264veryfast, skipped where FFmpeg has no libx264): 27 of 45;stop_writes_frames_held_by_audio_encoder(AAC in ADTS, built in): 67 of 68.The guard
stop_without_encoder_delay_keeps_every_frame(FFV1) passes: 45 of 45 and no extra packets.GREEN: ee89d5e. 4/4 with
ENABLE_RUST_LIBOBSOFF and ON: MPEG-4 44/44, libx264 45/45, FFV1 45/45. For AAC, 68 frames give 69 packets: the encoder's final padding frame.test_ffmpeg_output_stop(2/2) andtest_ffmpeg_output_alpha(3/3) still pass.Full ctest at
-j8(private Xvfb, systemlibobs-openglmasked, TMPDIR unset): 267/267 in each lane. Skipped onlyopen_crashes_without_obs_core(intest_audio_ioandtest_video_io, as on master). All PipeWire/Pulse tests ran.clang-format 22.1.3, gersemi 0.25.0 and
ci/test_registration.pyare clean.CI: the test is registered like
test_ffmpeg_output_stop(OS_LINUX AND TARGET OBS::libobs-opengl,GRAPHICS_MODULE_PATH, run under xvfb-run). It skips every case without a display, checked withDISPLAYunset. The libx264 case skips where FFmpeg lacks it, and the other three use encoders built into FFmpeg.The release check again, on this branch's build (C lane, with the frontend): see the table above.
Checklist
master-W..., ratchets): noneAI note: Claude Code (Claude Opus 5.5) wrote the code, the test, the commit messages and this text under the submitter's direction, and ran the tests above on the submitter's machines.
🤖 Generated with Claude Code