Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

  1. /*
  2.  * Copyright (c) 2012 Stefano Sabatini
  3.  *
  4.  * Permission is hereby granted, free of charge, to any person obtaining a copy
  5.  * of this software and associated documentation files (the "Software"), to deal
  6.  * in the Software without restriction, including without limitation the rights
  7.  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8.  * copies of the Software, and to permit persons to whom the Software is
  9.  * furnished to do so, subject to the following conditions:
  10.  *
  11.  * The above copyright notice and this permission notice shall be included in
  12.  * all copies or substantial portions of the Software.
  13.  *
  14.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17.  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19.  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20.  * THE SOFTWARE.
  21.  */
  22.  
  23. /**
  24.  * @file
  25.  * libavformat demuxing API use example.
  26.  *
  27.  * Show how to use the libavformat and libavcodec API to demux and
  28.  * decode audio and video data.
  29.  * @example doc/examples/demuxing.c
  30.  */
  31.  
  32. #include <libavutil/imgutils.h>
  33. #include <libavutil/samplefmt.h>
  34. #include <libavutil/timestamp.h>
  35. #include <libavformat/avformat.h>
  36.  
  37. static AVFormatContext *fmt_ctx = NULL;
  38. static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
  39. static AVStream *video_stream = NULL, *audio_stream = NULL;
  40. static const char *src_filename = NULL;
  41. static const char *video_dst_filename = NULL;
  42. static const char *audio_dst_filename = NULL;
  43. static FILE *video_dst_file = NULL;
  44. static FILE *audio_dst_file = NULL;
  45.  
  46. static uint8_t *video_dst_data[4] = {NULL};
  47. static int      video_dst_linesize[4];
  48. static int video_dst_bufsize;
  49.  
  50. static int video_stream_idx = -1, audio_stream_idx = -1;
  51. static AVFrame *frame = NULL;
  52. static AVPacket pkt;
  53. static int video_frame_count = 0;
  54. static int audio_frame_count = 0;
  55.  
  56. static int decode_packet(int *got_frame, int cached)
  57. {
  58.     int ret = 0;
  59.     int decoded = pkt.size;
  60.  
  61.     if (pkt.stream_index == video_stream_idx) {
  62.         /* decode video frame */
  63.         ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
  64.         if (ret < 0) {
  65.             fprintf(stderr, "Error decoding video frame\n");
  66.             return ret;
  67.         }
  68.  
  69.         if (*got_frame) {
  70.             printf("video_frame%s n:%d coded_n:%d pts:%s\n",
  71.                    cached ? "(cached)" : "",
  72.                    video_frame_count++, frame->coded_picture_number,
  73.                    av_ts2timestr(frame->pts, &video_dec_ctx->time_base));
  74.  
  75.             /* copy decoded frame to destination buffer:
  76.              * this is required since rawvideo expects non aligned data */
  77.             av_image_copy(video_dst_data, video_dst_linesize,
  78.                           (const uint8_t **)(frame->data), frame->linesize,
  79.                           video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
  80.  
  81.             /* write to rawvideo file */
  82.             fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
  83.         }
  84.     } else if (pkt.stream_index == audio_stream_idx) {
  85.         /* decode audio frame */
  86.         ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
  87.         if (ret < 0) {
  88.             fprintf(stderr, "Error decoding audio frame\n");
  89.             return ret;
  90.         }
  91.         /* Some audio decoders decode only part of the packet, and have to be
  92.          * called again with the remainder of the packet data.
  93.          * Sample: fate-suite/lossless-audio/luckynight-partial.shn
  94.          * Also, some decoders might over-read the packet. */
  95.         decoded = FFMIN(ret, pkt.size);
  96.  
  97.         if (*got_frame) {
  98.             size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
  99.             printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
  100.                    cached ? "(cached)" : "",
  101.                    audio_frame_count++, frame->nb_samples,
  102.                    av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
  103.  
  104.             /* Write the raw audio data samples of the first plane. This works
  105.              * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
  106.              * most audio decoders output planar audio, which uses a separate
  107.              * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
  108.              * In other words, this code will write only the first audio channel
  109.              * in these cases.
  110.              * You should use libswresample or libavfilter to convert the frame
  111.              * to packed data. */
  112.             fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);
  113.         }
  114.     }
  115.  
  116.     return decoded;
  117. }
  118.  
  119. static int open_codec_context(int *stream_idx,
  120.                               AVFormatContext *fmt_ctx, enum AVMediaType type)
  121. {
  122.     int ret;
  123.     AVStream *st;
  124.     AVCodecContext *dec_ctx = NULL;
  125.     AVCodec *dec = NULL;
  126.  
  127.     ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  128.     if (ret < 0) {
  129.         fprintf(stderr, "Could not find %s stream in input file '%s'\n",
  130.                 av_get_media_type_string(type), src_filename);
  131.         return ret;
  132.     } else {
  133.         *stream_idx = ret;
  134.         st = fmt_ctx->streams[*stream_idx];
  135.  
  136.         /* find decoder for the stream */
  137.         dec_ctx = st->codec;
  138.         dec = avcodec_find_decoder(dec_ctx->codec_id);
  139.         if (!dec) {
  140.             fprintf(stderr, "Failed to find %s codec\n",
  141.                     av_get_media_type_string(type));
  142.             return ret;
  143.         }
  144.  
  145.         if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  146.             fprintf(stderr, "Failed to open %s codec\n",
  147.                     av_get_media_type_string(type));
  148.             return ret;
  149.         }
  150.     }
  151.  
  152.     return 0;
  153. }
  154.  
  155. static int get_format_from_sample_fmt(const char **fmt,
  156.                                       enum AVSampleFormat sample_fmt)
  157. {
  158.     int i;
  159.     struct sample_fmt_entry {
  160.         enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  161.     } sample_fmt_entries[] = {
  162.         { AV_SAMPLE_FMT_U8,  "u8",    "u8"    },
  163.         { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  164.         { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  165.         { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  166.         { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  167.     };
  168.     *fmt = NULL;
  169.  
  170.     for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  171.         struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  172.         if (sample_fmt == entry->sample_fmt) {
  173.             *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  174.             return 0;
  175.         }
  176.     }
  177.  
  178.     fprintf(stderr,
  179.             "sample format %s is not supported as output format\n",
  180.             av_get_sample_fmt_name(sample_fmt));
  181.     return -1;
  182. }
  183.  
  184. int main (int argc, char **argv)
  185. {
  186.     int ret = 0, got_frame;
  187.  
  188.     if (argc != 4) {
  189.         fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
  190.                 "API example program to show how to read frames from an input file.\n"
  191.                 "This program reads frames from a file, decodes them, and writes decoded\n"
  192.                 "video frames to a rawvideo file named video_output_file, and decoded\n"
  193.                 "audio frames to a rawaudio file named audio_output_file.\n"
  194.                 "\n", argv[0]);
  195.         exit(1);
  196.     }
  197.     src_filename = argv[1];
  198.     video_dst_filename = argv[2];
  199.     audio_dst_filename = argv[3];
  200.  
  201.     /* register all formats and codecs */
  202.     av_register_all();
  203.  
  204.     /* open input file, and allocate format context */
  205.     if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
  206.         fprintf(stderr, "Could not open source file %s\n", src_filename);
  207.         exit(1);
  208.     }
  209.  
  210.     /* retrieve stream information */
  211.     if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
  212.         fprintf(stderr, "Could not find stream information\n");
  213.         exit(1);
  214.     }
  215.  
  216.     if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
  217.         video_stream = fmt_ctx->streams[video_stream_idx];
  218.         video_dec_ctx = video_stream->codec;
  219.  
  220.         video_dst_file = fopen(video_dst_filename, "wb");
  221.         if (!video_dst_file) {
  222.             fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  223.             ret = 1;
  224.             goto end;
  225.         }
  226.  
  227.         /* allocate image where the decoded image will be put */
  228.         ret = av_image_alloc(video_dst_data, video_dst_linesize,
  229.                              video_dec_ctx->width, video_dec_ctx->height,
  230.                              video_dec_ctx->pix_fmt, 1);
  231.         if (ret < 0) {
  232.             fprintf(stderr, "Could not allocate raw video buffer\n");
  233.             goto end;
  234.         }
  235.         video_dst_bufsize = ret;
  236.     }
  237.  
  238.     if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
  239.         audio_stream = fmt_ctx->streams[audio_stream_idx];
  240.         audio_dec_ctx = audio_stream->codec;
  241.         audio_dst_file = fopen(audio_dst_filename, "wb");
  242.         if (!audio_dst_file) {
  243.             fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  244.             ret = 1;
  245.             goto end;
  246.         }
  247.     }
  248.  
  249.     /* dump input information to stderr */
  250.     av_dump_format(fmt_ctx, 0, src_filename, 0);
  251.  
  252.     if (!audio_stream && !video_stream) {
  253.         fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
  254.         ret = 1;
  255.         goto end;
  256.     }
  257.  
  258.     frame = avcodec_alloc_frame();
  259.     if (!frame) {
  260.         fprintf(stderr, "Could not allocate frame\n");
  261.         ret = AVERROR(ENOMEM);
  262.         goto end;
  263.     }
  264.  
  265.     /* initialize packet, set data to NULL, let the demuxer fill it */
  266.     av_init_packet(&pkt);
  267.     pkt.data = NULL;
  268.     pkt.size = 0;
  269.  
  270.     if (video_stream)
  271.         printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
  272.     if (audio_stream)
  273.         printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
  274.  
  275.     /* read frames from the file */
  276.     while (av_read_frame(fmt_ctx, &pkt) >= 0) {
  277.         AVPacket orig_pkt = pkt;
  278.         do {
  279.             ret = decode_packet(&got_frame, 0);
  280.             if (ret < 0)
  281.                 break;
  282.             pkt.data += ret;
  283.             pkt.size -= ret;
  284.         } while (pkt.size > 0);
  285.         av_free_packet(&orig_pkt);
  286.     }
  287.  
  288.     /* flush cached frames */
  289.     pkt.data = NULL;
  290.     pkt.size = 0;
  291.     do {
  292.         decode_packet(&got_frame, 1);
  293.     } while (got_frame);
  294.  
  295.     printf("Demuxing succeeded.\n");
  296.  
  297.     if (video_stream) {
  298.         printf("Play the output video file with the command:\n"
  299.                "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
  300.                av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
  301.                video_dst_filename);
  302.     }
  303.  
  304.     if (audio_stream) {
  305.         enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;
  306.         int n_channels = audio_dec_ctx->channels;
  307.         const char *fmt;
  308.  
  309.         if (av_sample_fmt_is_planar(sfmt)) {
  310.             const char *packed = av_get_sample_fmt_name(sfmt);
  311.             printf("Warning: the sample format the decoder produced is planar "
  312.                    "(%s). This example will output the first channel only.\n",
  313.                    packed ? packed : "?");
  314.             sfmt = av_get_packed_sample_fmt(sfmt);
  315.             n_channels = 1;
  316.         }
  317.  
  318.         if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
  319.             goto end;
  320.  
  321.         printf("Play the output audio file with the command:\n"
  322.                "ffplay -f %s -ac %d -ar %d %s\n",
  323.                fmt, n_channels, audio_dec_ctx->sample_rate,
  324.                audio_dst_filename);
  325.     }
  326.  
  327. end:
  328.     if (video_dec_ctx)
  329.         avcodec_close(video_dec_ctx);
  330.     if (audio_dec_ctx)
  331.         avcodec_close(audio_dec_ctx);
  332.     avformat_close_input(&fmt_ctx);
  333.     if (video_dst_file)
  334.         fclose(video_dst_file);
  335.     if (audio_dst_file)
  336.         fclose(audio_dst_file);
  337.     av_free(frame);
  338.     av_free(video_dst_data[0]);
  339.  
  340.     return ret < 0;
  341. }
  342.