FFmpeg decoding .mp4 video file

Sir DrinksCoffeeALot picture Sir DrinksCoffeeALot · Mar 3, 2016 · Viewed 9.5k times · Source

I'm working on a project that needs to open .mp4 file format, read it's frames 1 by 1, decode them and encode them with better type of lossless compression and save them into a file.

Please correct me if i'm wrong with order of doing things, because i'm not 100% sure how this particular thing should be done. From my understanding it should go like this:

1. Open input .mp4 file
2. Find stream info -> find video stream index
3. Copy codec pointer of found video stream index into AVCodecContext type pointer
4. Find decoder -> allocate codec context -> open codec
5. Read frame by frame -> decode the frame -> encode the frame -> save it into a file

So far i encountered couple of problems. For example, if i want to save a frame using av_interleaved_write_frame() function, i can't open input .mp4 file using avformat_open_input() since it's gonna populate filename part of the AVFormatContext structure with input file name and therefore i can't "write" into that file. I've tried different solution using av_guess_format() but when i dump format using dump_format() i get nothing so i can't find stream information about which codec is it using.

So if anyone have any suggestions, i would really appreciate them. Thank you in advance.

Answer

Ronald S. Bultje picture Ronald S. Bultje · Mar 3, 2016

See the "detailed description" in the muxing docs. You:

  1. set ctx->oformat using av_guess_format
  2. set ctx->pb using avio_open2
  3. call avformat_new_stream for each stream in the output file. If you're re-encoding, this is by adding each stream of the input file into the output file.
  4. call avformat_write_header
  5. call av_interleaved_write_frame in a loop
  6. call av_write_trailer
  7. close the file (avio_close) and clear up all allocated memory