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.

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