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.

572 lines
18KB

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