FFmpeg Bitrate Stats
Simple script for calculating bitrate statistics using FFmpeg.
Note: Previous versions installed a ffmpeg_bitrate_stats executable. To harmonize it with other tools, now the executable is called ffmpeg-bitrate-stats . Please ensure you remove the old executable (e.g. run which ffmpeg_bitrate_stats and remove the file).
Requirements
- Python 3.8 or higher
- FFmpeg:
- download a static build from their website
- put the ffprobe executable in your $PATH
Installation
pip3 install ffmpeg_bitrate_stats
Or clone this repository, then run the tool with python -m ffmpeg_bitrate_stats
Usage
The script outputs a bunch of bitrate statistics, including aggregations for pre-defined windows. These windows can either be time-based or GOP-based (for video streams). When choosing a time-based window, you can specify the size of the chunks in seconds.
Output is to STDOUT so you can redirect that to a file or another script.
usage: __main__.py [-h] [-n] [-v] [-s ] [-a ] [-c CHUNK_SIZE] [-of ] [-p] [-pw PLOT_WIDTH] [-ph PLOT_HEIGHT] input ffmpeg_bitrate_stats v0.4.3 positional arguments: input input file options: -h, --help show this help message and exit -n, --dry-run Do not run command, just show what would be done (default: False) -v, --verbose Show verbose output (default: False) -s , --stream-type Stream type to analyze (default: video) -a , --aggregation Window for aggregating statistics, either time-based (per-second) or per GOP (default: time) -c CHUNK_SIZE, --chunk-size CHUNK_SIZE Custom aggregation window size in seconds (default: 1.0) -of , --output-format output in which format (default: json) -p, --plot Plot the bitrate over time (to STDERR) (default: False) -pw PLOT_WIDTH, --plot-width PLOT_WIDTH Plot width (default: 70) -ph PLOT_HEIGHT, --plot-height PLOT_HEIGHT Plot height (default: 18)
Output
The output can be JSON, which includes individual fields for each chunk, or CSV, which repeats each line for each chunk. The CSV adheres to the “tidy” data concept, so it’s a little redundant.
Rates are given in kilobit per second, using SI prefixes (i.e., kilo = 1000).
Explanation of the fields:
- input_file : Path to the input file
- stream_type : Type of stream used (video, audio)
- avg_fps : Average FPS (number of frames divided by duration)
- num_frames : Number of frames
- avg_bitrate : Average bitrate
- avg_bitrate_over_chunks : Average bitrate calculated over the chunks
- max_bitrate : Maximum bitrate calculated over the chunks
- min_bitrate : Minimum bitrate calculated over the chunks
- max_bitrate_factor : Relation between peak and average
- bitrate_per_chunk : Individual bitrates for each chunk
- aggregation : Type of aggregation used
- chunk_size : Size of the chunk (when aggregation is «time»)
- duration : Total duration of the stream. It is the sum of all frame durations, where each frame’s duration is either based on duration_time field in ffmpeg, or the difference between the current and previous frame’s PTS.
ffmpeg-bitrate-stats -a -c -of json BigBuckBunny.mp4
➜ ffmpeg-bitrate-stats -a time -c 30 -of csv BigBuckBunny.mp4 input_file,chunk_index,stream_type,avg_fps,num_frames,avg_bitrate,avg_bitrate_over_chunks,max_bitrate,min_bitrate,max_bitrate_factor,bitrate_per_chunk,aggregation,chunk_size,duration BigBuckBunny.mp4,0,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,8960.89,time,30.0,634.517 BigBuckBunny.mp4,1,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,8036.678,time,30.0,634.517 BigBuckBunny.mp4,2,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,6099.959,time,30.0,634.517 BigBuckBunny.mp4,3,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,4247.879,time,30.0,634.517 BigBuckBunny.mp4,4,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,7276.979,time,30.0,634.517 BigBuckBunny.mp4,5,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,5738.383,time,30.0,634.517 BigBuckBunny.mp4,6,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,7740.339,time,30.0,634.517 BigBuckBunny.mp4,7,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,7881.705,time,30.0,634.517 BigBuckBunny.mp4,8,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,7572.594,time,30.0,634.517 BigBuckBunny.mp4,9,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,8387.719,time,30.0,634.517 BigBuckBunny.mp4,10,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,9634.343,time,30.0,634.517 BigBuckBunny.mp4,11,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,9939.488,time,30.0,634.517 BigBuckBunny.mp4,12,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,9365.104,time,30.0,634.517 BigBuckBunny.mp4,13,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,5061.071,time,30.0,634.517 BigBuckBunny.mp4,14,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,14565.117,time,30.0,634.517 BigBuckBunny.mp4,15,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,9725.483,time,30.0,634.517 BigBuckBunny.mp4,16,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,4573.873,time,30.0,634.517 BigBuckBunny.mp4,17,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,7765.041,time,30.0,634.517 BigBuckBunny.mp4,18,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,9796.135,time,30.0,634.517 BigBuckBunny.mp4,19,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,12524.024,time,30.0,634.517 BigBuckBunny.mp4,20,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,3876.533,time,30.0,634.517 BigBuckBunny.mp4,21,video,60.002,38072,8002.859,7849.263,14565.117,3876.533,1.82,3914.455,time,30.0,634.517
Plotting
To enable plots, pass the -p or —plot flag. This will plot the bitrate over time to STDERR. You can redirect this to a file, or pipe it to another program. Or you can disable STDOUT output with >/dev/null to only see the plot:
ffmpeg-bitrate-stats -a -c -p BigBuckBunny.mp4 >/dev/null
This might output a plot like this:
API
The program exposes an API that you can use yourself:
For more usage please read the docs.
License
ffmpeg_bitrate_stats, Copyright (c) 2019-2023 Werner Robitza
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
audio-metadata¶
audio-metadata is a library for reading and, in the future, writing audio metadata.
Getting Started¶
Install audio-metadata with pip.
$ pip install -U audio-metadata
Overview¶
The goals of audio-metadata are to provide a nice API and good UX while keeping the codebase as clean and simple as possible.
Features and functionality that set it apart:
- Uses the Python standard load(s)/dump(s) API.
- Can load filepaths, os.PathLike objects, file-like objects, and bytes-like objects.
- Some common libraries shadow the representation of a dict and/or dict methods but do not behave like a dict.
- Supports attribute-style access that can be mixed with dict key-subscription.
- This includes humanized representations of certain values like filesize, bitrate, duration, and sample rate.
>>> import audio_metadata >>> metadata = audio_metadata.load('05 - Heart of Hearts.flac') >>> metadata 'filepath': '05 - Heart of Hearts.flac', 'filesize': '44.23 MiB', 'pictures': [], 'seektable': , 'streaminfo': 'bit_depth': 16, 'bitrate': '1022 Kbps', 'channels': 2, 'duration': '06:03', 'md5': '3ae700893d099a5d281a5d8db7847671', 'sample_rate': '44.1 KHz', >)>, 'tags': 'album': ['Myth Takes'], 'artist': ['. '], 'bpm': ['119'], 'date': ['2007'], 'genre': ['Dance Punk'], 'title': ['Heart of Hearts'], 'tracknumber': ['05'], >)>, >)> >>> metadata['streaminfo'] 'bit_depth': 16, 'bitrate': '1022 Kbps', 'channels': 2, 'duration': '06:03', 'md5': '3ae700893d099a5d281a5d8db7847671', 'sample_rate': '44.1 KHz', >)> >>> metadata.streaminfo.bitrate 1022134.0362995076 >>> metadata.streaminfo['duration'] 362.9066666666667 >>> metadata['streaminfo'].sample_rate 44100
Как я могу извлечь метаданные и информацию о битрейте из аудио / видео файла в Python
То, что я хотел бы сделать, это получить метаданные из аудио- или видеофайлов и сохранить их в записи базы данных, пока единственный способ сделать это, похоже, сохранить AVCONV в файл, используя подпроцесс. Откройте вызов, затем прочитайте этот файл, есть ли библиотеки, которые могут сделать это, чтобы сохранить некоторые шаги? Я не мог найти способ сделать это с помощью Pydub или PySox. Вот мой упрощенный код для начинающих, который я использовал, который работает, и помещает биттрейт, продолжительность и т.д. В переменную audio_info и метаданные в метаданные. Выход OGG работал иначе, чем в других форматах, которые я тестировал (это была тонна видео и аудио!).
try: p = subprocess.Popen(["avconv" , "-i" , music_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() retcode = p.wait() except IOError,e: pass extension = uploaded_music_file[-3:] if "ogg" not in [err , extension]: if "Metadata:" in err: list = err.split("Metadata:") holder = list[1].split("Duration:") metadata = holder[0] audio_info = holder[1].replace("At least one output file must be specified","") print metadata print audio_info else: list = err.split("Duration:") audio_info = list[1].replace("At least one output file must be specified","") print "No Metadata" print audio_info else: list = err.split("Duration:") if "Metadata:" in list[1]: data = list[1].split("Metadata:") metadata = data[1].replace("At least one output file must be specified","") audio_info = data[0] print metadata print audio_info else: audio_info = list[1].replace("At least one output file must be specified","") print "No Metadata" print audio_info if (audio_info): print "AUDIO INFO:" cursor.execute("UPDATE songDB SET audio_info = %s WHERE ,[ audio_info , song_id ] ) if (metadata): print "METADATA:" cursor.execute("songDB pack_song SET metadata = %s WHERE ,[ metadata , song_id ] )