demux_decode.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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_copy2(video_dst_data, video_dst_linesize,
  74. 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. }
  124. return ret;
  125. }
  126. static int open_codec_context(int *stream_idx,
  127. AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type)
  128. {
  129. int ret, stream_index;
  130. AVStream *st;
  131. const AVCodec *dec = NULL;
  132. ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  133. if (ret < 0) {
  134. fprintf(stderr, "Could not find %s stream in input file '%s'\n",
  135. av_get_media_type_string(type), src_filename);
  136. return ret;
  137. } else {
  138. stream_index = ret;
  139. st = fmt_ctx->streams[stream_index];
  140. /* find decoder for the stream */
  141. dec = avcodec_find_decoder(st->codecpar->codec_id);
  142. if (!dec) {
  143. fprintf(stderr, "Failed to find %s codec\n",
  144. av_get_media_type_string(type));
  145. return AVERROR(EINVAL);
  146. }
  147. /* Allocate a codec context for the decoder */
  148. *dec_ctx = avcodec_alloc_context3(dec);
  149. if (!*dec_ctx) {
  150. fprintf(stderr, "Failed to allocate the %s codec context\n",
  151. av_get_media_type_string(type));
  152. return AVERROR(ENOMEM);
  153. }
  154. /* Copy codec parameters from input stream to output codec context */
  155. if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) {
  156. fprintf(stderr, "Failed to copy %s codec parameters to decoder context\n",
  157. av_get_media_type_string(type));
  158. return ret;
  159. }
  160. /* Init the decoders */
  161. if ((ret = avcodec_open2(*dec_ctx, dec, NULL)) < 0) {
  162. fprintf(stderr, "Failed to open %s codec\n",
  163. av_get_media_type_string(type));
  164. return ret;
  165. }
  166. *stream_idx = stream_index;
  167. }
  168. return 0;
  169. }
  170. static int get_format_from_sample_fmt(const char **fmt,
  171. enum AVSampleFormat sample_fmt)
  172. {
  173. int i;
  174. struct sample_fmt_entry {
  175. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  176. } sample_fmt_entries[] = {
  177. { AV_SAMPLE_FMT_U8, "u8", "u8" },
  178. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  179. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  180. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  181. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  182. };
  183. *fmt = NULL;
  184. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  185. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  186. if (sample_fmt == entry->sample_fmt) {
  187. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  188. return 0;
  189. }
  190. }
  191. fprintf(stderr,
  192. "sample format %s is not supported as output format\n",
  193. av_get_sample_fmt_name(sample_fmt));
  194. return -1;
  195. }
  196. int main (int argc, char **argv)
  197. {
  198. int ret = 0;
  199. if (argc != 4) {
  200. fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
  201. "API example program to show how to read frames from an input file.\n"
  202. "This program reads frames from a file, decodes them, and writes decoded\n"
  203. "video frames to a rawvideo file named video_output_file, and decoded\n"
  204. "audio frames to a rawaudio file named audio_output_file.\n",
  205. argv[0]);
  206. exit(1);
  207. }
  208. src_filename = argv[1];
  209. video_dst_filename = argv[2];
  210. audio_dst_filename = argv[3];
  211. /* open input file, and allocate format context */
  212. if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
  213. fprintf(stderr, "Could not open source file %s\n", src_filename);
  214. exit(1);
  215. }
  216. /* retrieve stream information */
  217. if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
  218. fprintf(stderr, "Could not find stream information\n");
  219. exit(1);
  220. }
  221. if (open_codec_context(&video_stream_idx, &video_dec_ctx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
  222. video_stream = fmt_ctx->streams[video_stream_idx];
  223. video_dst_file = fopen(video_dst_filename, "wb");
  224. if (!video_dst_file) {
  225. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  226. ret = 1;
  227. goto end;
  228. }
  229. /* allocate image where the decoded image will be put */
  230. width = video_dec_ctx->width;
  231. height = video_dec_ctx->height;
  232. pix_fmt = video_dec_ctx->pix_fmt;
  233. ret = av_image_alloc(video_dst_data, video_dst_linesize,
  234. width, height, pix_fmt, 1);
  235. if (ret < 0) {
  236. fprintf(stderr, "Could not allocate raw video buffer\n");
  237. goto end;
  238. }
  239. video_dst_bufsize = ret;
  240. }
  241. if (open_codec_context(&audio_stream_idx, &audio_dec_ctx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
  242. audio_stream = fmt_ctx->streams[audio_stream_idx];
  243. audio_dst_file = fopen(audio_dst_filename, "wb");
  244. if (!audio_dst_file) {
  245. fprintf(stderr, "Could not open destination file %s\n", audio_dst_filename);
  246. ret = 1;
  247. goto end;
  248. }
  249. }
  250. /* dump input information to stderr */
  251. av_dump_format(fmt_ctx, 0, src_filename, 0);
  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. frame = av_frame_alloc();
  258. if (!frame) {
  259. fprintf(stderr, "Could not allocate frame\n");
  260. ret = AVERROR(ENOMEM);
  261. goto end;
  262. }
  263. pkt = av_packet_alloc();
  264. if (!pkt) {
  265. fprintf(stderr, "Could not allocate packet\n");
  266. ret = AVERROR(ENOMEM);
  267. goto end;
  268. }
  269. if (video_stream)
  270. printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
  271. if (audio_stream)
  272. printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
  273. /* read frames from the file */
  274. while (av_read_frame(fmt_ctx, pkt) >= 0) {
  275. // check if the packet belongs to a stream we are interested in, otherwise
  276. // skip it
  277. if (pkt->stream_index == video_stream_idx)
  278. ret = decode_packet(video_dec_ctx, pkt);
  279. else if (pkt->stream_index == audio_stream_idx)
  280. ret = decode_packet(audio_dec_ctx, pkt);
  281. av_packet_unref(pkt);
  282. if (ret < 0)
  283. break;
  284. }
  285. /* flush the decoders */
  286. if (video_dec_ctx)
  287. decode_packet(video_dec_ctx, NULL);
  288. if (audio_dec_ctx)
  289. decode_packet(audio_dec_ctx, NULL);
  290. printf("Demuxing succeeded.\n");
  291. if (video_stream) {
  292. printf("Play the output video file with the command:\n"
  293. "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
  294. av_get_pix_fmt_name(pix_fmt), width, height,
  295. video_dst_filename);
  296. }
  297. if (audio_stream) {
  298. enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;
  299. int n_channels = audio_dec_ctx->ch_layout.nb_channels;
  300. const char *fmt;
  301. if (av_sample_fmt_is_planar(sfmt)) {
  302. const char *packed = av_get_sample_fmt_name(sfmt);
  303. printf("Warning: the sample format the decoder produced is planar "
  304. "(%s). This example will output the first channel only.\n",
  305. packed ? packed : "?");
  306. sfmt = av_get_packed_sample_fmt(sfmt);
  307. n_channels = 1;
  308. }
  309. if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
  310. goto end;
  311. printf("Play the output audio file with the command:\n"
  312. "ffplay -f %s -ac %d -ar %d %s\n",
  313. fmt, n_channels, audio_dec_ctx->sample_rate,
  314. audio_dst_filename);
  315. }
  316. end:
  317. avcodec_free_context(&video_dec_ctx);
  318. avcodec_free_context(&audio_dec_ctx);
  319. avformat_close_input(&fmt_ctx);
  320. if (video_dst_file)
  321. fclose(video_dst_file);
  322. if (audio_dst_file)
  323. fclose(audio_dst_file);
  324. av_packet_free(&pkt);
  325. av_frame_free(&frame);
  326. av_free(video_dst_data[0]);
  327. return ret < 0;
  328. }