Read memory reading and writing based on the simplest ffmpeg sampling: memory player

Source: Internet
Author: User

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

Based on the simplest FFmpeg sample series read-Write memory list:

Simplest example of ffmpeg-based memory read and write: Memory player

Simplest sample of memory read-write based on ffmpeg: memory transcoding device

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

A sample of two simplest ffmpeg for memory reads and writes is planned.

All previous examples of ffmpeg are operations on the file. For example, "100 lines of code to achieve the simplest ffmpeg+sdl-based video player" is a video of the file.

The simplest ffmpeg-based transcoding program also converts a video file to a video file. "The simplest video encoder based on FFmpeg (YUV Code of H. A)" is also the last code to get a video file of H. In fact, not all video encoding, decoding is for the file processing. Sometimes it is necessary to decode the video data in a section of memory. For example, video data sent through other systems. The same, sometimes encoded video data may not have to be saved as a file. Like what. Requires that the encoded video data be sent to other systems for next processing. The above two situations require ffmpeg not only the file "read, write" operation, but to the memory "read, write" operation. So the two examples that are intended to be recorded are those that use FFmpeg to read and write memory.

A sample of FFmpeg read and write memory has been described in the article "FFmpeg reading data from memory (or outputting data to memory)", but has not done project full code.

This document records the simplest ffmpeg-based memory player. In this example, the video data in the file is first read into memory through Fread (), and then the data in memory is played back using FFmpeg.

The second example of the plan record for the next article is the simplest ffmpeg memory-based transcoding device.

In the sample. First, the video data in the file is read into memory via Fread (). Then use FFmpeg to read the data and transcode it. The transcoded data is then output to a piece of memory, and the data is then written into a file via Fwrite ().

about how to read data from memory is no longer detailed here. Able to participate in the article:

FFmpeg reading data from memory (or outputting data to memory)

Key points

The key points are two:

1. Initialize your own defined Aviocontext, specifying your own defined callback function.

The demo sample code is as follows:

Cache in Aviocontext unsigned char *aviobuffer= (unsigned char*) av_malloc (32768); Aviocontext *avio=avio_alloc_context (Aviobuffer, 32768,0,null,read_buffer,null,null);p formatctx->pb=avio; if (Avformat_open_input (&pformatctx,null,null,null)!=0) {           printf ("couldn ' t open inputstream. (Cannot turn on input stream) \ n");           return-1;}

In the code above, you define the callback function Read_buffer (). When you use Avformat_open_input () to open media data, you can not specify the URL of the file. That is, its 2nd parameter is null (since the data is not read by a file, but is provided by Read_buffer ())

2. Write the callback function yourself.

The demo sample code is as follows:

Callbackint read_buffer (void *opaque, uint8_t *buf, int buf_size) {if (!feof (Fp_open)) {Inttrue_size=fread (buf,1,buf_ Size,fp_open); return true_size;} else{return-1;}}

When the system needs data. The callback function is invoked on its own initiative to obtain the data.

For simplicity, this example reads data to memory directly using Fread (). The callback function needs to pay extra attention to its parameters and return values.

Source

The following is directly affixed to the source code of the program:

/** * Simplest FFmpeg-based memory read/write sample (memory player) * Simplest FFmpeg mem player * * Lei hua * [email protected] * Communication University/Digital TV Technology * Communication University of China/digital TV technology * http://blog.csdn.net/leixiaohua1020 * * This program enables the playback of video data in memory. * Is the simplest example of using ffmpeg to read memory.

* * This software play video data in memory (not a file). * It ' s The simplest example to use FFmpeg to read from memory. * */#include <stdio.h> #define __STDC_CONSTANT_MACROS#IFDEF _win32//windowsextern "C" {#include "libavcodec/ Avcodec.h "#include" libavformat/avformat.h "#include" libswscale/swscale.h "#include" sdl/sdl.h "}; #else//linux...# ifdef __cplusplusextern "C" {#endif # include <libavcodec/avcodec.h> #include <libavformat/avformat.h># Include <libswscale/swscale.h> #include <SDL/SDL.h> #ifdef __cplusplus}; #endif #endif//output yuv420p # Define output_yuv420p 0FILE *fp_open=null;//callbackint read_buffer (void *opaque, uint8_t *buf, int buf_size) {if (!feof ( Fp_open) {int true_size=fread (buf,1,buf_size,fp_open); return true_size;} else{return-1;}} int main (int argc, char* argv[]) {avformatcontext*pformatctx;inti, videoindex; Avcodeccontext*pcodecctx; Avcodec*pcodec;char filepath[]= "cuc60anniversary_start.mkv"; Av_register_all (); Avformat_network_init (); Pformatctx = AvformAt_alloc_context (); Fp_open=fopen (filepath, "rb+");//init aviocontextunsigned Char *aviobuffer= (unsigned char *) av_ malloc (32768); Aviocontext *avio =avio_alloc_context (Aviobuffer, 32768,0,null,read_buffer,null,null);p formatctx->pb=avio;if ( Avformat_open_input (&pformatctx,null,null,null)!=0) {printf ("couldn ' t open input stream.\n"); return-1;} if (Avformat_find_stream_info (pformatctx,null) <0) {printf ("couldn ' t find stream information.\n"); return-1;} Videoindex=-1;for (i=0; i<pformatctx->nb_streams; i++) if (pformatctx->streams[i]->codec->codec_type ==avmedia_type_video) {videoindex=i;break;} if (videoindex==-1) {printf ("didn ' t find a video stream.\n"); return-1;} Pcodecctx=pformatctx->streams[videoindex]->codec;pcodec=avcodec_find_decoder (pCodecCtx->codec_id); if ( Pcodec==null) {printf ("Codec not found.\n"); return-1;} if (Avcodec_open2 (Pcodecctx, Pcodec,null) <0) {printf ("Could not open codec.\n"); return-1;} Avframe*pframe,*pframeyuv;pframe=av_frame_alloc ();p Frameyuv=av_fRame_alloc ();//uint8_t *out_buffer= (uint8_t *) Av_malloc (avpicture_get_size (pix_fmt_yuv420p, PCodecCtx->width, Pcodecctx->height));//avpicture_fill ((Avpicture *) PFRAMEYUV, Out_buffer, pix_fmt_yuv420p, PCodecCtx->width, pcodecctx->height);//sdl----------------------------if (Sdl_init (Sdl_init_video | Sdl_init_audio | Sdl_init_timer) {printf ("Could not initialize SDL-%s\n", Sdl_geterror ()); return-1;} int screen_w=0,screen_h=0; Sdl_surface *screen; Screen_w = Pcodecctx->width;screen_h = Pcodecctx->height;screen = Sdl_setvideomode (Screen_w, Screen_h, 0,0); Screen) {printf ("Sdl:could not set video mode-exiting:%s\n", Sdl_geterror ()); return-1;} Sdl_overlay *bmp; BMP = Sdl_createyuvoverlay (pcodecctx->width, pcodecctx->height,sdl_yv12_overlay, screen); Sdl_rect rect;rect.x = 0; Rect.y = 0; RECT.W = Screen_w; Rect.h = Screen_h; SDL End------------------------int ret, got_picture; Avpacket *packet= (Avpacket *) av_malloc (sizeof (Avpacket)); #if OUTPUT_yuv420p FILE *fp_yuv=fopen ("Output.yuv", "wb+"); #endif sdl_wm_setcaption ("simplest FFmpeg Mem Player", NULL); struct Swscontext *img_convert_ctx;img_convert_ctx = Sws_ GetContext (Pcodecctx->width, Pcodecctx->height, Pcodecctx->pix_fmt, Pcodecctx->width, pCodecCtx-> Height, pix_fmt_yuv420p, sws_bicubic, NULL, NULL, NULL); ------------------------------while (Av_read_frame (pformatctx, packet) >=0) {if (packet->stream_index== Videoindex) {ret = Avcodec_decode_video2 (Pcodecctx, Pframe, &got_picture, packet); if (Ret < 0) {printf ("Decode Error.\n "); return-1;} if (got_picture) {sdl_lockyuvoverlay (BMP);p frameyuv->data[0]=bmp->pixels[0];p frameyuv->data[1]=bmp-> PIXELS[2];p frameyuv->data[2]=bmp->pixels[1]; Pframeyuv->linesize[0]=bmp->pitches[0];p frameyuv->linesize[1]=bmp->pitches[2]; Pframeyuv->linesize[2]=bmp->pitches[1];sws_scale (Img_convert_ctx, (const uint8_t* const*) PFrame->data, Pframe->linesize, 0, Pcodecctx->height, Pframeyuv->data, pframeyuv->linesize); #if output_yuv420pint Y_size=pcodecctx->width*pcodecctx->height ; Fwrite (PFRAMEYUV-&GT;DATA[0],1,Y_SIZE,FP_YUV); Y fwrite (PFRAMEYUV-&GT;DATA[1],1,Y_SIZE/4,FP_YUV); Ufwrite (PFRAMEYUV-&GT;DATA[2],1,Y_SIZE/4,FP_YUV); V#endifsdl_unlockyuvoverlay (BMP); Sdl_displayyuvoverlay (BMP, &rect); Delay 40mssdl_delay (40);}} Av_free_packet (packet);} Sws_freecontext (IMG_CONVERT_CTX), #if output_yuv420p fclose (FP_YUV); #endif fclose (Fp_open); Sdl_quit ();//av_free (Out_buffer); Av_free (PFRAMEYUV); Avcodec_close (PCODECCTX); Avformat_close_input (& PFORMATCTX); return 0;}


The ability to use code-defined macros to determine whether the decoded yuv420p data is exported as a file:


Results

The execution results of the program are as follows.

Ability to decode and play test video.

Coincides with the 60 anniversary celebration, so intercepted a small section of the beginning of the celebration of the party as a test video, to the mother's birthday ~

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbgvpeglhb2h1ytewmja=/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/southeast "/>


Download


Simplest FFmpeg mem Handler


Project Home

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

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

Open source China: Http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_mem_handler


CSDN:
http://download.csdn.net/detail/leixiaohua1020/8003731

This project includes a sample of two ffmpeg read and write memory:
Simplest_ffmpeg_mem_player: FFmpeg-based memory player.
Simplest_ffmpeg_mem_transcoder: FFmpeg-based Memory transcoding (next article record).


Updated-1.1 (2015.2.13) =========================================

This time, the cross-platform requirements were taken into account. Adjusted the source code. After this adjustment. Source code can be compiled on the following platform:

VC + +: Open the SLn file to compile without configuration.

Cl.exe: Open Compile_cl.bat can be used to compile the command line under the cl.exe, note that you may need to follow the VC installation path to adjust the number of parameters in the script. Compile commands such as the following.

:: VS2010 environmentcall "D:\Program Files\Microsoft Visual Studio 10.0\vc\vcvarsall.bat":: Include@set include= Include;%i Nclude%::lib@set Lib=lib;%lib%::compile and Linkcl simplest_ffmpeg_mem_player.cpp/md/link SDL.lib SDLmain.lib Avcodec.lib ^avformat.lib avutil.lib avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib ^/subsystem: Windows/opt:noref

The MINGW:MINGW command-line execution compile_mingw.sh can be compiled using MinGW's g++. Compile commands such as the following.

g++ simplest_ffmpeg_mem_player.cpp-g-o simplest_ffmpeg_mem_player.exe-i/usr/local/include-l/usr/local/lib- Lmingw32-lsdlmain-lsdl-lavformat-lavcodec-lavutil-lswscale

GCC (Linux): The Linux command line executes compile_gcc.sh and can be compiled using GCC. Compile commands such as the following.

GCC simplest_ffmpeg_mem_player.cpp-g-o simplest_ffmpeg_mem_player.out-lstdc++-i/usr/local/include-l/usr/local/ Lib-lsdlmain-lsdl-lavformat-lavcodec-lavutil-lswscale

GCC (MacOS): Mac terminal execution compile_gcc_mac.sh can be compiled using the Mac's GCC, the Mac's gcc and Linux gcc is not very different, but when using SDL1.2, you must add "-framework Cocoa "Parameter, otherwise the compilation cannot pass. Compile commands such as the following.


GCC simplest_ffmpeg_mem_player.cpp-g-o simplest_ffmpeg_mem_player.out-lstdc++-framework cocoa-i/usr/local/include -l/usr/local/lib-lsdlmain-lsdl-lavformat-lavcodec-lavutil-lswscale

PS: Related compilation commands have been saved in the project directory

csdn:http://download.csdn.net/detail/leixiaohua1020/8445795

SourceForge has been updated.



Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.

Read memory reading and writing based on the simplest ffmpeg sampling: memory player

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.