NuPlayer.cpp revision 078cfcf7cce9185ec7559910d08b0bc02bfc88a3
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "NuPlayer"
19#include <utils/Log.h>
20
21#include "NuPlayer.h"
22
23#include "HTTPLiveSource.h"
24#include "NuPlayerDecoder.h"
25#include "NuPlayerDriver.h"
26#include "NuPlayerRenderer.h"
27#include "NuPlayerSource.h"
28#include "StreamingSource.h"
29
30#include "ATSParser.h"
31
32#include <media/stagefright/foundation/hexdump.h>
33#include <media/stagefright/foundation/ABuffer.h>
34#include <media/stagefright/foundation/ADebug.h>
35#include <media/stagefright/foundation/AMessage.h>
36#include <media/stagefright/ACodec.h>
37#include <media/stagefright/MediaErrors.h>
38#include <media/stagefright/MetaData.h>
39#include <surfaceflinger/Surface.h>
40#include <gui/ISurfaceTexture.h>
41
42namespace android {
43
44////////////////////////////////////////////////////////////////////////////////
45
46NuPlayer::NuPlayer()
47    : mUIDValid(false),
48      mAudioEOS(false),
49      mVideoEOS(false),
50      mScanSourcesPending(false),
51      mScanSourcesGeneration(0),
52      mFlushingAudio(NONE),
53      mFlushingVideo(NONE),
54      mResetInProgress(false),
55      mResetPostponed(false) {
56}
57
58NuPlayer::~NuPlayer() {
59}
60
61void NuPlayer::setUID(uid_t uid) {
62    mUIDValid = true;
63    mUID = uid;
64}
65
66void NuPlayer::setDriver(const wp<NuPlayerDriver> &driver) {
67    mDriver = driver;
68}
69
70void NuPlayer::setDataSource(const sp<IStreamSource> &source) {
71    sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
72
73    msg->setObject("source", new StreamingSource(source));
74    msg->post();
75}
76
77void NuPlayer::setDataSource(
78        const char *url, const KeyedVector<String8, String8> *headers) {
79    sp<AMessage> msg = new AMessage(kWhatSetDataSource, id());
80
81    msg->setObject("source", new HTTPLiveSource(url, headers, mUIDValid, mUID));
82    msg->post();
83}
84
85void NuPlayer::setVideoSurface(const sp<Surface> &surface) {
86    sp<AMessage> msg = new AMessage(kWhatSetVideoNativeWindow, id());
87    msg->setObject("native-window", new NativeWindowWrapper(surface));
88    msg->post();
89}
90
91void NuPlayer::setVideoSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) {
92    sp<AMessage> msg = new AMessage(kWhatSetVideoNativeWindow, id());
93    sp<SurfaceTextureClient> surfaceTextureClient(surfaceTexture != NULL ?
94                new SurfaceTextureClient(surfaceTexture) : NULL);
95    msg->setObject("native-window", new NativeWindowWrapper(surfaceTextureClient));
96    msg->post();
97}
98
99void NuPlayer::setAudioSink(const sp<MediaPlayerBase::AudioSink> &sink) {
100    sp<AMessage> msg = new AMessage(kWhatSetAudioSink, id());
101    msg->setObject("sink", sink);
102    msg->post();
103}
104
105void NuPlayer::start() {
106    (new AMessage(kWhatStart, id()))->post();
107}
108
109void NuPlayer::pause() {
110    (new AMessage(kWhatPause, id()))->post();
111}
112
113void NuPlayer::resume() {
114    (new AMessage(kWhatResume, id()))->post();
115}
116
117void NuPlayer::resetAsync() {
118    (new AMessage(kWhatReset, id()))->post();
119}
120
121void NuPlayer::seekToAsync(int64_t seekTimeUs) {
122    sp<AMessage> msg = new AMessage(kWhatSeek, id());
123    msg->setInt64("seekTimeUs", seekTimeUs);
124    msg->post();
125}
126
127// static
128bool NuPlayer::IsFlushingState(FlushStatus state, bool *needShutdown) {
129    switch (state) {
130        case FLUSHING_DECODER:
131            if (needShutdown != NULL) {
132                *needShutdown = false;
133            }
134            return true;
135
136        case FLUSHING_DECODER_SHUTDOWN:
137            if (needShutdown != NULL) {
138                *needShutdown = true;
139            }
140            return true;
141
142        default:
143            return false;
144    }
145}
146
147void NuPlayer::onMessageReceived(const sp<AMessage> &msg) {
148    switch (msg->what()) {
149        case kWhatSetDataSource:
150        {
151            LOGV("kWhatSetDataSource");
152
153            CHECK(mSource == NULL);
154
155            sp<RefBase> obj;
156            CHECK(msg->findObject("source", &obj));
157
158            mSource = static_cast<Source *>(obj.get());
159            break;
160        }
161
162        case kWhatSetVideoNativeWindow:
163        {
164            LOGV("kWhatSetVideoNativeWindow");
165
166            sp<RefBase> obj;
167            CHECK(msg->findObject("native-window", &obj));
168
169            mNativeWindow = static_cast<NativeWindowWrapper *>(obj.get());
170            break;
171        }
172
173        case kWhatSetAudioSink:
174        {
175            LOGV("kWhatSetAudioSink");
176
177            sp<RefBase> obj;
178            CHECK(msg->findObject("sink", &obj));
179
180            mAudioSink = static_cast<MediaPlayerBase::AudioSink *>(obj.get());
181            break;
182        }
183
184        case kWhatStart:
185        {
186            LOGV("kWhatStart");
187
188            mAudioEOS = false;
189            mVideoEOS = false;
190            mSkipRenderingAudioUntilMediaTimeUs = -1;
191            mSkipRenderingVideoUntilMediaTimeUs = -1;
192
193            mSource->start();
194
195            mRenderer = new Renderer(
196                    mAudioSink,
197                    new AMessage(kWhatRendererNotify, id()));
198
199            looper()->registerHandler(mRenderer);
200
201            postScanSources();
202            break;
203        }
204
205        case kWhatScanSources:
206        {
207            int32_t generation;
208            CHECK(msg->findInt32("generation", &generation));
209            if (generation != mScanSourcesGeneration) {
210                // Drop obsolete msg.
211                break;
212            }
213
214            mScanSourcesPending = false;
215
216            LOGV("scanning sources haveAudio=%d, haveVideo=%d",
217                 mAudioDecoder != NULL, mVideoDecoder != NULL);
218
219            instantiateDecoder(false, &mVideoDecoder);
220
221            if (mAudioSink != NULL) {
222                instantiateDecoder(true, &mAudioDecoder);
223            }
224
225            if (!mSource->feedMoreTSData()) {
226                if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
227                    // We're not currently decoding anything (no audio or
228                    // video tracks found) and we just ran out of input data.
229                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
230                }
231                break;
232            }
233
234            if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
235                msg->post(100000ll);
236                mScanSourcesPending = true;
237            }
238            break;
239        }
240
241        case kWhatVideoNotify:
242        case kWhatAudioNotify:
243        {
244            bool audio = msg->what() == kWhatAudioNotify;
245
246            sp<AMessage> codecRequest;
247            CHECK(msg->findMessage("codec-request", &codecRequest));
248
249            int32_t what;
250            CHECK(codecRequest->findInt32("what", &what));
251
252            if (what == ACodec::kWhatFillThisBuffer) {
253                status_t err = feedDecoderInputData(
254                        audio, codecRequest);
255
256                if (err == -EWOULDBLOCK) {
257                    if (mSource->feedMoreTSData()) {
258                        msg->post();
259                    }
260                }
261            } else if (what == ACodec::kWhatEOS) {
262                mRenderer->queueEOS(audio, ERROR_END_OF_STREAM);
263            } else if (what == ACodec::kWhatFlushCompleted) {
264                bool needShutdown;
265
266                if (audio) {
267                    CHECK(IsFlushingState(mFlushingAudio, &needShutdown));
268                    mFlushingAudio = FLUSHED;
269                } else {
270                    CHECK(IsFlushingState(mFlushingVideo, &needShutdown));
271                    mFlushingVideo = FLUSHED;
272                }
273
274                LOGV("decoder %s flush completed", audio ? "audio" : "video");
275
276                if (needShutdown) {
277                    LOGV("initiating %s decoder shutdown",
278                         audio ? "audio" : "video");
279
280                    (audio ? mAudioDecoder : mVideoDecoder)->initiateShutdown();
281
282                    if (audio) {
283                        mFlushingAudio = SHUTTING_DOWN_DECODER;
284                    } else {
285                        mFlushingVideo = SHUTTING_DOWN_DECODER;
286                    }
287                }
288
289                finishFlushIfPossible();
290            } else if (what == ACodec::kWhatOutputFormatChanged) {
291                if (audio) {
292                    int32_t numChannels;
293                    CHECK(codecRequest->findInt32("channel-count", &numChannels));
294
295                    int32_t sampleRate;
296                    CHECK(codecRequest->findInt32("sample-rate", &sampleRate));
297
298                    LOGV("Audio output format changed to %d Hz, %d channels",
299                         sampleRate, numChannels);
300
301                    mAudioSink->close();
302                    CHECK_EQ(mAudioSink->open(
303                                sampleRate,
304                                numChannels,
305                                AUDIO_FORMAT_PCM_16_BIT,
306                                8 /* bufferCount */),
307                             (status_t)OK);
308                    mAudioSink->start();
309
310                    mRenderer->signalAudioSinkChanged();
311                } else {
312                    // video
313
314                    int32_t width, height;
315                    CHECK(codecRequest->findInt32("width", &width));
316                    CHECK(codecRequest->findInt32("height", &height));
317
318                    int32_t cropLeft, cropTop, cropRight, cropBottom;
319                    CHECK(codecRequest->findRect(
320                                "crop",
321                                &cropLeft, &cropTop, &cropRight, &cropBottom));
322
323                    LOGV("Video output format changed to %d x %d "
324                         "(crop: %d x %d @ (%d, %d))",
325                         width, height,
326                         (cropRight - cropLeft + 1),
327                         (cropBottom - cropTop + 1),
328                         cropLeft, cropTop);
329
330                    notifyListener(
331                            MEDIA_SET_VIDEO_SIZE,
332                            cropRight - cropLeft + 1,
333                            cropBottom - cropTop + 1);
334                }
335            } else if (what == ACodec::kWhatShutdownCompleted) {
336                LOGV("%s shutdown completed", audio ? "audio" : "video");
337                if (audio) {
338                    mAudioDecoder.clear();
339
340                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
341                    mFlushingAudio = SHUT_DOWN;
342                } else {
343                    mVideoDecoder.clear();
344
345                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
346                    mFlushingVideo = SHUT_DOWN;
347                }
348
349                finishFlushIfPossible();
350            } else if (what == ACodec::kWhatError) {
351                LOGE("Received error from %s decoder, aborting playback.",
352                     audio ? "audio" : "video");
353
354                mRenderer->queueEOS(audio, UNKNOWN_ERROR);
355            } else {
356                CHECK_EQ((int)what, (int)ACodec::kWhatDrainThisBuffer);
357
358                renderBuffer(audio, codecRequest);
359            }
360
361            break;
362        }
363
364        case kWhatRendererNotify:
365        {
366            int32_t what;
367            CHECK(msg->findInt32("what", &what));
368
369            if (what == Renderer::kWhatEOS) {
370                int32_t audio;
371                CHECK(msg->findInt32("audio", &audio));
372
373                int32_t finalResult;
374                CHECK(msg->findInt32("finalResult", &finalResult));
375
376                if (audio) {
377                    mAudioEOS = true;
378                } else {
379                    mVideoEOS = true;
380                }
381
382                if (finalResult == ERROR_END_OF_STREAM) {
383                    LOGV("reached %s EOS", audio ? "audio" : "video");
384                } else {
385                    LOGE("%s track encountered an error (0x%08x)",
386                         audio ? "audio" : "video", finalResult);
387
388                    notifyListener(
389                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
390                }
391
392                if ((mAudioEOS || mAudioDecoder == NULL)
393                        && (mVideoEOS || mVideoDecoder == NULL)) {
394                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
395                }
396            } else if (what == Renderer::kWhatPosition) {
397                int64_t positionUs;
398                CHECK(msg->findInt64("positionUs", &positionUs));
399
400                if (mDriver != NULL) {
401                    sp<NuPlayerDriver> driver = mDriver.promote();
402                    if (driver != NULL) {
403                        driver->notifyPosition(positionUs);
404                    }
405                }
406            } else {
407                CHECK_EQ(what, (int32_t)Renderer::kWhatFlushComplete);
408
409                int32_t audio;
410                CHECK(msg->findInt32("audio", &audio));
411
412                LOGV("renderer %s flush completed.", audio ? "audio" : "video");
413            }
414            break;
415        }
416
417        case kWhatMoreDataQueued:
418        {
419            break;
420        }
421
422        case kWhatReset:
423        {
424            LOGV("kWhatReset");
425
426            if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
427                // We're currently flushing, postpone the reset until that's
428                // completed.
429
430                LOGV("postponing reset");
431
432                mResetPostponed = true;
433                break;
434            }
435
436            if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
437                finishReset();
438                break;
439            }
440
441            if (mAudioDecoder != NULL) {
442                flushDecoder(true /* audio */, true /* needShutdown */);
443            }
444
445            if (mVideoDecoder != NULL) {
446                flushDecoder(false /* audio */, true /* needShutdown */);
447            }
448
449            mResetInProgress = true;
450            break;
451        }
452
453        case kWhatSeek:
454        {
455            int64_t seekTimeUs;
456            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
457
458            LOGV("kWhatSeek seekTimeUs=%lld us (%.2f secs)",
459                 seekTimeUs, seekTimeUs / 1E6);
460
461            mSource->seekTo(seekTimeUs);
462
463            if (mDriver != NULL) {
464                sp<NuPlayerDriver> driver = mDriver.promote();
465                if (driver != NULL) {
466                    driver->notifySeekComplete();
467                }
468            }
469
470            break;
471        }
472
473        case kWhatPause:
474        {
475            CHECK(mRenderer != NULL);
476            mRenderer->pause();
477            break;
478        }
479
480        case kWhatResume:
481        {
482            CHECK(mRenderer != NULL);
483            mRenderer->resume();
484            break;
485        }
486
487        default:
488            TRESPASS();
489            break;
490    }
491}
492
493void NuPlayer::finishFlushIfPossible() {
494    if (mFlushingAudio != FLUSHED && mFlushingAudio != SHUT_DOWN) {
495        return;
496    }
497
498    if (mFlushingVideo != FLUSHED && mFlushingVideo != SHUT_DOWN) {
499        return;
500    }
501
502    LOGV("both audio and video are flushed now.");
503
504    mRenderer->signalTimeDiscontinuity();
505
506    if (mAudioDecoder != NULL) {
507        mAudioDecoder->signalResume();
508    }
509
510    if (mVideoDecoder != NULL) {
511        mVideoDecoder->signalResume();
512    }
513
514    mFlushingAudio = NONE;
515    mFlushingVideo = NONE;
516
517    if (mResetInProgress) {
518        LOGV("reset completed");
519
520        mResetInProgress = false;
521        finishReset();
522    } else if (mResetPostponed) {
523        (new AMessage(kWhatReset, id()))->post();
524        mResetPostponed = false;
525    } else if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
526        postScanSources();
527    }
528}
529
530void NuPlayer::finishReset() {
531    CHECK(mAudioDecoder == NULL);
532    CHECK(mVideoDecoder == NULL);
533
534    mRenderer.clear();
535    mSource.clear();
536
537    if (mDriver != NULL) {
538        sp<NuPlayerDriver> driver = mDriver.promote();
539        if (driver != NULL) {
540            driver->notifyResetComplete();
541        }
542    }
543}
544
545void NuPlayer::postScanSources() {
546    if (mScanSourcesPending) {
547        return;
548    }
549
550    sp<AMessage> msg = new AMessage(kWhatScanSources, id());
551    msg->setInt32("generation", mScanSourcesGeneration);
552    msg->post();
553
554    mScanSourcesPending = true;
555}
556
557status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) {
558    if (*decoder != NULL) {
559        return OK;
560    }
561
562    sp<MetaData> meta = mSource->getFormat(audio);
563
564    if (meta == NULL) {
565        return -EWOULDBLOCK;
566    }
567
568    sp<AMessage> notify =
569        new AMessage(audio ? kWhatAudioNotify : kWhatVideoNotify,
570                     id());
571
572    *decoder = audio ? new Decoder(notify) :
573                       new Decoder(notify, mNativeWindow);
574    looper()->registerHandler(*decoder);
575
576    (*decoder)->configure(meta);
577
578    int64_t durationUs;
579    if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
580        sp<NuPlayerDriver> driver = mDriver.promote();
581        if (driver != NULL) {
582            driver->notifyDuration(durationUs);
583        }
584    }
585
586    return OK;
587}
588
589status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) {
590    sp<AMessage> reply;
591    CHECK(msg->findMessage("reply", &reply));
592
593    if ((audio && IsFlushingState(mFlushingAudio))
594            || (!audio && IsFlushingState(mFlushingVideo))) {
595        reply->setInt32("err", INFO_DISCONTINUITY);
596        reply->post();
597        return OK;
598    }
599
600    sp<ABuffer> accessUnit;
601    status_t err = mSource->dequeueAccessUnit(audio, &accessUnit);
602
603    if (err == -EWOULDBLOCK) {
604        return err;
605    } else if (err != OK) {
606        if (err == INFO_DISCONTINUITY) {
607            int32_t type;
608            CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
609
610            bool formatChange =
611                type == ATSParser::DISCONTINUITY_FORMATCHANGE;
612
613            LOGV("%s discontinuity (formatChange=%d)",
614                 audio ? "audio" : "video", formatChange);
615
616            if (audio) {
617                mSkipRenderingAudioUntilMediaTimeUs = -1;
618            } else {
619                mSkipRenderingVideoUntilMediaTimeUs = -1;
620            }
621
622            sp<AMessage> extra;
623            if (accessUnit->meta()->findMessage("extra", &extra)
624                    && extra != NULL) {
625                int64_t resumeAtMediaTimeUs;
626                if (extra->findInt64(
627                            "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) {
628                    LOGI("suppressing rendering of %s until %lld us",
629                            audio ? "audio" : "video", resumeAtMediaTimeUs);
630
631                    if (audio) {
632                        mSkipRenderingAudioUntilMediaTimeUs =
633                            resumeAtMediaTimeUs;
634                    } else {
635                        mSkipRenderingVideoUntilMediaTimeUs =
636                            resumeAtMediaTimeUs;
637                    }
638                }
639            }
640
641            flushDecoder(audio, formatChange);
642        }
643
644        reply->setInt32("err", err);
645        reply->post();
646        return OK;
647    }
648
649    // LOGV("returned a valid buffer of %s data", audio ? "audio" : "video");
650
651#if 0
652    int64_t mediaTimeUs;
653    CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
654    LOGV("feeding %s input buffer at media time %.2f secs",
655         audio ? "audio" : "video",
656         mediaTimeUs / 1E6);
657#endif
658
659    reply->setObject("buffer", accessUnit);
660    reply->post();
661
662    return OK;
663}
664
665void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) {
666    // LOGV("renderBuffer %s", audio ? "audio" : "video");
667
668    sp<AMessage> reply;
669    CHECK(msg->findMessage("reply", &reply));
670
671    if (IsFlushingState(audio ? mFlushingAudio : mFlushingVideo)) {
672        // We're currently attempting to flush the decoder, in order
673        // to complete this, the decoder wants all its buffers back,
674        // so we don't want any output buffers it sent us (from before
675        // we initiated the flush) to be stuck in the renderer's queue.
676
677        LOGV("we're still flushing the %s decoder, sending its output buffer"
678             " right back.", audio ? "audio" : "video");
679
680        reply->post();
681        return;
682    }
683
684    sp<RefBase> obj;
685    CHECK(msg->findObject("buffer", &obj));
686
687    sp<ABuffer> buffer = static_cast<ABuffer *>(obj.get());
688
689    int64_t &skipUntilMediaTimeUs =
690        audio
691            ? mSkipRenderingAudioUntilMediaTimeUs
692            : mSkipRenderingVideoUntilMediaTimeUs;
693
694    if (skipUntilMediaTimeUs >= 0) {
695        int64_t mediaTimeUs;
696        CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs));
697
698        if (mediaTimeUs < skipUntilMediaTimeUs) {
699            LOGV("dropping %s buffer at time %lld as requested.",
700                 audio ? "audio" : "video",
701                 mediaTimeUs);
702
703            reply->post();
704            return;
705        }
706
707        skipUntilMediaTimeUs = -1;
708    }
709
710    mRenderer->queueBuffer(audio, buffer, reply);
711}
712
713void NuPlayer::notifyListener(int msg, int ext1, int ext2) {
714    if (mDriver == NULL) {
715        return;
716    }
717
718    sp<NuPlayerDriver> driver = mDriver.promote();
719
720    if (driver == NULL) {
721        return;
722    }
723
724    driver->sendEvent(msg, ext1, ext2);
725}
726
727void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
728    // Make sure we don't continue to scan sources until we finish flushing.
729    ++mScanSourcesGeneration;
730    mScanSourcesPending = false;
731
732    (audio ? mAudioDecoder : mVideoDecoder)->signalFlush();
733    mRenderer->flush(audio);
734
735    FlushStatus newStatus =
736        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
737
738    if (audio) {
739        CHECK(mFlushingAudio == NONE
740                || mFlushingAudio == AWAITING_DISCONTINUITY);
741
742        mFlushingAudio = newStatus;
743
744        if (mFlushingVideo == NONE) {
745            mFlushingVideo = (mVideoDecoder != NULL)
746                ? AWAITING_DISCONTINUITY
747                : FLUSHED;
748        }
749    } else {
750        CHECK(mFlushingVideo == NONE
751                || mFlushingVideo == AWAITING_DISCONTINUITY);
752
753        mFlushingVideo = newStatus;
754
755        if (mFlushingAudio == NONE) {
756            mFlushingAudio = (mAudioDecoder != NULL)
757                ? AWAITING_DISCONTINUITY
758                : FLUSHED;
759        }
760    }
761}
762
763}  // namespace android
764