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.

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