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.

676 lines
21KB

  1. /*
  2. * Copyright (c) 2003 Fabrice Bellard
  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 API example.
  25. *
  26. * Output a media file in any supported libavformat format. The default
  27. * codecs are used.
  28. * @example muxing.c
  29. */
  30. #include <stdlib.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. #include <math.h>
  34. #include <libavutil/avassert.h>
  35. #include <libavutil/channel_layout.h>
  36. #include <libavutil/opt.h>
  37. #include <libavutil/mathematics.h>
  38. #include <libavutil/timestamp.h>
  39. #include <libavformat/avformat.h>
  40. #include <libswscale/swscale.h>
  41. #include <libswresample/swresample.h>
  42. #define STREAM_DURATION 10.0
  43. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  44. #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
  45. #define SCALE_FLAGS SWS_BICUBIC
  46. // a wrapper around a single output AVStream
  47. typedef struct OutputStream {
  48. AVStream *st;
  49. /* pts of the next frame that will be generated */
  50. int64_t next_pts;
  51. int samples_count;
  52. AVFrame *frame;
  53. AVFrame *tmp_frame;
  54. float t, tincr, tincr2;
  55. struct SwsContext *sws_ctx;
  56. struct SwrContext *swr_ctx;
  57. } OutputStream;
  58. static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
  59. {
  60. AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
  61. printf("pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
  62. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base),
  63. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base),
  64. av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base),
  65. pkt->stream_index);
  66. }
  67. static int write_frame(AVFormatContext *fmt_ctx, const AVRational *time_base, AVStream *st, AVPacket *pkt)
  68. {
  69. /* rescale output packet timestamp values from codec to stream timebase */
  70. av_packet_rescale_ts(pkt, *time_base, st->time_base);
  71. pkt->stream_index = st->index;
  72. /* Write the compressed frame to the media file. */
  73. log_packet(fmt_ctx, pkt);
  74. return av_interleaved_write_frame(fmt_ctx, pkt);
  75. }
  76. /* Add an output stream. */
  77. static void add_stream(OutputStream *ost, AVFormatContext *oc,
  78. AVCodec **codec,
  79. enum AVCodecID codec_id)
  80. {
  81. AVCodecContext *c;
  82. int i;
  83. /* find the encoder */
  84. *codec = avcodec_find_encoder(codec_id);
  85. if (!(*codec)) {
  86. fprintf(stderr, "Could not find encoder for '%s'\n",
  87. avcodec_get_name(codec_id));
  88. exit(1);
  89. }
  90. ost->st = avformat_new_stream(oc, *codec);
  91. if (!ost->st) {
  92. fprintf(stderr, "Could not allocate stream\n");
  93. exit(1);
  94. }
  95. ost->st->id = oc->nb_streams-1;
  96. c = ost->st->codec;
  97. switch ((*codec)->type) {
  98. case AVMEDIA_TYPE_AUDIO:
  99. c->sample_fmt = (*codec)->sample_fmts ?
  100. (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
  101. c->bit_rate = 64000;
  102. c->sample_rate = 44100;
  103. if ((*codec)->supported_samplerates) {
  104. c->sample_rate = (*codec)->supported_samplerates[0];
  105. for (i = 0; (*codec)->supported_samplerates[i]; i++) {
  106. if ((*codec)->supported_samplerates[i] == 44100)
  107. c->sample_rate = 44100;
  108. }
  109. }
  110. c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
  111. c->channel_layout = AV_CH_LAYOUT_STEREO;
  112. if ((*codec)->channel_layouts) {
  113. c->channel_layout = (*codec)->channel_layouts[0];
  114. for (i = 0; (*codec)->channel_layouts[i]; i++) {
  115. if ((*codec)->channel_layouts[i] == AV_CH_LAYOUT_STEREO)
  116. c->channel_layout = AV_CH_LAYOUT_STEREO;
  117. }
  118. }
  119. c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
  120. ost->st->time_base = (AVRational){ 1, c->sample_rate };
  121. break;
  122. case AVMEDIA_TYPE_VIDEO:
  123. c->codec_id = codec_id;
  124. c->bit_rate = 400000;
  125. /* Resolution must be a multiple of two. */
  126. c->width = 352;
  127. c->height = 288;
  128. /* timebase: This is the fundamental unit of time (in seconds) in terms
  129. * of which frame timestamps are represented. For fixed-fps content,
  130. * timebase should be 1/framerate and timestamp increments should be
  131. * identical to 1. */
  132. ost->st->time_base = (AVRational){ 1, STREAM_FRAME_RATE };
  133. c->time_base = ost->st->time_base;
  134. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  135. c->pix_fmt = STREAM_PIX_FMT;
  136. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  137. /* just for testing, we also add B frames */
  138. c->max_b_frames = 2;
  139. }
  140. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
  141. /* Needed to avoid using macroblocks in which some coeffs overflow.
  142. * This does not happen with normal video, it just happens here as
  143. * the motion of the chroma plane does not match the luma plane. */
  144. c->mb_decision = 2;
  145. }
  146. break;
  147. default:
  148. break;
  149. }
  150. /* Some formats want stream headers to be separate. */
  151. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  152. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  153. }
  154. /**************************************************************/
  155. /* audio output */
  156. static AVFrame *alloc_audio_frame(enum AVSampleFormat sample_fmt,
  157. uint64_t channel_layout,
  158. int sample_rate, int nb_samples)
  159. {
  160. AVFrame *frame = av_frame_alloc();
  161. int ret;
  162. if (!frame) {
  163. fprintf(stderr, "Error allocating an audio frame\n");
  164. exit(1);
  165. }
  166. frame->format = sample_fmt;
  167. frame->channel_layout = channel_layout;
  168. frame->sample_rate = sample_rate;
  169. frame->nb_samples = nb_samples;
  170. if (nb_samples) {
  171. ret = av_frame_get_buffer(frame, 0);
  172. if (ret < 0) {
  173. fprintf(stderr, "Error allocating an audio buffer\n");
  174. exit(1);
  175. }
  176. }
  177. return frame;
  178. }
  179. static void open_audio(AVFormatContext *oc, AVCodec *codec, OutputStream *ost, AVDictionary *opt_arg)
  180. {
  181. AVCodecContext *c;
  182. int nb_samples;
  183. int ret;
  184. AVDictionary *opt = NULL;
  185. c = ost->st->codec;
  186. /* open it */
  187. av_dict_copy(&opt, opt_arg, 0);
  188. ret = avcodec_open2(c, codec, &opt);
  189. av_dict_free(&opt);
  190. if (ret < 0) {
  191. fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
  192. exit(1);
  193. }
  194. /* init signal generator */
  195. ost->t = 0;
  196. ost->tincr = 2 * M_PI * 110.0 / c->sample_rate;
  197. /* increment frequency by 110 Hz per second */
  198. ost->tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
  199. if (c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)
  200. nb_samples = 10000;
  201. else
  202. nb_samples = c->frame_size;
  203. ost->frame = alloc_audio_frame(AV_SAMPLE_FMT_S16, c->channel_layout,
  204. c->sample_rate, nb_samples);
  205. ost->tmp_frame = alloc_audio_frame(c->sample_fmt, c->channel_layout,
  206. c->sample_rate, ost->frame->nb_samples);
  207. /* create resampler context */
  208. if (c->sample_fmt != AV_SAMPLE_FMT_S16) {
  209. ost->swr_ctx = swr_alloc();
  210. if (!ost->swr_ctx) {
  211. fprintf(stderr, "Could not allocate resampler context\n");
  212. exit(1);
  213. }
  214. /* set options */
  215. av_opt_set_int (ost->swr_ctx, "in_channel_count", c->channels, 0);
  216. av_opt_set_int (ost->swr_ctx, "in_sample_rate", c->sample_rate, 0);
  217. av_opt_set_sample_fmt(ost->swr_ctx, "in_sample_fmt", AV_SAMPLE_FMT_S16, 0);
  218. av_opt_set_int (ost->swr_ctx, "out_channel_count", c->channels, 0);
  219. av_opt_set_int (ost->swr_ctx, "out_sample_rate", c->sample_rate, 0);
  220. av_opt_set_sample_fmt(ost->swr_ctx, "out_sample_fmt", c->sample_fmt, 0);
  221. /* initialize the resampling context */
  222. if ((ret = swr_init(ost->swr_ctx)) < 0) {
  223. fprintf(stderr, "Failed to initialize the resampling context\n");
  224. exit(1);
  225. }
  226. }
  227. }
  228. /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
  229. * 'nb_channels' channels. */
  230. static AVFrame *get_audio_frame(OutputStream *ost)
  231. {
  232. int j, i, v, ret;
  233. int16_t *q = (int16_t*)ost->frame->data[0];
  234. /* check if we want to generate more frames */
  235. if (av_compare_ts(ost->next_pts, ost->st->codec->time_base,
  236. STREAM_DURATION, (AVRational){ 1, 1 }) >= 0)
  237. return NULL;
  238. /* when we pass a frame to the encoder, it may keep a reference to it
  239. * internally;
  240. * make sure we do not overwrite it here
  241. */
  242. ret = av_frame_make_writable(ost->frame);
  243. if (ret < 0)
  244. exit(1);
  245. for (j = 0; j < ost->frame->nb_samples; j++) {
  246. v = (int)(sin(ost->t) * 10000);
  247. for (i = 0; i < ost->st->codec->channels; i++)
  248. *q++ = v;
  249. ost->t += ost->tincr;
  250. ost->tincr += ost->tincr2;
  251. }
  252. ost->frame->pts = ost->next_pts;
  253. ost->next_pts += ost->frame->nb_samples;
  254. return ost->frame;
  255. }
  256. /*
  257. * encode one audio frame and send it to the muxer
  258. * return 1 when encoding is finished, 0 otherwise
  259. */
  260. static int write_audio_frame(AVFormatContext *oc, OutputStream *ost)
  261. {
  262. AVCodecContext *c;
  263. AVPacket pkt = { 0 }; // data and size must be 0;
  264. AVFrame *frame;
  265. int ret;
  266. int got_packet;
  267. int dst_nb_samples;
  268. av_init_packet(&pkt);
  269. c = ost->st->codec;
  270. frame = get_audio_frame(ost);
  271. if (frame) {
  272. /* convert samples from native format to destination codec format, using the resampler */
  273. if (ost->swr_ctx) {
  274. /* compute destination number of samples */
  275. dst_nb_samples = av_rescale_rnd(swr_get_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples,
  276. c->sample_rate, c->sample_rate, AV_ROUND_UP);
  277. av_assert0(dst_nb_samples == frame->nb_samples);
  278. /* convert to destination format */
  279. ret = swr_convert(ost->swr_ctx,
  280. ost->tmp_frame->data, dst_nb_samples,
  281. (const uint8_t **)frame->data, frame->nb_samples);
  282. if (ret < 0) {
  283. fprintf(stderr, "Error while converting\n");
  284. exit(1);
  285. }
  286. frame = ost->tmp_frame;
  287. } else {
  288. dst_nb_samples = frame->nb_samples;
  289. }
  290. frame->pts = av_rescale_q(ost->samples_count, (AVRational){1, c->sample_rate}, c->time_base);
  291. ost->samples_count += dst_nb_samples;
  292. }
  293. ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
  294. if (ret < 0) {
  295. fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
  296. exit(1);
  297. }
  298. if (got_packet) {
  299. ret = write_frame(oc, &c->time_base, ost->st, &pkt);
  300. if (ret < 0) {
  301. fprintf(stderr, "Error while writing audio frame: %s\n",
  302. av_err2str(ret));
  303. exit(1);
  304. }
  305. }
  306. return (frame || got_packet) ? 0 : 1;
  307. }
  308. /**************************************************************/
  309. /* video output */
  310. static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
  311. {
  312. AVFrame *picture;
  313. int ret;
  314. picture = av_frame_alloc();
  315. if (!picture)
  316. return NULL;
  317. picture->format = pix_fmt;
  318. picture->width = width;
  319. picture->height = height;
  320. /* allocate the buffers for the frame data */
  321. ret = av_frame_get_buffer(picture, 32);
  322. if (ret < 0) {
  323. fprintf(stderr, "Could not allocate frame data.\n");
  324. exit(1);
  325. }
  326. return picture;
  327. }
  328. static void open_video(AVFormatContext *oc, AVCodec *codec, OutputStream *ost, AVDictionary *opt_arg)
  329. {
  330. int ret;
  331. AVCodecContext *c = ost->st->codec;
  332. AVDictionary *opt = NULL;
  333. av_dict_copy(&opt, opt_arg, 0);
  334. /* open the codec */
  335. ret = avcodec_open2(c, codec, &opt);
  336. av_dict_free(&opt);
  337. if (ret < 0) {
  338. fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
  339. exit(1);
  340. }
  341. /* allocate and init a re-usable frame */
  342. ost->frame = alloc_picture(c->pix_fmt, c->width, c->height);
  343. if (!ost->frame) {
  344. fprintf(stderr, "Could not allocate video frame\n");
  345. exit(1);
  346. }
  347. /* If the output format is not YUV420P, then a temporary YUV420P
  348. * picture is needed too. It is then converted to the required
  349. * output format. */
  350. ost->tmp_frame = NULL;
  351. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  352. ost->tmp_frame = alloc_picture(AV_PIX_FMT_YUV420P, c->width, c->height);
  353. if (!ost->tmp_frame) {
  354. fprintf(stderr, "Could not allocate temporary picture\n");
  355. exit(1);
  356. }
  357. }
  358. }
  359. /* Prepare a dummy image. */
  360. static void fill_yuv_image(AVFrame *pict, int frame_index,
  361. int width, int height)
  362. {
  363. int x, y, i, ret;
  364. /* when we pass a frame to the encoder, it may keep a reference to it
  365. * internally;
  366. * make sure we do not overwrite it here
  367. */
  368. ret = av_frame_make_writable(pict);
  369. if (ret < 0)
  370. exit(1);
  371. i = frame_index;
  372. /* Y */
  373. for (y = 0; y < height; y++)
  374. for (x = 0; x < width; x++)
  375. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
  376. /* Cb and Cr */
  377. for (y = 0; y < height / 2; y++) {
  378. for (x = 0; x < width / 2; x++) {
  379. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
  380. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
  381. }
  382. }
  383. }
  384. static AVFrame *get_video_frame(OutputStream *ost)
  385. {
  386. AVCodecContext *c = ost->st->codec;
  387. /* check if we want to generate more frames */
  388. if (av_compare_ts(ost->next_pts, ost->st->codec->time_base,
  389. STREAM_DURATION, (AVRational){ 1, 1 }) >= 0)
  390. return NULL;
  391. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  392. /* as we only generate a YUV420P picture, we must convert it
  393. * to the codec pixel format if needed */
  394. if (!ost->sws_ctx) {
  395. ost->sws_ctx = sws_getContext(c->width, c->height,
  396. AV_PIX_FMT_YUV420P,
  397. c->width, c->height,
  398. c->pix_fmt,
  399. SCALE_FLAGS, NULL, NULL, NULL);
  400. if (!ost->sws_ctx) {
  401. fprintf(stderr,
  402. "Could not initialize the conversion context\n");
  403. exit(1);
  404. }
  405. }
  406. fill_yuv_image(ost->tmp_frame, ost->next_pts, c->width, c->height);
  407. sws_scale(ost->sws_ctx,
  408. (const uint8_t * const *)ost->tmp_frame->data, ost->tmp_frame->linesize,
  409. 0, c->height, ost->frame->data, ost->frame->linesize);
  410. } else {
  411. fill_yuv_image(ost->frame, ost->next_pts, c->width, c->height);
  412. }
  413. ost->frame->pts = ost->next_pts++;
  414. return ost->frame;
  415. }
  416. /*
  417. * encode one video frame and send it to the muxer
  418. * return 1 when encoding is finished, 0 otherwise
  419. */
  420. static int write_video_frame(AVFormatContext *oc, OutputStream *ost)
  421. {
  422. int ret;
  423. AVCodecContext *c;
  424. AVFrame *frame;
  425. int got_packet = 0;
  426. c = ost->st->codec;
  427. frame = get_video_frame(ost);
  428. if (oc->oformat->flags & AVFMT_RAWPICTURE) {
  429. /* a hack to avoid data copy with some raw video muxers */
  430. AVPacket pkt;
  431. av_init_packet(&pkt);
  432. if (!frame)
  433. return 1;
  434. pkt.flags |= AV_PKT_FLAG_KEY;
  435. pkt.stream_index = ost->st->index;
  436. pkt.data = (uint8_t *)frame;
  437. pkt.size = sizeof(AVPicture);
  438. pkt.pts = pkt.dts = frame->pts;
  439. av_packet_rescale_ts(&pkt, c->time_base, ost->st->time_base);
  440. ret = av_interleaved_write_frame(oc, &pkt);
  441. } else {
  442. AVPacket pkt = { 0 };
  443. av_init_packet(&pkt);
  444. /* encode the image */
  445. ret = avcodec_encode_video2(c, &pkt, frame, &got_packet);
  446. if (ret < 0) {
  447. fprintf(stderr, "Error encoding video frame: %s\n", av_err2str(ret));
  448. exit(1);
  449. }
  450. if (got_packet) {
  451. ret = write_frame(oc, &c->time_base, ost->st, &pkt);
  452. } else {
  453. ret = 0;
  454. }
  455. }
  456. if (ret < 0) {
  457. fprintf(stderr, "Error while writing video frame: %s\n", av_err2str(ret));
  458. exit(1);
  459. }
  460. return (frame || got_packet) ? 0 : 1;
  461. }
  462. static void close_stream(AVFormatContext *oc, OutputStream *ost)
  463. {
  464. avcodec_close(ost->st->codec);
  465. av_frame_free(&ost->frame);
  466. av_frame_free(&ost->tmp_frame);
  467. sws_freeContext(ost->sws_ctx);
  468. swr_free(&ost->swr_ctx);
  469. }
  470. /**************************************************************/
  471. /* media file output */
  472. int main(int argc, char **argv)
  473. {
  474. OutputStream video_st = { 0 }, audio_st = { 0 };
  475. const char *filename;
  476. AVOutputFormat *fmt;
  477. AVFormatContext *oc;
  478. AVCodec *audio_codec, *video_codec;
  479. int ret;
  480. int have_video = 0, have_audio = 0;
  481. int encode_video = 0, encode_audio = 0;
  482. AVDictionary *opt = NULL;
  483. /* Initialize libavcodec, and register all codecs and formats. */
  484. av_register_all();
  485. if (argc < 2) {
  486. printf("usage: %s output_file\n"
  487. "API example program to output a media file with libavformat.\n"
  488. "This program generates a synthetic audio and video stream, encodes and\n"
  489. "muxes them into a file named output_file.\n"
  490. "The output format is automatically guessed according to the file extension.\n"
  491. "Raw images can also be output by using '%%d' in the filename.\n"
  492. "\n", argv[0]);
  493. return 1;
  494. }
  495. filename = argv[1];
  496. if (argc > 3 && !strcmp(argv[2], "-flags")) {
  497. av_dict_set(&opt, argv[2], argv[3], 0);
  498. }
  499. /* allocate the output media context */
  500. avformat_alloc_output_context2(&oc, NULL, NULL, filename);
  501. if (!oc) {
  502. printf("Could not deduce output format from file extension: using MPEG.\n");
  503. avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
  504. }
  505. if (!oc)
  506. return 1;
  507. fmt = oc->oformat;
  508. /* Add the audio and video streams using the default format codecs
  509. * and initialize the codecs. */
  510. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  511. add_stream(&video_st, oc, &video_codec, fmt->video_codec);
  512. have_video = 1;
  513. encode_video = 1;
  514. }
  515. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  516. add_stream(&audio_st, oc, &audio_codec, fmt->audio_codec);
  517. have_audio = 1;
  518. encode_audio = 1;
  519. }
  520. /* Now that all the parameters are set, we can open the audio and
  521. * video codecs and allocate the necessary encode buffers. */
  522. if (have_video)
  523. open_video(oc, video_codec, &video_st, opt);
  524. if (have_audio)
  525. open_audio(oc, audio_codec, &audio_st, opt);
  526. av_dump_format(oc, 0, filename, 1);
  527. /* open the output file, if needed */
  528. if (!(fmt->flags & AVFMT_NOFILE)) {
  529. ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
  530. if (ret < 0) {
  531. fprintf(stderr, "Could not open '%s': %s\n", filename,
  532. av_err2str(ret));
  533. return 1;
  534. }
  535. }
  536. /* Write the stream header, if any. */
  537. ret = avformat_write_header(oc, &opt);
  538. if (ret < 0) {
  539. fprintf(stderr, "Error occurred when opening output file: %s\n",
  540. av_err2str(ret));
  541. return 1;
  542. }
  543. while (encode_video || encode_audio) {
  544. /* select the stream to encode */
  545. if (encode_video &&
  546. (!encode_audio || av_compare_ts(video_st.next_pts, video_st.st->codec->time_base,
  547. audio_st.next_pts, audio_st.st->codec->time_base) <= 0)) {
  548. encode_video = !write_video_frame(oc, &video_st);
  549. } else {
  550. encode_audio = !write_audio_frame(oc, &audio_st);
  551. }
  552. }
  553. /* Write the trailer, if any. The trailer must be written before you
  554. * close the CodecContexts open when you wrote the header; otherwise
  555. * av_write_trailer() may try to use memory that was freed on
  556. * av_codec_close(). */
  557. av_write_trailer(oc);
  558. /* Close each codec. */
  559. if (have_video)
  560. close_stream(oc, &video_st);
  561. if (have_audio)
  562. close_stream(oc, &audio_st);
  563. if (!(fmt->flags & AVFMT_NOFILE))
  564. /* Close the output file. */
  565. avio_close(oc->pb);
  566. /* free the stream */
  567. avformat_free_context(oc);
  568. return 0;
  569. }