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.

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