Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
CSE5300/playback_buffer.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
57 lines (50 sloc)
1.68 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import time | |
import threading | |
class PlaybackBuffer: | |
def __init__(self, buffer_size, debug=False): | |
self.segments = [] | |
self.buffer_size = buffer_size | |
self.buffer = 0 # Number of seconds in buffer | |
self.current_rate = 0 | |
self.lock = threading.Lock() | |
self.debug = debug | |
def start(self): | |
t = threading.Thread(target=PlaybackBuffer.run_forever, args=(self,)) | |
t.setDaemon(True) | |
t.start() | |
def _run_forever(self): | |
interval = 0.5 | |
while True: | |
time.sleep(interval) | |
self.lock.acquire() | |
if self.buffer > 0: | |
self.buffer = self.buffer - 0.5 | |
self.debug_print("Drain buffer %f" % self.buffer) | |
self.lock.release() | |
def run_forever(self): | |
try: | |
self._run_forever() | |
except Exception as e: | |
print '----- error in buffer -----' | |
print e | |
import traceback | |
traceback.print_exc() | |
sys.stdout.flush() | |
# Assume available_bytes is checked before adding | |
def add_four_second_segment(self, nbytes_four_second): | |
self.lock.acquire() | |
self.buffer = self.buffer + 4 # Each buffer element is a 4 second chunk | |
self.debug_print("Add buffer %f" % self.buffer) | |
self.lock.release() | |
def available_bytes(self): | |
available = 0 | |
self.lock.acquire() | |
if (self.buffer <= self.buffer_size): # Buffer contains 240 seconds of video play | |
available = 1 | |
self.lock.release() | |
return available | |
def debug_print(self, msg): | |
if self.debug: | |
print msg | |
sys.stdout.flush() |