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.

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