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.

614 lines
19KB

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