encoding.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /*
  2. * Copyright (c) 2001 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. * libavcodec API use example.
  25. *
  26. * Note that libavcodec only handles codecs (mpeg, mpeg4, etc...),
  27. * not file formats (avi, vob, etc...). See library 'libavformat' for the
  28. * format handling
  29. */
  30. #include "libavcodec/avcodec.h"
  31. #include "libavutil/mathematics.h"
  32. #define INBUF_SIZE 4096
  33. #define AUDIO_INBUF_SIZE 20480
  34. #define AUDIO_REFILL_THRESH 4096
  35. /*
  36. * Audio encoding example
  37. */
  38. static void audio_encode_example(const char *filename)
  39. {
  40. AVCodec *codec;
  41. AVCodecContext *c= NULL;
  42. int frame_size, i, j, out_size, outbuf_size;
  43. FILE *f;
  44. short *samples;
  45. float t, tincr;
  46. uint8_t *outbuf;
  47. printf("Audio encoding\n");
  48. /* find the MP2 encoder */
  49. codec = avcodec_find_encoder(CODEC_ID_MP2);
  50. if (!codec) {
  51. fprintf(stderr, "codec not found\n");
  52. exit(1);
  53. }
  54. c = avcodec_alloc_context3(codec);
  55. /* put sample parameters */
  56. c->bit_rate = 64000;
  57. c->sample_rate = 44100;
  58. c->channels = 2;
  59. c->sample_fmt = AV_SAMPLE_FMT_S16;
  60. /* open it */
  61. if (avcodec_open(c, codec) < 0) {
  62. fprintf(stderr, "could not open codec\n");
  63. exit(1);
  64. }
  65. /* the codec gives us the frame size, in samples */
  66. frame_size = c->frame_size;
  67. samples = malloc(frame_size * 2 * c->channels);
  68. outbuf_size = 10000;
  69. outbuf = malloc(outbuf_size);
  70. f = fopen(filename, "wb");
  71. if (!f) {
  72. fprintf(stderr, "could not open %s\n", filename);
  73. exit(1);
  74. }
  75. /* encode a single tone sound */
  76. t = 0;
  77. tincr = 2 * M_PI * 440.0 / c->sample_rate;
  78. for(i=0;i<200;i++) {
  79. for(j=0;j<frame_size;j++) {
  80. samples[2*j] = (int)(sin(t) * 10000);
  81. samples[2*j+1] = samples[2*j];
  82. t += tincr;
  83. }
  84. /* encode the samples */
  85. out_size = avcodec_encode_audio(c, outbuf, outbuf_size, samples);
  86. fwrite(outbuf, 1, out_size, f);
  87. }
  88. fclose(f);
  89. free(outbuf);
  90. free(samples);
  91. avcodec_close(c);
  92. av_free(c);
  93. }
  94. /*
  95. * Audio decoding.
  96. */
  97. static void audio_decode_example(const char *outfilename, const char *filename)
  98. {
  99. AVCodec *codec;
  100. AVCodecContext *c= NULL;
  101. int out_size, len;
  102. FILE *f, *outfile;
  103. uint8_t *outbuf;
  104. uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  105. AVPacket avpkt;
  106. av_init_packet(&avpkt);
  107. printf("Audio decoding\n");
  108. /* find the mpeg audio decoder */
  109. codec = avcodec_find_decoder(CODEC_ID_MP2);
  110. if (!codec) {
  111. fprintf(stderr, "codec not found\n");
  112. exit(1);
  113. }
  114. c = avcodec_alloc_context3(codec);
  115. /* open it */
  116. if (avcodec_open(c, codec) < 0) {
  117. fprintf(stderr, "could not open codec\n");
  118. exit(1);
  119. }
  120. outbuf = malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);
  121. f = fopen(filename, "rb");
  122. if (!f) {
  123. fprintf(stderr, "could not open %s\n", filename);
  124. exit(1);
  125. }
  126. outfile = fopen(outfilename, "wb");
  127. if (!outfile) {
  128. av_free(c);
  129. exit(1);
  130. }
  131. /* decode until eof */
  132. avpkt.data = inbuf;
  133. avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
  134. while (avpkt.size > 0) {
  135. out_size = AVCODEC_MAX_AUDIO_FRAME_SIZE;
  136. len = avcodec_decode_audio3(c, (short *)outbuf, &out_size, &avpkt);
  137. if (len < 0) {
  138. fprintf(stderr, "Error while decoding\n");
  139. exit(1);
  140. }
  141. if (out_size > 0) {
  142. /* if a frame has been decoded, output it */
  143. fwrite(outbuf, 1, out_size, outfile);
  144. }
  145. avpkt.size -= len;
  146. avpkt.data += len;
  147. if (avpkt.size < AUDIO_REFILL_THRESH) {
  148. /* Refill the input buffer, to avoid trying to decode
  149. * incomplete frames. Instead of this, one could also use
  150. * a parser, or use a proper container format through
  151. * libavformat. */
  152. memmove(inbuf, avpkt.data, avpkt.size);
  153. avpkt.data = inbuf;
  154. len = fread(avpkt.data + avpkt.size, 1,
  155. AUDIO_INBUF_SIZE - avpkt.size, f);
  156. if (len > 0)
  157. avpkt.size += len;
  158. }
  159. }
  160. fclose(outfile);
  161. fclose(f);
  162. free(outbuf);
  163. avcodec_close(c);
  164. av_free(c);
  165. }
  166. /*
  167. * Video encoding example
  168. */
  169. static void video_encode_example(const char *filename)
  170. {
  171. AVCodec *codec;
  172. AVCodecContext *c= NULL;
  173. int i, out_size, size, x, y, outbuf_size;
  174. FILE *f;
  175. AVFrame *picture;
  176. uint8_t *outbuf;
  177. printf("Video encoding\n");
  178. /* find the mpeg1 video encoder */
  179. codec = avcodec_find_encoder(CODEC_ID_MPEG1VIDEO);
  180. if (!codec) {
  181. fprintf(stderr, "codec not found\n");
  182. exit(1);
  183. }
  184. c = avcodec_alloc_context3(codec);
  185. picture= avcodec_alloc_frame();
  186. /* put sample parameters */
  187. c->bit_rate = 400000;
  188. /* resolution must be a multiple of two */
  189. c->width = 352;
  190. c->height = 288;
  191. /* frames per second */
  192. c->time_base= (AVRational){1,25};
  193. c->gop_size = 10; /* emit one intra frame every ten frames */
  194. c->max_b_frames=1;
  195. c->pix_fmt = PIX_FMT_YUV420P;
  196. /* open it */
  197. if (avcodec_open(c, codec) < 0) {
  198. fprintf(stderr, "could not open codec\n");
  199. exit(1);
  200. }
  201. f = fopen(filename, "wb");
  202. if (!f) {
  203. fprintf(stderr, "could not open %s\n", filename);
  204. exit(1);
  205. }
  206. /* alloc image and output buffer */
  207. outbuf_size = 100000;
  208. outbuf = malloc(outbuf_size);
  209. /* the image can be allocated by any means and av_image_alloc() is
  210. * just the most convenient way if av_malloc() is to be used */
  211. av_image_alloc(picture->data, picture->linesize,
  212. c->width, c->height, c->pix_fmt, 1);
  213. /* encode 1 second of video */
  214. for(i=0;i<25;i++) {
  215. fflush(stdout);
  216. /* prepare a dummy image */
  217. /* Y */
  218. for(y=0;y<c->height;y++) {
  219. for(x=0;x<c->width;x++) {
  220. picture->data[0][y * picture->linesize[0] + x] = x + y + i * 3;
  221. }
  222. }
  223. /* Cb and Cr */
  224. for(y=0;y<c->height/2;y++) {
  225. for(x=0;x<c->width/2;x++) {
  226. picture->data[1][y * picture->linesize[1] + x] = 128 + y + i * 2;
  227. picture->data[2][y * picture->linesize[2] + x] = 64 + x + i * 5;
  228. }
  229. }
  230. /* encode the image */
  231. out_size = avcodec_encode_video(c, outbuf, outbuf_size, picture);
  232. printf("encoding frame %3d (size=%5d)\n", i, out_size);
  233. fwrite(outbuf, 1, out_size, f);
  234. }
  235. /* get the delayed frames */
  236. for(; out_size; i++) {
  237. fflush(stdout);
  238. out_size = avcodec_encode_video(c, outbuf, outbuf_size, NULL);
  239. printf("write frame %3d (size=%5d)\n", i, out_size);
  240. fwrite(outbuf, 1, out_size, f);
  241. }
  242. /* add sequence end code to have a real mpeg file */
  243. outbuf[0] = 0x00;
  244. outbuf[1] = 0x00;
  245. outbuf[2] = 0x01;
  246. outbuf[3] = 0xb7;
  247. fwrite(outbuf, 1, 4, f);
  248. fclose(f);
  249. free(outbuf);
  250. avcodec_close(c);
  251. av_free(c);
  252. av_free(picture->data[0]);
  253. av_free(picture);
  254. printf("\n");
  255. }
  256. /*
  257. * Video decoding example
  258. */
  259. static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
  260. char *filename)
  261. {
  262. FILE *f;
  263. int i;
  264. f=fopen(filename,"w");
  265. fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
  266. for(i=0;i<ysize;i++)
  267. fwrite(buf + i * wrap,1,xsize,f);
  268. fclose(f);
  269. }
  270. static void video_decode_example(const char *outfilename, const char *filename)
  271. {
  272. AVCodec *codec;
  273. AVCodecContext *c= NULL;
  274. int frame, got_picture, len;
  275. FILE *f;
  276. AVFrame *picture;
  277. uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  278. char buf[1024];
  279. AVPacket avpkt;
  280. av_init_packet(&avpkt);
  281. /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
  282. memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  283. printf("Video decoding\n");
  284. /* find the mpeg1 video decoder */
  285. codec = avcodec_find_decoder(CODEC_ID_MPEG1VIDEO);
  286. if (!codec) {
  287. fprintf(stderr, "codec not found\n");
  288. exit(1);
  289. }
  290. c = avcodec_alloc_context3(codec);
  291. picture= avcodec_alloc_frame();
  292. if(codec->capabilities&CODEC_CAP_TRUNCATED)
  293. c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
  294. /* For some codecs, such as msmpeg4 and mpeg4, width and height
  295. MUST be initialized there because this information is not
  296. available in the bitstream. */
  297. /* open it */
  298. if (avcodec_open(c, codec) < 0) {
  299. fprintf(stderr, "could not open codec\n");
  300. exit(1);
  301. }
  302. /* the codec gives us the frame size, in samples */
  303. f = fopen(filename, "rb");
  304. if (!f) {
  305. fprintf(stderr, "could not open %s\n", filename);
  306. exit(1);
  307. }
  308. frame = 0;
  309. for(;;) {
  310. avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
  311. if (avpkt.size == 0)
  312. break;
  313. /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)
  314. and this is the only method to use them because you cannot
  315. know the compressed data size before analysing it.
  316. BUT some other codecs (msmpeg4, mpeg4) are inherently frame
  317. based, so you must call them with all the data for one
  318. frame exactly. You must also initialize 'width' and
  319. 'height' before initializing them. */
  320. /* NOTE2: some codecs allow the raw parameters (frame size,
  321. sample rate) to be changed at any frame. We handle this, so
  322. you should also take care of it */
  323. /* here, we use a stream based decoder (mpeg1video), so we
  324. feed decoder and see if it could decode a frame */
  325. avpkt.data = inbuf;
  326. while (avpkt.size > 0) {
  327. len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
  328. if (len < 0) {
  329. fprintf(stderr, "Error while decoding frame %d\n", frame);
  330. exit(1);
  331. }
  332. if (got_picture) {
  333. printf("saving frame %3d\n", frame);
  334. fflush(stdout);
  335. /* the picture is allocated by the decoder. no need to
  336. free it */
  337. snprintf(buf, sizeof(buf), outfilename, frame);
  338. pgm_save(picture->data[0], picture->linesize[0],
  339. c->width, c->height, buf);
  340. frame++;
  341. }
  342. avpkt.size -= len;
  343. avpkt.data += len;
  344. }
  345. }
  346. /* some codecs, such as MPEG, transmit the I and P frame with a
  347. latency of one frame. You must do the following to have a
  348. chance to get the last frame of the video */
  349. avpkt.data = NULL;
  350. avpkt.size = 0;
  351. len = avcodec_decode_video2(c, picture, &got_picture, &avpkt);
  352. if (got_picture) {
  353. printf("saving last frame %3d\n", frame);
  354. fflush(stdout);
  355. /* the picture is allocated by the decoder. no need to
  356. free it */
  357. snprintf(buf, sizeof(buf), outfilename, frame);
  358. pgm_save(picture->data[0], picture->linesize[0],
  359. c->width, c->height, buf);
  360. frame++;
  361. }
  362. fclose(f);
  363. avcodec_close(c);
  364. av_free(c);
  365. av_free(picture);
  366. printf("\n");
  367. }
  368. int main(int argc, char **argv)
  369. {
  370. const char *filename;
  371. /* must be called before using avcodec lib */
  372. avcodec_init();
  373. /* register all the codecs */
  374. avcodec_register_all();
  375. if (argc <= 1) {
  376. audio_encode_example("/tmp/test.mp2");
  377. audio_decode_example("/tmp/test.sw", "/tmp/test.mp2");
  378. video_encode_example("/tmp/test.mpg");
  379. filename = "/tmp/test.mpg";
  380. } else {
  381. filename = argv[1];
  382. }
  383. // audio_decode_example("/tmp/test.sw", filename);
  384. video_decode_example("/tmp/test%d.pgm", filename);
  385. return 0;
  386. }