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.

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