NuPlayer.cpp revision c92fd24c10a6bf80b346d7e261325434d9c6964b
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(sampleRate, numChannels), (status_t)OK);
303                    mAudioSink->start();
304
305                    mRenderer->signalAudioSinkChanged();
306                } else {
307                    // video
308
309                    int32_t width, height;
310                    CHECK(codecRequest->findInt32("width", &width));
311                    CHECK(codecRequest->findInt32("height", &height));
312
313                    int32_t cropLeft, cropTop, cropRight, cropBottom;
314                    CHECK(codecRequest->findRect(
315                                "crop",
316                                &cropLeft, &cropTop, &cropRight, &cropBottom));
317
318                    LOGV("Video output format changed to %d x %d "
319                         "(crop: %d, %d, %d, %d)",
320                         width, height,
321                         cropLeft, cropTop, cropRight, cropBottom);
322
323                    notifyListener(
324                            MEDIA_SET_VIDEO_SIZE,
325                            cropRight - cropLeft + 1,
326                            cropBottom - cropTop + 1);
327                }
328            } else if (what == ACodec::kWhatShutdownCompleted) {
329                LOGV("%s shutdown completed", audio ? "audio" : "video");
330                if (audio) {
331                    mAudioDecoder.clear();
332
333                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
334                    mFlushingAudio = SHUT_DOWN;
335                } else {
336                    mVideoDecoder.clear();
337
338                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
339                    mFlushingVideo = SHUT_DOWN;
340                }
341
342                finishFlushIfPossible();
343            } else if (what == ACodec::kWhatError) {
344                LOGE("Received error from %s decoder, aborting playback.",
345                     audio ? "audio" : "video");
346
347                mRenderer->queueEOS(audio, UNKNOWN_ERROR);
348            } else {
349                CHECK_EQ((int)what, (int)ACodec::kWhatDrainThisBuffer);
350
351                renderBuffer(audio, codecRequest);
352            }
353
354            break;
355        }
356
357        case kWhatRendererNotify:
358        {
359            int32_t what;
360            CHECK(msg->findInt32("what", &what));
361
362            if (what == Renderer::kWhatEOS) {
363                int32_t audio;
364                CHECK(msg->findInt32("audio", &audio));
365
366                int32_t finalResult;
367                CHECK(msg->findInt32("finalResult", &finalResult));
368
369                if (audio) {
370                    mAudioEOS = true;
371                } else {
372                    mVideoEOS = true;
373                }
374
375                if (finalResult == ERROR_END_OF_STREAM) {
376                    LOGV("reached %s EOS", audio ? "audio" : "video");
377                } else {
378                    LOGE("%s track encountered an error (0x%08x)",
379                         audio ? "audio" : "video", finalResult);
380
381                    notifyListener(
382                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, finalResult);
383                }
384
385                if ((mAudioEOS || mAudioDecoder == NULL)
386                        && (mVideoEOS || mVideoDecoder == NULL)) {
387                    notifyListener(MEDIA_PLAYBACK_COMPLETE, 0, 0);
388                }
389            } else if (what == Renderer::kWhatPosition) {
390                int64_t positionUs;
391                CHECK(msg->findInt64("positionUs", &positionUs));
392
393                if (mDriver != NULL) {
394                    sp<NuPlayerDriver> driver = mDriver.promote();
395                    if (driver != NULL) {
396                        driver->notifyPosition(positionUs);
397                    }
398                }
399            } else {
400                CHECK_EQ(what, (int32_t)Renderer::kWhatFlushComplete);
401
402                int32_t audio;
403                CHECK(msg->findInt32("audio", &audio));
404
405                LOGV("renderer %s flush completed.", audio ? "audio" : "video");
406            }
407            break;
408        }
409
410        case kWhatMoreDataQueued:
411        {
412            break;
413        }
414
415        case kWhatReset:
416        {
417            LOGV("kWhatReset");
418
419            if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
420                // We're currently flushing, postpone the reset until that's
421                // completed.
422
423                LOGV("postponing reset");
424
425                mResetPostponed = true;
426                break;
427            }
428
429            if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
430                finishReset();
431                break;
432            }
433
434            if (mAudioDecoder != NULL) {
435                flushDecoder(true /* audio */, true /* needShutdown */);
436            }
437
438            if (mVideoDecoder != NULL) {
439                flushDecoder(false /* audio */, true /* needShutdown */);
440            }
441
442            mResetInProgress = true;
443            break;
444        }
445
446        case kWhatSeek:
447        {
448            int64_t seekTimeUs;
449            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
450
451            LOGV("kWhatSeek seekTimeUs=%lld us (%.2f secs)",
452                 seekTimeUs, seekTimeUs / 1E6);
453
454            mSource->seekTo(seekTimeUs);
455
456            if (mDriver != NULL) {
457                sp<NuPlayerDriver> driver = mDriver.promote();
458                if (driver != NULL) {
459                    driver->notifySeekComplete();
460                }
461            }
462
463            break;
464        }
465
466        case kWhatPause:
467        {
468            CHECK(mRenderer != NULL);
469            mRenderer->pause();
470            break;
471        }
472
473        case kWhatResume:
474        {
475            CHECK(mRenderer != NULL);
476            mRenderer->resume();
477            break;
478        }
479
480        default:
481            TRESPASS();
482            break;
483    }
484}
485
486void NuPlayer::finishFlushIfPossible() {
487    if (mFlushingAudio != FLUSHED && mFlushingAudio != SHUT_DOWN) {
488        return;
489    }
490
491    if (mFlushingVideo != FLUSHED && mFlushingVideo != SHUT_DOWN) {
492        return;
493    }
494
495    LOGV("both audio and video are flushed now.");
496
497    mRenderer->signalTimeDiscontinuity();
498
499    if (mAudioDecoder != NULL) {
500        mAudioDecoder->signalResume();
501    }
502
503    if (mVideoDecoder != NULL) {
504        mVideoDecoder->signalResume();
505    }
506
507    mFlushingAudio = NONE;
508    mFlushingVideo = NONE;
509
510    if (mResetInProgress) {
511        LOGV("reset completed");
512
513        mResetInProgress = false;
514        finishReset();
515    } else if (mResetPostponed) {
516        (new AMessage(kWhatReset, id()))->post();
517        mResetPostponed = false;
518    } else if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
519        postScanSources();
520    }
521}
522
523void NuPlayer::finishReset() {
524    CHECK(mAudioDecoder == NULL);
525    CHECK(mVideoDecoder == NULL);
526
527    mRenderer.clear();
528    mSource.clear();
529
530    if (mDriver != NULL) {
531        sp<NuPlayerDriver> driver = mDriver.promote();
532        if (driver != NULL) {
533            driver->notifyResetComplete();
534        }
535    }
536}
537
538void NuPlayer::postScanSources() {
539    if (mScanSourcesPending) {
540        return;
541    }
542
543    sp<AMessage> msg = new AMessage(kWhatScanSources, id());
544    msg->setInt32("generation", mScanSourcesGeneration);
545    msg->post();
546
547    mScanSourcesPending = true;
548}
549
550status_t NuPlayer::instantiateDecoder(bool audio, sp<Decoder> *decoder) {
551    if (*decoder != NULL) {
552        return OK;
553    }
554
555    sp<MetaData> meta = mSource->getFormat(audio);
556
557    if (meta == NULL) {
558        return -EWOULDBLOCK;
559    }
560
561    sp<AMessage> notify =
562        new AMessage(audio ? kWhatAudioNotify : kWhatVideoNotify,
563                     id());
564
565    *decoder = audio ? new Decoder(notify) :
566                       new Decoder(notify, mNativeWindow);
567    looper()->registerHandler(*decoder);
568
569    (*decoder)->configure(meta);
570
571    int64_t durationUs;
572    if (mDriver != NULL && mSource->getDuration(&durationUs) == OK) {
573        sp<NuPlayerDriver> driver = mDriver.promote();
574        if (driver != NULL) {
575            driver->notifyDuration(durationUs);
576        }
577    }
578
579    return OK;
580}
581
582status_t NuPlayer::feedDecoderInputData(bool audio, const sp<AMessage> &msg) {
583    sp<AMessage> reply;
584    CHECK(msg->findMessage("reply", &reply));
585
586    if ((audio && IsFlushingState(mFlushingAudio))
587            || (!audio && IsFlushingState(mFlushingVideo))) {
588        reply->setInt32("err", INFO_DISCONTINUITY);
589        reply->post();
590        return OK;
591    }
592
593    sp<ABuffer> accessUnit;
594    status_t err = mSource->dequeueAccessUnit(audio, &accessUnit);
595
596    if (err == -EWOULDBLOCK) {
597        return err;
598    } else if (err != OK) {
599        if (err == INFO_DISCONTINUITY) {
600            int32_t type;
601            CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
602
603            bool formatChange =
604                type == ATSParser::DISCONTINUITY_FORMATCHANGE;
605
606            LOGV("%s discontinuity (formatChange=%d)",
607                 audio ? "audio" : "video", formatChange);
608
609            if (audio) {
610                mSkipRenderingAudioUntilMediaTimeUs = -1;
611            } else {
612                mSkipRenderingVideoUntilMediaTimeUs = -1;
613            }
614
615            sp<AMessage> extra;
616            if (accessUnit->meta()->findMessage("extra", &extra)
617                    && extra != NULL) {
618                int64_t resumeAtMediaTimeUs;
619                if (extra->findInt64(
620                            "resume-at-mediatimeUs", &resumeAtMediaTimeUs)) {
621                    LOGI("suppressing rendering of %s until %lld us",
622                            audio ? "audio" : "video", resumeAtMediaTimeUs);
623
624                    if (audio) {
625                        mSkipRenderingAudioUntilMediaTimeUs =
626                            resumeAtMediaTimeUs;
627                    } else {
628                        mSkipRenderingVideoUntilMediaTimeUs =
629                            resumeAtMediaTimeUs;
630                    }
631                }
632            }
633
634            flushDecoder(audio, formatChange);
635        }
636
637        reply->setInt32("err", err);
638        reply->post();
639        return OK;
640    }
641
642    // LOGV("returned a valid buffer of %s data", audio ? "audio" : "video");
643
644#if 0
645    int64_t mediaTimeUs;
646    CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
647    LOGV("feeding %s input buffer at media time %.2f secs",
648         audio ? "audio" : "video",
649         mediaTimeUs / 1E6);
650#endif
651
652    reply->setObject("buffer", accessUnit);
653    reply->post();
654
655    return OK;
656}
657
658void NuPlayer::renderBuffer(bool audio, const sp<AMessage> &msg) {
659    // LOGV("renderBuffer %s", audio ? "audio" : "video");
660
661    sp<AMessage> reply;
662    CHECK(msg->findMessage("reply", &reply));
663
664    sp<RefBase> obj;
665    CHECK(msg->findObject("buffer", &obj));
666
667    sp<ABuffer> buffer = static_cast<ABuffer *>(obj.get());
668
669    int64_t &skipUntilMediaTimeUs =
670        audio
671            ? mSkipRenderingAudioUntilMediaTimeUs
672            : mSkipRenderingVideoUntilMediaTimeUs;
673
674    if (skipUntilMediaTimeUs >= 0) {
675        int64_t mediaTimeUs;
676        CHECK(buffer->meta()->findInt64("timeUs", &mediaTimeUs));
677
678        if (mediaTimeUs < skipUntilMediaTimeUs) {
679            LOGV("dropping %s buffer at time %lld as requested.",
680                 audio ? "audio" : "video",
681                 mediaTimeUs);
682
683            reply->post();
684            return;
685        }
686
687        skipUntilMediaTimeUs = -1;
688    }
689
690    mRenderer->queueBuffer(audio, buffer, reply);
691}
692
693void NuPlayer::notifyListener(int msg, int ext1, int ext2) {
694    if (mDriver == NULL) {
695        return;
696    }
697
698    sp<NuPlayerDriver> driver = mDriver.promote();
699
700    if (driver == NULL) {
701        return;
702    }
703
704    driver->sendEvent(msg, ext1, ext2);
705}
706
707void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
708    // Make sure we don't continue to scan sources until we finish flushing.
709    ++mScanSourcesGeneration;
710    mScanSourcesPending = false;
711
712    (audio ? mAudioDecoder : mVideoDecoder)->signalFlush();
713    mRenderer->flush(audio);
714
715    FlushStatus newStatus =
716        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
717
718    if (audio) {
719        CHECK(mFlushingAudio == NONE
720                || mFlushingAudio == AWAITING_DISCONTINUITY);
721
722        mFlushingAudio = newStatus;
723
724        if (mFlushingVideo == NONE) {
725            mFlushingVideo = (mVideoDecoder != NULL)
726                ? AWAITING_DISCONTINUITY
727                : FLUSHED;
728        }
729    } else {
730        CHECK(mFlushingVideo == NONE
731                || mFlushingVideo == AWAITING_DISCONTINUITY);
732
733        mFlushingVideo = newStatus;
734
735        if (mFlushingAudio == NONE) {
736            mFlushingAudio = (mAudioDecoder != NULL)
737                ? AWAITING_DISCONTINUITY
738                : FLUSHED;
739        }
740    }
741}
742
743}  // namespace android
744