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