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.

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