NuPlayerDecoder.cpp revision 2abde2c118a94f843a7450818c925d3f0b673cd3
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 "NuPlayerDecoder"
19#include <utils/Log.h>
20#include <inttypes.h>
21
22#include "NuPlayerDecoder.h"
23
24#include <media/ICrypto.h>
25#include <media/stagefright/foundation/ABitReader.h>
26#include <media/stagefright/foundation/ABuffer.h>
27#include <media/stagefright/foundation/ADebug.h>
28#include <media/stagefright/foundation/AMessage.h>
29#include <media/stagefright/MediaBuffer.h>
30#include <media/stagefright/MediaCodec.h>
31#include <media/stagefright/MediaDefs.h>
32#include <media/stagefright/MediaErrors.h>
33
34namespace android {
35
36NuPlayer::Decoder::Decoder(
37        const sp<AMessage> &notify,
38        const sp<NativeWindowWrapper> &nativeWindow)
39    : mNotify(notify),
40      mNativeWindow(nativeWindow),
41      mBufferGeneration(0),
42      mPaused(true),
43      mComponentName("decoder") {
44    // Every decoder has its own looper because MediaCodec operations
45    // are blocking, but NuPlayer needs asynchronous operations.
46    mDecoderLooper = new ALooper;
47    mDecoderLooper->setName("NPDecoder");
48    mDecoderLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
49
50    mCodecLooper = new ALooper;
51    mCodecLooper->setName("NPDecoder-CL");
52    mCodecLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
53}
54
55NuPlayer::Decoder::~Decoder() {
56    mDecoderLooper->unregisterHandler(id());
57    mDecoderLooper->stop();
58
59    releaseAndResetMediaBuffers();
60}
61
62static
63status_t PostAndAwaitResponse(
64        const sp<AMessage> &msg, sp<AMessage> *response) {
65    status_t err = msg->postAndAwaitResponse(response);
66
67    if (err != OK) {
68        return err;
69    }
70
71    if (!(*response)->findInt32("err", &err)) {
72        err = OK;
73    }
74
75    return err;
76}
77
78void NuPlayer::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
79    mCSDsForCurrentFormat.clear();
80    for (int32_t i = 0; ; ++i) {
81        AString tag = "csd-";
82        tag.append(i);
83        sp<ABuffer> buffer;
84        if (!format->findBuffer(tag.c_str(), &buffer)) {
85            break;
86        }
87        mCSDsForCurrentFormat.push(buffer);
88    }
89}
90
91void NuPlayer::Decoder::onConfigure(const sp<AMessage> &format) {
92    CHECK(mCodec == NULL);
93
94    ++mBufferGeneration;
95
96    AString mime;
97    CHECK(format->findString("mime", &mime));
98
99    sp<Surface> surface = NULL;
100    if (mNativeWindow != NULL) {
101        surface = mNativeWindow->getSurfaceTextureClient();
102    }
103
104    mComponentName = mime;
105    mComponentName.append(" decoder");
106    ALOGV("[%s] onConfigure (surface=%p)", mComponentName.c_str(), surface.get());
107
108    mCodec = MediaCodec::CreateByType(mCodecLooper, mime.c_str(), false /* encoder */);
109    int32_t secure = 0;
110    if (format->findInt32("secure", &secure) && secure != 0) {
111        if (mCodec != NULL) {
112            mCodec->getName(&mComponentName);
113            mComponentName.append(".secure");
114            mCodec->release();
115            ALOGI("[%s] creating", mComponentName.c_str());
116            mCodec = MediaCodec::CreateByComponentName(
117                    mCodecLooper, mComponentName.c_str());
118        }
119    }
120    if (mCodec == NULL) {
121        ALOGE("Failed to create %s%s decoder",
122                (secure ? "secure " : ""), mime.c_str());
123        handleError(UNKNOWN_ERROR);
124        return;
125    }
126
127    mCodec->getName(&mComponentName);
128
129    status_t err;
130    if (mNativeWindow != NULL) {
131        // disconnect from surface as MediaCodec will reconnect
132        err = native_window_api_disconnect(
133                surface.get(), NATIVE_WINDOW_API_MEDIA);
134        // We treat this as a warning, as this is a preparatory step.
135        // Codec will try to connect to the surface, which is where
136        // any error signaling will occur.
137        ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
138    }
139    err = mCodec->configure(
140            format, surface, NULL /* crypto */, 0 /* flags */);
141    if (err != OK) {
142        ALOGE("Failed to configure %s decoder (err=%d)", mComponentName.c_str(), err);
143        mCodec->release();
144        mCodec.clear();
145        handleError(err);
146        return;
147    }
148    rememberCodecSpecificData(format);
149
150    // the following should work in configured state
151    CHECK_EQ((status_t)OK, mCodec->getOutputFormat(&mOutputFormat));
152    CHECK_EQ((status_t)OK, mCodec->getInputFormat(&mInputFormat));
153
154    err = mCodec->start();
155    if (err != OK) {
156        ALOGE("Failed to start %s decoder (err=%d)", mComponentName.c_str(), err);
157        mCodec->release();
158        mCodec.clear();
159        handleError(err);
160        return;
161    }
162
163    // the following should work after start
164    CHECK_EQ((status_t)OK, mCodec->getInputBuffers(&mInputBuffers));
165    releaseAndResetMediaBuffers();
166    CHECK_EQ((status_t)OK, mCodec->getOutputBuffers(&mOutputBuffers));
167    ALOGV("[%s] got %zu input and %zu output buffers",
168            mComponentName.c_str(),
169            mInputBuffers.size(),
170            mOutputBuffers.size());
171
172    requestCodecNotification();
173    mPaused = false;
174}
175
176void NuPlayer::Decoder::releaseAndResetMediaBuffers() {
177    for (size_t i = 0; i < mMediaBuffers.size(); i++) {
178        if (mMediaBuffers[i] != NULL) {
179            mMediaBuffers[i]->release();
180            mMediaBuffers.editItemAt(i) = NULL;
181        }
182    }
183    mMediaBuffers.resize(mInputBuffers.size());
184    for (size_t i = 0; i < mMediaBuffers.size(); i++) {
185        mMediaBuffers.editItemAt(i) = NULL;
186    }
187    mInputBufferIsDequeued.clear();
188    mInputBufferIsDequeued.resize(mInputBuffers.size());
189    for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
190        mInputBufferIsDequeued.editItemAt(i) = false;
191    }
192}
193
194void NuPlayer::Decoder::requestCodecNotification() {
195    if (mCodec != NULL) {
196        sp<AMessage> reply = new AMessage(kWhatCodecNotify, id());
197        reply->setInt32("generation", mBufferGeneration);
198        mCodec->requestActivityNotification(reply);
199    }
200}
201
202bool NuPlayer::Decoder::isStaleReply(const sp<AMessage> &msg) {
203    int32_t generation;
204    CHECK(msg->findInt32("generation", &generation));
205    return generation != mBufferGeneration;
206}
207
208void NuPlayer::Decoder::init() {
209    mDecoderLooper->registerHandler(this);
210}
211
212void NuPlayer::Decoder::configure(const sp<AMessage> &format) {
213    sp<AMessage> msg = new AMessage(kWhatConfigure, id());
214    msg->setMessage("format", format);
215    msg->post();
216}
217
218void NuPlayer::Decoder::signalUpdateFormat(const sp<AMessage> &format) {
219    sp<AMessage> msg = new AMessage(kWhatUpdateFormat, id());
220    msg->setMessage("format", format);
221    msg->post();
222}
223
224status_t NuPlayer::Decoder::getInputBuffers(Vector<sp<ABuffer> > *buffers) const {
225    sp<AMessage> msg = new AMessage(kWhatGetInputBuffers, id());
226    msg->setPointer("buffers", buffers);
227
228    sp<AMessage> response;
229    return PostAndAwaitResponse(msg, &response);
230}
231
232void NuPlayer::Decoder::handleError(int32_t err)
233{
234    // We cannot immediately release the codec due to buffers still outstanding
235    // in the renderer.  We signal to the player the error so it can shutdown/release the
236    // decoder after flushing and increment the generation to discard unnecessary messages.
237
238    ++mBufferGeneration;
239
240    sp<AMessage> notify = mNotify->dup();
241    notify->setInt32("what", kWhatError);
242    notify->setInt32("err", err);
243    notify->post();
244}
245
246bool NuPlayer::Decoder::handleAnInputBuffer() {
247    size_t bufferIx = -1;
248    status_t res = mCodec->dequeueInputBuffer(&bufferIx);
249    ALOGV("[%s] dequeued input: %d",
250            mComponentName.c_str(), res == OK ? (int)bufferIx : res);
251    if (res != OK) {
252        if (res != -EAGAIN) {
253            ALOGE("Failed to dequeue input buffer for %s (err=%d)",
254                    mComponentName.c_str(), res);
255            handleError(res);
256        }
257        return false;
258    }
259
260    CHECK_LT(bufferIx, mInputBuffers.size());
261
262    if (mMediaBuffers[bufferIx] != NULL) {
263        mMediaBuffers[bufferIx]->release();
264        mMediaBuffers.editItemAt(bufferIx) = NULL;
265    }
266    mInputBufferIsDequeued.editItemAt(bufferIx) = true;
267
268    sp<AMessage> reply = new AMessage(kWhatInputBufferFilled, id());
269    reply->setSize("buffer-ix", bufferIx);
270    reply->setInt32("generation", mBufferGeneration);
271
272    if (!mCSDsToSubmit.isEmpty()) {
273        sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
274        ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
275        reply->setBuffer("buffer", buffer);
276        mCSDsToSubmit.removeAt(0);
277        reply->post();
278        return true;
279    }
280
281    sp<AMessage> notify = mNotify->dup();
282    notify->setInt32("what", kWhatFillThisBuffer);
283    notify->setBuffer("buffer", mInputBuffers[bufferIx]);
284    notify->setMessage("reply", reply);
285    notify->post();
286    return true;
287}
288
289void android::NuPlayer::Decoder::onInputBufferFilled(const sp<AMessage> &msg) {
290    size_t bufferIx;
291    CHECK(msg->findSize("buffer-ix", &bufferIx));
292    CHECK_LT(bufferIx, mInputBuffers.size());
293    sp<ABuffer> codecBuffer = mInputBuffers[bufferIx];
294
295    sp<ABuffer> buffer;
296    bool hasBuffer = msg->findBuffer("buffer", &buffer);
297
298    // handle widevine classic source - that fills an arbitrary input buffer
299    MediaBuffer *mediaBuffer = NULL;
300    if (hasBuffer) {
301        mediaBuffer = (MediaBuffer *)(buffer->getMediaBufferBase());
302        if (mediaBuffer != NULL) {
303            // likely filled another buffer than we requested: adjust buffer index
304            size_t ix;
305            for (ix = 0; ix < mInputBuffers.size(); ix++) {
306                const sp<ABuffer> &buf = mInputBuffers[ix];
307                if (buf->data() == mediaBuffer->data()) {
308                    // all input buffers are dequeued on start, hence the check
309                    CHECK(mInputBufferIsDequeued[ix]);
310                    ALOGV("[%s] received MediaBuffer for #%zu instead of #%zu",
311                            mComponentName.c_str(), ix, bufferIx);
312
313                    // TRICKY: need buffer for the metadata, so instead, set
314                    // codecBuffer to the same (though incorrect) buffer to
315                    // avoid a memcpy into the codecBuffer
316                    codecBuffer = buffer;
317                    codecBuffer->setRange(
318                            mediaBuffer->range_offset(),
319                            mediaBuffer->range_length());
320                    bufferIx = ix;
321                    break;
322                }
323            }
324            CHECK(ix < mInputBuffers.size());
325        }
326    }
327
328
329
330    if (buffer == NULL /* includes !hasBuffer */) {
331        int32_t streamErr = ERROR_END_OF_STREAM;
332        CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
333
334        if (streamErr == OK) {
335            /* buffers are returned to hold on to */
336            return;
337        }
338
339        // attempt to queue EOS
340        status_t err = mCodec->queueInputBuffer(
341                bufferIx,
342                0,
343                0,
344                0,
345                MediaCodec::BUFFER_FLAG_EOS);
346        if (err == OK) {
347            mInputBufferIsDequeued.editItemAt(bufferIx) = false;
348        } else if (streamErr == ERROR_END_OF_STREAM) {
349            streamErr = err;
350            // err will not be ERROR_END_OF_STREAM
351        }
352
353        if (streamErr != ERROR_END_OF_STREAM) {
354            ALOGE("Stream error for %s (err=%d), EOS %s queued",
355                    mComponentName.c_str(),
356                    streamErr,
357                    err == OK ? "successfully" : "unsuccessfully");
358            handleError(streamErr);
359        }
360    } else {
361        int64_t timeUs = 0;
362        uint32_t flags = 0;
363        CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
364
365        int32_t eos, csd;
366        // we do not expect SYNCFRAME for decoder
367        if (buffer->meta()->findInt32("eos", &eos) && eos) {
368            flags |= MediaCodec::BUFFER_FLAG_EOS;
369        } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
370            flags |= MediaCodec::BUFFER_FLAG_CODECCONFIG;
371        }
372
373        // copy into codec buffer
374        if (buffer != codecBuffer) {
375            CHECK_LE(buffer->size(), codecBuffer->capacity());
376            codecBuffer->setRange(0, buffer->size());
377            memcpy(codecBuffer->data(), buffer->data(), buffer->size());
378        }
379
380        status_t err = mCodec->queueInputBuffer(
381                        bufferIx,
382                        codecBuffer->offset(),
383                        codecBuffer->size(),
384                        timeUs,
385                        flags);
386        if (err != OK) {
387            if (mediaBuffer != NULL) {
388                mediaBuffer->release();
389            }
390            ALOGE("Failed to queue input buffer for %s (err=%d)",
391                    mComponentName.c_str(), err);
392            handleError(err);
393        } else {
394            mInputBufferIsDequeued.editItemAt(bufferIx) = false;
395            if (mediaBuffer != NULL) {
396                CHECK(mMediaBuffers[bufferIx] == NULL);
397                mMediaBuffers.editItemAt(bufferIx) = mediaBuffer;
398            }
399        }
400    }
401}
402
403bool NuPlayer::Decoder::handleAnOutputBuffer() {
404    size_t bufferIx = -1;
405    size_t offset;
406    size_t size;
407    int64_t timeUs;
408    uint32_t flags;
409    status_t res = mCodec->dequeueOutputBuffer(
410            &bufferIx, &offset, &size, &timeUs, &flags);
411
412    if (res != OK) {
413        ALOGV("[%s] dequeued output: %d", mComponentName.c_str(), res);
414    } else {
415        ALOGV("[%s] dequeued output: %d (time=%lld flags=%" PRIu32 ")",
416                mComponentName.c_str(), (int)bufferIx, timeUs, flags);
417    }
418
419    if (res == INFO_OUTPUT_BUFFERS_CHANGED) {
420        res = mCodec->getOutputBuffers(&mOutputBuffers);
421        if (res != OK) {
422            ALOGE("Failed to get output buffers for %s after INFO event (err=%d)",
423                    mComponentName.c_str(), res);
424            handleError(res);
425            return false;
426        }
427        // NuPlayer ignores this
428        return true;
429    } else if (res == INFO_FORMAT_CHANGED) {
430        sp<AMessage> format = new AMessage();
431        res = mCodec->getOutputFormat(&format);
432        if (res != OK) {
433            ALOGE("Failed to get output format for %s after INFO event (err=%d)",
434                    mComponentName.c_str(), res);
435            handleError(res);
436            return false;
437        }
438
439        sp<AMessage> notify = mNotify->dup();
440        notify->setInt32("what", kWhatOutputFormatChanged);
441        notify->setMessage("format", format);
442        notify->post();
443        return true;
444    } else if (res == INFO_DISCONTINUITY) {
445        // nothing to do
446        return true;
447    } else if (res != OK) {
448        if (res != -EAGAIN) {
449            ALOGE("Failed to dequeue output buffer for %s (err=%d)",
450                    mComponentName.c_str(), res);
451            handleError(res);
452        }
453        return false;
454    }
455
456    CHECK_LT(bufferIx, mOutputBuffers.size());
457    sp<ABuffer> buffer = mOutputBuffers[bufferIx];
458    buffer->setRange(offset, size);
459    buffer->meta()->clear();
460    buffer->meta()->setInt64("timeUs", timeUs);
461    if (flags & MediaCodec::BUFFER_FLAG_EOS) {
462        buffer->meta()->setInt32("eos", true);
463    }
464    // we do not expect CODECCONFIG or SYNCFRAME for decoder
465
466    sp<AMessage> reply = new AMessage(kWhatRenderBuffer, id());
467    reply->setSize("buffer-ix", bufferIx);
468    reply->setInt32("generation", mBufferGeneration);
469
470    sp<AMessage> notify = mNotify->dup();
471    notify->setInt32("what", kWhatDrainThisBuffer);
472    notify->setBuffer("buffer", buffer);
473    notify->setMessage("reply", reply);
474    notify->post();
475
476    // FIXME: This should be handled after rendering is complete,
477    // but Renderer needs it now
478    if (flags & MediaCodec::BUFFER_FLAG_EOS) {
479        ALOGV("queueing eos [%s]", mComponentName.c_str());
480        sp<AMessage> notify = mNotify->dup();
481        notify->setInt32("what", kWhatEOS);
482        notify->setInt32("err", ERROR_END_OF_STREAM);
483        notify->post();
484    }
485    return true;
486}
487
488void NuPlayer::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
489    status_t err;
490    int32_t render;
491    size_t bufferIx;
492    CHECK(msg->findSize("buffer-ix", &bufferIx));
493    if (msg->findInt32("render", &render) && render) {
494        int64_t timestampNs;
495        CHECK(msg->findInt64("timestampNs", &timestampNs));
496        err = mCodec->renderOutputBufferAndRelease(bufferIx, timestampNs);
497    } else {
498        err = mCodec->releaseOutputBuffer(bufferIx);
499    }
500    if (err != OK) {
501        ALOGE("failed to release output buffer for %s (err=%d)",
502                mComponentName.c_str(), err);
503        handleError(err);
504    }
505}
506
507void NuPlayer::Decoder::onFlush() {
508    status_t err = OK;
509    if (mCodec != NULL) {
510        err = mCodec->flush();
511        mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
512        ++mBufferGeneration;
513    }
514
515    if (err != OK) {
516        ALOGE("failed to flush %s (err=%d)", mComponentName.c_str(), err);
517        handleError(err);
518        // finish with posting kWhatFlushCompleted.
519        // we attempt to release the buffers even if flush fails.
520    }
521    releaseAndResetMediaBuffers();
522
523    sp<AMessage> notify = mNotify->dup();
524    notify->setInt32("what", kWhatFlushCompleted);
525    notify->post();
526    mPaused = true;
527}
528
529void NuPlayer::Decoder::onResume() {
530    mPaused = false;
531}
532
533void NuPlayer::Decoder::onShutdown() {
534    status_t err = OK;
535    if (mCodec != NULL) {
536        err = mCodec->release();
537        mCodec = NULL;
538        ++mBufferGeneration;
539
540        if (mNativeWindow != NULL) {
541            // reconnect to surface as MediaCodec disconnected from it
542            status_t error =
543                    native_window_api_connect(
544                            mNativeWindow->getNativeWindow().get(),
545                            NATIVE_WINDOW_API_MEDIA);
546            ALOGW_IF(error != NO_ERROR,
547                    "[%s] failed to connect to native window, error=%d",
548                    mComponentName.c_str(), error);
549        }
550        mComponentName = "decoder";
551    }
552
553    releaseAndResetMediaBuffers();
554
555    if (err != OK) {
556        ALOGE("failed to release %s (err=%d)", mComponentName.c_str(), err);
557        handleError(err);
558        // finish with posting kWhatShutdownCompleted.
559    }
560
561    sp<AMessage> notify = mNotify->dup();
562    notify->setInt32("what", kWhatShutdownCompleted);
563    notify->post();
564    mPaused = true;
565}
566
567void NuPlayer::Decoder::onMessageReceived(const sp<AMessage> &msg) {
568    ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
569
570    switch (msg->what()) {
571        case kWhatConfigure:
572        {
573            sp<AMessage> format;
574            CHECK(msg->findMessage("format", &format));
575            onConfigure(format);
576            break;
577        }
578
579        case kWhatUpdateFormat:
580        {
581            sp<AMessage> format;
582            CHECK(msg->findMessage("format", &format));
583            rememberCodecSpecificData(format);
584            break;
585        }
586
587        case kWhatGetInputBuffers:
588        {
589            uint32_t replyID;
590            CHECK(msg->senderAwaitsResponse(&replyID));
591
592            Vector<sp<ABuffer> > *dstBuffers;
593            CHECK(msg->findPointer("buffers", (void **)&dstBuffers));
594
595            dstBuffers->clear();
596            for (size_t i = 0; i < mInputBuffers.size(); i++) {
597                dstBuffers->push(mInputBuffers[i]);
598            }
599
600            (new AMessage)->postReply(replyID);
601            break;
602        }
603
604        case kWhatCodecNotify:
605        {
606            if (!isStaleReply(msg)) {
607                if (!mPaused) {
608                    while (handleAnInputBuffer()) {
609                    }
610                }
611
612                while (handleAnOutputBuffer()) {
613                }
614            }
615
616            requestCodecNotification();
617            break;
618        }
619
620        case kWhatInputBufferFilled:
621        {
622            if (!isStaleReply(msg)) {
623                onInputBufferFilled(msg);
624            }
625
626            break;
627        }
628
629        case kWhatRenderBuffer:
630        {
631            if (!isStaleReply(msg)) {
632                onRenderBuffer(msg);
633            }
634            break;
635        }
636
637        case kWhatFlush:
638        {
639            sp<AMessage> format;
640            if (msg->findMessage("new-format", &format)) {
641                rememberCodecSpecificData(format);
642            }
643            onFlush();
644            break;
645        }
646
647        case kWhatResume:
648        {
649            onResume();
650            break;
651        }
652
653        case kWhatShutdown:
654        {
655            onShutdown();
656            break;
657        }
658
659        default:
660            TRESPASS();
661            break;
662    }
663}
664
665void NuPlayer::Decoder::signalFlush(const sp<AMessage> &format) {
666    sp<AMessage> msg = new AMessage(kWhatFlush, id());
667    if (format != NULL) {
668        msg->setMessage("new-format", format);
669    }
670    msg->post();
671}
672
673void NuPlayer::Decoder::signalResume() {
674    (new AMessage(kWhatResume, id()))->post();
675}
676
677void NuPlayer::Decoder::initiateShutdown() {
678    (new AMessage(kWhatShutdown, id()))->post();
679}
680
681bool NuPlayer::Decoder::supportsSeamlessAudioFormatChange(const sp<AMessage> &targetFormat) const {
682    if (targetFormat == NULL) {
683        return true;
684    }
685
686    AString mime;
687    if (!targetFormat->findString("mime", &mime)) {
688        return false;
689    }
690
691    if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
692        // field-by-field comparison
693        const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
694        for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
695            int32_t oldVal, newVal;
696            if (!mOutputFormat->findInt32(keys[i], &oldVal) ||
697                    !targetFormat->findInt32(keys[i], &newVal) ||
698                    oldVal != newVal) {
699                return false;
700            }
701        }
702
703        sp<ABuffer> oldBuf, newBuf;
704        if (mOutputFormat->findBuffer("csd-0", &oldBuf) &&
705                targetFormat->findBuffer("csd-0", &newBuf)) {
706            if (oldBuf->size() != newBuf->size()) {
707                return false;
708            }
709            return !memcmp(oldBuf->data(), newBuf->data(), oldBuf->size());
710        }
711    }
712    return false;
713}
714
715bool NuPlayer::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
716    if (mOutputFormat == NULL) {
717        return false;
718    }
719
720    if (targetFormat == NULL) {
721        return true;
722    }
723
724    AString oldMime, newMime;
725    if (!mOutputFormat->findString("mime", &oldMime)
726            || !targetFormat->findString("mime", &newMime)
727            || !(oldMime == newMime)) {
728        return false;
729    }
730
731    bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
732    bool seamless;
733    if (audio) {
734        seamless = supportsSeamlessAudioFormatChange(targetFormat);
735    } else {
736        int32_t isAdaptive;
737        seamless = (mCodec != NULL &&
738                mInputFormat->findInt32("adaptive-playback", &isAdaptive) &&
739                isAdaptive);
740    }
741
742    ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
743    return seamless;
744}
745
746struct CCData {
747    CCData(uint8_t type, uint8_t data1, uint8_t data2)
748        : mType(type), mData1(data1), mData2(data2) {
749    }
750    bool getChannel(size_t *channel) const {
751        if (mData1 >= 0x10 && mData1 <= 0x1f) {
752            *channel = (mData1 >= 0x18 ? 1 : 0) + (mType ? 2 : 0);
753            return true;
754        }
755        return false;
756    }
757
758    uint8_t mType;
759    uint8_t mData1;
760    uint8_t mData2;
761};
762
763static bool isNullPad(CCData *cc) {
764    return cc->mData1 < 0x10 && cc->mData2 < 0x10;
765}
766
767static void dumpBytePair(const sp<ABuffer> &ccBuf) {
768    size_t offset = 0;
769    AString out;
770
771    while (offset < ccBuf->size()) {
772        char tmp[128];
773
774        CCData *cc = (CCData *) (ccBuf->data() + offset);
775
776        if (isNullPad(cc)) {
777            // 1 null pad or XDS metadata, ignore
778            offset += sizeof(CCData);
779            continue;
780        }
781
782        if (cc->mData1 >= 0x20 && cc->mData1 <= 0x7f) {
783            // 2 basic chars
784            sprintf(tmp, "[%d]Basic: %c %c", cc->mType, cc->mData1, cc->mData2);
785        } else if ((cc->mData1 == 0x11 || cc->mData1 == 0x19)
786                 && cc->mData2 >= 0x30 && cc->mData2 <= 0x3f) {
787            // 1 special char
788            sprintf(tmp, "[%d]Special: %02x %02x", cc->mType, cc->mData1, cc->mData2);
789        } else if ((cc->mData1 == 0x12 || cc->mData1 == 0x1A)
790                 && cc->mData2 >= 0x20 && cc->mData2 <= 0x3f){
791            // 1 Spanish/French char
792            sprintf(tmp, "[%d]Spanish: %02x %02x", cc->mType, cc->mData1, cc->mData2);
793        } else if ((cc->mData1 == 0x13 || cc->mData1 == 0x1B)
794                 && cc->mData2 >= 0x20 && cc->mData2 <= 0x3f){
795            // 1 Portuguese/German/Danish char
796            sprintf(tmp, "[%d]German: %02x %02x", cc->mType, cc->mData1, cc->mData2);
797        } else if ((cc->mData1 == 0x11 || cc->mData1 == 0x19)
798                 && cc->mData2 >= 0x20 && cc->mData2 <= 0x2f){
799            // Mid-Row Codes (Table 69)
800            sprintf(tmp, "[%d]Mid-row: %02x %02x", cc->mType, cc->mData1, cc->mData2);
801        } else if (((cc->mData1 == 0x14 || cc->mData1 == 0x1c)
802                  && cc->mData2 >= 0x20 && cc->mData2 <= 0x2f)
803                  ||
804                   ((cc->mData1 == 0x17 || cc->mData1 == 0x1f)
805                  && cc->mData2 >= 0x21 && cc->mData2 <= 0x23)){
806            // Misc Control Codes (Table 70)
807            sprintf(tmp, "[%d]Ctrl: %02x %02x", cc->mType, cc->mData1, cc->mData2);
808        } else if ((cc->mData1 & 0x70) == 0x10
809                && (cc->mData2 & 0x40) == 0x40
810                && ((cc->mData1 & 0x07) || !(cc->mData2 & 0x20)) ) {
811            // Preamble Address Codes (Table 71)
812            sprintf(tmp, "[%d]PAC: %02x %02x", cc->mType, cc->mData1, cc->mData2);
813        } else {
814            sprintf(tmp, "[%d]Invalid: %02x %02x", cc->mType, cc->mData1, cc->mData2);
815        }
816
817        if (out.size() > 0) {
818            out.append(", ");
819        }
820
821        out.append(tmp);
822
823        offset += sizeof(CCData);
824    }
825
826    ALOGI("%s", out.c_str());
827}
828
829NuPlayer::CCDecoder::CCDecoder(const sp<AMessage> &notify)
830    : mNotify(notify),
831      mCurrentChannel(0),
832      mSelectedTrack(-1) {
833      for (size_t i = 0; i < sizeof(mTrackIndices)/sizeof(mTrackIndices[0]); ++i) {
834          mTrackIndices[i] = -1;
835      }
836}
837
838size_t NuPlayer::CCDecoder::getTrackCount() const {
839    return mFoundChannels.size();
840}
841
842sp<AMessage> NuPlayer::CCDecoder::getTrackInfo(size_t index) const {
843    if (!isTrackValid(index)) {
844        return NULL;
845    }
846
847    sp<AMessage> format = new AMessage();
848
849    format->setInt32("type", MEDIA_TRACK_TYPE_SUBTITLE);
850    format->setString("language", "und");
851    format->setString("mime", MEDIA_MIMETYPE_TEXT_CEA_608);
852    //CC1, field 0 channel 0
853    bool isDefaultAuto = (mFoundChannels[index] == 0);
854    format->setInt32("auto", isDefaultAuto);
855    format->setInt32("default", isDefaultAuto);
856    format->setInt32("forced", 0);
857
858    return format;
859}
860
861status_t NuPlayer::CCDecoder::selectTrack(size_t index, bool select) {
862    if (!isTrackValid(index)) {
863        return BAD_VALUE;
864    }
865
866    if (select) {
867        if (mSelectedTrack == (ssize_t)index) {
868            ALOGE("track %zu already selected", index);
869            return BAD_VALUE;
870        }
871        ALOGV("selected track %zu", index);
872        mSelectedTrack = index;
873    } else {
874        if (mSelectedTrack != (ssize_t)index) {
875            ALOGE("track %zu is not selected", index);
876            return BAD_VALUE;
877        }
878        ALOGV("unselected track %zu", index);
879        mSelectedTrack = -1;
880    }
881
882    return OK;
883}
884
885bool NuPlayer::CCDecoder::isSelected() const {
886    return mSelectedTrack >= 0 && mSelectedTrack < (int32_t) getTrackCount();
887}
888
889bool NuPlayer::CCDecoder::isTrackValid(size_t index) const {
890    return index < getTrackCount();
891}
892
893int32_t NuPlayer::CCDecoder::getTrackIndex(size_t channel) const {
894    if (channel < sizeof(mTrackIndices)/sizeof(mTrackIndices[0])) {
895        return mTrackIndices[channel];
896    }
897    return -1;
898}
899
900// returns true if a new CC track is found
901bool NuPlayer::CCDecoder::extractFromSEI(const sp<ABuffer> &accessUnit) {
902    int64_t timeUs;
903    CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
904
905    sp<ABuffer> sei;
906    if (!accessUnit->meta()->findBuffer("sei", &sei) || sei == NULL) {
907        return false;
908    }
909
910    bool trackAdded = false;
911
912    NALBitReader br(sei->data() + 1, sei->size() - 1);
913    // sei_message()
914    while (br.atLeastNumBitsLeft(16)) { // at least 16-bit for sei_message()
915        uint32_t payload_type = 0;
916        size_t payload_size = 0;
917        uint8_t last_byte;
918
919        do {
920            last_byte = br.getBits(8);
921            payload_type += last_byte;
922        } while (last_byte == 0xFF);
923
924        do {
925            last_byte = br.getBits(8);
926            payload_size += last_byte;
927        } while (last_byte == 0xFF);
928
929        // sei_payload()
930        if (payload_type == 4) {
931            // user_data_registered_itu_t_t35()
932
933            // ATSC A/72: 6.4.2
934            uint8_t itu_t_t35_country_code = br.getBits(8);
935            uint16_t itu_t_t35_provider_code = br.getBits(16);
936            uint32_t user_identifier = br.getBits(32);
937            uint8_t user_data_type_code = br.getBits(8);
938
939            payload_size -= 1 + 2 + 4 + 1;
940
941            if (itu_t_t35_country_code == 0xB5
942                    && itu_t_t35_provider_code == 0x0031
943                    && user_identifier == 'GA94'
944                    && user_data_type_code == 0x3) {
945                // MPEG_cc_data()
946                // ATSC A/53 Part 4: 6.2.3.1
947                br.skipBits(1); //process_em_data_flag
948                bool process_cc_data_flag = br.getBits(1);
949                br.skipBits(1); //additional_data_flag
950                size_t cc_count = br.getBits(5);
951                br.skipBits(8); // em_data;
952                payload_size -= 2;
953
954                if (process_cc_data_flag) {
955                    AString out;
956
957                    sp<ABuffer> ccBuf = new ABuffer(cc_count * sizeof(CCData));
958                    ccBuf->setRange(0, 0);
959
960                    for (size_t i = 0; i < cc_count; i++) {
961                        uint8_t marker = br.getBits(5);
962                        CHECK_EQ(marker, 0x1f);
963
964                        bool cc_valid = br.getBits(1);
965                        uint8_t cc_type = br.getBits(2);
966                        // remove odd parity bit
967                        uint8_t cc_data_1 = br.getBits(8) & 0x7f;
968                        uint8_t cc_data_2 = br.getBits(8) & 0x7f;
969
970                        if (cc_valid
971                                && (cc_type == 0 || cc_type == 1)) {
972                            CCData cc(cc_type, cc_data_1, cc_data_2);
973                            if (!isNullPad(&cc)) {
974                                size_t channel;
975                                if (cc.getChannel(&channel) && getTrackIndex(channel) < 0) {
976                                    mTrackIndices[channel] = mFoundChannels.size();
977                                    mFoundChannels.push_back(channel);
978                                    trackAdded = true;
979                                }
980                                memcpy(ccBuf->data() + ccBuf->size(),
981                                        (void *)&cc, sizeof(cc));
982                                ccBuf->setRange(0, ccBuf->size() + sizeof(CCData));
983                            }
984                        }
985                    }
986                    payload_size -= cc_count * 3;
987
988                    mCCMap.add(timeUs, ccBuf);
989                    break;
990                }
991            } else {
992                ALOGV("Malformed SEI payload type 4");
993            }
994        } else {
995            ALOGV("Unsupported SEI payload type %d", payload_type);
996        }
997
998        // skipping remaining bits of this payload
999        br.skipBits(payload_size * 8);
1000    }
1001
1002    return trackAdded;
1003}
1004
1005sp<ABuffer> NuPlayer::CCDecoder::filterCCBuf(
1006        const sp<ABuffer> &ccBuf, size_t index) {
1007    sp<ABuffer> filteredCCBuf = new ABuffer(ccBuf->size());
1008    filteredCCBuf->setRange(0, 0);
1009
1010    size_t cc_count = ccBuf->size() / sizeof(CCData);
1011    const CCData* cc_data = (const CCData*)ccBuf->data();
1012    for (size_t i = 0; i < cc_count; ++i) {
1013        size_t channel;
1014        if (cc_data[i].getChannel(&channel)) {
1015            mCurrentChannel = channel;
1016        }
1017        if (mCurrentChannel == mFoundChannels[index]) {
1018            memcpy(filteredCCBuf->data() + filteredCCBuf->size(),
1019                    (void *)&cc_data[i], sizeof(CCData));
1020            filteredCCBuf->setRange(0, filteredCCBuf->size() + sizeof(CCData));
1021        }
1022    }
1023
1024    return filteredCCBuf;
1025}
1026
1027void NuPlayer::CCDecoder::decode(const sp<ABuffer> &accessUnit) {
1028    if (extractFromSEI(accessUnit)) {
1029        ALOGI("Found CEA-608 track");
1030        sp<AMessage> msg = mNotify->dup();
1031        msg->setInt32("what", kWhatTrackAdded);
1032        msg->post();
1033    }
1034    // TODO: extract CC from other sources
1035}
1036
1037void NuPlayer::CCDecoder::display(int64_t timeUs) {
1038    if (!isTrackValid(mSelectedTrack)) {
1039        ALOGE("Could not find current track(index=%d)", mSelectedTrack);
1040        return;
1041    }
1042
1043    ssize_t index = mCCMap.indexOfKey(timeUs);
1044    if (index < 0) {
1045        ALOGV("cc for timestamp %" PRId64 " not found", timeUs);
1046        return;
1047    }
1048
1049    sp<ABuffer> ccBuf = filterCCBuf(mCCMap.valueAt(index), mSelectedTrack);
1050
1051    if (ccBuf->size() > 0) {
1052#if 0
1053        dumpBytePair(ccBuf);
1054#endif
1055
1056        ccBuf->meta()->setInt32("trackIndex", mSelectedTrack);
1057        ccBuf->meta()->setInt64("timeUs", timeUs);
1058        ccBuf->meta()->setInt64("durationUs", 0ll);
1059
1060        sp<AMessage> msg = mNotify->dup();
1061        msg->setInt32("what", kWhatClosedCaptionData);
1062        msg->setBuffer("buffer", ccBuf);
1063        msg->post();
1064    }
1065
1066    // remove all entries before timeUs
1067    mCCMap.removeItemsAt(0, index + 1);
1068}
1069
1070void NuPlayer::CCDecoder::flush() {
1071    mCCMap.clear();
1072}
1073
1074}  // namespace android
1075
1076