mux.c 20 KB

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