title: How to extract the bitrate and other statistics of a video file with Python
body: <p>I am trying to extract the prevailing bitrate of a video file (e.g. <strong>.mkv</strong> file containing a movie) at a regular sampling interval of between 1-10 seconds under conditions of normal playback. Kind of like you may see in <strong>vlc</strong>, during playback of the file in the statistics window. </p>
  
  <p>Can anyone suggest the best way to bootstrap the coding of such an analyser? Is there a library that provides an API to such information that people know of? Perhaps a Python wrapper for <strong>ffmpeg</strong> or equivalent tool that processes video files and can thereby extract such statistics. </p>
  
  <p>What I am really aiming for is a <strong>CSV</strong> format file containing the seconds offset and the average or actual bitrate in KiB/s at that offset into the asset. </p>
  
  <p><strong>Update:</strong> </p>
  
  <p>I built pyffmpeg and wrote the following spike: </p>
  
  <pre><code>import pyffmpeg
  
  reader = pyffmpeg.FFMpegReader(False)
  reader.open("/home/mark/Videos/BBB.m2ts", pyffmpeg.TS_VIDEO)
  tracks=reader.get_tracks()
  
  # Called for each frame
  def obs(f):
    pass
  
  tracks[0].set_observer(obs)
  reader.run()
  </code></pre>
  
  <p>But observing frame information (f) in the callback does not appear to give me any hooks to calculate per second bitrates. In fact bitrate calculations within pyffmpeg are measured across the entire file (filesize / duration) and so the treatment within the library is very superficial. Clearly its focus is on extract i-frames and other frame/GOP specific work. </p>