Keep producer timestamps and queue capacity in source frames, configure AAC at a native rate and initialize conversion before exposing the Surface. Preserve direct standard-rate input. Cancel partial network startup on setup failure, retaining the original error.
Full Windows C89 and GCC/Clang sanitizer suites pass, including source clocks and conversion-startup rollback. Native device acceptance remains separate.
Accept vcodec=av1, route its sized OBUs to enhanced FLV, and preserve SDR/HDR profile and source color admission. Select Android AV1 levels from Annex A main-tier display-rate, picture, dimension, header-rate and bitrate bounds; native inventory still validates the complete request.
Strict C89 Windows and Linux ASan/UBSan frontend/session/worker suites pass. File and stream tests cover SDR, PQ and scRGB; four actual-source MIME, routing and level-limit mutations are rejected. Native device encoder acceptance remains separate.
Select the owned stream dispatcher for RTMP(S), validate native FLV/AAC options, propagate coded HDR source metadata, and keep stream URLs out of file history. Expose backend streaming capability and enable shared RTMP/FLV in Vulkan Android NDK builds with crypto.
Windows frontend and native menu checks pass; full arm64 Android library builds and links with native streaming entry points and passes 16 KiB ELF alignment. This is build/contract acceptance, not physical-device or independent receiver acceptance. Direct integer source audio rates and AVC/HEVC are retained; fractional-rate resampling and AV1 frontend selection remain separate work.
Connect the admitted desktop Vulkan encode queue to viewport recording through
an asynchronous worker. Capture GPU pixels in the renderer submission, publish
only successful submissions, and retain source/device resources through stop,
resize and deferred video reinitialization. Refuse unsupported devices, HDR,
formats and audio layouts before creating output. Start after the first core
frame so admission uses its actual audio layout.
Hold PCM on the existing worker queue until encoded video establishes its
clock limit. Trim trailing queued PCM at video EOS before AC-3 padding and
publish the actual consumed count after worker retirement. This prevents a
threaded resize from leaving audio beyond the last captured picture. Add no
producer locks, waits, pixel readbacks or pacing logs.
Configure selects the driver on desktop Vulkan builds with its dependencies;
existing default driver priority is retained. Add frontend admission/lifetime,
delayed-video PCM, terminal-result publication and native isolated-window
resize/reinit/stop regression coverage.
Validation: GCC/Clang ASan+UBSan frontend contracts, Vulkan encode contracts,
recording output/session/dispatch contracts and independent MP4 A/V checks.
Windows native recording passes threaded/direct multichannel float PCM at
32/44.1/48 kHz, plus resize, reinit and stop with Khronos sync validation.
Desktop Linux and Windows frontends build with automatic feature selection.
Native Linux GPU acceptance remains open. The unrelated extended RSLC unsized
uniform-buffer fixture is rejected by the installed standalone SPIR-V validator;
that check is retained as a failure, not reported as an extended-suite pass.
Keep the producer clock and queue budget in source frames. Convert on the recording worker through AudioToolbox, retain converted packets across mux backpressure and retire native input borrows before queue teardown. Preserve the direct path for integral rates and extend conversion contracts through eight channels.
Derive the native Metal backend from a shared SDK floor rather than a desktop-only target check. Add shared RTMP/FLV flags to the existing Apple network configuration and let griffin include the existing native implementation units. Extend the real SDK audit to compile the actual C frontend using automatic backend admission, with ARC kept out of C compilation.
This is an unlanded integration candidate. SDK compilation, full Apple application linking and physical-device recording/streaming acceptance are pending.
Use the same native queue limits in menu ranges and backend initialization. Honor the selected NVENC ring size instead of fixing it at four. Keep invalid legacy values on the existing four-slot fallback and restore legacy ranges when switching away from native recording.
Validate native ranges and fallback values, driver changes and actual Metal initializer slot configurations in the portable frontend tests.
Query registered recording backends instead of restricting the shared Recording page and Quick Menu start action to FFmpeg. Native GPU recorders expose their custom profiles, GPU capture, frame-drop and queue controls; compiled Metal/NVENC RTMP providers also expose service, profile and URL settings. Keep unsupported quality/software controls hidden and omit the UDP Local mode for RTMP-only backends in dropdowns and left/right navigation. Capability queries do no device, codec or network work.
The production settings-list, Quick Menu predicate and setting actions pass a shared native capability fixture on Windows and Linux sanitizers. The actual old settings-list body and old start predicate each fail it. Full application/native build checks remain required before publication.
Admit RTMP/RTMPS URLs and strict FLV/AAC profiles, preserve fractional source audio clocks and choose supported AAC output rates. Enable the built-in transport by default for eligible networked Metal/AVFoundation builds while respecting explicit feature disables.
Keep stream URLs out of recording history and avoid retaining a redundant frontend URL copy. Release the worker startup URL after the client adopts it and keep unsupported SDK builds on the existing fallback.
Add portable profile/source-clock checks and native application start/stop acceptance for direct/threaded AVC, fractional HEVC, mono and video-only output. Native acceptance remains required before landing.
Select HEVC Annex B framing and advertise the actual encoder and optional AAC track during worker setup. Derive colorInfo from coded encoder metadata, preserving absent mastering/light values and the existing core HDR ABI. Keep packet/audio leases and bounded worker scheduling unchanged.
Allow native HEVC streaming in the frontend and use its smaller FLV packet limit. Cover admission/teardown contracts, real SDR/PQ/HLG GPU streams, wire color metadata and threaded/direct frontend streaming. Correct the native fixture to use the codec-specific packet bound.
rslc_front: the parser's error returns go through rslc_p_fail()'s
false directly instead of a comma expression. encoding_deflate: the
past-end refill counts its overrun in a branch. gl2: drop an unused
local. record_ffmpeg: ok starts false and the lowered-thread flag lives
only under FFMPEG_HAVE_THREAD_NICE. rgui: subtitle glyph counts are
narrowed after clamping to the column count. r7z: pend_method takes
the resumable coder's method ID explicitly as 32 bits.
The recorder's av_log callback builds each line in a slot of the
calling thread's own, claimed with a compare-and-swap and released once
the line is out, so lines from the encoder threads never splice and no
call waits on another.
The ffmpeg core hands each subtitle track's newest change to the thread
that renders through a one-slot mailbox swapped with a single exchange;
only that thread calls into libass, seeks included. A change supersedes
the one before it, so the held memory stays bounded when nothing
renders. Targets without pointer atomics keep a lock around the swap.
samples/cores/ffmpeg_ass_events checks the hand-off against a libass
stand-in, and samples/record/ffmpeg_pipeline gains a lane for whole log
lines from several threads.
Use the format-ID specifier required by AudioToolbox when selecting AAC sample rates. Validate requested audio settings and retry with the encoder default bitrate when the preset is rejected.
Report refused or failed audio/video appends instead of returning success. Cover the property ABI, buffer release and writer states with portable regressions, and add a native AudioToolbox contract check.
Connect the MediaCodec recording frontend to worker-owned encoders and
Vulkan capture without frame-path readbacks or new waits. Keep capture
leases through native retirement and defer cold queue work on contention.
Calibrate AAC presentation edits, omit an empty audio source, and drain
healthy recordings before video resets. Retain the teardown path for
failed or ambiguous GPU work. Include portable lifecycle, audio, file
and capture regressions.
Enable video-history storage, lifetime, playlist display/actions and native recording publication when HAVE_WEBMPLAYER supplies playback without FFmpeg or MPV. Classify builtin movies consistently during history/pre-load handling.
Validated a full FFmpeg/MPV-disabled builtin-player release build, actual MP4 playback and the resulting movieplayer/builtin video-history entry. The Metal controller history branch also compiles with warnings as errors and its 2 KiB frame budget.
Capture the final Metal drawable on its existing command buffer and service owned VideoToolbox/AVFoundation recording on the dedicated worker. Share frontend GPU lifecycle hooks with NVENC, retain in-flight snapshots through stop, and preserve source timestamps across repeated presentations and allowed drops.
Add sanitizer coverage for capture backpressure and output changes, plus a full native frontend build gate. Native frontend runtime acceptance remains pending.
AudioFormatGetProperty may return fewer ranges than its advertised capacity. Iterate only the returned complete entries, reject oversized or malformed responses and ignore invalid ranges before falling back. Share the helper with the pending native recording mux.
Validation: GCC and Clang C89, 2 KiB frame limit, ASan/UBSan; shortened response reproduces the old invalid rate selection. Native framework validation remains pending.
Select P010 BT.2020/PQ for HEVC and AV1 when the renderer reports active PQ or scRGB. Preserve SDR BT.709 admission, refuse H.264 HDR, and stop before a changed output encoding enters an existing session. Reuse GPU conversion without frame-path waits or readback; leave unknown mastering and content-light metadata unspecified.
Derive MP4 nclx from encoder configuration and refuse contradictory AV1 sequence tags. Add independent HDR bitstream, native frontend pixel/audio and output-mode guard coverage.
Keep the original multichannel batch available to recording when playback uses the stereo fallback, without retaining it after the callback. Admit native AC-3 speaker masks up to six channels while preserving their positions.
Use the configured float hint before a device context exists, even if the audio active flag is already set. Add channel-identity and startup-format regressions plus native signed-PCM and negotiated-float acceptance.
Enable optional AC-3 from the existing signed PCM recording path at 32, 44.1 and 48 kHz. Arm audio and video together after worker startup, preserve their shared clock, and fail on PCM backpressure or rate changes without blocking or dropping audio.
Let already queued video frames complete after normal stop so the audio tail stays aligned. Cover admission and retirement boundaries in portable tests and validate all codec/threading/rate combinations through the real frontend.
Expose an explicit video-only NVENC MP4 recording driver for SDR D3D12. Carry GPU capture and timestamps with direct or threaded video frames, then retire the owned capture asynchronously after queued frames release it. Defer startup until the viewport is ready and keep staged quit alive through finalization.
Add real frontend codec acceptance and frame-rate and wrapper lease regressions. Core audio and HDR admission remain unavailable in this mode.
Keep bottom-up input pitch signed through the video FIFO row packer and stop advancing the source after the final row. Preserve the packed positive-stride bulk copy. Exercise signed packed/padded rows at contiguous and split ring boundaries, including one-row inputs, and encode/decode alternating bottom-up frames with pixel and timestamp checks.
The WDM-KS property, setup and stream-header structs, the waveOut and IEC 61937 wave formats, the CoreAudio stream descriptions and the PulseAudio sample spec are set member by member; the WDM-KS position, latency and RT-buffer queries, the ASIO channel queries and the Mach timebase read only what their checked calls return. Each packet submitted on the WDM-KS stream writes its header's members rather than clearing it.
Encode pending silence shorter than an audio frame before flushing the encoder. Discarding that remainder truncates drop-mode recordings even when finalization succeeds.
Decode lossless recordings in the regression to verify the real audio prefix and all owed silence, with and without a whole encoder frame of debt.
Use the channel count when deinterleaving samples, retain the stereo path, and route mono through a duplicated pair for the stereo resampler. Fill FFmpeg frames with the packed plane layout produced by the helpers and propagate frame preparation errors.
Cover mono, stereo, three-channel and six-channel planar samples, allocation recovery, and actual AAC encoder input including partial final frames.
Return conversion and planarization failures before encoding unfinished audio. Track float-buffer capacities independently so a retry completes outstanding allocations, and retain successful pair-buffer resizes if the next allocation fails.
Cover allocation failures and successful retries in integer, float, multichannel pair and planar audio paths.
Mark recording failed, clear the worker's alive flag and wake producers when a required scratch buffer cannot be allocated. Free the remaining scratch before exiting so producers cannot remain blocked behind an undrained queue.
Cover startup audio and plain-ring video allocation failures, producer rejection, finalization failure and cleanup.
Mark finalization failed when required audio or plain-ring video scratch cannot be allocated, while retaining safe draining and cleanup.
Inject both failures after the encoder has joined and verify failure reporting and output closure alongside successful recording.
Remember audio/video codec and packet-write failures while the encoder owns the recorder. Read the result after joining and draining so a later successful trailer cannot hide an incomplete recording.
Cover send, receive, packet-write, and final-drain failures alongside normal recording and cleanup.
Check trailer, buffered output, and close errors while always closing the file. Propagate failed finalization through frontend teardown and skip history insertion for incomplete recordings.
Cover failing output writes, close failures, sticky AVIO errors, frontend cleanup, and successful completion.
The video ring is mirrored, so a frame is one contiguous span across
the wrap: the push packs its rows into one reservation and publishes
once, and the encoder side scales straight out of the ring instead of
copying the frame into a scratch buffer first. Where a ring cannot be
mirrored the push publishes per contiguous span and the encoder side
keeps its scratch copy for the frames that straddle the wrap.
ffmpeg_pipeline_test pushes every other frame with a padded pitch and
gains a PLAIN_RING build that takes the unmirrored path.
The audio and video contexts, which avcodec_alloc_context3() made, are
released with avcodec_free_context() on every FFmpeg the recorder
builds against, in place of an avcodec_close() and av_free() pair that
only FFmpeg 8 went without.
The video ring is held under a byte ceiling, 256 MiB on 32-bit hosts and
1 GiB elsewhere: a queue deeper than that is shortened to fit, a ring
that still cannot be had is halved down to the minimum, and the size it
got is the one logged. The frontend's Debug log level asks libav* for
AV_LOG_VERBOSE, not AV_LOG_DEBUG, where encoders log every frame from
their threads.
ffmpeg_pipeline_test opens a recording of 16 MiB frames with a
128-frame queue and checks the queue it got is within the ceiling, and
that Debug logging stops at AV_LOG_VERBOSE.
* recording: add video_record_allow_frame_drop and video_record_fifo_frames
Wires two record_ffmpeg queue knobs through the settings_def
single-source tables, record_params and the Recording settings list
(shown for the ffmpeg driver only).
video_record_allow_frame_drop bool, default true
video_record_fifo_frames uint, default 32, 8..128 step 4
(Lakka: advanced only)
Both are read when a recording starts; the driver side is the next
patch. msg_hash_lbl_str.h regenerated with tools/gen_lbl_str.py, keeping
only the two new rows.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: drop instead of stalling when the encoder falls behind
With the encoder behind, a full queue blocked the frontend in
push_video/push_audio, so a slow encoder slowed the game down.
With video_record_allow_frame_drop (default on):
- a frame that doesn't fit is dropped; the count rides with the next
queued frame and the encoder leaves a pts gap for it, so video stays
aligned with audio
- an audio chunk that doesn't fit is owed as silence and written ahead
of the next chunk that does, and anything still owed is encoded at
finalize, so the audio track keeps its length
- drops are reported every 64 frames and summarised at teardown
The video queue depth comes from video_record_fifo_frames (8..128).
The audio queue holds 2 s at the core's rate instead of ~0.36 s at
48 kHz. With drop off, both paths block as before.
ffmpeg_pipeline_test gains a drop-mode pass that checks the surviving
frames come out in order, pixel-exact and at their own timestamps.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: make RTMP streaming presets ingest-compliant
The Twitch/YouTube/Facebook/Kick modes reused the recording presets:
CRF (unbounded VBR), the encoder's default GOP (~4 s for x264 at
60 fps), audio at whatever rate was closest to the core's and no
audio bitrate. Ingest servers want CBR H.264, a 2 s keyframe interval
and AAC at 44.1/48 kHz.
For the FLV/RTMP modes:
- CBR video at 2500/4500/6000 kbps (low/med/high), 1 s VBV buffer,
x264 nal-hrd=cbr, no B-frames
- a fixed 2 s keyframe interval: x264 scenecut=0, and keyframes are
forced on time rather than counted in frames, since pts gaps from
dropped frames or cores presenting every other tick stretch a
frame-counted GOP
- AAC 160 kbps at 48 kHz
Rate control goes through the generic AVCodecContext fields so it
carries over to other encoders. Local/custom streaming and the
recording presets are unchanged.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: optional hardware H.264 encoder with libx264 fallback
New setting video_record_hw_encoder (default on for HAVE_LAKKA_SWITCH,
off elsewhere). When set and the built-in preset would use libx264,
these encoders are tried in order and the first that opens is used:
h264_nvv4l2, h264_nvmpi, h264_v4l2m2m, h264_rkmpp, h264_nvenc,
h264_amf, h264_qsv, h264_videotoolbox, h264_mediacodec
All take system-memory frames; VAAPI is skipped because it needs a
hw_frames_ctx upload path. Input is YUV420P if the encoder takes it,
else NV12 (via swscale). x264 private options are not passed to them;
rate control/GOP come from the generic AVCodecContext fields, plus
rc=cbr for the RTMP presets. CRF presets get a bitrate derived from
0.05/0.1/0.2 bits per pixel per frame (low/med/high), floor 500 kbps.
If none open, libx264 is used as before. Custom configs are untouched.
ffmpeg_init_video is split so one encoder attempt is a self-contained
alloc/configure/open that frees its context on failure. Also sets
AVCodecContext.framerate, which some hardware rate controllers need.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: run encoder threads at lower priority in drop mode
With a CPU-bound software core, libx264's worker threads, the
swscale/AAC work on the encoder thread and the core's main thread all
compete at the same priority, so recording slows the game even when
the queues never fill.
In drop-on-full mode, run everything encoder-side at nice +10:
- the driver's encoder thread renices itself on start
- threads spawned during the video/audio avcodec_open2() (x264's pool
and lookahead) are found by diffing /proc/self/task and reniced
afterwards; lowering the main thread around the open instead isn't
reversible without CAP_SYS_NICE
The encoder then gets what the core leaves, and any shortfall shows up
as dropped frames rather than game slowdown. Linux only; skipped when
drop-on-full is off, since starving the encoder there means stalls.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: route libav* logging into RetroArch's log
FFmpeg logged to stderr through its default callback, so codec
messages never reached RetroArch's log or log file, which is what a
user can attach after a crash.
While recording, install an av_log callback that assembles lines
FFmpeg builds from several calls and forwards them as
RARCH_ERR/WARN/LOG/DBG by level, tagged [FFmpeg/lav]. A partial line
is flushed when the next piece comes from another context, so two
threads' messages are never spliced. FFmpeg's level follows the
frontend log level. The default callback is restored when the
recording is freed.
Adds verbosity_get_log_level().
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* video: BGRX readback for GPU recording (gl, vulkan)
GPU (post-shaded) recording, which hardware-rendered cores are forced
into, read every frame with read_viewport(), which converts the
32-bit readback to BGR24 on the main thread inside the frame budget.
The encoder thread then converts BGR24 to YUV again, and the frame is
queued at the viewport rounded up to powers of two.
- Add an optional video_driver_t::read_viewport_bgrx() that returns
the viewport as 32-bit B,G,R,X plus its row order. It is the last
slot, so positional driver tables leave it NULL.
- gl: desktop GL already reads back GL_BGRA, so rows are copied as-is
(RGBA is swizzled on GLES), on both the PBO and synchronous paths.
- vulkan: B8G8R8A8 swapchains copy rows as-is, RGBA ones swizzle.
- Recording uses it when the driver has it, feeding the encoder
ARGB8888: the main thread's work per frame becomes a plain copy and
the encoder thread converts once. Little-endian hosts only, since
FFEMU_PIX_ARGB8888 is a native-endian word. The threaded wrapper
keeps its own readback on the video thread.
- The encoder queue is sized to the exact viewport (a resize already
ends the recording): 1280x720 rather than 2048x1024 per frame.
The BGR24 path is unchanged for screenshots and other drivers.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* video: BGRX readback for glcore, gl1, sdl2 and sdl3; fix sdl2 readback
Extend read_viewport_bgrx() to the other Linux-capable drivers.
- glcore: the async PBO readback reads GL_BGRA on desktop GL (GLES
keeps RGBA), with the BGR24 scaler's input format to match, so
recording gets a plain row copy as on gl.
- gl1: synchronous RGBA readback, swizzled to BGRX.
- sdl3: sdl3_capture_viewport() can emit BGRX, top row first.
- sdl2: read_viewport() converted the whole window surface
(SDL_GetWindowSurface() on a window that has a renderer), copied
surface->h * pitch into a buffer sized for the viewport, top row
first where callers expect bottom row first, and leaked the
converted surface on every call, so GPU recording and screenshots
came out as garbage. Do what sdl3 does: redraw the last core frame
into the game viewport and SDL_RenderReadPixels() exactly that, as
BGRX or as flipped BGR24.
The drivers that pass OpenXR slots positionally get NULLs for them
so the new slot lands in place.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* recording: performance counters for the recording path
Register frontend performance counters for each stage of a recording,
reported at exit with perfcnt_enable, so its cost can be placed:
record_readback main thread: GPU readback
record_push_video main thread: queueing a frame for the encoder
record_push_audio audio path: queueing audio
record_scale encoder thread: colour conversion and scaling
record_encode_video encoder thread: video encode and mux
record_encode_audio encoder thread: audio resample, encode and mux
Counters are only touched with perfcnt_enable set, and each has a
single writer.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: timestamp video from the audio clock
Video pts was one tick per frame handed to the encoder, i.e. it
assumed the core delivers a frame on every retro_run(). Many don't: a
30 fps game on a 60 Hz core (Dolphin's Wind Waker, for one) only
calls the video callback for new frames, and frame skipping and
run-ahead do the same. Those recordings played their video at the
wrong speed: a 26-minute Wind Waker session produced 13 minutes of
video under 26 minutes of audio, and RetroArch's own player, which is
clocked by audio, hung once the video track ran out.
Count every audio frame the core produced, which is the core's real
elapsed time, and place each video frame at that point on the
timeline through the same pts skip dropped frames use. Frames that
arrive every other tick get pts 0, 2, 4, ... Without audio, the
one-tick-per-frame accounting is kept.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* recording: optional "Record Game Only" (no menu, OSD or menu time)
GPU recording reads the backbuffer at the end of the frame, so the
volume and other OSD messages, notification widgets, statistics,
input overlays and, with content running behind it, the menu end up
in the recording, and the menu's filler silence puts the time spent
in the menu into it too. That is what's on screen, which some users
expect, so this adds a switch rather than changing the default.
New setting video_record_game_only ("Record Game Only", default off).
It travels with the frame, like gpu_recording. When on:
- gl, glcore: the async PBO readback is issued right after the core's
image (shader chain, PQ->SDR conversion) is in the backbuffer,
before any UI is drawn. Under scRGB output the backbuffer only gets
the image at the final composite, so that path reads back at the end.
- vulkan: after the final pass, end the render pass, copy the
backbuffer to the readback staging buffer and resume with
keep_render_pass (LOAD), so the UI draws over the unchanged image.
HDR output keeps the end-of-frame readback, which needs its tonemap.
- audio_driver_menu_sample() doesn't push the menu's filler silence,
so menu time is left out, as its frames already are.
When off, behaviour is as before.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* recording: apply the content rotation to raw (non-GPU) recordings
Raw recordings encoded the core's frames as handed over, ignoring the
rotation the display applies (core-requested or the user's video
rotation), so vertical games came out sideways. GPU recordings were
unaffected since they read back the already-rotated screen.
Pass the rotation to the recorder, describe the output with width and
height swapped for quarter turns (unless --size gave one), and rotate
each frame on the encoder thread before scaling.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: scale frames smaller than the output size to fill it
ffmpeg_scale_input() clamped the scaling destination to the source
size whenever a frame was smaller than the output. That was meant for
the one pixel of padding added to reach even dimensions, but applied
to any smaller frame: frames below the core's base geometry landed in
the top-left corner of a black frame (Mupen64Plus-Next with Angrylion
and GPU recording off), and video_record_scale_factor > 1 had no
effect, since every frame is smaller than the scaled output.
Scale every frame to the output size; only a frame exactly one pixel
short of it in a dimension (the even-size padding) is copied 1:1.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: fill audio gaps when the core stops producing audio
A core that produces no audio for a while, rather than producing
silence, sent nothing to the recorder, so that time was missing from
the audio track and everything after it was out of sync (e.g.
Mupen64Plus' 64DD loading). With video timestamps taken from the
audio clock it would also stall the video timeline.
Once 4 video frames in a row arrive without any audio, owe one frame
period (sample_rate / fps, with the fraction carried) of silence per
video frame, backfilling the 4 already seen, through the existing
owed-silence mechanism. The silence goes ahead of later audio in both
drop and blocking mode.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* record_ffmpeg: drop the global 'ctx', close the output on failure
The muxer context also lived in a non-static global named 'ctx', an
exported symbol in every binary that links this driver, used by
finalize to close the output. Use handle->muxer.ctx throughout.
A recording that fails after the output was opened (an encoder that
won't open, say) never reached finalize, so its file stayed open.
ffmpeg_free() closes it.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Tpe3orhELpViSQpZcsTTjr
* recording: rotated raw aspect, quiet drop mode, lowered encoders by inheritance, frame format across a threading switch
- A raw recording of a turned picture takes the display's aspect as it
is, which is already the turned one; only an aspect worked out from
the output size follows the turn, and --size keeps its own shape
(record_raw_geometry).
- Drop mode says nothing while it records: dropped frames are counted
and the total is logged when the recording ends.
- In drop mode the encoders are opened on a thread that has lowered its
own priority, so the threads they start run lowered and no other
thread is touched.
- Only the frontend-thread perf counters are registered, as the menu
reads and resets them live.
- A GPU recording opened for 32-bit frames gets them widened from BGR24
when the readback in charge hands over BGR24 - the threaded wrapper's,
or a driver without the 32-bit one - into its own buffer.
- At the end of a recording the real audio left in the queue is encoded
ahead of the silence still owed; the gap fill counts every frame the
core presents, frame_drop_ratio or not; the output is closed whenever
it is open; an encoder that leaves the CBR request unused is named.
ffmpeg_pipeline_test checks the geometry, that drop mode drops frames
without a warning or an on-screen message, and that its encoder
threads run lowered. threaded_video's gpu record format lane records
on Vulkan unthreaded and threaded with a 32-bit recording open, and
reads every row of what it is handed.
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: LibretroAdmin <[email protected]>
The encoder waits on data, which each push notifies after writing; a
push that finds no room waits on space, which the encoder notifies
after each read, bounded so it looks at alive again. No lock is taken
on either side and no wake can fall between a check and a sleep.
deinit_thread() notifies both once alive is clear.
The lock budget holds ffmpeg_push_video, ffmpeg_push_audio and
ffmpeg_thread to none.
struct record_params carries out_dims and fb_dims as VIDEO_SCALE_PACK
words; ffmpeg scales and evens the output size in locals and stores
the result as a word, and sizes its buffers with VIDEO_SCALE_AREA.
The width/height pairs that travel as a single word all use
VIDEO_SCALE_PACK and its accessors now: the threaded wrapper's
viewport slots, the cached frame's dimensions, the output size, and
record_video_data, which carries both axes as one member. The macros
move to video_defines.h so the record drivers reach them. Clamping
applies everywhere the macro does, so an axis past 65535 saturates
rather than wrapping into a small number.
samples/gfx/threaded_video gains a size-pair round-trip lane: it
publishes at dimensions no square frame can hide, reads both axes back
through the public accessors, and checks the clamp at the top of the
range. A store and a load that disagree on which half holds which axis
fails it by name.
@available has two problems for RetroArch's range of targets:
1. It needs a clang new enough to know the syntax, so the ancient
toolchains building the legacy iOS/macOS targets cannot compile
any file that uses it.
2. It lowers to a call to __isPlatformVersionAtLeast() every time
it is evaluated, including in per-frame and per-input paths.
Introduce apple_runtime.h with apple_runtime_available(mac, ios,
tvos), a drop-in replacement that resolves the running OS version
exactly once per process and caches it in a static int; after
warm-up every check is a single load and integer compare, cheaper
than @available. Platforms the original check did not list are
passed as 0, preserving @available's semantics of returning true
on unlisted platforms.
The version is read from UIDevice systemVersion on iOS/tvOS (never
shimmed, works on any version), and on macOS from the
kern.osproductversion sysctl - which reports the real OS version
even for binaries linked against pre-11.0 SDKs, where the
NSProcessInfo APIs (and @available's own plist source) are subject
to the 10.16 compatibility shim - with an
operatingSystemVersionString fallback for pre-10.13.4 systems.
This also fixes the broken iOS 9 / iOS 6 CI builds: cocoa_common.m
used UIWindowScene.effectiveGeometry, an iOS 16 API that older SDKs
(e.g. iPhoneOS 14.2) do not declare at all, so @available could not
save compilation. That call chain is now resolved entirely at
runtime via objc_msgSend (identical cost to a compiled property
access), with the capability probe cached in a static.
All 84 live @available sites across 13 files are converted.
Behavior on every OS version is unchanged: the same paths are taken
at the same version thresholds. Swift #available sites are
untouched; Swift enforces availability at compile time and those
files only build on modern toolchains.
Existing compile-time SDK gates (e.g. around NSWorkspace
isVoiceOverEnabled and the Metal HDR blocks) are kept, since they
guard symbol declarations, not runtime dispatch; comments updated
accordingly.
Auditing the two other ffmpeg users the way the core was audited.
camera/drivers/ffmpeg.c had two things:
- ffmpeg_camera_stop() flushed the decoder and then joined the poll
thread. The poll thread is the decoder's other user - it sends
every packet it reads and receives every frame - and an
AVCodecContext takes one user at a time. So the flush ran against a
live decoding thread. The join comes first now, and the flush
after, where the context has one user again.
- 'done', the poll thread's loop condition, was a volatile bool: set
by the main thread in stop(), read by the thread every turn, with
nothing held on either side - target_buffer_lock covers the frame,
not this. volatile is not a synchronisation primitive; it stops the
compiler caching the load and orders nothing, so the thread had no
guarantee of seeing what the main thread wrote before it. An
atomic, as the ffmpeg core's own flags became for the same reason.
record/drivers/record_ffmpeg.c came out clean. Its queues are
already lock-free retro_spsc rings and 'alive' is already an atomic.
'can_sleep' carried a volatile and does not need one: every access is
under cond_lock, or - the one in init_thread() - before the thread
that reads it exists. The volatile said the opposite, that here was a
flag crossing threads without a lock, so it is gone and the comment
says what actually protects it. No behaviour change there.
The record pipeline harness passes, plain and under TSan.
The three fifos between the pushing thread (ffmpeg_push_video /
ffmpeg_push_audio, on the frontend's audio and video paths) and the
encoder thread were fifo_buffer_t under one lock, and both sides held
that lock for their whole frame copy: the push wrote a frame - up to
fb_width x fb_height x pix_size, row by row - under it, and the encoder
read one out under it. At 1080p XRGB that is an 8 MB memcpy on each
side that the other could not overlap with.
Each queue is single-producer/single-consumer, so replace them with
retro_spsc_t and drop the lock: the two copies now run concurrently.
cond/cond_lock and the can_sleep handshake are unchanged.
Ordering: the frame's rows are written before its attr, and the
encoder takes the attr as the signal that a whole frame is behind it.
The attr ring's release/acquire orders the video ring's publication
before it, so the encoder's read of the frame sees all of it - which
the old code got from the lock instead.
The push's room check asked only the attr fifo, relying on the two
being sized in step; the rings round up to powers of two
independently, so it now asks both. fifo_new() was never checked;
a ring that fails to init fails the recorder. The volatile alive
flag becomes a retro_atomic_int_t: TSan flagged the encoder loop's
read against deinit_thread()'s clear.
Verified by samples/record/ffmpeg_pipeline (next commit): 240 frames
whose pixels encode their number, pushed with the encoder draining
concurrently, decoded back in order and pixel-exact; clean under
ASan+UBSan and TSan. The same harness passes against the fifo
version, with the alive race as TSan's one finding there.
Phase 5's recording: a core delivering 5.1 was recorded as the
fold. The recorder now opens in the core's layout when the core had
one at the start of the recording and the container has a default
layout for the count - quad, 5.1 with the pair at the back, 7.1,
the layouts in the order the recorder takes frames - and every push
is brought to that layout by one function: a batch in the layout
goes as it is, a stereo batch on a 5.1 recording lands in the
fronts with the rest silent, a batch of another layout is remapped
(positions both have copied, positions only the recording has zero,
positions only the batch has folded into the fronts at the BS.775
gains, LFE dropped), a float batch narrowed once. The classic
entries, the wide entry on the threaded ring and the non-threaded
path all push through it. A stereo core records as it always did.
The FFmpeg recorder takes the container's default layout for the
count instead of stereo, and resamples a wider frame through one
instance of its float resampler per pair at one ratio, so a
recording sample rate still applies. The AVFoundation recorder
names a wider layout by its channel bitmap, since the frames are
in the bitmap's order and the MPEG 7.1 tags put the pairs the
other way about; not compiled here.
The upmix harness checks the remap's cases; the discrete harness
records a 5.1 batch and a stereo batch through the real push with
a capturing recorder opened in 5.1 and then in stereo, and finds
the core's rears in the recording's, the stereo batch in the fronts
alone, and the fold at -3 dB.
strlcpy() begins with strlen() of its source. It lives in another
translation unit, so with no LTO that scan happens at runtime even when
the source is a literal whose length the compiler already measured, and
the call itself cannot be folded away either.
strlcpy_lit() passes the length over as sizeof(). When the destination
size is also a constant -- sizeof(buf), the usual case -- nothing is
left but the stores memcpy() compiles to:
strlcpy "core_options" sizeof(buf) 7.01 ns
strlcpy_lit "core_options" sizeof(buf) 0.42 ns
strlcpy 41-char literal sizeof(buf) 7.74 ns
strlcpy_lit 41-char literal sizeof(buf) 0.71 ns
strlcpy "core_options" runtime len 7.11 ns
strlcpy_lit "core_options" runtime len 0.70 ns
The destination bound is kept. When the literal does not fit it defers
to strlcpy(), so the copy truncates as before rather than overrunning;
a form that took only the literal would have turned every one of these
sites into an overflow waiting for a small buffer. The literal is
concatenated with "" so a non-literal source is a compile error rather
than a sizeof() that silently measures a pointer.
818 sites across 104 files were converted by parsing arguments rather
than by pattern-matching text: only a three-argument call whose second
argument is a bare string literal is rewritten, so a macro that happens
to expand to a literal is left alone. Line endings are preserved, so
the CRLF files carry only their own changed lines.
test/compat/test_strl.c compares the two against each other over every
destination size from 0 past the literal's length, for literals that
are empty, single-character, path-shaped, adjacently concatenated and
escape-bearing, checking the return, the terminator and the whole
buffer so an overrun past the terminator is caught. ASan+UBSan+LSan and
TSan both 4/4. The full menu_displaylist_build_list walk over every
displaylist type is byte-identical to before the change
(md5 a2a081bcac09cdc8d72d67efd14ac40e).
ffmpeg_free() released the AVFormatContext with a bare av_free() of
the url and the struct, which leaves behind everything the context
owns: the streams avformat_new_stream() created, their codec
parameters, the metadata dictionary and the muxer's private data.
The init-time comment already assumed avformat_free_context() did the
teardown. It does now, and with it the driver's harness run leaves
LeakSanitizer with nothing to report.
encode_audio() allocated an AVFrame for every audio block and then, in
av_frame_get_buffer(), a sample buffer for it that was never used: the
frame's data pointers were immediately repointed at the handle's own
sample buffer by avcodec_fill_audio_frame(), and the whole thing was
freed after the packet loop. The frame now lives on the audio state
with its format and channel layout set once at init, and each block
only sets its sample count and pts and wraps the handle's buffer; the
dry flush sends NULL as before and no longer touches it.
The 8 MiB video and 16 KiB audio "outbuf"s are gone with it. They were
preset on the packet before every encode as if the packet had to own
its output, which the send/receive API stopped needing when this file
moved to it - avcodec_receive_packet() supplies the packet's own
buffer and av_packet_unref() releases it - and nothing ever freed
them, so every recording session leaked the pair. A harness driving
the driver through 120 video frames and 95 audio blocks shows those
8,404,992 bytes gone from the leak report and the decoded audio and
video streams frame-hash identical to before.
MSYS2 updated mingw-w64-ffmpeg to 9.0, which removes the deprecated
AVCodec.sample_fmts / AVCodec.supported_samplerates arrays and breaks
the MSYS2 CI build in record_ffmpeg.c.
record_ffmpeg: add accessors that use avcodec_get_supported_config()
where available (lavc >= 61.13.100, FFmpeg 7.1+) and fall back to the
legacy AVCodec struct members on older versions. NULL now means
unrestricted instead of being dereferenced, hardening both paths.
camera/ffmpeg: version-gate const-ness of the AVInputFormat/AVCodec
pointers; lavf 59 (FFmpeg 5.0) made that API const-correct, lavf 58
(FFmpeg 4.x, the driver's minimum) warns on const pointers.
Verified: compile matrix with production flags against FFmpeg 3.4.13,
4.4.5, 5.1.6, 6.1.2, 7.1.1, 8.1.2 and 9.0 all clean; full configure +
make against FFmpeg 9.0 builds and links; resolver logic runtime-tested
under ASan/UBSan against FFmpeg 9.0 (new path) and 6.1.2 (legacy path)
with identical results and no sanitizer findings.
When the chosen audio encoder consumes s16 and a sample-rate conversion
is required, the recorder converted the game audio s16 -> float,
resampled in float, then converted float -> s16 for the encoder. That
round-trip exists only because the shared resampler ABI is float.
Use the integer sinc resampler (the same one the main audio path uses to
avoid this exact detour) when the encoder is s16 and the output is
stereo, resampling s16 -> s16 directly. The float resampler is kept for
float encoders (whose output must be float anyway) and for the mono case
(the integer resampler is interleaved-stereo only); when no sample-rate
conversion is needed the existing s16 passthrough is unchanged. The two
resamplers are mutually exclusive, so the shared fixed_conv buffer is
reused for the integer output with no conflict.
Verified against the float path on a resampled stereo signal: identical
output frame counts and within 1 LSB (0.03 LSB RMS), i.e. audibly
identical, since both use the same sinc design. bandwidth_mod is passed
the raw ratio to match the main audio path's anti-aliasing behaviour.