muxing.c 21 KB

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