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.

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