Android MediaCodec 解码H264/H265码流视频_android h265 mediacodec-程序员宅基地

技术标签: Android音视频相关专栏  h.264  MediaCodec  android  H265  

音视频学习H264系列:H264简介

音视频学习H264系列:H264视频编码原理基础分析

音视频学习H264系列:H264视频编码原理进阶分析

音视频学习H264系列:MediaCodec H264/H265解码

音视频学习H264系列:终结篇实战

序言

本篇是有关音视频学习系列中的H264 / H265的解码视频部分,文章大部分记录直接上干货,编码原理基础部分【音视频学习H264系列:H264视频编码原理】后续再补上。欢迎留言讨论。

使用MediaCodec 解码H264/H265码流视频,那必须谈下MediaCodec这个神器。附官网数据流程图如下:

input:ByteBuffer输入方;

output:ByteBuffer输出方;

  • 使用者从MediaCodec请求一个空的输入buffer(ByteBuffer),填充满数据后将它传递给MediaCodec处理。
  • MediaCodec处理完这些数据并将处理结果输出至一个空的输出buffer(ByteBuffer)中。
  • 使用者从MediaCodec获取输出buffer的数据,消耗掉里面的数据,使用完输出buffer的数据之后,将其释放回编解码。

H264码流解码示例代码如下(基本都做了注释)

package com.zqfdev.h264decodedemo;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
import android.view.Surface;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * @author zhangqingfa
 * @createDate 2020/12/10 11:39
 * @description 解码H264播放
 */
public class H264DeCodePlay {

    private static final String TAG = "zqf-dev";
    //视频路径
    private String videoPath;
    //使用android MediaCodec解码
    private MediaCodec mediaCodec;
    private Surface surface;

    H264DeCodePlay(String videoPath, Surface surface) {
        this.videoPath = videoPath;
        this.surface = surface;
        initMediaCodec();
    }

    private void initMediaCodec() {
        try {
            Log.e(TAG, "videoPath " + videoPath);
            //创建解码器 H264的Type为  AAC
            mediaCodec = MediaCodec.createDecoderByType("video/avc");
            //创建配置
            MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/avc", 540, 960);
            //设置解码预期的帧速率【以帧/秒为单位的视频格式的帧速率的键】
            mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
            //配置绑定mediaFormat和surface
            mediaCodec.configure(mediaFormat, surface, null, 0);
        } catch (IOException e) {
            e.printStackTrace();
            //创建解码失败
            Log.e(TAG, "创建解码失败");
        }
    }

    /**
     * 解码播放
     */
    void decodePlay() {
        mediaCodec.start();
        new Thread(new MyRun()).start();
    }

    private class MyRun implements Runnable {

        @Override
        public void run() {
            try {
                //1、IO流方式读取h264文件【太大的视频分批加载】
                byte[] bytes = null;
                bytes = getBytes(videoPath);
                Log.e(TAG, "bytes size " + bytes.length);
                //2、拿到 mediaCodec 所有队列buffer[]
                ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
                //开始位置
                int startIndex = 0;
                //h264总字节数
                int totalSize = bytes.length;
                //3、解析
                while (true) {
                    //判断是否符合
                    if (totalSize == 0 || startIndex >= totalSize) {
                        break;
                    }
                    //寻找索引
                    int nextFrameStart = findByFrame(bytes, startIndex + 1, totalSize);
                    if (nextFrameStart == -1) break;
                    MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                    // 查询10000毫秒后,如果dSP芯片的buffer全部被占用,返回-1;存在则大于0
                    int inIndex = mediaCodec.dequeueInputBuffer(10000);
                    if (inIndex >= 0) {
                        //根据返回的index拿到可以用的buffer
                        ByteBuffer byteBuffer = inputBuffers[inIndex];
                        //清空缓存
                        byteBuffer.clear();
                        //开始为buffer填充数据
                        byteBuffer.put(bytes, startIndex, nextFrameStart - startIndex);
                        //填充数据后通知mediacodec查询inIndex索引的这个buffer,
                        mediaCodec.queueInputBuffer(inIndex, 0, nextFrameStart - startIndex, 0, 0);
                        //为下一帧做准备,下一帧首就是前一帧的尾。
                        startIndex = nextFrameStart;
                    } else {
                        //等待查询空的buffer
                        continue;
                    }
                    //mediaCodec 查询 "mediaCodec的输出方队列"得到索引
                    int outIndex = mediaCodec.dequeueOutputBuffer(info, 10000);
                    Log.e(TAG, "outIndex " + outIndex);
                    if (outIndex >= 0) {
                        try {
                            //暂时以休眠线程方式放慢播放速度
                            Thread.sleep(33);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //如果surface绑定了,则直接输入到surface渲染并释放
                        mediaCodec.releaseOutputBuffer(outIndex, true);
                    } else {
                        Log.e(TAG, "没有解码成功");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //读取一帧数据
    private int findByFrame(byte[] bytes, int start, int totalSize) {
        for (int i = start; i < totalSize - 4; i++) {
            //对output.h264文件分析 可通过分隔符 0x00000001 读取真正的数据
            if (bytes[i] == 0x00 && bytes[i + 1] == 0x00 && bytes[i + 2] == 0x00 && bytes[i + 3] == 0x01) {
                return i;
            }
        }
        return -1;
    }

    private byte[] getBytes(String videoPath) throws IOException {
        InputStream is = new DataInputStream(new FileInputStream(new File(videoPath)));
        int len;
        int size = 1024;
        byte[] buf;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        buf = new byte[size];
        while ((len = is.read(buf, 0, size)) != -1)
            bos.write(buf, 0, len);
        buf = bos.toByteArray();
        return buf;
    }
}

H265示例代码如下

package com.zqfdev.h264decodedemo;

import android.media.MediaCodec;
import android.media.MediaFormat;
import android.util.Log;
import android.view.Surface;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

/**
 * @author zhangqingfa
 * @createDate 2020/12/10 11:39
 * @description 解码H264播放
 */
public class H265DeCodePlay {

    private static final String TAG = "zqf-dev";
    //视频路径
    private String videoPath;
    //使用android MediaCodec解码
    private MediaCodec mediaCodec;
    private Surface surface;

    H265DeCodePlay(String videoPath, Surface surface) {
        this.videoPath = videoPath;
        this.surface = surface;
        initMediaCodec();
    }

    private void initMediaCodec() {
        try {
            Log.e(TAG, "videoPath " + videoPath);
            //创建解码器 H264的Type为  AAC
            mediaCodec = MediaCodec.createDecoderByType("video/hevc");
            //创建配置
            MediaFormat mediaFormat = MediaFormat.createVideoFormat("video/hevc", 368, 384);
            //设置解码预期的帧速率【以帧/秒为单位的视频格式的帧速率的键】
            mediaFormat.setInteger(MediaFormat.KEY_FRAME_RATE, 15);
            //配置绑定mediaFormat和surface
            mediaCodec.configure(mediaFormat, surface, null, 0);
        } catch (IOException e) {
            e.printStackTrace();
            //创建解码失败
            Log.e(TAG, "创建解码失败");
        }
    }

    /**
     * 解码播放
     */
    void decodePlay() {
        mediaCodec.start();
        new Thread(new MyRun()).start();
    }

    private class MyRun implements Runnable {

        @Override
        public void run() {
            try {
                //1、IO流方式读取h264文件【太大的视频分批加载】
                byte[] bytes = null;
                bytes = getBytes(videoPath);
                Log.e(TAG, "bytes size " + bytes.length);
                //2、拿到 mediaCodec 所有队列buffer[]
                ByteBuffer[] inputBuffers = mediaCodec.getInputBuffers();
                //开始位置
                int startIndex = 0;
                //h264总字节数
                int totalSize = bytes.length;
                //3、解析
                while (true) {
                    //判断是否符合
                    if (totalSize == 0 || startIndex >= totalSize) {
                        break;
                    }
                    //寻找索引
                    int nextFrameStart = findByFrame(bytes, startIndex + 1, totalSize);
                    if (nextFrameStart == -1) break;
                    Log.e(TAG, "nextFrameStart " + nextFrameStart);
                    MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
                    // 查询10000毫秒后,如果dSP芯片的buffer全部被占用,返回-1;存在则大于0
                    int inIndex = mediaCodec.dequeueInputBuffer(10000);
                    if (inIndex >= 0) {
                        //根据返回的index拿到可以用的buffer
                        ByteBuffer byteBuffer = inputBuffers[inIndex];
                        //清空byteBuffer缓存
                        byteBuffer.clear();
                        //开始为buffer填充数据
                        byteBuffer.put(bytes, startIndex, nextFrameStart - startIndex);
                        //填充数据后通知mediacodec查询inIndex索引的这个buffer,
                        mediaCodec.queueInputBuffer(inIndex, 0, nextFrameStart - startIndex, 0, 0);
                        //为下一帧做准备,下一帧首就是前一帧的尾。
                        startIndex = nextFrameStart;
                    } else {
                        //等待查询空的buffer
                        continue;
                    }
                    //mediaCodec 查询 "mediaCodec的输出方队列"得到索引
                    int outIndex = mediaCodec.dequeueOutputBuffer(info, 10000);
                    Log.e(TAG, "outIndex " + outIndex);
                    if (outIndex >= 0) {
                        try {
                            //暂时以休眠线程方式放慢播放速度
                            Thread.sleep(33);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //如果surface绑定了,则直接输入到surface渲染并释放
                        mediaCodec.releaseOutputBuffer(outIndex, true);
                    } else {
                        Log.e(TAG, "没有解码成功");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //读取一帧数据
    private int findByFrame(byte[] bytes, int start, int totalSize) {
        for (int i = start; i < totalSize - 4; i++) {
            //对output.h264文件分析 可通过分隔符 0x00000001 读取真正的数据
            if (bytes[i] == 0x00 && bytes[i + 1] == 0x00 && bytes[i + 2] == 0x00 && bytes[i + 3] == 0x01) {
                return i;
            }
        }
        return -1;
    }

    private byte[] getBytes(String videoPath) throws IOException {
        InputStream is = new DataInputStream(new FileInputStream(new File(videoPath)));
        int len;
        int size = 1024;
        byte[] buf;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        buf = new byte[size];
        while ((len = is.read(buf, 0, size)) != -1)
            bos.write(buf, 0, len);
        buf = bos.toByteArray();
        return buf;
    }
}

MainActivity代码如下

package com.zqfdev.h264decodedemo;

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.File;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class MainActivity extends AppCompatActivity {
    private String[] permiss = {"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE"};
    private H264DeCodePlay h264DeCodePlay;
//    private H265DeCodePlay h265DeCodePlay;
    private String videoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermiss();
        initView();
    }

    private void checkPermiss() {
        int code = ActivityCompat.checkSelfPermission(this, permiss[0]);
        if (code != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限,去申请写的权限
            ActivityCompat.requestPermissions(this, permiss, 11);
        }
    }

    private void initView() {
        File dir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
        if (!dir.exists()) dir.mkdirs();
        final File file = new File(dir, "output.h264");
//        final File file = new File(dir, "output.h265");
        if (!file.exists()) {
            Log.e("Tag", "文件不存在");
            return;
        }
        videoPath = file.getAbsolutePath();
        final SurfaceView surface = findViewById(R.id.surface);
        final SurfaceHolder holder = surface.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                h264DeCodePlay = new H264DeCodePlay(videoPath, holder.getSurface());
                h264DeCodePlay.decodePlay();
//                h265DeCodePlay = new H265DeCodePlay(videoPath, holder.getSurface());
//                h265DeCodePlay.decodePlay();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {

            }
        });
    }
}

测试的H264 / H265码流视频通过FFmpeg抽取可得到。

命令行:

ffmpeg -i 源视频.mp4 -codec copy -bsf: h264_mp4toannexb -f h264 输出视频.h264

附上测试视频下载地址:

H264资源:output.h264-Android文档类资源-CSDN下载

H265资源:https://download.csdn.net/download/Ae_fring/13624500

效果如下:

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

智能推荐

前端系列——vue2+高德地图web端开发(poi搜索两种方式)_前端开发的时候地图搜索一般用什么-程序员宅基地

文章浏览阅读5.8k次,点赞12次,收藏34次。前端系列——vue2+高德地图web端开发(poi搜索)前言基础什么是poi搜索1. 输入提示结合poi搜索官方代码步骤1.进行plugins插件注册2.data中编写placeSearch变量3.在methods中编写select函数4.在initMap函数中增加poi搜索处理逻辑解释2.直接进行poi搜索步骤1.在Search.vue中我们把接收到的值传到MapContainer.vue中2.在MapContainer.vue中接收3.编写watch进行监听完整代码(MapContainer.vue)结_前端开发的时候地图搜索一般用什么

微信退款操作_微信退款签名生成-程序员宅基地

文章浏览阅读600次。请求XML示例<xml> <appid>wx2421b1c4370ec43b</appid> <mch_id>10000100</mch_id> <nonce_str>6cefdb308e1e2e8aabd48cf79e546a02</nonce_str> <out_refund_no>1415701182</out_refund_no> <out_trad_微信退款签名生成

JS(javascript) delete 详解_js delete-程序员宅基地

文章浏览阅读7.6k次。js delete javascript_js delete

链路追踪 SkyWalking 源码分析 —— Collector Storage 存储组件-程序员宅基地

文章浏览阅读857次。点击上方“芋道源码”,选择“设为星标”做积极的人,而不是积极废人!源码精品专栏中文详细注释的开源项目RPC 框架 Dubbo 源码解析网络应用框架 Netty 源码解析..._writerequest.refreshpolicy.immediate save

Error creating bean with name ‘dataSource‘ defined in class path resource [applicationContext.xml]_error creating bean with name 'datasource' defined-程序员宅基地

文章浏览阅读5.1k次。分析:异常信息提示错误出在C3P0连接池,检查applicationContext.xml后发现并没有什么错误,于是我们可以锁定问题出在 jar 库依赖,问题的出现可能就是 jar 库冲突,选择性地删掉一个就OK了。严重: 在路径为[/SSH02-SpringWebPojo]的上下文中,servlet[servlets.RegisterServlet]的Servlet.service()引发异常org.springframework.beans.factory.BeanCreationException_error creating bean with name 'datasource' defined in class path resource [c

kafka参数auto.offset.reset与消失丢失_kafka auto.offset.reset 找不到配置-程序员宅基地

文章浏览阅读218次。kafka一种极端的的消息丢失。_kafka auto.offset.reset 找不到配置

随便推点

Windows批处理脚本:ffmpeg转换b站m4n视频_ffmpeg批处理脚本-程序员宅基地

文章浏览阅读437次。(3)将下载到的M4S文件拖到.bat文件上即可作为参数执行,转为MP3需要一个音频文件,转为MP4需要音频文件和视频文件两个一起拖到.bat上。(1)上面的代码两段set是用于修改下载到的文件的后缀名,从m4s改为MP3或者MP4。的是延迟变量,~n是取出文件的文件名,~x是取出文件的扩展名。(2)修改文件后缀名,将.txt改为.bat。(1)创建文本文件,并将需要代码复制进去。_ffmpeg批处理脚本

搜集的游戏引擎-程序员宅基地

文章浏览阅读130次。从Gist上发现的,挺全的IMPORTANT! Remember to check out the wiki page at https://github.com/bebraw/jswiki/wiki/Game-Engines for the most up to date version. There's also a "notes" column in the table but it s...

网易2018校园招聘编程题真题集合(一)_小易准备去魔法王国采购魔法神器购买魔法神器需要使用魔法币但是小易现在一枚魔-程序员宅基地

文章浏览阅读255次。1、答案及运行结果:递归(逆推):直接或者间接地调用自身递归算法解决问题的特点:(1) 递归就是在过程或函数里调用自身。(2) 在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。(3) 递归算法解题通常显得很简洁,但递归算法解题的运行效率较低。所以一般不提倡用递归算法设计程序。(4) 在递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储。递归次数过多容易造成栈溢出等。所以一..._小易准备去魔法王国采购魔法神器购买魔法神器需要使用魔法币但是小易现在一枚魔

hashcode详解-程序员宅基地

文章浏览阅读2k次。HashCode是在Java中用于获取对象的唯一标识符的方法。它是根据对象的内容生成的一个整数值。对象的hashCode()方法被调用时,它返回的是对象的哈希码。哈希码可以用于在哈希表等数据结构中快速定位对象。在Java中,hashCode()方法是被Object类定义的,所有的对象都可以调用该方法。默认情况下,hashCode()方法返回的是对象的内存地址的哈希码表示。通常情况下,如果两个对象的equals()方法返回true,那么它们的hashCode()方法应该返回相同的值。_hashcode

java计算机毕业设计(附源码)英语单词学习软件app(ssm+mysql+maven+LW文档)-程序员宅基地

文章浏览阅读231次,点赞5次,收藏6次。其次,通过智能化的学习算法,软件能够根据用户的学习进度和记忆能力,提供定制化的学习计划和复习提醒,从而确保学习效果的最大化。此外,软件中的互动元素和游戏化设计,增加了学习的趣味性,激发了用户的学习动力。最后,随着用户词汇量的增加,他们将更加自信地运用英语进行沟通和表达,这不仅有助于个人职业发展,也促进了跨文化交流,增进了不同文化之间的理解和尊重。因此,英语单词学习软件APP的开发和应用,不仅是技术进步的体现,更是推动语言学习和文化交流的重要力量。随着科技的发展和移动设备的普及,学习英语的方式也在不断进化。

_004_jspAndServlet_Servlet3.0的异步_hasoriginalrequestandresponse-程序员宅基地

文章浏览阅读127次。来自https://www.cnblogs.com/zr520/p/6103410.html,感谢作者的无私分享。servlet之前的操作同时同步的,就是按照这样的一个流程来走的:1.请求根据一个路径路由到一个servlet中,2.servlet获取一系列的参数3.执行一系列的逻辑(花费时间所占的比重也更大)4.返回结果上面的问题出现在这一系列的操作都是同步的,所以这个请求必定是堵塞到所以任务都完..._hasoriginalrequestandresponse

推荐文章

热门文章

相关标签