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.

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