muxing.c 20 KB

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