はじめに
Media Source Extensions(MSE)は、HTML5 の <audio>
要素と <video>
要素に対して拡張バッファリングと再生制御を提供します。当初は Dynamic Adaptive Streaming over HTTP(DASH)ベースの動画プレーヤーをサポートするために開発されましたが、ここではオーディオ、特にギャップレス再生での使用方法について説明します。
曲が途切れることなく再生される音楽アルバムを聴いたことがある方は、今この瞬間も聴いているかもしれません。アーティストはこうしたギャップレス再生体験を芸術的な選択肢として提供するだけでなく、アナログ レコードや CD のアーティファクトとして、音声が連続した 1 つのストリームとして書き込むこともできます。残念ながら、MP3 や AAC などの最新のオーディオ コーデックの仕組みにより、こうしたシームレスな音声体験が現在失われていることがよくあります。
理由については後で詳しく説明しますが、ひとまずデモから始めましょう。以下は、優れた Sintel を 5 つの MP3 ファイルに分割し、MSE を使用して再構成した動画の最初の 30 秒です。赤い線は、各 MP3 の作成(エンコード)中に生じた隙間を示しています。この部分でグリッチが発生します。
うわっ!このたびはご不便をおかけして申し訳ございません。改善の余地があります。もう少し作業すれば、上のデモとまったく同じ MP3 ファイルを使用して、MSE を使用してこれらの煩わしいギャップを取り除くことができます。次のデモの緑色の線は、ファイルが結合され、ギャップが取り除かれた場所を示しています。Chrome 38 以降では、シームレスに再生されます。
ギャップのないコンテンツを作成する方法はたくさんあります。このデモでは、通常のユーザーが置かれているファイルの種類に焦点を当てます。各ファイルが、その前後の音声セグメントに関係なく個別にエンコードされている。
基本的な設定
まず、MediaSource
インスタンスの基本的な設定について解説します。Media Source Extensions は、その名が示すように、既存のメディア要素の拡張にすぎません。以下では、標準の URL を設定する場合と同様に、MediaSource
インスタンスを表す Object URL
を音声要素のソース属性に割り当てています。
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); } );
});
audio.src = URL.createObjectURL(mediaSource);
MediaSource
オブジェクトが接続されると、このオブジェクトは初期化を行い、最終的に sourceopen
イベントを呼び出します。この時点で、SourceBuffer
を作成できます。上記の例では、MP3 セグメントの解析とデコードができる audio/mpeg
セグメントを作成していますが、他のタイプもいくつか利用できます。
異常な波形
後ほどコードに戻りますが、今追加したファイル、特に最後に追加したファイルを詳しく見てみましょう。下のグラフは、sintel_0.mp3
トラックから両方のチャンネルの平均値をとった直近 3, 000 サンプルのグラフです。赤色の線上の各ピクセルは、[-1.0, 1.0]
の範囲内の浮動小数点サンプルです。
あのゼロ(無音)サンプルは一体何だ!?これは、エンコード時に発生した圧縮アーティファクトが原因です。ほとんどのエンコーダには、なんらかのパディングが導入されています。このケースでは、LAME によって、ちょうど 576 個のパディング サンプルがファイルの末尾に追加されています。
各ファイルには、末尾のパディングに加えて、先頭にもパディングが追加されています。sintel_1.mp3
トラックを見ると、前面にさらに 576 個のパディング サンプルがあることがわかります。パディングの量はエンコーダとコンテンツによって異なりますが、正確な値は各ファイルに含まれている metadata
に基づいて決定されます。
前のデモのセグメント間のグリッチの原因は、各ファイルの先頭と末尾にある無音部分です。ギャップレス再生を実現するには、このような無音部分を取り除く必要があります。これは MediaSource
で簡単に行えます。以下では、追加ウィンドウとタイムスタンプ オフセットを使用してこの無音部分を削除するように onAudioLoaded()
メソッドを変更します。
サンプルコード
function onAudioLoaded(data, index) {
// Parsing gapless metadata is unfortunately non trivial and a bit messy, so
// we'll glaze over it here; see the appendix 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 end 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();
URL.revokeObjectURL(audio.src);
}
});
}
// 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 garbage collection may remove ranges of
// media in unexpected places.
sourceBuffer.appendBuffer(data);
}
シームレスな波形
追加ウィンドウを適用した後の波形をもう一度確認することで、素晴らしい新しいコードが何を達成したかを見てみましょう。以下では、sintel_0.mp3
の最後にある無音セクション(赤色)と sintel_1.mp3
の先頭にある無音セクション(青色)が削除され、セグメント間のシームレスな遷移を実現しています。
おわりに
以上で、5 つのセグメントすべてを 1 つにシームレスにつなぎ合わせ、デモはこれで終了となります。先に進む前に、onAudioLoaded()
メソッドではコンテナやコーデックが考慮されていないことにお気づきでしょうか。つまり、これらの手法はすべて、コンテナやコーデックの種類に関係なく機能します。以下では、DASH 対応の元のデモ MP3 ではなく、断片化された MP4 を再生できます。
ギャップのないコンテンツ作成とメタデータ解析について詳しくは、以下の付録をご覧ください。また、gapless.js
でこのデモのベースとなっているコードの詳細を確認することもできます。
今後ともよろしくお願いいたします。
付録 A: ギャップのないコンテンツの作成
ギャップのないコンテンツを作るのは、なかなか実現しにくいものです。以下では、このデモで使用する Sintel メディアの作成について説明します。まず、Sintel のロスレス FLAC サウンドトラックのコピーが必要です。今後のために SHA1 が以下に含まれています。ツールには、FFmpeg、MP4Box、LAME、OSX(afconvert を含む)が必要です。
unzip Jan_Morgenstern-Sintel-FLAC.zip
sha1sum 1-Snow_Fight.flac
# 0535ca207ccba70d538f7324916a3f1a3d550194 1-Snow_Fight.flac
まず、最初の 31.5 秒の 1-Snow_Fight.flac
トラックを分割します。また、再生終了後のクリックを避けるために、28 秒から始まる 2.5 秒のフェードアウトを追加します。以下の FFmpeg コマンドラインを使用すると、これらすべてを行い、結果を sintel.flac
に入れることができます。
ffmpeg -i 1-Snow_Fight.flac -t 31.5 -af "afade=t=out:st=28:d=2.5" sintel.flac
次に、ファイルをそれぞれ 6.5 秒の 5 つの Wave ファイルに分割します。ほぼすべてのエンコーダが取り込みをサポートしているため、Wave を使用するのが最も簡単です。繰り返しになりますが、これを FFmpeg で正確に実行できます。FFmpeg では、sintel_0.wav
、sintel_1.wav
、sintel_2.wav
、sintel_3.wav
、sintel_4.wav
を使用します。
ffmpeg -i sintel.flac -acodec pcm_f32le -map 0 -f segment \
-segment_list out.list -segment_time 6.5 sintel_%d.wav
次に、MP3 ファイルを作成します。LAME には、ギャップレス コンテンツを作成するための複数のオプションがあります。コンテンツをコントロールしている場合は、--nogap
を使用してすべてのファイルをバッチ エンコードし、セグメント間にパディングが発生しないようにできます。ただし、このデモではパディングを使用して、Wave ファイルの標準高品質の VBR エンコードを使用します。
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
MP3 ファイルの作成に必要なのはこれだけです。次に、断片化された MP4 ファイルの作成について説明します。iTunes 用にマスターされたメディアの作成については、Apple の指示に従います。以下では、指示に沿って Wave ファイルを中間 CAF ファイルに変換してから、推奨パラメータを使用して MP4 コンテナ内で AAC としてエンコードします。
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
これで、いくつかの M4A ファイルが用意されました。MediaSource
で使用する前に、適切にフラグメント化する必要があります。ここでは、1 秒のフラグメント サイズを使用します。MP4Box は、断片化された各 MP4 を、破棄可能な MPEG-DASH マニフェスト(sintel_#_dash.mpd
)とともに sintel_#_dashinit.mp4
として書き出します。
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
これで、ギャップレス再生に必要な正しいメタデータを使用して、MP4 ファイルと MP3 ファイルを断片化しました。このメタデータの内容について詳しくは、付録 B をご覧ください。
付録 B: ギャップのないメタデータの解析
ギャップのないコンテンツの作成と同様に、ギャップのないメタデータの解析は、保存のための標準的な方法がないため、難しい場合があります。最も一般的な 2 つのエンコーダである LAME と iTunes が、ギャップレス メタデータをどのように保存しているかを、以下で説明します。まず、ヘルパー メソッドと、上記で使用した ParseGaplessData()
の概要を設定しましょう。
// 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 = new TextDecoder().decode(arrayBuffer.slice(0, 512));
var frontPadding = 0, endPadding = 0, realSamples = 0;
// ... we'll fill this in as we go below.
解析と説明が最も簡単であるため、Apple の iTunes メタデータ形式についてまず説明します。MP3 と M4A ファイル内に、iTunes(および afconvert)を次のように ASCII で短いセクションを記述します。
iTunSMPB[ 26 bytes ]0000000 00000840 000001C0 0000000000046E00
これは、MP3 コンテナ内の ID3 タグ内と MP4 コンテナ内のメタデータ Atom 内に記述されます。ここでは、最初の 0000000
トークンを無視できます。次の 3 つのトークンは、前面パディング、終了パディング、パディングなしのサンプル数です。これらを音声のサンプルレートで割ると、それぞれの時間の長さが得られます。
// 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);
}
その一方で、ほとんどのオープンソース MP3 エンコーダは、サイレント MPEG フレーム内に配置された特別な Xing ヘッダー内にギャップレス メタデータを格納します(これはサイレントであるため、Xing ヘッダーを認識しないデコーダは単に無音を再生します)。残念ながら、このタグは常に存在するわけではなく、オプションのフィールドが多数含まれています。このデモではメディアを管理しますが、実際には、ギャップレス メタデータが実際に使用可能になるタイミングを知るために追加のチェックが必要になります。
まず、合計サンプル数を解析します。わかりやすくするために、これを Xing ヘッダーから読み取りますが、通常の MPEG オーディオ ヘッダーから構築することもできます。Xing ヘッダーは、Xing
タグまたは Info
タグでマークできます。このタグからちょうど 4 バイト後に、ファイル内のフレームの総数を表す 32 ビットがあります。この値をフレームあたりのサンプル数を乗算すると、ファイル内の合計サンプル数が得られます。
// 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:
// http://www.codeproject.com/Articles/8295/MPEG-Audio-Frame-Header
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.
サンプルの総数がわかったので、パディング サンプルの数を読み取ります。エンコーダによっては、Xing ヘッダーにネストされた LAME タグまたは Lavf タグで記述される場合があります。このヘッダーのちょうど 17 バイト後に、それぞれ 12 ビットのフロントとエンドのパディングを表す 3 バイトがあります。
xingDataIndex = byteStr.indexOf('LAME');
if (xingDataIndex == -1) xingDataIndex = byteStr.indexOf('Lavf');
if (xingDataIndex != -1) {
// See http://gabriel.mp3-tech.org/mp3infotag.html#delays 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
};
}
これにより、ギャップのないコンテンツの大部分を解析する完全な関数ができました。ただし、エッジケースは確実に存在するため、本番環境で同様のコードを使用する前に注意することをおすすめします。
付録 C: ガベージ コレクションについて
SourceBuffer
インスタンスに属するメモリは、コンテンツ タイプ、プラットフォーム固有の上限、現在の再生位置に応じて、アクティブにガベージ コレクションされます。Chrome では、まず、すでに再生されたバッファからメモリが回収されます。ただし、メモリ使用量がプラットフォーム固有の制限を超えると、再生されていないバッファからメモリが削除されます。
メモリの再利用が原因で再生がタイムラインのギャップに到達すると、ギャップが十分に小さいとグリッチしたり、ギャップが大きすぎると完全に停止したりすることがあります。どちらもユーザー エクスペリエンスは良くないため、一度に大量のデータを追加せず、メディア タイムラインから不要になった範囲を手動で削除することが重要です。
範囲は、各 SourceBuffer
の remove()
メソッドで削除できます。[start, end]
の範囲(秒単位)を受け取ります。appendBuffer()
と同様に、各 remove()
は、完了時に updateend
イベントを呼び出します。その他の削除や追加は、イベントが発生するまで実行しないでください。
パソコンの Chrome では、約 12 MB の音声コンテンツと 150 MB 動画コンテンツをメモリに一度に保存できます。ブラウザやプラットフォームをまたいでこれらの値に依存しないでください。たとえば、これらの値がモバイル デバイスを表すものではありません。
ガベージ コレクションは、SourceBuffers
に追加されたデータにのみ影響します。JavaScript 変数でバッファに格納できるデータの量に制限はありません。必要に応じて、同じデータを同じ位置に再度追加することもできます。