The simplest ffmpeg-based package Format converter (no codec)

Source: Internet
Author: User
Tags file url goto printf visual studio

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

The simplest ffmpeg-based package format processing series of articles list:

Simplest FFmpeg-based package format processing: AV splitter Lite (demuxer-simple)

Simplest FFmpeg-based package format processing: AV Splitter (demuxer)

Simplest FFmpeg-based package format processing: AV multiplexer (muxer)

Simplest ffmpeg-based Encapsulation Format processing: Encapsulation format conversion (remuxer)

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


Introduction

This article describes a ffmpeg-based encapsulation format converter. The so-called encapsulation format conversion is the conversion between avi,flv,mkv,mp4 these formats (corresponding. avi,.flv,.mkv,.mp4 files). It is important to note that this program does not encode and decode audio and video. Instead, the AV compression stream is extracted directly from one of the encapsulated format files and packaged into a different package format file. The traditional transcoding program works as shown in the following diagram:
The illustration above illustrates an example of FLV (Video: H. +, Audio: AAC) transcoding to AVI (Video: MPEG2, audio MP3). The process of visible video transcoding is generally the equivalent of "recording" the video and audio again.
This procedure works as shown in the following diagram:

By the figure, this program does not do video and audio codec work, so this program and ordinary transcoding software compared to the following two features:
Processing speed is extremely fast. The audio codec algorithm is very complex and occupies most of the time of transcoding. This saves a lot of time because there is no need to encode and decode the video and audio.

Visual audio quality. Because there is no need to encode and decode the AV, there is no compression damage to the video audio.


process (2014.9.29 update)

A flowchart of Remuxer based on FFmpeg is attached below. The graph uses a light red to mark the key data structure, and the light blue color shows the function of the output video data. It can be seen that a program contains the processing of two files: reading the input file (on the left) and writing to the output file (on the right). A avcodec_copy_context () copy of the input avcodeccontext to the output Avcodeccontext is used in the middle.


Briefly describe the significance of the key functions in the process:

Input file operation:

Avformat_open_input (): Opens the input file and initializes the avformatcontext of the input video stream.

Av_read_frame (): Reads a avpacket from the input file.

Output file operation:

AVFORMAT_ALLOC_OUTPUT_CONTEXT2 (): Initializes the avformatcontext of the output video stream.

Avformat_new_stream (): Creates the avstream of the output stream.

Avcodec_copy_context (): Copies the value of the Avcodeccontex of the input video stream to the avcodeccontext of the output video.

Avio_open (): Open the output file.

Avformat_write_header (): Writes the file header (this function is not required for some encapsulation formats that do not have a file header.) such as Mpeg2ts).

Av_interleaved_write_frame (): Writes Avpacket (store video compression stream data) to the file.

Av_write_trailer (): Writes the end of the file (this function is not required for some encapsulation formats that do not have a file header.) such as Mpeg2ts).
Code

Put the code, the code is adapted from the FFmpeg example, the platform is VC2010.

/*  * simplest FFMPEG-based package format converter  *simplest FFmpeg remuxer  *  * lei Huawei Lei Xiaohua  * leixiaohua1020@126.com  * Communication University/Digital TV technology  *communication University of china/digital TV technology  *http
://blog.csdn.net/leixiaohua1020  *  * This program realizes the conversion between the video encapsulation format.
 * need to note that this program does not change the audio encoding format.  *  * This software converts a media file from one container format  * to another container format without
encoding/decoding video files.
 */  #include "stdafx.h"   extern "C" {#include "libavformat/avformat.h"};     int _tmain (int argc, _tchar* argv[]) {    Avoutputformat *ofmt = NULL;    // The input corresponds to a avformatcontext, and the output corresponds to a avformatcontext    //(input avformatcontext and output Avformatcontext) &
nbsp;   Avformatcontext *ifmt_ctx = null, *OFMT_CTX = NULL;
    Avpacket PKT;
    const char *in_filename, *out_filename;
    int ret, I;     if (argc < 3) {        printf ("Usage:%s input output\n"              "Remux a media file with Libavformat and libavcodec.\n"  & nbsp;          "The output format is guessed according to the file extension.\n "           " Modified by Lei Xiaohua, Leixiaohua1020@126.com\n "           " communication University of China/digital TV technology\n "           "
Http://blog.csdn.net/leixiaohua1020 ", argv[0]);
        return 1;    }     in_filename  = argv[1];//Enter file name (input file URL)     Out_
filename = argv[2];//output file name (output file URL)     Av_register_all ();    //Input     if (ret = Avformat_open_input (&ifmt_ctx, in_filename, 0, 0)) < 0) {  &nbsp
;     printf ("Could not open input file.");
        Goto END;    }     if (ret = avformat_find_stream_info (ifmt_ctx, 0)) < 0) {&NBSP;&NBSP;&NBSP;&N
bsp;    printf ("Failed to retrieve input stream information");
        Goto END;
   }     Av_dump_format (ifmt_ctx, 0, in_filename, 0);    /outputs (output)     avformat_alloc_output_context2 (&ofmt_ctx, NULL, NULL, OUT_
filename);     if (!ofmt_ctx) {        printf ("Could not create output context\
n ");
        ret = Averror_unknown;
        Goto END;    }     ofmt = ofmt_ctx->oformat;     for (i = 0; i < ifmt_ctx->nb_streams; i++) {       ///based on input stream Build output stream (Create output Avstream according to input avstream)         Avstream *in_stream
= ifmt_ctx->streams[i];         Avstream *out_stream = Avformat_new_stream (Ofmt_ctx, in_stream->
CODEC-&GT;CODEC);         if (!out_stream) {        
    printf ("Failed Allocating output stream\n");
            ret = Averror_unknown;
            Goto END;        }        // Copy avcodeccontext settings (copy the settings of Avcodeccontext)         ret = avcodec_copy _context (Out_stream->codec, In_streaM-&GT;CODEC);         if (Ret < 0) {         
   printf ("Failed to copy context from input to output stream codec context\n");
            Goto END;        }         out_stream->codec->
Codec_tag = 0;         if (Ofmt_ctx->oformat->flags & Avfmt_globalheader)              out_stream->codec->flags |= Codec_flag_global_
HEADER;    }    /output format------------------    av_dump_format (ofmt_ctx, 0, out
_filename, 1);    //Opening output file (open output files)     if (! ( Ofmt->flags & Avfmt_nofile) {        ret = Avio_open (&AMP;OFMT_CTX-&GT;PB , Out_filename, AVIO_FLAg_write);         if (Ret < 0) {         
   printf ("Could not open output file '%s '", out_filename);
            Goto END;        }    }    //write header (write file header)  &
nbsp;  ret = Avformat_write_header (Ofmt_ctx, NULL);     if (Ret < 0) {        printf ("Error occurred when opening OUTPU
T file\n ");
        Goto END;
   }     int frame_index=0;     while (1) {        avstream *in_stream, *out_stream;         //Get a avpacket (get an avpacket)         ret
= Av_read_frame (Ifmt_ctx, &AMP;PKT);       &nBsp
if (Ret < 0)             break;
        in_stream  = ifmt_ctx->streams[pkt.stream_index];
        Out_stream = ofmt_ctx->streams[pkt.stream_index];        /* Copy packet */       //Convert pts/ DTS (Convert pts/dts)         pkt.pts = Av_rescale_q_rnd (pkt.pts, in_stream-> Time_base, Out_stream->time_base, (avrounding) (av_round_near_inf|
Av_round_pass_minmax));         Pkt.dts = Av_rescale_q_rnd (Pkt.dts, In_stream->time_base, out_stream- >time_base, (avrounding) (av_round_near_inf|
Av_round_pass_minmax));         pkt.duration = Av_rescale_q (pkt.duration, In_stream->time_base, Out_
Stream->time_base);
        Pkt.pos =-1;        //write (write)         ret = Av_interleaved_write_
FRAME (ofmt_ctx, &pkt);         if (Ret < 0) {         
   printf ("Error muxing packet\n");
            break;        }         printf ("Write%8d frames to
Output file\n ", frame_index);
        Av_free_packet (&AMP;PKT);
        frame_index++;
   }    //write the end of the document (write file trailer)     Av_write_trailer (OFMT_CTX);
End:     avformat_close_input (&AMP;IFMT_CTX);    /* Close Output */    if (ofmt_ctx &&!) Ofmt->flags & Avfmt_nofile)         Avio_close (OFMT_CTX-&GT;PB);
    Avformat_free_context (OFMT_CTX);     if (Ret < 0 && ret! = averror_eof) {        printf ("Err
or occurred.\n ");
        return-1;
   }     return 0; }

When debugging, only the "right-click Project---debug--" command-line parameters "set the input file name and output file name is OK."


Results

The following illustration shows the AV parameters for a test input file. The following illustration shows the audio-visual parameters for the output file. It can be seen that in addition to the video packaging format from FLV to MP4, other related to the visual audio encoding parameters without any changes.



Download


Simplest ffmpeg format


Project Home

sourceforge:https://sourceforge.net/projects/simplestffmpegformat/

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

Open source China: Http://git.oschina.net/leixiaohua1020/simplest_ffmpeg_format
CSDN Download:
http://download.csdn.net/detail/leixiaohua1020/8005317

The project contains 4 examples:

Simplest_ffmpeg_demuxer_simple: Video-Audio splitter (simplified version).

Simplest_ffmpeg_demuxer: Video-Audio splitter.

Simplest_ffmpeg_muxer: Video audio multiplexer.

Simplest_ffmpeg_remuxer: Encapsulates the format converter.


Update -1.1==================================================

Fixes the following issues:
(1) Operational issues under release release
(2) Simplest_ffmpeg_muxer package H/A lost sound when the bare stream

CSDN Download Address:

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


update -1.2 (2015.2.13) =========================================

This time, considering the cross-platform requirements, the source code has been adjusted. After this adjustment, the 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 compiled using cl.exe at the command line, note that you may need to follow the VC installation path to adjust the parameters inside the script. The compile command is as follows.

:: VS2010 Environment call
"D:\Program Files\Microsoft Visual Studio 10.0\vc\vcvarsall.bat"
:: Include
@ Set include=include;%i Nclude%
:: Lib
@set lib=lib;%lib%
:: Compile and link
cl simplest_ffmpeg_remuxer.cpp/link avcodec.lib Avformat.lib avutil.lib ^
avdevice.lib avfilter.lib postproc.lib swresample.lib swscale.lib/opt:noref

The MINGW:MINGW command line runs compile_mingw.sh to compile using MinGW's g++. The compile command is as follows.

g++ simplest_ffmpeg_remuxer.cpp-g-o simplest_ffmpeg_remuxer.exe \
-i/usr/local/include-l/usr/local/lib- Lavformat-lavcodec-lavutil

Gcc:linux or MacOS command line run compile_gcc.sh can be compiled using GCC. The compile command is as follows.

GCC simplest_ffmpeg_remuxer.cpp-g-o simplest_ffmpeg_remuxer.out-i/usr/local/include-l/usr/local/lib \
- Lavformat-lavcodec-lavutil

PS: The related compilation commands have been saved in the project folder

CSDN Download Address: http://download.csdn.net/detail/leixiaohua1020/8445303

The SourceForge has been updated.

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.