Skip to content

fix(recording): improve raw file resampling to address A/V sync issues (audio) - #24481

Closed
prlanzarin wants to merge 9 commits into
bigbluebutton:v3.0.x-releasefrom
prlanzarin:u30/fix/port-resample-rap-nacelle
Closed

prlanzarin wants to merge 9 commits into
bigbluebutton:v3.0.x-releasefrom
prlanzarin:u30/fix/port-resample-rap-nacelle

Conversation

@prlanzarin

@prlanzarin prlanzarin commented Jan 16, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

This is the audio variant of #24490.

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 audio, the issue is more prominent in LiveKit where recordings are muxed without encoding - whereas FreeSWITCH encodes + muxes recordings which allows for PTS gaps to be filled with silence at capture time.

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 audio files in record-and-playback so that the aforementioned issues are addressed:

Closes Issue(s)

None

@prlanzarin prlanzarin added this to the Release 3.0 milestone Jan 16, 2026
@coderabbitai

coderabbitai Bot commented Jan 16, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request introduces audio resampling functionality triggered by PTS (presentation timestamp) gap detection. A new MediaUtils module provides methods to detect large timing gaps in audio files using ffprobe. The existing Audio module is enhanced with resampling and segment processing methods that identify audio segments with problematic gaps and resample them to produce new OGG files. The render flow integrates gap detection, conditional resampling, and updates to EDL and audioinfo data structures to reference resampled files. Corrupt audio entries are also removed from both EDL and audioinfo during processing.

Sequence Diagram

sequenceDiagram
    participant Render as Render Process
    participant MediaUtils as MediaUtils
    participant Audio as Audio Module
    participant FileSystem as File System
    participant EDL as EDL/Audioinfo

    Render->>MediaUtils: has_large_pts_gaps?(filename, max_gap_ms)
    MediaUtils->>MediaUtils: get_packet_pts_times(filename)
    MediaUtils->>MediaUtils: Scan for gaps > threshold
    MediaUtils-->>Render: Gap pair or nil

    alt Large Gap Detected
        Render->>Audio: get_all_processing_segments(filename, max_gap_ms, duration)
        Audio-->>Render: Segments (COPY vs RECODE)
        
        Render->>Audio: resample_audio_files(filenames, output_dir)
        Audio->>FileSystem: Generate new OGG files (segmented resampling)
        FileSystem-->>Audio: New filenames map
        Audio-->>Render: original → new filename mapping
        
        Render->>EDL: Update with new filenames
        Render->>FileSystem: Delete old audio files
        Render->>EDL: Remove corrupt entries from audioinfo
    else No Large Gap
        Render->>Audio: Process normally
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title directly addresses the main change: improving audio resampling to fix A/V sync issues caused by PTS gaps, which aligns with the primary focus of this PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description check ✅ Passed The pull request description is directly related to the changeset, explaining the purpose, motivation, and implementation details of audio resampling improvements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@record-and-playback/core/lib/recordandplayback/edl/video.rb`:
- Around line 532-606: resample_video_files currently hardcodes
intermediate_format = 'webm' and uses libvpx for blank segments regardless of
original_video_codec_info, causing stream-copy failures for H.264 and other
codecs; update resample_video_files to inspect original_video_codec_info and
choose a compatible intermediate_format and blank-video codec/params (e.g., use
'webm' + libvpx for vp8/vp9, use 'mkv' + libx264 for h264, and a safe fallback
like 'mp4'+'libx264' or always re-encode copy segments when codec/container
mismatch), ensure the chosen format is used when building part_path and when
assembling cmd_part for both :recode and :copy actions, and fallback to
re-encoding copy segments (not -c copy) if you cannot guarantee container/codec
compatibility; reference the variables original_video_codec_info,
intermediate_format, part_path, cmd_part, and processing_segments to implement
the conditional selection and fallback.
- Around line 333-363: The current flow updates EDL filenames immediately after
calling resample_video_files, which can delete originals from videoinfo even if
the resampled file is invalid; instead, call video_info on each new filename
returned by resample_video_files first, build a filtered filename_update_map
containing only successfully validated resamples (info[:video] present and
info[:duration] > 0), add failures to corrupt_videos and do NOT delete the
original from videoinfo for failed resamples, then only iterate over edl and
replace video_data[:filename] using the filtered map and update videoinfo by
adding validated new entries and deleting originals only for those validated
mappings.
🧹 Nitpick comments (2)
record-and-playback/core/lib/recordandplayback/edl/video.rb (1)

449-456: Unused video_info_entry parameter.

video_info_entry isn’t used; removing it (or prefixing with _) reduces confusion and avoids misleading callers.

♻️ Suggested cleanup
-def self.get_all_processing_segments(filename, max_gap_ms, video_total_duration_s, video_info_entry)
+def self.get_all_processing_segments(filename, max_gap_ms, video_total_duration_s)
...
-          processing_segments = get_all_processing_segments(original_filename, MAX_GAP_FOR_RESAMPLE_MS, original_total_duration_s, videoinfo_h[original_filename])
+          processing_segments = get_all_processing_segments(original_filename, MAX_GAP_FOR_RESAMPLE_MS, original_total_duration_s)

Also applies to: 556-556

record-and-playback/core/lib/recordandplayback/edl/audio.rb (1)

304-339: Keep standard resampling options consistent.

The non-segmented branch only sets -acodec, so quality/container flags differ from the rest of the pipeline. Reusing FFMPEG_WF_ARGS keeps output consistent.

♻️ Suggested tweak
-             resample_cmd = [*FFMPEG, '-i', original_filename,
-                             '-vn', '-acodec', FFMPEG_WF_CODEC, 
-                             '-af', 'aresample=async=1000', output_filename_ogg]
+             resample_cmd = [*FFMPEG, '-i', original_filename,
+                             '-vn', '-af', 'aresample=async=1000',
+                             *FFMPEG_WF_ARGS, output_filename_ogg]
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 60ef3c1 and 852880b.

📒 Files selected for processing (3)
  • record-and-playback/core/lib/recordandplayback/edl/audio.rb
  • record-and-playback/core/lib/recordandplayback/edl/media_utils.rb
  • record-and-playback/core/lib/recordandplayback/edl/video.rb
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-09-11T20:24:01.217Z
Learnt from: kepstin
Repo: bigbluebutton/bigbluebutton PR: 23887
File: record-and-playback/video/playback/video/index.html.erb:27-29
Timestamp: 2025-09-11T20:24:01.217Z
Learning: In BigBlueButton's video recording processing pipeline, YAML configuration data (including format hashes) has its keys converted to symbols using deep_symbolize_keys! in the process/video.rb script, so templates should access format data using symbol keys like format[:extension] and format[:mimetype] rather than string keys.

Applied to files:

  • record-and-playback/core/lib/recordandplayback/edl/video.rb
📚 Learning: 2025-09-11T20:24:01.217Z
Learnt from: kepstin
Repo: bigbluebutton/bigbluebutton PR: 23887
File: record-and-playback/video/playback/video/index.html.erb:27-29
Timestamp: 2025-09-11T20:24:01.217Z
Learning: In BigBlueButton's video recording processing pipeline, format hashes loaded from YAML configuration are converted to use symbol keys via format.symbolize_keys! in the process/video.rb script before being passed to templates, so templates should access format data using symbol keys like format[:extension] and format[:mimetype] rather than string keys.

Applied to files:

  • record-and-playback/core/lib/recordandplayback/edl/video.rb
🧬 Code graph analysis (2)
record-and-playback/core/lib/recordandplayback/edl/audio.rb (2)
record-and-playback/core/lib/recordandplayback/edl/video.rb (1)
  • get_all_processing_segments (451-530)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (2)
  • has_large_pts_gaps? (66-88)
  • get_packet_pts_times (29-61)
record-and-playback/core/lib/recordandplayback/edl/video.rb (2)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (1)
  • has_large_pts_gaps? (66-88)
record-and-playback/core/lib/recordandplayback/edl/audio.rb (1)
  • get_all_processing_segments (410-465)
🪛 RuboCop (1.82.1)
record-and-playback/core/lib/recordandplayback/edl/audio.rb

[convention] 124-124: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 129-129: Line is too long. [210/128]

(Layout/LineLength)


[convention] 137-137: Line is too long. [147/128]

(Layout/LineLength)


[convention] 142-142: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 144-144: Use next to skip iteration.

(Style/Next)


[convention] 144-150: Use safe navigation (&.) instead of checking if an object exists before calling the method.

(Style/SafeNavigation)


[convention] 146-146: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.

(Style/IfUnlessModifier)


[convention] 154-154: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 156-156: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 161-161: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 171-171: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 324-324: Line is too long. [161/128]

(Layout/LineLength)


[convention] 329-329: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 329-329: Line is too long. [141/128]

(Layout/LineLength)


[convention] 331-331: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 332-332: Put a comma after the last item of a multiline array.

(Style/TrailingCommaInArrayLiteral)


[convention] 353-353: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.

(Style/IfUnlessModifier)


[convention] 363-363: Line is too long. [168/128]

(Layout/LineLength)


[convention] 368-368: Line is too long. [166/128]

(Layout/LineLength)


[convention] 374-374: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 376-376: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 377-377: Line is too long. [129/128]

(Layout/LineLength)


[convention] 379-379: Line is too long. [137/128]

(Layout/LineLength)


[convention] 387-387: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 387-387: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 391-391: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 393-393: Put a comma after the last item of a multiline array.

(Style/TrailingCommaInArrayLiteral)


[convention] 394-394: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 397-397: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 399-399: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 402-402: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 404-404: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 447-447: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 459-459: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 460-460: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.

(Style/IfUnlessModifier)


[convention] 461-461: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)

record-and-playback/core/lib/recordandplayback/edl/media_utils.rb

[convention] 1-1: Unnecessary utf-8 encoding comment.

(Style/Encoding)


[convention] 1-1: Missing frozen string literal comment.

(Style/FrozenStringLiteralComment)


[convention] 32-32: Put a comma after the last item of a multiline array.

(Style/TrailingCommaInArrayLiteral)


[convention] 34-34: Line is too long. [169/128]

(Layout/LineLength)


[convention] 35-35: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 41-41: Add empty line after guard clause.

(Layout/EmptyLineAfterGuardClause)


[convention] 41-41: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 45-45: Line is too long. [161/128]

(Layout/LineLength)


[convention] 48-48: Prefer $CHILD_STATUS from the stdlib 'English' module (don't forget to require it) over $?.

(Style/SpecialGlobalVars)


[convention] 52-52: Line is too long. [167/128]

(Layout/LineLength)


[convention] 55-55: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 56-56: Redundant return detected.

(Style/RedundantReturn)


[convention] 58-58: Line is too long. [134/128]

(Layout/LineLength)


[convention] 68-68: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 73-73: Line is too long. [181/128]

(Layout/LineLength)


[convention] 80-80: Line is too long. [225/128]

(Layout/LineLength)


[convention] 85-85: Trailing whitespace detected.

(Layout/TrailingWhitespace)

record-and-playback/core/lib/recordandplayback/edl/video.rb

[convention] 324-324: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 324-324: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 328-328: Line is too long. [208/128]

(Layout/LineLength)


[convention] 334-334: Line is too long. [140/128]

(Layout/LineLength)


[convention] 335-335: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 337-337: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[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)


[warning] 451-451: Unused method argument - video_info_entry. If it's necessary, use _ or _video_info_entry as an argument name to indicate that it won't be used. If it's unnecessary, remove it.

(Lint/UnusedMethodArgument)


[convention] 453-453: Modifier form of if makes the line too long.

(Style/IfUnlessModifier)


[convention] 453-453: Line is too long. [146/128]

(Layout/LineLength)


[convention] 464-464: Modifier form of unless makes the line too long.

(Style/IfUnlessModifier)


[convention] 464-464: Line is too long. [136/128]

(Layout/LineLength)


[convention] 465-465: Modifier form of unless makes the line too long.

(Style/IfUnlessModifier)


[convention] 465-465: Line is too long. [173/128]

(Layout/LineLength)


[convention] 477-477: Line is too long. [176/128]

(Layout/LineLength)


[convention] 478-478: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 480-480: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 487-487: Line is too long. [168/128]

(Layout/LineLength)


[convention] 489-489: Line is too long. [217/128]

(Layout/LineLength)


[convention] 500-500: Line is too long. [162/128]

(Layout/LineLength)


[convention] 506-506: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 520-520: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 522-522: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 525-525: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)


[convention] 525-525: Line is too long. [129/128]

(Layout/LineLength)


[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)


[convention] 615-615: Line is too long. [170/128]

(Layout/LineLength)


[convention] 622-622: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 629-629: Put a comma after the last item of a multiline array.

(Style/TrailingCommaInArrayLiteral)


[convention] 637-637: Line is too long. [139/128]

(Layout/LineLength)


[convention] 640-640: Line is too long. [188/128]

(Layout/LineLength)


[convention] 644-644: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 931-931: Missing space after #.

(Layout/LeadingCommentSpace)


[convention] 1114-1114: Put a comma after the last item of a multiline array.

(Style/TrailingCommaInArrayLiteral)


[convention] 1116-1116: Line is too long. [136/128]

(Layout/LineLength)


[convention] 1120-1120: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 1124-1124: Use safe navigation (&.) instead of checking if an object exists before calling the method.

(Style/SafeNavigation)


[convention] 1126-1126: Add empty line after guard clause.

(Layout/EmptyLineAfterGuardClause)


[convention] 1132-1132: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 1133-1133: Line is too long. [139/128]

(Layout/LineLength)


[convention] 1138-1138: Line is too long. [148/128]

(Layout/LineLength)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-package (bbb-html5)
  • GitHub Check: build-package (bbb-playback-record)
🔇 Additional comments (6)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (2)

26-61: Robust PTS extraction flow.

Parsing/error handling looks solid, and the nil fallback keeps callers safe. Please sanity-check against a couple of representative ffprobe CSV outputs to confirm the format stays consistent.


63-88: Gap detection logic is clear.

Returning the first gap boundary should make downstream diagnostics straightforward.

record-and-playback/core/lib/recordandplayback/edl/video.rb (1)

1109-1137: Packet/keyframe extraction is well structured.

Clear parsing with graceful failure paths. Please verify against representative ffprobe JSON output for large files.

record-and-playback/core/lib/recordandplayback/edl/audio.rb (3)

102-115: Nice sync between EDL and audioinfo.

Removing corrupt audio entries from audioinfo while pruning the EDL avoids stale metadata during segment processing.


120-173: Gap-driven resampling integration looks solid.

The flow cleanly detects large PTS gaps, resamples, and updates EDL/audioinfo. Please validate on a recording with a known large gap to ensure the swap and metadata refresh behave as expected.


410-465: Segment construction logic is straightforward.

Merging recode intervals and emitting copy/recode segments reads clean and defensive.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines +333 to +363
if videos_to_resample_due_to_gaps.any?
BigBlueButton.logger.info "Resampling #{videos_to_resample_due_to_gaps.length} video(s) with large PTS gaps (segmented approach)."
resampled_videos_dir = File.join(File.dirname(output_basename), "resampled_videos_segmented")
FileUtils.mkdir_p(resampled_videos_dir)

filename_update_map_gaps = resample_video_files(videos_to_resample_due_to_gaps, resampled_videos_dir, videoinfo)

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# First, let's see the full context of the code snippet and surrounding logic
cd record-and-playback/core/lib/recordandplayback/edl
ls -la video.rb 2>/dev/null || echo "File not found in expected location"

Repository: bigbluebutton/bigbluebutton

Length of output: 129


🏁 Script executed:

# Find the video.rb file
find . -name "video.rb" -type f 2>/dev/null | head -5

Repository: bigbluebutton/bigbluebutton

Length of output: 307


🏁 Script executed:

# Let's get the file size to see if we can read it entirely
stat record-and-playback/core/lib/recordandplayback/edl/video.rb 2>/dev/null || find . -name "video.rb" -type f -exec stat {} \;

Repository: bigbluebutton/bigbluebutton

Length of output: 230


🏁 Script executed:

# Search for the file and check its structure
fd "video\.rb" --type f

Repository: bigbluebutton/bigbluebutton

Length of output: 365


🏁 Script executed:

# Let's read the specific section mentioned in the review (lines 333-363)
sed -n '330,365p' ./record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 1961


🏁 Script executed:

# Let's also see more context before and after to understand the full flow
sed -n '318,400p' ./record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 4156


🏁 Script executed:

# Let's search for where original video files are deleted or handled
rg "videoinfo\.delete|File\.delete|FileUtils\.rm" ./record-and-playback/core/lib/recordandplayback/edl/video.rb -B 2 -A 2

Repository: bigbluebutton/bigbluebutton

Length of output: 805


🏁 Script executed:

# Let's check the resample_video_files method to understand what files it returns and how it handles originals
sed -n '532,648p' ./record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 7182


🏁 Script executed:

# Let's verify if original files are ever deleted from disk after validation
rg "File\.delete|FileUtils\.rm_rf|remove_entry_secure" ./record-and-playback/core/lib/recordandplayback/edl/video.rb -B 1 -A 1 | head -40

Repository: bigbluebutton/bigbluebutton

Length of output: 736


🏁 Script executed:

# Check what happens with corrupt_videos after removal from EDL
sed -n '375,400p' ./record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 1110


🏁 Script executed:

# Let's check if original video files are cleaned up anywhere after the resampling process
rg -A 10 "if corrupt_videos.length > 0" ./record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 409


🏁 Script executed:

# Let's verify the full flow - check if original files are ever deleted from disk anywhere
rg "File\.delete|remove.*original" ./record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 108


🏁 Script executed:

# Let's check the videoinfo structure and how it's used in composite_cut to understand impact of deletion
sed -n '1,100p' ./record-and-playback/core/lib/recordandplayback/edl/video.rb | head -50

Repository: bigbluebutton/bigbluebutton

Length of output: 2397


🏁 Script executed:

# Let's look at the full render method signature and understand the overall flow
rg "def render" ./record-and-playback/core/lib/recordandplayback/edl/video.rb -A 2

Repository: bigbluebutton/bigbluebutton

Length of output: 53


🏁 Script executed:

# Search for render method definition to understand the context better
rg "def.*render" ./record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 135


🏁 Script executed:

# Check the broader context - how videoinfo is passed and used after this point
sed -n '1,50p' ./record-and-playback/core/lib/recordandplayback/edl/video.rb | grep -A 20 "def self.render"

Repository: bigbluebutton/bigbluebutton

Length of output: 53


🏁 Script executed:

# Let's see if there are any other resample blocks or similar patterns that might show best practice
rg -B 5 "filename_update_map" ./record-and-playback/core/lib/recordandplayback/edl/video.rb | head -80

Repository: bigbluebutton/bigbluebutton

Length of output: 2247


Validate resampled videos before updating EDL to prevent video data loss.

The EDL is updated with new filenames before the resampled files are validated. If a resampled file fails validation, the original filename is deleted from videoinfo while the EDL entry gets removed later as corrupt, resulting in a missing video area in the final output. Validate the resampled files first, build a map of only successful resamples, and update the EDL only for those that passed validation.

🐛 Suggested fix: validate before swapping filenames
-          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 "Validating segment-resampled videos before updating EDL."
+            valid_update_map = {}
+            filename_update_map_gaps.each do |original_filename, new_filename|
+              info = video_info(new_filename)
+              if info[:video] && info[:duration] != 0
+                BigBlueButton.logger.debug "Successfully resampled and got info for #{new_filename}. Duration: #{info[:duration]}"
+                videoinfo[new_filename] = info
+                videoinfo.delete(original_filename)
+                valid_update_map[original_filename] = new_filename
+              else
+                BigBlueButton.logger.error "Resampled video file #{new_filename} is corrupt or invalid. Keeping original: #{original_filename}."
+                corrupt_videos << new_filename
+              end
+            end
+
+            if valid_update_map.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 valid_update_map.key?(video_data[:filename])
+                      video_data[:filename] = valid_update_map[video_data[:filename]]
+                    end
+                  end
+                end
+              end
+            end
+          end
🧰 Tools
🪛 RuboCop (1.82.1)

[convention] 334-334: Line is too long. [140/128]

(Layout/LineLength)


[convention] 335-335: Prefer single-quoted strings when you don't need string interpolation or special symbols.

(Style/StringLiterals)


[convention] 337-337: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[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 333
- 363, The current flow updates EDL filenames immediately after calling
resample_video_files, which can delete originals from videoinfo even if the
resampled file is invalid; instead, call video_info on each new filename
returned by resample_video_files first, build a filtered filename_update_map
containing only successfully validated resamples (info[:video] present and
info[:duration] > 0), add failures to corrupt_videos and do NOT delete the
original from videoinfo for failed resamples, then only iterate over edl and
replace video_data[:filename] using the filtered map and update videoinfo by
adding validated new entries and deleting originals only for those validated
mappings.

Comment on lines +532 to +606
# 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}'"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

wc -l record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 135


🏁 Script executed:

# First, let's see the full method and understand the concatenation process
sed -n '532,650p' record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 7219


🏁 Script executed:

# Let's check what happens after parts are created - look for concat handling
sed -n '600,700p' record-and-playback/core/lib/recordandplayback/edl/video.rb

Repository: bigbluebutton/bigbluebutton

Length of output: 5222


🏁 Script executed:

# Also check for any codec/format handling elsewhere in the file
rg -n "concat|webm|copy|codec" record-and-playback/core/lib/recordandplayback/edl/video.rb -A 2 -B 2

Repository: bigbluebutton/bigbluebutton

Length of output: 12529


🌐 Web query:

FFmpeg copy H.264 to WebM container compatibility

💡 Result:

Short answer: You generally cannot copy H.264 into a true WebM file. The WebM container spec only supports VP8/VP9/AV1 video and Vorbis/Opus audio; H.264 is not a supported codec for WebM, so ffmpeg will refuse a -c copy into .webm and report "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM." [1][2][3]

What to do

  • If you need to keep H.264, use a Matroska (.mkv) or MP4 (.mp4/.mov) container (Matroska can store H.264). Example: ffmpeg -i input.mp4 -c copy output.mkv. ffmpeg will fail if you try -c copy to .webm. [1][3]
  • If you need a WebM file, re-encode the video to a supported codec (e.g. VP9 or AV1) and audio to Vorbis/Opus. Example: ffmpeg -i input.mp4 -c:v libvpx-vp9 -b:v 2M -c:a libopus output.webm. [2][3]
  • You can force ffmpeg to write a Matroska stream with a .webm extension (ffmpeg -f matroska -c copy out.webm), but that produces a non-conforming file (Matroska labeled as WebM) and may not play everywhere — better use .mkv if you mean Matroska. [1]

Sources

  • FFmpeg mailing-list discussion / error message showing ffmpeg rejects H.264-in-WebM. [1]
  • MDN / web media format guidance (WebM codecs and container notes). [2]
  • Community Q&A / examples (Superuser/StackOverflow) describing supported codecs and ffmpeg usage. [3]

🌐 Web query:

WebM container supported video codecs VP8 VP9

💡 Result:

Short answer: WebM's required/supported video codecs are VP8 and VP9, and modern WebM also supports AV1. Common audio codecs are Vorbis and Opus; subtitles use WebVTT. [1][2]

References:

  • MDN (WebM: VP8, VP9, AV1; Vorbis, Opus). [1]
  • Library of Congress WebM format summary (may contain VP8/VP9, Vorbis, WebVTT). [2]

Use container and blank video codec compatible with source codec.

The code hardcodes WebM as the intermediate format and VP8 as the blank codec. When -c copy attempts to stream-copy H.264 or other incompatible codecs into WebM, ffmpeg will fail with "Only VP8 or VP9 video and Vorbis or Opus audio are supported for WebM." Although error handling prevents corruption, segmented resampling aborts silently for H.264 and other incompatible sources—a critical limitation since H.264 is extremely common. The extracted original_video_codec_info (line 543) is never consulted to adapt the strategy.

Select intermediate format and blank codec based on source codec: for VP8/VP9 use WebM, for H.264 use MKV (compatible with stream copy), for others use a common container/codec pair. Alternatively, always re-encode copy segments to ensure compatibility rather than stream-copying incompatible codecs.

🧰 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, resample_video_files currently hardcodes intermediate_format = 'webm' and
uses libvpx for blank segments regardless of original_video_codec_info, causing
stream-copy failures for H.264 and other codecs; update resample_video_files to
inspect original_video_codec_info and choose a compatible intermediate_format
and blank-video codec/params (e.g., use 'webm' + libvpx for vp8/vp9, use 'mkv' +
libx264 for h264, and a safe fallback like 'mp4'+'libx264' or always re-encode
copy segments when codec/container mismatch), ensure the chosen format is used
when building part_path and when assembling cmd_part for both :recode and :copy
actions, and fallback to re-encoding copy segments (not -c copy) if you cannot
guarantee container/codec compatibility; reference the variables
original_video_codec_info, intermediate_format, part_path, cmd_part, and
processing_segments to implement the conditional selection and fallback.

@kepstin

kepstin commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

Note that the changes for video will conflict with the refactoring that I've done in #24483

Specifically, all the code involved in probing or pre-processing video files has been moved to record-and-playback/core/lib/recordandplayback/edl/video/video_source.rb

@prlanzarin

Copy link
Copy Markdown
Member Author

@kepstin Ack. Do you prefer to handle #24483 or this one first?

@kepstin

kepstin commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

I think I'd like to do #24483 first for the video. If you are able to separate the video and audio parts of this into separate PRs, I should be able to look at the audio parts sooner.

prlanzarin and others added 9 commits January 19, 2026 13:21
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]>
Resample all files present in the final edl to help fix desyncs when file has large pts gaps.
Only resample individual audio tracks if their gaps are larger than 60s.
For gaps smaller than that, the mixing process seems to handle PTS gaps
properly.

Co-authored-by: germanocaumo <[email protected]>
Audio resample can lead to high ffmpeg memory usage when audio file has large pts gaps, change the resample to re-encode the gappy parts as silence (like it is done por video):
- idenfity each gap > MAX_AUDIO_GAP_FOR_RESAMPLE_MS
- break the file into multiple parts, copying the good parts and generating silence for the gappy parts
- concatenate all the parts to create the new resampled file
…id timestamp issues

- Process segments into intermediate WAV (PCM) files instead of OGG to avoid `libvorbis` timestamp issues and audio repetition artifacts.
- Use `atrim` for frame-accurate cutting
- Concatenate wav parts and encode them to ogg in one go. This ensures a clean, continuous output stream with fresh timestamps generated by the encoder.
@prlanzarin
prlanzarin force-pushed the u30/fix/port-resample-rap-nacelle branch from 852880b to 585422b Compare January 19, 2026 13:26
@prlanzarin prlanzarin changed the title fix(recording): improve raw file resampling to address A/V sync issues fix(recording): improve raw file resampling to address A/V sync issues (audio) Jan 19, 2026
@sonarqubecloud

Copy link
Copy Markdown

@prlanzarin

Copy link
Copy Markdown
Member Author

@kepstin @germanocaumo I've split this PR into its audio and video versions.
This PR (#24481) is the audio one.
See #24490 for the video part.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Around line 410-465: The gap end can exceed the actual audio length because
gap_end = current_pts + margin_s in get_all_processing_segments, causing extra
silence and drifting duration; clamp gap_end to audio_total_duration_s when
building recode_intervals (and ensure any merged interval ends are also bounded
by audio_total_duration_s) so all intervals and the final segments never extend
past audio_total_duration_s.

Comment on lines +410 to +465
def self.get_all_processing_segments(filename, max_gap_ms, audio_total_duration_s, margin_s = 0.0)
pts_times = BigBlueButton::EDL::MediaUtils.get_packet_pts_times(filename, 'a')
return [{ start_pts: 0.0, end_pts: audio_total_duration_s, action: :copy }] if pts_times.nil? || pts_times.empty?

max_gap_seconds = max_gap_ms / 1000.0
recode_intervals = []

previous_pts = pts_times.first
pts_times.each do |current_pts|
if current_pts > previous_pts
gap = current_pts - previous_pts
if gap > max_gap_seconds
gap_start = [previous_pts - margin_s, 0.0].max
gap_end = current_pts + margin_s
recode_intervals << { start: gap_start, end: gap_end }
end
end
previous_pts = current_pts
end

recode_intervals.sort_by! { |r| r[:start] }
merged_recode_intervals = []
recode_intervals.each do |current_interval|
if merged_recode_intervals.empty?
merged_recode_intervals << current_interval
else
last_interval = merged_recode_intervals.last
if current_interval[:start] <= last_interval[:end] + 0.01
last_interval[:end] = [last_interval[:end], current_interval[:end]].max
else
merged_recode_intervals << current_interval
end
end
end

segments = []
last_processed_pts = 0.0

merged_recode_intervals.each do |interval|
if interval[:start] > last_processed_pts + 0.01
segments << { start_pts: last_processed_pts, end_pts: interval[:start], action: :copy }
end
segments << { start_pts: interval[:start], end_pts: interval[:end], action: :recode }
last_processed_pts = interval[:end]
end

if last_processed_pts < audio_total_duration_s - 0.01
segments << { start_pts: last_processed_pts, end_pts: audio_total_duration_s, action: :copy }
end

if segments.empty?
segments << { start_pts: 0.0, end_pts: audio_total_duration_s, action: :copy }
end

segments
end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Clamp gap end to total duration to avoid extending audio length.
margin_s can push gap_end past audio_total_duration_s, which would insert extra silence and drift the final duration. Clamping keeps the output length stable.

🐛 Proposed fix
-              gap_end = current_pts + margin_s
+              gap_end = [current_pts + margin_s, audio_total_duration_s].min
🧰 Tools
🪛 RuboCop (1.82.1)

[convention] 447-447: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 459-459: Trailing whitespace detected.

(Layout/TrailingWhitespace)


[convention] 460-460: Favor modifier if usage when having a single-line body. Another good alternative is the usage of control flow &&/||.

(Style/IfUnlessModifier)


[convention] 461-461: Use 2 (not 3) spaces for indentation.

(Layout/IndentationWidth)

🤖 Prompt for AI Agents
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 410
- 465, The gap end can exceed the actual audio length because gap_end =
current_pts + margin_s in get_all_processing_segments, causing extra silence and
drifting duration; clamp gap_end to audio_total_duration_s when building
recode_intervals (and ensure any merged interval ends are also bounded by
audio_total_duration_s) so all intervals and the final segments never extend
past audio_total_duration_s.

@github-actions

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

@kepstin

kepstin commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor

For testing purposes, it's straightforwards to create an audio file containing a timestamp gap.

First generate a file containing an audio signal for testing (I'm using a basic sine wave here, you can use any audio source including existing recorded audio):

ffmpeg -filter_complex sine -c:a libopus -b:a 64K -f webm -t 15:00 sine.webm

Then write an ffconcat playlist file with a "duration" set on the first audio segment which is longer than the length of the audio in the segment. This causes the concat input to offset the timestamps of the following segment, leaving a gap. Here I am generating a sequence with 15 minutes of sine wave, a 1 hour gap, then 15 minutes of sine wave:

ffconcat version 1.0
file sine.webm
duration 1:15:00
file sine.webm

And run the following ffmpeg command to turn that into a single webm audio file for testing:

ffmpeg -i test-audio-gap.ffconcat -c:a copy test-audio-gap.webm

I have verified that the gap detection code in this PR correctly detects the gap in a file generated in this way.

Via code inspection of ffmpeg's aresample filter, and testing, I have verified the memory issue when dealing with large audio gaps. This can be seen in the following output:

# run ffmpeg aresample filter over entire length of file with gap
/usr/bin/time -v ffmpeg -i test-audio-gap.webm -af aresample=async=1000 -f null -
[...]
	Maximum resident set size (kbytes): 1634776 # approx 1.6GB

# run ffmpeg aresample filter after an atrim filter cutting at the start of the gap
/usr/bin/time -v ffmpeg -i test-audio-gap.webm -af atrim=end=900.021,aresample=async=1000 -f null -
[...]
	Maximum resident set size (kbytes): 66208 # approx 66MB

# run ffmpeg aresample filter after seeking to the end of the gap
/usr/bin/time -v ffmpeg -ss 1:15:00 -i test-audio-gap.webm -af aresample=async=1000 -f null -
[...]
	Maximum resident set size (kbytes): 66820 # approx 66MB

I'm not a fan of the way the code is currently structured, where it generates a new full-length uncompressed wave file of the entire length of the audio when it detects gaps like this. I don't think this is actually necessary. Rather than do this, it should be possible to edit the audio EDL to add a cut when the gap starts, and another cut when the gap ends, and remove the affected audio file from the list of audio files to be mixed during the gap. This will improve the processing speed and reduce the required disk space usage.

@germanocaumo

Copy link
Copy Markdown
Contributor

For testing purposes, it's straightforwards to create an audio file containing a timestamp gap.

First generate a file containing an audio signal for testing (I'm using a basic sine wave here, you can use any audio source including existing recorded audio):

ffmpeg -filter_complex sine -c:a libopus -b:a 64K -f webm -t 15:00 sine.webm

Then write an ffconcat playlist file with a "duration" set on the first audio segment which is longer than the length of the audio in the segment. This causes the concat input to offset the timestamps of the following segment, leaving a gap. Here I am generating a sequence with 15 minutes of sine wave, a 1 hour gap, then 15 minutes of sine wave:

ffconcat version 1.0
file sine.webm
duration 1:15:00
file sine.webm

And run the following ffmpeg command to turn that into a single webm audio file for testing:

ffmpeg -i test-audio-gap.ffconcat -c:a copy test-audio-gap.webm

I have verified that the gap detection code in this PR correctly detects the gap in a file generated in this way.

Via code inspection of ffmpeg's aresample filter, and testing, I have verified the memory issue when dealing with large audio gaps. This can be seen in the following output:

# run ffmpeg aresample filter over entire length of file with gap
/usr/bin/time -v ffmpeg -i test-audio-gap.webm -af aresample=async=1000 -f null -
[...]
	Maximum resident set size (kbytes): 1634776 # approx 1.6GB

# run ffmpeg aresample filter after an atrim filter cutting at the start of the gap
/usr/bin/time -v ffmpeg -i test-audio-gap.webm -af atrim=end=900.021,aresample=async=1000 -f null -
[...]
	Maximum resident set size (kbytes): 66208 # approx 66MB

# run ffmpeg aresample filter after seeking to the end of the gap
/usr/bin/time -v ffmpeg -ss 1:15:00 -i test-audio-gap.webm -af aresample=async=1000 -f null -
[...]
	Maximum resident set size (kbytes): 66820 # approx 66MB

I'm not a fan of the way the code is currently structured, where it generates a new full-length uncompressed wave file of the entire length of the audio when it detects gaps like this. I don't think this is actually necessary. Rather than do this, it should be possible to edit the audio EDL to add a cut when the gap starts, and another cut when the gap ends, and remove the affected audio file from the list of audio files to be mixed during the gap. This will improve the processing speed and reduce the required disk space usage.

@kepstin we tried this approach also but observed that the final audio after manipulating the EDL doing this was getting out of sync for the recordings we had, se we did not went further with the implementation.

@github-actions

github-actions Bot commented Mar 2, 2026

Copy link
Copy Markdown

This pull request has conflicts ☹
Please resolve those so we can review the pull request.
Thanks.

@kepstin

kepstin commented Mar 2, 2026

Copy link
Copy Markdown
Contributor

@kepstin we tried this approach also but observed that the final audio after manipulating the EDL doing this was getting out of sync for the recordings we had, se we did not went further with the implementation.

Hmm. If this is the case, then there must be some fundamental issue that is wrong with the audio processing. Adding additional cuts should not be changing the audio/video sync.

Which direction does the desync happen? Does the audio get steadily more and more delayed as the meeting goes on? Is it inconsistent? Does it affect everyone in the session or just some people? Is the audio file length adjustment (speed adjustment) triggered?

@kepstin

kepstin commented Mar 11, 2026

Copy link
Copy Markdown
Contributor

I'd like to revisit the idea of manipulating the EDL to skip the gaps with the change in #24734 applied.

I spent some time investigating possible causes of desync caused by ffmpeg seeking in files with gaps, and found a problem where an audio track could be mixed with an offset if the seekpoint into the audio file was inside a gap. This can be resolved with the first_pts option, which causes the aresample filter to fill in the gap between the '0' timestamp (the seek point) and the time when the first audio file is received with silence, in order to preserve the correct offset.

@prlanzarin

Copy link
Copy Markdown
Member Author

I'd like to revisit the idea of manipulating the EDL to skip the gaps with the change in #24734 applied.

I spent some time investigating possible causes of desync caused by ffmpeg seeking in files with gaps, and found a problem where an audio track could be mixed with an offset if the seekpoint into the audio file was inside a gap. This can be resolved with the first_pts option, which causes the aresample filter to fill in the gap between the '0' timestamp (the seek point) and the time when the first audio file is received with silence, in order to preserve the correct offset.

cc @germanocaumo
FWIW the problematic recording that displayed desync issues with the original EDL-based solution had a screenshare with audio in it - and the desync was related to it.
That was made on a mixed setup (LiveKit audio, mediasoup screen share).
We'll look into reprocessing that recording with the above change + the original EDL-based commits.

@kepstin

kepstin commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

I've put together my own version of the audio gap removal via EDL editing here: v3.0.x-release...kepstin:bigbluebutton:audio-edl-remove-gaps which I would be interested in getting some feedback on.

Compared to this PR, I've adjusted the way gap detection works so it only needs to run the ffprobe command to dump PTS value once per file (no second run on files with gaps), and added handling for packet durations to ensure gaps are only counted for the time between when one packet ends and when the next packet starts (I'm not totally sure of whether this logic is correct for video, but it is correct for audio. Can always skip it on video if it's a problem). Also fixed up some issues with the ffprobe command caused by inheriting some values from the FFPROBE constant which aren't actually desired in this use case.

@kepstin

kepstin commented Mar 19, 2026

Copy link
Copy Markdown
Contributor

Thanks @germanocaumo for providing some recording files which demonstrated an audio/video desync. I discovered that the ffmpeg "aresample" filter in ffmpeg 4.4 on Ubuntu 22.04 is broken, but a workaround is available. I've updated the code at v3.0.x-release...kepstin:bigbluebutton:audio-edl-remove-gaps with that fix and some other changes which should improve processing speed and reduce the places where audio offsets could get introduced.

After some testing, I expect to create a new PR from that branch which will replace this PR.

@prlanzarin

Copy link
Copy Markdown
Member Author

Superseded by #24776

@prlanzarin prlanzarin closed this Mar 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants