demuxing.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. * @file
  24. * libavformat demuxing API use example.
  25. *
  26. * Show how to use the libavformat and libavcodec API to demux and
  27. * decode audio and video data.
  28. */
  29. #include <libavutil/imgutils.h>
  30. #include <libavutil/samplefmt.h>
  31. #include <libavutil/timestamp.h>
  32. #include <libavformat/avformat.h>
  33. static AVFormatContext *fmt_ctx = NULL;
  34. static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
  35. static AVStream *video_stream = NULL, *audio_stream = NULL;
  36. static const char *src_filename = NULL;
  37. static const char *video_dst_filename = NULL;
  38. static const char *audio_dst_filename = NULL;
  39. static FILE *video_dst_file = NULL;
  40. static FILE *audio_dst_file = NULL;
  41. static uint8_t *video_dst_data[4] = {NULL};
  42. static int video_dst_linesize[4];
  43. static int video_dst_bufsize;
  44. static uint8_t **audio_dst_data = NULL;
  45. static int audio_dst_linesize;
  46. static int audio_dst_bufsize;
  47. static int video_stream_idx = -1, audio_stream_idx = -1;
  48. static AVFrame *frame = NULL;
  49. static AVPacket pkt;
  50. static int video_frame_count = 0;
  51. static int audio_frame_count = 0;
  52. static int decode_packet(int *got_frame, int cached)
  53. {
  54. int ret = 0;
  55. if (pkt.stream_index == video_stream_idx) {
  56. /* decode video frame */
  57. ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
  58. if (ret < 0) {
  59. fprintf(stderr, "Error decoding video frame\n");
  60. return ret;
  61. }
  62. if (*got_frame) {
  63. printf("video_frame%s n:%d coded_n:%d pts:%s\n",
  64. cached ? "(cached)" : "",
  65. video_frame_count++, frame->coded_picture_number,
  66. av_ts2timestr(frame->pts, &video_dec_ctx->time_base));
  67. /* copy decoded frame to destination buffer:
  68. * this is required since rawvideo expects non aligned data */
  69. av_image_copy(video_dst_data, video_dst_linesize,
  70. (const uint8_t **)(frame->data), frame->linesize,
  71. video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
  72. /* write to rawvideo file */
  73. fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
  74. }
  75. } else if (pkt.stream_index == audio_stream_idx) {
  76. /* decode audio frame */
  77. ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
  78. if (ret < 0) {
  79. fprintf(stderr, "Error decoding audio frame\n");
  80. return ret;
  81. }
  82. if (*got_frame) {
  83. printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
  84. cached ? "(cached)" : "",
  85. audio_frame_count++, frame->nb_samples,
  86. av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
  87. ret = av_samples_alloc(audio_dst_data, &audio_dst_linesize, frame->channels,
  88. frame->nb_samples, frame->format, 1);
  89. if (ret < 0) {
  90. fprintf(stderr, "Could not allocate audio buffer\n");
  91. return AVERROR(ENOMEM);
  92. }
  93. /* TODO: extend return code of the av_samples_* functions so that this call is not needed */
  94. audio_dst_bufsize =
  95. av_samples_get_buffer_size(NULL, frame->channels,
  96. frame->nb_samples, frame->format, 1);
  97. /* copy audio data to destination buffer:
  98. * this is required since rawaudio expects non aligned data */
  99. av_samples_copy(audio_dst_data, frame->data, 0, 0,
  100. frame->nb_samples, frame->channels, frame->format);
  101. /* write to rawaudio file */
  102. fwrite(audio_dst_data[0], 1, audio_dst_bufsize, audio_dst_file);
  103. av_freep(&audio_dst_data[0]);
  104. }
  105. }
  106. return ret;
  107. }
  108. static int open_codec_context(int *stream_idx,
  109. AVFormatContext *fmt_ctx, enum AVMediaType type)
  110. {
  111. int ret;
  112. AVStream *st;
  113. AVCodecContext *dec_ctx = NULL;
  114. AVCodec *dec = NULL;
  115. ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  116. if (ret < 0) {
  117. fprintf(stderr, "Could not find %s stream in input file '%s'\n",
  118. av_get_media_type_string(type), src_filename);
  119. return ret;
  120. } else {
  121. *stream_idx = ret;
  122. st = fmt_ctx->streams[*stream_idx];
  123. /* find decoder for the stream */
  124. dec_ctx = st->codec;
  125. dec = avcodec_find_decoder(dec_ctx->codec_id);
  126. if (!dec) {
  127. fprintf(stderr, "Failed to find %s codec\n",
  128. av_get_media_type_string(type));
  129. return ret;
  130. }
  131. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  132. fprintf(stderr, "Failed to open %s codec\n",
  133. av_get_media_type_string(type));
  134. return ret;
  135. }
  136. }
  137. return 0;
  138. }
  139. static int get_format_from_sample_fmt(const char **fmt,
  140. enum AVSampleFormat sample_fmt)
  141. {
  142. int i;
  143. struct sample_fmt_entry {
  144. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  145. } sample_fmt_entries[] = {
  146. { AV_SAMPLE_FMT_U8, "u8", "u8" },
  147. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  148. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  149. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  150. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  151. };
  152. *fmt = NULL;
  153. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  154. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  155. if (sample_fmt == entry->sample_fmt) {
  156. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  157. return 0;
  158. }
  159. }
  160. fprintf(stderr,
  161. "sample format %s is not supported as output format\n",
  162. av_get_sample_fmt_name(sample_fmt));
  163. return -1;
  164. }
  165. int main (int argc, char **argv)
  166. {
  167. int ret = 0, got_frame;
  168. if (argc != 4) {
  169. fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
  170. "API example program to show how to read frames from an input file.\n"
  171. "This program reads frames from a file, decodes them, and writes decoded\n"
  172. "video frames to a rawvideo file named video_output_file, and decoded\n"
  173. "audio frames to a rawaudio file named audio_output_file.\n"
  174. "\n", argv[0]);
  175. exit(1);
  176. }
  177. src_filename = argv[1];
  178. video_dst_filename = argv[2];
  179. audio_dst_filename = argv[3];
  180. /* register all formats and codecs */
  181. av_register_all();
  182. /* open input file, and allocated format context */
  183. if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
  184. fprintf(stderr, "Could not open source file %s\n", src_filename);
  185. exit(1);
  186. }
  187. /* retrieve stream information */
  188. if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
  189. fprintf(stderr, "Could not find stream information\n");
  190. exit(1);
  191. }
  192. if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
  193. video_stream = fmt_ctx->streams[video_stream_idx];
  194. video_dec_ctx = video_stream->codec;
  195. video_dst_file = fopen(video_dst_filename, "wb");
  196. if (!video_dst_file) {
  197. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  198. ret = 1;
  199. goto end;
  200. }
  201. /* allocate image where the decoded image will be put */
  202. ret = av_image_alloc(video_dst_data, video_dst_linesize,
  203. video_dec_ctx->width, video_dec_ctx->height,
  204. video_dec_ctx->pix_fmt, 1);
  205. if (ret < 0) {
  206. fprintf(stderr, "Could not allocate raw video buffer\n");
  207. goto end;
  208. }
  209. video_dst_bufsize = ret;
  210. }
  211. /* dump input information to stderr */
  212. av_dump_format(fmt_ctx, 0, src_filename, 0);
  213. if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
  214. int nb_planes;
  215. audio_stream = fmt_ctx->streams[audio_stream_idx];
  216. audio_dec_ctx = audio_stream->codec;
  217. audio_dst_file = fopen(audio_dst_filename, "wb");
  218. if (!audio_dst_file) {
  219. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  220. ret = 1;
  221. goto end;
  222. }
  223. nb_planes = av_sample_fmt_is_planar(audio_dec_ctx->sample_fmt) ?
  224. audio_dec_ctx->channels : 1;
  225. audio_dst_data = av_mallocz(sizeof(uint8_t *) * nb_planes);
  226. if (!audio_dst_data) {
  227. fprintf(stderr, "Could not allocate audio data buffers\n");
  228. ret = AVERROR(ENOMEM);
  229. goto end;
  230. }
  231. }
  232. if (!audio_stream && !video_stream) {
  233. fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
  234. ret = 1;
  235. goto end;
  236. }
  237. frame = avcodec_alloc_frame();
  238. if (!frame) {
  239. fprintf(stderr, "Could not allocate frame\n");
  240. ret = AVERROR(ENOMEM);
  241. goto end;
  242. }
  243. /* initialize packet, set data to NULL, let the demuxer fill it */
  244. av_init_packet(&pkt);
  245. pkt.data = NULL;
  246. pkt.size = 0;
  247. if (video_stream)
  248. printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
  249. if (audio_stream)
  250. printf("Demuxing video from file '%s' into '%s'\n", src_filename, audio_dst_filename);
  251. /* read frames from the file */
  252. while (av_read_frame(fmt_ctx, &pkt) >= 0)
  253. decode_packet(&got_frame, 0);
  254. /* flush cached frames */
  255. pkt.data = NULL;
  256. pkt.size = 0;
  257. do {
  258. decode_packet(&got_frame, 1);
  259. } while (got_frame);
  260. printf("Demuxing succeeded.\n");
  261. if (video_stream) {
  262. printf("Play the output video file with the command:\n"
  263. "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
  264. av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
  265. video_dst_filename);
  266. }
  267. if (audio_stream) {
  268. const char *fmt;
  269. if ((ret = get_format_from_sample_fmt(&fmt, audio_dec_ctx->sample_fmt) < 0))
  270. goto end;
  271. printf("Play the output audio file with the command:\n"
  272. "ffplay -f %s -ac %d -ar %d %s\n",
  273. fmt, audio_dec_ctx->channels, audio_dec_ctx->sample_rate,
  274. audio_dst_filename);
  275. }
  276. end:
  277. if (video_dec_ctx)
  278. avcodec_close(video_dec_ctx);
  279. if (audio_dec_ctx)
  280. avcodec_close(audio_dec_ctx);
  281. avformat_close_input(&fmt_ctx);
  282. if (video_dst_file)
  283. fclose(video_dst_file);
  284. if (audio_dst_file)
  285. fclose(audio_dst_file);
  286. av_free(frame);
  287. av_free(video_dst_data[0]);
  288. av_free(audio_dst_data);
  289. return ret < 0;
  290. }