-
Notifications
You must be signed in to change notification settings - Fork 14
/
webrtc-internals.js
2139 lines (1858 loc) · 67.3 KB
/
webrtc-internals.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var USER_MEDIA_TAB_ID = 'user-media-tab-id';
var tabView = null;
var ssrcInfoManager = null;
var peerConnectionUpdateTable = null;
var statsTable = null;
var dumpCreator = null;
/** A map from peer connection id to the PeerConnectionRecord. */
var peerConnectionDataStore = {};
/** A list of getUserMedia requests. */
var userMediaRequests = [];
/** A simple class to store the updates and stats data for a peer connection. */
var PeerConnectionRecord = (function() {
/** @constructor */
function PeerConnectionRecord() {
/** @private */
this.record_ = {
constraints: {},
rtcConfiguration: [],
stats: {},
updateLog: [],
url: '',
};
};
PeerConnectionRecord.prototype = {
/** @override */
toJSON: function() {
return this.record_;
},
/**
* Adds the initilization info of the peer connection.
* @param {string} url The URL of the web page owning the peer connection.
* @param {Array} rtcConfiguration
* @param {!Object} constraints Media constraints.
*/
initialize: function(url, rtcConfiguration, constraints) {
this.record_.url = url;
this.record_.rtcConfiguration = rtcConfiguration;
this.record_.constraints = constraints;
},
/**
* @param {string} dataSeriesId The TimelineDataSeries identifier.
* @return {!TimelineDataSeries}
*/
getDataSeries: function(dataSeriesId) {
return this.record_.stats[dataSeriesId];
},
/**
* @param {string} dataSeriesId The TimelineDataSeries identifier.
* @param {!TimelineDataSeries} dataSeries The TimelineDataSeries to set to.
*/
setDataSeries: function(dataSeriesId, dataSeries) {
this.record_.stats[dataSeriesId] = dataSeries;
},
/**
* @param {!Object} update The object contains keys "time", "type", and
* "value".
*/
addUpdate: function(update) {
var time = new Date(parseFloat(update.time));
this.record_.updateLog.push({
time: time.toLocaleString(),
type: update.type,
value: update.value,
});
},
};
return PeerConnectionRecord;
})();
// The maximum number of data points bufferred for each stats. Old data points
// will be shifted out when the buffer is full.
var MAX_STATS_DATA_POINT_BUFFER_SIZE = 1000;
// // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* A TabView provides the ability to create tabs and switch between tabs. It's
* responsible for creating the DOM and managing the visibility of each tab.
* The first added tab is active by default and the others hidden.
*/
var TabView = (function() {
'use strict';
/**
* @constructor
* @param {Element} root The root DOM element containing the tabs.
*/
function TabView(root) {
this.root_ = root;
this.ACTIVE_TAB_HEAD_CLASS_ = 'active-tab-head';
this.ACTIVE_TAB_BODY_CLASS_ = 'active-tab-body';
this.TAB_HEAD_CLASS_ = 'tab-head';
this.TAB_BODY_CLASS_ = 'tab-body';
/**
* A mapping for an id to the tab elements.
* @type {!Object<!TabDom>}
* @private
*/
this.tabElements_ = {};
this.headBar_ = null;
this.activeTabId_ = null;
this.initializeHeadBar_();
}
// Creates a simple object containing the tab head and body elements.
function TabDom(h, b) {
this.head = h;
this.body = b;
}
TabView.prototype = {
/**
* Adds a tab with the specified id and title.
* @param {string} id
* @param {string} title
* @return {!Element} The tab body element.
*/
addTab: function(id, title) {
if (this.tabElements_[id])
throw 'Tab already exists: ' + id;
var head = document.createElement('span');
head.className = this.TAB_HEAD_CLASS_;
head.textContent = title;
head.title = title;
this.headBar_.appendChild(head);
head.addEventListener('click', this.switchTab_.bind(this, id));
var body = document.createElement('div');
body.className = this.TAB_BODY_CLASS_;
body.id = id;
this.root_.appendChild(body);
this.tabElements_[id] = new TabDom(head, body);
if (!this.activeTabId_) {
this.switchTab_(id);
}
return this.tabElements_[id].body;
},
/** Removes the tab. @param {string} id */
removeTab: function(id) {
if (!this.tabElements_[id])
return;
this.tabElements_[id].head.parentNode.removeChild(
this.tabElements_[id].head);
this.tabElements_[id].body.parentNode.removeChild(
this.tabElements_[id].body);
delete this.tabElements_[id];
if (this.activeTabId_ == id) {
this.switchTab_(Object.keys(this.tabElements_)[0]);
}
},
/**
* Switches the specified tab into view.
*
* @param {string} activeId The id the of the tab that should be switched to
* active state.
* @private
*/
switchTab_: function(activeId) {
if (this.activeTabId_ && this.tabElements_[this.activeTabId_]) {
this.tabElements_[this.activeTabId_].body.classList.remove(
this.ACTIVE_TAB_BODY_CLASS_);
this.tabElements_[this.activeTabId_].head.classList.remove(
this.ACTIVE_TAB_HEAD_CLASS_);
}
this.activeTabId_ = activeId;
if (this.tabElements_[activeId]) {
this.tabElements_[activeId].body.classList.add(
this.ACTIVE_TAB_BODY_CLASS_);
this.tabElements_[activeId].head.classList.add(
this.ACTIVE_TAB_HEAD_CLASS_);
}
},
/** Initializes the bar containing the tab heads. */
initializeHeadBar_: function() {
this.headBar_ = document.createElement('div');
this.root_.appendChild(this.headBar_);
this.headBar_.style.textAlign = 'center';
},
};
return TabView;
})();
// // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* A TimelineDataSeries collects an ordered series of (time, value) pairs,
* and converts them to graph points. It also keeps track of its color and
* current visibility state.
* It keeps MAX_STATS_DATA_POINT_BUFFER_SIZE data points at most. Old data
* points will be dropped when it reaches this size.
*/
var TimelineDataSeries = (function() {
'use strict';
/**
* @constructor
*/
function TimelineDataSeries() {
// List of DataPoints in chronological order.
this.dataPoints_ = [];
// Default color. Should always be overridden prior to display.
this.color_ = 'red';
// Whether or not the data series should be drawn.
this.isVisible_ = true;
this.cacheStartTime_ = null;
this.cacheStepSize_ = 0;
this.cacheValues_ = [];
}
TimelineDataSeries.prototype = {
/**
* @override
*/
toJSON: function() {
if (this.dataPoints_.length < 1)
return {};
var values = [];
for (var i = 0; i < this.dataPoints_.length; ++i) {
values.push(this.dataPoints_[i].value);
}
return {
startTime: this.dataPoints_[0].time,
endTime: this.dataPoints_[this.dataPoints_.length - 1].time,
values: JSON.stringify(values),
};
},
/**
* Adds a DataPoint to |this| with the specified time and value.
* DataPoints are assumed to be received in chronological order.
*/
addPoint: function(timeTicks, value) {
var time = new Date(timeTicks);
this.dataPoints_.push(new DataPoint(time, value));
if (this.dataPoints_.length > MAX_STATS_DATA_POINT_BUFFER_SIZE)
this.dataPoints_.shift();
},
isVisible: function() {
return this.isVisible_;
},
show: function(isVisible) {
this.isVisible_ = isVisible;
},
getColor: function() {
return this.color_;
},
setColor: function(color) {
this.color_ = color;
},
getCount: function() {
return this.dataPoints_.length;
},
/**
* Returns a list containing the values of the data series at |count|
* points, starting at |startTime|, and |stepSize| milliseconds apart.
* Caches values, so showing/hiding individual data series is fast.
*/
getValues: function(startTime, stepSize, count) {
// Use cached values, if we can.
if (this.cacheStartTime_ == startTime &&
this.cacheStepSize_ == stepSize &&
this.cacheValues_.length == count) {
return this.cacheValues_;
}
// Do all the work.
this.cacheValues_ = this.getValuesInternal_(startTime, stepSize, count);
this.cacheStartTime_ = startTime;
this.cacheStepSize_ = stepSize;
return this.cacheValues_;
},
/**
* Returns the cached |values| in the specified time period.
*/
getValuesInternal_: function(startTime, stepSize, count) {
var values = [];
var nextPoint = 0;
var currentValue = 0;
var time = startTime;
for (var i = 0; i < count; ++i) {
while (nextPoint < this.dataPoints_.length &&
this.dataPoints_[nextPoint].time < time) {
currentValue = this.dataPoints_[nextPoint].value;
++nextPoint;
}
values[i] = currentValue;
time += stepSize;
}
return values;
}
};
/**
* A single point in a data series. Each point has a time, in the form of
* milliseconds since the Unix epoch, and a numeric value.
* @constructor
*/
function DataPoint(time, value) {
this.time = time;
this.value = value;
}
return TimelineDataSeries;
})();
// // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Get the ssrc if |report| is an ssrc report.
*
* @param {!Object} report The object contains id, type, and stats, where stats
* is the object containing timestamp and values, which is an array of
* strings, whose even index entry is the name of the stat, and the odd
* index entry is the value.
* @return {?string} The ssrc.
*/
function GetSsrcFromReport(report) {
if (report.type != 'ssrc') {
console.warn("Trying to get ssrc from non-ssrc report.");
return null;
}
// If the 'ssrc' name-value pair exists, return the value; otherwise, return
// the report id.
// The 'ssrc' name-value pair only exists in an upcoming Libjingle change. Old
// versions use id to refer to the ssrc.
//
// TODO(jiayl): remove the fallback to id once the Libjingle change is rolled
// to Chrome.
if (report.stats && report.stats.values) {
for (var i = 0; i < report.stats.values.length - 1; i += 2) {
if (report.stats.values[i] == 'ssrc') {
return report.stats.values[i + 1];
}
}
}
return report.id;
};
/**
* SsrcInfoManager stores the ssrc stream info extracted from SDP.
*/
var SsrcInfoManager = (function() {
'use strict';
/**
* @constructor
*/
function SsrcInfoManager() {
/**
* Map from ssrc id to an object containing all the stream properties.
* @type {!Object<!Object<string>>}
* @private
*/
this.streamInfoContainer_ = {};
/**
* The string separating attibutes in an SDP.
* @type {string}
* @const
* @private
*/
this.ATTRIBUTE_SEPARATOR_ = /[\r,\n]/;
/**
* The regex separating fields within an ssrc description.
* @type {RegExp}
* @const
* @private
*/
this.FIELD_SEPARATOR_REGEX_ = / .*:/;
/**
* The prefix string of an ssrc description.
* @type {string}
* @const
* @private
*/
this.SSRC_ATTRIBUTE_PREFIX_ = 'a=ssrc:';
/**
* The className of the ssrc info parent element.
* @type {string}
* @const
*/
this.SSRC_INFO_BLOCK_CLASS = 'ssrc-info-block';
}
SsrcInfoManager.prototype = {
/**
* Extracts the stream information from |sdp| and saves it.
* For example:
* a=ssrc:1234 msid:abcd
* a=ssrc:1234 label:hello
*
* @param {string} sdp The SDP string.
*/
addSsrcStreamInfo: function(sdp) {
var attributes = sdp.split(this.ATTRIBUTE_SEPARATOR_);
for (var i = 0; i < attributes.length; ++i) {
// Check if this is a ssrc attribute.
if (attributes[i].indexOf(this.SSRC_ATTRIBUTE_PREFIX_) != 0)
continue;
var nextFieldIndex = attributes[i].search(this.FIELD_SEPARATOR_REGEX_);
if (nextFieldIndex == -1)
continue;
var ssrc = attributes[i].substring(this.SSRC_ATTRIBUTE_PREFIX_.length,
nextFieldIndex);
if (!this.streamInfoContainer_[ssrc])
this.streamInfoContainer_[ssrc] = {};
// Make |rest| starting at the next field.
var rest = attributes[i].substring(nextFieldIndex + 1);
var name, value;
while (rest.length > 0) {
nextFieldIndex = rest.search(this.FIELD_SEPARATOR_REGEX_);
if (nextFieldIndex == -1)
nextFieldIndex = rest.length;
// The field name is the string before the colon.
name = rest.substring(0, rest.indexOf(':'));
// The field value is from after the colon to the next field.
value = rest.substring(rest.indexOf(':') + 1, nextFieldIndex);
this.streamInfoContainer_[ssrc][name] = value;
// Move |rest| to the start of the next field.
rest = rest.substring(nextFieldIndex + 1);
}
}
},
/**
* @param {string} sdp The ssrc id.
* @return {!Object<string>} The object containing the ssrc infomation.
*/
getStreamInfo: function(ssrc) {
return this.streamInfoContainer_[ssrc];
},
/**
* Populate the ssrc information into |parentElement|, each field as a
* DIV element.
*
* @param {!Element} parentElement The parent element for the ssrc info.
* @param {string} ssrc The ssrc id.
*/
populateSsrcInfo: function(parentElement, ssrc) {
if (!this.streamInfoContainer_[ssrc])
return;
parentElement.className = this.SSRC_INFO_BLOCK_CLASS;
var fieldElement;
for (var property in this.streamInfoContainer_[ssrc]) {
fieldElement = document.createElement('div');
parentElement.appendChild(fieldElement);
fieldElement.textContent =
property + ':' + this.streamInfoContainer_[ssrc][property];
}
}
};
return SsrcInfoManager;
})();
// // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// This file contains helper methods to draw the stats timeline graphs.
// Each graph represents a series of stats report for a PeerConnection,
// e.g. 1234-0-ssrc-abcd123-bytesSent is the graph for the series of bytesSent
// for ssrc-abcd123 of PeerConnection 0 in process 1234.
// The graphs are drawn as CANVAS, grouped per report type per PeerConnection.
// Each group has an expand/collapse button and is collapsed initially.
//
// // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* A TimelineGraphView displays a timeline graph on a canvas element.
*/
var TimelineGraphView = (function() {
'use strict';
// Maximum number of labels placed vertically along the sides of the graph.
var MAX_VERTICAL_LABELS = 6;
// Vertical spacing between labels and between the graph and labels.
var LABEL_VERTICAL_SPACING = 4;
// Horizontal spacing between vertically placed labels and the edges of the
// graph.
var LABEL_HORIZONTAL_SPACING = 3;
// Horizintal spacing between two horitonally placed labels along the bottom
// of the graph.
var LABEL_LABEL_HORIZONTAL_SPACING = 25;
// Length of ticks, in pixels, next to y-axis labels. The x-axis only has
// one set of labels, so it can use lines instead.
var Y_AXIS_TICK_LENGTH = 10;
var GRID_COLOR = '#CCC';
var TEXT_COLOR = '#000';
var BACKGROUND_COLOR = '#FFF';
var MAX_DECIMAL_PRECISION = 2;
/**
* @constructor
*/
function TimelineGraphView(divId, canvasId) {
this.scrollbar_ = {position_: 0, range_: 0};
this.graphDiv_ = $(divId);
this.canvas_ = $(canvasId);
// Set the range and scale of the graph. Times are in milliseconds since
// the Unix epoch.
// All measurements we have must be after this time.
this.startTime_ = 0;
// The current rightmost position of the graph is always at most this.
this.endTime_ = 1;
this.graph_ = null;
// Horizontal scale factor, in terms of milliseconds per pixel.
this.scale_ = 1000;
// Initialize the scrollbar.
this.updateScrollbarRange_(true);
}
TimelineGraphView.prototype = {
setScale: function(scale) {
this.scale_ = scale;
},
// Returns the total length of the graph, in pixels.
getLength_: function() {
var timeRange = this.endTime_ - this.startTime_;
// Math.floor is used to ignore the last partial area, of length less
// than this.scale_.
return Math.floor(timeRange / this.scale_);
},
/**
* Returns true if the graph is scrolled all the way to the right.
*/
graphScrolledToRightEdge_: function() {
return this.scrollbar_.position_ == this.scrollbar_.range_;
},
/**
* Update the range of the scrollbar. If |resetPosition| is true, also
* sets the slider to point at the rightmost position and triggers a
* repaint.
*/
updateScrollbarRange_: function(resetPosition) {
var scrollbarRange = this.getLength_() - this.canvas_.width;
if (scrollbarRange < 0)
scrollbarRange = 0;
// If we've decreased the range to less than the current scroll position,
// we need to move the scroll position.
if (this.scrollbar_.position_ > scrollbarRange)
resetPosition = true;
this.scrollbar_.range_ = scrollbarRange;
if (resetPosition) {
this.scrollbar_.position_ = scrollbarRange;
this.repaint();
}
},
/**
* Sets the date range displayed on the graph, switches to the default
* scale factor, and moves the scrollbar all the way to the right.
*/
setDateRange: function(startDate, endDate) {
this.startTime_ = startDate.getTime();
this.endTime_ = endDate.getTime();
// Safety check.
if (this.endTime_ <= this.startTime_)
this.startTime_ = this.endTime_ - 1;
this.updateScrollbarRange_(true);
},
/**
* Updates the end time at the right of the graph to be the current time.
* Specifically, updates the scrollbar's range, and if the scrollbar is
* all the way to the right, keeps it all the way to the right. Otherwise,
* leaves the view as-is and doesn't redraw anything.
*/
updateEndDate: function(opt_date) {
this.endTime_ = opt_date || (new Date()).getTime();
this.updateScrollbarRange_(this.graphScrolledToRightEdge_());
},
getStartDate: function() {
return new Date(this.startTime_);
},
/**
* Replaces the current TimelineDataSeries with |dataSeries|.
*/
setDataSeries: function(dataSeries) {
// Simply recreates the Graph.
this.graph_ = new Graph();
for (var i = 0; i < dataSeries.length; ++i)
this.graph_.addDataSeries(dataSeries[i]);
this.repaint();
},
/**
* Adds |dataSeries| to the current graph.
*/
addDataSeries: function(dataSeries) {
if (!this.graph_)
this.graph_ = new Graph();
this.graph_.addDataSeries(dataSeries);
this.repaint();
},
/**
* Draws the graph on |canvas_|.
*/
repaint: function() {
if (this.canvas_.offsetParent === null) {
return; // dont repaint graphs that are not visible.
}
this.repaintTimerRunning_ = false;
var width = this.canvas_.width;
var height = this.canvas_.height;
var context = this.canvas_.getContext('2d');
// Clear the canvas.
context.fillStyle = BACKGROUND_COLOR;
context.fillRect(0, 0, width, height);
// Try to get font height in pixels. Needed for layout.
var fontHeightString = context.font.match(/([0-9]+)px/)[1];
var fontHeight = parseInt(fontHeightString);
// Safety check, to avoid drawing anything too ugly.
if (fontHeightString.length == 0 || fontHeight <= 0 ||
fontHeight * 4 > height || width < 50) {
return;
}
// Save current transformation matrix so we can restore it later.
context.save();
// The center of an HTML canvas pixel is technically at (0.5, 0.5). This
// makes near straight lines look bad, due to anti-aliasing. This
// translation reduces the problem a little.
context.translate(0.5, 0.5);
// Figure out what time values to display.
var position = this.scrollbar_.position_;
// If the entire time range is being displayed, align the right edge of
// the graph to the end of the time range.
if (this.scrollbar_.range_ == 0)
position = this.getLength_() - this.canvas_.width;
var visibleStartTime = this.startTime_ + position * this.scale_;
// Make space at the bottom of the graph for the time labels, and then
// draw the labels.
var textHeight = height;
height -= fontHeight + LABEL_VERTICAL_SPACING;
this.drawTimeLabels(context, width, height, textHeight, visibleStartTime);
// Draw outline of the main graph area.
context.strokeStyle = GRID_COLOR;
context.strokeRect(0, 0, width - 1, height - 1);
if (this.graph_) {
// Layout graph and have them draw their tick marks.
this.graph_.layout(
width, height, fontHeight, visibleStartTime, this.scale_);
this.graph_.drawTicks(context);
// Draw the lines of all graphs, and then draw their labels.
this.graph_.drawLines(context);
this.graph_.drawLabels(context);
}
// Restore original transformation matrix.
context.restore();
},
/**
* Draw time labels below the graph. Takes in start time as an argument
* since it may not be |startTime_|, when we're displaying the entire
* time range.
*/
drawTimeLabels: function(context, width, height, textHeight, startTime) {
// Draw the labels 1 minute apart.
var timeStep = 1000 * 60;
// Find the time for the first label. This time is a perfect multiple of
// timeStep because of how UTC times work.
var time = Math.ceil(startTime / timeStep) * timeStep;
context.textBaseline = 'bottom';
context.textAlign = 'center';
context.fillStyle = TEXT_COLOR;
context.strokeStyle = GRID_COLOR;
// Draw labels and vertical grid lines.
while (true) {
var x = Math.round((time - startTime) / this.scale_);
if (x >= width)
break;
var text = (new Date(time)).toLocaleTimeString();
context.fillText(text, x, textHeight);
context.beginPath();
context.lineTo(x, 0);
context.lineTo(x, height);
context.stroke();
time += timeStep;
}
},
getDataSeriesCount: function() {
if (this.graph_)
return this.graph_.dataSeries_.length;
return 0;
},
hasDataSeries: function(dataSeries) {
if (this.graph_)
return this.graph_.hasDataSeries(dataSeries);
return false;
},
};
/**
* A Graph is responsible for drawing all the TimelineDataSeries that have
* the same data type. Graphs are responsible for scaling the values, laying
* out labels, and drawing both labels and lines for its data series.
*/
var Graph = (function() {
/**
* @constructor
*/
function Graph() {
this.dataSeries_ = [];
// Cached properties of the graph, set in layout.
this.width_ = 0;
this.height_ = 0;
this.fontHeight_ = 0;
this.startTime_ = 0;
this.scale_ = 0;
// The lowest/highest values adjusted by the vertical label step size
// in the displayed range of the graph. Used for scaling and setting
// labels. Set in layoutLabels.
this.min_ = 0;
this.max_ = 0;
// Cached text of equally spaced labels. Set in layoutLabels.
this.labels_ = [];
}
/**
* A Label is the label at a particular position along the y-axis.
* @constructor
*/
function Label(height, text) {
this.height = height;
this.text = text;
}
Graph.prototype = {
addDataSeries: function(dataSeries) {
this.dataSeries_.push(dataSeries);
},
hasDataSeries: function(dataSeries) {
for (var i = 0; i < this.dataSeries_.length; ++i) {
if (this.dataSeries_[i] == dataSeries)
return true;
}
return false;
},
/**
* Returns a list of all the values that should be displayed for a given
* data series, using the current graph layout.
*/
getValues: function(dataSeries) {
if (!dataSeries.isVisible())
return null;
return dataSeries.getValues(this.startTime_, this.scale_, this.width_);
},
/**
* Updates the graph's layout. In particular, both the max value and
* label positions are updated. Must be called before calling any of the
* drawing functions.
*/
layout: function(width, height, fontHeight, startTime, scale) {
this.width_ = width;
this.height_ = height;
this.fontHeight_ = fontHeight;
this.startTime_ = startTime;
this.scale_ = scale;
// Find largest value.
var max = 0, min = 0;
for (var i = 0; i < this.dataSeries_.length; ++i) {
var values = this.getValues(this.dataSeries_[i]);
if (!values)
continue;
for (var j = 0; j < values.length; ++j) {
if (values[j] > max)
max = values[j];
else if (values[j] < min)
min = values[j];
}
}
this.layoutLabels_(min, max);
},
/**
* Lays out labels and sets |max_|/|min_|, taking the time units into
* consideration. |maxValue| is the actual maximum value, and
* |max_| will be set to the value of the largest label, which
* will be at least |maxValue|. Similar for |min_|.
*/
layoutLabels_: function(minValue, maxValue) {
if (maxValue - minValue < 1024) {
this.layoutLabelsBasic_(minValue, maxValue, MAX_DECIMAL_PRECISION);
return;
}
// Find appropriate units to use.
var units = ['', 'k', 'M', 'G', 'T', 'P'];
// Units to use for labels. 0 is '1', 1 is K, etc.
// We start with 1, and work our way up.
var unit = 1;
minValue /= 1024;
maxValue /= 1024;
while (units[unit + 1] && maxValue - minValue >= 1024) {
minValue /= 1024;
maxValue /= 1024;
++unit;
}
// Calculate labels.
this.layoutLabelsBasic_(minValue, maxValue, MAX_DECIMAL_PRECISION);
// Append units to labels.
for (var i = 0; i < this.labels_.length; ++i)
this.labels_[i] += ' ' + units[unit];
// Convert |min_|/|max_| back to unit '1'.
this.min_ *= Math.pow(1024, unit);
this.max_ *= Math.pow(1024, unit);
},
/**
* Same as layoutLabels_, but ignores units. |maxDecimalDigits| is the
* maximum number of decimal digits allowed. The minimum allowed
* difference between two adjacent labels is 10^-|maxDecimalDigits|.
*/
layoutLabelsBasic_: function(minValue, maxValue, maxDecimalDigits) {
this.labels_ = [];
var range = maxValue - minValue;
// No labels if the range is 0.
if (range == 0) {
this.min_ = this.max_ = maxValue;
return;
}
// The maximum number of equally spaced labels allowed. |fontHeight_|
// is doubled because the top two labels are both drawn in the same
// gap.
var minLabelSpacing = 2 * this.fontHeight_ + LABEL_VERTICAL_SPACING;
// The + 1 is for the top label.
var maxLabels = 1 + this.height_ / minLabelSpacing;
if (maxLabels < 2) {
maxLabels = 2;
} else if (maxLabels > MAX_VERTICAL_LABELS) {
maxLabels = MAX_VERTICAL_LABELS;
}
// Initial try for step size between conecutive labels.
var stepSize = Math.pow(10, -maxDecimalDigits);
// Number of digits to the right of the decimal of |stepSize|.
// Used for formating label strings.
var stepSizeDecimalDigits = maxDecimalDigits;
// Pick a reasonable step size.
while (true) {
// If we use a step size of |stepSize| between labels, we'll need:
//
// Math.ceil(range / stepSize) + 1
//
// labels. The + 1 is because we need labels at both at 0 and at
// the top of the graph.
// Check if we can use steps of size |stepSize|.
if (Math.ceil(range / stepSize) + 1 <= maxLabels)
break;
// Check |stepSize| * 2.
if (Math.ceil(range / (stepSize * 2)) + 1 <= maxLabels) {
stepSize *= 2;
break;
}
// Check |stepSize| * 5.
if (Math.ceil(range / (stepSize * 5)) + 1 <= maxLabels) {
stepSize *= 5;
break;
}
stepSize *= 10;
if (stepSizeDecimalDigits > 0)
--stepSizeDecimalDigits;
}
// Set the min/max so it's an exact multiple of the chosen step size.
this.max_ = Math.ceil(maxValue / stepSize) * stepSize;
this.min_ = Math.floor(minValue / stepSize) * stepSize;
// Create labels.
for (var label = this.max_; label >= this.min_; label -= stepSize)
this.labels_.push(label.toFixed(stepSizeDecimalDigits));
},
/**
* Draws tick marks for each of the labels in |labels_|.
*/
drawTicks: function(context) {
var x1;
var x2;
x1 = this.width_ - 1;
x2 = this.width_ - 1 - Y_AXIS_TICK_LENGTH;
context.fillStyle = GRID_COLOR;
context.beginPath();
for (var i = 1; i < this.labels_.length - 1; ++i) {
// The rounding is needed to avoid ugly 2-pixel wide anti-aliased
// lines.
var y = Math.round(this.height_ * i / (this.labels_.length - 1));
context.moveTo(x1, y);
context.lineTo(x2, y);