Repository navigation
fix(recording): improve raw file resampling to address A/V sync issues (video) - #24490
prlanzarin wants to merge 4 commits into
Conversation
Add a shared media_utils module to record-and-playback that provides re-usable utils in EDL processing for all sources (A/V). This first implementation contains PTS utils for detecting large gaps and obtaining PTS times, which will be used in improved PTS gap handling in subsequent commits. Co-authored-by: germanocaumo <[email protected]>
Videos with large gaps were causing high memory usage during processing, this PR add gap detection and apply a resample to the parts that have gaps (using the key frame before and after gap). Co-authored-by: germanocaumo <[email protected]>
Reduce to 30s as some recordings still used more than 2GB with one minute.
WalkthroughThis pull request adds a new segmented video resampling feature to handle videos with large PTS (Presentation Timestamp) gaps. A new Sequence Diagram(s)sequenceDiagram
participant Render as Video Render<br/>Pipeline
participant MediaUtils as MediaUtils<br/>Module
participant FFprobe as ffprobe
participant Video as Video Module<br/>Resample
participant FileSystem as File System
participant EDL as EDL/Videoinfo<br/>Metadata
Render->>Render: Scan videoinfo entries
Render->>MediaUtils: has_large_pts_gaps?<br/>(filename, max_gap_ms, stream_type)
MediaUtils->>FFprobe: Execute ffprobe<br/>packet query
FFprobe-->>MediaUtils: PTS times data
MediaUtils->>MediaUtils: Parse & filter<br/>PTS values
MediaUtils->>MediaUtils: Scan for gaps<br/>exceeding threshold
MediaUtils-->>Render: Gap boundary [prev_pts, curr_pts]<br/>or nil
alt Large Gap Detected
Render->>Video: get_all_processing_segments<br/>(filename, max_gap_ms, ...)
Video->>FFprobe: Extract PTS & keyframe times
FFprobe-->>Video: Timing data
Video->>Video: Compute copy vs<br/>recode segments
Video-->>Render: Segment list
Render->>Video: resample_video_files<br/>(gap_info_map, target_dir, ...)
Video->>FileSystem: Process each segment
alt Recode segment
Video->>FileSystem: Create blank segment<br/>via ffmpeg
else Copy segment
Video->>FileSystem: Copy stable segment
end
Video->>FileSystem: Concatenate segments
Video-->>Render: Mapping: original→resampled
Render->>EDL: Update video filenames
Render->>EDL: Update videoinfo entries
end
Render->>Render: Continue render<br/>with updated metadata
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes 🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Fix all issues with AI agents
In `@record-and-playback/core/lib/recordandplayback/edl/video.rb`:
- Around line 340-362: The code updates EDL and replaces original filenames
in-place before validating resampled outputs, which can lose the original when
validation fails; change the flow to first iterate filename_update_map_gaps and
call video_info(new_filename) to validate each resampled file (collect valid
mappings and mark invalid ones in corrupt_videos), then only after validation
perform the EDL replacement and update videoinfo for mappings that passed
validation (leave original videoinfo entries untouched for failed mappings); use
the existing symbols filename_update_map_gaps, video_info, corrupt_videos,
videoinfo and edl to locate where to perform validation-first logic and to swap
filenames/videoinfo only for successful validations.
- Around line 532-606: The resample_video_files implementation currently always
generates blank recode parts as VP8@25fps which will break concat when the
original stream codec or framerate differs; update resample_video_files to read
the original codec and framerate from videoinfo_h[original_filename] and use
those values when building the recode cmd_part (replace hardcoded
['-c:v','libvpx','-crf','30','-b:v','1M'] and framerate=25 with parameters
matching the source codec and r/framerate), or alternatively choose a single
target codec/framerate and ensure both recode and copy paths re-encode to that
target (i.e. stop using '-c copy' in the copy branch and re-encode when
codecs/framerates differ); modify where action == :recode and where action ==
:copy (processing_segments loop, cmd_part construction) to enforce matching
codec/framerate for all parts using videoinfo_h lookup.
🧹 Nitpick comments (1)
record-and-playback/core/lib/recordandplayback/edl/video.rb (1)
449-466: Unused parameter inget_all_processing_segments.
video_info_entryisn’t used; consider removing it or renaming to_video_info_entryfor clarity.
| if filename_update_map_gaps.any? | ||
| BigBlueButton.logger.info "Updating EDL and video information for segment-resampled videos." | ||
| edl.each do |entry| | ||
| entry[:areas].each_value do |videos_in_area| | ||
| videos_in_area.each do |video_data| | ||
| if filename_update_map_gaps.key?(video_data[:filename]) | ||
| video_data[:filename] = filename_update_map_gaps[video_data[:filename]] | ||
| end | ||
| end | ||
| end | ||
| end | ||
|
|
||
| filename_update_map_gaps.each do |original_filename, new_filename| | ||
| info = video_info(new_filename) | ||
| if !info[:video] || info[:duration] == 0 | ||
| BigBlueButton.logger.error "Resampled video file #{new_filename} is corrupt or invalid. Original: #{original_filename}. This may cause issues." | ||
| corrupt_videos << new_filename # Mark the new file as corrupt | ||
| videoinfo.delete(original_filename) if videoinfo.key?(original_filename) | ||
| else | ||
| BigBlueButton.logger.debug "Successfully resampled and got info for #{new_filename}. Duration: #{info[:duration]}" | ||
| videoinfo[new_filename] = info | ||
| videoinfo.delete(original_filename) if videoinfo.key?(original_filename) | ||
| end |
There was a problem hiding this comment.
Avoid dropping the original video when a resampled output fails validation.
EDL gets rewritten before the new file is validated; if the resampled file is invalid, the original is effectively lost and the video is removed. Consider validating first, then swapping.
🛠️ Suggested fix (validate first, then swap)
- if filename_update_map_gaps.any?
- BigBlueButton.logger.info "Updating EDL and video information for segment-resampled videos."
- edl.each do |entry|
- entry[:areas].each_value do |videos_in_area|
- videos_in_area.each do |video_data|
- if filename_update_map_gaps.key?(video_data[:filename])
- video_data[:filename] = filename_update_map_gaps[video_data[:filename]]
- end
- end
- end
- end
-
- filename_update_map_gaps.each do |original_filename, new_filename|
- info = video_info(new_filename)
- if !info[:video] || info[:duration] == 0
- BigBlueButton.logger.error "Resampled video file #{new_filename} is corrupt or invalid. Original: #{original_filename}. This may cause issues."
- corrupt_videos << new_filename # Mark the new file as corrupt
- videoinfo.delete(original_filename) if videoinfo.key?(original_filename)
- else
- BigBlueButton.logger.debug "Successfully resampled and got info for #{new_filename}. Duration: #{info[:duration]}"
- videoinfo[new_filename] = info
- videoinfo.delete(original_filename) if videoinfo.key?(original_filename)
- end
- end
- end
+ if filename_update_map_gaps.any?
+ BigBlueButton.logger.info "Updating EDL and video information for segment-resampled videos."
+ filename_update_map_gaps.each do |original_filename, new_filename|
+ info = video_info(new_filename)
+ if !info[:video] || info[:duration] == 0
+ BigBlueButton.logger.error "Resampled video file #{new_filename} is corrupt or invalid. Keeping original: #{original_filename}."
+ corrupt_videos << new_filename
+ next
+ end
+
+ edl.each do |entry|
+ entry[:areas].each_value do |videos_in_area|
+ videos_in_area.each do |video_data|
+ video_data[:filename] = new_filename if video_data[:filename] == original_filename
+ end
+ end
+ end
+
+ BigBlueButton.logger.debug "Successfully resampled and got info for #{new_filename}. Duration: #{info[:duration]}"
+ videoinfo[new_filename] = info
+ videoinfo.delete(original_filename) if videoinfo.key?(original_filename)
+ end
+ end📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if filename_update_map_gaps.any? | |
| BigBlueButton.logger.info "Updating EDL and video information for segment-resampled videos." | |
| edl.each do |entry| | |
| entry[:areas].each_value do |videos_in_area| | |
| videos_in_area.each do |video_data| | |
| if filename_update_map_gaps.key?(video_data[:filename]) | |
| video_data[:filename] = filename_update_map_gaps[video_data[:filename]] | |
| end | |
| end | |
| end | |
| end | |
| filename_update_map_gaps.each do |original_filename, new_filename| | |
| info = video_info(new_filename) | |
| if !info[:video] || info[:duration] == 0 | |
| BigBlueButton.logger.error "Resampled video file #{new_filename} is corrupt or invalid. Original: #{original_filename}. This may cause issues." | |
| corrupt_videos << new_filename # Mark the new file as corrupt | |
| videoinfo.delete(original_filename) if videoinfo.key?(original_filename) | |
| else | |
| BigBlueButton.logger.debug "Successfully resampled and got info for #{new_filename}. Duration: #{info[:duration]}" | |
| videoinfo[new_filename] = info | |
| videoinfo.delete(original_filename) if videoinfo.key?(original_filename) | |
| end | |
| if filename_update_map_gaps.any? | |
| BigBlueButton.logger.info "Updating EDL and video information for segment-resampled videos." | |
| filename_update_map_gaps.each do |original_filename, new_filename| | |
| info = video_info(new_filename) | |
| if !info[:video] || info[:duration] == 0 | |
| BigBlueButton.logger.error "Resampled video file #{new_filename} is corrupt or invalid. Keeping original: #{original_filename}." | |
| corrupt_videos << new_filename | |
| next | |
| end | |
| edl.each do |entry| | |
| entry[:areas].each_value do |videos_in_area| | |
| videos_in_area.each do |video_data| | |
| video_data[:filename] = new_filename if video_data[:filename] == original_filename | |
| end | |
| end | |
| end | |
| BigBlueButton.logger.debug "Successfully resampled and got info for #{new_filename}. Duration: #{info[:duration]}" | |
| videoinfo[new_filename] = info | |
| videoinfo.delete(original_filename) if videoinfo.key?(original_filename) | |
| end | |
| end |
🧰 Tools
🪛 RuboCop (1.82.1)
[convention] 341-341: Prefer single-quoted strings when you don't need string interpolation or special symbols.
(Style/StringLiterals)
[convention] 355-355: Line is too long. [159/128]
(Layout/LineLength)
[convention] 357-357: Move videoinfo.delete(original_filename) if videoinfo.key?(original_filename) out of the conditional.
(Style/IdenticalConditionalBranches)
[convention] 359-359: Line is too long. [130/128]
(Layout/LineLength)
[convention] 361-361: Move videoinfo.delete(original_filename) if videoinfo.key?(original_filename) out of the conditional.
(Style/IdenticalConditionalBranches)
🤖 Prompt for AI Agents
In `@record-and-playback/core/lib/recordandplayback/edl/video.rb` around lines 340
- 362, The code updates EDL and replaces original filenames in-place before
validating resampled outputs, which can lose the original when validation fails;
change the flow to first iterate filename_update_map_gaps and call
video_info(new_filename) to validate each resampled file (collect valid mappings
and mark invalid ones in corrupt_videos), then only after validation perform the
EDL replacement and update videoinfo for mappings that passed validation (leave
original videoinfo entries untouched for failed mappings); use the existing
symbols filename_update_map_gaps, video_info, corrupt_videos, videoinfo and edl
to locate where to perform validation-first logic and to swap
filenames/videoinfo only for successful validations.
| # Resamples video files by identifying all large PTS gaps, cutting at surrounding keyframes, | ||
| # re-encoding gappy segments (by replacing with blank video), and stream-copying stable segments. | ||
| def self.resample_video_files(files_and_gap_info_map, target_directory, videoinfo_h) | ||
| filename_update_map = {} | ||
| intermediate_format = 'webm' | ||
|
|
||
| files_and_gap_info_map.each do |original_filename, _first_gap_info_ignored| # First gap info is ignored, we find all gaps | ||
| original_basename = File.basename(original_filename, '.*') | ||
| parts_dir = File.join(target_directory, "#{original_basename}_parts") | ||
| FileUtils.mkdir_p(parts_dir) | ||
|
|
||
| original_video_codec_info = videoinfo_h[original_filename]&.dig(:video, :codec_name) | ||
| unless original_video_codec_info | ||
| BigBlueButton.logger.error "Could not determine original video codec for #{original_filename}. Skipping segmented resampling." | ||
| FileUtils.remove_entry_secure(parts_dir) if Dir.exist?(parts_dir) | ||
| next | ||
| end | ||
| original_total_duration_s = videoinfo_h[original_filename][:duration] / 1000.0 | ||
|
|
||
| output_ext = 'webm' | ||
| final_resampled_filename = File.join(target_directory, "#{original_basename}_segmented_resampled.#{output_ext}") | ||
|
|
||
| BigBlueButton.logger.info "Segmented resampling for '#{original_filename}' (codec: #{original_video_codec_info}, duration: #{original_total_duration_s.round(3)}s). Output: '#{final_resampled_filename}'" | ||
|
|
||
| processing_segments = get_all_processing_segments(original_filename, MAX_GAP_FOR_RESAMPLE_MS, original_total_duration_s, videoinfo_h[original_filename]) | ||
|
|
||
| if processing_segments.empty? | ||
| BigBlueButton.logger.warn "No processing segments generated for '#{original_filename}'. Skipping segmented resampling for this file." | ||
| FileUtils.remove_entry_secure(parts_dir) if Dir.exist?(parts_dir) | ||
| next | ||
| end | ||
|
|
||
| # If only one copy segment covering the whole video, it's like a remux. | ||
| # This can happen if no significant gaps are found or keyframes don't allow isolation. | ||
| if processing_segments.length == 1 && processing_segments.first[:action] == :copy && processing_segments.first[:start_pts] < 0.01 && (processing_segments.first[:end_pts] - original_total_duration_s).abs < 0.01 | ||
| BigBlueButton.logger.info "No gaps requiring re-encoding found for '#{original_filename}' based on keyframes. Will perform a simple copy/remux." | ||
| # This will be handled by the loop below creating one copy part. | ||
| end | ||
|
|
||
| parts_to_concat = [] | ||
| overall_success = true | ||
|
|
||
| processing_segments.each_with_index do |segment, index| | ||
| part_start_pts = segment[:start_pts] | ||
| part_end_pts = segment[:end_pts] | ||
| action = segment[:action] | ||
| part_duration = part_end_pts - part_start_pts | ||
|
|
||
| if part_duration <= 0.01 # Skip negligible/zero duration segments | ||
| BigBlueButton.logger.debug "Skipping segment ##{index+1} for '#{original_filename}' due to zero/negligible duration (#{part_duration.round(3)}s)." | ||
| next | ||
| end | ||
|
|
||
| part_path = File.join(parts_dir, "#{original_basename}_part#{index + 1}.#{intermediate_format}") | ||
|
|
||
| if action == :recode | ||
| # Generate a blank video segment for the duration of the gap. | ||
| original_info = videoinfo_h[original_filename] | ||
| width = original_info[:width] | ||
| height = original_info[:height] | ||
| framerate = 25 | ||
|
|
||
| color_source_spec = "color=c=#{self.background_color}:s=#{width}x#{height}:r=#{framerate}" | ||
|
|
||
| cmd_part = [*FFMPEG, '-y', '-f', 'lavfi', '-i', color_source_spec, '-t', part_duration.to_s] | ||
| cmd_part += ['-an'] # No audio for the blank video segment | ||
| # Using typical VP8 parameters. | ||
| cmd_part += ['-c:v', 'libvpx', '-crf', '30', '-b:v', '1M'] | ||
| BigBlueButton.logger.info "Creating Part ##{index + 1} (BLANK VIDEO from #{part_start_pts.round(3)}s to #{part_end_pts.round(3)}s, duration #{part_duration.round(3)}s) for '#{original_filename}'" | ||
| else # :copy | ||
| # Use -t with part_duration for copied segments. | ||
| # Add -avoid_negative_ts make_zero for robust timestamp handling. | ||
| cmd_part = [*FFMPEG, '-y', '-ss', part_start_pts.to_s, '-i', original_filename, '-t', part_duration.to_s] | ||
| cmd_part += ['-c', 'copy', '-avoid_negative_ts', 'make_zero', '-reset_timestamps', '1'] | ||
| BigBlueButton.logger.info "Creating Part ##{index + 1} (COPY from #{part_start_pts.round(3)}s, duration #{part_duration.round(3)}s) for '#{original_filename}'" |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
wc -l record-and-playback/core/lib/recordandplayback/edl/video.rbRepository: bigbluebutton/bigbluebutton
Length of output: 135
🏁 Script executed:
sed -n '532,650p' record-and-playback/core/lib/recordandplayback/edl/video.rbRepository: bigbluebutton/bigbluebutton
Length of output: 7219
🏁 Script executed:
# Check how the parts are concatenated after creation
rg -A 30 'parts_to_concat' record-and-playback/core/lib/recordandplayback/edl/video.rbRepository: bigbluebutton/bigbluebutton
Length of output: 4530
🏁 Script executed:
# Look for concat_demuxer or ffmpeg concat protocol usage
rg -B 5 -A 15 'concat:' record-and-playback/core/lib/recordandplayback/edl/video.rbRepository: bigbluebutton/bigbluebutton
Length of output: 53
🏁 Script executed:
# Check the structure of videoinfo_h to understand what data is available
rg -B 10 'videoinfo_h' record-and-playback/core/lib/recordandplayback/edl/video.rb | head -100Repository: bigbluebutton/bigbluebutton
Length of output: 2688
Concatenation will fail when source codec differs from VP8 or framerate differs from 25fps.
When recode segments are always VP8 @ 25fps and copy segments preserve the source codec/framerate, the ffmpeg concat demuxer with -c copy cannot stream-copy incompatible streams. Specifically:
- If source is VP9 or H.264, concat will fail because you're mixing VP8 (recode parts) with source codec (copy parts)
- Framerate mismatch between blank segments (25fps) and source segments (23.976fps, 30fps, etc.) causes timing drift
Re-encode recode segments to match the source codec and framerate, or re-encode all segments consistently to a target codec/framerate.
Suggested approach
Detect source codec early and use it for recode segments:
filename_update_map = {}
- intermediate_format = 'webm'
files_and_gap_info_map.each do |original_filename, _first_gap_info_ignored|
original_basename = File.basename(original_filename, '.*')
parts_dir = File.join(target_directory, "#{original_basename}_parts")
FileUtils.mkdir_p(parts_dir)
original_video_codec_info = videoinfo_h[original_filename]&.dig(:video, :codec_name)
unless original_video_codec_info
BigBlueButton.logger.error "Could not determine original video codec for #{original_filename}. Skipping segmented resampling."
FileUtils.remove_entry_secure(parts_dir) if Dir.exist?(parts_dir)
next
end
original_total_duration_s = videoinfo_h[original_filename][:duration] / 1000.0
- output_ext = 'webm'
+ # Select encoder and format based on source codec
+ encoder, intermediate_format, output_ext =
+ case original_video_codec_info
+ when 'vp8' then ['libvpx', 'webm', 'webm']
+ when 'vp9' then ['libvpx-vp9', 'webm', 'webm']
+ when 'h264' then ['libx264', 'mp4', 'mp4']
+ else
+ BigBlueButton.logger.error "Unsupported codec #{original_video_codec_info} for segmented resampling; skipping."
+ FileUtils.remove_entry_secure(parts_dir) if Dir.exist?(parts_dir)
+ next
+ endFor framerate, extract and use source framerate in recode segments:
if action == :recode
original_info = videoinfo_h[original_filename]
width = original_info[:width]
height = original_info[:height]
- framerate = 25
+ framerate = begin
+ rate = original_info.dig(:video, :r_frame_rate)
+ rate && rate != '0/0' ? rate.to_r.to_f : 25
+ rescue StandardError
+ 25
+ end
color_source_spec = "color=c=#{self.background_color}:s=#{width}x#{height}:r=#{framerate}"
cmd_part = [*FFMPEG, '-y', '-f', 'lavfi', '-i', color_source_spec, '-t', part_duration.to_s]
cmd_part += ['-an']
- cmd_part += ['-c:v', 'libvpx', '-crf', '30', '-b:v', '1M']
+ cmd_part += ['-c:v', encoder, '-crf', '30', '-b:v', '1M']🧰 Tools
🪛 RuboCop (1.82.1)
[convention] 538-538: Line is too long. [129/128]
(Layout/LineLength)
[convention] 545-545: Line is too long. [138/128]
(Layout/LineLength)
[convention] 553-553: Trailing whitespace detected.
(Layout/TrailingWhitespace)
[convention] 554-554: Line is too long. [212/128]
(Layout/LineLength)
[convention] 556-556: Line is too long. [162/128]
(Layout/LineLength)
[convention] 559-559: Line is too long. [145/128]
(Layout/LineLength)
[convention] 563-563: Trailing whitespace detected.
(Layout/TrailingWhitespace)
[convention] 566-566: Line is too long. [219/128]
(Layout/LineLength)
[convention] 567-567: Use 2 (not 3) spaces for indentation.
(Layout/IndentationWidth)
[convention] 567-567: Line is too long. [157/128]
(Layout/LineLength)
[convention] 568-568: Incorrect indentation detected (column 13 instead of 12).
(Layout/CommentIndentation)
[convention] 581-581: Surrounding space missing for operator +.
(Layout/SpaceAroundOperators)
[convention] 581-581: Line is too long. [160/128]
(Layout/LineLength)
[convention] 586-586: Trailing whitespace detected.
(Layout/TrailingWhitespace)
[convention] 592-592: Trailing whitespace detected.
(Layout/TrailingWhitespace)
[convention] 594-594: Redundant self detected.
(Style/RedundantSelf)
[convention] 599-599: Trailing whitespace detected.
(Layout/TrailingWhitespace)
[convention] 600-600: Line is too long. [209/128]
(Layout/LineLength)
[convention] 606-606: Line is too long. [173/128]
(Layout/LineLength)
🤖 Prompt for AI Agents
In `@record-and-playback/core/lib/recordandplayback/edl/video.rb` around lines 532
- 606, The resample_video_files implementation currently always generates blank
recode parts as VP8@25fps which will break concat when the original stream codec
or framerate differs; update resample_video_files to read the original codec and
framerate from videoinfo_h[original_filename] and use those values when building
the recode cmd_part (replace hardcoded ['-c:v','libvpx','-crf','30','-b:v','1M']
and framerate=25 with parameters matching the source codec and r/framerate), or
alternatively choose a single target codec/framerate and ensure both recode and
copy paths re-encode to that target (i.e. stop using '-c copy' in the copy
branch and re-encode when codecs/framerates differ); modify where action ==
:recode and where action == :copy (processing_segments loop, cmd_part
construction) to enforce matching codec/framerate for all parts using
videoinfo_h lookup.
Automated tests Summary✅ All the CI tests have passed! |
|
This pull request has conflicts ☹ |
|
The problem with high memory usage in ffmpeg when processing large video gaps has been fixed in newer ffmpeg versions. I think the ffmpeg version in Ubuntu 24.04 is ok. The existing code should already be handling filling in gaps correctly (keeping audio/video sync), using the features of the I would still be interested in adding code which stops displaying a webcam during a long gap in order to avoid showing a "frozen" camera for a long time, and that would also avoid the memory problem with old ffmpeg versions as a side-effect. |



What does this PR do?
This is the video variant of #24481, which will need to be rebased once #24483 is merged.
Raw audio and/or video files with significant PTS gaps may cause noticeable A/V desynchronization or just overall desync compared to the original wall-clock time of raw files.
For video, this affects any of the SFU-based bridges (mediasoup/LiveKit) and all available recorders (Kurento/bbb-webrtc-recorder).
While we do have some resampling code in record-and-playback, it is not sufficient to address large enough gaps. Current behavior either compresses gaps and rewrites PTS to be monotonically increasing (causes overall desync) or do not do any resampling at all (cameras, A/V desync).
This pull request introduces various changes to the resampling of raw video files in record-and-playback so that the aforementioned issues are addressed:
Add a shared media_utils module to record-and-playback that provides
re-usable utils in EDL processing for all sources (A/V).
this PR add gap detection and apply a resample to the parts that have
gaps (using the key frame before and after gap).
Closes Issue(s)
None