Android 13 - Media框架(6)- NuPlayer

2023-11-13

上一节我们通过 NuPlayerDriver 了解了 NuPlayer 的使用方式,这一节我们一起来学习 NuPlayer 的部分实现细节。
ps:之前用 NuPlayer 播放本地视频很多都无法播放,所以觉得它不太行,这两天重新阅读发现它的功能其实很全面,无法播放都是Extractor的锅,NuPlayer 有很多细节值得学习!

1、NuPlayer结构

请添加图片描述

我将 NuPlayer 拆成4部分来学习,分别是:

  • Source:数据源,包括 IO 和 demux 两部分;
  • Decoder:编解码组件,使用 MediaCodec 实现;
  • Render:用于解码后的数据渲染与 Avsync;
  • Controller:以上三个部分的控制器,这里指的是 NuPlayer 自身;

2、NuPlayer控制接口的实现

2.1、setDataSourceAsync

setDataSource 是用来根据传进来的 url 创建对应类型 Source 的,这里找一个最常用的版本:

void NuPlayer::setDataSourceAsync(
        const sp<IMediaHTTPService> &httpService,
        const char *url,
        const KeyedVector<String8, String8> *headers) {
	// 1. 异步消息处理
    sp<AMessage> msg = new AMessage(kWhatSetDataSource, this);
    size_t len = strlen(url);
	// 2. 用于Source 给 NuPlayer 的 Callback
    sp<AMessage> notify = new AMessage(kWhatSourceNotify, this);

    sp<Source> source;
    // 3. 根据 url 创建对应的 Source
    if (IsHTTPLiveURL(url)) {
        source = new HTTPLiveSource(notify, httpService, url, headers);
        mDataSourceType = DATA_SOURCE_TYPE_HTTP_LIVE;
    } else if (!strncasecmp(url, "rtsp://", 7)) {
        source = new RTSPSource(
                notify, httpService, url, headers, mUIDValid, mUID);
        mDataSourceType = DATA_SOURCE_TYPE_RTSP;
    } else if ((!strncasecmp(url, "http://", 7)
                || !strncasecmp(url, "https://", 8))
                    && ((len >= 4 && !strcasecmp(".sdp", &url[len - 4]))
                    || strstr(url, ".sdp?"))) {
        source = new RTSPSource(
                notify, httpService, url, headers, mUIDValid, mUID, true);
        mDataSourceType = DATA_SOURCE_TYPE_RTSP;
    } else {
        sp<GenericSource> genericSource =
                new GenericSource(notify, mUIDValid, mUID, mMediaClock);

        status_t err = genericSource->setDataSource(httpService, url, headers);

        if (err == OK) {
            source = genericSource;
        } else {
            ALOGE("Failed to set data source!");
        }
        mDataSourceType = DATA_SOURCE_TYPE_GENERIC_URL;
    }
    msg->setObject("source", source);
    msg->post();
}
  1. NuPlayer 使用 android 异步消息处理机制来处理上层调用;
  2. 创建一个 AMessage 并将 target 设定为 NuPlayer 自身,从而实现 Source 到 NuPlayer 的 Callback;
  3. 根据 url 创建对应的 Source
    • 如果 url 以 .m3u8 结尾,那么认为这是一个直播源,创建 HTTPLiveSource
    • 如果 url 以 rtsp:// 开头,那么创建 RTSPSource
    • 如果 url 以 http:// https://开头,并以 .sdp 结尾,那么创建 RTSPSource,但是和上面的参数上会有区别;
    • 如果上面的条件不满足,则创建 GenericSource,一般是用来播放本地文件的。
  4. 设定对应的 mDataSourceType;

我们在上一篇笔记中说到,setDataSource 必须是同步调用,NuPlayer 完成 Source 创建后会 Callback 给 NuPlayerDriver:

        case kWhatSetDataSource:
        {
            CHECK(mSource == NULL);
            status_t err = OK;
            sp<RefBase> obj;
            CHECK(msg->findObject("source", &obj));
            if (obj != NULL) {
                Mutex::Autolock autoLock(mSourceLock);
                mSource = static_cast<Source *>(obj.get());
            } else {
                err = UNKNOWN_ERROR;
            }
            CHECK(mDriver != NULL);
            sp<NuPlayerDriver> driver = mDriver.promote();
            if (driver != NULL) {
                driver->notifySetDataSourceCompleted(err);
            }
            break;
        }

setDataSource 完成后,一些和 Source 相关的方法就可以调用了,比如 setBufferingSettings

2.2、prepareAsync

prepare 控制的内容很简单,就是调用 Source 的 prepareAsync 方法:

        case kWhatPrepare:
        {
            ALOGV("onMessageReceived kWhatPrepare");
            mSource->prepareAsync();
            break;
        }

Source prepareAsync 完成后会调用 post 将消息发送回来:

        case Source::kWhatPrepared:
        {
        	// 1、
            ALOGV("NuPlayer::onSourceNotify Source::kWhatPrepared source: %p", mSource.get());
            if (mSource == NULL) {
                // This is a stale notification from a source that was
                // asynchronously preparing when the client called reset().
                // We handled the reset, the source is gone.
                break;
            }

            int32_t err;
            CHECK(msg->findInt32("err", &err));

            if (err != OK) {
                // shut down potential secure codecs in case client never calls reset
                mDeferredActions.push_back(
                        new FlushDecoderAction(FLUSH_CMD_SHUTDOWN /* audio */,
                                               FLUSH_CMD_SHUTDOWN /* video */));
                processDeferredActions();
            } else {
                mPrepared = true;
            }

            sp<NuPlayerDriver> driver = mDriver.promote();
            if (driver != NULL) {
                // notify duration first, so that it's definitely set when
                // the app received the "prepare complete" callback.
                int64_t durationUs;
                if (mSource->getDuration(&durationUs) == OK) {
                    driver->notifyDuration(durationUs);
                }
                driver->notifyPrepareCompleted(err);
            }

            break;
        }

这里有对 prepareAsync 过程中调用 reset 的情况做一些处理,如果 Source 被reset销毁变成 NULL,那么就不会上抛回调消息

2.3、start

        case kWhatStart:
        {
            ALOGV("kWhatStart");
            if (mStarted) {
                // do not resume yet if the source is still buffering
                if (!mPausedForBuffering) {
                    onResume();
                }
            } else {
                onStart();
            }
            mPausedByClient = false;
            break;
        }

如果播放还未开始,则调用 onStart,如果是暂停状态则调用 onResume,但是如果因为 buffer 不足 Source callback 回来调用了 pause,则不做任何操作。

先来看 onStart:

void NuPlayer::onStart(int64_t startPositionUs, MediaPlayerSeekMode mode) {
	// 1. 启动source
    if (!mSourceStarted) {
        mSourceStarted = true;
        mSource->start();
    }
    // 1. 如果设置了起播位置,则调用seek
    if (startPositionUs > 0) {
        performSeek(startPositionUs, mode);
        if (mSource->getFormat(false /* audio */) == NULL) {
            return;
        }
    }
	// 2. 初始化状态
    mOffloadAudio = false;
    mAudioEOS = false;
    mVideoEOS = false;
    mStarted = true;
    mPaused = false;

    uint32_t flags = 0;

    if (mSource->isRealTime()) {
        flags |= Renderer::FLAG_REAL_TIME;
    }
	// 3. 检查audio video format
    bool hasAudio = (mSource->getFormat(true /* audio */) != NULL);
    bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
    if (!hasAudio && !hasVideo) {
        ALOGE("no metadata for either audio or video source");
        mSource->stop();
        mSourceStarted = false;
        notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, ERROR_MALFORMED);
        return;
    }
    ALOGV_IF(!hasAudio, "no metadata for audio source");  // video only stream

    sp<MetaData> audioMeta = mSource->getFormatMeta(true /* audio */);

    audio_stream_type_t streamType = AUDIO_STREAM_MUSIC;
    if (mAudioSink != NULL) {
        streamType = mAudioSink->getAudioStreamType();
    }
	// 4. 判断当前 audio format 是否支持 offload 模式,如果是DRM视频,则不允许 offload
    mOffloadAudio =
        canOffloadStream(audioMeta, hasVideo, mSource->isStreaming(), streamType)
                && (mPlaybackSettings.mSpeed == 1.f && mPlaybackSettings.mPitch == 1.f);

    // Modular DRM: Disabling audio offload if the source is protected
    if (mOffloadAudio && mIsDrmProtected) {
        mOffloadAudio = false;
    }

    if (mOffloadAudio) {
        flags |= Renderer::FLAG_OFFLOAD_AUDIO;
    }
	// 5. 创建Render,创建 RendererLooper 处理 Render的事件
    sp<AMessage> notify = new AMessage(kWhatRendererNotify, this);
    ++mRendererGeneration;
    notify->setInt32("generation", mRendererGeneration);
    mRenderer = new Renderer(mAudioSink, mMediaClock, notify, flags);
    mRendererLooper = new ALooper;
    mRendererLooper->setName("NuPlayerRenderer");
    mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
    mRendererLooper->registerHandler(mRenderer);
	// 6. 初始化 render 设置
    status_t err = mRenderer->setPlaybackSettings(mPlaybackSettings);
    if (err != OK) {
        mSource->stop();
        mSourceStarted = false;
        notifyListener(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
        return;
    }
    float rate = getFrameRate();
    if (rate > 0) {
        mRenderer->setVideoFrameRate(rate);
    }
	// 7. 如果当前有 video 和 audio decoder,将decoder 和 render绑定
    if (mVideoDecoder != NULL) {
        mVideoDecoder->setRenderer(mRenderer);
    }
    if (mAudioDecoder != NULL) {
        mAudioDecoder->setRenderer(mRenderer);
    }
    startPlaybackTimer("onstart");
	// 8. 调用 postScanSources
    postScanSources();
}

虽然 onStart 方法比较长,但是还是比较有条理的,启动了 Source,创建并启动 Render,创建并启动 Decoder:

  1. 启动 Source,对起播位置进行设定;
  2. 检查视频是否含有audio video source,如果都没有则该视频不能播放;
  3. 判断当前 audio format 是否支持 offload 模式,如果是DRM视频,则不允许 offload,audio 的工作方式将会影响 Render 的工作方式;
  4. 创建Render,创建 RendererLooper 处理 Render的事件,初始化 Render 设定;
  5. 调用 postScanSources 创建 Decoder;

接下来看 postScanSources 是如何创建 Decoder 的:

        case kWhatScanSources:
        {
            bool rescan = false;
			// 1. 创建 video
            if (mSurface != NULL) {
                if (instantiateDecoder(false, &mVideoDecoder) == -EWOULDBLOCK) {
                    rescan = true;
                }
            }
			// 2. 创建 audio
            // Don't try to re-open audio sink if there's an existing decoder.
            if (mAudioSink != NULL && mAudioDecoder == NULL) {
                if (instantiateDecoder(true, &mAudioDecoder) == -EWOULDBLOCK) {
                    rescan = true;
                }
            }
            // 3. 如果创建失败则重新扫描
            if (rescan) {
                msg->post(100000LL);
                mScanSourcesPending = true;
            }
            break;
        }
  1. 如果 Surface 不为 NULL,那么就会调用 instantiateDecoder 创建 video decoder;
  2. mAudioSink 不为 NULL,那么就会去创建 audio decoder;
  3. 如果有哪一个 decoder 创建失败,那么就会不断发送 kWhatScanSources 扫描 source,直到 video 和 audio decoder 都创建完成。

从这里我们大致可以猜到,播放过程中是可以先只播放 video 或者 audio,再中途追加播放另一个,只要 avsync 能够支援就行。

status_t NuPlayer::instantiateDecoder(
        bool audio, sp<DecoderBase> *decoder, bool checkAudioModeChange) {
    // 1. 检查 decoder 是否已经创建,如果已经创建则不重复创建
    if (*decoder != NULL || (audio && mFlushingAudio == SHUT_DOWN)) {
        return OK;
    }
	// 2. 获取 format,如果没有 format 则退出等待下次扫描
    sp<AMessage> format = mSource->getFormat(audio);
    if (format == NULL) {
        return UNKNOWN_ERROR;
    } else {
        status_t err;
        if (format->findInt32("err", &err) && err) {
            return err;
        }
    }

    format->setInt32("priority", 0 /* realtime */);

    if (mDataSourceType == DATA_SOURCE_TYPE_RTP) {
        ALOGV("instantiateDecoder: set decoder error free on stream corrupt.");
        format->setInt32("corrupt-free", true);
    }
	// 3. 创建 CCDecoder,初始化Video Decoder config format
    if (!audio) {
        AString mime;
        CHECK(format->findString("mime", &mime));

        sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, this);
        if (mCCDecoder == NULL) {
            mCCDecoder = new CCDecoder(ccNotify);
        }

        if (mSourceFlags & Source::FLAG_SECURE) {
            format->setInt32("secure", true);
        }

        if (mSourceFlags & Source::FLAG_PROTECTED) {
            format->setInt32("protected", true);
        }

        float rate = getFrameRate();
        if (rate > 0) {
            format->setFloat("operating-rate", rate * mPlaybackSettings.mSpeed);
        }
    }

    Mutex::Autolock autoLock(mDecoderLock);
    if (audio) {
        sp<AMessage> notify = new AMessage(kWhatAudioNotify, this);
        ++mAudioDecoderGeneration;
        notify->setInt32("generation", mAudioDecoderGeneration);

        if (checkAudioModeChange) {
            determineAudioModeChange(format);
        }
        // 4. 创建 audio decoder,如果是offload 模式则创建DecoderPassThrough,否则创建Decoder
        if (mOffloadAudio) {
            mSource->setOffloadAudio(true /* offload */);

            const bool hasVideo = (mSource->getFormat(false /*audio */) != NULL);
            format->setInt32("has-video", hasVideo);
            *decoder = new DecoderPassThrough(notify, mSource, mRenderer);
            ALOGV("instantiateDecoder audio DecoderPassThrough  hasVideo: %d", hasVideo);
        } else {
            mSource->setOffloadAudio(false /* offload */);

            *decoder = new Decoder(notify, mSource, mPID, mUID, mRenderer);
            ALOGV("instantiateDecoder audio Decoder");
        }
        mAudioDecoderError = false;
    } else {
        sp<AMessage> notify = new AMessage(kWhatVideoNotify, this);
        ++mVideoDecoderGeneration;
        notify->setInt32("generation", mVideoDecoderGeneration);
		// 5. 创建 video decoder
        *decoder = new Decoder(
                notify, mSource, mPID, mUID, mRenderer, mSurface, mCCDecoder);
        mVideoDecoderError = false;

        // enable FRC if high-quality AV sync is requested, even if not
        // directly queuing to display, as this will even improve textureview
        // playback.
        {
            if (property_get_bool("persist.sys.media.avsync", false)) {
                format->setInt32("auto-frc", 1);
            }
        }
    }
    // 6. 调用创建的decoder的init方法
    (*decoder)->init();

    // Modular DRM
    if (mIsDrmProtected) {
        format->setPointer("crypto", mCrypto.get());
        ALOGV("instantiateDecoder: mCrypto: %p (%d) isSecure: %d", mCrypto.get(),
                (mCrypto != NULL ? mCrypto->getStrongCount() : 0),
                (mSourceFlags & Source::FLAG_SECURE) != 0);
    }
	// 7. 调用创建的decoder的configure方法
    (*decoder)->configure(format);
    return OK;
}
  1. 检查 decoder 是否已经创建,如果已经创建则不重复创建;
  2. 获取 format,如果没有 format 则退出等待下次扫描;
  3. 如果是要创建video decoder,则创建 CCDecoder,初始化Video Decoder config format;
  4. 创建 audio decoder,如果是offload 模式则创建DecoderPassThrough,否则创建Decoder
  5. 创建 video decoder
  6. 调用创建的decoder的init方法
  7. 调用创建的decoder的configure方法

在创建 VideoDecoder 和 AudioDecoder 时,需要将 render 作为参数传递进去,这里已经将decoder 和 render 做了绑定。

NuPlayerDecoder 没有start接口,configure 调用中会自动完成 start调用,所以 instantiateDecoder 调用完成后 decoder 就已经启动完成了。

2.4、pause

pause 方法很简单,只要将 Source 和 Render 都 pause 就行,Decoder 无法从 Source 拿到数据,那么自然而然就暂停了。

void NuPlayer::onPause() {
    updatePlaybackTimer(true /* stopping */, "onPause");
    if (mPaused) {
        return;
    }
    mPaused = true;
    if (mSource != NULL) {
        mSource->pause();
    } else {
        ALOGW("pause called when source is gone or not set");
    }
    if (mRenderer != NULL) {
        mRenderer->pause();
    } else {
        ALOGW("pause called when renderer is gone or not set");
    }
}

这里再看 start 方法中的 onResume,恢复 Source 和 Renderer 的动作就行:

void NuPlayer::onResume() {
    if (!mPaused || mResetting) {
        ALOGD_IF(mResetting, "resetting, onResume discarded");
        return;
    }
    mPaused = false;
    if (mSource != NULL) {
        mSource->resume();
    } else {
        ALOGW("resume called when source is gone or not set");
    }
    // |mAudioDecoder| may have been released due to the pause timeout, so re-create it if
    // needed.
    if (audioDecoderStillNeeded() && mAudioDecoder == NULL) {
        instantiateDecoder(true /* audio */, &mAudioDecoder);
    }
    if (mRenderer != NULL) {
        mRenderer->resume();
    } else {
        ALOGW("resume called when renderer is gone or not set");
    }
}

2.5、resetAsync

void NuPlayer::resetAsync() {
    sp<Source> source;
    {
        Mutex::Autolock autoLock(mSourceLock);
        source = mSource;
    }

    if (source != NULL) {
        source->disconnect();
    }

    (new AMessage(kWhatReset, this))->post();
}

由于 Source 可能会出现阻塞的情况,所以 resetAsync 处理过程中需要先调用 Source.disconnect ,从达到加速reset的目的。

        case kWhatReset:
        {
            mResetting = true;
            // 1. flush
            mDeferredActions.push_back(
                    new FlushDecoderAction(
                        FLUSH_CMD_SHUTDOWN /* audio */,
                        FLUSH_CMD_SHUTDOWN /* video */));
            // 2. reset
            mDeferredActions.push_back(
                    new SimpleAction(&NuPlayer::performReset));
            processDeferredActions();
            break;
        }

reset 的过程分为两个步骤:

  1. flush:刷新 decoder render 中的数据,立即停止播放;
  2. reset:释放 decoder render source 的资源;

先来看下 processDeferredActions 方法,这里用到一种延迟处理的机制,一开始我不是很理解为什么这里要用这种机制,为什么不直接按顺序 post 一条消息呢?仔细阅读注释可以发现意思是这样:当不在即时状态时,我们将不会执行被延迟的方法。看起来还是有点难懂,但是它后面还举了例子,当 decoder 进入到了 flushing 和 shutting down 的状态时,这些被延迟的方法将不再被处理。

我的理解是这样,接下来需要执行的几个 Action 必须是要按照顺序执行的,但是目前处在 onMessageReceived 处理过程中,用 postAwaitResponse 等待返回肯定是不行的;如果按顺序 post 消息执行,由于 Action 执行的任务是异步的,并不能保证后面 Action 执行时前面的 Action 已经执行完成。所以这里用了 DeferredActions 机制,处理 Action 时先检查状态,如果状态不如预期则延迟执行,等待上一条 Action 执行完成后再调用 processDeferredActions 统一执行延迟的任务,从而保证了执行顺序。

void NuPlayer::processDeferredActions() {
    while (!mDeferredActions.empty()) {
        // We won't execute any deferred actions until we're no longer in
        // an intermediate state, i.e. one more more decoders are currently
        // flushing or shutting down.
        if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
            // We're currently flushing, postpone the reset until that's
            // completed.
            ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
                  mFlushingAudio, mFlushingVideo);
            break;
        }
        sp<Action> action = *mDeferredActions.begin();
        mDeferredActions.erase(mDeferredActions.begin());
        action->execute(this);
    }
}

接下来看 flush 流程,核心是调用的 decoder,并且将参数 needShutdown 置为 true

void NuPlayer::performDecoderFlush(FlushCommand audio, FlushCommand video) {
    ALOGV("performDecoderFlush audio=%d, video=%d", audio, video);

    if ((audio == FLUSH_CMD_NONE || mAudioDecoder == NULL)
            && (video == FLUSH_CMD_NONE || mVideoDecoder == NULL)) {
        return;
    }

    if (audio != FLUSH_CMD_NONE && mAudioDecoder != NULL) {
        flushDecoder(true /* audio */, (audio == FLUSH_CMD_SHUTDOWN));
    }

    if (video != FLUSH_CMD_NONE && mVideoDecoder != NULL) {
        flushDecoder(false /* audio */, (video == FLUSH_CMD_SHUTDOWN));
    }
}

flushDecoder 的核心是调用 Decoder 的 signalFlush 方法,并且将 mFlushingAudio 和 mFlushingVideo 置为 FLUSHING_DECODER_SHUTDOWN ,这将终止 decoder 的运行;如果是单纯的 flush 两个标志将被置为 FLUSHING_DECODER,decoder 将会继续运行。

void NuPlayer::flushDecoder(bool audio, bool needShutdown) {
    ALOGV("[%s] flushDecoder needShutdown=%d",
          audio ? "audio" : "video", needShutdown);

    const sp<DecoderBase> &decoder = getDecoder(audio);
    if (decoder == NULL) {
        ALOGI("flushDecoder %s without decoder present",
             audio ? "audio" : "video");
        return;
    }

    // Make sure we don't continue to scan sources until we finish flushing.
    ++mScanSourcesGeneration;
    if (mScanSourcesPending) {
        if (!needShutdown) {
            mDeferredActions.push_back(
                    new SimpleAction(&NuPlayer::performScanSources));
        }
        mScanSourcesPending = false;
    }

    decoder->signalFlush();

    FlushStatus newStatus =
        needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;

    mFlushComplete[audio][false /* isDecoder */] = (mRenderer == NULL);
    mFlushComplete[audio][true /* isDecoder */] = false;
    if (audio) {
        ALOGE_IF(mFlushingAudio != NONE,
                "audio flushDecoder() is called in state %d", mFlushingAudio);
        mFlushingAudio = newStatus;
    } else {
        ALOGE_IF(mFlushingVideo != NONE,
                "video flushDecoder() is called in state %d", mFlushingVideo);
        mFlushingVideo = newStatus;
    }
}

由于 mFlushingAudio 和 mFlushingVideo 不再是 FLUSH_CMD_NONE,所以 flushDecoder 执行完成后将暂时跳过 performReset 的执行。我们之前了解到 reset 是阻塞执行的,那这里是不是就卡死了呢?

当然不会,decoder 执行完 flush之后会 callback 回来。调用 flush 的过程中 render 也会被 flush,同样也会有个 callback回来,render callback的处理内容和decoder类似,这里暂时就不贴了。

else if (what == DecoderBase::kWhatFlushCompleted) {
                ALOGV("decoder %s flush completed", audio ? "audio" : "video");

                handleFlushComplete(audio, true /* isDecoder */);
                finishFlushIfPossible();
            }

mFlushComplete 分为两组:

isAudio isDecoder
audio decoder
audio render
video decoder
video render

handleFlushComplete 需要分别等到audio 和 video 的 decoder 和 render 的 flush callback 都上抛才会真正去执行,如果当前的 FlushStatus 是 FLUSHING_DECODER,那么flush过程就完成了;如果FlushStatus 是 FLUSHING_DECODER_SHUTDOWN,那么还会继续调用 decoder 的 initiateShutdown 方法去释放 decoder 中的资源,并将 status 重新置为 SHUTTING_DOWN_DECODER

void NuPlayer::handleFlushComplete(bool audio, bool isDecoder) {
    // We wait for both the decoder flush and the renderer flush to complete
    // before entering either the FLUSHED or the SHUTTING_DOWN_DECODER state.

    mFlushComplete[audio][isDecoder] = true;
    if (!mFlushComplete[audio][!isDecoder]) {
        return;
    }

    FlushStatus *state = audio ? &mFlushingAudio : &mFlushingVideo;
    switch (*state) {
        case FLUSHING_DECODER:
        {
            *state = FLUSHED;
            break;
        }

        case FLUSHING_DECODER_SHUTDOWN:
        {
            *state = SHUTTING_DOWN_DECODER;

            ALOGV("initiating %s decoder shutdown", audio ? "audio" : "video");
            getDecoder(audio)->initiateShutdown();
            break;
        }

        default:
            // decoder flush completes only occur in a flushing state.
            LOG_ALWAYS_FATAL_IF(isDecoder, "decoder flush in invalid state %d", *state);
            break;
    }
}

由于 status 为 SHUTTING_DOWN_DECODER,finishFlushIfPossible 将不会有什么动作,接下来会继续等待 decoder shutdown 完成上抛 callback。

else if (what == DecoderBase::kWhatShutdownCompleted) {
                ALOGV("%s shutdown completed", audio ? "audio" : "video");
                if (audio) {
                    Mutex::Autolock autoLock(mDecoderLock);
                    mAudioDecoder.clear();
                    mAudioDecoderError = false;
                    ++mAudioDecoderGeneration;

                    CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
                    mFlushingAudio = SHUT_DOWN;
                } else {
                    Mutex::Autolock autoLock(mDecoderLock);
                    mVideoDecoder.clear();
                    mVideoDecoderError = false;
                    ++mVideoDecoderGeneration;

                    CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
                    mFlushingVideo = SHUT_DOWN;
                }

                finishFlushIfPossible();
            } 

收到 kWhatShutdownCompleted 之后 NuPlayer 将会释放掉 decoder,然后执行 finishFlushIfPossible。

finishFlushIfPossible 会重置 mFlushingAudio 和 mFlushingVideo 的状态,然后执行剩下来的被推迟的方法,接下来要执行的是 performReset,进行 reset 函数的收尾。

void NuPlayer::performReset() {
    ALOGV("performReset");

    CHECK(mAudioDecoder == NULL);
    CHECK(mVideoDecoder == NULL);

    updatePlaybackTimer(true /* stopping */, "performReset");
    updateRebufferingTimer(true /* stopping */, true /* exiting */);

    cancelPollDuration();

    ++mScanSourcesGeneration;
    mScanSourcesPending = false;

    if (mRendererLooper != NULL) {
        if (mRenderer != NULL) {
            mRendererLooper->unregisterHandler(mRenderer->id());
        }
        mRendererLooper->stop();
        mRendererLooper.clear();
    }
    mRenderer.clear();
    ++mRendererGeneration;

    if (mSource != NULL) {
        mSource->stop();

        Mutex::Autolock autoLock(mSourceLock);
        mSource.clear();
    }

    if (mDriver != NULL) {
        sp<NuPlayerDriver> driver = mDriver.promote();
        if (driver != NULL) {
            driver->notifyResetComplete();
        }
    }

    mStarted = false;
    mPrepared = false;
    mResetting = false;
    mSourceStarted = false;

    // Modular DRM
    if (mCrypto != NULL) {
        // decoders will be flushed before this so their mCrypto would go away on their own
        // TODO change to ALOGV
        ALOGD("performReset mCrypto: %p (%d)", mCrypto.get(),
                (mCrypto != NULL ? mCrypto->getStrongCount() : 0));
        mCrypto.clear();
    }
    mIsDrmProtected = false;
}

reset 函数将会停止并销毁掉 renderLooper 和 render,停止并销毁掉 Source,最后 callback 通知 NuPlayerDriver reset 操作完成。

请添加图片描述

2.6、seekToAsync

如果调用 seekToAsync 时已经 prepare 完成但是还没起播,那么调用 seek 方法会帮助我们调用 start,解出内容后就暂停,从而达到预览的效果。

        case kWhatSeek:
        {
            int64_t seekTimeUs;
            int32_t mode;
            int32_t needNotify;
            CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
            CHECK(msg->findInt32("mode", &mode));
            CHECK(msg->findInt32("needNotify", &needNotify));

            if (!mStarted) {
                // Seek before the player is started. In order to preview video,
                // need to start the player and pause it. This branch is called
                // only once if needed. After the player is started, any seek
                // operation will go through normal path.
                // Audio-only cases are handled separately.
                onStart(seekTimeUs, (MediaPlayerSeekMode)mode);
                if (mStarted) {
                    onPause();
                    mPausedByClient = true;
                }
                if (needNotify) {
                    notifyDriverSeekComplete();
                }
                break;
            }

            mDeferredActions.push_back(
                    new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */,
                                           FLUSH_CMD_FLUSH /* video */));

            mDeferredActions.push_back(
                    new SeekAction(seekTimeUs, (MediaPlayerSeekMode)mode));

            // After a flush without shutdown, decoder is paused.
            // Don't resume it until source seek is done, otherwise it could
            // start pulling stale data too soon.
            mDeferredActions.push_back(
                    new ResumeDecoderAction(needNotify));

            processDeferredActions();
            break;
        }

处理 seek 总共分为3个 Action:FlushDecoderAction、SeekAction、ResumeDecoderAction。其中 FlushDecoderAction 我们在上一节中已经了解过了,不一样的是这里并不会走到 shutdown 的流程中。

SeekAction 核心是调用 Source 的 seekTo:

void NuPlayer::performSeek(int64_t seekTimeUs, MediaPlayerSeekMode mode) {
    ALOGV("performSeek seekTimeUs=%lld us (%.2f secs), mode=%d",
          (long long)seekTimeUs, seekTimeUs / 1E6, mode);

    if (mSource == NULL) {
        // This happens when reset occurs right before the loop mode
        // asynchronously seeks to the start of the stream.
        LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL,
                "mSource is NULL and decoders not NULL audio(%p) video(%p)",
                mAudioDecoder.get(), mVideoDecoder.get());
        return;
    }
    mPreviousSeekTimeUs = seekTimeUs;
    mSource->seekTo(seekTimeUs, mode);
    ++mTimedTextGeneration;

    // everything's flushed, continue playback.
}

seek 完成后会立刻调用 resume 恢复播放,如果这里不恢复就会出现黑屏的情况。resume 主要是用来操作 Decoder,调用 Decoder 的 signalResume,signalResume 执行完成后,decoder 重新开始接收数据,开始播放。

void NuPlayer::performResumeDecoders(bool needNotify) {
    if (needNotify) {
        mResumePending = true;
        if (mVideoDecoder == NULL) {
            // if audio-only, we can notify seek complete now,
            // as the resume operation will be relatively fast.
            finishResume();
        }
    }

    if (mVideoDecoder != NULL) {
        // When there is continuous seek, MediaPlayer will cache the seek
        // position, and send down new seek request when previous seek is
        // complete. Let's wait for at least one video output frame before
        // notifying seek complete, so that the video thumbnail gets updated
        // when seekbar is dragged.
        mVideoDecoder->signalResume(needNotify);
    }

    if (mAudioDecoder != NULL) {
        mAudioDecoder->signalResume(false /* needNotify */);
    }
}

void NuPlayer::finishResume() {
    if (mResumePending) {
        mResumePending = false;
        notifyDriverSeekComplete();
    }
}

关于 seekToAsync 的第三个参数 needNotify 还要提一下,这里这么设计是因为 seekToAsync 除了我们主动调用外,NuPlayerDriver 那边还有可能自动调用。我们主动调用,需要将执行完成的消息 Callback 到上层,另外stop之后再重新prepare也会调用seek,这里也需要 Callback;自动调用指的是播放结束再调用 start,这里会 seek 到0的位置,不需要 Callback通知上层。

还有一点自己的理解,之前我们大致了解 prepare 是一个异步处理的过程,这个过程中 reset 需要有一些特殊的处理,这里的 seek 也是异步的过程,那 seek 过程中 reset 或者 stop 需要有特殊处理吗?答案是不需要的,seek 会在 Looper 执行,reset 和 stop 的消息需要等待 seek 执行完成再处理,所以这是是顺序执行的,并没有真正的异步。


3、ALooper 与 Callback 设计

NuPlayer 共有1个 ALooper,但是这个 Looper 是给 Renderer使用的:

    mRenderer = new Renderer(mAudioSink, mMediaClock, notify, flags);
    mRendererLooper = new ALooper;
    mRendererLooper->setName("NuPlayerRenderer");
    mRendererLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
    mRendererLooper->registerHandler(mRenderer);

NuPlayer 自身使用的 ALooper 在 NuPlayerDriver 中创建:

	mLooper(new ALooper),
	mLooper->setName("NuPlayerDriver Looper");
	mLooper->start(false, true, PRIORITY_AUDIO);
	mLooper->registerHandler(mPlayer);

这里会有个问题,为什么它自己使用的 ALooper 不在 NuPlayer 中创建,而是要放在上层中创建呢?对比 Source 和 Decoder,他们使用的 ALooper 却放在自己的类中创建。

我认为放在哪一层创建都是可以的,但是要注意的是,如果 ALooper 在自己的构造函数中创建时,registerHandler(this) 不能在构造函数中调用!需要等构造函数调用完成后再注册到 ALooper 中。

以 NuPlayerDecoder 为例,他的 Looper 是在构造函数中创建,但是 registerHandler 放在 init 中,NuPlayer 创建了 Decoder 实例后需要额外调用 init 方法来注册。

NuPlayer::DecoderBase::DecoderBase(const sp<AMessage> &notify)
    :  mNotify(notify),
       mBufferGeneration(0),
       mPaused(false),
       mStats(new AMessage),
       mRequestInputBuffersPending(false) {
    // Every decoder has its own looper because MediaCodec operations
    // are blocking, but NuPlayer needs asynchronous operations.
    mDecoderLooper = new ALooper;
    mDecoderLooper->setName("NPDecoder");
    mDecoderLooper->start(false, false, ANDROID_PRIORITY_AUDIO);
}

void NuPlayer::DecoderBase::init() {
    mDecoderLooper->registerHandler(this);
}

回到 NuPlayer 中来,NuPlayerDriver Looper 除了处理 NuPlayer 异步消息外,还要处理 Source、Render、Decoder 发送上来的 Callback 消息,消息来源用 AMessage.what 区分,具体的消息用 what成员区分:

  • Source:kWhatSourceNotify
  • Render:kWhatRendererNotify
  • Decoder:kWhatVideoNotify、kWhatAudioNotify

4、总结

到这里 NuPlayer 的了解就告一段落,里面异步处理的思想 和 播放器的处理流程 还是要多多揣摩学习,回想起自己写的 Player 各种处理速度都不理想,还是太年轻了。

这里再整理关键方法需要执行的内容:

  • setDataSourceAsync:
    1. create Source
  • prepareAsync
    1. Source.prepareAsync
  • start
    1. create Render
    2. create Decoder,start Decoder and Render
  • pause
    1. pause Source
    2. pause Render
  • start (resume)
    1. resume Source
    2. resume Render
  • seekToAsync
    1. flush Decoder (pause) and Render
    2. seek Source
    3. resume Decoder and Render
  • resetAsync
    1. disconnect Source
    2. flush Decoder and Render
    3. shut down Decoder
    4. release Decoder
    5. stop and release Render
    6. stop and release Source

再对比下两个暂停的实现方式:
pause 通过暂停 Source 送数据,暂停 Render 渲染数据来完成,Decoder 不需要暂停;
flush 的暂停通过不给 Decoder 喂数据来实现,不需要暂停 Source。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 13 - Media框架(6)- NuPlayer 的相关文章

  • Android 主机意图过滤器通配符

    是否可以在 android host 属性上使用通配符 就像是 android host site com android pathPattern android pathPrefix m android scheme http gt Or
  • 在 Android 中创建和使用 9 补丁图像

    我最近听说了 9 补丁图像 我知道它是 9 平铺的并且是可拉伸的 我想了解更多 如何创建 9 块图像 有什么工具吗 我可以通过 AndroidSDK 或代码创建它吗 9 patch 相对于普通 png 的主要优点 它是否可以根据屏幕动态 自
  • 定期运行任务(每天一次/每周一次)

    我想定期 每周 每天一次 运行一些任务 即获取我的网站新闻页面 即使我的应用程序已关闭 是否可以 是的 您需要查看报警管理器 http developer android com reference android app AlarmMan
  • Android 上的 Firebase:如何检查 Firebase 身份验证失败原因?

    我在 Android 上使用 Firebase 和 Firebase Auth 功能 I try FirebaseAuth signInWithEmailAndPassword如果失败 我想知道为什么登录过程失败 The signInWit
  • 使用 Google Places Autocomplete API 的 REQUEST_DENIED 响应

    我正在开发 Android 应用程序 它使用谷歌的地点自动完成 API 当尝试点击以下网址时 我得到的答复如下 预测 状态 REQUEST DENIED 我从下面的链接获得了 API 密钥Google API 控制台 http code g
  • Android Studio - 错误:未捕获翻译错误:com.android.dx.cf.code.SimException:本地 0001:无效

    我刚刚使用 Android Studio 设置了一台新计算机 并从 bitbucket 导入了我的项目 问题是我现在在尝试构建项目时遇到此错误 信息 Gradle 任务 app clean app generateDebugSources
  • 如何将 EditText 传递给另一个活动?

    Intent intent new Intent this Name class intent putExtra key et getText toString startActivity intent Intent intent getI
  • 按钮未显示在屏幕上

    我创建了一个应用程序 其中显示带有图像和文本的列表视图 我在页面末尾添加按钮 但这没有显示在屏幕上 我是 Android 新手 我该如何解决这个问题 这是我的 UI XML 代码
  • AnalyticsService 未在应用程序清单中注册 - 错误

    我正在尝试使用 sdk 中提供的以下文档向 Android 应用程序实施谷歌分析服务 https developers google com analytics devguides collection android v4 https d
  • 如何从android获取应用程序安装时间

    我尝试了一些方法 但没有成功 请帮助我 PackageManager pm context getPackageManager ApplicationInfo appInfo pm getApplicationInfo app packag
  • Android GCM 服务器的 API 密钥

    我有点困惑我应该为 GCM 服务器使用哪个 API 密钥 在文档中它说使用 android api 密钥 这对我不起作用并且总是给出未经授权的 http developer android com google gcm gs html ht
  • 在 AppAuth-Android 中注销

    我有一个用JAVA开发的Android应用程序 对于这个应用程序 我使用的是身份服务器4 https github com IdentityServer IdentityServer4作为我的 STS 一切正常 但我找不到任何注销的实现Ap
  • 通过列表视图检查动态生成的复选框时遇到问题

    我知道其他成员已经提出了这个问题 一些成员也给出了解决方案 但问题是我没有找到任何适合我的应用程序的解决方案 我正在创建一个应用程序 其中我有一个屏幕 它将显示动态列表视图 其中包含列表项 复选框和三个文本视图 一个用于候选人姓名 另外两个
  • jar 中的 apklib 有什么优点?

    我正在关注这个问题 https stackoverflow com questions 6059502 whats the difference between apklib and jar files但它并没有完全回答我的问题 jar 中
  • android 中camera.setParameters 失败

    我已将相机功能包含在我的应用程序中 我还在市场上推出了该应用程序 我从一位用户那里收到一条错误消息 称他在打开相机时遇到错误 我已经在 2 1 的设备上测试了该应用程序 我从用户那里得到的错误是使用 Nexus One 它主要运行 2 2
  • 删除Android所有语言中的字符串

    我有一个包含多个翻译的应用程序 我想删除一些字符串 我怎样才能重构并删除它们一次 例如在默认情况下strings xml文件并自动将删除传播到其他翻译的其他 strings xml 文件 您可以通过 Android Studio 中的 翻译
  • 不显示 WRITE_EXTERNAL_STORAGE 的权限对话框

    I want to download a file using DownloadManager And DownloadManager wants to WRITE EXTERNAL STORAGE permission I have in
  • Android:打开和关闭SQLite数据库

    我正在开发Android应用程序 我经常在其中访问本地数据库 该数据库可以从不同的主题访问 因此我遇到了数据库的协调问题 我使用以下open and close method public void open mDb mDbHelper g
  • Android:确定 2.2 及更高版本上的摄像头数量

    我的应用程序需要在 Android 2 2 及更高版本上运行 我需要一种方法来确定可用摄像机的数量 有很多帖子解决了这个问题 但我找不到一个有效的 一种解决方案是简单地检测操作系统版本 任何 2 2 版本的设备都仅限于 1 个摄像头 即使该
  • 如何以编程方式创建活动转换?

    我想以编程方式创建一个动画 以从触摸屏点启动具有缩放效果的活动 接下来我模拟缩放输入效果

随机推荐

  • 华为IC岗笔试刷题含答案(2)

    目录 单选 多选 判断 单选 1 的目的都是关注单元模块的集成 功能组合 模块间的接口及时序 sub chip本身的设计功能和规格正确性 A 集成验证 IT B FPGA原型验证 C 系统验证ST D 单元验证UT 2 关于多bit信号的异
  • react学习之完善官网游戏教程

    react学习之完善官网游戏教程 1 在游戏历史记录列表显示每一步棋的坐标 格式为 列号 行号 2 在历史记录列表中加粗显示当前选择的项目 3 使用两个循环来渲染出棋盘的格子 而不是在代码里写死 hardcode 4 添加一个可以升序或降序
  • 203实验室启动conda

    启动conda 环境 由于我们没有conda init 以后每次启动都需要用这个命令 source miniconda3 bin activate
  • CentOS 编译错误+配置错误解决方法集合

    ERROR the HTTP XSLT module requires the libxml2 libxslt yum y install libxml2 libxml2 dev yum y install libxslt devel 1
  • 基于OpenCV的简易实时手势识别(含代码)

    基于OpenCV的简易实时手势识别 1 基本信息介绍 1 1实验步骤 1 2效果展示 2 肤色检测 二值化 开运算 高斯模糊 2 1 flip 函数原型 2 2cvtColor 函数原型 2 3split 函数原型 2 4GaussianB
  • C++ stack容器-50-栈容器基本概念和常用接口

    接着学习下一个容器 stack 栈容器 当然后面还要学习一个队列容器 两个有点相似一般一起对比和学习 本篇主要学习栈容器的基本概念和常用接口的基本使用 1 什么是stack stack是一种先进后出 First In Last Out FI
  • 开发中遇到不好解决的问题记录

    1 本地和测试和真实模拟数据 本地连接生产环境且登录相关用户token 都重现不了 后面管理员账号转交成功了 重现不了用户报的错
  • 【MAC终端UI自动化】pyautogui.click,图像识别定位不准排查

    原始代码 点不到图片位置 x y pyautogui locateCenterOnScreen image 1 png pyautogui click x y 排查一 没有鼠标点击的权限 打开系统偏好设置 gt 安全与隐私 gt 在 允许下
  • 国家医保服务平台js逆向(SM4+SM2)

    网站 aHR0cHM6Ly9mdXd1Lm5oc2EuZ292LmNuL25hdGlvbmFsSGFsbFN0LyMvc2VhcmNoL21lZGljYWwtc2VydmljZT9jb2RlPTkwMDAwJmZsYWc9ZmFsc2UmZ
  • 梯度下降算法介绍

    最优化 Optimization 在我们的日常生活中扮演着重要角色 最优化意味着找到问题的最优解 在机器学习中 通过训练集数据找到最优解 并在验证集上进行检测 许多机器学习算法都需要用到最优化 例如线性回归 linear regressio
  • Flutter中MethodChannel/EventChannel的原理

    前言 Flutter开发中或多或少都需要和原生端做一些交互 Flutter SDK中也为开发者提供了MethodChannel EventChannel实现了Flutter调用原生端以及原生端调用Flutter MethodChannel
  • 爬虫第一篇——Anaconda与jupyter安装配置与使用

    Anaconda与jupyter安装配置与使用 1 anaconda安装 进入官网下载 1 进去之后选择与自己电脑版本相匹配的版本下载 比如我的电脑是win10 64位 点击之后下载 下载完成后打开所在文件夹 右键 管理员身份运行 点击fi
  • Ice Skating CodeForces - 217A(并查集基本操作)

    题意 给出n个点的坐标 如果两个点x相同或者y相同 则两点可以联通 问你最少加几条线 能使全部点联通 AC代码 include
  • web前端顶岗实习总结报告_web前端年度工作总结范文

    web前端年度工作总结范文 导语 WEB前端是现在it行业是一件伤脑力和高报酬的工作 下面小编整理了web前端年度工作总结范文 欢迎参考借鉴 web前端年度工作总结 从入职到现在 我在导师的指导下走上了前端之路 在这段时间的学习和项目中使我
  • angularJS的文件的下载

    一 使用window location href url的方式 这种方式可以获取到要下载的文件 但是当下载的文件不存在 或者下载过程中后台报错的话会发生跳转 二 使用 http实现异步无刷新的下载文件 1 http method post
  • FRP进阶篇之安全认证

    目录 一 前言 二 通信加密 1 概述 2 使用 三 BasicAuth 鉴权 1 概述 2 使用 2 1 客户端配置 2 2 启动客户端 2 3 效果验证 四 TLS双向身份验证 1 概述 2 使用 2 1 生成证书 2 2 服务端配置
  • Google Mock启蒙篇matcher详细尽说明

    Google Mock启蒙篇 2 Google C Mocking Framework for Dummies 翻译 来自 Koala s blog 时间 2012 08 06 19 24 04 原文链接 http quweiprotoss
  • Linux---多线程、线程池

    多线程 线程概念 线程就是进程中的一条执行流 负责代码的执行调度 在linux下线程执行流是通过pcb实现的 一个进程中可以有多个pcb 这些pcb共享进程中的大部分资源 所以线程被称为一个轻量级进程 Notes 进程是系统进行资源分配的基
  • 点云渲染的颗粒感和背景色相关

    很奇怪 在加alpha通道时 当背景是黑色时 黑色点云特别显示颗粒感 而背景色是灰色偏白时 颗粒感消失 看来是审美观很重要啊
  • Android 13 - Media框架(6)- NuPlayer

    上一节我们通过 NuPlayerDriver 了解了 NuPlayer 的使用方式 这一节我们一起来学习 NuPlayer 的部分实现细节 ps 之前用 NuPlayer 播放本地视频很多都无法播放 所以觉得它不太行 这两天重新阅读发现它的