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.

522 lines
16KB

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