Fix three PyChecker-detected gotchas.
[python/dscho.git] / Demo / sgi / video / syncaudio.py
blobfd09d2879c6580dc1792dc5de08ede9e2e4a84f2
1 import AL
2 import al
3 import sys
4 import vtime
5 import socket
6 import time
9 SLEEPTIME = 500 # 500 ms sleeps
10 SAMPLEFREQ = 16000 # 16Khz samples
11 SAMPLERATE = AL.RATE_16000
12 NEEDBUFFERED = SAMPLEFREQ # Buffer 1 second of sound
13 BUFFERSIZE = NEEDBUFFERED*4 # setqueuesize() par for 2 second sound
15 AVSYNCPORT = 10000 # Port for time syncing
16 AVCTLPORT = 10001 # Port for record start/stop
18 def main():
19 if len(sys.argv) <> 3:
20 print 'Usage: ', sys.argv[0], 'videohostname soundfile'
21 sys.exit(1)
23 ofile = open(sys.argv[2], 'w')
25 globaltime = vtime.VTime().init(0,sys.argv[1],AVSYNCPORT)
27 ctl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
28 ctl.bind((socket.gethostname(),AVCTLPORT))
30 inp = openmic()
32 out = 0 # Open aiff file
34 while 1:
35 if mainloop(None, ctl, inp, out, globaltime):
36 break
37 if mainloop(ofile, ctl, inp, out, globaltime):
38 break
39 pass # Close aiff file
40 sys.exit(0)
42 def openmic():
43 conf = al.newconfig()
44 conf.setqueuesize(BUFFERSIZE)
45 conf.setwidth(AL.SAMPLE_16)
46 conf.setchannels(AL.MONO)
47 return al.openport('micr','r',conf)
49 def mainloop(ofile, ctl, inp, out, globaltime):
51 # Wait for sync packet, keeping 1-2 seconds of sound in the
52 # buffer
54 totsamps = 0
55 totbytes = 0
56 starttime = time.millitimer()
57 while 1:
58 time.millisleep(SLEEPTIME)
59 if ctl.avail():
60 break
61 nsamples = inp.getfilled()-NEEDBUFFERED
62 if nsamples>0:
63 data = inp.readsamps(nsamples)
64 totsamps = totsamps + nsamples
65 totbytes = totbytes + len(data)
66 if ofile <> None:
67 ofile.write(data)
69 # Compute his starttime and the timestamp of the first byte in the
70 # buffer. Discard all buffered data upto his starttime
72 startstop,histime = eval(ctl.recv(100))
73 if (ofile == None and startstop == 0) or \
74 (ofile <> None and startstop == 1):
75 print 'Sync error: saving=',save,' request=',startstop
76 sys.exit(1)
77 filllevel = inp.getfilled()
78 filltime = time.millitimer()
79 filltime = filltime - filllevel / (SAMPLEFREQ/1000)
80 starttime = globaltime.his2mine(histime)
81 nsamples = starttime - filltime
82 if nsamples < 0:
83 print 'Start/stop signal came too late'
84 sys.exit(1)
85 nsamples = nsamples * (SAMPLEFREQ / 1000)
86 data = inp.readsamps(nsamples)
87 totsamps = totsamps + nsamples
88 totbytes = totbytes + len(data)
89 print 'Time: ', time.millitimer()-starttime, ', Bytes: ', totbytes, ', Samples: ', totsamps
90 if ofile <> None:
91 ofile.write(data)
92 return (startstop == 2)
94 main()