switcher.js
13.2 KB
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
(function(window, document) {
'use strict';
var segmentDuration = 9, // seconds
segmentCount = 100,
duration = segmentDuration * segmentCount,
propagationDelay = 0.5,
runSimulation,
playlistResponse,
player,
runButton,
parameters,
addTimePeriod,
networkTimeline,
timePeriod,
timeline,
displayTimeline;
// mock out the environment and dependencies
videojs.options.flash.swf = '../../node_modules/video.js/dist/video-js/video-js.swf';
videojs.Hls.SegmentParser = function() {
this.getFlvHeader = function() {
return new Uint8Array([]);
};
this.parseSegmentBinaryData = function() {};
this.flushTags = function() {};
this.tagsAvailable = function() {
return false;
};
};
// a dynamic number of time-bandwidth pairs may be defined to drive the simulation
addTimePeriod = document.querySelector('.add-time-period');
networkTimeline = document.querySelector('.network-timeline');
timePeriod = networkTimeline.cloneNode(true);
addTimePeriod.addEventListener('click', function() {
var clone = timePeriod.cloneNode(true),
fragment = document.createDocumentFragment(),
count = networkTimeline.querySelectorAll('input.bandwidth').length,
time = clone.querySelector('.time'),
bandwidth = clone.querySelector('input.bandwidth');
time.name = 'time' + count;
bandwidth.name = 'bandwidth' + count;
while (clone.childNodes.length) {
fragment.appendChild(clone.childNodes[0]);
}
networkTimeline.appendChild(fragment);
});
// collect the simulation parameters
parameters = function() {
var times = Array.prototype.slice.call(document.querySelectorAll('.time')),
bandwidths = document.querySelectorAll('input.bandwidth'),
playlists = Array.prototype.slice.call(document.querySelectorAll('input.bitrate'));
return {
playlists: playlists.map(function(input) {
return +input.value;
}),
bandwidths: times.reduce(function(conditions, time, i) {
return conditions.concat({
time: +time.value,
bandwidth: +bandwidths[i].value
});
}, [])
};
};
// send a mock playlist response
playlistResponse = function(bitrate) {
var i = segmentCount,
response = '#EXTM3U\n';
while (i--) {
response += '#EXTINF:' + segmentDuration + ',\n';
response += bitrate + '-' + (segmentCount - i) + '\n';
}
response += '#EXT-X-ENDLIST\n';
return response;
};
// run the simulation
runSimulation = function(options, done) {
var results = {
bandwidth: [],
effectiveBandwidth: [],
playlists: [],
buffered: [],
options: options
},
bandwidths = options.bandwidths,
fixture = document.getElementById('fixture'),
realSetTimeout = window.setTimeout,
clock,
fakeXhr,
requests,
video,
t = 0,
i = 0;
// clean up the last run if necessary
if (player) {
player.dispose();
};
// mock out the environment
clock = sinon.useFakeTimers();
fakeXhr = sinon.useFakeXMLHttpRequest();
requests = [];
fakeXhr.onCreate = function(xhr) {
xhr.startTime = +new Date();
xhr.delivered = 0;
requests.push(xhr);
};
// initialize the HLS tech
fixture.innerHTML = '';
video = document.createElement('video');
video.className = 'video-js vjs-default-skin';
video.controls = true;
fixture.appendChild(video);
player = videojs(video, {
techOrder: ['hls'],
sources: [{
src: 'http://example.com/master.m3u8',
type: 'application/x-mpegurl'
}]
});
player.ready(function() {
// run next tick so that Flash doesn't swallow exceptions
realSetTimeout(function() {
var master = '#EXTM3U\n' +
options.playlists.reduce(function(playlists, value) {
return playlists +
'#EXT-X-STREAM-INF:BANDWIDTH=' + value + '\n' +
'playlist-' + value + '\n';
}, ''),
buffered = 0,
currentTime = 0;
// simulate buffered and currentTime during playback
player.buffered = function() {
return videojs.createTimeRange(0, currentTime + buffered);
};
player.currentTime = function() {
return currentTime;
};
// respond to the playlist requests
requests.shift().respond(200, null, master);
requests[0].respond(200, null, playlistResponse(+requests[0].url.match(/\d+$/)));
requests.shift();
bandwidths.sort(function(left, right) {
return left.time - right.time;
});
// pre-calculate the bandwidth at each second
for (t = i = 0; t < duration; t++) {
while (bandwidths[i + 1] && bandwidths[i + 1].time <= t) {
i++;
}
results.bandwidth.push({
time: t,
bandwidth: bandwidths[i].bandwidth
});
}
// advance time and collect simulation results
for (t = 0; t < duration; clock.tick(1000), t++) {
// schedule response deliveries
while (requests.length) {
(function(request) {
var segmentSize;
// playlist responses
if (/playlist-\d+$/.test(request.url)) {
// for simplicity, playlist responses have zero trasmission time
return setTimeout(function() {
request.respond(200, null, playlistResponse(+request.url.match(/\d+$/)));
}, propagationDelay * 1000);
}
// segment responses
segmentSize = +request.url.match(/(\d+)-\d+$/)[1] * segmentDuration;
// segment response headers arrive after the propogation delay
setTimeout(function() {
var arrival = Math.ceil(+new Date() * 0.001);
results.playlists.push({
time: arrival,
bitrate: +request.url.match(/(\d+)-\d+$/)[1]
});
request.setResponseHeaders({
'Content-Type': 'video/mp2t'
});
results.bandwidth.slice(arrival).every(function(value, i) {
var remaining = segmentSize - request.delivered;
if (remaining - value.bandwidth <= 0) {
// send the response body once all bytes have been delivered
setTimeout(function() {
if (request.aborted) {
return;
}
request.status = 200;
request.response = new Uint8Array(segmentSize * 0.125);
request.setResponseBody('');
buffered += segmentDuration;
// update the buffered value
results.buffered[results.buffered.length - 1].buffered = buffered;
results.effectiveBandwidth.push({
time: Math.ceil(+new Date() * 0.001),
bandwidth: player.hls.bandwidth
});
}, ((remaining / value.bandwidth) + i) * 1000);
return false;
}
// record the bits for this tick
request.delivered += value.bandwidth;
return true;
});
}, propagationDelay * 1000);
})(requests.shift());
}
results.buffered.push({
time: t,
buffered: buffered
});
// simulate playback
if (buffered > 0) {
buffered--;
currentTime++;
}
player.trigger('timeupdate');
}
// restore the environment
clock.restore();
fakeXhr.restore();
done(null, results);
}, 0);
});
};
runButton = document.getElementById('run-simulation');
runButton.addEventListener('click', function() {
runSimulation(parameters(), displayTimeline);
});
// render the timeline with d3
timeline = document.querySelector('.timeline');
timeline.innerHTML = '';
(function() {
var margin = {
top: 20,
right: 80,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom,
svg;
svg = d3.select('.timeline').append('svg')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
displayTimeline = function(error, data) {
var x = d3.scale.linear().range([0, width]),
y = d3.scale.linear().range([height, 0]),
timeAxis = d3.svg.axis().scale(x).orient('bottom'),
tickFormatter = d3.format(',.0f'),
bitrateAxis = d3.svg.axis()
.scale(y)
.tickFormat(function(value) {
return tickFormatter(value / 1024);
})
.orient('left'),
bandwidthLine = d3.svg.line()
.interpolate('basis')
.x(function(data) {
return x(data.time);
})
.y(function(data) {
return y(data.bandwidth);
}),
effectiveBandwidthLine = d3.svg.line()
.interpolate('basis')
.x(function(data) {
return x(data.time);
})
.y(function(data) {
return y(data.bandwidth);
});
x.domain(d3.extent(data.bandwidth, function(data) {
return data.time;
}));
y.domain([0, Math.max(d3.max(data.bandwidth, function(data) {
return data.bandwidth;
}), d3.max(data.options.playlists))]);
// time axis
svg.selectAll('.axis').remove();
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(timeAxis);
// bitrate axis
svg.append('g')
.attr('class', 'y axis')
.call(bitrateAxis)
.append('text')
.attr('transform', 'rotate(-90)')
.attr('y', 6)
.attr('dy', '.71em')
.style('text-anchor', 'end')
.text('Bitrate (kb/s)');
// playlist bitrate lines
svg.selectAll('.line.bitrate')
.data(data.options.playlists)
.enter().append('path')
.attr('class', 'line bitrate')
.attr('d', function(playlist) {
return 'M0,' + y(playlist) + 'L' + width + ',' + y(playlist);
});
// bandwidth line
svg.selectAll('.bandwidth').remove();
svg.append('path')
.datum(data.bandwidth)
.attr('class', 'line bandwidth')
.attr('d', bandwidthLine);
svg.selectAll('.effective-bandwidth').remove();
svg.append('path')
.datum(data.effectiveBandwidth)
.attr('class', 'line effective-bandwidth')
.attr('d', effectiveBandwidthLine);
svg.append('text')
.attr('class', 'bandwidth label')
.attr('transform', 'translate(' + x(x.range()[1]) + ', ' + y(data.bandwidth.slice(-1)[0].bandwidth) + ')')
.attr('dy', '1.35em')
.text('bandwidth');
svg.append('text')
.attr('class', 'bandwidth label')
.attr('transform', 'translate(' + x(x.range()[1]) + ', ' + y(data.effectiveBandwidth.slice(-1)[0].bandwidth) + ')')
.attr('dy', '1.35em')
.text('measured');
// segment bitrate dots
svg.selectAll('.segment-bitrate').remove();
svg.selectAll('.segment-bitrate')
.data(data.playlists)
.enter().append('circle')
.attr('class', 'dot segment-bitrate')
.attr('r', 3.5)
.attr('cx', function(playlist) {
return x(playlist.time);
})
.attr('cy', function(playlist) {
return y(playlist.bitrate);
});
// highlight intervals when the buffer is empty
svg.selectAll('.buffer-empty').remove();
svg.selectAll('.buffer-empty')
.data(data.buffered.reduce(function(result, sample) {
var last = result[result.length - 1];
if (sample.buffered === 0) {
if (last && sample.time === last.end + 1) {
// add this sample to the interval we're accumulating
return result.slice(0, result.length - 1).concat({
start: last.start,
end: sample.time
});
} else {
// this sample starts a new interval
return result.concat({
start: sample.time,
end: sample.time
});
}
}
// filter out time periods where the buffer isn't empty
return result;
}, []))
.enter().append('rect')
.attr('class', 'buffer-empty')
.attr('x', function(data) {
return x(data.start);
})
.attr('width', function(data) {
return x(1 + data.end - data.start);
})
.attr('y', 0)
.attr('height', y(height));
};
})();
runSimulation(parameters(), displayTimeline);
})(window, document);