#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
 Copyright (C) 2004 jan gerber <j@reboot.fm>

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Library General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
'''

import os
import string
from time import *
from sys import exit
from ogg import OggSyncState, vorbis
from shout import Shout
from types import NoneType
from urllib2 import urlopen
from xmlrpclib import ServerProxy
from math import *
#from random import randint


class shoutogg :
	def __init__(self) :
		self.ogg = OggSyncState()
		self.page = 0
		#self.serial = randint(1,65536)
		self.serial = 1
		self.shout = Shout()
		self.shout.host = '127.0.0.1'
		self.shout.port = 8000
		self.shout.user = 'source'
		self.shout.password = 'hack4me'
		self.shout.mount = '/fallback.ogg'
		self.shout.format = 'vorbis'
		self.shout.protocol = 'http'
		self.shout.open()
	def __call__(self, data) :
		self.ogg.bytesin(data)
		while 1:
				newpage = self.ogg.pageseek()
				if newpage == None :
					break
				if self.page == 0 :
				   	self.page = newpage
				   	continue
				if self.page.serialno != newpage.serialno : self.page.eos = 1
				if newpage.pageno==0 : self.page.eos = 1
				self.page.serialno=self.serial
				if self.page.eos == 1 :
				   if self.serial<65536 : self.serial = self.serial + 1
				   else : self.serial = 0
				self.shout.sync()
				out=self.page.header+self.page.body
				self.shout.send(out)
				self.page=newpage
		return

def fillbuffer(f):
	read = f.read(4096)
	length=len(read)
	return (read,length)

def print_log(string):
	print time(),"\t:",string

xmlrpcurl="http://localhost:8070"
next_url='http://localhost/ogg/test.ogg'
fallback_url='http://localhost/ogg/test.ogg'

so=shoutogg()
server = ServerProxy(xmlrpcurl)
f=urlopen(next_url)
ftotal = 0
timestamp=0
f_tmp=0

print_log("starting up oggstreamer.")
while 1 :
	while 1:
		length = 0
		while length == 0 :
			(read,length) = fillbuffer(f)
			if length == 0:
				f.close()
				f= urlopen(fallback_url)
		ftotal = ftotal + len(read)
		so(read)
	print 'Track end, total %d bytes' % ftotal
	f.close()
