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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/renderers/audio_renderer_impl.h"
#include <math.h>
#include <algorithm>
#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/single_thread_task_runner.h"
#include "base/time/default_tick_clock.h"
#include "build/build_config.h"
#include "media/base/audio_buffer.h"
#include "media/base/audio_buffer_converter.h"
#include "media/base/audio_hardware_config.h"
#include "media/base/audio_splicer.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/demuxer_stream.h"
#include "media/base/media_log.h"
#include "media/base/timestamp_constants.h"
#include "media/filters/audio_clock.h"
#include "media/filters/decrypting_demuxer_stream.h"
namespace media {
namespace {
enum AudioRendererEvent {
INITIALIZED,
RENDER_ERROR,
RENDER_EVENT_MAX = RENDER_ERROR,
};
void HistogramRendererEvent(AudioRendererEvent event) {
UMA_HISTOGRAM_ENUMERATION(
"Media.AudioRendererEvents", event, RENDER_EVENT_MAX + 1);
}
} // namespace
AudioRendererImpl::AudioRendererImpl(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
media::AudioRendererSink* sink,
ScopedVector<AudioDecoder> decoders,
const AudioHardwareConfig& hardware_config,
const scoped_refptr<MediaLog>& media_log)
: task_runner_(task_runner),
expecting_config_changes_(false),
sink_(sink),
audio_buffer_stream_(
new AudioBufferStream(task_runner, decoders.Pass(), media_log)),
hardware_config_(hardware_config),
media_log_(media_log),
tick_clock_(new base::DefaultTickClock()),
last_audio_memory_usage_(0),
playback_rate_(0.0),
state_(kUninitialized),
buffering_state_(BUFFERING_HAVE_NOTHING),
rendering_(false),
sink_playing_(false),
pending_read_(false),
received_end_of_stream_(false),
rendered_end_of_stream_(false),
weak_factory_(this) {
audio_buffer_stream_->set_splice_observer(base::Bind(
&AudioRendererImpl::OnNewSpliceBuffer, weak_factory_.GetWeakPtr()));
audio_buffer_stream_->set_config_change_observer(base::Bind(
&AudioRendererImpl::OnConfigChange, weak_factory_.GetWeakPtr()));
}
AudioRendererImpl::~AudioRendererImpl() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
// If Render() is in progress, this call will wait for Render() to finish.
// After this call, the |sink_| will not call back into |this| anymore.
sink_->Stop();
if (!init_cb_.is_null())
base::ResetAndReturn(&init_cb_).Run(PIPELINE_ERROR_ABORT);
}
void AudioRendererImpl::StartTicking() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(!rendering_);
rendering_ = true;
base::AutoLock auto_lock(lock_);
// Wait for an eventual call to SetPlaybackRate() to start rendering.
if (playback_rate_ == 0) {
DCHECK(!sink_playing_);
return;
}
StartRendering_Locked();
}
void AudioRendererImpl::StartRendering_Locked() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, kPlaying);
DCHECK(!sink_playing_);
DCHECK_NE(playback_rate_, 0.0);
lock_.AssertAcquired();
sink_playing_ = true;
base::AutoUnlock auto_unlock(lock_);
sink_->Play();
}
void AudioRendererImpl::StopTicking() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(rendering_);
rendering_ = false;
base::AutoLock auto_lock(lock_);
// Rendering should have already been stopped with a zero playback rate.
if (playback_rate_ == 0) {
DCHECK(!sink_playing_);
return;
}
StopRendering_Locked();
}
void AudioRendererImpl::StopRendering_Locked() {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, kPlaying);
DCHECK(sink_playing_);
lock_.AssertAcquired();
sink_playing_ = false;
base::AutoUnlock auto_unlock(lock_);
sink_->Pause();
stop_rendering_time_ = last_render_time_;
}
void AudioRendererImpl::SetMediaTime(base::TimeDelta time) {
DVLOG(1) << __FUNCTION__ << "(" << time << ")";
DCHECK(task_runner_->BelongsToCurrentThread());
base::AutoLock auto_lock(lock_);
DCHECK(!rendering_);
DCHECK_EQ(state_, kFlushed);
start_timestamp_ = time;
ended_timestamp_ = kInfiniteDuration();
last_render_time_ = stop_rendering_time_ = base::TimeTicks();
first_packet_timestamp_ = kNoTimestamp();
audio_clock_.reset(new AudioClock(time, audio_parameters_.sample_rate()));
}
base::TimeDelta AudioRendererImpl::CurrentMediaTime() {
// In practice the Render() method is called with a high enough frequency
// that returning only the front timestamp is good enough and also prevents
// returning values that go backwards in time.
base::TimeDelta current_media_time;
{
base::AutoLock auto_lock(lock_);
current_media_time = audio_clock_->front_timestamp();
}
DVLOG(2) << __FUNCTION__ << ": " << current_media_time;
return current_media_time;
}
bool AudioRendererImpl::GetWallClockTimes(
const std::vector<base::TimeDelta>& media_timestamps,
std::vector<base::TimeTicks>* wall_clock_times) {
base::AutoLock auto_lock(lock_);
DCHECK(wall_clock_times->empty());
// When playback is paused (rate is zero), assume a rate of 1.0.
const double playback_rate = playback_rate_ ? playback_rate_ : 1.0;
const bool is_time_moving = sink_playing_ && playback_rate_ &&
!last_render_time_.is_null() &&
stop_rendering_time_.is_null();
// Pre-compute the time until playback of the audio buffer extents, since
// these values are frequently used below.
const base::TimeDelta time_until_front =
audio_clock_->TimeUntilPlayback(audio_clock_->front_timestamp());
const base::TimeDelta time_until_back =
audio_clock_->TimeUntilPlayback(audio_clock_->back_timestamp());
if (media_timestamps.empty()) {
// Return the current media time as a wall clock time while accounting for
// frames which may be in the process of play out.
wall_clock_times->push_back(std::min(
std::max(tick_clock_->NowTicks(), last_render_time_ + time_until_front),
last_render_time_ + time_until_back));
return is_time_moving;
}
wall_clock_times->reserve(media_timestamps.size());
for (const auto& media_timestamp : media_timestamps) {
// When time was or is moving and the requested media timestamp is within
// range of played out audio, we can provide an exact conversion.
if (!last_render_time_.is_null() &&
media_timestamp >= audio_clock_->front_timestamp() &&
media_timestamp <= audio_clock_->back_timestamp()) {
wall_clock_times->push_back(
last_render_time_ + audio_clock_->TimeUntilPlayback(media_timestamp));
continue;
}
base::TimeDelta base_timestamp, time_until_playback;
if (media_timestamp < audio_clock_->front_timestamp()) {
base_timestamp = audio_clock_->front_timestamp();
time_until_playback = time_until_front;
} else {
base_timestamp = audio_clock_->back_timestamp();
time_until_playback = time_until_back;
}
// In practice, most calls will be estimates given the relatively small
// window in which clients can get the actual time.
wall_clock_times->push_back(last_render_time_ + time_until_playback +
(media_timestamp - base_timestamp) /
playback_rate);
}
return is_time_moving;
}
TimeSource* AudioRendererImpl::GetTimeSource() {
return this;
}
void AudioRendererImpl::Flush(const base::Closure& callback) {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, kPlaying);
DCHECK(flush_cb_.is_null());
flush_cb_ = callback;
ChangeState_Locked(kFlushing);
if (pending_read_)
return;
ChangeState_Locked(kFlushed);
DoFlush_Locked();
}
void AudioRendererImpl::DoFlush_Locked() {
DCHECK(task_runner_->BelongsToCurrentThread());
lock_.AssertAcquired();
DCHECK(!pending_read_);
DCHECK_EQ(state_, kFlushed);
audio_buffer_stream_->Reset(base::Bind(&AudioRendererImpl::ResetDecoderDone,
weak_factory_.GetWeakPtr()));
}
void AudioRendererImpl::ResetDecoderDone() {
DCHECK(task_runner_->BelongsToCurrentThread());
{
base::AutoLock auto_lock(lock_);
DCHECK_EQ(state_, kFlushed);
DCHECK(!flush_cb_.is_null());
received_end_of_stream_ = false;
rendered_end_of_stream_ = false;
// Flush() may have been called while underflowed/not fully buffered.
if (buffering_state_ != BUFFERING_HAVE_NOTHING)
SetBufferingState_Locked(BUFFERING_HAVE_NOTHING);
splicer_->Reset();
if (buffer_converter_)
buffer_converter_->Reset();
algorithm_->FlushBuffers();
}
// Changes in buffering state are always posted. Flush callback must only be
// run after buffering state has been set back to nothing.
task_runner_->PostTask(FROM_HERE, base::ResetAndReturn(&flush_cb_));
}
void AudioRendererImpl::StartPlaying() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
base::AutoLock auto_lock(lock_);
DCHECK(!sink_playing_);
DCHECK_EQ(state_, kFlushed);
DCHECK_EQ(buffering_state_, BUFFERING_HAVE_NOTHING);
DCHECK(!pending_read_) << "Pending read must complete before seeking";
ChangeState_Locked(kPlaying);
AttemptRead_Locked();
}
void AudioRendererImpl::Initialize(
DemuxerStream* stream,
const PipelineStatusCB& init_cb,
const SetCdmReadyCB& set_cdm_ready_cb,
const StatisticsCB& statistics_cb,
const BufferingStateCB& buffering_state_cb,
const base::Closure& ended_cb,
const PipelineStatusCB& error_cb,
const base::Closure& waiting_for_decryption_key_cb) {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(stream);
DCHECK_EQ(stream->type(), DemuxerStream::AUDIO);
DCHECK(!init_cb.is_null());
DCHECK(!statistics_cb.is_null());
DCHECK(!buffering_state_cb.is_null());
DCHECK(!ended_cb.is_null());
DCHECK(!error_cb.is_null());
DCHECK_EQ(kUninitialized, state_);
DCHECK(sink_.get());
state_ = kInitializing;
// Always post |init_cb_| because |this| could be destroyed if initialization
// failed.
init_cb_ = BindToCurrentLoop(init_cb);
buffering_state_cb_ = buffering_state_cb;
ended_cb_ = ended_cb;
error_cb_ = error_cb;
statistics_cb_ = statistics_cb;
const AudioParameters& hw_params = hardware_config_.GetOutputConfig();
expecting_config_changes_ = stream->SupportsConfigChanges();
if (!expecting_config_changes_ || !hw_params.IsValid()) {
// The actual buffer size is controlled via the size of the AudioBus
// provided to Render(), so just choose something reasonable here for looks.
int buffer_size = stream->audio_decoder_config().samples_per_second() / 100;
audio_parameters_.Reset(
AudioParameters::AUDIO_PCM_LOW_LATENCY,
stream->audio_decoder_config().channel_layout(),
stream->audio_decoder_config().samples_per_second(),
stream->audio_decoder_config().bits_per_channel(),
buffer_size);
buffer_converter_.reset();
} else {
audio_parameters_.Reset(
hw_params.format(),
// Always use the source's channel layout to avoid premature downmixing
// (http://crbug.com/379288), platform specific issues around channel
// layouts (http://crbug.com/266674), and unnecessary upmixing overhead.
stream->audio_decoder_config().channel_layout(),
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
// On ChromeOS and Android let the OS level resampler handle resampling
// unless the initial sample rate is too low; this allows support for
// sample rate adaptations where necessary.
stream->audio_decoder_config().samples_per_second() < 44100
? hw_params.sample_rate()
: stream->audio_decoder_config().samples_per_second(),
#else
hw_params.sample_rate(),
#endif
hw_params.bits_per_sample(),
hardware_config_.GetHighLatencyBufferSize());
}
audio_clock_.reset(
new AudioClock(base::TimeDelta(), audio_parameters_.sample_rate()));
audio_buffer_stream_->Initialize(
stream, base::Bind(&AudioRendererImpl::OnAudioBufferStreamInitialized,
weak_factory_.GetWeakPtr()),
set_cdm_ready_cb, statistics_cb, waiting_for_decryption_key_cb);
}
void AudioRendererImpl::OnAudioBufferStreamInitialized(bool success) {
DVLOG(1) << __FUNCTION__ << ": " << success;
DCHECK(task_runner_->BelongsToCurrentThread());
base::AutoLock auto_lock(lock_);
if (!success) {
state_ = kUninitialized;
base::ResetAndReturn(&init_cb_).Run(DECODER_ERROR_NOT_SUPPORTED);
return;
}
if (!audio_parameters_.IsValid()) {
DVLOG(1) << __FUNCTION__ << ": Invalid audio parameters: "
<< audio_parameters_.AsHumanReadableString();
ChangeState_Locked(kUninitialized);
base::ResetAndReturn(&init_cb_).Run(PIPELINE_ERROR_INITIALIZATION_FAILED);
return;
}
if (expecting_config_changes_)
buffer_converter_.reset(new AudioBufferConverter(audio_parameters_));
splicer_.reset(new AudioSplicer(audio_parameters_.sample_rate(), media_log_));
// We're all good! Continue initializing the rest of the audio renderer
// based on the decoder format.
algorithm_.reset(new AudioRendererAlgorithm());
algorithm_->Initialize(audio_parameters_);
ChangeState_Locked(kFlushed);
HistogramRendererEvent(INITIALIZED);
{
base::AutoUnlock auto_unlock(lock_);
sink_->Initialize(audio_parameters_, this);
sink_->Start();
// Some sinks play on start...
sink_->Pause();
}
DCHECK(!sink_playing_);
base::ResetAndReturn(&init_cb_).Run(PIPELINE_OK);
}
void AudioRendererImpl::SetVolume(float volume) {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(sink_.get());
sink_->SetVolume(volume);
}
void AudioRendererImpl::DecodedAudioReady(
AudioBufferStream::Status status,
const scoped_refptr<AudioBuffer>& buffer) {
DVLOG(2) << __FUNCTION__ << "(" << status << ")";
DCHECK(task_runner_->BelongsToCurrentThread());
base::AutoLock auto_lock(lock_);
DCHECK(state_ != kUninitialized);
CHECK(pending_read_);
pending_read_ = false;
if (status == AudioBufferStream::ABORTED ||
status == AudioBufferStream::DEMUXER_READ_ABORTED) {
HandleAbortedReadOrDecodeError(false);
return;
}
if (status == AudioBufferStream::DECODE_ERROR) {
HandleAbortedReadOrDecodeError(true);
return;
}
DCHECK_EQ(status, AudioBufferStream::OK);
DCHECK(buffer.get());
if (state_ == kFlushing) {
ChangeState_Locked(kFlushed);
DoFlush_Locked();
return;
}
if (expecting_config_changes_) {
DCHECK(buffer_converter_);
buffer_converter_->AddInput(buffer);
while (buffer_converter_->HasNextBuffer()) {
if (!splicer_->AddInput(buffer_converter_->GetNextBuffer())) {
HandleAbortedReadOrDecodeError(true);
return;
}
}
} else {
if (!splicer_->AddInput(buffer)) {
HandleAbortedReadOrDecodeError(true);
return;
}
}
if (!splicer_->HasNextBuffer()) {
AttemptRead_Locked();
return;
}
bool need_another_buffer = false;
while (splicer_->HasNextBuffer())
need_another_buffer = HandleSplicerBuffer_Locked(splicer_->GetNextBuffer());
if (!need_another_buffer && !CanRead_Locked())
return;
AttemptRead_Locked();
}
bool AudioRendererImpl::HandleSplicerBuffer_Locked(
const scoped_refptr<AudioBuffer>& buffer) {
lock_.AssertAcquired();
if (buffer->end_of_stream()) {
received_end_of_stream_ = true;
} else {
if (state_ == kPlaying) {
if (IsBeforeStartTime(buffer))
return true;
// Trim off any additional time before the start timestamp.
const base::TimeDelta trim_time = start_timestamp_ - buffer->timestamp();
if (trim_time > base::TimeDelta()) {
buffer->TrimStart(buffer->frame_count() *
(static_cast<double>(trim_time.InMicroseconds()) /
buffer->duration().InMicroseconds()));
}
// If the entire buffer was trimmed, request a new one.
if (!buffer->frame_count())
return true;
}
if (state_ != kUninitialized)
algorithm_->EnqueueBuffer(buffer);
}
// Store the timestamp of the first packet so we know when to start actual
// audio playback.
if (first_packet_timestamp_ == kNoTimestamp())
first_packet_timestamp_ = buffer->timestamp();
const size_t memory_usage = algorithm_->GetMemoryUsage();
PipelineStatistics stats;
stats.audio_memory_usage = memory_usage - last_audio_memory_usage_;
last_audio_memory_usage_ = memory_usage;
task_runner_->PostTask(FROM_HERE, base::Bind(statistics_cb_, stats));
switch (state_) {
case kUninitialized:
case kInitializing:
case kFlushing:
NOTREACHED();
return false;
case kFlushed:
DCHECK(!pending_read_);
return false;
case kPlaying:
if (buffer->end_of_stream() || algorithm_->IsQueueFull()) {
if (buffering_state_ == BUFFERING_HAVE_NOTHING)
SetBufferingState_Locked(BUFFERING_HAVE_ENOUGH);
return false;
}
return true;
}
return false;
}
void AudioRendererImpl::AttemptRead() {
base::AutoLock auto_lock(lock_);
AttemptRead_Locked();
}
void AudioRendererImpl::AttemptRead_Locked() {
DCHECK(task_runner_->BelongsToCurrentThread());
lock_.AssertAcquired();
if (!CanRead_Locked())
return;
pending_read_ = true;
audio_buffer_stream_->Read(base::Bind(&AudioRendererImpl::DecodedAudioReady,
weak_factory_.GetWeakPtr()));
}
bool AudioRendererImpl::CanRead_Locked() {
lock_.AssertAcquired();
switch (state_) {
case kUninitialized:
case kInitializing:
case kFlushing:
case kFlushed:
return false;
case kPlaying:
break;
}
return !pending_read_ && !received_end_of_stream_ &&
!algorithm_->IsQueueFull();
}
void AudioRendererImpl::SetPlaybackRate(double playback_rate) {
DVLOG(1) << __FUNCTION__ << "(" << playback_rate << ")";
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_GE(playback_rate, 0);
DCHECK(sink_.get());
base::AutoLock auto_lock(lock_);
// We have two cases here:
// Play: current_playback_rate == 0 && playback_rate != 0
// Pause: current_playback_rate != 0 && playback_rate == 0
double current_playback_rate = playback_rate_;
playback_rate_ = playback_rate;
if (!rendering_)
return;
if (current_playback_rate == 0 && playback_rate != 0) {
StartRendering_Locked();
return;
}
if (current_playback_rate != 0 && playback_rate == 0) {
StopRendering_Locked();
return;
}
}
bool AudioRendererImpl::IsBeforeStartTime(
const scoped_refptr<AudioBuffer>& buffer) {
DCHECK_EQ(state_, kPlaying);
return buffer.get() && !buffer->end_of_stream() &&
(buffer->timestamp() + buffer->duration()) < start_timestamp_;
}
int AudioRendererImpl::Render(AudioBus* audio_bus,
uint32_t audio_delay_milliseconds,
uint32_t frames_skipped) {
const int requested_frames = audio_bus->frames();
base::TimeDelta playback_delay = base::TimeDelta::FromMilliseconds(
audio_delay_milliseconds);
const int delay_frames = static_cast<int>(playback_delay.InSecondsF() *
audio_parameters_.sample_rate());
int frames_written = 0;
{
base::AutoLock auto_lock(lock_);
last_render_time_ = tick_clock_->NowTicks();
if (!stop_rendering_time_.is_null()) {
audio_clock_->CompensateForSuspendedWrites(
last_render_time_ - stop_rendering_time_, delay_frames);
stop_rendering_time_ = base::TimeTicks();
}
// Ensure Stop() hasn't destroyed our |algorithm_| on the pipeline thread.
if (!algorithm_) {
audio_clock_->WroteAudio(
0, requested_frames, delay_frames, playback_rate_);
return 0;
}
if (playback_rate_ == 0) {
audio_clock_->WroteAudio(
0, requested_frames, delay_frames, playback_rate_);
return 0;
}
// Mute audio by returning 0 when not playing.
if (state_ != kPlaying) {
audio_clock_->WroteAudio(
0, requested_frames, delay_frames, playback_rate_);
return 0;
}
// Delay playback by writing silence if we haven't reached the first
// timestamp yet; this can occur if the video starts before the audio.
if (algorithm_->frames_buffered() > 0) {
DCHECK(first_packet_timestamp_ != kNoTimestamp());
const base::TimeDelta play_delay =
first_packet_timestamp_ - audio_clock_->back_timestamp();
if (play_delay > base::TimeDelta()) {
DCHECK_EQ(frames_written, 0);
frames_written =
std::min(static_cast<int>(play_delay.InSecondsF() *
audio_parameters_.sample_rate()),
requested_frames);
audio_bus->ZeroFramesPartial(0, frames_written);
}
// If there's any space left, actually render the audio; this is where the
// aural magic happens.
if (frames_written < requested_frames) {
frames_written += algorithm_->FillBuffer(
audio_bus, frames_written, requested_frames - frames_written,
playback_rate_);
}
}
// We use the following conditions to determine end of playback:
// 1) Algorithm can not fill the audio callback buffer
// 2) We received an end of stream buffer
// 3) We haven't already signalled that we've ended
// 4) We've played all known audio data sent to hardware
//
// We use the following conditions to determine underflow:
// 1) Algorithm can not fill the audio callback buffer
// 2) We have NOT received an end of stream buffer
// 3) We are in the kPlaying state
//
// Otherwise the buffer has data we can send to the device.
//
// Per the TimeSource API the media time should always increase even after
// we've rendered all known audio data. Doing so simplifies scenarios where
// we have other sources of media data that need to be scheduled after audio
// data has ended.
//
// That being said, we don't want to advance time when underflowed as we
// know more decoded frames will eventually arrive. If we did, we would
// throw things out of sync when said decoded frames arrive.
int frames_after_end_of_stream = 0;
if (frames_written == 0) {
if (received_end_of_stream_) {
if (ended_timestamp_ == kInfiniteDuration())
ended_timestamp_ = audio_clock_->back_timestamp();
frames_after_end_of_stream = requested_frames;
} else if (state_ == kPlaying &&
buffering_state_ != BUFFERING_HAVE_NOTHING) {
algorithm_->IncreaseQueueCapacity();
SetBufferingState_Locked(BUFFERING_HAVE_NOTHING);
}
}
audio_clock_->WroteAudio(frames_written + frames_after_end_of_stream,
requested_frames,
delay_frames,
playback_rate_);
if (CanRead_Locked()) {
task_runner_->PostTask(FROM_HERE,
base::Bind(&AudioRendererImpl::AttemptRead,
weak_factory_.GetWeakPtr()));
}
if (audio_clock_->front_timestamp() >= ended_timestamp_ &&
!rendered_end_of_stream_) {
rendered_end_of_stream_ = true;
task_runner_->PostTask(FROM_HERE, ended_cb_);
}
}
DCHECK_LE(frames_written, requested_frames);
return frames_written;
}
void AudioRendererImpl::OnRenderError() {
// UMA data tells us this happens ~0.01% of the time. Trigger an error instead
// of trying to gracefully fall back to a fake sink. It's very likely
// OnRenderError() should be removed and the audio stack handle errors without
// notifying clients. See http://crbug.com/234708 for details.
HistogramRendererEvent(RENDER_ERROR);
MEDIA_LOG(ERROR, media_log_) << "audio render error";
// Post to |task_runner_| as this is called on the audio callback thread.
task_runner_->PostTask(FROM_HERE,
base::Bind(error_cb_, PIPELINE_ERROR_DECODE));
}
void AudioRendererImpl::HandleAbortedReadOrDecodeError(bool is_decode_error) {
DCHECK(task_runner_->BelongsToCurrentThread());
lock_.AssertAcquired();
PipelineStatus status = is_decode_error ? PIPELINE_ERROR_DECODE : PIPELINE_OK;
switch (state_) {
case kUninitialized:
case kInitializing:
NOTREACHED();
return;
case kFlushing:
ChangeState_Locked(kFlushed);
if (status == PIPELINE_OK) {
DoFlush_Locked();
return;
}
MEDIA_LOG(ERROR, media_log_) << "audio decode error during flushing";
error_cb_.Run(status);
base::ResetAndReturn(&flush_cb_).Run();
return;
case kFlushed:
case kPlaying:
if (status != PIPELINE_OK) {
MEDIA_LOG(ERROR, media_log_) << "audio decode error during playing";
error_cb_.Run(status);
}
return;
}
}
void AudioRendererImpl::ChangeState_Locked(State new_state) {
DVLOG(1) << __FUNCTION__ << " : " << state_ << " -> " << new_state;
lock_.AssertAcquired();
state_ = new_state;
}
void AudioRendererImpl::OnNewSpliceBuffer(base::TimeDelta splice_timestamp) {
DCHECK(task_runner_->BelongsToCurrentThread());
splicer_->SetSpliceTimestamp(splice_timestamp);
}
void AudioRendererImpl::OnConfigChange() {
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(expecting_config_changes_);
buffer_converter_->ResetTimestampState();
// Drain flushed buffers from the converter so the AudioSplicer receives all
// data ahead of any OnNewSpliceBuffer() calls. Since discontinuities should
// only appear after config changes, AddInput() should never fail here.
while (buffer_converter_->HasNextBuffer())
CHECK(splicer_->AddInput(buffer_converter_->GetNextBuffer()));
}
void AudioRendererImpl::SetBufferingState_Locked(
BufferingState buffering_state) {
DVLOG(1) << __FUNCTION__ << " : " << buffering_state_ << " -> "
<< buffering_state;
DCHECK_NE(buffering_state_, buffering_state);
lock_.AssertAcquired();
buffering_state_ = buffering_state;
task_runner_->PostTask(FROM_HERE,
base::Bind(buffering_state_cb_, buffering_state_));
}
} // namespace media
|