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.

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