You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

642 lines
20KB

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