Skip to content

fix(recording): Address A/V sync issues, glitches on cuts, ffmpeg memory usage (audio) - #24776

Merged
antobinary merged 17 commits into
bigbluebutton:v3.0.x-developfrom
kepstin:audio-edl-remove-gaps
Mar 23, 2026
Merged

antobinary merged 17 commits into
bigbluebutton:v3.0.x-developfrom
kepstin:audio-edl-remove-gaps

Conversation

@kepstin

@kepstin kepstin commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

This is a replacement for #24481.

An approach is taken where after analyzing the audio files to check for gaps, the audio file is removed from the EDL structure for the duration of the "gap" to prevent ffmpeg from processing the file during this time period. This fixes the excessive memory usage in the ffmpeg aresample filter.

The start_pts feature of the aresample filter is used to ensure sample-accurate alignment of audio during cuts.

While analyzing some recordings that had A/V sync issues after applying these changes, I discovered that the aresample filter in ffmpeg 4.4 (Ubuntu 22.04) was injecting several seconds of silent audio with incorrect timestamps into some audio tracks, causing A/V sync issues. This happened due to a bug in a performance optimization in the filter, where it is intended to "pass through" audio until it detects a need to start resampling to correct drift, and then start resampling afterwards. The silent audio with incorrect timestamps was generated when the filter switched to resampling mode. A workaround is available - set a flag that forces it to use resampling mode from the start of the file.

The remaining changes are:

  • A performance fix, to remove the second audio processing pass and mixing step needed to handle deskshare audio. Now that all of the issues with multiple audio tracks and audio sync during cuts have been fixed, it's possible to combine the microphone and deskshare audio into a single pass.
  • Switch to 'flac' as the intermediate file format. The previously used 'vorbis' codec has fixed size blocks, which means that when concatenated with the method previously used, it would sometimes introduce audio glitches at cut points. The variable block size in 'flac' avoids this issue, without using as much disk space as uncompressed 'wav' would need for temporary files.

kepstin and others added 6 commits March 11, 2026 14:58
By default, the `aresample` filter assumes that the timestamp of the
first audio frame it sees is the start of the audio, and the output
timestamps will be offset so that point becomes 0 in the output.
If the seek point happened to be in a gap where there were no audio
frames, this will cause the audio to be earlier than expected.

Setting the `first_pts=0` option causes the filter to trim or pad
the start of the output audio to preserve the correct offset relative to
0, where 0 is the seek point (set with the `-ss` option).
When there's a large timestamp gap, the ffmpeg `aresample` filter
generates silent audio to fill the gap, but it enqueues the full length
of the gap into the filter chain all at once, which uses a lot of
memory. To work around this issue, detect long gaps in the audio files
and remove the audio file from the mix for the duration of the gap.

This solution requires only a single pass through each audio file to
do timestamp analysis to find all the gaps, and the EDL processing does
one pass through the EDL for each file with gaps - O(M×N) - which is
probably as good as it gets without making the code significantly more
complicated.
Previous code processed them separately, then mixed them. This added
an extra set of temporary files, an extra generation loss if a lossy
working format is used, and another place where audio sync issues
can be introduced.

Now that the audio processing reliably handles multiple concurrent
audio tracks and audio coming/going, merge the microphone and deskshare
audio EDLs to process them together.
Vorbis audio uses fixed-size packet and doesn't concatenate cleanly
with the method that we're using. This can result in audio glitches
during audio cuts, and might cause (very small amounts of) A/V desync
in some players.

Flac uses variable-sized packets and can be concatenated cleanly. The
other option is wav, but flac saves quite a lot of disk space and isn't
that much slower.

Some tweaks have been made to the presentation recording format to
ensure it only encodes the final audio to ogg vorbis once regardless of
whether or not the webcam video is used.
@coderabbitai

coderabbitai Bot commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Deskshare audio EDLs are merged into the main audio EDL earlier. A new BigBlueButton::EDL::MediaUtils.pts_gaps probes media with ffprobe to detect PTS gaps; EDL helpers split entries at gap boundaries and remove audios fully inside gaps. render now removes corrupt audios (and their audioinfo refs), calls remove_audio_gaps, then enforces cut lengths and computes next_timestamp before rendering. FFmpeg audio filters were reworked to resample (aresample to 48000 Hz) before aformat; waveform output changed from Ogg/Vorbis to FLAC; non-silence seeking uses -noaccurate_seek.

Sequence Diagram(s)

sequenceDiagram
    participant Proc as Processor
    participant EDL as EDL::Audio
    participant MU as EDL::MediaUtils
    participant FFPROBE as ffprobe
    participant FFMPEG as ffmpeg

    Proc->>EDL: create base audio EDL
    Proc->>EDL: create deskshare audio EDL (if present)
    Proc->>EDL: merge(*edls)
    activate EDL
        EDL->>MU: pts_gaps(process_dir, audio_file, :audio)
        activate MU
            MU->>FFPROBE: spawn ffprobe (packet=pts_time,duration_time CSV)
            FFPROBE-->>MU: packet rows
            MU->>MU: detect gaps >= min_gap
            MU-->>EDL: gap intervals
        deactivate MU
        EDL->>EDL: split_edl_at(...) for detected gaps
        EDL->>EDL: remove_audio_gaps(...)
        EDL->>EDL: remove corrupt audios and delete audioinfo refs
        EDL->>EDL: enforce_cut_lengths(...)
        EDL->>EDL: compute next_timestamp
    deactivate EDL

    Proc->>EDL: render(edl)
    activate EDL
        EDL->>FFMPEG: read segments with -noaccurate_seek, -ss, -i
        EDL->>FFMPEG: per-track filters: aresample -> aformat -> concat/merge
        FFMPEG-->>EDL: rendered audio + waveform (.flac)
    deactivate EDL
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title accurately summarizes the main changes: addressing A/V sync issues, glitches on cuts, and ffmpeg memory usage related to audio processing.
Description check ✅ Passed The pull request description is directly related to the changeset, explaining the technical approach, rationale for changes (gap detection, aresample filter usage, codec switch), and performance optimizations.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@antobinary antobinary added this to the Release 3.0 milestone Mar 19, 2026

@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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Around line 335-337: The code builds the ffmpeg filter string using an
undefined variable audio_date which causes a NameError; update the conditional
branch that appends "atempo=...,atrim=start=..." to use the correct local
variable audio_data (i.e., call ms_to_s(audio_data[:timestamp]) instead of
ms_to_s(audio_date[:timestamp])) so the filter string is constructed from the
actual audio_data timestamp before appending FFMPEG_ARESAMPLE, FFMPEG_AFORMAT,
and apad.

In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb`:
- Around line 57-69: ffprobe's stderr is being merged into the CSV pipe (err:
%i[child out]) which corrupts CSV parsing; update the spawn call that uses
ffprobe_cmd so stderr is redirected to the log file instead of :child/out (use a
File or log_file handle for the err option) and ensure the log file is
opened/appended and closed properly so the CSV reader created by CSV.new(r, ...)
only sees ffprobe stdout; keep the existing r,w pipe usage and close w after
spawn as currently implemented.

In
`@record-and-playback/core/lib/recordandplayback/generators/audio_processor.rb`:
- Around line 66-72: The code currently assigns the intermediate FLAC path to
`@audio_file` (result of BigBlueButton::EDL::Audio.render) so
get_processed_audio_file still returns the working FLAC instead of the encoded
OGG; after calling BigBlueButton::EDL.encode(`@audio_file`, nil, ogg_format,
file_basename) update `@audio_file` to point to the resulting encoded file (e.g.
construct or retrieve "#{file_basename}.ogg") so get_processed_audio_file and
callers return the final OGG artifact; apply the same change for the other
occurrence around the later encode call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0ab79930-bf78-4a44-9a01-1eeebf2e94eb

📥 Commits

Reviewing files that changed from the base of the PR and between b6c0c5c and c21683c.

📒 Files selected for processing (6)
  • 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/generators/audio_processor.rb
  • record-and-playback/presentation/scripts/process/presentation.rb
  • record-and-playback/screenshare/scripts/process/screenshare.rb
  • record-and-playback/video/scripts/process/video.rb

@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

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

397-447: Gap removal logic is functional but the enumerator pattern could be clearer.

The use of .each to create an enumerator, then calling .none? and .size before iterating with .next works but is unconventional. Consider separating the array from the enumerator for clarity:

♻️ Optional: clearer enumerator usage
       def self.remove_audio_gaps(edl, audio_files, process_dir)
         audio_files.each do |filename|
-          gaps = BigBlueButton::EDL::MediaUtils.pts_gaps(process_dir, filename, :audio).each
-          next if gaps.none?
+          gaps_array = BigBlueButton::EDL::MediaUtils.pts_gaps(process_dir, filename, :audio)
+          next if gaps_array.empty?
 
-          BigBlueButton.logger.info("Audio file #{File.basename(filename)} has #{gaps.size} gap(s), adjusting EDL")
+          BigBlueButton.logger.info("Audio file #{File.basename(filename)} has #{gaps_array.size} gap(s), adjusting EDL")
 
+          gaps = gaps_array.each
           next_i = 0
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 397
- 447, The code in remove_audio_gaps mixes an array and an enumerator (using
.each then calling .none? and .size before .next), which is confusing; change it
to first capture the gaps array from
BigBlueButton::EDL::MediaUtils.pts_gaps(process_dir, filename, :audio) into a
variable (e.g., gaps_array), return early if gaps_array.empty?, log using
gaps_array.size, then create an enumerator from that array (e.g., gaps =
gaps_array.each) and use gaps.next/StopIteration as before; keep split_edl_at,
entry[:audios].reject!, and the existing rescue StopIteration logic unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb`:
- Line 45: The raise uses method-call syntax and will trigger NoMethodError;
update the raise in media_utils (the branch that currently does: else raise
ArgumentError("Unexpected stream_type #{stream_type.inspect}")) to use proper
Ruby exception construction such as raise ArgumentError, "Unexpected stream_type
#{stream_type.inspect}" or raise ArgumentError.new("Unexpected stream_type
#{stream_type.inspect}") so the intended ArgumentError is raised with the
message.

---

Nitpick comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Around line 397-447: The code in remove_audio_gaps mixes an array and an
enumerator (using .each then calling .none? and .size before .next), which is
confusing; change it to first capture the gaps array from
BigBlueButton::EDL::MediaUtils.pts_gaps(process_dir, filename, :audio) into a
variable (e.g., gaps_array), return early if gaps_array.empty?, log using
gaps_array.size, then create an enumerator from that array (e.g., gaps =
gaps_array.each) and use gaps.next/StopIteration as before; keep split_edl_at,
entry[:audios].reject!, and the existing rescue StopIteration logic unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b7f705c8-35c4-4aee-aef3-3c086741bbda

📥 Commits

Reviewing files that changed from the base of the PR and between c21683c and 222939f.

📒 Files selected for processing (2)
  • record-and-playback/core/lib/recordandplayback/edl/audio.rb
  • record-and-playback/core/lib/recordandplayback/edl/media_utils.rb

@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

🧹 Nitpick comments (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (1)

88-90: Prefer chomp over chomp! for stable log values.

On Line 89, line.chomp! can return nil when no newline is removed; that can log nil unexpectedly.

🛠️ Proposed fix
-              BigBlueButton.logger.debug(line.chomp!)
+              BigBlueButton.logger.debug(line.chomp)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb` around
lines 88 - 90, Replace the destructive chomp! call inside the log_file.each_line
loop so logging never receives nil: in the block that iterates over
log_file.each_line and calls BigBlueButton.logger.debug(line.chomp!), change it
to use non-destructive chomp (line.chomp) before passing to
BigBlueButton.logger.debug to ensure stable string values are always logged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb`:
- Around line 32-33: The method's threshold logic uses `gap > min_gap` which
contradicts the documented contract "at least this long (ms)" for the `min_gap`
parameter; change the comparison to `gap >= min_gap` where gaps are filtered
(replace `>` with `>=` for the `gap` vs `min_gap` check), and update any nearby
comment or test expectations if they rely on the exclusive behavior; refer to
the `min_gap` variable and the gap filtering expression in this file to locate
and fix the code.
- Around line 67-86: The CSV parsing loop (CSV.new / csv.each and the
prev_end/pts calculation) can raise and skip the Process.wait2(pid) call,
leaving the spawned ffprobe (pid) as a zombie; wrap the CSV parsing and
iteration in a begin...ensure (or ensure-only) block so that Process.wait2(pid)
is invoked from the ensure clause regardless of exceptions, preserving the
existing logging (BigBlueButton.logger.debug("ffprobe #{status}")) and still
collecting pts_gaps/prev_end as before.

---

Nitpick comments:
In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb`:
- Around line 88-90: Replace the destructive chomp! call inside the
log_file.each_line loop so logging never receives nil: in the block that
iterates over log_file.each_line and calls
BigBlueButton.logger.debug(line.chomp!), change it to use non-destructive chomp
(line.chomp) before passing to BigBlueButton.logger.debug to ensure stable
string values are always logged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 0ae67ffe-90c9-46db-ac13-bc427240c078

📥 Commits

Reviewing files that changed from the base of the PR and between 222939f and 589b4e8.

📒 Files selected for processing (1)
  • record-and-playback/core/lib/recordandplayback/edl/media_utils.rb

kepstin added 2 commits March 20, 2026 11:37
Make sure that the ffprobe process is waited for, and the log output is
printed, even if an exception is raised during the CSV output parsing.

@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

🧹 Nitpick comments (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (1)

1-1: Optional: Update file header for Ruby style conventions.

The # encoding: UTF-8 comment is unnecessary since Ruby 2.0+ defaults to UTF-8. Consider replacing it with # frozen_string_literal: true for immutable string literals.

♻️ Suggested change
-# encoding: UTF-8
+# frozen_string_literal: true
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb` at line 1,
Replace the old encoding header at the top of media_utils.rb with Ruby's modern
frozen-string literal directive: remove the line "# encoding: UTF-8" and add "#
frozen_string_literal: true" as the first line so strings in this file become
immutable; ensure the change appears at the top of media_utils.rb (affecting any
methods or classes defined below, e.g., in this file's media helper functions).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb`:
- Around line 89-92: Replace the destructive chomp! call that may return nil
with the non-destructive chomp when iterating log_file lines; in the block where
log_file.each_line do |line| ... BigBlueButton.logger.debug(line.chomp!) change
to BigBlueButton.logger.debug(line.chomp) so the logger always receives a String
(locate this in media_utils.rb where the file is rewound and iterated).

---

Nitpick comments:
In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb`:
- Line 1: Replace the old encoding header at the top of media_utils.rb with
Ruby's modern frozen-string literal directive: remove the line "# encoding:
UTF-8" and add "# frozen_string_literal: true" as the first line so strings in
this file become immutable; ensure the change appears at the top of
media_utils.rb (affecting any methods or classes defined below, e.g., in this
file's media helper functions).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: dfb9ea3a-049e-4260-a561-562bf95e6866

📥 Commits

Reviewing files that changed from the base of the PR and between 589b4e8 and 4a797af.

📒 Files selected for processing (1)
  • record-and-playback/core/lib/recordandplayback/edl/media_utils.rb

@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.

🧹 Nitpick comments (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (1)

1-1: Optional: modernize file header comment.

# encoding: UTF-8 is unnecessary on modern Ruby; consider replacing it with # frozen_string_literal: true to satisfy style checks.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb` at line 1,
Replace the legacy file header "# encoding: UTF-8" with the modern Ruby magic
comment "# frozen_string_literal: true"; locate the existing header line (the
literal "# encoding: UTF-8") in media_utils.rb and swap it out so the file uses
frozen_string_literal to satisfy style checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@record-and-playback/core/lib/recordandplayback/edl/media_utils.rb`:
- Line 1: Replace the legacy file header "# encoding: UTF-8" with the modern
Ruby magic comment "# frozen_string_literal: true"; locate the existing header
line (the literal "# encoding: UTF-8") in media_utils.rb and swap it out so the
file uses frozen_string_literal to satisfy style checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e2a2e60b-fac1-4d60-969b-44a4e44f6b40

📥 Commits

Reviewing files that changed from the base of the PR and between 4a797af and 67af89f.

📒 Files selected for processing (1)
  • record-and-playback/core/lib/recordandplayback/edl/media_utils.rb

@antobinary antobinary mentioned this pull request Mar 20, 2026
22 of 26 tasks

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Line 132: The line uses an incorrect variable name next_idl causing a
NameError when merging EDLs; change done[next_idl] = true if entries_i[next_edl]
>= edls[next_edl].length to use next_edl (i.e., set done[next_edl] = true when
entries_i[next_edl] has reached edls[next_edl].length) so the done array is
updated for the correct EDL index (affecting the merge loop that references
done, entries_i, next_edl, and edls).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a5119846-0830-43bb-ab70-0d9088a074e5

📥 Commits

Reviewing files that changed from the base of the PR and between 4a797af and c3bcf38.

📒 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/generators/audio_processor.rb

@kepstin

kepstin commented Mar 20, 2026

Copy link
Copy Markdown
Contributor Author

@germanocaumo I've made some formatting cleanup changes - before we merge this, it would be great if you could retest a recording with deskshare audio just to make sure I didn't overlook any mistakes.

@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

🧹 Nitpick comments (2)
record-and-playback/core/lib/recordandplayback/edl/audio.rb (2)

328-328: Optional: Float equality comparison.

The static analyzer warns that speed != 1.0 may be unreliable due to floating-point precision. In this context the risk is low since speed is either the literal 1.0 default or comes from a ratio that already passed a 0.3% tolerance check (line 302). However, for defensive coding, consider:

💡 Alternative approach
-              line << "atempo=#{speed},atrim=start=#{ms_to_s(audio_data[:timestamp])}," if speed != 1.0
+              line << "atempo=#{speed},atrim=start=#{ms_to_s(audio_data[:timestamp])}," unless (speed - 1.0).abs < 0.0001

Or track whether speed was modified with a boolean flag.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` at line 328, The
float equality check using `speed != 1.0` is fragile; change the condition in
the code that builds the filter string (the expression that currently appends
`"atempo=#{speed},atrim=start=#{ms_to_s(audio_data[:timestamp])}," if speed !=
1.0`) to use a small epsilon comparison (e.g., `if (speed - 1.0).abs > EPSILON`)
or use a boolean flag set when `speed` is actually modified earlier, so the
`atempo`/`atrim` fragment is only appended when speed was intentionally changed;
reference the `speed` variable and the `ms_to_s(audio_data[:timestamp])` string
construction to locate where to update the condition.

118-121: Minor: Comment says "videos" but this handles audios.

The comment appears to be a copy-paste artifact from similar video EDL code.

📝 Suggested fix
-          # Remove deleted videos
+          # Remove deleted audios
           del_audios.each do |audio|
             merged_entry[:audios].reject! { |a| a[:filename] == audio[:filename] }
           end
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 118
- 121, The comment above the deletion loop mistakenly says "videos" while the
code operates on audios; update the comment to accurately reflect the operation
(e.g., change "# Remove deleted videos" to "# Remove deleted audios") near the
block that iterates over del_audios and modifies merged_entry[:audios] to keep
it consistent with the variables del_audios, audio and merged_entry[:audios].
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Around line 391-397: The code currently calls
BigBlueButton::EDL::MediaUtils.pts_gaps(...).each which returns an Enumerator
and then uses gaps.none? which consumes the enumerator, causing subsequent
gaps.next to raise StopIteration; fix by materializing the gaps into a
collection before checking/consuming it — e.g. assign gaps =
BigBlueButton::EDL::MediaUtils.pts_gaps(process_dir, filename, :audio).each.to_a
(or call .to_a on the original return), then use gaps.empty? (or iterate over
the array) so the later use of gaps.next / gap_start, gap_end and next_i works
correctly.

---

Nitpick comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Line 328: The float equality check using `speed != 1.0` is fragile; change the
condition in the code that builds the filter string (the expression that
currently appends
`"atempo=#{speed},atrim=start=#{ms_to_s(audio_data[:timestamp])}," if speed !=
1.0`) to use a small epsilon comparison (e.g., `if (speed - 1.0).abs > EPSILON`)
or use a boolean flag set when `speed` is actually modified earlier, so the
`atempo`/`atrim` fragment is only appended when speed was intentionally changed;
reference the `speed` variable and the `ms_to_s(audio_data[:timestamp])` string
construction to locate where to update the condition.
- Around line 118-121: The comment above the deletion loop mistakenly says
"videos" while the code operates on audios; update the comment to accurately
reflect the operation (e.g., change "# Remove deleted videos" to "# Remove
deleted audios") near the block that iterates over del_audios and modifies
merged_entry[:audios] to keep it consistent with the variables del_audios, audio
and merged_entry[:audios].

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6e781d37-f85e-40fc-a785-61d1893ed9be

📥 Commits

Reviewing files that changed from the base of the PR and between c3bcf38 and 1f7e559.

📒 Files selected for processing (1)
  • record-and-playback/core/lib/recordandplayback/edl/audio.rb

This worked perfectly fine on the array iterator, where both values
could be calculated lazily (they do not consume the iterator) but it
made the code a bit more difficult to understand.

@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

🧹 Nitpick comments (4)
record-and-playback/core/lib/recordandplayback/edl/audio.rb (4)

417-420: Minor: Trailing comma after last argument.

This is a style convention issue flagged by RuboCop. While harmless, removing the trailing comma aligns with Ruby style conventions for method calls.

♻️ Suggested fix
             BigBlueButton.logger.debug(
               "Processing gap [#{gap_start}ms, #{gap_end}ms) " \
-              "in EDL entry #{i} (timestamp=#{entry[:timestamp]}ms)",
+              "in EDL entry #{i} (timestamp=#{entry[:timestamp]}ms)"
             )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 417
- 420, Remove the trailing comma from the debug call to satisfy RuboCop styling:
locate the BigBlueButton.logger.debug invocation that logs "Processing gap
[#{gap_start}ms, #{gap_end}ms) in EDL entry #{i}
(timestamp=#{entry[:timestamp]}ms)" and remove the trailing comma after the
final argument so the method call has no extraneous comma.

26-32: Redundant .freeze calls with frozen_string_literal: true.

Since frozen_string_literal: true is enabled at the top of the file, string literals are automatically frozen. The explicit .freeze calls on these interpolated strings are redundant and can be removed for cleaner code.

♻️ Suggested cleanup
-      FFMPEG_AEVALSRC = "aevalsrc=s=#{SAMPLE_RATE}:c=stereo:exprs=0|0".freeze
+      FFMPEG_AEVALSRC = "aevalsrc=s=#{SAMPLE_RATE}:c=stereo:exprs=0|0"
       # Do audio sync to timestamps with a maximum stretch/squeeze rate of 1%
       # Use first_pts to trim (or pad) audio to start at the correct sample
       # Set flags=res to force resampler to be used to workaround a bug in ffmpeg 4.4 where it
       # inserts extra frames with bad timestamps when starting the resampler on-demand.
-      FFMPEG_ARESAMPLE = "aresample=async=#{(SAMPLE_RATE / 100).round}:first_pts=0:flags=res".freeze
-      FFMPEG_AFORMAT = "aformat=sample_fmts=s16:sample_rates=#{SAMPLE_RATE}:channel_layouts=stereo".freeze
+      FFMPEG_ARESAMPLE = "aresample=async=#{(SAMPLE_RATE / 100).round}:first_pts=0:flags=res"
+      FFMPEG_AFORMAT = "aformat=sample_fmts=s16:sample_rates=#{SAMPLE_RATE}:channel_layouts=stereo"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 26
- 32, Remove the redundant .freeze calls on the string constants
FFMPEG_AEVALSRC, FFMPEG_ARESAMPLE, and FFMPEG_AFORMAT since the file has
frozen_string_literal: true; update the declarations to use plain string
literals (keeping interpolation of SAMPLE_RATE intact) so the constants remain
frozen by the magic comment but without unnecessary .freeze calls.

67-69: Confusing variable naming in iteration.

The variable names are misleading: entry holds an index value (from entries_i), not an entry object, and edl holds the iteration index, not an EDL. Consider renaming for clarity.

♻️ Suggested rename
-          entries_i.each_with_index do |entry, edl|
-            entries << edls[edl][entry]
+          entries_i.each_with_index do |entry_i, edl_i|
+            entries << edls[edl_i][entry_i]
           end
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 67
- 69, The loop variable names in the entries_i.each_with_index block are
misleading: change the parameters from |entry, edl| to descriptive names like
|entry_index, edl_index| (or |entry_idx, edl_idx|) and update the body to use
those names (entries << edls[edl_index][entry_index]) so it's clear that
entries_i provides an index and edl is the loop index; keep references to
entries_i, entries, and edls and only rename the block parameters and their
usages.

328-328: Float equality comparison may be unreliable.

Comparing floats with != can produce unexpected results due to floating-point precision. Since speed is calculated as a ratio of durations, it may not exactly equal 1.0 even when logically intended to.

Consider using a tolerance-based comparison or ensuring speed remains exactly 1.0 when unmodified.

♻️ Suggested fix using tolerance
-              line << "atempo=#{speed},atrim=start=#{ms_to_s(audio_data[:timestamp])}," if speed != 1.0
+              line << "atempo=#{speed},atrim=start=#{ms_to_s(audio_data[:timestamp])}," unless (speed - 1.0).abs < 0.0001
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` at line 328, The
float comparison "speed != 1.0" is fragile; change it to a tolerance-based check
(e.g., use an EPSILON like 1e-6 and test (speed - 1.0).abs > EPSILON) or ensure
'speed' is normalized to exactly 1.0 when unmodified before this line; update
the condition that builds the audio filter string (the expression that appends
"atempo=#{speed},atrim=...") to use that tolerance check and, if normalizing,
set 'speed = 1.0' when the ratio is effectively 1.0. Ensure you reference the
local variable 'speed' and the ms_to_s(audio_data[:timestamp]) usage so the new
condition controls appending the atempo/atrim fragment.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Around line 118-121: Update the mistaken comment above the loop that removes
deleted audio entries: change "Remove deleted videos" to "Remove deleted audios"
(or "Remove deleted audio entries") so it accurately reflects the code within
the del_audios.each block that rejects entries from merged_entry[:audios]; do
not modify logic in del_audios, merged_entry, or the block itself—only update
the comment text.

---

Nitpick comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Around line 417-420: Remove the trailing comma from the debug call to satisfy
RuboCop styling: locate the BigBlueButton.logger.debug invocation that logs
"Processing gap [#{gap_start}ms, #{gap_end}ms) in EDL entry #{i}
(timestamp=#{entry[:timestamp]}ms)" and remove the trailing comma after the
final argument so the method call has no extraneous comma.
- Around line 26-32: Remove the redundant .freeze calls on the string constants
FFMPEG_AEVALSRC, FFMPEG_ARESAMPLE, and FFMPEG_AFORMAT since the file has
frozen_string_literal: true; update the declarations to use plain string
literals (keeping interpolation of SAMPLE_RATE intact) so the constants remain
frozen by the magic comment but without unnecessary .freeze calls.
- Around line 67-69: The loop variable names in the entries_i.each_with_index
block are misleading: change the parameters from |entry, edl| to descriptive
names like |entry_index, edl_index| (or |entry_idx, edl_idx|) and update the
body to use those names (entries << edls[edl_index][entry_index]) so it's clear
that entries_i provides an index and edl is the loop index; keep references to
entries_i, entries, and edls and only rename the block parameters and their
usages.
- Line 328: The float comparison "speed != 1.0" is fragile; change it to a
tolerance-based check (e.g., use an EPSILON like 1e-6 and test (speed - 1.0).abs
> EPSILON) or ensure 'speed' is normalized to exactly 1.0 when unmodified before
this line; update the condition that builds the audio filter string (the
expression that appends "atempo=#{speed},atrim=...") to use that tolerance check
and, if normalizing, set 'speed = 1.0' when the ratio is effectively 1.0. Ensure
you reference the local variable 'speed' and the ms_to_s(audio_data[:timestamp])
usage so the new condition controls appending the atempo/atrim fragment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7724a6c4-af05-440d-8af1-9f8efba9e71a

📥 Commits

Reviewing files that changed from the base of the PR and between 1f7e559 and a39a90f.

📒 Files selected for processing (1)
  • record-and-playback/core/lib/recordandplayback/edl/audio.rb

@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
6.9% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@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.

🧹 Nitpick comments (2)
record-and-playback/core/lib/recordandplayback/edl/audio.rb (2)

26-32: Consider removing redundant .freeze on interpolated strings.

With frozen_string_literal: true at the top of the file, all string literals (including those with interpolation) are automatically frozen. The explicit .freeze calls are redundant but harmless.

♻️ Proposed fix
-      FFMPEG_AEVALSRC = "aevalsrc=s=#{SAMPLE_RATE}:c=stereo:exprs=0|0".freeze
+      FFMPEG_AEVALSRC = "aevalsrc=s=#{SAMPLE_RATE}:c=stereo:exprs=0|0"
       # Do audio sync to timestamps with a maximum stretch/squeeze rate of 1%
       # Use first_pts to trim (or pad) audio to start at the correct sample
       # Set flags=res to force resampler to be used to workaround a bug in ffmpeg 4.4 where it
       # inserts extra frames with bad timestamps when starting the resampler on-demand.
-      FFMPEG_ARESAMPLE = "aresample=async=#{(SAMPLE_RATE / 100).round}:first_pts=0:flags=res".freeze
-      FFMPEG_AFORMAT = "aformat=sample_fmts=s16:sample_rates=#{SAMPLE_RATE}:channel_layouts=stereo".freeze
+      FFMPEG_ARESAMPLE = "aresample=async=#{(SAMPLE_RATE / 100).round}:first_pts=0:flags=res"
+      FFMPEG_AFORMAT = "aformat=sample_fmts=s16:sample_rates=#{SAMPLE_RATE}:channel_layouts=stereo"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 26
- 32, The three constants FFMPEG_AEVALSRC, FFMPEG_ARESAMPLE, and FFMPEG_AFORMAT
use explicit .freeze on interpolated string literals even though
frozen_string_literal: true makes them immutable; remove the redundant .freeze
calls from those constant assignments and keep the string literals as-is so they
remain frozen by the file-level directive.

55-136: High cognitive complexity – consider extracting helper methods.

SonarCloud flags this method at complexity 23 (allowed 15). While the merge logic is correct, extracting smaller helper methods would improve readability and testability:

  • find_next_entry(edls, entries_i) – returns the entry with the lowest timestamp
  • compute_audio_changes(prev_entry, next_entry) – returns added/removed audios

Also, the variable naming on lines 67-68 is confusing—entry actually holds an index value:

entries_i.each_with_index do |entry, edl|  # 'entry' is an index, not an entry object
  entries << edls[edl][entry]
end

Consider renaming to entry_index or idx for clarity.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb` around lines 55
- 136, The merge method in RecordAndPlayback::EDL::Audio is too complex; extract
small helpers to reduce cognitive complexity: implement find_next_entry(edls,
entries_i) to return [next_edl_index, next_entry],
compute_audio_changes(prev_entry, next_entry) to return [add_audios,
del_audios], and a helper to build_or_update_merged_entry(merged_edl,
next_entry, offset) to encapsulate the new-entry creation and timestamp offset
logic; also rename the block parameters in entries_i.each_with_index from
|entry, edl| to |entry_index, edl| (or |idx, edl|) when building entries so the
variable meaning is clear, then replace the inlined logic in merge with calls to
these helpers to keep merge focused and under the complexity threshold.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@record-and-playback/core/lib/recordandplayback/edl/audio.rb`:
- Around line 26-32: The three constants FFMPEG_AEVALSRC, FFMPEG_ARESAMPLE, and
FFMPEG_AFORMAT use explicit .freeze on interpolated string literals even though
frozen_string_literal: true makes them immutable; remove the redundant .freeze
calls from those constant assignments and keep the string literals as-is so they
remain frozen by the file-level directive.
- Around line 55-136: The merge method in RecordAndPlayback::EDL::Audio is too
complex; extract small helpers to reduce cognitive complexity: implement
find_next_entry(edls, entries_i) to return [next_edl_index, next_entry],
compute_audio_changes(prev_entry, next_entry) to return [add_audios,
del_audios], and a helper to build_or_update_merged_entry(merged_edl,
next_entry, offset) to encapsulate the new-entry creation and timestamp offset
logic; also rename the block parameters in entries_i.each_with_index from
|entry, edl| to |entry_index, edl| (or |idx, edl|) when building entries so the
variable meaning is clear, then replace the inlined logic in merge with calls to
these helpers to keep merge focused and under the complexity threshold.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6c37c4c2-3abe-48c0-bb05-375844c728dd

📥 Commits

Reviewing files that changed from the base of the PR and between a39a90f and c46a06c.

📒 Files selected for processing (1)
  • record-and-playback/core/lib/recordandplayback/edl/audio.rb

@github-actions

Copy link
Copy Markdown

✅ Automated tests have passed!

@antobinary
antobinary changed the base branch from v3.0.x-release to v3.0.x-develop March 23, 2026 16:56
@antobinary
antobinary merged commit 1a63169 into bigbluebutton:v3.0.x-develop Mar 23, 2026
31 of 32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants