Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(466)

Side by Side Diff: chromecast/media/cma/decoder/cast_audio_decoder_linux.cc

Issue 1494713002: [Chromecast] Move CastAudioDecoder out to chromecast/media/cma/decoder (Closed) Base URL: https://chromium.googlesource.com/chromium/src@master
Patch Set: remove tracing and compatibility #ifdef Created 5 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « chromecast/media/cma/decoder/cast_audio_decoder_android.cc ('k') | chromecast/media/media.gyp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2015 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 "chromecast/media/cma/decoder/cast_audio_decoder.h"
6
7 #include <limits>
8 #include <queue>
9 #include <vector>
10
11 #include "base/bind.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/single_thread_task_runner.h"
15 #include "chromecast/media/cma/base/decoder_buffer_adapter.h"
16 #include "chromecast/media/cma/base/decoder_buffer_base.h"
17 #include "chromecast/media/cma/base/decoder_config_adapter.h"
18 #include "media/base/audio_buffer.h"
19 #include "media/base/audio_bus.h"
20 #include "media/base/cdm_context.h"
21 #include "media/base/channel_layout.h"
22 #include "media/base/channel_mixer.h"
23 #include "media/base/decoder_buffer.h"
24 #include "media/base/sample_format.h"
25 #include "media/filters/ffmpeg_audio_decoder.h"
26 #include "media/filters/opus_audio_decoder.h"
27
28 namespace chromecast {
29 namespace media {
30
31 namespace {
32
33 const int kOpusSamplingRate = 48000;
34 const uint8 kFakeOpusExtraData[19] = {
35 'O', 'p', 'u', 's', 'H', 'e', 'a', 'd', // offset 0, OpusHead
36 0, // offset 8, version
37 2, // offset 9, channels
38 0, 0, // offset 10, skip
39 static_cast<uint8>(kOpusSamplingRate & 0xFF), // offset 12, LE
40 static_cast<uint8>((kOpusSamplingRate >> 8) & 0xFF),
41 static_cast<uint8>((kOpusSamplingRate >> 16) & 0xFF),
42 static_cast<uint8>((kOpusSamplingRate >> 24) & 0xFF),
43 0, 0, // offset 16, gain
44 0, // offset 18, stereo mapping
45 };
46
47 const int kOutputChannelCount = 2; // Always output stereo audio.
48 const int kMaxChannelInput = 2;
49
50 class CastAudioDecoderImpl : public CastAudioDecoder {
51 public:
52 CastAudioDecoderImpl(
53 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
54 const InitializedCallback& initialized_callback,
55 OutputFormat output_format)
56 : task_runner_(task_runner),
57 initialized_callback_(initialized_callback),
58 output_format_(output_format),
59 initialized_(false),
60 decode_pending_(false),
61 weak_factory_(this) {}
62
63 ~CastAudioDecoderImpl() override {}
64
65 void Initialize(const media::AudioConfig& config) {
66 DCHECK(!initialized_);
67 DCHECK_LE(config_.channel_number, kMaxChannelInput);
68 config_ = config;
69 if (config_.channel_number == 1) {
70 // If the input is mono, create a ChannelMixer to convert mono to stereo.
71 // TODO(kmackay) Support other channel format conversions?
72 mixer_.reset(new ::media::ChannelMixer(::media::CHANNEL_LAYOUT_MONO,
73 ::media::CHANNEL_LAYOUT_STEREO));
74 }
75 base::WeakPtr<CastAudioDecoderImpl> self = weak_factory_.GetWeakPtr();
76 if (config.codec == media::kCodecOpus) {
77 // Insert fake extradata to make OpusAudioDecoder work with v2mirroring.
78 if (config_.extra_data.empty() &&
79 config_.samples_per_second == kOpusSamplingRate &&
80 config_.channel_number == 2)
81 config_.extra_data.assign(
82 kFakeOpusExtraData,
83 kFakeOpusExtraData + sizeof(kFakeOpusExtraData));
84 decoder_.reset(new ::media::OpusAudioDecoder(task_runner_));
85 } else {
86 decoder_.reset(new ::media::FFmpegAudioDecoder(
87 task_runner_, make_scoped_refptr(new ::media::MediaLog())));
88 }
89 decoder_->Initialize(
90 media::DecoderConfigAdapter::ToMediaAudioDecoderConfig(config_),
91 ::media::SetCdmReadyCB(),
92 base::Bind(&CastAudioDecoderImpl::OnInitialized, self),
93 base::Bind(&CastAudioDecoderImpl::OnDecoderOutput, self));
94 // Unfortunately there is no result from decoder_->Initialize() until later
95 // (the pipeline status callback is posted to the task runner).
96 }
97
98 // CastAudioDecoder implementation:
99 bool Decode(const scoped_refptr<media::DecoderBufferBase>& data,
100 const DecodeCallback& decode_callback) override {
101 DCHECK(!decode_callback.is_null());
102 DCHECK(task_runner_->BelongsToCurrentThread());
103 if (!initialized_ || decode_pending_) {
104 decode_queue_.push(std::make_pair(data, decode_callback));
105 } else {
106 DecodeNow(data, decode_callback);
107 }
108 return true;
109 }
110
111 private:
112 typedef std::pair<scoped_refptr<media::DecoderBufferBase>, DecodeCallback>
113 DecodeBufferCallbackPair;
114
115 void DecodeNow(const scoped_refptr<media::DecoderBufferBase>& data,
116 const DecodeCallback& decode_callback) {
117 if (data->end_of_stream()) {
118 // Post the task to ensure that |decode_callback| is not called from
119 // within a call to Decode().
120 task_runner_->PostTask(FROM_HERE,
121 base::Bind(decode_callback, kDecodeOk, data));
122 return;
123 }
124
125 // FFmpegAudioDecoder requires a timestamp to be set.
126 base::TimeDelta timestamp =
127 base::TimeDelta::FromMicroseconds(data->timestamp());
128 if (timestamp == ::media::kNoTimestamp())
129 data->set_timestamp(base::TimeDelta());
130
131 decode_pending_ = true;
132 decoder_->Decode(data->ToMediaBuffer(),
133 base::Bind(&CastAudioDecoderImpl::OnDecodeStatus,
134 weak_factory_.GetWeakPtr(),
135 timestamp,
136 decode_callback));
137 }
138
139 void OnInitialized(bool success) {
140 DCHECK(!initialized_);
141 LOG_IF(ERROR, !success) << "Failed to initialize FFmpegAudioDecoder";
142 if (success)
143 initialized_ = true;
144
145 if (success && !decode_queue_.empty()) {
146 const auto& d = decode_queue_.front();
147 DecodeNow(d.first, d.second);
148 decode_queue_.pop();
149 }
150
151 if (!initialized_callback_.is_null())
152 initialized_callback_.Run(initialized_);
153 }
154
155 void OnDecodeStatus(base::TimeDelta buffer_timestamp,
156 const DecodeCallback& decode_callback,
157 ::media::AudioDecoder::Status status) {
158 Status result_status = kDecodeOk;
159 scoped_refptr<media::DecoderBufferBase> decoded;
160 if (status == ::media::AudioDecoder::kOk && !decoded_chunks_.empty()) {
161 decoded = ConvertDecoded();
162 } else {
163 if (status != ::media::AudioDecoder::kOk)
164 result_status = kDecodeError;
165 decoded = new media::DecoderBufferAdapter(config_.id,
166 new ::media::DecoderBuffer(0));
167 }
168 decoded_chunks_.clear();
169 decoded->set_timestamp(buffer_timestamp);
170 decode_callback.Run(result_status, decoded);
171
172 // Do not reset decode_pending_ to false until after the callback has
173 // finished running because the callback may call Decode().
174 decode_pending_ = false;
175
176 if (decode_queue_.empty())
177 return;
178
179 const auto& d = decode_queue_.front();
180 // Calling DecodeNow() here does not result in a loop, because
181 // OnDecodeStatus() is always called asynchronously (guaranteed by the
182 // AudioDecoder interface).
183 DecodeNow(d.first, d.second);
184 decode_queue_.pop();
185 }
186
187 void OnDecoderOutput(const scoped_refptr<::media::AudioBuffer>& decoded) {
188 decoded_chunks_.push_back(decoded);
189 }
190
191 scoped_refptr<media::DecoderBufferBase> ConvertDecoded() {
192 DCHECK(!decoded_chunks_.empty());
193 int num_frames = 0;
194 for (auto& chunk : decoded_chunks_)
195 num_frames += chunk->frame_count();
196
197 // Copy decoded data into an AudioBus for conversion.
198 scoped_ptr<::media::AudioBus> decoded =
199 ::media::AudioBus::Create(config_.channel_number, num_frames);
200 int bus_frame_offset = 0;
201 for (auto& chunk : decoded_chunks_) {
202 chunk->ReadFrames(
203 chunk->frame_count(), 0, bus_frame_offset, decoded.get());
204 bus_frame_offset += chunk->frame_count();
205 }
206
207 if (mixer_) {
208 // Convert to stereo if necessary.
209 scoped_ptr<::media::AudioBus> converted_to_stereo =
210 ::media::AudioBus::Create(kOutputChannelCount, num_frames);
211 mixer_->Transform(decoded.get(), converted_to_stereo.get());
212 decoded.swap(converted_to_stereo);
213 }
214
215 // Convert to the desired output format.
216 return FinishConversion(decoded.get());
217 }
218
219 scoped_refptr<media::DecoderBufferBase> FinishConversion(
220 ::media::AudioBus* bus) {
221 DCHECK_EQ(kOutputChannelCount, bus->channels());
222 int size = bus->frames() * kOutputChannelCount *
223 OutputFormatSizeInBytes(output_format_);
224 scoped_refptr<::media::DecoderBuffer> result(
225 new ::media::DecoderBuffer(size));
226
227 if (output_format_ == kOutputSigned16) {
228 bus->ToInterleaved(bus->frames(),
229 OutputFormatSizeInBytes(output_format_),
230 result->writable_data());
231 } else if (output_format_ == kOutputPlanarFloat) {
232 // Data in an AudioBus is already in planar float format; just copy each
233 // channel into the result buffer in order.
234 float* ptr = reinterpret_cast<float*>(result->writable_data());
235 for (int c = 0; c < bus->channels(); ++c) {
236 memcpy(ptr, bus->channel(c), bus->frames() * sizeof(float));
237 ptr += bus->frames();
238 }
239 } else {
240 NOTREACHED();
241 }
242
243 result->set_duration(base::TimeDelta::FromMicroseconds(
244 bus->frames() * base::Time::kMicrosecondsPerSecond /
245 config_.samples_per_second));
246 return make_scoped_refptr(
247 new media::DecoderBufferAdapter(config_.id, result));
248 }
249
250 const scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
251 InitializedCallback initialized_callback_;
252 OutputFormat output_format_;
253 media::AudioConfig config_;
254 scoped_ptr<::media::AudioDecoder> decoder_;
255 std::queue<DecodeBufferCallbackPair> decode_queue_;
256 bool initialized_;
257 scoped_ptr<::media::ChannelMixer> mixer_;
258 bool decode_pending_;
259 std::vector<scoped_refptr<::media::AudioBuffer>> decoded_chunks_;
260 base::WeakPtrFactory<CastAudioDecoderImpl> weak_factory_;
261
262 DISALLOW_COPY_AND_ASSIGN(CastAudioDecoderImpl);
263 };
264
265 } // namespace
266
267 // static
268 scoped_ptr<CastAudioDecoder> CastAudioDecoder::Create(
269 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
270 const media::AudioConfig& config,
271 OutputFormat output_format,
272 const InitializedCallback& initialized_callback) {
273 scoped_ptr<CastAudioDecoderImpl> decoder(new CastAudioDecoderImpl(
274 task_runner, initialized_callback, output_format));
275 decoder->Initialize(config);
276 return decoder.Pass();
277 }
278
279 // static
280 int CastAudioDecoder::OutputFormatSizeInBytes(
281 CastAudioDecoder::OutputFormat format) {
282 switch (format) {
283 case CastAudioDecoder::OutputFormat::kOutputSigned16:
284 return 2;
285 case CastAudioDecoder::OutputFormat::kOutputPlanarFloat:
286 return 4;
287 }
288 NOTREACHED();
289 return 1;
290 }
291
292 } // namespace media
293 } // namespace chromecast
OLDNEW
« no previous file with comments | « chromecast/media/cma/decoder/cast_audio_decoder_android.cc ('k') | chromecast/media/media.gyp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698