代码改变世界

Android: MediaCodec视频文件硬件解码,高效率得到YUV格式帧,快速保存JPEG图片(不使用OpenGL)

2017-06-17 17:42  指针空间  阅读(6271)  评论(0编辑  收藏  举报

以下文章转载自:

https://www.polarxiong.com/archives/Android-MediaCodec%E8%A7%86%E9%A2%91%E6%96%87%E4%BB%B6%E7%A1%AC%E4%BB%B6%E8%A7%A3%E7%A0%81-%E9%AB%98%E6%95%88%E7%8E%87%E5%BE%97%E5%88%B0YUV%E6%A0%BC%E5%BC%8F%E5%B8%A7-%E5%BF%AB%E9%80%9F%E4%BF%9D%E5%AD%98JPEG%E5%9B%BE%E7%89%87-%E4%B8%8D%E4%BD%BF%E7%94%A8OpenGL.html

 

Android: hardware decode video file through MediaCodec, get YUV format video frames directly (without OpenGL), efficiently save frames as YUV/JEPG format to file.

特点

以H.264编码分辨率1920x1080视频文件为例

  • 需要Android API 21
  • 直接将视频解码为YUV格式帧,不经过OpenGL,不转换为RGB
  • 对绝大多数设备和绝大多数视频编码格式,都可以解码得到NV21或I420格式帧数据
  • 30ms内获得NV21或I420格式帧数据
  • 10ms内将NV21或I420格式帧数据写入到文件
  • 对得到的NV21格式帧数据,在110ms内完成JPEG格式的转换和写入到文件

背景

因为实验需要在Android上高效率解码视频文件,并获得YUV格式帧数据,遂搜索寻找解决方法。最初找到bigflake的Android MediaCodec stuff,硬件解码视频不可多得的示例代码,其中提供了结合MediaCodec和OpenGL硬件解码视频并得到RGB格式帧数据,以及写入bitmap图片到文件的方法,测试发现效果不错,但我想要的是得到YUV格式的帧数据;在继续寻找RGB转YUV的方法时,苦于没有找到高效实现这个转换的方法,遂作罢。

后来发现MediaCodec解码得到的原始帧数据应当就是YUV格式,然后看到stackoverflow上的讨论Why doesn't the decoder of MediaCodec output a unified YUV format(like YUV420P)?,发现有人和我有一样的需要,但他已经发现了不同设备MediaCodec解码得到的YUV格式不相同这个问题,且由于各种格式繁杂,很难写出高效的格式转换方法。然后又发现了来自加州理工学院的一篇文章Android MediaCodec Formats,别人统计了市面上Android设备MediaCodec解码得到的不同YUV格式所占的比例,表格中显示出格式之繁多,且以COLOR_QCOM_FormatYUV420SemiPlanar32m,OMX_QCOM_COLOR_FormatYUV420PackedSemiPlanar64x32Tile2m8ka和COLOR_FormatYUV420SemiPlanar占据绝大多数。考虑放弃MediaCodec直接得到统一格式的YUV格式帧数据。

再后来不死心继续找,偶然找到了一份Android CTS测试ImageImageReader类的代码,发现了由MediaCodec解码直接得到指定YUV格式(如NV21,I420)视频帧的方法,遂有了此文。

概述

简单来说,整个过程是,MediaCodec将编码后的视频文件解码得到YUV420类的视频帧,然后将视频帧格式转换为NV21或I420格式,由用户进行后续处理;若需要写入.yuv文件,直接将转换后的数据写入即可。若需要保存为JPEG格式图片,将NV21格式帧数据转换为JPEG格式并写入。

详细来说,CTS测试中透露出可以指定硬件解码得到帧编码格式,虽然不同设备支持的编码格式都不尽相同,但得益于API 21加入的COLOR_FormatYUV420Flexible格式,MediaCodec的所有硬件解码都支持这种格式。但这样解码后得到的YUV420的具体格式又会因设备而异,如YUV420Planar,YUV420SemiPlanar,YUV420PackedSemiPlanar等。然而又得益于API 21对MediaCodec加入的Image类的支持,可以实现简单且高效的任意YUV420格式向如NV21,I420等格式的转换,这样就得到了一个统一的、可以预先指定的YUV格式视频帧。再进一步,YuvImage类提供了一种高效的NV21格式转换为JPEG格式并写入文件的方法,可以实现将解码得到的视频帧保存为JPEG格式图片的功能,且整个过程相比bigflake中提供的YUV经OpenGL转换为RGB格式,然后通过Bitmap类保存为图片,效率高很多。

MediaCodec指定帧格式

实际上,MediaCodec不仅在编码,而且在解码是也能够指定帧格式。能够指定的原因是,解码得到的帧的格式,并不是由如H.264编码的视频文件提前确定的,而是由解码器确定的,解码器支持哪些帧格式,就可以解码出哪些格式的帧。

获取支持的格式

MediaCodec虽然可以指定帧格式,但也不是能指定为任意格式,是需要硬件支持的。首先看看对于特定视频编码格式的MediaCodec解码器,支持哪些帧格式。

Java
private static int selectTrack(MediaExtractor extractor) {
    int numTracks = extractor.getTrackCount();
    for (int i = 0; i < numTracks; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        if (mime.startsWith("video/")) {
            if (VERBOSE) {
                Log.d(TAG, "Extractor selected track " + i + " (" + mime + "): " + format);
            }
            return i;
        }
    }
    return -1;
}

private void showSupportedColorFormat(MediaCodecInfo.CodecCapabilities caps) {
    System.out.print("supported color format: ");
    for (int c : caps.colorFormats) {
        System.out.print(c + "\t");
    }
    System.out.println();
}

MediaExtractor extractor = null;
MediaCodec decoder = null;
File videoFile = new File(videoFilePath);
extractor = new MediaExtractor();
extractor.setDataSource(videoFile.toString());
int trackIndex = selectTrack(extractor);
if (trackIndex < 0) {
    throw new RuntimeException("No video track found in " + videoFilePath);
}
extractor.selectTrack(trackIndex);
MediaFormat mediaFormat = extractor.getTrackFormat(trackIndex);
String mime = mediaFormat.getString(MediaFormat.KEY_MIME);
decoder = MediaCodec.createDecoderByType(mime);
showSupportedColorFormat(decoder.getCodecInfo().getCapabilitiesForType(mime));

MediaExtractor负责读取视频文件,获得视频文件信息,以及提供 视频编码后的帧数据(如H.264)selectTrack()获取视频所在的轨道号,getTrackFormat()获得视频的编码信息。再以此编码信息通过createDecoderByType()获得一个解码器,然后通过showSupportedColorFormat()就可以得到这个解码器支持的帧格式了。

比如对于我的设备,对于支持video/avc的解码器,支持的帧格式是

supported color format: 2135033992  21  47  25  27  35  40  52  2130706433  2130706434  20

这里的数字对应MediaCodecInfo.CodecCapabilities定义的帧格式,如2135033992对应COLOR_FormatYUV420Flexible,21对应COLOR_FormatYUV420SemiPlanar,25对应COLOR_FormatYCbYCr,27对应COLOR_FormatCbYCrY,35对应COLOR_FormatL8,40对应COLOR_FormatYUV422PackedSemiPlanar,20对应COLOR_FormatYUV420PackedPlanar。

COLOR_FormatYUV420Flexible

这里简单谈谈COLOR_FormatYUV420Flexible,YUV420Flexible并不是一种确定的YUV420格式,而是包含COLOR_FormatYUV411Planar, COLOR_FormatYUV411PackedPlanar, COLOR_FormatYUV420Planar, COLOR_FormatYUV420PackedPlanar, COLOR_FormatYUV420SemiPlanar和COLOR_FormatYUV420PackedSemiPlanar。在API 21引入YUV420Flexible的同时,它所包含的这些格式都deprecated掉了。

那么为什么所有的解码器都支持YUV420Flexible呢?官方没有说明这点,但我猜测,只要解码器支持YUV420Flexible中的任意一种格式,就会被认为支持YUV420Flexible格式。也就是说,几乎所有的解码器都支持YUV420Flexible代表的格式中的一种或几种。

指定帧格式

平常初始化MediaCodec并启动解码器是用如下代码

Java
decoder.configure(mediaFormat, null, null, 0);
decoder.start();

其中mediaFormat是之前得到的视频编码信息,这样向解码器确定了各种参数后,就能正常解码了。

而指定帧格式是在上述代码前增加

Java
mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT,
    MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible);

仅此一行,用来指定解码后的帧格式,换句话说,解码器将编码的帧解码为这种指定的格式。前面说到YUV420Flexible是几乎所有解码器都支持的,所以可以直接写死。

这个指定方法就是我在CTS中发现的,因为官方文档对KEY_COLOR_FORMAT的描述是set by the user for encoders, readable in the output format of decoders,也就是说只用在编码器中,而不是我们现在用的解码器中!

转换格式和写入文件

主体框架

先贴主体部分的代码

Java
final int width = mediaFormat.getInteger(MediaFormat.KEY_WIDTH);
final int height = mediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
int outputFrameCount = 0;
while (!sawOutputEOS) {
    if (!sawInputEOS) {
        int inputBufferId = decoder.dequeueInputBuffer(DEFAULT_TIMEOUT_US);
        if (inputBufferId >= 0) {
            ByteBuffer inputBuffer = decoder.getInputBuffer(inputBufferId);
            int sampleSize = extractor.readSampleData(inputBuffer, 0);
            if (sampleSize < 0) {
                decoder.queueInputBuffer(inputBufferId, 0, 0, 0L, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                sawInputEOS = true;
            } else {
                long presentationTimeUs = extractor.getSampleTime();
                decoder.queueInputBuffer(inputBufferId, 0, sampleSize, presentationTimeUs, 0);
                extractor.advance();
            }
        }
    }
    int outputBufferId = decoder.dequeueOutputBuffer(info, DEFAULT_TIMEOUT_US);
    if (outputBufferId >= 0) {
        if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
            sawOutputEOS = true;
        }
        boolean doRender = (info.size != 0);
        if (doRender) {
            outputFrameCount++;
            Image image = decoder.getOutputImage(outputBufferId);
            if (outputImageFileType != -1) {
                String fileName;
                switch (outputImageFileType) {
                    case FILE_TypeI420:
                        fileName = OUTPUT_DIR + String.format("frame_%05d_I420_%dx%d.yuv", outputFrameCount, width, height);
                        dumpFile(fileName, getDataFromImage(image, COLOR_FormatI420));
                        break;
                    case FILE_TypeNV21:
                        fileName = OUTPUT_DIR + String.format("frame_%05d_NV21_%dx%d.yuv", outputFrameCount, width, height);
                        dumpFile(fileName, getDataFromImage(image, COLOR_FormatNV21));
                        break;
                    case FILE_TypeJPEG:
                        fileName = OUTPUT_DIR + String.format("frame_%05d.jpg", outputFrameCount);
                        compressToJpeg(fileName, image);
                        break;
                }
            }
            image.close();
            decoder.releaseOutputBuffer(outputBufferId, true);
        }
    }
}

上述代码是MediaCodec解码的一般框架,不作过多解释。 不同于bigflake的是MediaCodec解码的输出没有指定一个Surface,而是利用API 21新功能,直接通过getOutputImage()将视频帧以Image的形式取出。

而我们现在得到的Image就可以确定是YUV420Flexible格式,而得益于Image类的抽象,我们又可以非常方便地将其转换为NV21或I420格式。关于具体的转换和写入文件的细节,参见我的另一篇文章Android: YUV_420_888编码Image转换为I420和NV21格式byte数组

总结

这篇文章饼画的很大,但写的很短,因为还有一大部分内容在如上链接中的文章中讲到。对于仅仅需要将视频切分为一帧一帧并保存为图片的用户来说,使用这种方法比bigflake的方法会快10倍左右,因为没有OpenGL渲染,以及转换为Bitmap的开销。而对于需要获得视频帧YUV格式数据的用户来说,这种方法能够直接得到YUV格式数据,中间没有数学运算,不会出现不必要的精度损失,而且,也是效率最高的。

此方法的核心原理就是通过指定解码器参数,保证了解码得到的帧格式一定是YUV420Flexible;通过Image实现了健壮且高效的YUV格式转换方法;通过YuvImage实现了快速的JPEG格式图片生成和写入的方法。

Demo

依照上面的描述,本文附带了一个Android APP Demo,指定输入视频文件和输出文件夹名,此APP可将视频帧保存为I420、NV21或JPEG格式。如有需要,请点击zhantong/Android-VideoToImages

demo screenshot

主要代码

Java
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.media.Image;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;


public class New {
    private static final String TAG = "VideoToFrames";
    private static final boolean VERBOSE = true;
    private static final long DEFAULT_TIMEOUT_US = 10000;

    private static final int COLOR_FormatI420 = 1;
    private static final int COLOR_FormatNV21 = 2;

    public static final int FILE_TypeI420 = 1;
    public static final int FILE_TypeNV21 = 2;
    public static final int FILE_TypeJPEG = 3;

    private final int decodeColorFormat = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Flexible;

    private int outputImageFileType = -1;
    private String OUTPUT_DIR;


    public void setSaveFrames(String dir, int fileType) throws IOException {
        if (fileType != FILE_TypeI420 && fileType != FILE_TypeNV21 && fileType != FILE_TypeJPEG) {
            throw new IllegalArgumentException("only support FILE_TypeI420 " + "and FILE_TypeNV21 " + "and FILE_TypeJPEG");
        }
        outputImageFileType = fileType;
        File theDir = new File(dir);
        if (!theDir.exists()) {
            theDir.mkdirs();
        } else if (!theDir.isDirectory()) {
            throw new IOException("Not a directory");
        }
        OUTPUT_DIR = theDir.getAbsolutePath() + "/";
    }

    public void videoDecode(String videoFilePath) throws IOException {
        MediaExtractor extractor = null;
        MediaCodec decoder = null;
        try {
            File videoFile = new File(videoFilePath);
            extractor = new MediaExtractor();
            extractor.setDataSource(videoFile.toString());
            int trackIndex = selectTrack(extractor);
            if (trackIndex < 0) {
                throw new RuntimeException("No video track found in " + videoFilePath);
            }
            extractor.selectTrack(trackIndex);
            MediaFormat mediaFormat = extractor.getTrackFormat(trackIndex);
            String mime = mediaFormat.getString(MediaFormat.KEY_MIME);
            decoder = MediaCodec.createDecoderByType(mime);
            showSupportedColorFormat(decoder.getCodecInfo().getCapabilitiesForType(mime));
            if (isColorFormatSupported(decodeColorFormat, decoder.getCodecInfo().getCapabilitiesForType(mime))) {
                mediaFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, decodeColorFormat);
                Log.i(TAG, "set decode color format to type " + decodeColorFormat);
            } else {
                Log.i(TAG, "unable to set decode color format, color format type " + decodeColorFormat + " not supported");
            }
            decodeFramesToImage(decoder, extractor, mediaFormat);
            decoder.stop();
        } finally {
            if (decoder != null) {
                decoder.stop();
                decoder.release();
                decoder = null;
            }
            if (extractor != null) {
                extractor.release();
                extractor = null;
            }
        }
    }

    private void showSupportedColorFormat(MediaCodecInfo.CodecCapabilities caps) {
        System.out.print("supported color format: ");
        for (int c : caps.colorFormats) {
            System.out.print(c + "\t");
        }
        System.out.println();
    }

    private boolean isColorFormatSupported(int colorFormat, MediaCodecInfo.CodecCapabilities caps) {
        for (int c : caps.colorFormats) {
            if (c == colorFormat) {
                return true;
            }
        }
        return false;
    }

    private void decodeFramesToImage(MediaCodec decoder, MediaExtractor extractor, MediaFormat mediaFormat) {
        MediaCodec.BufferInfo info = new MediaCodec.BufferInfo();
        boolean sawInputEOS = false;
        boolean sawOutputEOS = false;
        decoder.configure(mediaFormat, null, null, 0);
        decoder.start();
        final int width = mediaFormat.getInteger(MediaFormat.KEY_WIDTH);
        final int height = mediaFormat.getInteger(MediaFormat.KEY_HEIGHT);
        int outputFrameCount = 0;
        while (!sawOutputEOS) {
            if (!sawInputEOS) {
                int inputBufferId = decoder.dequeueInputBuffer(DEFAULT_TIMEOUT_US);
                if (inputBufferId >= 0) {
                    ByteBuffer inputBuffer = decoder.getInputBuffer(inputBufferId);
                    int sampleSize = extractor.readSampleData(inputBuffer, 0);
                    if (sampleSize < 0) {
                        decoder.queueInputBuffer(inputBufferId, 0, 0, 0L, MediaCodec.BUFFER_FLAG_END_OF_STREAM);
                        sawInputEOS = true;
                    } else {
                        long presentationTimeUs = extractor.getSampleTime();
                        decoder.queueInputBuffer(inputBufferId, 0, sampleSize, presentationTimeUs, 0);
                        extractor.advance();
                    }
                }
            }
            int outputBufferId = decoder.dequeueOutputBuffer(info, DEFAULT_TIMEOUT_US);
            if (outputBufferId >= 0) {
                if ((info.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                    sawOutputEOS = true;
                }
                boolean doRender = (info.size != 0);
                if (doRender) {
                    outputFrameCount++;
                    Image image = decoder.getOutputImage(outputBufferId);
                    System.out.println("image format: " + image.getFormat());
                    if (outputImageFileType != -1) {
                        String fileName;
                        switch (outputImageFileType) {
                            case FILE_TypeI420:
                                fileName = OUTPUT_DIR + String.format("frame_%05d_I420_%dx%d.yuv", outputFrameCount, width, height);
                                dumpFile(fileName, getDataFromImage(image, COLOR_FormatI420));
                                break;
                            case FILE_TypeNV21:
                                fileName = OUTPUT_DIR + String.format("frame_%05d_NV21_%dx%d.yuv", outputFrameCount, width, height);
                                dumpFile(fileName, getDataFromImage(image, COLOR_FormatNV21));
                                break;
                            case FILE_TypeJPEG:
                                fileName = OUTPUT_DIR + String.format("frame_%05d.jpg", outputFrameCount);
                                compressToJpeg(fileName, image);
                                break;
                        }
                    }
                    image.close();
                    decoder.releaseOutputBuffer(outputBufferId, true);
                }
            }
        }
    }

    private static int selectTrack(MediaExtractor extractor) {
        int numTracks = extractor.getTrackCount();
        for (int i = 0; i < numTracks; i++) {
            MediaFormat format = extractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("video/")) {
                if (VERBOSE) {
                    Log.d(TAG, "Extractor selected track " + i + " (" + mime + "): " + format);
                }
                return i;
            }
        }
        return -1;
    }

    private static boolean isImageFormatSupported(Image image) {
        int format = image.getFormat();
        switch (format) {
            case ImageFormat.YUV_420_888:
            case ImageFormat.NV21:
            case ImageFormat.YV12:
                return true;
        }
        return false;
    }

    private static byte[] getDataFromImage(Image image, int colorFormat) {
        if (colorFormat != COLOR_FormatI420 && colorFormat != COLOR_FormatNV21) {
            throw new IllegalArgumentException("only support COLOR_FormatI420 " + "and COLOR_FormatNV21");
        }
        if (!isImageFormatSupported(image)) {
            throw new RuntimeException("can't convert Image to byte array, format " + image.getFormat());
        }
        Rect crop = image.getCropRect();
        int format = image.getFormat();
        int width = crop.width();
        int height = crop.height();
        Image.Plane[] planes = image.getPlanes();
        byte[] data = new byte[width * height * ImageFormat.getBitsPerPixel(format) / 8];
        byte[] rowData = new byte[planes[0].getRowStride()];
        if (VERBOSE) Log.v(TAG, "get data from " + planes.length + " planes");
        int channelOffset = 0;
        int outputStride = 1;
        for (int i = 0; i < planes.length; i++) {
            switch (i) {
                case 0:
                    channelOffset = 0;
                    outputStride = 1;
                    break;
                case 1:
                    if (colorFormat == COLOR_FormatI420) {
                        channelOffset = width * height;
                        outputStride = 1;
                    } else if (colorFormat == COLOR_FormatNV21) {
                        channelOffset = width * height + 1;
                        outputStride = 2;
                    }
                    break;
                case 2:
                    if (colorFormat == COLOR_FormatI420) {
                        channelOffset = (int) (width * height * 1.25);
                        outputStride = 1;
                    } else if (colorFormat == COLOR_FormatNV21) {
                        channelOffset = width * height;
                        outputStride = 2;
                    }
                    break;
            }
            ByteBuffer buffer = planes[i].getBuffer();
            int rowStride = planes[i].getRowStride();
            int pixelStride = planes[i].getPixelStride();
            if (VERBOSE) {
                Log.v(TAG, "pixelStride " + pixelStride);
                Log.v(TAG, "rowStride " + rowStride);
                Log.v(TAG, "width " + width);
                Log.v(TAG, "height " + height);
                Log.v(TAG, "buffer size " + buffer.remaining());
            }
            int shift = (i == 0) ? 0 : 1;
            int w = width >> shift;
            int h = height >> shift;
            buffer.position(rowStride * (crop.top >> shift) + pixelStride * (crop.left >> shift));
            for (int row = 0; row < h; row++) {
                int length;
                if (pixelStride == 1 && outputStride == 1) {
                    length = w;
                    buffer.get(data, channelOffset, length);
                    channelOffset += length;
                } else {
                    length = (w - 1) * pixelStride + 1;
                    buffer.get(rowData, 0, length);
                    for (int col = 0; col < w; col++) {
                        data[channelOffset] = rowData[col * pixelStride];
                        channelOffset += outputStride;
                    }
                }
                if (row < h - 1) {
                    buffer.position(buffer.position() + rowStride - length);
                }
            }
            if (VERBOSE) Log.v(TAG, "Finished reading data from plane " + i);
        }
        return data;
    }

    private static void dumpFile(String fileName, byte[] data) {
        FileOutputStream outStream;
        try {
            outStream = new FileOutputStream(fileName);
        } catch (IOException ioe) {
            throw new RuntimeException("Unable to create output file " + fileName, ioe);
        }
        try {
            outStream.write(data);
            outStream.close();
        } catch (IOException ioe) {
            throw new RuntimeException("failed writing data to file " + fileName, ioe);
        }
    }

    private void compressToJpeg(String fileName, Image image) {
        FileOutputStream outStream;
        try {
            outStream = new FileOutputStream(fileName);
        } catch (IOException ioe) {
            throw new RuntimeException("Unable to create output file " + fileName, ioe);
        }
        Rect rect = image.getCropRect();
        YuvImage yuvImage = new YuvImage(getDataFromImage(image, COLOR_FormatNV21), ImageFormat.NV21, rect.width(), rect.height(), null);
        yuvImage.compressToJpeg(rect, 100, outStream);
    }
}

参考