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.

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