from streamer import Streamer, is_alive
import subprocess
import time
import sys
import os


class FileRadio(Streamer):
    REST_PATH = 'sample'

    def __init__(self, path):
        super().__init__()
        self.path = path
        self.basename = os.path.basename(self.path)
        self.name, self.ext = os.path.splitext(self.basename)

    def _stream_thread(self):
        self.playback = subprocess.Popen(
            [
                '/usr/bin/ffmpeg',
                '-re',                      # http://trac.ffmpeg.org/wiki/StreamingGuide#The-reflag
                '-stream_loop', '-1',       # Loop the stream indefinitely
                '-i', self.path,
                '-c', 'copy',
                '-f', 'rtsp',
                self.stream_address('localhost')
            ],
            stdin=subprocess.PIPE,
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

        while self.run:
            if not is_alive(self.playback):
                print('Playback failed, aborting stream.', file=sys.stderr)
                break
            time.sleep(0.1)

        self.run = False

        self.playback.kill()
        self.playback.wait()
        self.playback = None



if __name__ == '__main__':
    fr = FileRadio('./data/sampleaudio/taunt.mp3')
    fr.start_stream()

    while True:
        time.sleep(1)
