demuxing_decoding.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. #pragma warning( disable : 4996)
  2. /*
  3. * Copyright (c) 2012 Stefano Sabatini
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. */
  23. /**
  24. * @file
  25. * Demuxing and decoding example.
  26. *
  27. * Show how to use the libavformat and libavcodec API to demux and
  28. * decode audio and video data.
  29. * @example demuxing_decoding.c
  30. */
  31. #ifdef BUSTED_COMPILER
  32. #define inline __inline
  33. #ifndef snprintf
  34. #define snprintf(buf,len, format,...) _snprintf_s(buf, len,len, format, __VA_ARGS__)
  35. #endif
  36. #endif
  37. #include <libavutil/imgutils.h>
  38. #include <libavutil/samplefmt.h>
  39. #include <libavutil/timestamp.h>
  40. #include <libavformat/avformat.h>
  41. #include <libavformat/avio.h>
  42. #include "BufferNegotiator.h"
  43. static AVFormatContext *fmt_ctx = NULL;
  44. static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx = NULL;
  45. static AVIOContext* avio_ctx = NULL;
  46. static uint8_t* avio_ctx_buffer = NULL;
  47. static size_t avio_ctx_buffer_size = 48128;
  48. static int width, height;
  49. static enum AVPixelFormat pix_fmt;
  50. static AVStream *video_stream = NULL, *audio_stream = NULL;
  51. static int stopDecoding = 0;
  52. uint8_t *video_dst_data[4] = {NULL};
  53. static int video_dst_linesize[4];
  54. long video_dst_bufsize;
  55. static int video_stream_idx = -1, audio_stream_idx = -1;
  56. static AVFrame *frame = NULL;
  57. static AVPacket pkt;
  58. static int video_frame_count = 0;
  59. static int audio_frame_count = 0;
  60. static int read_packet(void* opaque, uint8_t* buf, int buf_size);
  61. /* Enable or disable frame reference counting. You are not supposed to support
  62. * both paths in your application but pick the one most appropriate to your
  63. * needs. Look for the use of refcount in this example to see what are the
  64. * differences of API usage between them. */
  65. static int refcount = 0;
  66. static int decode_packet(int *got_frame, int cached)
  67. {
  68. int ret = 0;
  69. int decoded = pkt.size;
  70. *got_frame = 0;
  71. if (pkt.stream_index == video_stream_idx) {
  72. /* decode video frame */
  73. ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
  74. if (ret < 0) {
  75. fprintf(stderr, "Error decoding video frame (%s)\n", av_err2str(ret));
  76. return ret;
  77. }
  78. if (*got_frame) {
  79. if (frame->width != width || frame->height != height ||
  80. frame->format != pix_fmt) {
  81. /* To handle this change, one could call av_image_alloc again and
  82. * decode the following frames into another rawvideo file. */
  83. fprintf(stderr, "Error: Width, height and pixel format have to be "
  84. "constant in a rawvideo file, but the width, height or "
  85. "pixel format of the input video changed:\n"
  86. "old: width = %d, height = %d, format = %s\n"
  87. "new: width = %d, height = %d, format = %s\n",
  88. width, height, av_get_pix_fmt_name(pix_fmt),
  89. frame->width, frame->height,
  90. av_get_pix_fmt_name(frame->format));
  91. return -1;
  92. }
  93. printf("video_frame%s n:%d coded_n:%d\n",
  94. cached ? "(cached)" : "",
  95. video_frame_count++, frame->coded_picture_number);
  96. /* copy decoded frame to destination buffer:
  97. * this is required since rawvideo expects non aligned data */
  98. LockBuffer();
  99. av_image_copy(video_dst_data, video_dst_linesize,
  100. (const uint8_t **)(frame->data), frame->linesize,
  101. pix_fmt, width, height);
  102. UnlockBuffer();
  103. /* write to rawvideo file */
  104. //fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
  105. }
  106. } else if (pkt.stream_index == audio_stream_idx) {
  107. /* decode audio frame */
  108. ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
  109. if (ret < 0) {
  110. fprintf(stderr, "Error decoding audio frame (%s)\n", av_err2str(ret));
  111. return ret;
  112. }
  113. /* Some audio decoders decode only part of the packet, and have to be
  114. * called again with the remainder of the packet data.
  115. * Sample: fate-suite/lossless-audio/luckynight-partial.shn
  116. * Also, some decoders might over-read the packet. */
  117. decoded = FFMIN(ret, pkt.size);
  118. if (*got_frame) {
  119. size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
  120. //printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
  121. // cached ? "(cached)" : "",
  122. // audio_frame_count++, frame->nb_samples,
  123. // av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
  124. /* Write the raw audio data samples of the first plane. This works
  125. * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
  126. * most audio decoders output planar audio, which uses a separate
  127. * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
  128. * In other words, this code will write only the first audio channel
  129. * in these cases.
  130. * You should use libswresample or libavfilter to convert the frame
  131. * to packed data. */
  132. //fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);
  133. }
  134. }
  135. /* If we use frame reference counting, we own the data and need
  136. * to de-reference it when we don't use it anymore */
  137. if (*got_frame && refcount)
  138. av_frame_unref(frame);
  139. return decoded;
  140. }
  141. static int open_codec_context(int *stream_idx,
  142. AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx, enum AVMediaType type)
  143. {
  144. int ret, stream_index;
  145. AVStream *st;
  146. AVCodec *dec = NULL;
  147. AVDictionary *opts = NULL;
  148. ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  149. if (ret < 0) {
  150. fprintf(stderr, "Could not find %s stream in input\n",
  151. av_get_media_type_string(type));
  152. return ret;
  153. } else {
  154. stream_index = ret;
  155. st = fmt_ctx->streams[stream_index];
  156. /* find decoder for the stream */
  157. dec = avcodec_find_decoder(st->codecpar->codec_id);
  158. if (!dec) {
  159. fprintf(stderr, "Failed to find %s codec\n",
  160. av_get_media_type_string(type));
  161. return AVERROR(EINVAL);
  162. }
  163. /* Allocate a codec context for the decoder */
  164. *dec_ctx = avcodec_alloc_context3(dec);
  165. if (!*dec_ctx) {
  166. fprintf(stderr, "Failed to allocate the %s codec context\n",
  167. av_get_media_type_string(type));
  168. return AVERROR(ENOMEM);
  169. }
  170. /* Copy codec parameters from input stream to output codec context */
  171. if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) {
  172. fprintf(stderr, "Failed to copy %s codec parameters to decoder context\n",
  173. av_get_media_type_string(type));
  174. return ret;
  175. }
  176. /* Init the decoders, with or without reference counting */
  177. av_dict_set(&opts, "refcounted_frames", refcount ? "1" : "0", 0);
  178. if ((ret = avcodec_open2(*dec_ctx, dec, &opts)) < 0) {
  179. fprintf(stderr, "Failed to open %s codec\n",
  180. av_get_media_type_string(type));
  181. return ret;
  182. }
  183. *stream_idx = stream_index;
  184. }
  185. return 0;
  186. }
  187. static int get_format_from_sample_fmt(const char **fmt,
  188. enum AVSampleFormat sample_fmt)
  189. {
  190. int i;
  191. struct sample_fmt_entry {
  192. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  193. } sample_fmt_entries[] = {
  194. { AV_SAMPLE_FMT_U8, "u8", "u8" },
  195. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  196. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  197. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  198. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  199. };
  200. *fmt = NULL;
  201. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  202. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  203. if (sample_fmt == entry->sample_fmt) {
  204. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  205. return 0;
  206. }
  207. }
  208. fprintf(stderr,
  209. "sample format %s is not supported as output format\n",
  210. av_get_sample_fmt_name(sample_fmt));
  211. return -1;
  212. }
  213. int StopDecoding()
  214. {
  215. stopDecoding = 1;
  216. return 0;
  217. }
  218. static int shouldInterrupt(void * junk)
  219. {
  220. return stopDecoding;
  221. }
  222. int DecodeStream()
  223. {
  224. int ret = 0, got_frame = 0;
  225. stopDecoding = 0;
  226. char* format = "mpegts";
  227. if (stopDecoding)
  228. {
  229. return -1;
  230. }
  231. do
  232. {
  233. AVInputFormat* fmt = NULL;
  234. if (stopDecoding == 1)
  235. return -1;
  236. fmt = av_find_input_format(format);
  237. fmt_ctx = avformat_alloc_context();
  238. fmt_ctx->interrupt_callback.callback = shouldInterrupt;
  239. fmt_ctx->interrupt_callback.opaque = NULL;
  240. AVDictionary* format_opts = NULL;
  241. av_dict_set(&format_opts, "probesize", "4194304", 0);
  242. avio_ctx_buffer = av_malloc(avio_ctx_buffer_size);
  243. if (!avio_ctx_buffer)
  244. {
  245. ret = AVERROR(ENOMEM);
  246. goto end;
  247. }
  248. avio_ctx = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size,
  249. 0, NULL, &read_packet, NULL, NULL);
  250. if (!avio_ctx)
  251. {
  252. ret = AVERROR(ENOMEM);
  253. goto end;
  254. }
  255. fmt_ctx->pb = avio_ctx;
  256. int averr = 0;
  257. /* open input file, and allocate format context */
  258. while ((averr = avformat_open_input(&fmt_ctx, NULL, fmt, &format_opts)) < 0)
  259. {
  260. if (stopDecoding == 1)
  261. {
  262. return -1;
  263. }
  264. _sleep(200);
  265. }
  266. int tries = 0;
  267. /* retrieve stream information */
  268. while (tries < 3)
  269. {
  270. if (avformat_find_stream_info(fmt_ctx, NULL) < 0)
  271. {
  272. fprintf(stderr, "Could not find stream information\n");
  273. tries++;
  274. }
  275. else
  276. {
  277. break;
  278. }
  279. }
  280. if (open_codec_context(&video_stream_idx, &video_dec_ctx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0)
  281. {
  282. video_stream = fmt_ctx->streams[video_stream_idx];
  283. /* allocate image where the decoded image will be put */
  284. width = video_dec_ctx->width;
  285. height = video_dec_ctx->height;
  286. pix_fmt = video_dec_ctx->pix_fmt;
  287. LockBuffer();
  288. ret = av_image_alloc(video_dst_data, video_dst_linesize, width, height, pix_fmt, 1);
  289. UnlockBuffer();
  290. if (ret < 0)
  291. {
  292. fprintf(stderr, "Could not allocate raw video buffer\n");
  293. goto end;
  294. }
  295. LockBuffer();
  296. video_dst_bufsize = ret;
  297. UnlockBuffer();
  298. }
  299. if (!video_stream)
  300. {
  301. fprintf(stderr, "Could not find video stream in the input, aborting\n");
  302. ret = 1;
  303. goto end;
  304. }
  305. frame = av_frame_alloc();
  306. if (!frame)
  307. {
  308. fprintf(stderr, "Could not allocate frame\n");
  309. ret = AVERROR(ENOMEM);
  310. goto end;
  311. }
  312. /* initialize packet, set data to NULL, let the demuxer fill it */
  313. av_init_packet(&pkt);
  314. pkt.data = NULL;
  315. pkt.size = 0;
  316. avio_flush(fmt_ctx->pb);
  317. avformat_flush(fmt_ctx);
  318. /* read frames from the file */
  319. while (av_read_frame(fmt_ctx, &pkt) >= 0 && !stopDecoding)
  320. {
  321. AVPacket orig_pkt = pkt;
  322. do
  323. {
  324. ret = decode_packet(&got_frame, 0);
  325. if (ret < 0)
  326. break;
  327. pkt.data += ret;
  328. pkt.size -= ret;
  329. } while (pkt.size > 0);
  330. av_packet_unref(&orig_pkt);
  331. }
  332. /* flush cached frames */
  333. pkt.data = NULL;
  334. pkt.size = 0;
  335. do
  336. {
  337. decode_packet(&got_frame, 1);
  338. } while (got_frame);
  339. end:
  340. LockBuffer();
  341. video_dst_bufsize = 0;
  342. avcodec_free_context(&video_dec_ctx);
  343. avcodec_free_context(&audio_dec_ctx);
  344. avformat_close_input(&fmt_ctx);
  345. av_freep(&avio_ctx->buffer);
  346. av_freep(&avio_ctx);
  347. avio_ctx = NULL;
  348. video_dec_ctx = NULL;
  349. audio_dec_ctx = NULL;
  350. fmt_ctx = NULL;
  351. av_frame_free(&frame);
  352. frame = NULL;
  353. av_free(video_dst_data[0]);
  354. video_dst_data[0] = NULL;
  355. UnlockBuffer();
  356. } while (1);
  357. return ret < 0;
  358. }
  359. static int read_packet(void* opaque, uint8_t* buf, int buf_size)
  360. {
  361. int ret = ReadInputBuffer(buf, buf_size);
  362. return ret;
  363. }