You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

414 lines
13 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #!/usr/bin/env python
  2. # Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style license
  5. # that can be found in the LICENSE file in the root of the source
  6. # tree. An additional intellectual property rights grant can be found
  7. # in the file PATENTS. All contributing project authors may
  8. # be found in the AUTHORS file in the root of the source tree.
  9. """Generate graphs for data generated by loopback tests.
  10. Usage examples:
  11. Show end to end time for a single full stack test.
  12. ./full_stack_tests_plot.py -df end_to_end -o 600 --frames 1000 vp9_data.txt
  13. Show simultaneously PSNR and encoded frame size for two different runs of
  14. full stack test. Averaged over a cycle of 200 frames. Used e.g. for
  15. screenshare slide test.
  16. ./full_stack_tests_plot.py -c 200 -df psnr -drf encoded_frame_size \\
  17. before.txt after.txt
  18. Similar to the previous test, but multiple graphs.
  19. ./full_stack_tests_plot.py -c 200 -df psnr vp8.txt vp9.txt --next \\
  20. -c 200 -df sender_time vp8.txt vp9.txt --next \\
  21. -c 200 -df end_to_end vp8.txt vp9.txt
  22. """
  23. import argparse
  24. from collections import defaultdict
  25. import itertools
  26. import sys
  27. import matplotlib.pyplot as plt
  28. import numpy
  29. # Fields
  30. DROPPED = 0
  31. INPUT_TIME = 1 # ms (timestamp)
  32. SEND_TIME = 2 # ms (timestamp)
  33. RECV_TIME = 3 # ms (timestamp)
  34. RENDER_TIME = 4 # ms (timestamp)
  35. ENCODED_FRAME_SIZE = 5 # bytes
  36. PSNR = 6
  37. SSIM = 7
  38. ENCODE_TIME = 8 # ms (time interval)
  39. TOTAL_RAW_FIELDS = 9
  40. SENDER_TIME = TOTAL_RAW_FIELDS + 0
  41. RECEIVER_TIME = TOTAL_RAW_FIELDS + 1
  42. END_TO_END = TOTAL_RAW_FIELDS + 2
  43. RENDERED_DELTA = TOTAL_RAW_FIELDS + 3
  44. FIELD_MASK = 255
  45. # Options
  46. HIDE_DROPPED = 256
  47. RIGHT_Y_AXIS = 512
  48. # internal field id, field name, title
  49. _FIELDS = [
  50. # Raw
  51. (DROPPED, "dropped", "dropped"),
  52. (INPUT_TIME, "input_time_ms", "input time"),
  53. (SEND_TIME, "send_time_ms", "send time"),
  54. (RECV_TIME, "recv_time_ms", "recv time"),
  55. (ENCODED_FRAME_SIZE, "encoded_frame_size", "encoded frame size"),
  56. (PSNR, "psnr", "PSNR"),
  57. (SSIM, "ssim", "SSIM"),
  58. (RENDER_TIME, "render_time_ms", "render time"),
  59. (ENCODE_TIME, "encode_time_ms", "encode time"),
  60. # Auto-generated
  61. (SENDER_TIME, "sender_time", "sender time"),
  62. (RECEIVER_TIME, "receiver_time", "receiver time"),
  63. (END_TO_END, "end_to_end", "end to end"),
  64. (RENDERED_DELTA, "rendered_delta", "rendered delta"),
  65. ]
  66. NAME_TO_ID = {field[1]: field[0] for field in _FIELDS}
  67. ID_TO_TITLE = {field[0]: field[2] for field in _FIELDS}
  68. def FieldArgToId(arg):
  69. if arg == "none":
  70. return None
  71. if arg in NAME_TO_ID:
  72. return NAME_TO_ID[arg]
  73. if arg + "_ms" in NAME_TO_ID:
  74. return NAME_TO_ID[arg + "_ms"]
  75. raise Exception("Unrecognized field name \"{}\"".format(arg))
  76. class PlotLine(object):
  77. """Data for a single graph line."""
  78. def __init__(self, label, values, flags):
  79. self.label = label
  80. self.values = values
  81. self.flags = flags
  82. class Data(object):
  83. """Object representing one full stack test."""
  84. def __init__(self, filename):
  85. self.title = ""
  86. self.length = 0
  87. self.samples = defaultdict(list)
  88. self._ReadSamples(filename)
  89. def _ReadSamples(self, filename):
  90. """Reads graph data from the given file."""
  91. f = open(filename)
  92. it = iter(f)
  93. self.title = it.next().strip()
  94. self.length = int(it.next())
  95. field_names = [name.strip() for name in it.next().split()]
  96. field_ids = [NAME_TO_ID[name] for name in field_names]
  97. for field_id in field_ids:
  98. self.samples[field_id] = [0.0] * self.length
  99. for sample_id in xrange(self.length):
  100. for col, value in enumerate(it.next().split()):
  101. self.samples[field_ids[col]][sample_id] = float(value)
  102. self._SubtractFirstInputTime()
  103. self._GenerateAdditionalData()
  104. f.close()
  105. def _SubtractFirstInputTime(self):
  106. offset = self.samples[INPUT_TIME][0]
  107. for field in [INPUT_TIME, SEND_TIME, RECV_TIME, RENDER_TIME]:
  108. if field in self.samples:
  109. self.samples[field] = [x - offset for x in self.samples[field]]
  110. def _GenerateAdditionalData(self):
  111. """Calculates sender time, receiver time etc. from the raw data."""
  112. s = self.samples
  113. last_render_time = 0
  114. for field_id in [SENDER_TIME, RECEIVER_TIME, END_TO_END, RENDERED_DELTA]:
  115. s[field_id] = [0] * self.length
  116. for k in range(self.length):
  117. s[SENDER_TIME][k] = s[SEND_TIME][k] - s[INPUT_TIME][k]
  118. decoded_time = s[RENDER_TIME][k]
  119. s[RECEIVER_TIME][k] = decoded_time - s[RECV_TIME][k]
  120. s[END_TO_END][k] = decoded_time - s[INPUT_TIME][k]
  121. if not s[DROPPED][k]:
  122. if k > 0:
  123. s[RENDERED_DELTA][k] = decoded_time - last_render_time
  124. last_render_time = decoded_time
  125. def _Hide(self, values):
  126. """
  127. Replaces values for dropped frames with None.
  128. These values are then skipped by the Plot() method.
  129. """
  130. return [None if self.samples[DROPPED][k] else values[k]
  131. for k in range(len(values))]
  132. def AddSamples(self, config, target_lines_list):
  133. """Creates graph lines from the current data set with given config."""
  134. for field in config.fields:
  135. # field is None means the user wants just to skip the color.
  136. if field is None:
  137. target_lines_list.append(None)
  138. continue
  139. field_id = field & FIELD_MASK
  140. values = self.samples[field_id]
  141. if field & HIDE_DROPPED:
  142. values = self._Hide(values)
  143. target_lines_list.append(PlotLine(
  144. self.title + " " + ID_TO_TITLE[field_id],
  145. values, field & ~FIELD_MASK))
  146. def AverageOverCycle(values, length):
  147. """
  148. Returns the list:
  149. [
  150. avg(values[0], values[length], ...),
  151. avg(values[1], values[length + 1], ...),
  152. ...
  153. avg(values[length - 1], values[2 * length - 1], ...),
  154. ]
  155. Skips None values when calculating the average value.
  156. """
  157. total = [0.0] * length
  158. count = [0] * length
  159. for k, val in enumerate(values):
  160. if val is not None:
  161. total[k % length] += val
  162. count[k % length] += 1
  163. result = [0.0] * length
  164. for k in range(length):
  165. result[k] = total[k] / count[k] if count[k] else None
  166. return result
  167. class PlotConfig(object):
  168. """Object representing a single graph."""
  169. def __init__(self, fields, data_list, cycle_length=None, frames=None,
  170. offset=0, output_filename=None, title="Graph"):
  171. self.fields = fields
  172. self.data_list = data_list
  173. self.cycle_length = cycle_length
  174. self.frames = frames
  175. self.offset = offset
  176. self.output_filename = output_filename
  177. self.title = title
  178. def Plot(self, ax1):
  179. lines = []
  180. for data in self.data_list:
  181. if not data:
  182. # Add None lines to skip the colors.
  183. lines.extend([None] * len(self.fields))
  184. else:
  185. data.AddSamples(self, lines)
  186. def _SliceValues(values):
  187. if self.offset:
  188. values = values[self.offset:]
  189. if self.frames:
  190. values = values[:self.frames]
  191. return values
  192. length = None
  193. for line in lines:
  194. if line is None:
  195. continue
  196. line.values = _SliceValues(line.values)
  197. if self.cycle_length:
  198. line.values = AverageOverCycle(line.values, self.cycle_length)
  199. if length is None:
  200. length = len(line.values)
  201. elif length != len(line.values):
  202. raise Exception("All arrays should have the same length!")
  203. ax1.set_xlabel("Frame", fontsize="large")
  204. if any(line.flags & RIGHT_Y_AXIS for line in lines if line):
  205. ax2 = ax1.twinx()
  206. ax2.set_xlabel("Frame", fontsize="large")
  207. else:
  208. ax2 = None
  209. # Have to implement color_cycle manually, due to two scales in a graph.
  210. color_cycle = ["b", "r", "g", "c", "m", "y", "k"]
  211. color_iter = itertools.cycle(color_cycle)
  212. for line in lines:
  213. if not line:
  214. color_iter.next()
  215. continue
  216. if self.cycle_length:
  217. x = numpy.array(range(self.cycle_length))
  218. else:
  219. x = numpy.array(range(self.offset, self.offset + len(line.values)))
  220. y = numpy.array(line.values)
  221. ax = ax2 if line.flags & RIGHT_Y_AXIS else ax1
  222. ax.Plot(x, y, "o-", label=line.label, markersize=3.0, linewidth=1.0,
  223. color=color_iter.next())
  224. ax1.grid(True)
  225. if ax2:
  226. ax1.legend(loc="upper left", shadow=True, fontsize="large")
  227. ax2.legend(loc="upper right", shadow=True, fontsize="large")
  228. else:
  229. ax1.legend(loc="best", shadow=True, fontsize="large")
  230. def LoadFiles(filenames):
  231. result = []
  232. for filename in filenames:
  233. if filename in LoadFiles.cache:
  234. result.append(LoadFiles.cache[filename])
  235. else:
  236. data = Data(filename)
  237. LoadFiles.cache[filename] = data
  238. result.append(data)
  239. return result
  240. LoadFiles.cache = {}
  241. def GetParser():
  242. class CustomAction(argparse.Action):
  243. def __call__(self, parser, namespace, values, option_string=None):
  244. if "ordered_args" not in namespace:
  245. namespace.ordered_args = []
  246. namespace.ordered_args.append((self.dest, values))
  247. parser = argparse.ArgumentParser(
  248. description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  249. parser.add_argument(
  250. "-c", "--cycle_length", nargs=1, action=CustomAction,
  251. type=int, help="Cycle length over which to average the values.")
  252. parser.add_argument(
  253. "-f", "--field", nargs=1, action=CustomAction,
  254. help="Name of the field to show. Use 'none' to skip a color.")
  255. parser.add_argument("-r", "--right", nargs=0, action=CustomAction,
  256. help="Use right Y axis for given field.")
  257. parser.add_argument("-d", "--drop", nargs=0, action=CustomAction,
  258. help="Hide values for dropped frames.")
  259. parser.add_argument("-o", "--offset", nargs=1, action=CustomAction, type=int,
  260. help="Frame offset.")
  261. parser.add_argument("-n", "--next", nargs=0, action=CustomAction,
  262. help="Separator for multiple graphs.")
  263. parser.add_argument(
  264. "--frames", nargs=1, action=CustomAction, type=int,
  265. help="Frame count to show or take into account while averaging.")
  266. parser.add_argument("-t", "--title", nargs=1, action=CustomAction,
  267. help="Title of the graph.")
  268. parser.add_argument(
  269. "-O", "--output_filename", nargs=1, action=CustomAction,
  270. help="Use to save the graph into a file. "
  271. "Otherwise, a window will be shown.")
  272. parser.add_argument(
  273. "files", nargs="+", action=CustomAction,
  274. help="List of text-based files generated by loopback tests.")
  275. return parser
  276. def _PlotConfigFromArgs(args, graph_num):
  277. # Pylint complains about using kwargs, so have to do it this way.
  278. cycle_length = None
  279. frames = None
  280. offset = 0
  281. output_filename = None
  282. title = "Graph"
  283. fields = []
  284. files = []
  285. mask = 0
  286. for key, values in args:
  287. if key == "cycle_length":
  288. cycle_length = values[0]
  289. elif key == "frames":
  290. frames = values[0]
  291. elif key == "offset":
  292. offset = values[0]
  293. elif key == "output_filename":
  294. output_filename = values[0]
  295. elif key == "title":
  296. title = values[0]
  297. elif key == "drop":
  298. mask |= HIDE_DROPPED
  299. elif key == "right":
  300. mask |= RIGHT_Y_AXIS
  301. elif key == "field":
  302. field_id = FieldArgToId(values[0])
  303. fields.append(field_id | mask if field_id is not None else None)
  304. mask = 0 # Reset mask after the field argument.
  305. elif key == "files":
  306. files.extend(values)
  307. if not files:
  308. raise Exception("Missing file argument(s) for graph #{}".format(graph_num))
  309. if not fields:
  310. raise Exception("Missing field argument(s) for graph #{}".format(graph_num))
  311. return PlotConfig(fields, LoadFiles(files), cycle_length=cycle_length,
  312. frames=frames, offset=offset, output_filename=output_filename,
  313. title=title)
  314. def PlotConfigsFromArgs(args):
  315. """Generates plot configs for given command line arguments."""
  316. # The way it works:
  317. # First we detect separators -n/--next and split arguments into groups, one
  318. # for each plot. For each group, we partially parse it with
  319. # argparse.ArgumentParser, modified to remember the order of arguments.
  320. # Then we traverse the argument list and fill the PlotConfig.
  321. args = itertools.groupby(args, lambda x: x in ["-n", "--next"])
  322. prep_args = list(list(group) for match, group in args if not match)
  323. parser = GetParser()
  324. plot_configs = []
  325. for index, raw_args in enumerate(prep_args):
  326. graph_args = parser.parse_args(raw_args).ordered_args
  327. plot_configs.append(_PlotConfigFromArgs(graph_args, index))
  328. return plot_configs
  329. def ShowOrSavePlots(plot_configs):
  330. for config in plot_configs:
  331. fig = plt.figure(figsize=(14.0, 10.0))
  332. ax = fig.add_subPlot(1, 1, 1)
  333. plt.title(config.title)
  334. config.Plot(ax)
  335. if config.output_filename:
  336. print "Saving to", config.output_filename
  337. fig.savefig(config.output_filename)
  338. plt.close(fig)
  339. plt.show()
  340. if __name__ == "__main__":
  341. ShowOrSavePlots(PlotConfigsFromArgs(sys.argv[1:]))