=====================================================

最简单的基于FFmpeg的内存读写的例子系列文章列表:

最简单的基于FFmpeg的内存读写的例子:内存播放器

最简单的基于FFmpeg的内存读写的例子:内存转码器

=====================================================

打算记录两个最简单的FFmpeg进行内存读写的例子。之前的所有有关FFmpeg的例子都是对文件进行操作的。例如《100行代码实现最简单的基于FFMPEG+SDL的视频播放器》播放的是一个视频的文件。而《最简单的基于FFMPEG的转码程序》也是将一个视频文件转换为另一个视频文件。《最简单的基于FFmpeg的视频编码器(YUV编码为H.264)》也是最后编码得到一个H.264视频文件。实际上,并不是所有视频的编码,解码都是针对文件进行处理的。有的时候需要的解码的视频数据在一段内存中。例如,通过其他系统送来的视频数据。同样,有的时候编码后的视频数据也未必要保存成一个文件。例如,要求将编码后的视频数据送给其他的系统进行下一步的处理。以上两种情况就要求FFmpeg不仅仅是对文件进行“读,写”操作,而是要对内存进行“读,写”操作。因此打算记录的两个例子就是使用FFmpeg对内存进行读写的例子。

有关FFmpeg读写内存的例子已经在文章《ffmpeg 从内存中读取数据(或将数据输出到内存)》中有过叙述,但是一直没有做完整代码的工程。本文记录《最简单的基于FFmpeg内存播放器》。该例子中,首先将文件中的视频数据通过fread()读取到内存中,然后使用FFmpeg播放内存中的数据。

下篇文章计划记录的第二个例子是《最简单的基于FFmpeg内存转码器》。该例子中,首先将文件中的视频数据通过fread()读取到内存中,然后使用FFmpeg读取该数据并进行转码,接着将转码后的数据输出到另一块内存中,最后将该数据通过fwrite()写入成文件。

关于如何从内存中读取数据在这里不再详述,可以参考文章:

ffmpeg 从内存中读取数据(或将数据输出到内存)

关键点

关键点就两个:

1.      初始化自定义的AVIOContext,指定自定义的回调函数。示例代码如下:

  1. //AVIOContext中的缓存
  2. unsigned char *aviobuffer=(unsigned char*)av_malloc(32768);
  3. AVIOContext *avio=avio_alloc_context(aviobuffer, 32768,0,NULL,read_buffer,NULL,NULL);
  4. pFormatCtx->pb=avio;
  5.  
  6. if(avformat_open_input(&pFormatCtx,NULL,NULL,NULL)!=0){
  7. printf("Couldn't open inputstream.(无法打开输入流)\n");
  8. return -1;
  9. }

上述代码中,自定义了回调函数read_buffer()。在使用avformat_open_input()打开媒体数据的时候,就可以不指定文件的URL了,即其第2个参数为NULL(因为数据不是靠文件读取,而是由read_buffer()提供)

2.      自己写回调函数。示例代码如下:

  1. //Callback
  2. int read_buffer(void *opaque, uint8_t *buf, int buf_size){
  3. if(!feof(fp_open)){
  4. inttrue_size=fread(buf,1,buf_size,fp_open);
  5. return true_size;
  6. }else{
  7. return -1;
  8. }
  9. }

当系统需要数据的时候,会自动调用该回调函数以获取数据。这个例子为了简单,直接使用fread()读取数据至内存。回调函数需要格外注意它的参数和返回值。

源代码

下面直接贴上程序的源代码:

  1. /**
  2. * 最简单的基于FFmpeg的内存读写例子(内存播放器)
  3. * Simplest FFmpeg mem Player
  4. *
  5. * 雷霄骅
  6. * leixiaohua1020@126.com
  7. * 中国传媒大学/数字电视技术
  8. * Communication University of China / Digital TV Technology
  9. * http://blog.csdn.net/leixiaohua1020
  10. *
  11. * 本程序实现了对内存中的视频数据的播放。
  12. * 是最简单的使用FFmpeg读内存的例子。
  13. *
  14. * This software play video data in memory (not a file).
  15. * It's the simplest example to use FFmpeg to read from memory.
  16. *
  17. */
  18.  
  19. #include <stdio.h>
  20.  
  21. #define __STDC_CONSTANT_MACROS
  22.  
  23. #ifdef _WIN32
  24. //Windows
  25. extern "C"
  26. {
  27. #include "libavcodec/avcodec.h"
  28. #include "libavformat/avformat.h"
  29. #include "libswscale/swscale.h"
  30. #include "SDL/SDL.h"
  31. };
  32. #else
  33. //Linux...
  34. #ifdef __cplusplus
  35. extern "C"
  36. {
  37. #endif
  38. #include <libavcodec/avcodec.h>
  39. #include <libavformat/avformat.h>
  40. #include <libswscale/swscale.h>
  41. #include <SDL/SDL.h>
  42. #ifdef __cplusplus
  43. };
  44. #endif
  45. #endif
  46.  
  47. //Output YUV420P
  48. #define OUTPUT_YUV420P 0
  49. FILE *fp_open=NULL;
  50.  
  51. //Callback
  52. int read_buffer(void *opaque, uint8_t *buf, int buf_size){
  53. if(!feof(fp_open)){
  54. int true_size=fread(buf,1,buf_size,fp_open);
  55. return true_size;
  56. }else{
  57. return -1;
  58. }
  59.  
  60. }
  61.  
  62. int main(int argc, char* argv[])
  63. {
  64.  
  65. AVFormatContext *pFormatCtx;
  66. int i, videoindex;
  67. AVCodecContext *pCodecCtx;
  68. AVCodec *pCodec;
  69. char filepath[]="cuc60anniversary_start.mkv";
  70.  
  71. av_register_all();
  72. avformat_network_init();
  73. pFormatCtx = avformat_alloc_context();
  74.  
  75. fp_open=fopen(filepath,"rb+");
  76. //Init AVIOContext
  77. unsigned char *aviobuffer=(unsigned char *)av_malloc(32768);
  78. AVIOContext *avio =avio_alloc_context(aviobuffer, 32768,0,NULL,read_buffer,NULL,NULL);
  79. pFormatCtx->pb=avio;
  80.  
  81. if(avformat_open_input(&pFormatCtx,NULL,NULL,NULL)!=0){
  82. printf("Couldn't open input stream.\n");
  83. return -1;
  84. }
  85. if(avformat_find_stream_info(pFormatCtx,NULL)<0){
  86. printf("Couldn't find stream information.\n");
  87. return -1;
  88. }
  89. videoindex=-1;
  90. for(i=0; i<pFormatCtx->nb_streams; i++)
  91. if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
  92. videoindex=i;
  93. break;
  94. }
  95. if(videoindex==-1){
  96. printf("Didn't find a video stream.\n");
  97. return -1;
  98. }
  99. pCodecCtx=pFormatCtx->streams[videoindex]->codec;
  100. pCodec=avcodec_find_decoder(pCodecCtx->codec_id);
  101. if(pCodec==NULL){
  102. printf("Codec not found.\n");
  103. return -1;
  104. }
  105. if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){
  106. printf("Could not open codec.\n");
  107. return -1;
  108. }
  109. AVFrame *pFrame,*pFrameYUV;
  110. pFrame=av_frame_alloc();
  111. pFrameYUV=av_frame_alloc();
  112. //uint8_t *out_buffer=(uint8_t *)av_malloc(avpicture_get_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
  113. //avpicture_fill((AVPicture *)pFrameYUV, out_buffer, AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
  114. //SDL----------------------------
  115. if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
  116. printf( "Could not initialize SDL - %s\n", SDL_GetError());
  117. return -1;
  118. }
  119.  
  120. int screen_w=0,screen_h=0;
  121. SDL_Surface *screen;
  122. screen_w = pCodecCtx->width;
  123. screen_h = pCodecCtx->height;
  124. screen = SDL_SetVideoMode(screen_w, screen_h, 0,0);
  125.  
  126. if(!screen) {
  127. printf("SDL: could not set video mode - exiting:%s\n",SDL_GetError());
  128. return -1;
  129. }
  130. SDL_Overlay *bmp;
  131. bmp = SDL_CreateYUVOverlay(pCodecCtx->width, pCodecCtx->height,SDL_YV12_OVERLAY, screen);
  132. SDL_Rect rect;
  133. rect.x = 0;
  134. rect.y = 0;
  135. rect.w = screen_w;
  136. rect.h = screen_h;
  137. //SDL End------------------------
  138. int ret, got_picture;
  139.  
  140. AVPacket *packet=(AVPacket *)av_malloc(sizeof(AVPacket));
  141.  
  142. #if OUTPUT_YUV420P
  143. FILE *fp_yuv=fopen("output.yuv","wb+");
  144. #endif
  145. SDL_WM_SetCaption("Simplest FFmpeg Mem Player",NULL);
  146.  
  147. struct SwsContext *img_convert_ctx;
  148. img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);
  149. //------------------------------
  150. while(av_read_frame(pFormatCtx, packet)>=0){
  151. if(packet->stream_index==videoindex){
  152. ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
  153. if(ret < 0){
  154. printf("Decode Error.\n");
  155. return -1;
  156. }
  157. if(got_picture){
  158. SDL_LockYUVOverlay(bmp);
  159. pFrameYUV->data[0]=bmp->pixels[0];
  160. pFrameYUV->data[1]=bmp->pixels[2];
  161. pFrameYUV->data[2]=bmp->pixels[1];
  162. pFrameYUV->linesize[0]=bmp->pitches[0];
  163. pFrameYUV->linesize[1]=bmp->pitches[2];
  164. pFrameYUV->linesize[2]=bmp->pitches[1];
  165. sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize);
  166. #if OUTPUT_YUV420P
  167. int y_size=pCodecCtx->width*pCodecCtx->height;
  168. fwrite(pFrameYUV->data[0],1,y_size,fp_yuv); //Y
  169. fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv); //U
  170. fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv); //V
  171. #endif
  172. SDL_UnlockYUVOverlay(bmp);
  173.  
  174. SDL_DisplayYUVOverlay(bmp, &rect);
  175. //Delay 40ms
  176. SDL_Delay(40);
  177. }
  178. }
  179. av_free_packet(packet);
  180. }
  181. sws_freeContext(img_convert_ctx);
  182.  
  183. #if OUTPUT_YUV420P
  184. fclose(fp_yuv);
  185. #endif
  186.  
  187. fclose(fp_open);
  188.  
  189. SDL_Quit();
  190.  
  191. //av_free(out_buffer);
  192. av_free(pFrameYUV);
  193. avcodec_close(pCodecCtx);
  194. avformat_close_input(&pFormatCtx);
  195.  
  196. return 0;
  197. }

可以通过代码定义的宏来确定是否将解码后的YUV420P数据输出成文件:

  1. #define OUTPUT_YUV420P 0

结果

程序的运行结果如下。可以解码播放测试视频。适逢60周年校庆,因此截取了一小段校庆晚会的开场画面作为测试视频,给母校庆生~

下载


simplest ffmpeg mem handler


项目主页

SourceForge:https://sourceforge.net/projects/simplestffmpegmemhandler/

Github:https://github.com/leixiaohua1020/simplest_ffmpeg_mem_handler

开源中国:http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_mem_handler

CSDN下载地址:
http://download.csdn.net/detail/leixiaohua1020/8003731

 本工程包含两个FFmpeg读写内存的例子:
 simplest_ffmpeg_mem_player:基于FFmpeg的内存播放器。
 simplest_ffmpeg_mem_transcoder:基于FFmpeg的内存转码器(下篇文章记录)。

更新-1.1 (2015.2.13)=========================================

这次考虑到了跨平台的要求,调整了源代码。经过这次调整之后,源代码可以在以下平台编译通过:

VC++:打开sln文件即可编译,无需配置。

cl.exe:打开compile_cl.bat即可命令行下使用cl.exe进行编译,注意可能需要按照VC的安装路径调整脚本里面的参数。编译命令如下。

  1. ::VS2010 Environment
  2. call "D:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"
  3. ::include
  4. @set INCLUDE=include;%INCLUDE%
  5. ::lib
  6. @set LIB=lib;%LIB%
  7. ::compile and link
  8. cl simplest_ffmpeg_mem_player.cpp /MD /link SDL.lib SDLmain.lib avcodec.lib ^
  9. avformat.lib avutil.lib avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib ^
  10. /SUBSYSTEM:WINDOWS /OPT:NOREF

MinGW:MinGW命令行下运行compile_mingw.sh即可使用MinGW的g++进行编译。编译命令如下。

  1. g++ simplest_ffmpeg_mem_player.cpp -g -o simplest_ffmpeg_mem_player.exe \
  2. -I /usr/local/include -L /usr/local/lib \
  3. -lmingw32 -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lswscale

GCC(Linux):Linux命令行下运行compile_gcc.sh即可使用GCC进行编译。编译命令如下。

  1. gcc simplest_ffmpeg_mem_player.cpp -g -o simplest_ffmpeg_mem_player.out -lstdc++ \
  2. -I /usr/local/include -L /usr/local/lib -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lswscale

GCC(MacOS):Mac终端下运行compile_gcc_mac.sh即可使用Mac 的GCC进行编译,Mac的GCC和Linux的GCC差别不大,但是使用SDL1.2的时候,必须加上“-framework Cocoa”参数,否则编译无法通过。编译命令如下。

  1. gcc simplest_ffmpeg_mem_player.cpp -g -o simplest_ffmpeg_mem_player.out -lstdc++ \
  2. -framework Cocoa -I /usr/local/include -L /usr/local/lib -lSDLmain -lSDL -lavformat -lavcodec -lavutil -lswscale

PS:相关的编译命令已经保存到了工程文件夹中

CSDN下载地址:http://download.csdn.net/detail/leixiaohua1020/8445795

SourceForge上已经更新。

最简单的基于FFmpeg的内存读写的例子:内存播放器的更多相关文章

  1. [开源]基于ffmpeg和libvlc的视频剪辑、播放器

    [开源]基于ffmpeg和libvlc的视频剪辑.播放器 以前研究的时候,写过一个简单的基于VLC的视频播放器.后来因为各种项目,有时为了方便测试,等各种原因,陆续加了一些功能,现在集成了视频播放.视 ...

  2. 基于ffmpeg和libvlc的视频剪辑、播放器

    以前研究的时候,写过一个简单的基于VLC的视频播放器.后来因为各种项目,有时为了方便测试,等各种原因,陆续加了一些功能,现在集成了视频播放.视频加减速.视频剪切,视频合并(增加中)等功能在一起.有时候 ...

  3. 最简单的基于FFmpeg的内存读写的例子:内存转码器

    ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章列表: 最简单的基于FFmpeg的内存读写的 ...

  4. (转)最简单的基于FFmpeg的内存读写的例子:内存播放器

    ffmpeg内存播放解码 目录(?)[+] ===================================================== 最简单的基于FFmpeg的内存读写的例子系列文章 ...

  5. 最简单的基于FFmpeg的推流器(以推送RTMP为例)

    ===================================================== 最简单的基于FFmpeg的推流器系列文章列表: <最简单的基于FFmpeg的推流器(以 ...

  6. 最简单的基于FFmpeg的解码器-纯净版(不包含libavformat)

    ===================================================== 最简单的基于FFmpeg的视频播放器系列文章列表: 100行代码实现最简单的基于FFMPEG ...

  7. 最简单的基于FFmpeg的编码器-纯净版(不包含libavformat)

    ===================================================== 最简单的基于FFmpeg的视频编码器文章列表: 最简单的基于FFMPEG的视频编码器(YUV ...

  8. 最简单的基于FFmpeg的libswscale的示例(YUV转RGB)

    ===================================================== 最简单的基于FFmpeg的libswscale的示例系列文章列表: 最简单的基于FFmpeg ...

  9. 基于<最简单的基于FFMPEG+SDL的视频播放器 ver2 (采用SDL2.0)>的一些个人总结

    最近因为项目接近收尾阶段,所以变的没有之前那么忙了,所以最近重新拿起了之前的一些FFMPEG和SDL的相关流媒体播放器的例子在看. 同时自己也用FFMPEG2.01,SDL2.01结合MFC以及网上罗 ...

随机推荐

  1. Python中的文件路径的分隔符

    主要是需要考虑分隔符的问题: 在Windows系统下的分隔符是:\ (反斜杠). 在Linux系统下的分隔符是:/(斜杠). 当在字符中出现\时,大家就要考虑到转义字符了. 转义字符的概念,参考维基百 ...

  2. jquery 跨域请求数据问题

    昨天参加了一个前端的面试,被问到一个跨域请求数据问题,我们之前一直用的是apicloud的api进行请求的,跨域是被apicloud封装起来的,也就没有注意跨域请求数据的问题.当被问到用jquery跨 ...

  3. diango-团队介绍

    1.使用django-admin startproject show创建项目,并使用python manage.py startapp team_show创建应用 2.进行相关的配置 3.代码的实现

  4. jenkins更新后出现JNLP-connect,JNLP2-connect警告

    在更新jenkins后出现提示 This Jenkins instance uses deprecated protocols: JNLP-connect,JNLP2-connect. It may ...

  5. jsp根据参数默认选中radio

    <% int vol = (Integer)request.getAttribute("cardtype") ; %> <input type="rad ...

  6. Python小代码_5_二维矩阵转置

    使用列表推导式实现二维矩阵转置 matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] print(matrix) matrix_t = [[ro ...

  7. linux tar解压命令

    linux下使用tar命令 解压语法:tar [主选项+辅选项] 文件或者目录 使用该命令时,主选项是必须要有的,它告诉tar要做什么事情,辅选项是辅助使用的,可以选用.主选项:c 创建新的档案文件. ...

  8. ACM Self Number

    In 1949 the Indian mathematician D.R. Kaprekar discovered a class of numbers called self-numbers. Fo ...

  9. [Angular2]eclipse中angular2开发环境的搭建

    本文作者:苏生米沿 本文地址:http://blog.csdn.net/sushengmiyan 环境准备 1.eclipse neon 2.网络连接 插件地址 eclipse的插件市场地址: htt ...

  10. (译)Objective-C 类属性

    翻译自:Objective-C Class Properties 译者:Haley_Wong 由于Swift 3.0 出了太多令人兴奋的新特性,人们很容易忽略 Objective-C中的小改动.苹果展 ...