Source

VPlayer / source_phonon.py

from time import sleep

from PyQt4 import QtCore

from vplayer.bufferer import Buffer
from vplayer.logger import log

class Source(QtCore.QIODevice):
    def __init__(self, track):
        QtCore.QIODevice.__init__(self)
        self.track = track
        self.buf = Buffer(track)
        self.buf.start()
        self.position = 0

    def atEnd(self):
        self.wait_for_buffer()
        return self.buf.length == self.pos

    def size(self):
        self.wait_for_buffer()
        return long(self.buf.length)

    def readData(self, maxsize):
        need = self.position + maxsize
        if need > self.buf.length:
            need = self.buf.length
        self.wait_for_buffer(need)
        if self.position < len(self.buf.data):
            data = self.buf.data[self.position : self.position + maxsize]
        else:
            data = bytes()
        self.position += len(data)
        return data

    def writeData(*args):
        return False

    def seek(self, pos):
        QtCore.QIODevice.seek(self, pos)
        self.wait_for_buffer()
        if pos > self.buf.pos:
            log.debug('Seek over downloaded range - not seeking')
            return False
        self.wait_for_buffer(pos)
        self.position = pos
        return True

    def isSequential(self):
        return False

    def wait_for_buffer(self, pos = 0):
        while not self.buf.length and not self.buf.failed:
            sleep(0.01)
        if pos:
            while self.buf.pos < pos and not self.buf.failed:
                sleep(0.01)
        if self.buf.failed:
            log.error('Buffer failed')

    def pos(self):
        return self.position

    def reset(self):
        self.position = 0
        return True

    def stop(self):
        self.buf.stop()
        while self.buf.isRunning():
            sleep(0.05)