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.

525 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. /*
  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, "Could not find codec\n");
  59. exit(1);
  60. }
  61. st = avformat_new_stream(oc, *codec);
  62. if (!st) {
  63. fprintf(stderr, "Could not allocate stream\n");
  64. exit(1);
  65. }
  66. st->id = oc->nb_streams-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 audio 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. if (!samples) {
  100. fprintf(stderr, "Could not allocate audio samples buffer\n");
  101. exit(1);
  102. }
  103. }
  104. /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
  105. * 'nb_channels' channels. */
  106. static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
  107. {
  108. int j, i, v;
  109. int16_t *q;
  110. q = samples;
  111. for (j = 0; j < frame_size; j++) {
  112. v = (int)(sin(t) * 10000);
  113. for (i = 0; i < nb_channels; i++)
  114. *q++ = v;
  115. t += tincr;
  116. tincr += tincr2;
  117. }
  118. }
  119. static void write_audio_frame(AVFormatContext *oc, AVStream *st)
  120. {
  121. AVCodecContext *c;
  122. AVPacket pkt = { 0 }; // data and size must be 0;
  123. AVFrame *frame = avcodec_alloc_frame();
  124. int got_packet, ret;
  125. av_init_packet(&pkt);
  126. c = st->codec;
  127. get_audio_frame(samples, audio_input_frame_size, c->channels);
  128. frame->nb_samples = audio_input_frame_size;
  129. avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
  130. (uint8_t *)samples,
  131. audio_input_frame_size *
  132. av_get_bytes_per_sample(c->sample_fmt) *
  133. c->channels, 1);
  134. ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
  135. if (ret < 0) {
  136. fprintf(stderr, "Error encoding audio frame\n");
  137. exit(1);
  138. }
  139. if (!got_packet)
  140. return;
  141. pkt.stream_index = st->index;
  142. /* Write the compressed frame to the media file. */
  143. if (av_interleaved_write_frame(oc, &pkt) != 0) {
  144. fprintf(stderr, "Error while writing audio frame\n");
  145. exit(1);
  146. }
  147. avcodec_free_frame(&frame);
  148. }
  149. static void close_audio(AVFormatContext *oc, AVStream *st)
  150. {
  151. avcodec_close(st->codec);
  152. av_free(samples);
  153. }
  154. /**************************************************************/
  155. /* video output */
  156. static AVFrame *frame;
  157. static AVPicture src_picture, dst_picture;
  158. static int frame_count;
  159. /* Add a video output stream. */
  160. static AVStream *add_video_stream(AVFormatContext *oc, AVCodec **codec,
  161. enum AVCodecID codec_id)
  162. {
  163. AVCodecContext *c;
  164. AVStream *st;
  165. /* find the video encoder */
  166. *codec = avcodec_find_encoder(codec_id);
  167. if (!(*codec)) {
  168. fprintf(stderr, "codec not found\n");
  169. exit(1);
  170. }
  171. st = avformat_new_stream(oc, *codec);
  172. if (!st) {
  173. fprintf(stderr, "Could not alloc stream\n");
  174. exit(1);
  175. }
  176. st->id = oc->nb_streams-1;
  177. c = st->codec;
  178. avcodec_get_context_defaults3(c, *codec);
  179. c->codec_id = codec_id;
  180. /* Put sample parameters. */
  181. c->bit_rate = 400000;
  182. /* Resolution must be a multiple of two. */
  183. c->width = 352;
  184. c->height = 288;
  185. /* timebase: This is the fundamental unit of time (in seconds) in terms
  186. * of which frame timestamps are represented. For fixed-fps content,
  187. * timebase should be 1/framerate and timestamp increments should be
  188. * identical to 1. */
  189. c->time_base.den = STREAM_FRAME_RATE;
  190. c->time_base.num = 1;
  191. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  192. c->pix_fmt = STREAM_PIX_FMT;
  193. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  194. /* just for testing, we also add B frames */
  195. c->max_b_frames = 2;
  196. }
  197. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
  198. /* Needed to avoid using macroblocks in which some coeffs overflow.
  199. * This does not happen with normal video, it just happens here as
  200. * the motion of the chroma plane does not match the luma plane. */
  201. c->mb_decision = 2;
  202. }
  203. /* Some formats want stream headers to be separate. */
  204. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  205. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  206. return st;
  207. }
  208. static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
  209. {
  210. int ret;
  211. AVCodecContext *c = st->codec;
  212. /* open the codec */
  213. if (avcodec_open2(c, codec, NULL) < 0) {
  214. fprintf(stderr, "Could not open video codec\n");
  215. exit(1);
  216. }
  217. /* allocate and init a re-usable frame */
  218. frame = avcodec_alloc_frame();
  219. if (!frame) {
  220. fprintf(stderr, "Could not allocate video frame\n");
  221. exit(1);
  222. }
  223. /* Allocate the encoded raw picture. */
  224. ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
  225. if (ret < 0) {
  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. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  233. ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
  234. if (ret < 0) {
  235. fprintf(stderr, "Could not allocate temporary picture\n");
  236. exit(1);
  237. }
  238. }
  239. /* copy data and linesize picture pointers to frame */
  240. *((AVPicture *)frame) = dst_picture;
  241. }
  242. /* Prepare a dummy image. */
  243. static void fill_yuv_image(AVPicture *pict, int frame_index,
  244. int width, int height)
  245. {
  246. int x, y, i;
  247. i = frame_index;
  248. /* Y */
  249. for (y = 0; y < height; y++)
  250. for (x = 0; x < width; x++)
  251. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
  252. /* Cb and Cr */
  253. for (y = 0; y < height / 2; y++) {
  254. for (x = 0; x < width / 2; x++) {
  255. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
  256. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
  257. }
  258. }
  259. }
  260. static void write_video_frame(AVFormatContext *oc, AVStream *st)
  261. {
  262. int ret;
  263. static struct SwsContext *sws_ctx;
  264. AVCodecContext *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 (!sws_ctx) {
  274. sws_ctx = sws_getContext(c->width, c->height, AV_PIX_FMT_YUV420P,
  275. c->width, c->height, c->pix_fmt,
  276. sws_flags, NULL, NULL, NULL);
  277. if (!sws_ctx) {
  278. fprintf(stderr,
  279. "Could not initialize the conversion context\n");
  280. exit(1);
  281. }
  282. }
  283. fill_yuv_image(&src_picture, frame_count, c->width, c->height);
  284. sws_scale(sws_ctx,
  285. (const uint8_t * const *)src_picture.data, src_picture.linesize,
  286. 0, c->height, dst_picture.data, dst_picture.linesize);
  287. } else {
  288. fill_yuv_image(&dst_picture, frame_count, c->width, c->height);
  289. }
  290. }
  291. if (oc->oformat->flags & AVFMT_RAWPICTURE) {
  292. /* Raw video case - directly store the picture in the packet */
  293. AVPacket pkt;
  294. av_init_packet(&pkt);
  295. pkt.flags |= AV_PKT_FLAG_KEY;
  296. pkt.stream_index = st->index;
  297. pkt.data = dst_picture.data[0];
  298. pkt.size = sizeof(AVPicture);
  299. ret = av_interleaved_write_frame(oc, &pkt);
  300. } else {
  301. /* encode the image */
  302. AVPacket pkt;
  303. int got_output;
  304. av_init_packet(&pkt);
  305. pkt.data = NULL; // packet data will be allocated by the encoder
  306. pkt.size = 0;
  307. ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
  308. if (ret < 0) {
  309. fprintf(stderr, "Error encoding video frame\n");
  310. exit(1);
  311. }
  312. /* If size is zero, it means the image was buffered. */
  313. if (got_output) {
  314. if (c->coded_frame->key_frame)
  315. pkt.flags |= AV_PKT_FLAG_KEY;
  316. pkt.stream_index = st->index;
  317. /* Write the compressed frame to the media file. */
  318. ret = av_interleaved_write_frame(oc, &pkt);
  319. } else {
  320. ret = 0;
  321. }
  322. }
  323. if (ret != 0) {
  324. fprintf(stderr, "Error while writing video frame\n");
  325. exit(1);
  326. }
  327. frame_count++;
  328. }
  329. static void close_video(AVFormatContext *oc, AVStream *st)
  330. {
  331. avcodec_close(st->codec);
  332. av_free(src_picture.data[0]);
  333. av_free(dst_picture.data[0]);
  334. av_free(frame);
  335. }
  336. /**************************************************************/
  337. /* media file output */
  338. int main(int argc, char **argv)
  339. {
  340. const char *filename;
  341. AVOutputFormat *fmt;
  342. AVFormatContext *oc;
  343. AVStream *audio_st, *video_st;
  344. AVCodec *audio_codec, *video_codec;
  345. double audio_pts, video_pts;
  346. int i;
  347. /* Initialize libavcodec, and register all codecs and formats. */
  348. av_register_all();
  349. if (argc != 2) {
  350. printf("usage: %s output_file\n"
  351. "API example program to output a media file with libavformat.\n"
  352. "This program generates a synthetic audio and video stream, encodes and\n"
  353. "muxes them into a file named output_file.\n"
  354. "The output format is automatically guessed according to the file extension.\n"
  355. "Raw images can also be output by using '%%d' in the filename.\n"
  356. "\n", argv[0]);
  357. return 1;
  358. }
  359. filename = argv[1];
  360. /* allocate the output media context */
  361. avformat_alloc_output_context2(&oc, NULL, NULL, filename);
  362. if (!oc) {
  363. printf("Could not deduce output format from file extension: using MPEG.\n");
  364. avformat_alloc_output_context2(&oc, NULL, "mpeg", filename);
  365. }
  366. if (!oc) {
  367. return 1;
  368. }
  369. fmt = oc->oformat;
  370. /* Add the audio and video streams using the default format codecs
  371. * and initialize the codecs. */
  372. video_st = NULL;
  373. audio_st = NULL;
  374. if (fmt->video_codec != AV_CODEC_ID_NONE) {
  375. video_st = add_video_stream(oc, &video_codec, fmt->video_codec);
  376. }
  377. if (fmt->audio_codec != AV_CODEC_ID_NONE) {
  378. audio_st = add_audio_stream(oc, &audio_codec, fmt->audio_codec);
  379. }
  380. /* Now that all the parameters are set, we can open the audio and
  381. * video codecs and allocate the necessary encode buffers. */
  382. if (video_st)
  383. open_video(oc, video_codec, video_st);
  384. if (audio_st)
  385. open_audio(oc, audio_codec, audio_st);
  386. av_dump_format(oc, 0, filename, 1);
  387. /* open the output file, if needed */
  388. if (!(fmt->flags & AVFMT_NOFILE)) {
  389. if (avio_open(&oc->pb, filename, AVIO_FLAG_WRITE) < 0) {
  390. fprintf(stderr, "Could not open '%s'\n", filename);
  391. return 1;
  392. }
  393. }
  394. /* Write the stream header, if any. */
  395. if (avformat_write_header(oc, NULL) < 0) {
  396. fprintf(stderr, "Error occurred when opening output file\n");
  397. return 1;
  398. }
  399. if (frame)
  400. frame->pts = 0;
  401. for (;;) {
  402. /* Compute current audio and video time. */
  403. if (audio_st)
  404. audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
  405. else
  406. audio_pts = 0.0;
  407. if (video_st)
  408. video_pts = (double)video_st->pts.val * video_st->time_base.num /
  409. video_st->time_base.den;
  410. else
  411. video_pts = 0.0;
  412. if ((!audio_st || audio_pts >= STREAM_DURATION) &&
  413. (!video_st || video_pts >= STREAM_DURATION))
  414. break;
  415. /* write interleaved audio and video frames */
  416. if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
  417. write_audio_frame(oc, audio_st);
  418. } else {
  419. write_video_frame(oc, video_st);
  420. frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base);
  421. }
  422. }
  423. /* Write the trailer, if any. The trailer must be written before you
  424. * close the CodecContexts open when you wrote the header; otherwise
  425. * av_write_trailer() may try to use memory that was freed on
  426. * av_codec_close(). */
  427. av_write_trailer(oc);
  428. /* Close each codec. */
  429. if (video_st)
  430. close_video(oc, video_st);
  431. if (audio_st)
  432. close_audio(oc, audio_st);
  433. /* Free the streams. */
  434. for (i = 0; i < oc->nb_streams; i++) {
  435. av_freep(&oc->streams[i]->codec);
  436. av_freep(&oc->streams[i]);
  437. }
  438. if (!(fmt->flags & AVFMT_NOFILE))
  439. /* Close the output file. */
  440. avio_close(oc->pb);
  441. /* free the stream */
  442. av_free(oc);
  443. return 0;
  444. }