Some fixing to hacks/analog.py.
[dcpomatic.git] / hacks / analog.py
index 473913de987872988185a000705edd3f62ff7dd9..fa12460141b46c8bc0be45e539761e5d9b9659a1 100644 (file)
@@ -1,4 +1,7 @@
 #!/usr/bin/python
+#
+# Analyse a DCP-o-matic log file to extract various information.
+#
 
 import sys
 import time
@@ -10,6 +13,8 @@ parser.add_argument('log_file')
 parser.add_argument('-q', '--queue', help='plot queue size', action='store_true')
 parser.add_argument('-e', '--encoder-threads', help='plot encoder thread activity', action='store_true')
 parser.add_argument('-f', '--plot-first-encoder', help='plot more detailed activity of the first encoder thread', action='store_true')
+parser.add_argument('-s', '--fps-stats', help='frames-per-second stats', action='store_true')
+parser.add_argument('--encoder-stats', help='encoder thread activity stats', action='store_true')
 parser.add_argument('--dump-first-encoder', help='dump activity of the first encoder thread', action='store_true')
 parser.add_argument('--from', help='time in seconds to start at', type=int, dest='from_time')
 parser.add_argument('--to', help='time in seconds to stop at', type=int, dest='to_time')
@@ -22,8 +27,9 @@ def find_nth(haystack, needle, n):
         n -= 1
     return start
 
+# Representation of time in seconds and microseconds
 class Time:
-    def __init__(self, s, m = 0):
+    def __init__(self, s = 0, m = 0):
         self.seconds = s
         self.microseconds = m
 
@@ -33,6 +39,14 @@ class Time:
     def float_seconds(self):
         return self.seconds + self.microseconds / 1000000.0
 
+    def __iadd__(self, x):
+        self.microseconds += x.microseconds
+        self.seconds += x.seconds
+        if self.microseconds >= 1000000:
+            self.microseconds -= 1000000
+            self.seconds += 1
+        return self
+
     def __sub__(self, x):
         m = self.microseconds - x.microseconds
         if m < 0:
@@ -41,14 +55,22 @@ class Time:
             return Time(self.seconds - x.seconds, m)
 
 queue_size = []
+general_events = []
+encoder_threads = []
 encoder_thread_events = dict()
 
 def add_encoder_thread_event(thread, time, event):
+    global encoder_threads
     global encoder_thread_events
-    if thread in encoder_thread_events:
-        encoder_thread_events[thread].append((time, event))
-    else:
+    if not thread in encoder_threads:
+        encoder_threads.append(thread)
         encoder_thread_events[thread] = [(time, event)]
+    else:
+        encoder_thread_events[thread].append((time, event))
+
+def add_general_event(time, event):
+    global general_events
+    general_events.append((time, event))
 
 f = open(args.log_file)
 start = None
@@ -57,49 +79,50 @@ while True:
     if l == '':
         break
 
-    l = l.strip()
-    p = l.split()
+    p = l.strip().split()
 
     if len(p) == 0:
         continue
 
     if len(p[0].split(':')) == 2:
-        # s:us timestamp
-        x = p[0].split(':')
-        T = Time(int(x[0]), int(x[1]))
-        message = l[l.find(' ')+1:]
+        # s:us timestamp: LOG_TIMING
+        t = p[0].split(':')
+        T = Time(int(t[0]), int(t[1]))
+        p = l.split()
+        message = p[1]
+        values = {}
+        for i in range(2, len(p)):
+            x = p[i].split('=')
+            values[x[0]] = x[1]
     else:
-        # Date/time timestamp
+        # Date/time timestamp: other LOG_*
         s = find_nth(l, ':', 3)
         T = Time(time.mktime(time.strptime(l[:s])))
         message = l[s+2:]
 
+    # T is elapsed time since the first log message
     if start is None:
         start = T
     else:
         T = T - start
 
-    thread = None
-    if message.startswith('['):
-        thread = message.split()[0][1:-1]
-        message = message[message.find(' ')+1:]
-
-    if message.startswith('adding to queue of '):
-        queue_size.append((T, int(message.split()[4])))
-    elif message.startswith('encoder thread sleeps'):
-        add_encoder_thread_event(thread, T, 'sleep')
-    elif message.startswith('encoder thread wakes'):
-        add_encoder_thread_event(thread, T, 'wake')
-    elif message.startswith('encoder thread begins local encode'):
-        add_encoder_thread_event(thread, T, 'begin_encode')
-    elif message.startswith('MagickImageProxy begins read and decode'):
-        add_encoder_thread_event(thread, T, 'magick_begin_decode')
-    elif message.startswith('MagickImageProxy completes read and decode'):
-        add_encoder_thread_event(thread, T, 'magick_end_decode')
-    elif message.startswith('encoder thread finishes local encode'):
-        add_encoder_thread_event(thread, T, 'end_encode')
+    # Not-so-human-readable log messages (LOG_TIMING)
+    if message == 'add-frame-to-queue':
+        queue_size.append((T, values['queue']))
+    elif message in ['encoder-sleep', 'encoder-wake', 'start-local-encode', 'finish-local-encode', 'start-remote-send', 'finish-remote-send', 'start-remote-encode-and-receive', 'finish-remote-encode-and-receive']:
+        add_encoder_thread_event(values['thread'], T, message)
+    # Human-readable log message (other LOG_*)
+    elif message.startswith('Finished locally-encoded'):
+        add_general_event(T, 'end_local_encode')
+    elif message.startswith('Finished remotely-encoded'):
+        add_general_event(T, 'end_remote_encode')
+    elif message.startswith('Transcode job starting'):
+        add_general_event(T, 'begin_transcode')
+    elif message.startswith('Transcode job completed successfully'):
+        add_general_event(T, 'end_transcode')
 
 if args.queue:
+    # Plot queue size against time; queue_size contains times and queue sizes
     plt.figure()
     x = []
     y = []
@@ -109,7 +132,12 @@ if args.queue:
 
     plt.plot(x, y)
     plt.show()
+
 elif args.encoder_threads:
+    # Plot the things that are happening in each encoder thread with time
+    # y=0 thread is sleeping
+    # y=1 thread is awake
+    # y=2 thread is encoding
     plt.figure()
     N = len(encoder_thread_events)
     n = 1
@@ -134,18 +162,14 @@ elif args.encoder_threads:
                 y.append(2)
             elif e[1] == 'end_encode':
                 y.append(1)
-            elif e[1] == 'magick_begin_decode':
-                y.append(3)
-            elif e[1] == 'magick_end_decode':
-                y.append(2)
 
             previous = y[-1]
 
         plt.plot(x, y)
         n += 1
-        break
 
     plt.show()
+
 elif args.plot_first_encoder:
     plt.figure()
     N = len(encoder_thread_events)
@@ -154,7 +178,7 @@ elif args.plot_first_encoder:
 
     N = 6
     n = 1
-    for t in ['sleep', 'wake', 'begin_encode', 'magick_begin_decode', 'magick_end_decode', 'end_encode']:
+    for t in ['sleep', 'wake', 'begin_encode', 'end_encode']:
         plt.subplot(N, 1, n)
         x = []
         y = []
@@ -170,15 +194,79 @@ elif args.plot_first_encoder:
                 y.append(0)
                 y.append(1)
                 y.append(0)
-                
+
         plt.plot(x, y)
         plt.title(t)
         n += 1
 
     plt.show()
+
 elif args.dump_first_encoder:
     events = encoder_thread_events.itervalues().next()
     last = 0
     for e in events:
         print e[0].float_seconds(), (e[0].float_seconds() - last), e[1]
         last = e[0].float_seconds()
+
+elif args.fps_stats:
+    local = 0
+    remote = 0
+    start = None
+    end = None
+    for e in general_events:
+        if e[1] == 'begin_transcode':
+            start = e[0]
+        elif e[1] == 'end_transcode':
+            end = e[0]
+        elif e[1] == 'end_local_encode':
+            local += 1
+        elif e[1] == 'end_remote_encode':
+            remote += 1
+
+    if end == None:
+        print 'Job did not appear to end'
+        sys.exit(1)
+
+    duration = end - start
+
+    print 'Job ran for %fs' % duration.float_seconds()
+    print '%d local and %d remote' % (local, remote)
+    print '%.2f fps local and %.2f fps remote' % (local / duration.float_seconds(), remote / duration.float_seconds())
+
+elif args.encoder_stats:
+    # Broad stats on what encoder threads spent their time doing
+    for t in encoder_threads:
+        last = None
+        asleep = Time()
+        encoding = Time()
+        sending = Time()
+        remote_encoding_and_receiving = Time()
+        wakes = 0
+        for e in encoder_thread_events[t]:
+            if e[1] not in ['encoder-sleep', 'encoder-wake', 'start-remote-send', 'finish-remote-send',
+                            'start-remote-encode-and-receive', 'finish-remote-encode-and-receive']:
+                continue
+
+            if last is not None:
+                if last[1] == 'encoder-sleep':
+                    asleep += e[0] - last[0]
+                elif last[1] == 'encoder-wake':
+                    wakes += 1
+                    encoding += e[0] - last[0]
+                elif last[1] == 'start-remote-send':
+                    sending += e[0] - last[0]
+                elif last[1] == 'start-remote-encode-and-receive':
+                    remote_encoding_and_receiving += e[0] - last[0]
+
+            last = e
+
+        print '-- Encoder thread %s' % t
+        print '\tAwoken %d times' % wakes
+        total = asleep.float_seconds() + encoding.float_seconds() + sending.float_seconds() + remote_encoding_and_receiving.float_seconds()
+        if total == 0:
+            continue
+        print '\tAsleep: %s (%.2f%%)' % (asleep, asleep.float_seconds() * 100 / total)
+        print '\tEncoding: %s (%.2f%%)' % (encoding, encoding.float_seconds() * 100 / total)
+        print '\tSending: %s (%.2f%%)' % (sending, sending.float_seconds() * 100 / total)
+        print '\tRemote encoding / receiving: %s (%.2f%%)' % (remote_encoding_and_receiving, remote_encoding_and_receiving.float_seconds() * 100 / total)
+        print ''