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.

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