b7d93c0ef2b5ccc067c07551da865567054c8889
[platform/framework/web/crosswalk.git] / src / media / filters / opus_audio_decoder.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "media/filters/opus_audio_decoder.h"
6
7 #include <cmath>
8
9 #include "base/single_thread_task_runner.h"
10 #include "base/sys_byteorder.h"
11 #include "media/base/audio_buffer.h"
12 #include "media/base/audio_decoder_config.h"
13 #include "media/base/audio_discard_helper.h"
14 #include "media/base/bind_to_current_loop.h"
15 #include "media/base/buffers.h"
16 #include "media/base/decoder_buffer.h"
17 #include "third_party/opus/src/include/opus.h"
18 #include "third_party/opus/src/include/opus_multistream.h"
19
20 namespace media {
21
22 static uint16 ReadLE16(const uint8* data, size_t data_size, int read_offset) {
23   uint16 value = 0;
24   DCHECK_LE(read_offset + sizeof(value), data_size);
25   memcpy(&value, data + read_offset, sizeof(value));
26   return base::ByteSwapToLE16(value);
27 }
28
29 // The Opus specification is part of IETF RFC 6716:
30 // http://tools.ietf.org/html/rfc6716
31
32 // Opus uses Vorbis channel mapping, and Vorbis channel mapping specifies
33 // mappings for up to 8 channels. This information is part of the Vorbis I
34 // Specification:
35 // http://www.xiph.org/vorbis/doc/Vorbis_I_spec.html
36 static const int kMaxVorbisChannels = 8;
37
38 // Maximum packet size used in Xiph's opusdec and FFmpeg's libopusdec.
39 static const int kMaxOpusOutputPacketSizeSamples = 960 * 6;
40
41 static void RemapOpusChannelLayout(const uint8* opus_mapping,
42                                    int num_channels,
43                                    uint8* channel_layout) {
44   DCHECK_LE(num_channels, kMaxVorbisChannels);
45
46   // Opus uses Vorbis channel layout.
47   const int32 num_layouts = kMaxVorbisChannels;
48   const int32 num_layout_values = kMaxVorbisChannels;
49
50   // Vorbis channel ordering for streams with >= 2 channels:
51   // 2 Channels
52   //   L, R
53   // 3 Channels
54   //   L, Center, R
55   // 4 Channels
56   //   Front L, Front R, Back L, Back R
57   // 5 Channels
58   //   Front L, Center, Front R, Back L, Back R
59   // 6 Channels (5.1)
60   //   Front L, Center, Front R, Back L, Back R, LFE
61   // 7 channels (6.1)
62   //   Front L, Front Center, Front R, Side L, Side R, Back Center, LFE
63   // 8 Channels (7.1)
64   //   Front L, Center, Front R, Side L, Side R, Back L, Back R, LFE
65   //
66   // Channel ordering information is taken from section 4.3.9 of the Vorbis I
67   // Specification:
68   // http://xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-800004.3.9
69
70   // These are the FFmpeg channel layouts expressed using the position of each
71   // channel in the output stream from libopus.
72   const uint8 kFFmpegChannelLayouts[num_layouts][num_layout_values] = {
73     { 0 },
74
75     // Stereo: No reorder.
76     { 0, 1 },
77
78     // 3 Channels, from Vorbis order to:
79     //  L, R, Center
80     { 0, 2, 1 },
81
82     // 4 Channels: No reorder.
83     { 0, 1, 2, 3 },
84
85     // 5 Channels, from Vorbis order to:
86     //  Front L, Front R, Center, Back L, Back R
87     { 0, 2, 1, 3, 4 },
88
89     // 6 Channels (5.1), from Vorbis order to:
90     //  Front L, Front R, Center, LFE, Back L, Back R
91     { 0, 2, 1, 5, 3, 4 },
92
93     // 7 Channels (6.1), from Vorbis order to:
94     //  Front L, Front R, Front Center, LFE, Side L, Side R, Back Center
95     { 0, 2, 1, 6, 3, 4, 5 },
96
97     // 8 Channels (7.1), from Vorbis order to:
98     //  Front L, Front R, Center, LFE, Back L, Back R, Side L, Side R
99     { 0, 2, 1, 7, 5, 6, 3, 4 },
100   };
101
102   // Reorder the channels to produce the same ordering as FFmpeg, which is
103   // what the pipeline expects.
104   const uint8* vorbis_layout_offset = kFFmpegChannelLayouts[num_channels - 1];
105   for (int channel = 0; channel < num_channels; ++channel)
106     channel_layout[channel] = opus_mapping[vorbis_layout_offset[channel]];
107 }
108
109 // Opus Extra Data contents:
110 // - "OpusHead" (64 bits)
111 // - version number (8 bits)
112 // - Channels C (8 bits)
113 // - Pre-skip (16 bits)
114 // - Sampling rate (32 bits)
115 // - Gain in dB (16 bits, S7.8)
116 // - Mapping (8 bits, 0=single stream (mono/stereo) 1=Vorbis mapping,
117 //            2..254: reserved, 255: multistream with no mapping)
118 //
119 // - if (mapping != 0)
120 //    - N = totel number of streams (8 bits)
121 //    - M = number of paired streams (8 bits)
122 //    - C times channel origin
123 //         - if (C<2*M)
124 //            - stream = byte/2
125 //            - if (byte&0x1 == 0)
126 //                - left
127 //              else
128 //                - right
129 //         - else
130 //            - stream = byte-M
131
132 // Default audio output channel layout. Used to initialize |stream_map| in
133 // OpusExtraData, and passed to opus_multistream_decoder_create() when the
134 // extra data does not contain mapping information. The values are valid only
135 // for mono and stereo output: Opus streams with more than 2 channels require a
136 // stream map.
137 static const int kMaxChannelsWithDefaultLayout = 2;
138 static const uint8 kDefaultOpusChannelLayout[kMaxChannelsWithDefaultLayout] = {
139     0, 1 };
140
141 // Size of the Opus extra data excluding optional mapping information.
142 static const int kOpusExtraDataSize = 19;
143
144 // Offset to the channel count byte in the Opus extra data.
145 static const int kOpusExtraDataChannelsOffset = 9;
146
147 // Offset to the pre-skip value in the Opus extra data.
148 static const int kOpusExtraDataSkipSamplesOffset = 10;
149
150 // Offset to the gain value in the Opus extra data.
151 static const int kOpusExtraDataGainOffset = 16;
152
153 // Offset to the channel mapping byte in the Opus extra data.
154 static const int kOpusExtraDataChannelMappingOffset = 18;
155
156 // Extra Data contains a stream map. The mapping values are in extra data beyond
157 // the always present |kOpusExtraDataSize| bytes of data. The mapping data
158 // contains stream count, coupling information, and per channel mapping values:
159 //   - Byte 0: Number of streams.
160 //   - Byte 1: Number coupled.
161 //   - Byte 2: Starting at byte 2 are |extra_data->channels| uint8 mapping
162 //             values.
163 static const int kOpusExtraDataNumStreamsOffset = kOpusExtraDataSize;
164 static const int kOpusExtraDataNumCoupledOffset =
165     kOpusExtraDataNumStreamsOffset + 1;
166 static const int kOpusExtraDataStreamMapOffset =
167     kOpusExtraDataNumStreamsOffset + 2;
168
169 struct OpusExtraData {
170   OpusExtraData()
171       : channels(0),
172         skip_samples(0),
173         channel_mapping(0),
174         num_streams(0),
175         num_coupled(0),
176         gain_db(0) {
177     memcpy(stream_map,
178            kDefaultOpusChannelLayout,
179            kMaxChannelsWithDefaultLayout);
180   }
181   int channels;
182   uint16 skip_samples;
183   int channel_mapping;
184   int num_streams;
185   int num_coupled;
186   int16 gain_db;
187   uint8 stream_map[kMaxVorbisChannels];
188 };
189
190 // Returns true when able to successfully parse and store Opus extra data in
191 // |extra_data|. Based on opus header parsing code in libopusdec from FFmpeg,
192 // and opus_header from Xiph's opus-tools project.
193 static bool ParseOpusExtraData(const uint8* data, int data_size,
194                                const AudioDecoderConfig& config,
195                                OpusExtraData* extra_data) {
196   if (data_size < kOpusExtraDataSize) {
197     DLOG(ERROR) << "Extra data size is too small:" << data_size;
198     return false;
199   }
200
201   extra_data->channels = *(data + kOpusExtraDataChannelsOffset);
202
203   if (extra_data->channels <= 0 || extra_data->channels > kMaxVorbisChannels) {
204     DLOG(ERROR) << "invalid channel count in extra data: "
205                 << extra_data->channels;
206     return false;
207   }
208
209   extra_data->skip_samples =
210       ReadLE16(data, data_size, kOpusExtraDataSkipSamplesOffset);
211   extra_data->gain_db = static_cast<int16>(
212       ReadLE16(data, data_size, kOpusExtraDataGainOffset));
213
214   extra_data->channel_mapping = *(data + kOpusExtraDataChannelMappingOffset);
215
216   if (!extra_data->channel_mapping) {
217     if (extra_data->channels > kMaxChannelsWithDefaultLayout) {
218       DLOG(ERROR) << "Invalid extra data, missing stream map.";
219       return false;
220     }
221
222     extra_data->num_streams = 1;
223     extra_data->num_coupled =
224         (ChannelLayoutToChannelCount(config.channel_layout()) > 1) ? 1 : 0;
225     return true;
226   }
227
228   if (data_size < kOpusExtraDataStreamMapOffset + extra_data->channels) {
229     DLOG(ERROR) << "Invalid stream map; insufficient data for current channel "
230                 << "count: " << extra_data->channels;
231     return false;
232   }
233
234   extra_data->num_streams = *(data + kOpusExtraDataNumStreamsOffset);
235   extra_data->num_coupled = *(data + kOpusExtraDataNumCoupledOffset);
236
237   if (extra_data->num_streams + extra_data->num_coupled != extra_data->channels)
238     DVLOG(1) << "Inconsistent channel mapping.";
239
240   for (int i = 0; i < extra_data->channels; ++i)
241     extra_data->stream_map[i] = *(data + kOpusExtraDataStreamMapOffset + i);
242   return true;
243 }
244
245 OpusAudioDecoder::OpusAudioDecoder(
246     const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
247     : task_runner_(task_runner),
248       opus_decoder_(NULL),
249       start_input_timestamp_(kNoTimestamp()) {}
250
251 void OpusAudioDecoder::Initialize(const AudioDecoderConfig& config,
252                                   const PipelineStatusCB& status_cb,
253                                   const OutputCB& output_cb) {
254   DCHECK(task_runner_->BelongsToCurrentThread());
255   PipelineStatusCB initialize_cb = BindToCurrentLoop(status_cb);
256
257   config_ = config;
258   output_cb_ = BindToCurrentLoop(output_cb);
259
260   if (!ConfigureDecoder()) {
261     initialize_cb.Run(DECODER_ERROR_NOT_SUPPORTED);
262     return;
263   }
264
265   initialize_cb.Run(PIPELINE_OK);
266 }
267
268 void OpusAudioDecoder::Decode(const scoped_refptr<DecoderBuffer>& buffer,
269                               const DecodeCB& decode_cb) {
270   DCHECK(task_runner_->BelongsToCurrentThread());
271   DCHECK(!decode_cb.is_null());
272
273   DecodeBuffer(buffer, BindToCurrentLoop(decode_cb));
274 }
275
276 void OpusAudioDecoder::Reset(const base::Closure& closure) {
277   DCHECK(task_runner_->BelongsToCurrentThread());
278
279   opus_multistream_decoder_ctl(opus_decoder_, OPUS_RESET_STATE);
280   ResetTimestampState();
281   task_runner_->PostTask(FROM_HERE, closure);
282 }
283
284 void OpusAudioDecoder::Stop() {
285   DCHECK(task_runner_->BelongsToCurrentThread());
286
287   if (!opus_decoder_)
288     return;
289
290   opus_multistream_decoder_ctl(opus_decoder_, OPUS_RESET_STATE);
291   ResetTimestampState();
292   CloseDecoder();
293 }
294
295 OpusAudioDecoder::~OpusAudioDecoder() {}
296
297 void OpusAudioDecoder::DecodeBuffer(
298     const scoped_refptr<DecoderBuffer>& input,
299     const DecodeCB& decode_cb) {
300   DCHECK(task_runner_->BelongsToCurrentThread());
301   DCHECK(!decode_cb.is_null());
302
303   DCHECK(input.get());
304
305   // Libopus does not buffer output. Decoding is complete when an end of stream
306   // input buffer is received.
307   if (input->end_of_stream()) {
308     decode_cb.Run(kOk);
309     return;
310   }
311
312   // Make sure we are notified if http://crbug.com/49709 returns.  Issue also
313   // occurs with some damaged files.
314   if (input->timestamp() == kNoTimestamp()) {
315     DLOG(ERROR) << "Received a buffer without timestamps!";
316     decode_cb.Run(kDecodeError);
317     return;
318   }
319
320   // Apply the necessary codec delay.
321   if (start_input_timestamp_ == kNoTimestamp())
322     start_input_timestamp_ = input->timestamp();
323   if (!discard_helper_->initialized() &&
324       input->timestamp() == start_input_timestamp_) {
325     discard_helper_->Reset(config_.codec_delay());
326   }
327
328   scoped_refptr<AudioBuffer> output_buffer;
329
330   if (!Decode(input, &output_buffer)) {
331     decode_cb.Run(kDecodeError);
332     return;
333   }
334
335   if (output_buffer) {
336     output_cb_.Run(output_buffer);
337   }
338
339   decode_cb.Run(kOk);
340 }
341
342 bool OpusAudioDecoder::ConfigureDecoder() {
343   if (config_.codec() != kCodecOpus) {
344     DVLOG(1) << "Codec must be kCodecOpus.";
345     return false;
346   }
347
348   const int channel_count =
349       ChannelLayoutToChannelCount(config_.channel_layout());
350   if (!config_.IsValidConfig() || channel_count > kMaxVorbisChannels) {
351     DLOG(ERROR) << "Invalid or unsupported audio stream -"
352                 << " codec: " << config_.codec()
353                 << " channel count: " << channel_count
354                 << " channel layout: " << config_.channel_layout()
355                 << " bits per channel: " << config_.bits_per_channel()
356                 << " samples per second: " << config_.samples_per_second();
357     return false;
358   }
359
360   if (config_.is_encrypted()) {
361     DLOG(ERROR) << "Encrypted audio stream not supported.";
362     return false;
363   }
364
365   // Clean up existing decoder if necessary.
366   CloseDecoder();
367
368   // Parse the Opus Extra Data.
369   OpusExtraData opus_extra_data;
370   if (!ParseOpusExtraData(config_.extra_data(), config_.extra_data_size(),
371                           config_,
372                           &opus_extra_data))
373     return false;
374
375   if (config_.codec_delay() < 0) {
376     DLOG(ERROR) << "Invalid file. Incorrect value for codec delay: "
377                 << config_.codec_delay();
378     return false;
379   }
380
381   if (config_.codec_delay() != opus_extra_data.skip_samples) {
382     DLOG(ERROR) << "Invalid file. Codec Delay in container does not match the "
383                 << "value in Opus Extra Data. " << config_.codec_delay()
384                 << " vs " << opus_extra_data.skip_samples;
385     return false;
386   }
387
388   uint8 channel_mapping[kMaxVorbisChannels] = {0};
389   memcpy(&channel_mapping,
390          kDefaultOpusChannelLayout,
391          kMaxChannelsWithDefaultLayout);
392
393   if (channel_count > kMaxChannelsWithDefaultLayout) {
394     RemapOpusChannelLayout(opus_extra_data.stream_map,
395                            channel_count,
396                            channel_mapping);
397   }
398
399   // Init Opus.
400   int status = OPUS_INVALID_STATE;
401   opus_decoder_ = opus_multistream_decoder_create(config_.samples_per_second(),
402                                                   channel_count,
403                                                   opus_extra_data.num_streams,
404                                                   opus_extra_data.num_coupled,
405                                                   channel_mapping,
406                                                   &status);
407   if (!opus_decoder_ || status != OPUS_OK) {
408     DLOG(ERROR) << "opus_multistream_decoder_create failed status="
409                 << opus_strerror(status);
410     return false;
411   }
412
413   status = opus_multistream_decoder_ctl(
414       opus_decoder_, OPUS_SET_GAIN(opus_extra_data.gain_db));
415   if (status != OPUS_OK) {
416     DLOG(ERROR) << "Failed to set OPUS header gain; status="
417                 << opus_strerror(status);
418     return false;
419   }
420
421   discard_helper_.reset(
422       new AudioDiscardHelper(config_.samples_per_second(), 0));
423   start_input_timestamp_ = kNoTimestamp();
424   return true;
425 }
426
427 void OpusAudioDecoder::CloseDecoder() {
428   if (opus_decoder_) {
429     opus_multistream_decoder_destroy(opus_decoder_);
430     opus_decoder_ = NULL;
431   }
432 }
433
434 void OpusAudioDecoder::ResetTimestampState() {
435   discard_helper_->Reset(
436       discard_helper_->TimeDeltaToFrames(config_.seek_preroll()));
437 }
438
439 bool OpusAudioDecoder::Decode(const scoped_refptr<DecoderBuffer>& input,
440                               scoped_refptr<AudioBuffer>* output_buffer) {
441   // Allocate a buffer for the output samples.
442   *output_buffer = AudioBuffer::CreateBuffer(
443       config_.sample_format(),
444       config_.channel_layout(),
445       ChannelLayoutToChannelCount(config_.channel_layout()),
446       config_.samples_per_second(),
447       kMaxOpusOutputPacketSizeSamples);
448   const int buffer_size =
449       output_buffer->get()->channel_count() *
450       output_buffer->get()->frame_count() *
451       SampleFormatToBytesPerChannel(config_.sample_format());
452
453   float* float_output_buffer = reinterpret_cast<float*>(
454       output_buffer->get()->channel_data()[0]);
455   const int frames_decoded =
456       opus_multistream_decode_float(opus_decoder_,
457                                     input->data(),
458                                     input->data_size(),
459                                     float_output_buffer,
460                                     buffer_size,
461                                     0);
462
463   if (frames_decoded < 0) {
464     DLOG(ERROR) << "opus_multistream_decode failed for"
465                 << " timestamp: " << input->timestamp().InMicroseconds()
466                 << " us, duration: " << input->duration().InMicroseconds()
467                 << " us, packet size: " << input->data_size() << " bytes with"
468                 << " status: " << opus_strerror(frames_decoded);
469     return false;
470   }
471
472   // Trim off any extraneous allocation.
473   DCHECK_LE(frames_decoded, output_buffer->get()->frame_count());
474   const int trim_frames = output_buffer->get()->frame_count() - frames_decoded;
475   if (trim_frames > 0)
476     output_buffer->get()->TrimEnd(trim_frames);
477
478   // Handles discards and timestamping.  Discard the buffer if more data needed.
479   if (!discard_helper_->ProcessBuffers(input, *output_buffer))
480     *output_buffer = NULL;
481
482   return true;
483 }
484
485 }  // namespace media