You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

344 lines
12KB

  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. * @example doc/examples/demuxing.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 AVStream *video_stream = NULL, *audio_stream = NULL;
  37. static const char *src_filename = NULL;
  38. static const char *video_dst_filename = NULL;
  39. static const char *audio_dst_filename = NULL;
  40. static FILE *video_dst_file = NULL;
  41. static FILE *audio_dst_file = NULL;
  42. static uint8_t *video_dst_data[4] = {NULL};
  43. static int video_dst_linesize[4];
  44. static int video_dst_bufsize;
  45. static int video_stream_idx = -1, audio_stream_idx = -1;
  46. static AVFrame *frame = NULL;
  47. static AVPacket pkt;
  48. static int video_frame_count = 0;
  49. static int audio_frame_count = 0;
  50. static int decode_packet(int *got_frame, int cached)
  51. {
  52. int ret = 0;
  53. int decoded = pkt.size;
  54. *got_frame = 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. /* Some audio decoders decode only part of the packet, and have to be
  83. * called again with the remainder of the packet data.
  84. * Sample: fate-suite/lossless-audio/luckynight-partial.shn
  85. * Also, some decoders might over-read the packet. */
  86. decoded = FFMIN(ret, pkt.size);
  87. if (*got_frame) {
  88. size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
  89. printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
  90. cached ? "(cached)" : "",
  91. audio_frame_count++, frame->nb_samples,
  92. av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
  93. /* Write the raw audio data samples of the first plane. This works
  94. * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
  95. * most audio decoders output planar audio, which uses a separate
  96. * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
  97. * In other words, this code will write only the first audio channel
  98. * in these cases.
  99. * You should use libswresample or libavfilter to convert the frame
  100. * to packed data. */
  101. fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);
  102. }
  103. }
  104. return decoded;
  105. }
  106. static int open_codec_context(int *stream_idx,
  107. AVFormatContext *fmt_ctx, enum AVMediaType type)
  108. {
  109. int ret;
  110. AVStream *st;
  111. AVCodecContext *dec_ctx = NULL;
  112. AVCodec *dec = NULL;
  113. ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  114. if (ret < 0) {
  115. fprintf(stderr, "Could not find %s stream in input file '%s'\n",
  116. av_get_media_type_string(type), src_filename);
  117. return ret;
  118. } else {
  119. *stream_idx = ret;
  120. st = fmt_ctx->streams[*stream_idx];
  121. /* find decoder for the stream */
  122. dec_ctx = st->codec;
  123. dec = avcodec_find_decoder(dec_ctx->codec_id);
  124. if (!dec) {
  125. fprintf(stderr, "Failed to find %s codec\n",
  126. av_get_media_type_string(type));
  127. return ret;
  128. }
  129. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  130. fprintf(stderr, "Failed to open %s codec\n",
  131. av_get_media_type_string(type));
  132. return ret;
  133. }
  134. }
  135. return 0;
  136. }
  137. static int get_format_from_sample_fmt(const char **fmt,
  138. enum AVSampleFormat sample_fmt)
  139. {
  140. int i;
  141. struct sample_fmt_entry {
  142. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  143. } sample_fmt_entries[] = {
  144. { AV_SAMPLE_FMT_U8, "u8", "u8" },
  145. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  146. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  147. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  148. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  149. };
  150. *fmt = NULL;
  151. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  152. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  153. if (sample_fmt == entry->sample_fmt) {
  154. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  155. return 0;
  156. }
  157. }
  158. fprintf(stderr,
  159. "sample format %s is not supported as output format\n",
  160. av_get_sample_fmt_name(sample_fmt));
  161. return -1;
  162. }
  163. int main (int argc, char **argv)
  164. {
  165. int ret = 0, got_frame;
  166. if (argc != 4) {
  167. fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
  168. "API example program to show how to read frames from an input file.\n"
  169. "This program reads frames from a file, decodes them, and writes decoded\n"
  170. "video frames to a rawvideo file named video_output_file, and decoded\n"
  171. "audio frames to a rawaudio file named audio_output_file.\n"
  172. "\n", argv[0]);
  173. exit(1);
  174. }
  175. src_filename = argv[1];
  176. video_dst_filename = argv[2];
  177. audio_dst_filename = argv[3];
  178. /* register all formats and codecs */
  179. av_register_all();
  180. /* open input file, and allocate format context */
  181. if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
  182. fprintf(stderr, "Could not open source file %s\n", src_filename);
  183. exit(1);
  184. }
  185. /* retrieve stream information */
  186. if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
  187. fprintf(stderr, "Could not find stream information\n");
  188. exit(1);
  189. }
  190. if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
  191. video_stream = fmt_ctx->streams[video_stream_idx];
  192. video_dec_ctx = video_stream->codec;
  193. video_dst_file = fopen(video_dst_filename, "wb");
  194. if (!video_dst_file) {
  195. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  196. ret = 1;
  197. goto end;
  198. }
  199. /* allocate image where the decoded image will be put */
  200. ret = av_image_alloc(video_dst_data, video_dst_linesize,
  201. video_dec_ctx->width, video_dec_ctx->height,
  202. video_dec_ctx->pix_fmt, 1);
  203. if (ret < 0) {
  204. fprintf(stderr, "Could not allocate raw video buffer\n");
  205. goto end;
  206. }
  207. video_dst_bufsize = ret;
  208. }
  209. if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
  210. audio_stream = fmt_ctx->streams[audio_stream_idx];
  211. audio_dec_ctx = audio_stream->codec;
  212. audio_dst_file = fopen(audio_dst_filename, "wb");
  213. if (!audio_dst_file) {
  214. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  215. ret = 1;
  216. goto end;
  217. }
  218. }
  219. /* dump input information to stderr */
  220. av_dump_format(fmt_ctx, 0, src_filename, 0);
  221. if (!audio_stream && !video_stream) {
  222. fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
  223. ret = 1;
  224. goto end;
  225. }
  226. frame = avcodec_alloc_frame();
  227. if (!frame) {
  228. fprintf(stderr, "Could not allocate frame\n");
  229. ret = AVERROR(ENOMEM);
  230. goto end;
  231. }
  232. /* initialize packet, set data to NULL, let the demuxer fill it */
  233. av_init_packet(&pkt);
  234. pkt.data = NULL;
  235. pkt.size = 0;
  236. if (video_stream)
  237. printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
  238. if (audio_stream)
  239. printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
  240. /* read frames from the file */
  241. while (av_read_frame(fmt_ctx, &pkt) >= 0) {
  242. AVPacket orig_pkt = pkt;
  243. do {
  244. ret = decode_packet(&got_frame, 0);
  245. if (ret < 0)
  246. break;
  247. pkt.data += ret;
  248. pkt.size -= ret;
  249. } while (pkt.size > 0);
  250. av_free_packet(&orig_pkt);
  251. }
  252. /* flush cached frames */
  253. pkt.data = NULL;
  254. pkt.size = 0;
  255. do {
  256. decode_packet(&got_frame, 1);
  257. } while (got_frame);
  258. printf("Demuxing succeeded.\n");
  259. if (video_stream) {
  260. printf("Play the output video file with the command:\n"
  261. "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
  262. av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
  263. video_dst_filename);
  264. }
  265. if (audio_stream) {
  266. enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;
  267. int n_channels = audio_dec_ctx->channels;
  268. const char *fmt;
  269. if (av_sample_fmt_is_planar(sfmt)) {
  270. const char *packed = av_get_sample_fmt_name(sfmt);
  271. printf("Warning: the sample format the decoder produced is planar "
  272. "(%s). This example will output the first channel only.\n",
  273. packed ? packed : "?");
  274. sfmt = av_get_packed_sample_fmt(sfmt);
  275. n_channels = 1;
  276. }
  277. if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
  278. goto end;
  279. printf("Play the output audio file with the command:\n"
  280. "ffplay -f %s -ac %d -ar %d %s\n",
  281. fmt, n_channels, audio_dec_ctx->sample_rate,
  282. audio_dst_filename);
  283. }
  284. end:
  285. if (video_dec_ctx)
  286. avcodec_close(video_dec_ctx);
  287. if (audio_dec_ctx)
  288. avcodec_close(audio_dec_ctx);
  289. avformat_close_input(&fmt_ctx);
  290. if (video_dst_file)
  291. fclose(video_dst_file);
  292. if (audio_dst_file)
  293. fclose(audio_dst_file);
  294. av_free(frame);
  295. av_free(video_dst_data[0]);
  296. return ret < 0;
  297. }