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