muxing.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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 <libavcodec/avcodec.h>
  40. #include <libavformat/avformat.h>
  41. #include <libswscale/swscale.h>
  42. #include <libswresample/swresample.h>
  43. #define STREAM_DURATION 10.0
  44. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  45. #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
  46. #define SCALE_FLAGS SWS_BICUBIC
  47. // a wrapper around a single output AVStream
  48. typedef struct OutputStream {
  49. AVStream *st;
  50. AVCodecContext *enc;
  51. /* pts of the next frame that will be generated */
  52. int64_t next_pts;
  53. int samples_count;
  54. AVFrame *frame;
  55. AVFrame *tmp_frame;
  56. AVPacket *tmp_pkt;
  57. float t, tincr, tincr2;
  58. struct SwsContext *sws_ctx;
  59. struct SwrContext *swr_ctx;
  60. } OutputStream;
  61. static void log_packet(const AVFormatContext *fmt_ctx, const AVPacket *pkt)
  62. {
  63. AVRational *time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
  64. printf("pts:%s pts_time:%s dts:%s dts_time:%s duration:%s duration_time:%s stream_index:%d\n",
  65. av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, time_base),
  66. av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, time_base),
  67. av_ts2str(pkt->duration), av_ts2timestr(pkt->duration, time_base),
  68. pkt->stream_index);
  69. }
  70. static int write_frame(AVFormatContext *fmt_ctx, AVCodecContext *c,
  71. AVStream *st, AVFrame *frame, AVPacket *pkt)
  72. {
  73. int ret;
  74. // send the frame to the encoder
  75. ret = avcodec_send_frame(c, frame);
  76. if (ret < 0) {
  77. fprintf(stderr, "Error sending a frame to the encoder: %s\n",
  78. av_err2str(ret));
  79. exit(1);
  80. }
  81. while (ret >= 0) {
  82. ret = avcodec_receive_packet(c, pkt);
  83. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  84. break;
  85. else if (ret < 0) {
  86. fprintf(stderr, "Error encoding a frame: %s\n", av_err2str(ret));
  87. exit(1);
  88. }
  89. /* rescale output packet timestamp values from codec to stream timebase */
  90. av_packet_rescale_ts(pkt, c->time_base, st->time_base);
  91. pkt->stream_index = st->index;
  92. /* Write the compressed frame to the media file. */
  93. log_packet(fmt_ctx, pkt);
  94. ret = av_interleaved_write_frame(fmt_ctx, pkt);
  95. /* pkt is now blank (av_interleaved_write_frame() takes ownership of
  96. * its contents and resets pkt), so that no unreferencing is necessary.
  97. * This would be different if one used av_write_frame(). */
  98. if (ret < 0) {
  99. fprintf(stderr, "Error while writing output packet: %s\n", av_err2str(ret));
  100. exit(1);
  101. }
  102. }
  103. return ret == AVERROR_EOF ? 1 : 0;
  104. }
  105. /* Add an output stream. */
  106. static void add_stream(OutputStream *ost, AVFormatContext *oc,
  107. const AVCodec **codec,
  108. enum AVCodecID codec_id)
  109. {
  110. AVCodecContext *c;
  111. int i;
  112. /* find the encoder */
  113. *codec = avcodec_find_encoder(codec_id);
  114. if (!(*codec)) {
  115. fprintf(stderr, "Could not find encoder for '%s'\n",
  116. avcodec_get_name(codec_id));
  117. exit(1);
  118. }
  119. ost->tmp_pkt = av_packet_alloc();
  120. if (!ost->tmp_pkt) {
  121. fprintf(stderr, "Could not allocate AVPacket\n");
  122. exit(1);
  123. }
  124. ost->st = avformat_new_stream(oc, NULL);
  125. if (!ost->st) {
  126. fprintf(stderr, "Could not allocate stream\n");
  127. exit(1);
  128. }
  129. ost->st->id = oc->nb_streams-1;
  130. c = avcodec_alloc_context3(*codec);
  131. if (!c) {
  132. fprintf(stderr, "Could not alloc an encoding context\n");
  133. exit(1);
  134. }
  135. ost->enc = c;
  136. switch ((*codec)->type) {
  137. case AVMEDIA_TYPE_AUDIO:
  138. c->sample_fmt = (*codec)->sample_fmts ?
  139. (*codec)->sample_fmts[0] : AV_SAMPLE_FMT_FLTP;
  140. c->bit_rate = 64000;
  141. c->sample_rate = 44100;
  142. if ((*codec)->supported_samplerates) {
  143. c->sample_rate = (*codec)->supported_samplerates[0];
  144. for (i = 0; (*codec)->supported_samplerates[i]; i++) {
  145. if ((*codec)->supported_samplerates[i] == 44100)
  146. c->sample_rate = 44100;
  147. }
  148. }
  149. av_channel_layout_copy(&c->ch_layout, &(AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO);
  150. ost->st->time_base = (AVRational){ 1, c->sample_rate };
  151. break;
  152. case AVMEDIA_TYPE_VIDEO:
  153. c->codec_id = codec_id;
  154. c->bit_rate = 400000;
  155. /* Resolution must be a multiple of two. */
  156. c->width = 352;
  157. c->height = 288;
  158. /* timebase: This is the fundamental unit of time (in seconds) in terms
  159. * of which frame timestamps are represented. For fixed-fps content,
  160. * timebase should be 1/framerate and timestamp increments should be
  161. * identical to 1. */
  162. ost->st->time_base = (AVRational){ 1, STREAM_FRAME_RATE };
  163. c->time_base = ost->st->time_base;
  164. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  165. c->pix_fmt = STREAM_PIX_FMT;
  166. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  167. /* just for testing, we also add B-frames */
  168. c->max_b_frames = 2;
  169. }
  170. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
  171. /* Needed to avoid using macroblocks in which some coeffs overflow.
  172. * This does not happen with normal video, it just happens here as
  173. * the motion of the chroma plane does not match the luma plane. */
  174. c->mb_decision = 2;
  175. }
  176. break;
  177. default:
  178. break;
  179. }
  180. /* Some formats want stream headers to be separate. */
  181. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  182. c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  183. }
  184. /**************************************************************/
  185. /* audio output */
  186. static AVFrame *alloc_audio_frame(enum AVSampleFormat sample_fmt,
  187. const AVChannelLayout *channel_layout,
  188. int sample_rate, int nb_samples)
  189. {
  190. AVFrame *frame = av_frame_alloc();
  191. int ret;
  192. if (!frame) {
  193. fprintf(stderr, "Error allocating an audio frame\n");
  194. exit(1);
  195. }
  196. frame->format = sample_fmt;
  197. av_channel_layout_copy(&frame->ch_layout, channel_layout);
  198. frame->sample_rate = sample_rate;
  199. frame->nb_samples = nb_samples;
  200. if (nb_samples) {
  201. ret = av_frame_get_buffer(frame, 0);
  202. if (ret < 0) {
  203. fprintf(stderr, "Error allocating an audio buffer\n");
  204. exit(1);
  205. }
  206. }
  207. return frame;
  208. }
  209. static void open_audio(AVFormatContext *oc, const AVCodec *codec,
  210. 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->ch_layout,
  235. c->sample_rate, nb_samples);
  236. ost->tmp_frame = alloc_audio_frame(AV_SAMPLE_FMT_S16, &c->ch_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_chlayout (ost->swr_ctx, "in_chlayout", &c->ch_layout, 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_chlayout (ost->swr_ctx, "out_chlayout", &c->ch_layout, 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->ch_layout.nb_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 = swr_get_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples;
  301. av_assert0(dst_nb_samples == frame->nb_samples);
  302. /* when we pass a frame to the encoder, it may keep a reference to it
  303. * internally;
  304. * make sure we do not overwrite it here
  305. */
  306. ret = av_frame_make_writable(ost->frame);
  307. if (ret < 0)
  308. exit(1);
  309. /* convert to destination format */
  310. ret = swr_convert(ost->swr_ctx,
  311. ost->frame->data, dst_nb_samples,
  312. (const uint8_t **)frame->data, frame->nb_samples);
  313. if (ret < 0) {
  314. fprintf(stderr, "Error while converting\n");
  315. exit(1);
  316. }
  317. frame = ost->frame;
  318. frame->pts = av_rescale_q(ost->samples_count, (AVRational){1, c->sample_rate}, c->time_base);
  319. ost->samples_count += dst_nb_samples;
  320. }
  321. return write_frame(oc, c, ost->st, frame, ost->tmp_pkt);
  322. }
  323. /**************************************************************/
  324. /* video output */
  325. static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
  326. {
  327. AVFrame *picture;
  328. int ret;
  329. picture = av_frame_alloc();
  330. if (!picture)
  331. return NULL;
  332. picture->format = pix_fmt;
  333. picture->width = width;
  334. picture->height = height;
  335. /* allocate the buffers for the frame data */
  336. ret = av_frame_get_buffer(picture, 0);
  337. if (ret < 0) {
  338. fprintf(stderr, "Could not allocate frame data.\n");
  339. exit(1);
  340. }
  341. return picture;
  342. }
  343. static void open_video(AVFormatContext *oc, const AVCodec *codec,
  344. 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), ost->tmp_pkt);
  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. av_packet_free(&ost->tmp_pkt);
  449. sws_freeContext(ost->sws_ctx);
  450. swr_free(&ost->swr_ctx);
  451. }
  452. /**************************************************************/
  453. /* media file output */
  454. int main(int argc, char **argv)
  455. {
  456. OutputStream video_st = { 0 }, audio_st = { 0 };
  457. const AVOutputFormat *fmt;
  458. const char *filename;
  459. AVFormatContext *oc;
  460. const AVCodec *audio_codec, *video_codec;
  461. int ret;
  462. int have_video = 0, have_audio = 0;
  463. int encode_video = 0, encode_audio = 0;
  464. AVDictionary *opt = NULL;
  465. int i;
  466. if (argc < 2) {
  467. printf("usage: %s output_file\n"
  468. "API example program to output a media file with libavformat.\n"
  469. "This program generates a synthetic audio and video stream, encodes and\n"
  470. "muxes them into a file named output_file.\n"
  471. "The output format is automatically guessed according to the file extension.\n"
  472. "Raw images can also be output by using '%%d' in the filename.\n"
  473. "\n", argv[0]);
  474. return 1;
  475. }
  476. filename = argv[1];
  477. for (i = 2; i+1 < argc; i+=2) {
  478. if (!strcmp(argv[i], "-flags") || !strcmp(argv[i], "-fflags"))
  479. av_dict_set(&opt, argv[i]+1, argv[i+1], 0);
  480. }
  481. /* allocate the output media context */
  482. avformat_alloc_output_context2(&oc, NULL, NULL, filename);
  483. if (!oc) {
  484. printf("Could not deduce output format from file extension: using MPEG.\n");
  485. avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
  486. }
  487. if (!oc)
  488. return 1;
  489. fmt = oc->oformat;
  490. /* Add the audio and video streams using the default format codecs
  491. * and initialize the codecs. */
  492. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  493. add_stream(&video_st, oc, &video_codec, fmt->video_codec);
  494. have_video = 1;
  495. encode_video = 1;
  496. }
  497. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  498. add_stream(&audio_st, oc, &audio_codec, fmt->audio_codec);
  499. have_audio = 1;
  500. encode_audio = 1;
  501. }
  502. /* Now that all the parameters are set, we can open the audio and
  503. * video codecs and allocate the necessary encode buffers. */
  504. if (have_video)
  505. open_video(oc, video_codec, &video_st, opt);
  506. if (have_audio)
  507. open_audio(oc, audio_codec, &audio_st, opt);
  508. av_dump_format(oc, 0, filename, 1);
  509. /* open the output file, if needed */
  510. if (!(fmt->flags & AVFMT_NOFILE)) {
  511. ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
  512. if (ret < 0) {
  513. fprintf(stderr, "Could not open '%s': %s\n", filename,
  514. av_err2str(ret));
  515. return 1;
  516. }
  517. }
  518. /* Write the stream header, if any. */
  519. ret = avformat_write_header(oc, &opt);
  520. if (ret < 0) {
  521. fprintf(stderr, "Error occurred when opening output file: %s\n",
  522. av_err2str(ret));
  523. return 1;
  524. }
  525. while (encode_video || encode_audio) {
  526. /* select the stream to encode */
  527. if (encode_video &&
  528. (!encode_audio || av_compare_ts(video_st.next_pts, video_st.enc->time_base,
  529. audio_st.next_pts, audio_st.enc->time_base) <= 0)) {
  530. encode_video = !write_video_frame(oc, &video_st);
  531. } else {
  532. encode_audio = !write_audio_frame(oc, &audio_st);
  533. }
  534. }
  535. av_write_trailer(oc);
  536. /* Close each codec. */
  537. if (have_video)
  538. close_stream(oc, &video_st);
  539. if (have_audio)
  540. close_stream(oc, &audio_st);
  541. if (!(fmt->flags & AVFMT_NOFILE))
  542. /* Close the output file. */
  543. avio_closep(&oc->pb);
  544. /* free the stream */
  545. avformat_free_context(oc);
  546. return 0;
  547. }