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.

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