demuxing_decoding.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. * Demuxing and decoding example.
  25. *
  26. * Show how to use the libavformat and libavcodec API to demux and
  27. * decode audio and video data.
  28. * @example demuxing_decoding.c
  29. */
  30. #include <libavutil/imgutils.h>
  31. #include <libavutil/samplefmt.h>
  32. #include <libavutil/timestamp.h>
  33. #include <libavformat/avformat.h>
  34. static AVFormatContext *fmt_ctx = NULL;
  35. static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
  36. static int width, height;
  37. static enum AVPixelFormat pix_fmt;
  38. static AVStream *video_stream = NULL, *audio_stream = NULL;
  39. static const char *src_filename = NULL;
  40. static const char *video_dst_filename = NULL;
  41. static const char *audio_dst_filename = NULL;
  42. static FILE *video_dst_file = NULL;
  43. static FILE *audio_dst_file = NULL;
  44. static uint8_t *video_dst_data[4] = {NULL};
  45. static int video_dst_linesize[4];
  46. static int video_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. /* Enable or disable frame reference counting. You are not supposed to support
  53. * both paths in your application but pick the one most appropriate to your
  54. * needs. Look for the use of refcount in this example to see what are the
  55. * differences of API usage between them. */
  56. static int refcount = 0;
  57. static int decode_packet(int *got_frame, int cached)
  58. {
  59. int ret = 0;
  60. int decoded = pkt.size;
  61. *got_frame = 0;
  62. if (pkt.stream_index == video_stream_idx) {
  63. /* decode video frame */
  64. ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
  65. if (ret < 0) {
  66. fprintf(stderr, "Error decoding video frame (%s)\n", av_err2str(ret));
  67. return ret;
  68. }
  69. if (*got_frame) {
  70. if (frame->width != width || frame->height != height ||
  71. frame->format != pix_fmt) {
  72. /* To handle this change, one could call av_image_alloc again and
  73. * decode the following frames into another rawvideo file. */
  74. fprintf(stderr, "Error: Width, height and pixel format have to be "
  75. "constant in a rawvideo file, but the width, height or "
  76. "pixel format of the input video changed:\n"
  77. "old: width = %d, height = %d, format = %s\n"
  78. "new: width = %d, height = %d, format = %s\n",
  79. width, height, av_get_pix_fmt_name(pix_fmt),
  80. frame->width, frame->height,
  81. av_get_pix_fmt_name(frame->format));
  82. return -1;
  83. }
  84. printf("video_frame%s n:%d coded_n:%d\n",
  85. cached ? "(cached)" : "",
  86. video_frame_count++, frame->coded_picture_number);
  87. /* copy decoded frame to destination buffer:
  88. * this is required since rawvideo expects non aligned data */
  89. av_image_copy(video_dst_data, video_dst_linesize,
  90. (const uint8_t **)(frame->data), frame->linesize,
  91. pix_fmt, width, height);
  92. /* write to rawvideo file */
  93. fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
  94. }
  95. } else if (pkt.stream_index == audio_stream_idx) {
  96. /* decode audio frame */
  97. ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
  98. if (ret < 0) {
  99. fprintf(stderr, "Error decoding audio frame (%s)\n", av_err2str(ret));
  100. return ret;
  101. }
  102. /* Some audio decoders decode only part of the packet, and have to be
  103. * called again with the remainder of the packet data.
  104. * Sample: fate-suite/lossless-audio/luckynight-partial.shn
  105. * Also, some decoders might over-read the packet. */
  106. decoded = FFMIN(ret, pkt.size);
  107. if (*got_frame) {
  108. size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
  109. printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
  110. cached ? "(cached)" : "",
  111. audio_frame_count++, frame->nb_samples,
  112. av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
  113. /* Write the raw audio data samples of the first plane. This works
  114. * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
  115. * most audio decoders output planar audio, which uses a separate
  116. * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
  117. * In other words, this code will write only the first audio channel
  118. * in these cases.
  119. * You should use libswresample or libavfilter to convert the frame
  120. * to packed data. */
  121. fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);
  122. }
  123. }
  124. /* If we use frame reference counting, we own the data and need
  125. * to de-reference it when we don't use it anymore */
  126. if (*got_frame && refcount)
  127. av_frame_unref(frame);
  128. return decoded;
  129. }
  130. static int open_codec_context(int *stream_idx,
  131. AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type)
  132. {
  133. int ret, stream_index;
  134. AVStream *st;
  135. AVCodec *dec = NULL;
  136. AVDictionary *opts = NULL;
  137. ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  138. if (ret < 0) {
  139. fprintf(stderr, "Could not find %s stream in input file '%s'\n",
  140. av_get_media_type_string(type), src_filename);
  141. return ret;
  142. } else {
  143. stream_index = ret;
  144. st = fmt_ctx->streams[stream_index];
  145. /* find decoder for the stream */
  146. dec = avcodec_find_decoder(st->codecpar->codec_id);
  147. if (!dec) {
  148. fprintf(stderr, "Failed to find %s codec\n",
  149. av_get_media_type_string(type));
  150. return AVERROR(EINVAL);
  151. }
  152. /* Allocate a codec context for the decoder */
  153. *dec_ctx = avcodec_alloc_context3(dec);
  154. if (!*dec_ctx) {
  155. fprintf(stderr, "Failed to allocate the %s codec context\n",
  156. av_get_media_type_string(type));
  157. return AVERROR(ENOMEM);
  158. }
  159. /* Copy codec parameters from input stream to output codec context */
  160. if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) {
  161. fprintf(stderr, "Failed to copy %s codec parameters to decoder context\n",
  162. av_get_media_type_string(type));
  163. return ret;
  164. }
  165. /* Init the decoders, with or without reference counting */
  166. av_dict_set(&opts, "refcounted_frames", refcount ? "1" : "0", 0);
  167. if ((ret = avcodec_open2(*dec_ctx, dec, &opts)) < 0) {
  168. fprintf(stderr, "Failed to open %s codec\n",
  169. av_get_media_type_string(type));
  170. return ret;
  171. }
  172. *stream_idx = stream_index;
  173. }
  174. return 0;
  175. }
  176. static int get_format_from_sample_fmt(const char **fmt,
  177. enum AVSampleFormat sample_fmt)
  178. {
  179. int i;
  180. struct sample_fmt_entry {
  181. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  182. } sample_fmt_entries[] = {
  183. { AV_SAMPLE_FMT_U8, "u8", "u8" },
  184. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  185. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  186. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  187. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  188. };
  189. *fmt = NULL;
  190. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  191. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  192. if (sample_fmt == entry->sample_fmt) {
  193. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  194. return 0;
  195. }
  196. }
  197. fprintf(stderr,
  198. "sample format %s is not supported as output format\n",
  199. av_get_sample_fmt_name(sample_fmt));
  200. return -1;
  201. }
  202. int main (int argc, char **argv)
  203. {
  204. int ret = 0, got_frame;
  205. if (argc != 4 && argc != 5) {
  206. fprintf(stderr, "usage: %s [-refcount] input_file video_output_file audio_output_file\n"
  207. "API example program to show how to read frames from an input file.\n"
  208. "This program reads frames from a file, decodes them, and writes decoded\n"
  209. "video frames to a rawvideo file named video_output_file, and decoded\n"
  210. "audio frames to a rawaudio file named audio_output_file.\n\n"
  211. "If the -refcount option is specified, the program use the\n"
  212. "reference counting frame system which allows keeping a copy of\n"
  213. "the data for longer than one decode call.\n"
  214. "\n", argv[0]);
  215. exit(1);
  216. }
  217. if (argc == 5 && !strcmp(argv[1], "-refcount")) {
  218. refcount = 1;
  219. argv++;
  220. }
  221. src_filename = argv[1];
  222. video_dst_filename = argv[2];
  223. audio_dst_filename = argv[3];
  224. /* open input file, and allocate format context */
  225. if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
  226. fprintf(stderr, "Could not open source file %s\n", src_filename);
  227. exit(1);
  228. }
  229. /* retrieve stream information */
  230. if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
  231. fprintf(stderr, "Could not find stream information\n");
  232. exit(1);
  233. }
  234. if (open_codec_context(&video_stream_idx, &video_dec_ctx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
  235. video_stream = fmt_ctx->streams[video_stream_idx];
  236. video_dst_file = fopen(video_dst_filename, "wb");
  237. if (!video_dst_file) {
  238. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  239. ret = 1;
  240. goto end;
  241. }
  242. /* allocate image where the decoded image will be put */
  243. width = video_dec_ctx->width;
  244. height = video_dec_ctx->height;
  245. pix_fmt = video_dec_ctx->pix_fmt;
  246. ret = av_image_alloc(video_dst_data, video_dst_linesize,
  247. width, height, pix_fmt, 1);
  248. if (ret < 0) {
  249. fprintf(stderr, "Could not allocate raw video buffer\n");
  250. goto end;
  251. }
  252. video_dst_bufsize = ret;
  253. }
  254. if (open_codec_context(&audio_stream_idx, &audio_dec_ctx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
  255. audio_stream = fmt_ctx->streams[audio_stream_idx];
  256. audio_dst_file = fopen(audio_dst_filename, "wb");
  257. if (!audio_dst_file) {
  258. fprintf(stderr, "Could not open destination file %s\n", audio_dst_filename);
  259. ret = 1;
  260. goto end;
  261. }
  262. }
  263. /* dump input information to stderr */
  264. av_dump_format(fmt_ctx, 0, src_filename, 0);
  265. if (!audio_stream && !video_stream) {
  266. fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
  267. ret = 1;
  268. goto end;
  269. }
  270. frame = av_frame_alloc();
  271. if (!frame) {
  272. fprintf(stderr, "Could not allocate frame\n");
  273. ret = AVERROR(ENOMEM);
  274. goto end;
  275. }
  276. /* initialize packet, set data to NULL, let the demuxer fill it */
  277. av_init_packet(&pkt);
  278. pkt.data = NULL;
  279. pkt.size = 0;
  280. if (video_stream)
  281. printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
  282. if (audio_stream)
  283. printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
  284. /* read frames from the file */
  285. while (av_read_frame(fmt_ctx, &pkt) >= 0) {
  286. AVPacket orig_pkt = pkt;
  287. do {
  288. ret = decode_packet(&got_frame, 0);
  289. if (ret < 0)
  290. break;
  291. pkt.data += ret;
  292. pkt.size -= ret;
  293. } while (pkt.size > 0);
  294. av_packet_unref(&orig_pkt);
  295. }
  296. /* flush cached frames */
  297. pkt.data = NULL;
  298. pkt.size = 0;
  299. do {
  300. decode_packet(&got_frame, 1);
  301. } while (got_frame);
  302. printf("Demuxing succeeded.\n");
  303. if (video_stream) {
  304. printf("Play the output video file with the command:\n"
  305. "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
  306. av_get_pix_fmt_name(pix_fmt), width, height,
  307. video_dst_filename);
  308. }
  309. if (audio_stream) {
  310. enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;
  311. int n_channels = audio_dec_ctx->channels;
  312. const char *fmt;
  313. if (av_sample_fmt_is_planar(sfmt)) {
  314. const char *packed = av_get_sample_fmt_name(sfmt);
  315. printf("Warning: the sample format the decoder produced is planar "
  316. "(%s). This example will output the first channel only.\n",
  317. packed ? packed : "?");
  318. sfmt = av_get_packed_sample_fmt(sfmt);
  319. n_channels = 1;
  320. }
  321. if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
  322. goto end;
  323. printf("Play the output audio file with the command:\n"
  324. "ffplay -f %s -ac %d -ar %d %s\n",
  325. fmt, n_channels, audio_dec_ctx->sample_rate,
  326. audio_dst_filename);
  327. }
  328. end:
  329. avcodec_free_context(&video_dec_ctx);
  330. avcodec_free_context(&audio_dec_ctx);
  331. avformat_close_input(&fmt_ctx);
  332. if (video_dst_file)
  333. fclose(video_dst_file);
  334. if (audio_dst_file)
  335. fclose(audio_dst_file);
  336. av_frame_free(&frame);
  337. av_free(video_dst_data[0]);
  338. return ret < 0;
  339. }