mux.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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 = av_rescale_rnd(swr_get_delay(ost->swr_ctx, c->sample_rate) + frame->nb_samples,
  298. c->sample_rate, c->sample_rate, AV_ROUND_UP);
  299. av_assert0(dst_nb_samples == frame->nb_samples);
  300. /* when we pass a frame to the encoder, it may keep a reference to it
  301. * internally;
  302. * make sure we do not overwrite it here
  303. */
  304. ret = av_frame_make_writable(ost->frame);
  305. if (ret < 0)
  306. exit(1);
  307. /* convert to destination format */
  308. ret = swr_convert(ost->swr_ctx,
  309. ost->frame->data, dst_nb_samples,
  310. (const uint8_t **)frame->data, frame->nb_samples);
  311. if (ret < 0) {
  312. fprintf(stderr, "Error while converting\n");
  313. exit(1);
  314. }
  315. frame = ost->frame;
  316. frame->pts = av_rescale_q(ost->samples_count, (AVRational){1, c->sample_rate}, c->time_base);
  317. ost->samples_count += dst_nb_samples;
  318. }
  319. return write_frame(oc, c, ost->st, frame, ost->tmp_pkt);
  320. }
  321. /**************************************************************/
  322. /* video output */
  323. static AVFrame *alloc_frame(enum AVPixelFormat pix_fmt, int width, int height)
  324. {
  325. AVFrame *frame;
  326. int ret;
  327. frame = av_frame_alloc();
  328. if (!frame)
  329. return NULL;
  330. frame->format = pix_fmt;
  331. frame->width = width;
  332. frame->height = height;
  333. /* allocate the buffers for the frame data */
  334. ret = av_frame_get_buffer(frame, 0);
  335. if (ret < 0) {
  336. fprintf(stderr, "Could not allocate frame data.\n");
  337. exit(1);
  338. }
  339. return frame;
  340. }
  341. static void open_video(AVFormatContext *oc, const AVCodec *codec,
  342. OutputStream *ost, AVDictionary *opt_arg)
  343. {
  344. int ret;
  345. AVCodecContext *c = ost->enc;
  346. AVDictionary *opt = NULL;
  347. av_dict_copy(&opt, opt_arg, 0);
  348. /* open the codec */
  349. ret = avcodec_open2(c, codec, &opt);
  350. av_dict_free(&opt);
  351. if (ret < 0) {
  352. fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
  353. exit(1);
  354. }
  355. /* allocate and init a re-usable frame */
  356. ost->frame = alloc_frame(c->pix_fmt, c->width, c->height);
  357. if (!ost->frame) {
  358. fprintf(stderr, "Could not allocate video frame\n");
  359. exit(1);
  360. }
  361. /* If the output format is not YUV420P, then a temporary YUV420P
  362. * picture is needed too. It is then converted to the required
  363. * output format. */
  364. ost->tmp_frame = NULL;
  365. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  366. ost->tmp_frame = alloc_frame(AV_PIX_FMT_YUV420P, c->width, c->height);
  367. if (!ost->tmp_frame) {
  368. fprintf(stderr, "Could not allocate temporary video frame\n");
  369. exit(1);
  370. }
  371. }
  372. /* copy the stream parameters to the muxer */
  373. ret = avcodec_parameters_from_context(ost->st->codecpar, c);
  374. if (ret < 0) {
  375. fprintf(stderr, "Could not copy the stream parameters\n");
  376. exit(1);
  377. }
  378. }
  379. /* Prepare a dummy image. */
  380. static void fill_yuv_image(AVFrame *pict, int frame_index,
  381. int width, int height)
  382. {
  383. int x, y, i;
  384. i = frame_index;
  385. /* Y */
  386. for (y = 0; y < height; y++)
  387. for (x = 0; x < width; x++)
  388. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
  389. /* Cb and Cr */
  390. for (y = 0; y < height / 2; y++) {
  391. for (x = 0; x < width / 2; x++) {
  392. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
  393. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
  394. }
  395. }
  396. }
  397. static AVFrame *get_video_frame(OutputStream *ost)
  398. {
  399. AVCodecContext *c = ost->enc;
  400. /* check if we want to generate more frames */
  401. if (av_compare_ts(ost->next_pts, c->time_base,
  402. STREAM_DURATION, (AVRational){ 1, 1 }) > 0)
  403. return NULL;
  404. /* when we pass a frame to the encoder, it may keep a reference to it
  405. * internally; make sure we do not overwrite it here */
  406. if (av_frame_make_writable(ost->frame) < 0)
  407. exit(1);
  408. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  409. /* as we only generate a YUV420P picture, we must convert it
  410. * to the codec pixel format if needed */
  411. if (!ost->sws_ctx) {
  412. ost->sws_ctx = sws_getContext(c->width, c->height,
  413. AV_PIX_FMT_YUV420P,
  414. c->width, c->height,
  415. c->pix_fmt,
  416. SCALE_FLAGS, NULL, NULL, NULL);
  417. if (!ost->sws_ctx) {
  418. fprintf(stderr,
  419. "Could not initialize the conversion context\n");
  420. exit(1);
  421. }
  422. }
  423. fill_yuv_image(ost->tmp_frame, ost->next_pts, c->width, c->height);
  424. sws_scale(ost->sws_ctx, (const uint8_t * const *) ost->tmp_frame->data,
  425. ost->tmp_frame->linesize, 0, c->height, ost->frame->data,
  426. ost->frame->linesize);
  427. } else {
  428. fill_yuv_image(ost->frame, ost->next_pts, c->width, c->height);
  429. }
  430. ost->frame->pts = ost->next_pts++;
  431. return ost->frame;
  432. }
  433. /*
  434. * encode one video frame and send it to the muxer
  435. * return 1 when encoding is finished, 0 otherwise
  436. */
  437. static int write_video_frame(AVFormatContext *oc, OutputStream *ost)
  438. {
  439. return write_frame(oc, ost->enc, ost->st, get_video_frame(ost), ost->tmp_pkt);
  440. }
  441. static void close_stream(AVFormatContext *oc, OutputStream *ost)
  442. {
  443. avcodec_free_context(&ost->enc);
  444. av_frame_free(&ost->frame);
  445. av_frame_free(&ost->tmp_frame);
  446. av_packet_free(&ost->tmp_pkt);
  447. sws_freeContext(ost->sws_ctx);
  448. swr_free(&ost->swr_ctx);
  449. }
  450. /**************************************************************/
  451. /* media file output */
  452. int main(int argc, char **argv)
  453. {
  454. OutputStream video_st = { 0 }, audio_st = { 0 };
  455. const AVOutputFormat *fmt;
  456. const char *filename;
  457. AVFormatContext *oc;
  458. const AVCodec *audio_codec, *video_codec;
  459. int ret;
  460. int have_video = 0, have_audio = 0;
  461. int encode_video = 0, encode_audio = 0;
  462. AVDictionary *opt = NULL;
  463. int i;
  464. if (argc < 2) {
  465. printf("usage: %s output_file\n"
  466. "API example program to output a media file with libavformat.\n"
  467. "This program generates a synthetic audio and video stream, encodes and\n"
  468. "muxes them into a file named output_file.\n"
  469. "The output format is automatically guessed according to the file extension.\n"
  470. "Raw images can also be output by using '%%d' in the filename.\n"
  471. "\n", argv[0]);
  472. return 1;
  473. }
  474. filename = argv[1];
  475. for (i = 2; i+1 < argc; i+=2) {
  476. if (!strcmp(argv[i], "-flags") || !strcmp(argv[i], "-fflags"))
  477. av_dict_set(&opt, argv[i]+1, argv[i+1], 0);
  478. }
  479. /* allocate the output media context */
  480. avformat_alloc_output_context2(&oc, NULL, NULL, filename);
  481. if (!oc) {
  482. printf("Could not deduce output format from file extension: using MPEG.\n");
  483. avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
  484. }
  485. if (!oc)
  486. return 1;
  487. fmt = oc->oformat;
  488. /* Add the audio and video streams using the default format codecs
  489. * and initialize the codecs. */
  490. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  491. add_stream(&video_st, oc, &video_codec, fmt->video_codec);
  492. have_video = 1;
  493. encode_video = 1;
  494. }
  495. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  496. add_stream(&audio_st, oc, &audio_codec, fmt->audio_codec);
  497. have_audio = 1;
  498. encode_audio = 1;
  499. }
  500. /* Now that all the parameters are set, we can open the audio and
  501. * video codecs and allocate the necessary encode buffers. */
  502. if (have_video)
  503. open_video(oc, video_codec, &video_st, opt);
  504. if (have_audio)
  505. open_audio(oc, audio_codec, &audio_st, opt);
  506. av_dump_format(oc, 0, filename, 1);
  507. /* open the output file, if needed */
  508. if (!(fmt->flags & AVFMT_NOFILE)) {
  509. ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
  510. if (ret < 0) {
  511. fprintf(stderr, "Could not open '%s': %s\n", filename,
  512. av_err2str(ret));
  513. return 1;
  514. }
  515. }
  516. /* Write the stream header, if any. */
  517. ret = avformat_write_header(oc, &opt);
  518. if (ret < 0) {
  519. fprintf(stderr, "Error occurred when opening output file: %s\n",
  520. av_err2str(ret));
  521. return 1;
  522. }
  523. while (encode_video || encode_audio) {
  524. /* select the stream to encode */
  525. if (encode_video &&
  526. (!encode_audio || av_compare_ts(video_st.next_pts, video_st.enc->time_base,
  527. audio_st.next_pts, audio_st.enc->time_base) <= 0)) {
  528. encode_video = !write_video_frame(oc, &video_st);
  529. } else {
  530. encode_audio = !write_audio_frame(oc, &audio_st);
  531. }
  532. }
  533. av_write_trailer(oc);
  534. /* Close each codec. */
  535. if (have_video)
  536. close_stream(oc, &video_st);
  537. if (have_audio)
  538. close_stream(oc, &audio_st);
  539. if (!(fmt->flags & AVFMT_NOFILE))
  540. /* Close the output file. */
  541. avio_closep(&oc->pb);
  542. /* free the stream */
  543. avformat_free_context(oc);
  544. return 0;
  545. }