demux_decode.c 13 KB

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