Make analog.py cope with another date/time format.
[dcpomatic.git] / hacks / analog.py
1 #!/usr/bin/python
2 #
3 # Analyse a DCP-o-matic log file to extract various information.
4 #
5
6 import sys
7 import time
8 import argparse
9 import matplotlib.pyplot as plt
10
11 parser = argparse.ArgumentParser()
12 parser.add_argument('log_file')
13 parser.add_argument('-q', '--queue', help='plot queue size', action='store_true')
14 parser.add_argument('-e', '--encoder-threads', help='plot encoder thread activity', action='store_true')
15 parser.add_argument('-f', '--plot-first-encoder', help='plot more detailed activity of the first encoder thread', action='store_true')
16 parser.add_argument('-s', '--fps-stats', help='frames-per-second stats', action='store_true')
17 parser.add_argument('--encoder-stats', help='encoder thread activity stats', action='store_true')
18 parser.add_argument('--dump-first-encoder', help='dump activity of the first encoder thread', action='store_true')
19 parser.add_argument('--from', help='time in seconds to start at', type=int, dest='from_time')
20 parser.add_argument('--to', help='time in seconds to stop at', type=int, dest='to_time')
21 args = parser.parse_args()
22
23 def find_nth(haystack, needle, n):
24     start = haystack.find(needle)
25     while start >= 0 and n > 1:
26         start = haystack.find(needle, start+len(needle))
27         n -= 1
28     return start
29
30 # Representation of time in seconds and microseconds
31 class Time:
32     def __init__(self, s = 0, m = 0):
33         self.seconds = s
34         self.microseconds = m
35
36     def __str__(self):
37         return '%d:%d' % (self.seconds, self.microseconds)
38
39     def float_seconds(self):
40         return self.seconds + self.microseconds / 1000000.0
41
42     def __iadd__(self, x):
43         self.microseconds += x.microseconds
44         self.seconds += x.seconds
45         if self.microseconds >= 1000000:
46             self.microseconds -= 1000000
47             self.seconds += 1
48         return self
49
50     def __sub__(self, x):
51         m = self.microseconds - x.microseconds
52         if m < 0:
53             return Time(self.seconds - x.seconds - 1, m + 1000000)
54         else:
55             return Time(self.seconds - x.seconds, m)
56
57 class EncoderThread:
58     def __init__(self, id):
59         self.id = id
60         self.events = []
61         self.server = None
62
63     def add_event(self, time, message, values):
64         self.events.append((time, message, values))
65
66 queue_size = []
67 general_events = []
68 encoder_threads = []
69
70 def find_encoder_thread(id):
71     global encoder_threads
72     thread = None
73     for t in encoder_threads:
74         if t.id == id:
75             thread = t
76
77     if thread is None:
78         thread = EncoderThread(id)
79         encoder_threads.append(thread)
80
81     return thread
82
83 def add_general_event(time, event):
84     global general_events
85     general_events.append((time, event))
86
87 f = open(args.log_file)
88 start = None
89 while True:
90     l = f.readline()
91     if l == '':
92         break
93
94     p = l.strip().split()
95
96     if len(p) == 0:
97         continue
98
99     if len(p[0].split(':')) == 2:
100         # s:us timestamp: LOG_TIMING
101         t = p[0].split(':')
102         T = Time(int(t[0]), int(t[1]))
103         p = l.split()
104         message = p[1]
105         values = {}
106         for i in range(2, len(p)):
107             x = p[i].split('=')
108             values[x[0]] = x[1]
109     else:
110         # Date/time timestamp: other LOG_*
111         s = find_nth(l, ':', 3)
112         try:
113             T = Time(time.mktime(time.strptime(l[:s])))
114         except:
115             T = Time(time.mktime(time.strptime(l[:s], "%d.%m.%Y %H:%M:%S")))
116         message = l[s+2:]
117
118     # T is elapsed time since the first log message
119     if start is None:
120         start = T
121     else:
122         T = T - start
123
124     # Not-so-human-readable log messages (LOG_TIMING)
125     if message == 'add-frame-to-queue':
126         queue_size.append((T, values['queue']))
127     elif message in ['encoder-sleep', 'encoder-wake', 'start-local-encode', 'finish-local-encode', 'start-remote-send', 'start-remote-encode', 'start-remote-receive', 'finish-remote-receive', 'start-encoder-thread']:
128         find_encoder_thread(values['thread']).add_event(T, message, values)
129     # Human-readable log message (other LOG_*)
130     elif message.startswith('Finished locally-encoded'):
131         add_general_event(T, 'end_local_encode')
132     elif message.startswith('Finished remotely-encoded'):
133         add_general_event(T, 'end_remote_encode')
134     elif message.startswith('Transcode job starting'):
135         add_general_event(T, 'begin_transcode')
136     elif message.startswith('Transcode job completed successfully'):
137         add_general_event(T, 'end_transcode')
138
139 if args.queue:
140     # Plot queue size against time; queue_size contains times and queue sizes
141     plt.figure()
142     x = []
143     y = []
144     for q in queue_size:
145         x.append(q[0].seconds)
146         y.append(q[1])
147
148     plt.plot(x, y)
149     plt.show()
150
151 elif args.encoder_threads:
152     # Plot the things that are happening in each encoder thread with time
153     # y=0 thread is sleeping
154     # y=1 thread is awake
155     # y=2 thread is encoding
156     plt.figure()
157     N = len(encoder_thread_events)
158     n = 1
159     for thread in encoder_threads:
160         plt.subplot(N, 1, n)
161         x = []
162         y = []
163         previous = 0
164         for e in thread.events:
165             if args.from_time is not None and e[0].float_seconds() <= args.from_time:
166                 continue
167             if args.to_time is not None and e[0].float_seconds() >= args.to_time:
168                 continue
169             x.append(e[0].float_seconds())
170             x.append(e[0].float_seconds())
171             y.append(previous)
172             if e[1] == 'sleep':
173                 y.append(0)
174             elif e[1] == 'wake':
175                 y.append(1)
176             elif e[1] == 'begin_encode':
177                 y.append(2)
178             elif e[1] == 'end_encode':
179                 y.append(1)
180
181             previous = y[-1]
182
183         plt.plot(x, y)
184         n += 1
185
186     plt.show()
187
188 elif args.plot_first_encoder:
189     plt.figure()
190     N = len(encoder_threads)
191     n = 1
192     events = encoder_threads[0].events
193
194     N = 6
195     n = 1
196     for t in ['sleep', 'wake', 'begin_encode', 'end_encode']:
197         plt.subplot(N, 1, n)
198         x = []
199         y = []
200         for e in events:
201             if args.from_time is not None and e[0].float_seconds() <= args.from_time:
202                 continue
203             if args.to_time is not None and e[0].float_seconds() >= args.to_time:
204                 continue
205             if e[1] == t:
206                 x.append(e[0].float_seconds())
207                 x.append(e[0].float_seconds())
208                 x.append(e[0].float_seconds())
209                 y.append(0)
210                 y.append(1)
211                 y.append(0)
212
213         plt.plot(x, y)
214         plt.title(t)
215         n += 1
216
217     plt.show()
218
219 elif args.dump_first_encoder:
220     events = encoder_thread_events.itervalues().next()
221     last = 0
222     for e in events:
223         print e[0].float_seconds(), (e[0].float_seconds() - last), e[1]
224         last = e[0].float_seconds()
225
226 elif args.fps_stats:
227     local = 0
228     remote = 0
229     start = None
230     end = None
231     for e in general_events:
232         if e[1] == 'begin_transcode':
233             start = e[0]
234         elif e[1] == 'end_transcode':
235             end = e[0]
236         elif e[1] == 'end_local_encode':
237             local += 1
238         elif e[1] == 'end_remote_encode':
239             remote += 1
240
241     if end == None:
242         print 'Job did not appear to end'
243         sys.exit(1)
244
245     duration = end - start
246
247     print 'Job ran for %fs' % duration.float_seconds()
248     print '%d local and %d remote' % (local, remote)
249     print '%.2f fps local and %.2f fps remote' % (local / duration.float_seconds(), remote / duration.float_seconds())
250
251 elif args.encoder_stats:
252     # Broad stats on what encoder threads spent their time doing
253     for t in encoder_threads:
254         last = None
255         asleep = Time()
256         local_encoding = Time()
257         sending = Time()
258         remote_encoding = Time()
259         receiving = Time()
260         wakes = 0
261         for e in t.events:
262             if last is not None:
263                 if last[1] == 'encoder-sleep':
264                     asleep += e[0] - last[0]
265                 elif last[1] == 'encoder-wake':
266                     wakes += 1
267                 elif last[1] == 'start-local-encode':
268                     local_encoding += e[0] - last[0]
269                 elif last[1] == 'start-remote-send':
270                     sending += e[0] - last[0]
271                 elif last[1] == 'start-remote-encode':
272                     remote_encoding += e[0] - last[0]
273                 elif last[1] == 'start-remote-receive':
274                     receiving += e[0] - last[0]
275                 elif last[1] == 'start-encoder-thread':
276                     find_encoder_thread(last[2]['thread']).server = last[2]['server']
277
278             last = e
279
280         print '-- Encoder thread %s (%s)' % (t.server, t.id)
281         print '\tAwoken %d times' % wakes
282
283         total = asleep.float_seconds() + local_encoding.float_seconds() + sending.float_seconds() + remote_encoding.float_seconds() + receiving.float_seconds()
284         if total == 0:
285             continue
286
287         print '\t%s: %2.f%%' % ('Asleep'.ljust(16), asleep.float_seconds() * 100 / total)
288
289         def print_with_fps(v, name, total, frames):
290             if v.float_seconds() > 1:
291                 print '\t%s: %2.f%% %.2ffps' % (name.ljust(16), v.float_seconds() * 100 / total, frames / v.float_seconds())
292
293         print_with_fps(local_encoding, 'Local encoding', total, wakes)
294         if sending.float_seconds() > 0:
295             print '\t%s: %2.f%%' % ('Sending'.ljust(16), sending.float_seconds() * 100 / total)
296         print_with_fps(remote_encoding, 'Remote encoding', total, wakes)
297         if receiving.float_seconds() > 0:
298             print '\t%s: %2.f%%' % ('Receiving'.ljust(16), receiving.float_seconds() * 100 / total)
299         print ''