Repository navigation
fix(recording): Address A/V sync issues, glitches on cuts, ffmpeg memory usage (audio) - #24776
Conversation
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.
WalkthroughDeskshare 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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
📒 Files selected for processing (6)
record-and-playback/core/lib/recordandplayback/edl/audio.rbrecord-and-playback/core/lib/recordandplayback/edl/media_utils.rbrecord-and-playback/core/lib/recordandplayback/generators/audio_processor.rbrecord-and-playback/presentation/scripts/process/presentation.rbrecord-and-playback/screenshare/scripts/process/screenshare.rbrecord-and-playback/video/scripts/process/video.rb
There was a problem hiding this comment.
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
.eachto create an enumerator, then calling.none?and.sizebefore iterating with.nextworks 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
📒 Files selected for processing (2)
record-and-playback/core/lib/recordandplayback/edl/audio.rbrecord-and-playback/core/lib/recordandplayback/edl/media_utils.rb
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (1)
88-90: Preferchompoverchomp!for stable log values.On Line 89,
line.chomp!can returnnilwhen 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
📒 Files selected for processing (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb
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.
There was a problem hiding this comment.
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-8comment is unnecessary since Ruby 2.0+ defaults to UTF-8. Consider replacing it with# frozen_string_literal: truefor 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
📒 Files selected for processing (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb
There was a problem hiding this comment.
🧹 Nitpick comments (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb (1)
1-1: Optional: modernize file header comment.
# encoding: UTF-8is unnecessary on modern Ruby; consider replacing it with# frozen_string_literal: trueto 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
📒 Files selected for processing (1)
record-and-playback/core/lib/recordandplayback/edl/media_utils.rb
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
record-and-playback/core/lib/recordandplayback/edl/audio.rbrecord-and-playback/core/lib/recordandplayback/edl/media_utils.rbrecord-and-playback/core/lib/recordandplayback/generators/audio_processor.rb
|
@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. |
There was a problem hiding this comment.
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.0may be unreliable due to floating-point precision. In this context the risk is low sincespeedis either the literal1.0default 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.0001Or 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
📒 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.
There was a problem hiding this comment.
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.freezecalls withfrozen_string_literal: true.Since
frozen_string_literal: trueis enabled at the top of the file, string literals are automatically frozen. The explicit.freezecalls 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:
entryholds an index value (fromentries_i), not an entry object, andedlholds 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. Sincespeedis calculated as a ratio of durations, it may not exactly equal1.0even when logically intended to.Consider using a tolerance-based comparison or ensuring
speedremains exactly1.0when 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
📒 Files selected for processing (1)
record-and-playback/core/lib/recordandplayback/edl/audio.rb
|
There was a problem hiding this comment.
🧹 Nitpick comments (2)
record-and-playback/core/lib/recordandplayback/edl/audio.rb (2)
26-32: Consider removing redundant.freezeon interpolated strings.With
frozen_string_literal: trueat the top of the file, all string literals (including those with interpolation) are automatically frozen. The explicit.freezecalls 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 timestampcompute_audio_changes(prev_entry, next_entry)– returns added/removed audiosAlso, the variable naming on lines 67-68 is confusing—
entryactually holds an index value:entries_i.each_with_index do |entry, edl| # 'entry' is an index, not an entry object entries << edls[edl][entry] endConsider renaming to
entry_indexoridxfor 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
📒 Files selected for processing (1)
record-and-playback/core/lib/recordandplayback/edl/audio.rb
✅ Automated tests have passed! |
1a63169
into
bigbluebutton:v3.0.x-develop


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
aresamplefilter.The
start_ptsfeature of thearesamplefilter 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
aresamplefilter 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: