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