title: Python Video Buffer for streamed video
body: <p>Mu objective is to create a function, given a url and a file path, that will download or buffer 25 MB of a video file (in this case from TiVo) and then launch the video in a player and continue downloading the rest of the video as the video plays.</p>
  
  <p>I found the code <a href="https://stackoverflow.com/questions/10224488/python-script-to-record-online-live-streaming-videos">here</a> to be helpful and it's appears to be a good start. This is my first Python project, so it been a learning process. Here is the code I have so far:</p>
  
  <pre><code>import os
  import sys
  import logging
  import requests as REQ
  from requests.auth import HTTPDigestAuth;
  import datetime as DT
  try:
          import cElementTree as ET
  except ImportError:
          try:
                  import xml.etree.cElementTree as ET
          except ImportError:
                  exit_err("Failed to import cElementTree from any known place");
  
  # Functions
  
  def fetchSelection(url, fp):
          print('Requesting ' + url + '...');
          r = REQ.get(url, auth=HTTPDigestAuth('tivo', mak), verify=False, stream=True);
          print('Fetching your selection...');
          if r.status_code == REQ.codes.ok:
                  print('HTTP Request sent, awaiting response... 200 OK');
                  print('Buffering...');
          else:
                  print('HTTP Request sent, awaiting response... ' + str(r.status_code));
                  print(r.raise_for_status());
                  return;
  
          video_file_size_start = 0;
          video_file_size_end = 1048576 * cacheSize;  # end in CacheSize in  MB
          block_size = 1024;
  
          with open(fp, 'wb') as fd:
                  for chunk in r.iter_content(block_size):
                          video_file_size_start += len(chunk);
                          if video_file_size_start &gt; video_file_size_end:
                                  break;
                          fd.write(chunk);
                          print(str(video_file_size_start/1024/1024) + ' MB / ' + str(video_file_size_end/1024/1024) + ' MB');
                  fd.close();
  
          return;
  </code></pre>
  
  <p>Here is where this code gets used later:</p>
  
  <pre><code>filePath = downloadPath + details[6] + '.tivo';
  fetchSelection(nUrl + '&amp;Format=' + videoFormat, filePath);
  print('Launching player...');
  playerCommand = 'tivodecode -m ' + mak + ' ' + filePath + ' | ';
  playerCommand += 'mplayer -vf pp=lb - cache 32768 -';
  os.system(playerCommand);
  nType = 0;
  </code></pre>
  
  <p>When I run my script, I get the following output:</p>
  
  <pre><code>Requesting http://192.168.1.102:80/download/Adventure%20Time.TiVo?Container=%2FNowPlaying&amp;id=653115&amp;Format=video/x-tivo-mpeg...
  Fetching your selection...
  HTTP Request sent, awaiting response... 503
  Traceback (most recent call last):
    File "test_read_nowPlaying2.py", line 186, in &lt;module&gt;
      fetchSelection(details[1] + '&amp;Format=' + videoFormat, filePath);
    File "test_read_nowPlaying2.py", line 128, in fetchSelection
      print(r.raise_for_status());
    File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 765, in raise_for_status
      raise HTTPError(http_error_msg, response=self)
  requests.exceptions.HTTPError: 503 Server Error: Server Busy
  </code></pre>
  
  <p><strong>EDIT:</strong> I figured out why I was getting the 503 response, I was not calling the right file. I had to request the video format of <code>video/x-tivo-mpeg-ts</code>.</p>
  
  <p>This is a work in progress and I am unsure how to proceed. I also don't know how to continue the download while the player is playing.</p>