improve treatment of multi-line replies, ignore empty lines
[python/dscho.git] / Demo / sgi / video / statit.py
blobb0c1782927729370dfdb0065e256c7db9fe6b115
1 import sys
2 from time import millitimer
4 def main():
5 filename = 'film2.video'
6 if sys.argv[1:]: filename = sys.argv[1]
7 f = open(filename, 'r')
9 line = f.readline()
10 w, h = eval(line[:-1])
11 w2, h2 = w/2, h/2
12 size = w2 * h2
14 data = data2 = t = t0 = t1 = None
15 nframes = 0
16 t0 = millitimer()
17 while 1:
18 line = f.readline()
19 if not line: break
20 t = eval(line[:-1])
21 data = None
22 data = f.read(size)
23 if len(data) <> size:
24 raise EOFError
25 dostat(w2, h2, data)
26 nframes = nframes+1
27 t1 = millitimer()
29 t = 0.001 * (t1-t0)
30 fps = 0.1 * int(10*nframes/t)
31 print nframes, 'frames in', t, 'sec. =', fps, 'frames/sec.'
33 def dostat(w, h, data):
34 print
35 stat3(w, h, data)
37 # Statistic op 1: frequencies of byte values
38 def stat1(w, h, data):
39 bins = [0]*256
40 for c in data:
41 i = ord(c)
42 bins[i] = bins[i]+1
43 prbins(bins)
45 def prbins(bins):
46 import string
47 s = ''
48 tot = 0
49 for i in range(256):
50 tot = tot + bins[i]
51 s = s + string.rjust(`bins[i]`, 4)
52 if len(s) >= 4*16:
53 print s, string.rjust(`tot`, 7)
54 s = ''
55 tot = 0
57 # Statistic op 2: run lengths
58 def stat2(w, h, data):
59 runs = []
60 for y in range(h):
61 count, value = 0, ord(data[y*w])
62 for c in data[y*w : y*w+w]:
63 i = ord(c)
64 if i <> value:
65 runs.append(count, value)
66 count, value = 0, i
67 count = count+1
68 runs.append(count, value)
69 print len(runs), 'runs =', 0.1 * (10*w*h/len(runs)), 'bytes/run'
71 # Statistic op 3: frequencies of byte differences
72 def stat3(w, h, data):
73 bins = [0]*256
74 prev = 0
75 for c in data:
76 i = ord(c)
77 delta = divmod(i-prev, 256)[1]
78 prev = i
79 bins[delta] = bins[delta]+1
80 prbins(bins)
82 # Try packing
83 def packblock(w, h, data):
84 res = ''
85 for y in range(h):
86 res = res + packline(data[y*w : y*w+w])
87 return res
89 def packline(line):
90 bytes = []
91 for c in line:
92 bytes.append(ord(c))
93 prev = bytes[0]
94 i, n = 1, len(bytes)
95 while i < n:
96 for pack in (0, 2, 4, 8):
97 if pack == 0:
98 lo, hi = 0, 0
99 else:
100 hi = pow(2, pack-1)-1
101 lo = -hi-1
102 p = prev
103 j = i
104 count = 0
105 while j < n:
106 x = bytes[j]
107 delta = byte(x-p)
108 if not lo <= delta <= hi:
109 break
110 p = x
111 j = j+1
113 def byte(x): return divmod(x, 256)[1]
115 main()