Switch from output seeking to combined input seeking and output seeking to accelerate extracting small segments from huge files #729
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Without this change, seeking inside a huge file gets slower the further you seek. E.g., if you want to have a small AudioSegment with 100 seconds starting from 7000 seconds, it may take up to 5 seconds to extract the segment. With this change, it takes less than a second!
I had the idea of trimming start and end positions with:
But this took surprisingly long!
From analysing the command line I realized, that AudioSegment.from_file() was first specifying the input file and then the seek parameters:
But when reading about the seek parameter for FFMPEG I understood from "https://trac.ffmpeg.org/wiki/Seeking", that actually:
As of FFmpeg 2.1, when transcoding with ffmpeg (i.e. not stream copying), -ss is now also "frame-accurate" even when used as an input option...
So I tried instead the following command:
... and the video file was processed incredibly much faster!
When the pull request first ran through a test with an mp3 file failed:
test_partial_load_start_second_and_duration_equals_cropped_mp3_audio_segment
The reason was that input seeking is not accurate for encoded streams! So I had to add some margin in the input seeking. I tried to calculate the maximum required margin based on the properties of the stream. Let me know, if it makes sense for you as well.
The approximate margin needed is ~144 ms.
At the end, we still need to seek the output stream, so the ffmpeg command would be