使用Android MediaCodec 硬解码延时问题分析-程序员宅基地

技术标签: codec  解码延时  流媒体  

使用Android MediaCodec 硬解码延时问题分析
2018年03月29日 09:30:38 珠雨妮儿 阅读数:2492
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuyunier/article/details/79730872
最近做项目用到Android native层的MediaCodec的接口对H264进行解码,通过在解码前和解码后加打印日志,发现解码耗时200多ms,和IOS的解码耗时10ms相比实在是延时好大。后来研究了两周也没能解决延时问题,很悲惨……不过还是将这过程中分析的思路记录下来,说不定以后万一灵感来了就解决了呢。

 起初在https://software.intel.com/en-us/forums/android-applications-on-intel-architecture/topic/536355和https://software.intel.com/en-us/android/articles/android-hardware-codec-mediacodec这两个网址中找到问题原因和一种解决方法。

  如果编码器类型是H.264,MediaCodec可能会有几帧的延迟(对于IA平台,它是7帧,而另一些则是3-5帧)。如果帧速率为30 FPS,则7帧将具有200毫秒的延迟。什么导致了硬件解码器的延迟?原因可能是主或高配置文件有一个B帧,并且如果当B帧引用后续缓冲区时解码器没有缓冲区,则该播放会短暂停止。英特尔已经考虑了硬件解码器的这种情况,并为主要或高配置文件提供了7个缓冲区,但是由于基线没有B帧,因此将其减少到基线的零缓冲区。其他供应商可能为所有配置文件使用4个缓冲区。
 因此,在基于IA的Android平台上,解决方案是将编码器更改为基线配置文件。如果编码器配置文件无法更改,则可行的解决方法是更改​​解码器端的配置数据。通常,配置文件位于第五个字节中,因此将基准配置文件更改为66会在IA平台上产生最低延迟。也就是说要想低延时,必须:

- 不要设置MediaFormat.KEY_MAX_WIDTH和MediaFormat.KEY_MAX_HEIGHT。

 - 将第一个SPS中的配置文件切换到基线,然后在第一个PPS后以正确的配置文件重新提交。

  先附上解码部分代码:

int OpenMetaCUDAVideoDecoderContext::OnVideoH264(uint8_t * frame, uint32_t frameSize){

DP_MSG("onVideoData=%6d, %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X\n",
       frameSize,
       frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],frame[6],frame[7]
);

int  pos = 0;
if( (frame[4] & 0X1F ) == 0X09 ){
    // this is an iframe
    frame     += 6;
    frameSize -= 6;
}

if( (frame[4] & 0X1F ) == 0X07 ){
    // this is an iframe
    iFrameFound = true;
}
else if(!iFrameFound){
    // iframe not found, do nothing
    return -1;
}

DP_MSG("video264::::%d",frameSize)

uint8_t *data = NULL;
uint8_t *pps = NULL;
uint8_t *sps = NULL;

// I know what my H.264 data source's NALUs look like so I know start code index is always 0.
// if you don't know where it starts, you can use a for loop similar to how i find the 2nd and 3rd start codes
int currentIndex = 0;
long blockLength = 0;

int nalu_type = (frame[currentIndex + 4] & 0x1F);
// if we havent already set up our format description with our SPS PPS parameters, we
// can't process any frames except type 7 that has our parameters
if (nalu_type != 7 && formatDesc == NULL)
{
    return -1;
}

if (nalu_type == 7)
{
    currentIndex = H264_findStartCode(frame,frameSize,currentIndex+4);
    size_t spsSize = currentIndex;

    // find what the second NALU type is
    nalu_type = (frame[currentIndex + 4] & 0x1F);

    DP_MSG("onVideoDataSPs=%6d, %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X\n",
           frameSize,
           frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],frame[6],frame[7]
    );

    // type 8 is the PPS parameter NALU
    if(nalu_type == 8){
        int nextIndex = H264_findStartCode(frame,frameSize,currentIndex+4);
        size_t ppsSize = nextIndex - currentIndex;

        DP_MSG("onVideoDataPPs=%6d, %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X\n",
               frameSize,
               frame[0],frame[1],frame[2],frame[3],frame[4],frame[5],frame[6],frame[7],
               frame[spsSize+1],frame[spsSize+2],frame[spsSize+3],frame[spsSize+4]
        );

        if(decompressionSession == NULL) {
            formatDesc = AMediaFormat_new();
            AMediaFormat_setString(formatDesc, "mime", "video/avc");
            AMediaFormat_setInt32(formatDesc, AMEDIAFORMAT_KEY_WIDTH, 1920); // 视频宽度
            AMediaFormat_setInt32(formatDesc, AMEDIAFORMAT_KEY_HEIGHT, 1088); // 视频高度

            sps = (uint8_t *)malloc(spsSize);
            pps = (uint8_t *)malloc(ppsSize);
            memcpy (sps, &frame[0], spsSize);
            memcpy (pps, &frame[spsSize], ppsSize);

            AMediaFormat_setBuffer(formatDesc, "csd-0", sps, spsSize); // sps
            AMediaFormat_setBuffer(formatDesc, "csd-1", pps, ppsSize); // pps

            DP_MSG("createDecompSession ========= ")
            this->createDecompSession();

            if(sps != NULL)
            {
                free(sps);
                sps = NULL;
            }
            if(pps != NULL)
            {
                free(pps);
                pps = NULL;
            }

        }

        // now lets handle the IDR frame that (should) come after the parameter sets
        // I say "should" because that's how I expect my H264 stream to work, YMMV
        currentIndex = nextIndex;
        nalu_type = (frame[currentIndex + 4] & 0x1F);

        while(currentIndex != -1 && nalu_type != 5 && nalu_type != 1){
            currentIndex = H264_findStartCode(frame,frameSize,currentIndex+4);
            nalu_type = (frame[currentIndex + 4] & 0x1F);
        }
    }
}

int32_t afout = 0;
   nalu_type = 5; // temp
// type 5 is an IDR frame NALU.  The SPS and PPS NALUs should always be followed by an IDR (or IFrame) NALU, as far as I know
if(nalu_type == 5)
{

    DP_MSG("jniPlayTs size=%d and %d \n",AMediaFormat_getInt32(formatDesc,AMEDIAFORMAT_KEY_COLOR_FORMAT,&afout),afout);
    //DP_MSG("theNativeWindow format %p and %d \n",theNativeWindow,ANativeWindow_getFormat(theNativeWindow));
    // find the offset, or where the SPS and PPS NALUs end and the IDR frame NALU begins
    int offset = currentIndex;//
    blockLength = frameSize - offset;

    data = &frame[offset];

    DP_MSG("nalu_type ===5 ")
    //DP_MSG("nalu_type ===5 %s /n ",AMediaFormat_toString(formatDesc))

    if(decompressionSession == nullptr)
    {
        DP_MSG("decompressionSession is null")
    }

    DP_MSG("OpenMetaCUDAVideoDecoder Start decoding: frameIdentifier=%lld",frameIdentifier);
    avx_info("OpenMetaCUDAVideoDecoder Start decoding: ","frameIdentifier=%lld",frameIdentifier);

    static int64_t  llPts = 0;

    ssize_t index = -1;
    index = AMediaCodec_dequeueInputBuffer(decompressionSession, 10000);
    if(index>=0)
    {
        size_t bufsize;
        auto buf = AMediaCodec_getInputBuffer(decompressionSession, index, &bufsize);
        if(buf!= nullptr )
        {
            DP_MSG("buf!= nullptr5======ww")
            memcpy(buf,data,blockLength);

            AMediaCodec_queueInputBuffer(decompressionSession, index, 0, blockLength, (uint64_t)frameIdentifier, 0);

            llPts += 3000;
        }

    }

    AMediaCodecBufferInfo info;
    auto status = AMediaCodec_dequeueOutputBuffer(decompressionSession, &info, 0);
    if (status >= 0) {
        if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) {
            DP_MSG("output EOS");
        }

        size_t outsize = 0;
        u_int8_t * outData = AMediaCodec_getOutputBuffer(decompressionSession,status,&outsize);
        auto formatType = AMediaCodec_getOutputFormat(decompressionSession);
        DP_MSG("format formatType to: %s", AMediaFormat_toString(formatType));
        int colorFormat = 0;
        int width = 0;
        int height = 0;
        AMediaFormat_getInt32(formatType,"color-format",&colorFormat);
        AMediaFormat_getInt32(formatType,"width",&width);
        AMediaFormat_getInt32(formatType,"height",&height);
        DP_MSG("format color-format : %d width :%d height :%d", colorFormat,width,height);

		AMediaFormat_delete(formatType);
        DP_MSG("OpenMetaCUDAVideoDecoder End   decoding: frameIdentifier=%lld,%d,%d,%p",info.presentationTimeUs,info.size,outsize,outData)
		if(this->kController){
            //OpenMetaPixelBuffer _kPixelBuffer(pixelBuffer,sizeof(pixelBuffer));
            OpenMetaPixelBuffer _kPixelBuffer(outData,sizeof(outData));
            _kPixelBuffer.kLine[0]  = outData;
            _kPixelBuffer.kLine[1]  = outData + width * height;
            _kPixelBuffer.kSizeX    = width;
            _kPixelBuffer.kSizeY    = height;
            _kPixelBuffer.kDataType = 1;
            _kPixelBuffer.kTimeStamp = info.presentationTimeUs;

            if(this!=NULL && this->kController!=NULL)
            {
                this->kController->OnVideoImage(&_kPixelBuffer);
            }

        }
        avx_info("OpenMetaCUDAVideoDecoder End   decoding:","%lld,%d,%d,%p",info.presentationTimeUs,info.size,outsize,outData);
        AMediaCodec_releaseOutputBuffer(decompressionSession, status, info.size != 0);

    } else if (status == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
        DP_MSG("output buffers changed");
    } else if (status == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
        auto format = AMediaCodec_getOutputFormat(decompressionSession);
        DP_MSG("format changed to: %s", AMediaFormat_toString(format));
        AMediaFormat_delete(format);
    } else if (status == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
        DP_MSG("no output buffer right now");
    } else {
        DP_MSG("unexpected info code: %zd", status);
    }
  
}

return 0;

}

  针对查到的解决办法,对以上代码进行了修改,分别是:

//将第一个sps的改为基线配置
sps = (uint8_t *)malloc(spsSize);
sps[0+5] = 66;
memcpy (sps, &frame[0], spsSize);

pps = (uint8_t *)malloc(ppsSize);
memcpy (pps, &frame[spsSize], ppsSize);

AMediaFormat_setBuffer(formatDesc, “csd-0”, sps, spsSize); // sps
AMediaFormat_setBuffer(formatDesc, “csd-1”, pps, ppsSize); // pps

//拷贝两份sps,将第一个sps的改为基线配置
sps = (uint8_t *)malloc(spsSize * 2);
memcpy (sps, &frame[0], spsSize);
sps[0+5] = 66;
memcpy (sps + spsSize, &frame[0], spsSize);

pps = (uint8_t *)malloc(ppsSize);
memcpy (pps, &frame[spsSize], ppsSize);

AMediaFormat_setBuffer(formatDesc, “csd-0”, sps, spsSize * 2); // sps
AMediaFormat_setBuffer(formatDesc, “csd-1”, pps, ppsSize); // pps
//拷贝两份sps,将第二份的第一个sps的改为基线配置
sps = (uint8_t *)malloc(spsSize * 2);
memcpy (sps, &frame[0], spsSize);
memcpy (sps + spsSize, &frame[0], spsSize);
sps[spsSize+5] = 66;

pps = (uint8_t *)malloc(ppsSize);
memcpy (pps, &frame[spsSize], ppsSize);

AMediaFormat_setBuffer(formatDesc, “csd-0”, sps, spsSize * 2); // sps
AMediaFormat_setBuffer(formatDesc, “csd-1”, pps, ppsSize); // pps
通过查看打印的开始解码与结束解码的时间发现,几种方法的时间差距并不是很大,依旧是200-250ms

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/eastbell/article/details/90672610

智能推荐

oracle 12c 集群安装后的检查_12c查看crs状态-程序员宅基地

文章浏览阅读1.6k次。安装配置gi、安装数据库软件、dbca建库见下:http://blog.csdn.net/kadwf123/article/details/784299611、检查集群节点及状态:[root@rac2 ~]# olsnodes -srac1 Activerac2 Activerac3 Activerac4 Active[root@rac2 ~]_12c查看crs状态

解决jupyter notebook无法找到虚拟环境的问题_jupyter没有pytorch环境-程序员宅基地

文章浏览阅读1.3w次,点赞45次,收藏99次。我个人用的是anaconda3的一个python集成环境,自带jupyter notebook,但在我打开jupyter notebook界面后,却找不到对应的虚拟环境,原来是jupyter notebook只是通用于下载anaconda时自带的环境,其他环境要想使用必须手动下载一些库:1.首先进入到自己创建的虚拟环境(pytorch是虚拟环境的名字)activate pytorch2.在该环境下下载这个库conda install ipykernelconda install nb__jupyter没有pytorch环境

国内安装scoop的保姆教程_scoop-cn-程序员宅基地

文章浏览阅读5.2k次,点赞19次,收藏28次。选择scoop纯属意外,也是无奈,因为电脑用户被锁了管理员权限,所有exe安装程序都无法安装,只可以用绿色软件,最后被我发现scoop,省去了到处下载XXX绿色版的烦恼,当然scoop里需要管理员权限的软件也跟我无缘了(譬如everything)。推荐添加dorado这个bucket镜像,里面很多中文软件,但是部分国外的软件下载地址在github,可能无法下载。以上两个是官方bucket的国内镜像,所有软件建议优先从这里下载。上面可以看到很多bucket以及软件数。如果官网登陆不了可以试一下以下方式。_scoop-cn

Element ui colorpicker在Vue中的使用_vue el-color-picker-程序员宅基地

文章浏览阅读4.5k次,点赞2次,收藏3次。首先要有一个color-picker组件 <el-color-picker v-model="headcolor"></el-color-picker>在data里面data() { return {headcolor: ’ #278add ’ //这里可以选择一个默认的颜色} }然后在你想要改变颜色的地方用v-bind绑定就好了,例如:这里的:sty..._vue el-color-picker

迅为iTOP-4412精英版之烧写内核移植后的镜像_exynos 4412 刷机-程序员宅基地

文章浏览阅读640次。基于芯片日益增长的问题,所以内核开发者们引入了新的方法,就是在内核中只保留函数,而数据则不包含,由用户(应用程序员)自己把数据按照规定的格式编写,并放在约定的地方,为了不占用过多的内存,还要求数据以根精简的方式编写。boot启动时,传参给内核,告诉内核设备树文件和kernel的位置,内核启动时根据地址去找到设备树文件,再利用专用的编译器去反编译dtb文件,将dtb还原成数据结构,以供驱动的函数去调用。firmware是三星的一个固件的设备信息,因为找不到固件,所以内核启动不成功。_exynos 4412 刷机

Linux系统配置jdk_linux配置jdk-程序员宅基地

文章浏览阅读2w次,点赞24次,收藏42次。Linux系统配置jdkLinux学习教程,Linux入门教程(超详细)_linux配置jdk

随便推点

matlab(4):特殊符号的输入_matlab微米怎么输入-程序员宅基地

文章浏览阅读3.3k次,点赞5次,收藏19次。xlabel('\delta');ylabel('AUC');具体符号的对照表参照下图:_matlab微米怎么输入

C语言程序设计-文件(打开与关闭、顺序、二进制读写)-程序员宅基地

文章浏览阅读119次。顺序读写指的是按照文件中数据的顺序进行读取或写入。对于文本文件,可以使用fgets、fputs、fscanf、fprintf等函数进行顺序读写。在C语言中,对文件的操作通常涉及文件的打开、读写以及关闭。文件的打开使用fopen函数,而关闭则使用fclose函数。在C语言中,可以使用fread和fwrite函数进行二进制读写。‍ Biaoge 于2024-03-09 23:51发布 阅读量:7 ️文章类型:【 C语言程序设计 】在C语言中,用于打开文件的函数是____,用于关闭文件的函数是____。

Touchdesigner自学笔记之三_touchdesigner怎么让一个模型跟着鼠标移动-程序员宅基地

文章浏览阅读3.4k次,点赞2次,收藏13次。跟随鼠标移动的粒子以grid(SOP)为partical(SOP)的资源模板,调整后连接【Geo组合+point spirit(MAT)】,在连接【feedback组合】适当调整。影响粒子动态的节点【metaball(SOP)+force(SOP)】添加mouse in(CHOP)鼠标位置到metaball的坐标,实现鼠标影响。..._touchdesigner怎么让一个模型跟着鼠标移动

【附源码】基于java的校园停车场管理系统的设计与实现61m0e9计算机毕设SSM_基于java技术的停车场管理系统实现与设计-程序员宅基地

文章浏览阅读178次。项目运行环境配置:Jdk1.8 + Tomcat7.0 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。项目技术:Springboot + mybatis + Maven +mysql5.7或8.0+html+css+js等等组成,B/S模式 + Maven管理等等。环境需要1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。_基于java技术的停车场管理系统实现与设计

Android系统播放器MediaPlayer源码分析_android多媒体播放源码分析 时序图-程序员宅基地

文章浏览阅读3.5k次。前言对于MediaPlayer播放器的源码分析内容相对来说比较多,会从Java-&amp;amp;gt;Jni-&amp;amp;gt;C/C++慢慢分析,后面会慢慢更新。另外,博客只作为自己学习记录的一种方式,对于其他的不过多的评论。MediaPlayerDemopublic class MainActivity extends AppCompatActivity implements SurfaceHolder.Cal..._android多媒体播放源码分析 时序图

java 数据结构与算法 ——快速排序法-程序员宅基地

文章浏览阅读2.4k次,点赞41次,收藏13次。java 数据结构与算法 ——快速排序法_快速排序法