summaryrefslogtreecommitdiff
path: root/tests/tests/media/common/src/android/media/cts/MediaCodecTunneledPlayer.java
blob: e0cae51fc93d5eae621728cd1cbf380d79a8601d (plain)
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
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package android.media.cts;

import android.content.Context;
import android.media.AudioTimestamp;
import android.media.AudioTrack;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.net.Uri;
import android.util.Log;
import android.view.SurfaceHolder;

import com.google.common.collect.ImmutableList;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * JB(API 21) introduces {@link MediaCodec} tunneled mode API.  It allows apps
 * to use MediaCodec to delegate their Audio/Video rendering to a vendor provided
 * Codec component.
 */
public class MediaCodecTunneledPlayer implements MediaTimeProvider {
    private static final String TAG = MediaCodecTunneledPlayer.class.getSimpleName();

    /** State the player starts in, before configuration. */
    private static final int STATE_IDLE = 1;
    /** State of the player during initial configuration. */
    private static final int STATE_PREPARING = 2;
    /** State of the player during playback. */
    private static final int STATE_PLAYING = 3;
    /** State of the player when configured but not playing. */
    private static final int STATE_PAUSED = 4;

    private Boolean mThreadStarted = false;
    private byte[] mSessionId;
    private CodecState mAudioTrackState;
    private int mMediaFormatHeight;
    private int mMediaFormatWidth;
    private Integer mState;
    private long mDeltaTimeUs;
    private long mDurationUs;
    private Map<Integer, CodecState> mAudioCodecStates;
    private Map<Integer, CodecState> mVideoCodecStates;
    private Map<String, String> mAudioHeaders;
    private Map<String, String> mVideoHeaders;
    private MediaExtractor mAudioExtractor;
    private MediaExtractor mVideoExtractor;
    private SurfaceHolder mSurfaceHolder;
    private Thread mThread;
    private Uri mAudioUri;
    private Uri mVideoUri;
    private boolean mIsTunneled;
    private int mAudioSessionId;
    private Context mContext;

    /*
     * Media player class to playback video using tunneled MediaCodec.
     */
    public MediaCodecTunneledPlayer(Context context, SurfaceHolder holder, boolean tunneled, int AudioSessionId) {
        mContext = context;
        mSurfaceHolder = holder;
        mIsTunneled = tunneled;
        mAudioTrackState = null;
        mState = STATE_IDLE;
        mAudioSessionId = AudioSessionId;
        mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (mThreadStarted) {
                        if (mThreadStarted == false) {
                            break;
                        }
                    }
                    synchronized (mState) {
                        if (mState == STATE_PLAYING) {
                            doSomeWork();
                            if (mAudioTrackState != null) {
                                mAudioTrackState.processAudioTrack();
                            }
                        }
                    }
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException ex) {
                        Log.d(TAG, "Thread interrupted");
                    }
                }
            }
        });
    }

    public void setAudioDataSource(Uri uri, Map<String, String> headers) {
        mAudioUri = uri;
        mAudioHeaders = headers;
    }

    public void setVideoDataSource(Uri uri, Map<String, String> headers) {
        mVideoUri = uri;
        mVideoHeaders = headers;
    }

    public final int getMediaFormatHeight() {
        return mMediaFormatHeight;
    }

    public final int getMediaFormatWidth() {
        return mMediaFormatWidth;
    }

    private boolean prepareAudio() throws IOException {
        for (int i = mAudioExtractor.getTrackCount(); i-- > 0;) {
            MediaFormat format = mAudioExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);

            if (!mime.startsWith("audio/")) {
                continue;
            }

            Log.d(TAG, "audio track #" + i + " " + format + " " + mime +
                  " Is ADTS:" + getMediaFormatInteger(format, MediaFormat.KEY_IS_ADTS) +
                  " Sample rate:" + getMediaFormatInteger(format, MediaFormat.KEY_SAMPLE_RATE) +
                  " Channel count:" +
                  getMediaFormatInteger(format, MediaFormat.KEY_CHANNEL_COUNT));

            mAudioExtractor.selectTrack(i);
            if (!addTrack(i, format)) {
                Log.e(TAG, "prepareAudio - addTrack() failed!");
                return false;
            }

            if (format.containsKey(MediaFormat.KEY_DURATION)) {
                long durationUs = format.getLong(MediaFormat.KEY_DURATION);

                if (durationUs > mDurationUs) {
                    mDurationUs = durationUs;
                }
                Log.d(TAG, "audio track format #" + i +
                        " Duration:" + mDurationUs + " microseconds");
            }
        }
        return true;
    }

    private boolean prepareVideo() throws IOException {
        for (int i = mVideoExtractor.getTrackCount(); i-- > 0;) {
            MediaFormat format = mVideoExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);

            if (!mime.startsWith("video/")) {
                continue;
            }

            mMediaFormatHeight = getMediaFormatInteger(format, MediaFormat.KEY_HEIGHT);
            mMediaFormatWidth = getMediaFormatInteger(format, MediaFormat.KEY_WIDTH);
            Log.d(TAG, "video track #" + i + " " + format + " " + mime +
                  " Width:" + mMediaFormatWidth + ", Height:" + mMediaFormatHeight);

            mVideoExtractor.selectTrack(i);
            if (!addTrack(i, format)) {
                Log.e(TAG, "prepareVideo - addTrack() failed!");
                return false;
            }

            if (format.containsKey(MediaFormat.KEY_DURATION)) {
                long durationUs = format.getLong(MediaFormat.KEY_DURATION);

                if (durationUs > mDurationUs) {
                    mDurationUs = durationUs;
                }
                Log.d(TAG, "track format #" + i + " Duration:" +
                        mDurationUs + " microseconds");
            }
        }
        return true;
    }

    public boolean prepare() throws IOException {
        if (null == mAudioExtractor) {
            mAudioExtractor = new MediaExtractor();
            if (null == mAudioExtractor) {
                Log.e(TAG, "prepare - Cannot create Audio extractor.");
                return false;
            }
        }

        if (null == mVideoExtractor){
            mVideoExtractor = new MediaExtractor();
            if (null == mVideoExtractor) {
                Log.e(TAG, "prepare - Cannot create Video extractor.");
                return false;
            }
        }

        mAudioExtractor.setDataSource(mContext, mAudioUri, mAudioHeaders);
        if (mVideoUri != null) {
            mVideoExtractor.setDataSource(mContext, mVideoUri, mVideoHeaders);
        }

        if (null == mVideoCodecStates) {
            mVideoCodecStates = new HashMap<Integer, CodecState>();
        } else {
            mVideoCodecStates.clear();
        }

        if (null == mAudioCodecStates) {
            mAudioCodecStates = new HashMap<Integer, CodecState>();
        } else {
            mAudioCodecStates.clear();
        }

        if (!prepareAudio()) {
            Log.e(TAG,"prepare - prepareAudio() failed!");
            return false;
        }
        if (!prepareVideo()) {
            Log.e(TAG,"prepare - prepareVideo() failed!");
            return false;
        }

        synchronized (mState) {
            mState = STATE_PAUSED;
        }
        return true;
    }

    private boolean addTrack(int trackIndex, MediaFormat format) throws IOException {
        String mime = format.getString(MediaFormat.KEY_MIME);
        boolean isVideo = mime.startsWith("video/");
        boolean isAudio = mime.startsWith("audio/");
        MediaCodec codec;

        // setup tunneled video codec if needed
        if (isVideo && mIsTunneled) {
            format.setFeatureEnabled(MediaCodecInfo.CodecCapabilities.FEATURE_TunneledPlayback,
                        true);
            MediaCodecList mcl = new MediaCodecList(MediaCodecList.ALL_CODECS);
            String codecName = mcl.findDecoderForFormat(format);
            if (codecName == null) {
                Log.e(TAG,"addTrack - Could not find Tunneled playback codec for "+mime+
                        " format!");
                return false;
            }

            codec = MediaCodec.createByCodecName(codecName);
            if (codec == null) {
                Log.e(TAG, "addTrack - Could not create Tunneled playback codec "+
                        codecName+"!");
                return false;
            }

            if (mAudioTrackState != null) {
                format.setInteger(MediaFormat.KEY_AUDIO_SESSION_ID, mAudioSessionId);
            }
        }
        else {
            codec = MediaCodec.createDecoderByType(mime);
            if (codec == null) {
                Log.e(TAG, "addTrack - Could not create regular playback codec for mime "+
                        mime+"!");
                return false;
            }
        }
        codec.configure(
                format,
                isVideo ? mSurfaceHolder.getSurface() : null, null, 0);

        CodecState state;
        if (isVideo) {
            state = new CodecState((MediaTimeProvider)this, mVideoExtractor,
                            trackIndex, format, codec, true, mIsTunneled, mAudioSessionId);
            mVideoCodecStates.put(Integer.valueOf(trackIndex), state);
        } else {
            state = new CodecState((MediaTimeProvider)this, mAudioExtractor,
                            trackIndex, format, codec, true, mIsTunneled, mAudioSessionId);
            mAudioCodecStates.put(Integer.valueOf(trackIndex), state);
        }

        if (isAudio) {
            mAudioTrackState = state;
        }

        return true;
    }

    protected int getMediaFormatInteger(MediaFormat format, String key) {
        return format.containsKey(key) ? format.getInteger(key) : 0;
    }

    public boolean start() {
        Log.d(TAG, "start");

        synchronized (mState) {
            if (mState == STATE_PLAYING || mState == STATE_PREPARING) {
                return true;
            } else if (mState == STATE_IDLE) {
                mState = STATE_PREPARING;
                return true;
            } else if (mState != STATE_PAUSED) {
                throw new IllegalStateException("Expected STATE_PAUSED, got " + mState);
            }

            for (CodecState state : mVideoCodecStates.values()) {
                state.start();
            }

            for (CodecState state : mAudioCodecStates.values()) {
                state.start();
            }

            mDeltaTimeUs = -1;
            mState = STATE_PLAYING;
        }
        return false;
    }

    public void startWork() throws IOException, Exception {
        try {
            // Just change state from STATE_IDLE to STATE_PREPARING.
            start();
            // Extract media information from uri asset, and change state to STATE_PAUSED.
            prepare();
            // Start CodecState, and change from STATE_PAUSED to STATE_PLAYING.
            start();
        } catch (IOException e) {
            throw e;
        }

        synchronized (mThreadStarted) {
            mThreadStarted = true;
            mThread.start();
        }
    }

    public void startThread() {
        start();
        synchronized (mThreadStarted) {
            mThreadStarted = true;
            mThread.start();
        }
    }

    // Pauses the audio track
    public void pause() {
        Log.d(TAG, "pause");

        synchronized (mState) {
            if (mState == STATE_PAUSED) {
                return;
            } else if (mState != STATE_PLAYING) {
                throw new IllegalStateException();
            }

            for (CodecState state : mVideoCodecStates.values()) {
                state.pause();
            }

            for (CodecState state : mAudioCodecStates.values()) {
                state.pause();
            }

            mState = STATE_PAUSED;
        }
    }

    public void flush() {
        Log.d(TAG, "flush");

        synchronized (mState) {
            if (mState == STATE_PLAYING || mState == STATE_PREPARING) {
                return;
            }

            for (CodecState state : mAudioCodecStates.values()) {
                state.flush();
            }

            for (CodecState state : mVideoCodecStates.values()) {
                state.flush();
            }
        }
    }

    /**
     * Flushes all the video codecs when the player is in stand-by.
     *
     * @throws IllegalStateException  if the player is not paused
     */
    public void videoFlush() {
        Log.d(TAG, "videoFlush");
        synchronized (mState) {
            if (mState != STATE_PAUSED) {
                throw new IllegalStateException("Expected STATE_PAUSED, got " + mState);
            }

            for (CodecState state : mVideoCodecStates.values()) {
                state.flush();
            }
        }
    }

    /** Seek all video tracks to their very beginning.
     *
     * @param  shouldContinuePts      a boolean that controls whether timestamps keep increasing
     * @throws IllegalStateException  if the player is not paused
     */
    public void videoSeekToBeginning(boolean shouldContinuePts) {
        Log.d(TAG, "videoSeekToBeginning");
        synchronized (mState) {
            if (mState != STATE_PAUSED) {
                throw new IllegalStateException("Expected STATE_PAUSED, got " + mState);
            }

            for (CodecState state : mVideoCodecStates.values()) {
                state.seekToBeginning(shouldContinuePts);
            }
        }
    }

    /**
     * Enables or disables looping. Should be called after {@link #prepare()}.
     */
    public void setLoopEnabled(boolean enabled) {
        synchronized (mState) {
            if (mVideoCodecStates != null) {
                for (CodecState state : mVideoCodecStates.values()) {
                    state.setLoopEnabled(enabled);
                }
            }

            if (mAudioCodecStates != null) {
                for (CodecState state : mAudioCodecStates.values()) {
                    state.setLoopEnabled(enabled);
                }
            }
        }
    }

    public void reset() {
        synchronized (mState) {
            if (mState == STATE_PLAYING) {
                pause();
            }
            if (mVideoCodecStates != null) {
                for (CodecState state : mVideoCodecStates.values()) {
                    state.release();
                }
                mVideoCodecStates = null;
            }

            if (mAudioCodecStates != null) {
                for (CodecState state : mAudioCodecStates.values()) {
                    state.release();
                }
                mAudioCodecStates = null;
            }

            if (mAudioExtractor != null) {
                mAudioExtractor.release();
                mAudioExtractor = null;
            }

            if (mVideoExtractor != null) {
                mVideoExtractor.release();
                mVideoExtractor = null;
            }

            mDurationUs = -1;
            mState = STATE_IDLE;
        }
        synchronized (mThreadStarted) {
            mThreadStarted = false;
        }
        try {
            mThread.join();
        } catch (InterruptedException ex) {
            Log.d(TAG, "mThread.join ", ex);
        }
    }

    public boolean isEnded() {
        for (CodecState state : mVideoCodecStates.values()) {
          if (!state.isEnded()) {
            return false;
          }
        }

        for (CodecState state : mAudioCodecStates.values()) {
            if (!state.isEnded()) {
              return false;
            }
        }

        return true;
    }

    private void doSomeWork() {
        try {
            for (CodecState state : mVideoCodecStates.values()) {
                state.doSomeWork();
            }
        } catch (IllegalStateException e) {
            throw new Error("Video CodecState.doSomeWork", e);
        }

        try {
            for (CodecState state : mAudioCodecStates.values()) {
                state.doSomeWork();
            }
        } catch (IllegalStateException e) {
            throw new Error("Audio CodecState.doSomeWork", e);
        }

    }

    public long getNowUs() {
        if (mAudioTrackState == null) {
            return System.currentTimeMillis() * 1000;
        }

        return mAudioTrackState.getAudioTimeUs();
    }

    public long getRealTimeUsForMediaTime(long mediaTimeUs) {
        if (mDeltaTimeUs == -1) {
            long nowUs = getNowUs();
            mDeltaTimeUs = nowUs - mediaTimeUs;
        }

        return mDeltaTimeUs + mediaTimeUs;
    }

    public int getDuration() {
        return (int)((mDurationUs + 500) / 1000);
    }

    /**
     * Retrieve the presentation timestamp of the latest queued output sample.
     * In tunnel mode, retrieves the presentation timestamp of the latest rendered video frame.
     * @return presentation timestamp in microseconds, or {@code CodecState.UNINITIALIZED_TIMESTAMP}
     * if playback has not started.
    */
    public int getCurrentPosition() {
        if (mVideoCodecStates == null) {
            return CodecState.UNINITIALIZED_TIMESTAMP;
        }

        long positionUs = CodecState.UNINITIALIZED_TIMESTAMP;

        for (CodecState state : mVideoCodecStates.values()) {
            long trackPositionUs = state.getCurrentPositionUs();
            if (trackPositionUs > positionUs) {
                positionUs = trackPositionUs;
            }
        }

        if (positionUs == CodecState.UNINITIALIZED_TIMESTAMP) {
            return CodecState.UNINITIALIZED_TIMESTAMP;
        }
        return (int) (positionUs + 500) / 1000;
    }

    /**
     * Returns the system time of the latest rendered frame in any of the video codecs.
     */
    public long getCurrentRenderedSystemTimeNano() {
        if (mVideoCodecStates == null) {
            return 0;
        }

        long position = 0;

        for (CodecState state : mVideoCodecStates.values()) {
            long trackPosition = state.getRenderedVideoSystemTimeNano();

            if (trackPosition > position) {
                position = trackPosition;
            }
        }
        return position;
    }

    /**
     * Returns the timestamp of the last written audio sample, in microseconds.
     */
    public long getAudioTrackPositionUs() {
        if (mAudioTrackState == null) {
            return 0;
        }
        return mAudioTrackState.getCurrentPositionUs();
    }

    /**
     * Returns the presentation timestamp of the last rendered video frame.
     *
     * Note: This assumes there is exactly one video codec running in the player.
     */
    public long getVideoTimeUs() {
        return mVideoCodecStates.get(0).getVideoTimeUs();
    }

    /**
     * Returns the ordered list of video frame timestamps rendered in tunnel mode.
     *
     * Note: This assumes there is exactly one video codec running in the player.
     */
    public ImmutableList<Long> getRenderedVideoFrameTimestampList() {
        return mVideoCodecStates.get(0).getRenderedVideoFrameTimestampList();
    }

    /**
     * Returns the ordered list of system times of rendered video frames in tunnel-mode.
     *
     * Note: This assumes there is at most one tunneled mode video codec running in the player.
     */
    public ImmutableList<Long> getRenderedVideoFrameSystemTimeList() {
        if (mVideoCodecStates == null) {
            return ImmutableList.<Long>of();
        }

        for (CodecState state : mVideoCodecStates.values()) {
            ImmutableList<Long> timestamps = state.getRenderedVideoFrameSystemTimeList();
            if (!timestamps.isEmpty())
                return timestamps;
        }
        return ImmutableList.<Long>of();
    }

    /**
     * When the player is on stand-by, tries to queue one frame worth of video per video codec.
     *
     * Returns arbitrarily the timestamp of any frame queued this way by one of the video codecs.
     * Returns null if no video frame were queued.
     */
    public Long queueOneVideoFrame() {
        Log.d(TAG, "queueOneVideoFrame");

        if (mVideoCodecStates == null || !(mState == STATE_PLAYING || mState == STATE_PAUSED)) {
            return null;
        }

        Long result = null;
        for (CodecState state : mVideoCodecStates.values()) {
            Long timestamp = state.doSomeWork(true /* mustWait */);
            if (timestamp != null) {
                result = timestamp;
            }
        }
        return result;
    }

    /**
     * Resume playback when paused.
     *
     * @throws IllegalStateException if playback is not paused or if there is no configured audio
     *                               track.
     */
    public void resume() {
        Log.d(TAG, "resume");
        if (mAudioTrackState == null) {
            throw new IllegalStateException("Resuming playback with no audio track");
        }
        if (mState != STATE_PAUSED) {
            throw new IllegalStateException("Expected STATE_PAUSED, got " + mState);
        }
        mAudioTrackState.playAudioTrack();
        mState = STATE_PLAYING;
    }

    /**
     * Configure video peek for the video codecs attached to the player.
     */
    public void setVideoPeek(boolean enable) {
        Log.d(TAG, "setVideoPeek");
        if (mVideoCodecStates == null) {
            return;
        }

        for (CodecState state: mVideoCodecStates.values()) {
            state.setVideoPeek(enable);
        }
    }

    public AudioTimestamp getTimestamp() {
        if (mAudioCodecStates == null) {
            return null;
        }

        AudioTimestamp timestamp = new AudioTimestamp();
        if (mAudioCodecStates.size() != 0) {
            timestamp =
                    mAudioCodecStates.entrySet().iterator().next().getValue().getTimestamp();
        }
        return timestamp;
    }

    /** Queries the attached video codecs for video peek ready signals.
     *
     * Returns true if any of the video codecs have video peek ready.
     * Returns false otherwise.
     */
    public boolean isFirstTunnelFrameReady() {
        Log.d(TAG, "firstTunnelFrameReady");
        if (mVideoCodecStates == null) {
            return false;
        }

        for (CodecState state : mVideoCodecStates.values()) {
            if (state.isFirstTunnelFrameReady()) {
                return true;
            }
        }
        return false;
    }

    /** Returns the number of frames that have been sent down to the HAL. */
    public int getAudioFramesWritten() {
        if (mAudioCodecStates == null) {
            return -1;
        }
        return mAudioCodecStates.entrySet().iterator().next().getValue().getFramesWritten();
    }

    public void stopWritingToAudioTrack(boolean stopWriting) {
        for (CodecState state : mAudioCodecStates.values()) {
            state.stopWritingToAudioTrack(stopWriting);
        }
    }

    /** Configure underrun simulation on audio codecs. */
    public void simulateAudioUnderrun(boolean enabled) {
        for (CodecState state: mAudioCodecStates.values()) {
            state.simulateUnderrun(enabled);
        }
    }

    /** Configure an offset (in ms) to audio content to simulate track desynchronization. */
    public void setAudioTrackOffsetMs(int audioOffsetMs) {
        if (mAudioTrackState != null) {
            mAudioTrackState.setAudioOffsetMs(audioOffsetMs);
        }
    }

    /** Returns the underlying {@code AudioTrack}, if any. */
    public AudioTrack getAudioTrack() {
        if (mAudioTrackState != null) {
            return mAudioTrackState.getAudioTrack();
        }
        return null;
    }
}