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.

495 lines
14KB

  1. /*
  2. * Libavformat API example: Output a media file in any supported
  3. * libavformat format. The default codecs are used.
  4. *
  5. * Copyright (c) 2003 Fabrice Bellard
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  20. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. */
  25. #include <stdlib.h>
  26. #include <stdio.h>
  27. #include <math.h>
  28. #ifndef M_PI
  29. #define M_PI 3.1415926535897931
  30. #endif
  31. #include "avformat.h"
  32. /* 5 seconds stream duration */
  33. #define STREAM_DURATION 5.0
  34. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  35. #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
  36. /**************************************************************/
  37. /* audio output */
  38. float t, tincr, tincr2;
  39. int16_t *samples;
  40. uint8_t *audio_outbuf;
  41. int audio_outbuf_size;
  42. int audio_input_frame_size;
  43. /*
  44. * add an audio output stream
  45. */
  46. AVStream *add_audio_stream(AVFormatContext *oc, int codec_id)
  47. {
  48. AVCodecContext *c;
  49. AVStream *st;
  50. st = av_new_stream(oc, 1);
  51. if (!st) {
  52. fprintf(stderr, "Could not alloc stream\n");
  53. exit(1);
  54. }
  55. c = &st->codec;
  56. c->codec_id = codec_id;
  57. c->codec_type = CODEC_TYPE_AUDIO;
  58. /* put sample parameters */
  59. c->bit_rate = 64000;
  60. c->sample_rate = 44100;
  61. c->channels = 2;
  62. return st;
  63. }
  64. void open_audio(AVFormatContext *oc, AVStream *st)
  65. {
  66. AVCodecContext *c;
  67. AVCodec *codec;
  68. c = &st->codec;
  69. /* find the audio encoder */
  70. codec = avcodec_find_encoder(c->codec_id);
  71. if (!codec) {
  72. fprintf(stderr, "codec not found\n");
  73. exit(1);
  74. }
  75. /* open it */
  76. if (avcodec_open(c, codec) < 0) {
  77. fprintf(stderr, "could not open codec\n");
  78. exit(1);
  79. }
  80. /* init signal generator */
  81. t = 0;
  82. tincr = 2 * M_PI * 110.0 / c->sample_rate;
  83. /* increment frequency by 110 Hz per second */
  84. tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
  85. audio_outbuf_size = 10000;
  86. audio_outbuf = malloc(audio_outbuf_size);
  87. /* ugly hack for PCM codecs (will be removed ASAP with new PCM
  88. support to compute the input frame size in samples */
  89. if (c->frame_size <= 1) {
  90. audio_input_frame_size = audio_outbuf_size / c->channels;
  91. switch(st->codec.codec_id) {
  92. case CODEC_ID_PCM_S16LE:
  93. case CODEC_ID_PCM_S16BE:
  94. case CODEC_ID_PCM_U16LE:
  95. case CODEC_ID_PCM_U16BE:
  96. audio_input_frame_size >>= 1;
  97. break;
  98. default:
  99. break;
  100. }
  101. } else {
  102. audio_input_frame_size = c->frame_size;
  103. }
  104. samples = malloc(audio_input_frame_size * 2 * c->channels);
  105. }
  106. /* prepare a 16 bit dummy audio frame of 'frame_size' samples and
  107. 'nb_channels' channels */
  108. void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
  109. {
  110. int j, i, v;
  111. int16_t *q;
  112. q = samples;
  113. for(j=0;j<frame_size;j++) {
  114. v = (int)(sin(t) * 10000);
  115. for(i = 0; i < nb_channels; i++)
  116. *q++ = v;
  117. t += tincr;
  118. tincr += tincr2;
  119. }
  120. }
  121. void write_audio_frame(AVFormatContext *oc, AVStream *st)
  122. {
  123. int out_size;
  124. AVCodecContext *c;
  125. c = &st->codec;
  126. get_audio_frame(samples, audio_input_frame_size, c->channels);
  127. out_size = avcodec_encode_audio(c, audio_outbuf, audio_outbuf_size, samples);
  128. /* write the compressed frame in the media file */
  129. if (av_write_frame(oc, st->index, audio_outbuf, out_size) != 0) {
  130. fprintf(stderr, "Error while writing audio frame\n");
  131. exit(1);
  132. }
  133. }
  134. void close_audio(AVFormatContext *oc, AVStream *st)
  135. {
  136. avcodec_close(&st->codec);
  137. av_free(samples);
  138. av_free(audio_outbuf);
  139. }
  140. /**************************************************************/
  141. /* video output */
  142. AVFrame *picture, *tmp_picture;
  143. uint8_t *video_outbuf;
  144. int frame_count, video_outbuf_size;
  145. /* add a video output stream */
  146. AVStream *add_video_stream(AVFormatContext *oc, int codec_id)
  147. {
  148. AVCodecContext *c;
  149. AVStream *st;
  150. st = av_new_stream(oc, 0);
  151. if (!st) {
  152. fprintf(stderr, "Could not alloc stream\n");
  153. exit(1);
  154. }
  155. c = &st->codec;
  156. c->codec_id = codec_id;
  157. c->codec_type = CODEC_TYPE_VIDEO;
  158. /* put sample parameters */
  159. c->bit_rate = 400000;
  160. /* resolution must be a multiple of two */
  161. c->width = 352;
  162. c->height = 288;
  163. /* frames per second */
  164. c->frame_rate = STREAM_FRAME_RATE;
  165. c->frame_rate_base = 1;
  166. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  167. if (c->codec_id == CODEC_ID_MPEG1VIDEO ||
  168. c->codec_id == CODEC_ID_MPEG2VIDEO) {
  169. /* just for testing, we also add B frames */
  170. c->max_b_frames = 2;
  171. }
  172. return st;
  173. }
  174. AVFrame *alloc_picture(int pix_fmt, int width, int height)
  175. {
  176. AVFrame *picture;
  177. uint8_t *picture_buf;
  178. int size;
  179. picture = avcodec_alloc_frame();
  180. if (!picture)
  181. return NULL;
  182. size = avpicture_get_size(pix_fmt, width, height);
  183. picture_buf = malloc(size);
  184. if (!picture_buf) {
  185. av_free(picture);
  186. return NULL;
  187. }
  188. avpicture_fill((AVPicture *)picture, picture_buf,
  189. pix_fmt, width, height);
  190. return picture;
  191. }
  192. void open_video(AVFormatContext *oc, AVStream *st)
  193. {
  194. AVCodec *codec;
  195. AVCodecContext *c;
  196. c = &st->codec;
  197. /* find the video encoder */
  198. codec = avcodec_find_encoder(c->codec_id);
  199. if (!codec) {
  200. fprintf(stderr, "codec not found\n");
  201. exit(1);
  202. }
  203. /* open the codec */
  204. if (avcodec_open(c, codec) < 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. video_outbuf_size = 200000;
  213. video_outbuf = malloc(video_outbuf_size);
  214. }
  215. /* allocate the encoded raw picture */
  216. picture = alloc_picture(c->pix_fmt, c->width, c->height);
  217. if (!picture) {
  218. fprintf(stderr, "Could not allocate picture\n");
  219. exit(1);
  220. }
  221. /* if the output format is not YUV420P, then a temporary YUV420P
  222. picture is needed too. It is then converted to the required
  223. output format */
  224. tmp_picture = NULL;
  225. if (c->pix_fmt != PIX_FMT_YUV420P) {
  226. tmp_picture = alloc_picture(PIX_FMT_YUV420P, c->width, c->height);
  227. if (!tmp_picture) {
  228. fprintf(stderr, "Could not allocate temporary picture\n");
  229. exit(1);
  230. }
  231. }
  232. }
  233. /* prepare a dummy image */
  234. void fill_yuv_image(AVFrame *pict, int frame_index, int width, int height)
  235. {
  236. int x, y, i;
  237. i = frame_index;
  238. /* Y */
  239. for(y=0;y<height;y++) {
  240. for(x=0;x<width;x++) {
  241. pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
  242. }
  243. }
  244. /* Cb and Cr */
  245. for(y=0;y<height/2;y++) {
  246. for(x=0;x<width/2;x++) {
  247. pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
  248. pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
  249. }
  250. }
  251. }
  252. void write_video_frame(AVFormatContext *oc, AVStream *st)
  253. {
  254. int out_size, ret;
  255. AVCodecContext *c;
  256. AVFrame *picture_ptr;
  257. c = &st->codec;
  258. if (frame_count >= STREAM_NB_FRAMES) {
  259. /* no more frame to compress. The codec has a latency of a few
  260. frames if using B frames, so we get the last frames by
  261. passing a NULL picture */
  262. picture_ptr = NULL;
  263. } else {
  264. if (c->pix_fmt != PIX_FMT_YUV420P) {
  265. /* as we only generate a YUV420P picture, we must convert it
  266. to the codec pixel format if needed */
  267. fill_yuv_image(tmp_picture, frame_count, c->width, c->height);
  268. img_convert((AVPicture *)picture, c->pix_fmt,
  269. (AVPicture *)tmp_picture, PIX_FMT_YUV420P,
  270. c->width, c->height);
  271. } else {
  272. fill_yuv_image(picture, frame_count, c->width, c->height);
  273. }
  274. picture_ptr = picture;
  275. }
  276. if (oc->oformat->flags & AVFMT_RAWPICTURE) {
  277. /* raw video case. The API will change slightly in the near
  278. futur for that */
  279. ret = av_write_frame(oc, st->index,
  280. (uint8_t *)picture_ptr, sizeof(AVPicture));
  281. } else {
  282. /* encode the image */
  283. out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture_ptr);
  284. /* if zero size, it means the image was buffered */
  285. if (out_size != 0) {
  286. /* write the compressed frame in the media file */
  287. /* XXX: in case of B frames, the pts is not yet valid */
  288. ret = av_write_frame(oc, st->index, video_outbuf, out_size);
  289. } else {
  290. ret = 0;
  291. }
  292. }
  293. if (ret != 0) {
  294. fprintf(stderr, "Error while writing video frame\n");
  295. exit(1);
  296. }
  297. frame_count++;
  298. }
  299. void close_video(AVFormatContext *oc, AVStream *st)
  300. {
  301. avcodec_close(&st->codec);
  302. av_free(picture->data[0]);
  303. av_free(picture);
  304. if (tmp_picture) {
  305. av_free(tmp_picture->data[0]);
  306. av_free(tmp_picture);
  307. }
  308. av_free(video_outbuf);
  309. }
  310. /**************************************************************/
  311. /* media file output */
  312. int main(int argc, char **argv)
  313. {
  314. const char *filename;
  315. AVOutputFormat *fmt;
  316. AVFormatContext *oc;
  317. AVStream *audio_st, *video_st;
  318. double audio_pts, video_pts;
  319. int i;
  320. /* initialize libavcodec, and register all codecs and formats */
  321. av_register_all();
  322. if (argc != 2) {
  323. printf("usage: %s output_file\n"
  324. "API example program to output a media file with libavformat.\n"
  325. "The output format is automatically guessed according to the file extension.\n"
  326. "Raw images can also be output by using '%%d' in the filename\n"
  327. "\n", argv[0]);
  328. exit(1);
  329. }
  330. filename = argv[1];
  331. /* auto detect the output format from the name. default is
  332. mpeg. */
  333. fmt = guess_format(NULL, filename, NULL);
  334. if (!fmt) {
  335. printf("Could not deduce output format from file extension: using MPEG.\n");
  336. fmt = guess_format("mpeg", NULL, NULL);
  337. }
  338. if (!fmt) {
  339. fprintf(stderr, "Could not find suitable output format\n");
  340. exit(1);
  341. }
  342. /* allocate the output media context */
  343. oc = av_mallocz(sizeof(AVFormatContext));
  344. if (!oc) {
  345. fprintf(stderr, "Memory error\n");
  346. exit(1);
  347. }
  348. oc->oformat = fmt;
  349. snprintf(oc->filename, sizeof(oc->filename), "%s", filename);
  350. /* add the audio and video streams using the default format codecs
  351. and initialize the codecs */
  352. video_st = NULL;
  353. audio_st = NULL;
  354. if (fmt->video_codec != CODEC_ID_NONE) {
  355. video_st = add_video_stream(oc, fmt->video_codec);
  356. }
  357. if (fmt->audio_codec != CODEC_ID_NONE) {
  358. audio_st = add_audio_stream(oc, fmt->audio_codec);
  359. }
  360. /* set the output parameters (must be done even if no
  361. parameters). */
  362. if (av_set_parameters(oc, NULL) < 0) {
  363. fprintf(stderr, "Invalid output format parameters\n");
  364. exit(1);
  365. }
  366. dump_format(oc, 0, filename, 1);
  367. /* now that all the parameters are set, we can open the audio and
  368. video codecs and allocate the necessary encode buffers */
  369. if (video_st)
  370. open_video(oc, video_st);
  371. if (audio_st)
  372. open_audio(oc, audio_st);
  373. /* open the output file, if needed */
  374. if (!(fmt->flags & AVFMT_NOFILE)) {
  375. if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
  376. fprintf(stderr, "Could not open '%s'\n", filename);
  377. exit(1);
  378. }
  379. }
  380. /* write the stream header, if any */
  381. av_write_header(oc);
  382. for(;;) {
  383. /* compute current audio and video time */
  384. if (audio_st)
  385. audio_pts = (double)audio_st->pts.val * oc->pts_num / oc->pts_den;
  386. else
  387. audio_pts = 0.0;
  388. if (video_st)
  389. video_pts = (double)video_st->pts.val * oc->pts_num / oc->pts_den;
  390. else
  391. video_pts = 0.0;
  392. if ((!audio_st || audio_pts >= STREAM_DURATION) &&
  393. (!video_st || video_pts >= STREAM_DURATION))
  394. break;
  395. /* write interleaved audio and video frames */
  396. if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
  397. write_audio_frame(oc, audio_st);
  398. } else {
  399. write_video_frame(oc, video_st);
  400. }
  401. }
  402. /* close each codec */
  403. if (video_st)
  404. close_video(oc, video_st);
  405. if (audio_st)
  406. close_audio(oc, audio_st);
  407. /* write the trailer, if any */
  408. av_write_trailer(oc);
  409. /* free the streams */
  410. for(i = 0; i < oc->nb_streams; i++) {
  411. av_freep(&oc->streams[i]);
  412. }
  413. if (!(fmt->flags & AVFMT_NOFILE)) {
  414. /* close the output file */
  415. url_fclose(&oc->pb);
  416. }
  417. /* free the stream */
  418. av_free(oc);
  419. return 0;
  420. }