muxing.c 21 KB

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