-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
565 lines (478 loc) · 26.2 KB
/
index.html
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
<!DOCTYPE html>
<base target="_blank"/>
<meta charset="utf-8">
<title>Media Source Extensions for Audio: Eliminating the Gap</title>
<link rel="stylesheet" href="gapless.css">
<script src="run_prettify.js"></script>
<script src="wavesurfer.min.js"></script>
<script src="peaks.js"></script>
<script src="gapless.js"></script>
<!-- TODO: Look into using polymer / material elements / new hawtness. -->
<div id="main">
<div class="header">
<span style="float: right">Dale Curtis</span>August 8, 2014
</div>
<h1>Media Source Extensions for Audio:<br>Eliminating the Gap</h1>
<nav role="navigation">
<ul>
<li>Gapless Playback</li>
<ul>
<li><a href="#introduction" target="_self">Introduction</a></li>
<li><a href="#basic-setup" target="_self">Basic Setup</a></li>
<li><a href="#anomalous-waveforms" target="_self">Anomalous Waveforms</a></li>
<li><a href="#code-please" target="_self">Example Code</a></li>
<li><a href="#seamless-waveform" target="_self">A Seamless Waveform</a></li>
<li><a href="#conclusion" target="_self">Conclusion</a></li>
</ul>
<li>Appendices</li>
<ul>
<li><a href="#creating-gapless-content" target="_self">A: Creating Gapless Content</a></li>
<li><a href="#parsing-gapless-metadata" target="_self">B: Parsing Gapless Metadata</a></li>
<li><a href="#garbage-collection" target="_self">C: On Garbage Collection</a></li>
</ul>
</ul>
</nav>
<h2 id="introduction">Introduction</h2>
<a href="http://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html">
Media Source Extensions (MSE)</a>
provide extended buffering and playback control for the HTML5 <audio>
and <video> elements. While originally developed to facilitate
<a href="http://dashif.org/mpeg-dash/">Dynamic Adaptive Streaming over HTTP
(DASH)</a> based video players, below we'll see how they can be used for
audio; specifically for
<a href="http://en.wikipedia.org/wiki/Gapless_playback">gapless playback</a>.
<p>You've likely listened to a music album where songs flowed seamlessly
across tracks; you may even be listening to one right now. Artists create
these <a href="http://en.wikipedia.org/wiki/Gapless_playback">gapless
playback</a> experiences both as an artistic choice as well as an artifact of
<a href="http://en.wikipedia.org/wiki/Gramophone_record">vinyl records</a> and
<a href="http://en.wikipedia.org/wiki/Compact_disc">CDs</a> where audio was
written as one continuous stream. Unfortunately, due to the way modern audio
codecs like
<a href="http://en.wikipedia.org/wiki/MP3">MP3</a> and
<a href="http://en.wikipedia.org/wiki/Advanced_Audio_Coding">AAC</a>
work, this seamless aural experience is often lost today.</p>
<p>Note: Most MP3 encoders (including LAME as used in this example) do not
produce sufficient pre-roll and post-roll for a flawless transition between
segments. If you need a truly flawless transition, we recommend using AAC
with the default paddings of 2112 and 960; see below. Alternatively you can
try to ensure your MP3 encoder generates at least 1152 samples of pre-roll
and post-roll. See <a href="https://github.com/dalecurtis/llama-demo/issues/3">
issue #3</a></p>
<p>We'll get into the details of why below, but for now lets start with a
demonstration. Below is the first thirty seconds of the excellent
<a href="http://www.sintel.org/">Sintel</a> chopped into five separate
MP3 files and reassembled using MSE. The red lines indicate gaps introduced
during the creation (encoding) of each MP3; you'll hear glitches at these
points.</p>
<div class="waveform-container">
<span class="play-overlay"></span>
<div id="waveform_mp3_gap" class="waveform"></div>
</div>
<p>Yuck! That's not a great experience; we can do better. With a little more
work, using the exact same MP3 files in the above demo, we can use MSE to
remove those annoying gaps. The green lines in the next demo indicate where
the files have been joined and the gaps removed. On Chrome 38+ this will
playback seamlessly!</p>
<div class="waveform-container">
<span class="play-overlay"></span>
<div id="waveform_mp3_gapless" class="waveform"></div>
</div>
<p>There are a <a href="#creating-gapless-content" target="_self">variety of
ways to create gapless content</a>. For the purposes of this demo, we'll
focus on the type of files a normal user might have lying around. Where each
file has been encoded separately without regard for the audio segments before
or after it.</p>
<h2 id="basic-setup">Basic Setup</h2>
<p>First, lets backtrack and cover the basic setup of a MediaSource instance.
Media Source Extensions, as the name implies, are just extensions to the
existing media elements. Below, we're assigning an
<a href="https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL">
Object URL</a>, representing our MediaSource instance, to the source
attribute of an audio element; just like you would set a standard URL.</p>
<pre class="prettyprint lang-js">
var audio = document.createElement('audio');
var mediaSource = new MediaSource();
var SEGMENTS = 5;
mediaSource.addEventListener('sourceopen', function() {
var sourceBuffer = mediaSource.addSourceBuffer('audio/mpeg');
function onAudioLoaded(data, index) {
// Append the ArrayBuffer data into our new SourceBuffer.
sourceBuffer.appendBuffer(data);
}
// Retrieve an audio segment via XHR. For simplicity, we're retrieving the
// entire segment at once, but we could also retrieve it in chunks and append
// each chunk separately. MSE will take care of assembling the pieces.
GET('sintel/sintel_0.mp3', function(data) { onAudioLoaded(data, 0); } );
}, false);
audio.src = window.URL.createObjectURL(mediaSource);
</pre>
<p>Once the MediaSource object is connected, it will perform some initialization
and eventually fire a "sourceopen" event; at which point we can create a
<a href="http://www.w3.org/TR/media-source/#sourcebuffer">SourceBuffer</a>.
In the example above, we're creating an "audio/mpeg" one, which is able to
parse and decode our MP3 segments; there are several
<a href="http://www.w3.org/2013/12/byte-stream-format-registry/">other types</a>
available.</p>
<h2 id="anomalous-waveforms">Anomalous Waveforms</h2>
<p>We'll come back to the code in a moment, but lets now look more closely at
the file we've just appended, specifically at the end of it. Below, is a graph
of the last 3000 samples averaged across both channels from the
<i><a href="sintel/sintel_0.mp3">sintel_0.mp3</a></i> track. Each pixel on the
red line is a <a href="http://en.wikipedia.org/wiki/Audio_bit_depth">
floating point sample</a> in the range of [-1.0, 1.0].</p>
<div class="waveform-container">
<h5>End of sintel_0.mp3</h5>
<img src="mp3_gap_end.png">
</div>
<p>What's with all that those zero (silent) samples!? They're actually due to
<a href="http://en.wikipedia.org/wiki/Gapless_playback#Compression_artifacts">
compression artifacts</a> introduced during encoding. Almost every encoder
introduces some type of padding. In this case
<a href="http://lame.sourceforge.net/">LAME</a> added exactly 576 padding
samples to the end of the file.</p>
<p>In addition to the padding at the end, each file also had padding added to
the beginning. If we peek ahead at the <i><a href="sintel/sintel_1.mp3">
sintel_1.mp3</a></i> track we'll see another 576 samples of padding exists
at the front. The amount of padding varies by encoder and content, but we know
the exact values based on <a href="#parsing-gapless-metadata" target="_self">
metadata</a> included within each file.
</p>
<div class="waveform-container">
<h5>Beginning of sintel_1.mp3</h5>
<img src="mp3_gap.png">
</div>
<p>The sections of silence at the beginning and end of each file are what
causes the "glitches" between segments in the previous demo. To achieve
gapless playback, we need to remove these sections of silence. Luckily,
this is easily done with MediaSource! Below, we'll modify our
<i>onAudioLoaded()</i> method to use an
<a href="https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#definitions">
append window</a> and a
<a href="https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-SourceBuffer-timestampOffset">
timestamp offset</a> to remove this silence.</p>
<h2 id="code-please">Example Code</h2>
<pre class="prettyprint lang-js">
function onAudioLoaded(data, index) {
// Parsing gapless metadata is unfortunately non trivial and a bit messy, so
// we'll glaze over it here; see the <a href="#parsing-gapless-metadata" target="_self">appendix</a> for details. ParseGaplessData()
// will return a dictionary with two elements:
//
// audioDuration: Duration in seconds of all non-padding audio.
// frontPaddingDuration: Duration in seconds of the front padding.
//
var gaplessMetadata = ParseGaplessData(data);
// Each appended segment must be appended relative to the next. To avoid any
// overlaps, we'll use the ending timestamp of the last append as the starting
// point for our next append or zero if we haven't appended anything yet.
var appendTime = index > 0 ? sourceBuffer.buffered.end(0) : 0;
// Simply put, an append window allows you to trim off audio (or video) frames
// which fall outside of a specified time range. Here, we'll use the end of
// our last append as the start of our append window and the end of the real
// audio data for this segment as the end of our append window.
sourceBuffer.appendWindowStart = appendTime;
sourceBuffer.appendWindowEnd = appendTime + gaplessMetadata.audioDuration;
// The timestampOffset field essentially tells MediaSource where in the media
// timeline the data given to appendBuffer() should be placed. I.e., if the
// timestampOffset is 1 second, the appended data will start 1 second into
// playback.
//
// MediaSource requires that the media timeline starts from time zero, so we
// need to ensure that the data left after filtering by the append window
// starts at time zero. We'll do this by shifting all of the padding we want
// to discard before our append time (and thus, before our append window).
sourceBuffer.timestampOffset =
appendTime - gaplessMetadata.frontPaddingDuration;
// When appendBuffer() completes, it will fire an "updateend" event signaling
// that it's okay to append another segment of media. Here, we'll chain the
// append for the next segment to the completion of our current append.
if (index == 0) {
sourceBuffer.addEventListener('updateend', function() {
if (++index < SEGMENTS) {
GET('sintel/sintel_' + index + '.mp3',
function(data) { onAudioLoaded(data, index); });
} else {
// We've loaded all available segments, so tell MediaSource there are no
// more buffers which will be appended.
mediaSource.endOfStream();
}
});
}
// appendBuffer() will now use the timestamp offset and append window settings
// to filter and timestamp the data we're appending.
//
// Note: While this demo uses very little memory, more complex use cases need
// to be careful about memory usage or <a href="#garbage-collection" target="_self">garbage collection</a> may remove ranges of
// media in unexpected places.
sourceBuffer.appendBuffer(data);
}
</pre>
<h2 id="seamless-waveform">A Seamless Waveform</h2>
<p>Lets see what our shiny new code has accomplished by taking another look
at the waveform after we've applied our append windows. Below, you can see
that the silent section at the end of
<i><a href="sintel/sintel_0.mp3">sintel_0.mp3</a></i> (in red) and
the silent section at the beginning of
<i><a href="sintel/sintel_1.mp3">sintel_1.mp3</a></i> (in blue) have
been removed; leaving us with a seamless transition between segments.</p>
<div class="waveform-container">
<h5>Joining of sintel_0.mp3 and sintel_1.mp3</h5>
<img src="mp3_mid.png">
</div>
<h2 id="conclusion">Conclusion</h2>
<p>With that we've stitched all five segments seamlessly into one and have
subsequently reached the end of our demo. Before we go, you may have noticed
that our <i>onAudioLoaded()</i> method has no consideration for containers or
codecs... Which means all of these techniques will work irrespective of the
container or codec type; below you can replay the original demo DASH-ready
fragmented MP4 instead of MP3.</p>
<div class="waveform-container">
<span class="play-overlay"></span>
<div id="waveform_mp4_gapless" class="waveform"></div>
</div>
<p>If you'd like to know more check the appendices below for a deeper look at
gapless content creation and metadata parsing. You can also explore
<a href="gapless.js"><i>gapless.js</i></a> for a closer look at the code
powering this demo.</p>
<p>Thanks for reading!</p>
<h2 id="creating-gapless-content">Appendix A: Creating Gapless Content</h2>
Creating gapless content can be hard to get right. Below we'll walk through
how the <a href="http://www.sintel.org/">Sintel</a> media used in this demo
were created. To start you'll need a copy of the
<a href="http://media.xiph.org/sintel/Jan_Morgenstern-Sintel-FLAC.zip">
lossless FLAC soundtrack</a> for Sintel; for posterity, the SHA1 is included
below. For tools, you'll need <a href="http://ffmpeg.org/">FFmpeg</a>,
<a href="http://gpac.wp.mines-telecom.fr/mp4box/">MP4Box</a>,
<a href="http://lame.sourceforge.net/">LAME</a>, and an OSX installation with
<a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man1/afconvert.1.html">
afconvert</a>.
<pre class="prettyprint lang-bash">
unzip Jan_Morgenstern-Sintel-FLAC.zip
sha1sum 1-Snow_Fight.flac
# 0535ca207ccba70d538f7324916a3f1a3d550194 1-Snow_Fight.flac
</pre>
<p>First, we'll split out the first 31.5 seconds the <i>1-Snow_Fight.flac</i>
track. We also want to add a 2.5 second fade out starting at 28 seconds in to
avoid any clicks once playback finishes. Using the FFmpeg command line below
we can accomplish all of this and put the results in <i>sintel.flac</i>.</p>
<pre class="prettyprint lang-bash">
ffmpeg -i 1-Snow_Fight.flac -t 31.5 -af "afade=t=out:st=28:d=2.5" sintel.flac
</pre>
<p>Next, we'll split the file into 5 <a href="http://en.wikipedia.org/wiki/WAV">
wave</a> files of 6.5 seconds each; it's easiest to use wave since almost
every encoder supports ingestion of it. Again, we can do this precisely with
FFmpeg, after which we'll have: <i>sintel_0.wav</i>, <i>sintel_1.wav</i>,
<i>sintel_2.wav</i>, <i>sintel_3.wav</i>, and <i>sintel_4.wav</i>.</p>
<pre class="prettyprint lang-bash">
ffmpeg -i sintel.flac -acodec pcm_f32le -map 0 -f segment \
-segment_list out.list -segment_time 6.5 sintel_%d.wav
</pre>
<p>Next, lets create the MP3 files. LAME has several options for creating
gapless content. If you're in control of the content you might consider using
--nogap with a batch encoding of all files to avoid padding between segments
altogether. For the purposes of this demo though, we want that padding so
we'll use a standard high quality VBR encoding of the wave files.</p>
<pre class="prettyprint lang-bash">
lame -V=2 sintel_0.wav sintel_0.mp3
lame -V=2 sintel_1.wav sintel_1.mp3
lame -V=2 sintel_2.wav sintel_2.mp3
lame -V=2 sintel_3.wav sintel_3.mp3
lame -V=2 sintel_4.wav sintel_4.mp3
</pre>
<p>That's all that's necessary to create the MP3 files. Now lets cover the
creation of the fragmented MP4 files. We'll follow Apple's directions for
creating media which is
<a href="http://www.apple.com/itunes/mastered-for-itunes/">mastered for
iTunes</a>. Below, we'll convert the wave files into intermediate
<a href="http://en.wikipedia.org/wiki/Core_Audio_Format">CAF</a> files, per
the instructions, before encoding them as
<a href="http://en.wikipedia.org/wiki/Advanced_Audio_Coding">AAC</a> in an
<a href="http://en.wikipedia.org/wiki/MP4">MP4</a> container using the
recommended parameters.</p>
<pre class="prettyprint lang-bash">
afconvert sintel_0.wav sintel_0_intermediate.caf -d 0 -f caff \
--soundcheck-generate
afconvert sintel_1.wav sintel_1_intermediate.caf -d 0 -f caff \
--soundcheck-generate
afconvert sintel_2.wav sintel_2_intermediate.caf -d 0 -f caff \
--soundcheck-generate
afconvert sintel_3.wav sintel_3_intermediate.caf -d 0 -f caff \
--soundcheck-generate
afconvert sintel_4.wav sintel_4_intermediate.caf -d 0 -f caff \
--soundcheck-generate
afconvert sintel_0_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
-b 256000 -q 127 -s 2 sintel_0.m4a
afconvert sintel_1_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
-b 256000 -q 127 -s 2 sintel_1.m4a
afconvert sintel_2_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
-b 256000 -q 127 -s 2 sintel_2.m4a
afconvert sintel_3_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
-b 256000 -q 127 -s 2 sintel_3.m4a
afconvert sintel_4_intermediate.caf -d aac -f m4af -u pgcm 2 --soundcheck-read \
-b 256000 -q 127 -s 2 sintel_4.m4a
</pre>
<p>We now have several M4A files which we need to
<a href="http://gpac.wp.mines-telecom.fr/mp4box/dash/">fragment</a>
appropriately before they can be used with MediaSource. For our purposes,
we'll use a fragment size of one second. MP4Box will write out each
fragmented MP4 as <i>sintel_#_dashinit.mp4</i> along with an MPEG-DASH
manifest (<i>sintel_#_dash.mpd</i>) which can be discarded.</p>
<pre class="prettyprint lang-bash">
MP4Box -dash 1000 sintel_0.m4a && mv sintel_0_dashinit.mp4 sintel_0.mp4
MP4Box -dash 1000 sintel_1.m4a && mv sintel_1_dashinit.mp4 sintel_1.mp4
MP4Box -dash 1000 sintel_2.m4a && mv sintel_2_dashinit.mp4 sintel_2.mp4
MP4Box -dash 1000 sintel_3.m4a && mv sintel_3_dashinit.mp4 sintel_3.mp4
MP4Box -dash 1000 sintel_4.m4a && mv sintel_4_dashinit.mp4 sintel_4.mp4
rm sintel_{0,1,2,3,4}_dash.mpd
</pre>
<p>That's it! We now have fragmented MP4 and MP3 files with the correct
metadata necessary for gapless playback. See <a href="">appendix b</a> for
more details on just what that metadata looks like.</p>
<h2 id="parsing-gapless-metadata">Appendix B: Parsing Gapless Metadata</h2>
<p>Just like creating gapless content, parsing the gapless metadata can be
tricky since there's no standard method for storage. Below we'll cover how the
two most common encoders, LAME and iTunes, store their gapless metadata. Lets
start by setting up some helper methods and an outline for the
<i>ParseGaplessData()</i> used above.</p>
<pre class="prettyprint lang-js">
// Since most MP3 encoders store the gapless metadata in binary, we'll need a
// method for turning bytes into integers. Note: This doesn't work for values
// larger than 2^30 since we'll overflow the signed integer type when shifting.
function ReadInt(buffer) {
var result = buffer.charCodeAt(0);
for (var i = 1; i < buffer.length; ++i) {
result <<= 8;
result += buffer.charCodeAt(i);
}
return result;
}
function ParseGaplessData(arrayBuffer) {
// Gapless data is generally within the first 512 bytes, so limit parsing.
var byteStr = String.fromCharCode.apply(
null, new Uint8Array(arrayBuffer.slice(0, 512)));
var frontPadding = 0, endPadding = 0, realSamples = 0;
// ... we'll fill this in as we go below.
</pre>
<p>We'll cover Apple's iTunes metadata format first since it's the easiest to
parse and explain. Within MP3 and M4A files iTunes (and afconvert) write a
short section in ASCII like so:</p>
<pre>
iTunSMPB[ 26 bytes ]0000000 00000840 000001C0 0000000000046E00
</pre>
<p>This is written inside an ID3 tag within the MP3 container and within a
metadata atom inside the MP4 container. For our purposes, we can
ignore the first "0000000" token. The next three tokens are the front padding,
end padding, and total non-padding sample count. Dividing each of these by the
sample rate of the audio gives us the duration for each.</p>
<pre class="prettyprint lang-js">
// iTunes encodes the gapless data as hex strings like so:
//
// 'iTunSMPB[ 26 bytes ]0000000 00000840 000001C0 0000000000046E00'
// 'iTunSMPB[ 26 bytes ]####### frontpad endpad real samples'
//
// The approach here elides the complexity of actually parsing MP4 atoms. It
// may not work for all files without some tweaks.
var iTunesDataIndex = byteStr.indexOf('iTunSMPB');
if (iTunesDataIndex != -1) {
var frontPaddingIndex = iTunesDataIndex + 34;
frontPadding = parseInt(byteStr.substr(frontPaddingIndex, 8), 16);
var endPaddingIndex = frontPaddingIndex + 9;
endPadding = parseInt(byteStr.substr(endPaddingIndex, 8), 16);
var sampleCountIndex = endPaddingIndex + 9;
realSamples = parseInt(byteStr.substr(sampleCountIndex, 16), 16);
}
</pre>
<p>On the flip side, most open source MP3 encoders will store the gapless
metadata within a special
<a href="http://gabriel.mp3-tech.org/mp3infotag.html">Xing header</a> placed
inside of a silent MPEG frame (it's silent so decoders which don't understand
the Xing header will simply play silence). Sadly this tag is not always
present and has a number of optional fields. For the purposes of this demo, we
have control over the media, but in practice some additional sanity checks
will be required to know when gapless metadata is actually available.</p>
<p>First we'll parse the total sample count. For simplicity we'll read this
from the Xing header, but it could be constructed from the normal
<a href="http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header">
MPEG audio header</a>. Xing headers can be marked by either a 'Xing' or 'Info'
tag. Exactly 4 bytes after this tag there are 32-bits representing the
total number of frames in the file; multiplying this value by the number of
samples per frame will give us the total samples in the file.</p>
<pre class="prettyprint lang-js">
// Xing padding is encoded as 24bits within the header. Note: This code will
// only work for Layer3 Version 1 and Layer2 MP3 files with XING frame counts
// and gapless information. See the following document for more details:
// <a href="http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header">http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header</a>
var xingDataIndex = byteStr.indexOf('Xing');
if (xingDataIndex == -1) xingDataIndex = byteStr.indexOf('Info');
if (xingDataIndex != -1) {
// See section 2.3.1 in the link above for the specifics on parsing the Xing
// frame count.
var frameCountIndex = xingDataIndex + 8;
var frameCount = ReadInt(byteStr.substr(frameCountIndex, 4));
// For Layer3 Version 1 and Layer2 there are 1152 samples per frame. See
// section 2.1.5 in the link above for more details.
var paddedSamples = frameCount * 1152;
// ... we'll cover this below.
</pre>
<p>Now that we have the total number of samples we can move on to reading out
the number of padding samples. Depending on your encoder this may be written
under a 'LAME' or 'Lavf' tag nested in the Xing header. Exactly 17 bytes after
this header there are 3 bytes representing the front and end padding in
12-bits each respectively.</p>
<pre class="prettyprint lang-js">
xingDataIndex = byteStr.indexOf('LAME');
if (xingDataIndex == -1) xingDataIndex = byteStr.indexOf('Lavf');
if (xingDataIndex != -1) {
// See <a href="http://gabriel.mp3-tech.org/mp3infotag.html#delays">http://gabriel.mp3-tech.org/mp3infotag.html#delays</a> for details of
// how this information is encoded and parsed.
var gaplessDataIndex = xingDataIndex + 21;
var gaplessBits = ReadInt(byteStr.substr(gaplessDataIndex, 3));
// Upper 12 bits are the front padding, lower are the end padding.
frontPadding = gaplessBits >> 12;
endPadding = gaplessBits & 0xFFF;
}
realSamples = paddedSamples - (frontPadding + endPadding);
}
return {
audioDuration: realSamples * SECONDS_PER_SAMPLE,
frontPaddingDuration: frontPadding * SECONDS_PER_SAMPLE
};
}
</pre>
<p>With that we have a complete function for parsing the vast majority of
gapless content out there. Edge cases certainly abound though, so caution is
recommended before using similar code in production.</p>
<h2 id="garbage-collection">Appendix C: On Garbage Collection</h2>
<p>Memory belonging to SourceBuffers is actively
<a href="http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)">
garbage collected</a> according to content type, platform specific limits, and
the current play position. In Chrome, memory will first be reclaimed from
already played buffers. However, if memory usage exceeds platform specific
limits, it will remove memory from unplayed buffers.</p>
<p>When playback reaches a gap in the timeline due to reclaimed memory it may
glitch if the gap is small enough or stall completely if the gap is too large.
Neither is a great user experience, so it's important to avoid appending too
much data at once and to manually remove ranges from the media timeline that
are no longer necessary.</p>
<p>Ranges can be removed via the
<a href="https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end">
remove()</a> method on each SourceBuffer; which takes a [start, end] range in
seconds. Similar to appendBuffer(), each remove() will fire an "updateend"
event once it completes. Other removes or appends should not be issued until
the event fires.</p>
<p>On desktop Chrome, you can keep approximately 12 megabytes of audio content
and 150 megabytes of video content in memory at once. You should not rely on
these values across browsers or platforms; e.g., they are most certainly not
representative of mobile devices.</p>
<p>Garbage collection only impacts data added to SourceBuffers; there are no
limits on how much data you can keep buffered in JavaScript variables. You
may also reappend the same data in the same position if necessary.</p>
<div class="header">
<span style="float: right;">
Powered by <a href="https://code.google.com/p/google-code-prettify/">
google-code-prettify</a>, <a href="http://www.gnuplot.info/">gnuplot</a>,
and <a href="http://www.wavesurfer.fm/">wavesurfer.fm</a>.
</span>
</div>
<br/>
</div>