Discuz! Board

 找回密码
 
搜索
查看: 15771|回复: 17

ffmpeg 示例代码大全

[复制链接]

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
发表于 2013-2-25 15:59:55 | 显示全部楼层 |阅读模式
号称大全,其实远不是“大全”,不过,我会把我能找到的一些简单代码摘录下来,一起放到这儿,以方便一些新手,新入门者的参考。

若你手头也有一些入门代码,希望你也能把它贴上来,以方便所有人。

我为人人,人人为我。

注:其实这些ffmpeg自身有提供非常全面的文档(URL: http://ffmpeg.org/doxygen/trunk/index.html),详细到具体每个文件、每个结构体的定义,只不是这些文档都是english,因此老是有一些english不太好的童鞋到群里问这个问那个。。。还有一些人,干脆就是连Google, Baidu都懒得用,真是无奈。好吧,我就为懒人们再作点贡献吧。

拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:19:15 | 显示全部楼层

ffmpeg 示例代码大全 - decoding_encoding.c

  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. #include <math.h>
  23. #include <libavutil/opt.h>
  24. #include <libavcodec/avcodec.h>
  25. #include <libavutil/channel_layout.h>
  26. #include <libavutil/common.h>
  27. #include <libavutil/imgutils.h>
  28. #include <libavutil/mathematics.h>
  29. #include <libavutil/samplefmt.h>
  30. #define INBUF_SIZE 4096
  31. #define AUDIO_INBUF_SIZE 20480
  32. #define AUDIO_REFILL_THRESH 4096
  33. /* check that a given sample format is supported by the encoder */
  34. static int check_sample_fmt(AVCodec *codec, enum AVSampleFormat sample_fmt)
  35. {
  36. const enum AVSampleFormat *p = codec->sample_fmts;
  37. while (*p != AV_SAMPLE_FMT_NONE) {
  38. if (*p == sample_fmt)
  39. return 1;
  40. p++;
  41. }
  42. return 0;
  43. }
  44. /* just pick the highest supported samplerate */
  45. static int select_sample_rate(AVCodec *codec)
  46. {
  47. const int *p;
  48. int best_samplerate = 0;
  49. if (!codec->supported_samplerates)
  50. return 44100;
  51. p = codec->supported_samplerates;
  52. while (*p) {
  53. best_samplerate = FFMAX(*p, best_samplerate);
  54. p++;
  55. }
  56. return best_samplerate;
  57. }
  58. /* select layout with the highest channel count */
  59. static int select_channel_layout(AVCodec *codec)
  60. {
  61. const uint64_t *p;
  62. uint64_t best_ch_layout = 0;
  63. int best_nb_channells = 0;
  64. if (!codec->channel_layouts)
  65. return AV_CH_LAYOUT_STEREO;
  66. p = codec->channel_layouts;
  67. while (*p) {
  68. int nb_channels = av_get_channel_layout_nb_channels(*p);
  69. if (nb_channels > best_nb_channells) {
  70. best_ch_layout = *p;
  71. best_nb_channells = nb_channels;
  72. }
  73. p++;
  74. }
  75. return best_ch_layout;
  76. }
  77. /*
  78. * Audio encoding example
  79. */
  80. static void audio_encode_example(const char *filename)
  81. {
  82. AVCodec *codec;
  83. AVCodecContext *c= NULL;
  84. AVFrame *frame;
  85. AVPacket pkt;
  86. int i, j, k, ret, got_output;
  87. int buffer_size;
  88. FILE *f;
  89. uint16_t *samples;
  90. float t, tincr;
  91. printf("Encode audio file %s\n", filename);
  92. /* find the MP2 encoder */
  93. codec = avcodec_find_encoder(AV_CODEC_ID_MP2);
  94. if (!codec) {
  95. fprintf(stderr, "Codec not found\n");
  96. exit(1);
  97. }
  98. c = avcodec_alloc_context3(codec);
  99. if (!c) {
  100. fprintf(stderr, "Could not allocate audio codec context\n");
  101. exit(1);
  102. }
  103. /* put sample parameters */
  104. c->bit_rate = 64000;
  105. /* check that the encoder supports s16 pcm input */
  106. c->sample_fmt = AV_SAMPLE_FMT_S16;
  107. if (!check_sample_fmt(codec, c->sample_fmt)) {
  108. fprintf(stderr, "Encoder does not support sample format %s",
  109. av_get_sample_fmt_name(c->sample_fmt));
  110. exit(1);
  111. }
  112. /* select other audio parameters supported by the encoder */
  113. c->sample_rate = select_sample_rate(codec);
  114. c->channel_layout = select_channel_layout(codec);
  115. c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
  116. /* open it */
  117. if (avcodec_open2(c, codec, NULL) < 0) {
  118. fprintf(stderr, "Could not open codec\n");
  119. exit(1);
  120. }
  121. f = fopen(filename, "wb");
  122. if (!f) {
  123. fprintf(stderr, "Could not open %s\n", filename);
  124. exit(1);
  125. }
  126. /* frame containing input raw audio */
  127. frame = avcodec_alloc_frame();
  128. if (!frame) {
  129. fprintf(stderr, "Could not allocate audio frame\n");
  130. exit(1);
  131. }
  132. frame->nb_samples = c->frame_size;
  133. frame->format = c->sample_fmt;
  134. frame->channel_layout = c->channel_layout;
  135. /* the codec gives us the frame size, in samples,
  136. * we calculate the size of the samples buffer in bytes */
  137. buffer_size = av_samples_get_buffer_size(NULL, c->channels, c->frame_size,
  138. c->sample_fmt, 0);
  139. samples = av_malloc(buffer_size);
  140. if (!samples) {
  141. fprintf(stderr, "Could not allocate %d bytes for samples buffer\n",
  142. buffer_size);
  143. exit(1);
  144. }
  145. /* setup the data pointers in the AVFrame */
  146. ret = avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
  147. (const uint8_t*)samples, buffer_size, 0);
  148. if (ret < 0) {
  149. fprintf(stderr, "Could not setup audio frame\n");
  150. exit(1);
  151. }
  152. /* encode a single tone sound */
  153. t = 0;
  154. tincr = 2 * M_PI * 440.0 / c->sample_rate;
  155. for(i=0;i<200;i++) {
  156. av_init_packet(&pkt);
  157. pkt.data = NULL; // packet data will be allocated by the encoder
  158. pkt.size = 0;
  159. for (j = 0; j < c->frame_size; j++) {
  160. samples[2*j] = (int)(sin(t) * 10000);
  161. for (k = 1; k < c->channels; k++)
  162. samples[2*j + k] = samples[2*j];
  163. t += tincr;
  164. }
  165. /* encode the samples */
  166. ret = avcodec_encode_audio2(c, &pkt, frame, &got_output);
  167. if (ret < 0) {
  168. fprintf(stderr, "Error encoding audio frame\n");
  169. exit(1);
  170. }
  171. if (got_output) {
  172. fwrite(pkt.data, 1, pkt.size, f);
  173. av_free_packet(&pkt);
  174. }
  175. }
  176. /* get the delayed frames */
  177. for (got_output = 1; got_output; i++) {
  178. ret = avcodec_encode_audio2(c, &pkt, NULL, &got_output);
  179. if (ret < 0) {
  180. fprintf(stderr, "Error encoding frame\n");
  181. exit(1);
  182. }
  183. if (got_output) {
  184. fwrite(pkt.data, 1, pkt.size, f);
  185. av_free_packet(&pkt);
  186. }
  187. }
  188. fclose(f);
  189. av_freep(&samples);
  190. avcodec_free_frame(&frame);
  191. avcodec_close(c);
  192. av_free(c);
  193. }
  194. /*
  195. * Audio decoding.
  196. */
  197. static void audio_decode_example(const char *outfilename, const char *filename)
  198. {
  199. AVCodec *codec;
  200. AVCodecContext *c= NULL;
  201. int len;
  202. FILE *f, *outfile;
  203. uint8_t inbuf[AUDIO_INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  204. AVPacket avpkt;
  205. AVFrame *decoded_frame = NULL;
  206. av_init_packet(&avpkt);
  207. printf("Decode audio file %s to %s\n", filename, outfilename);
  208. /* find the mpeg audio decoder */
  209. codec = avcodec_find_decoder(AV_CODEC_ID_MP2);
  210. if (!codec) {
  211. fprintf(stderr, "Codec not found\n");
  212. exit(1);
  213. }
  214. c = avcodec_alloc_context3(codec);
  215. if (!c) {
  216. fprintf(stderr, "Could not allocate audio codec context\n");
  217. exit(1);
  218. }
  219. /* open it */
  220. if (avcodec_open2(c, codec, NULL) < 0) {
  221. fprintf(stderr, "Could not open codec\n");
  222. exit(1);
  223. }
  224. f = fopen(filename, "rb");
  225. if (!f) {
  226. fprintf(stderr, "Could not open %s\n", filename);
  227. exit(1);
  228. }
  229. outfile = fopen(outfilename, "wb");
  230. if (!outfile) {
  231. av_free(c);
  232. exit(1);
  233. }
  234. /* decode until eof */
  235. avpkt.data = inbuf;
  236. avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);
  237. while (avpkt.size > 0) {
  238. int got_frame = 0;
  239. if (!decoded_frame) {
  240. if (!(decoded_frame = avcodec_alloc_frame())) {
  241. fprintf(stderr, "Could not allocate audio frame\n");
  242. exit(1);
  243. }
  244. } else
  245. avcodec_get_frame_defaults(decoded_frame);
  246. len = avcodec_decode_audio4(c, decoded_frame, &got_frame, &avpkt);
  247. if (len < 0) {
  248. fprintf(stderr, "Error while decoding\n");
  249. exit(1);
  250. }
  251. if (got_frame) {
  252. /* if a frame has been decoded, output it */
  253. int data_size = av_samples_get_buffer_size(NULL, c->channels,
  254. decoded_frame->nb_samples,
  255. c->sample_fmt, 1);
  256. fwrite(decoded_frame->data[0], 1, data_size, outfile);
  257. }
  258. avpkt.size -= len;
  259. avpkt.data += len;
  260. avpkt.dts =
  261. avpkt.pts = AV_NOPTS_VALUE;
  262. if (avpkt.size < AUDIO_REFILL_THRESH) {
  263. /* Refill the input buffer, to avoid trying to decode
  264. * incomplete frames. Instead of this, one could also use
  265. * a parser, or use a proper container format through
  266. * libavformat. */
  267. memmove(inbuf, avpkt.data, avpkt.size);
  268. avpkt.data = inbuf;
  269. len = fread(avpkt.data + avpkt.size, 1,
  270. AUDIO_INBUF_SIZE - avpkt.size, f);
  271. if (len > 0)
  272. avpkt.size += len;
  273. }
  274. }
  275. fclose(outfile);
  276. fclose(f);
  277. avcodec_close(c);
  278. av_free(c);
  279. avcodec_free_frame(&decoded_frame);
  280. }
  281. /*
  282. * Video encoding example
  283. */
  284. static void video_encode_example(const char *filename, int codec_id)
  285. {
  286. AVCodec *codec;
  287. AVCodecContext *c= NULL;
  288. int i, ret, x, y, got_output;
  289. FILE *f;
  290. AVFrame *frame;
  291. AVPacket pkt;
  292. uint8_t endcode[] = { 0, 0, 1, 0xb7 };
  293. printf("Encode video file %s\n", filename);
  294. /* find the mpeg1 video encoder */
  295. codec = avcodec_find_encoder(codec_id);
  296. if (!codec) {
  297. fprintf(stderr, "Codec not found\n");
  298. exit(1);
  299. }
  300. c = avcodec_alloc_context3(codec);
  301. if (!c) {
  302. fprintf(stderr, "Could not allocate video codec context\n");
  303. exit(1);
  304. }
  305. /* put sample parameters */
  306. c->bit_rate = 400000;
  307. /* resolution must be a multiple of two */
  308. c->width = 352;
  309. c->height = 288;
  310. /* frames per second */
  311. c->time_base= (AVRational){1,25};
  312. c->gop_size = 10; /* emit one intra frame every ten frames */
  313. c->max_b_frames=1;
  314. c->pix_fmt = AV_PIX_FMT_YUV420P;
  315. if(codec_id == AV_CODEC_ID_H264)
  316. av_opt_set(c->priv_data, "preset", "slow", 0);
  317. /* open it */
  318. if (avcodec_open2(c, codec, NULL) < 0) {
  319. fprintf(stderr, "Could not open codec\n");
  320. exit(1);
  321. }
  322. f = fopen(filename, "wb");
  323. if (!f) {
  324. fprintf(stderr, "Could not open %s\n", filename);
  325. exit(1);
  326. }
  327. frame = avcodec_alloc_frame();
  328. if (!frame) {
  329. fprintf(stderr, "Could not allocate video frame\n");
  330. exit(1);
  331. }
  332. frame->format = c->pix_fmt;
  333. frame->width = c->width;
  334. frame->height = c->height;
  335. /* the image can be allocated by any means and av_image_alloc() is
  336. * just the most convenient way if av_malloc() is to be used */
  337. ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height,
  338. c->pix_fmt, 32);
  339. if (ret < 0) {
  340. fprintf(stderr, "Could not allocate raw picture buffer\n");
  341. exit(1);
  342. }
  343. /* encode 1 second of video */
  344. for(i=0;i<25;i++) {
  345. av_init_packet(&pkt);
  346. pkt.data = NULL; // packet data will be allocated by the encoder
  347. pkt.size = 0;
  348. fflush(stdout);
  349. /* prepare a dummy image */
  350. /* Y */
  351. for(y=0;y<c->height;y++) {
  352. for(x=0;x<c->width;x++) {
  353. frame->data[0][y * frame->linesize[0] + x] = x + y + i * 3;
  354. }
  355. }
  356. /* Cb and Cr */
  357. for(y=0;y<c->height/2;y++) {
  358. for(x=0;x<c->width/2;x++) {
  359. frame->data[1][y * frame->linesize[1] + x] = 128 + y + i * 2;
  360. frame->data[2][y * frame->linesize[2] + x] = 64 + x + i * 5;
  361. }
  362. }
  363. frame->pts = i;
  364. /* encode the image */
  365. ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
  366. if (ret < 0) {
  367. fprintf(stderr, "Error encoding frame\n");
  368. exit(1);
  369. }
  370. if (got_output) {
  371. printf("Write frame %3d (size=%5d)\n", i, pkt.size);
  372. fwrite(pkt.data, 1, pkt.size, f);
  373. av_free_packet(&pkt);
  374. }
  375. }
  376. /* get the delayed frames */
  377. for (got_output = 1; got_output; i++) {
  378. fflush(stdout);
  379. ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
  380. if (ret < 0) {
  381. fprintf(stderr, "Error encoding frame\n");
  382. exit(1);
  383. }
  384. if (got_output) {
  385. printf("Write frame %3d (size=%5d)\n", i, pkt.size);
  386. fwrite(pkt.data, 1, pkt.size, f);
  387. av_free_packet(&pkt);
  388. }
  389. }
  390. /* add sequence end code to have a real mpeg file */
  391. fwrite(endcode, 1, sizeof(endcode), f);
  392. fclose(f);
  393. avcodec_close(c);
  394. av_free(c);
  395. av_freep(&frame->data[0]);
  396. avcodec_free_frame(&frame);
  397. printf("\n");
  398. }
  399. /*
  400. * Video decoding example
  401. */
  402. static void pgm_save(unsigned char *buf, int wrap, int xsize, int ysize,
  403. char *filename)
  404. {
  405. FILE *f;
  406. int i;
  407. f=fopen(filename,"w");
  408. fprintf(f,"P5\n%d %d\n%d\n",xsize,ysize,255);
  409. for(i=0;i<ysize;i++)
  410. fwrite(buf + i * wrap,1,xsize,f);
  411. fclose(f);
  412. }
  413. static int decode_write_frame(const char *outfilename, AVCodecContext *avctx,
  414. AVFrame *frame, int *frame_count, AVPacket *pkt, int last)
  415. {
  416. int len, got_frame;
  417. char buf[1024];
  418. len = avcodec_decode_video2(avctx, frame, &got_frame, pkt);
  419. if (len < 0) {
  420. fprintf(stderr, "Error while decoding frame %d\n", *frame_count);
  421. return len;
  422. }
  423. if (got_frame) {
  424. printf("Saving %sframe %3d\n", last ? "last " : "", *frame_count);
  425. fflush(stdout);
  426. /* the picture is allocated by the decoder, no need to free it */
  427. snprintf(buf, sizeof(buf), outfilename, *frame_count);
  428. pgm_save(frame->data[0], frame->linesize[0],
  429. avctx->width, avctx->height, buf);
  430. (*frame_count)++;
  431. }
  432. if (pkt->data) {
  433. pkt->size -= len;
  434. pkt->data += len;
  435. }
  436. return 0;
  437. }
  438. static void video_decode_example(const char *outfilename, const char *filename)
  439. {
  440. AVCodec *codec;
  441. AVCodecContext *c= NULL;
  442. int frame_count;
  443. FILE *f;
  444. AVFrame *frame;
  445. uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE];
  446. AVPacket avpkt;
  447. av_init_packet(&avpkt);
  448. /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */
  449. memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);
  450. printf("Decode video file %s to %s\n", filename, outfilename);
  451. /* find the mpeg1 video decoder */
  452. codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
  453. if (!codec) {
  454. fprintf(stderr, "Codec not found\n");
  455. exit(1);
  456. }
  457. c = avcodec_alloc_context3(codec);
  458. if (!c) {
  459. fprintf(stderr, "Could not allocate video codec context\n");
  460. exit(1);
  461. }
  462. if(codec->capabilities&CODEC_CAP_TRUNCATED)
  463. c->flags|= CODEC_FLAG_TRUNCATED; /* we do not send complete frames */
  464. /* For some codecs, such as msmpeg4 and mpeg4, width and height
  465. MUST be initialized there because this information is not
  466. available in the bitstream. */
  467. /* open it */
  468. if (avcodec_open2(c, codec, NULL) < 0) {
  469. fprintf(stderr, "Could not open codec\n");
  470. exit(1);
  471. }
  472. f = fopen(filename, "rb");
  473. if (!f) {
  474. fprintf(stderr, "Could not open %s\n", filename);
  475. exit(1);
  476. }
  477. frame = avcodec_alloc_frame();
  478. if (!frame) {
  479. fprintf(stderr, "Could not allocate video frame\n");
  480. exit(1);
  481. }
  482. frame_count = 0;
  483. for(;;) {
  484. avpkt.size = fread(inbuf, 1, INBUF_SIZE, f);
  485. if (avpkt.size == 0)
  486. break;
  487. /* NOTE1: some codecs are stream based (mpegvideo, mpegaudio)
  488. and this is the only method to use them because you cannot
  489. know the compressed data size before analysing it.
  490. BUT some other codecs (msmpeg4, mpeg4) are inherently frame
  491. based, so you must call them with all the data for one
  492. frame exactly. You must also initialize 'width' and
  493. 'height' before initializing them. */
  494. /* NOTE2: some codecs allow the raw parameters (frame size,
  495. sample rate) to be changed at any frame. We handle this, so
  496. you should also take care of it */
  497. /* here, we use a stream based decoder (mpeg1video), so we
  498. feed decoder and see if it could decode a frame */
  499. avpkt.data = inbuf;
  500. while (avpkt.size > 0)
  501. if (decode_write_frame(outfilename, c, frame, &frame_count, &avpkt, 0) < 0)
  502. exit(1);
  503. }
  504. /* some codecs, such as MPEG, transmit the I and P frame with a
  505. latency of one frame. You must do the following to have a
  506. chance to get the last frame of the video */
  507. avpkt.data = NULL;
  508. avpkt.size = 0;
  509. decode_write_frame(outfilename, c, frame, &frame_count, &avpkt, 1);
  510. fclose(f);
  511. avcodec_close(c);
  512. av_free(c);
  513. avcodec_free_frame(&frame);
  514. printf("\n");
  515. }
  516. int main(int argc, char **argv)
  517. {
  518. const char *output_type;
  519. /* register all the codecs */
  520. avcodec_register_all();
  521. if (argc < 2) {
  522. printf("usage: %s output_type\n"
  523. "API example program to decode/encode a media stream with libavcodec.\n"
  524. "This program generates a synthetic stream and encodes it to a file\n"
  525. "named test.h264, test.mp2 or test.mpg depending on output_type.\n"
  526. "The encoded stream is then decoded and written to a raw data output.\n"
  527. "output_type must be choosen between 'h264', 'mp2', 'mpg'.\n",
  528. argv[0]);
  529. return 1;
  530. }
  531. output_type = argv[1];
  532. if (!strcmp(output_type, "h264")) {
  533. video_encode_example("test.h264", AV_CODEC_ID_H264);
  534. } else if (!strcmp(output_type, "mp2")) {
  535. audio_encode_example("test.mp2");
  536. audio_decode_example("test.sw", "test.mp2");
  537. } else if (!strcmp(output_type, "mpg")) {
  538. video_encode_example("test.mpg", AV_CODEC_ID_MPEG1VIDEO);
  539. video_decode_example("test%02d.pgm", "test.mpg");
  540. } else {
  541. fprintf(stderr, "Invalid output type '%s', choose between 'h264', 'mp2', or 'mpg'\n",
  542. output_type);
  543. return 1;
  544. }
  545. return 0;
  546. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:35:47 | 显示全部楼层

ffmpeg 示例代码大全 - demuxing.c

  1. /*
  2. * Copyright (c) 2012 Stefano Sabatini
  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. #include <libavutil/imgutils.h>
  23. #include <libavutil/samplefmt.h>
  24. #include <libavutil/timestamp.h>
  25. #include <libavformat/avformat.h>
  26. static AVFormatContext *fmt_ctx = NULL;
  27. static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
  28. static AVStream *video_stream = NULL, *audio_stream = NULL;
  29. static const char *src_filename = NULL;
  30. static const char *video_dst_filename = NULL;
  31. static const char *audio_dst_filename = NULL;
  32. static FILE *video_dst_file = NULL;
  33. static FILE *audio_dst_file = NULL;
  34. static uint8_t *video_dst_data[4] = {NULL};
  35. static int video_dst_linesize[4];
  36. static int video_dst_bufsize;
  37. static uint8_t **audio_dst_data = NULL;
  38. static int audio_dst_linesize;
  39. static int audio_dst_bufsize;
  40. static int video_stream_idx = -1, audio_stream_idx = -1;
  41. static AVFrame *frame = NULL;
  42. static AVPacket pkt;
  43. static int video_frame_count = 0;
  44. static int audio_frame_count = 0;
  45. static int decode_packet(int *got_frame, int cached)
  46. {
  47. int ret = 0;
  48. if (pkt.stream_index == video_stream_idx) {
  49. /* decode video frame */
  50. ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);
  51. if (ret < 0) {
  52. fprintf(stderr, "Error decoding video frame\n");
  53. return ret;
  54. }
  55. if (*got_frame) {
  56. printf("video_frame%s n:%d coded_n:%d pts:%s\n",
  57. cached ? "(cached)" : "",
  58. video_frame_count++, frame->coded_picture_number,
  59. av_ts2timestr(frame->pts, &video_dec_ctx->time_base));
  60. /* copy decoded frame to destination buffer:
  61. * this is required since rawvideo expects non aligned data */
  62. av_image_copy(video_dst_data, video_dst_linesize,
  63. (const uint8_t **)(frame->data), frame->linesize,
  64. video_dec_ctx->pix_fmt, video_dec_ctx->width, video_dec_ctx->height);
  65. /* write to rawvideo file */
  66. fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
  67. }
  68. } else if (pkt.stream_index == audio_stream_idx) {
  69. /* decode audio frame */
  70. ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);
  71. if (ret < 0) {
  72. fprintf(stderr, "Error decoding audio frame\n");
  73. return ret;
  74. }
  75. if (*got_frame) {
  76. printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",
  77. cached ? "(cached)" : "",
  78. audio_frame_count++, frame->nb_samples,
  79. av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));
  80. ret = av_samples_alloc(audio_dst_data, &audio_dst_linesize, frame->channels,
  81. frame->nb_samples, frame->format, 1);
  82. if (ret < 0) {
  83. fprintf(stderr, "Could not allocate audio buffer\n");
  84. return AVERROR(ENOMEM);
  85. }
  86. /* TODO: extend return code of the av_samples_* functions so that this call is not needed */
  87. audio_dst_bufsize =
  88. av_samples_get_buffer_size(NULL, frame->channels,
  89. frame->nb_samples, frame->format, 1);
  90. /* copy audio data to destination buffer:
  91. * this is required since rawaudio expects non aligned data */
  92. av_samples_copy(audio_dst_data, frame->data, 0, 0,
  93. frame->nb_samples, frame->channels, frame->format);
  94. /* write to rawaudio file */
  95. fwrite(audio_dst_data[0], 1, audio_dst_bufsize, audio_dst_file);
  96. av_freep(&audio_dst_data[0]);
  97. }
  98. }
  99. return ret;
  100. }
  101. static int open_codec_context(int *stream_idx,
  102. AVFormatContext *fmt_ctx, enum AVMediaType type)
  103. {
  104. int ret;
  105. AVStream *st;
  106. AVCodecContext *dec_ctx = NULL;
  107. AVCodec *dec = NULL;
  108. ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
  109. if (ret < 0) {
  110. fprintf(stderr, "Could not find %s stream in input file '%s'\n",
  111. av_get_media_type_string(type), src_filename);
  112. return ret;
  113. } else {
  114. *stream_idx = ret;
  115. st = fmt_ctx->streams[*stream_idx];
  116. /* find decoder for the stream */
  117. dec_ctx = st->codec;
  118. dec = avcodec_find_decoder(dec_ctx->codec_id);
  119. if (!dec) {
  120. fprintf(stderr, "Failed to find %s codec\n",
  121. av_get_media_type_string(type));
  122. return ret;
  123. }
  124. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  125. fprintf(stderr, "Failed to open %s codec\n",
  126. av_get_media_type_string(type));
  127. return ret;
  128. }
  129. }
  130. return 0;
  131. }
  132. static int get_format_from_sample_fmt(const char **fmt,
  133. enum AVSampleFormat sample_fmt)
  134. {
  135. int i;
  136. struct sample_fmt_entry {
  137. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  138. } sample_fmt_entries[] = {
  139. { AV_SAMPLE_FMT_U8, "u8", "u8" },
  140. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  141. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  142. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  143. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  144. };
  145. *fmt = NULL;
  146. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  147. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  148. if (sample_fmt == entry->sample_fmt) {
  149. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  150. return 0;
  151. }
  152. }
  153. fprintf(stderr,
  154. "sample format %s is not supported as output format\n",
  155. av_get_sample_fmt_name(sample_fmt));
  156. return -1;
  157. }
  158. int main (int argc, char **argv)
  159. {
  160. int ret = 0, got_frame;
  161. if (argc != 4) {
  162. fprintf(stderr, "usage: %s input_file video_output_file audio_output_file\n"
  163. "API example program to show how to read frames from an input file.\n"
  164. "This program reads frames from a file, decodes them, and writes decoded\n"
  165. "video frames to a rawvideo file named video_output_file, and decoded\n"
  166. "audio frames to a rawaudio file named audio_output_file.\n"
  167. "\n", argv[0]);
  168. exit(1);
  169. }
  170. src_filename = argv[1];
  171. video_dst_filename = argv[2];
  172. audio_dst_filename = argv[3];
  173. /* register all formats and codecs */
  174. av_register_all();
  175. /* open input file, and allocate format context */
  176. if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
  177. fprintf(stderr, "Could not open source file %s\n", src_filename);
  178. exit(1);
  179. }
  180. /* retrieve stream information */
  181. if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
  182. fprintf(stderr, "Could not find stream information\n");
  183. exit(1);
  184. }
  185. if (open_codec_context(&video_stream_idx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
  186. video_stream = fmt_ctx->streams[video_stream_idx];
  187. video_dec_ctx = video_stream->codec;
  188. video_dst_file = fopen(video_dst_filename, "wb");
  189. if (!video_dst_file) {
  190. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  191. ret = 1;
  192. goto end;
  193. }
  194. /* allocate image where the decoded image will be put */
  195. ret = av_image_alloc(video_dst_data, video_dst_linesize,
  196. video_dec_ctx->width, video_dec_ctx->height,
  197. video_dec_ctx->pix_fmt, 1);
  198. if (ret < 0) {
  199. fprintf(stderr, "Could not allocate raw video buffer\n");
  200. goto end;
  201. }
  202. video_dst_bufsize = ret;
  203. }
  204. if (open_codec_context(&audio_stream_idx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
  205. int nb_planes;
  206. audio_stream = fmt_ctx->streams[audio_stream_idx];
  207. audio_dec_ctx = audio_stream->codec;
  208. audio_dst_file = fopen(audio_dst_filename, "wb");
  209. if (!audio_dst_file) {
  210. fprintf(stderr, "Could not open destination file %s\n", video_dst_filename);
  211. ret = 1;
  212. goto end;
  213. }
  214. nb_planes = av_sample_fmt_is_planar(audio_dec_ctx->sample_fmt) ?
  215. audio_dec_ctx->channels : 1;
  216. audio_dst_data = av_mallocz(sizeof(uint8_t *) * nb_planes);
  217. if (!audio_dst_data) {
  218. fprintf(stderr, "Could not allocate audio data buffers\n");
  219. ret = AVERROR(ENOMEM);
  220. goto end;
  221. }
  222. }
  223. /* dump input information to stderr */
  224. av_dump_format(fmt_ctx, 0, src_filename, 0);
  225. if (!audio_stream && !video_stream) {
  226. fprintf(stderr, "Could not find audio or video stream in the input, aborting\n");
  227. ret = 1;
  228. goto end;
  229. }
  230. frame = avcodec_alloc_frame();
  231. if (!frame) {
  232. fprintf(stderr, "Could not allocate frame\n");
  233. ret = AVERROR(ENOMEM);
  234. goto end;
  235. }
  236. /* initialize packet, set data to NULL, let the demuxer fill it */
  237. av_init_packet(&pkt);
  238. pkt.data = NULL;
  239. pkt.size = 0;
  240. if (video_stream)
  241. printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
  242. if (audio_stream)
  243. printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);
  244. /* read frames from the file */
  245. while (av_read_frame(fmt_ctx, &pkt) >= 0) {
  246. decode_packet(&got_frame, 0);
  247. av_free_packet(&pkt);
  248. }
  249. /* flush cached frames */
  250. pkt.data = NULL;
  251. pkt.size = 0;
  252. do {
  253. decode_packet(&got_frame, 1);
  254. } while (got_frame);
  255. printf("Demuxing succeeded.\n");
  256. if (video_stream) {
  257. printf("Play the output video file with the command:\n"
  258. "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
  259. av_get_pix_fmt_name(video_dec_ctx->pix_fmt), video_dec_ctx->width, video_dec_ctx->height,
  260. video_dst_filename);
  261. }
  262. if (audio_stream) {
  263. const char *fmt;
  264. if ((ret = get_format_from_sample_fmt(&fmt, audio_dec_ctx->sample_fmt)) < 0)
  265. goto end;
  266. printf("Play the output audio file with the command:\n"
  267. "ffplay -f %s -ac %d -ar %d %s\n",
  268. fmt, audio_dec_ctx->channels, audio_dec_ctx->sample_rate,
  269. audio_dst_filename);
  270. }
  271. end:
  272. if (video_dec_ctx)
  273. avcodec_close(video_dec_ctx);
  274. if (audio_dec_ctx)
  275. avcodec_close(audio_dec_ctx);
  276. avformat_close_input(&fmt_ctx);
  277. if (video_dst_file)
  278. fclose(video_dst_file);
  279. if (audio_dst_file)
  280. fclose(audio_dst_file);
  281. av_free(frame);
  282. av_free(video_dst_data[0]);
  283. av_free(audio_dst_data);
  284. return ret < 0;
  285. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:39:05 | 显示全部楼层

ffmpeg 示例代码大全 - filtering_audio.c

  1. /*
  2. * Copyright (c) 2010 Nicolas George
  3. * Copyright (c) 2011 Stefano Sabatini
  4. * Copyright (c) 2012 Clément Bœsch
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include <unistd.h>
  25. #include <libavcodec/avcodec.h>
  26. #include <libavformat/avformat.h>
  27. #include <libavfilter/avfiltergraph.h>
  28. #include <libavfilter/avcodec.h>
  29. #include <libavfilter/buffersink.h>
  30. #include <libavfilter/buffersrc.h>
  31. const char *filter_descr = "aresample=8000,aconvert=s16:mono";
  32. const char *player = "ffplay -f s16le -ar 8000 -ac 1 -";
  33. static AVFormatContext *fmt_ctx;
  34. static AVCodecContext *dec_ctx;
  35. AVFilterContext *buffersink_ctx;
  36. AVFilterContext *buffersrc_ctx;
  37. AVFilterGraph *filter_graph;
  38. static int audio_stream_index = -1;
  39. static int open_input_file(const char *filename)
  40. {
  41. int ret;
  42. AVCodec *dec;
  43. if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
  44. av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
  45. return ret;
  46. }
  47. if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  48. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  49. return ret;
  50. }
  51. /* select the audio stream */
  52. ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);
  53. if (ret < 0) {
  54. av_log(NULL, AV_LOG_ERROR, "Cannot find a audio stream in the input file\n");
  55. return ret;
  56. }
  57. audio_stream_index = ret;
  58. dec_ctx = fmt_ctx->streams[audio_stream_index]->codec;
  59. /* init the audio decoder */
  60. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  61. av_log(NULL, AV_LOG_ERROR, "Cannot open audio decoder\n");
  62. return ret;
  63. }
  64. return 0;
  65. }
  66. static int init_filters(const char *filters_descr)
  67. {
  68. char args[512];
  69. int ret;
  70. AVFilter *abuffersrc = avfilter_get_by_name("abuffer");
  71. AVFilter *abuffersink = avfilter_get_by_name("ffabuffersink");
  72. AVFilterInOut *outputs = avfilter_inout_alloc();
  73. AVFilterInOut *inputs = avfilter_inout_alloc();
  74. const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16, -1 };
  75. AVABufferSinkParams *abuffersink_params;
  76. const AVFilterLink *outlink;
  77. AVRational time_base = fmt_ctx->streams[audio_stream_index]->time_base;
  78. filter_graph = avfilter_graph_alloc();
  79. /* buffer audio source: the decoded frames from the decoder will be inserted here. */
  80. if (!dec_ctx->channel_layout)
  81. dec_ctx->channel_layout = av_get_default_channel_layout(dec_ctx->channels);
  82. snprintf(args, sizeof(args),
  83. "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64,
  84. time_base.num, time_base.den, dec_ctx->sample_rate,
  85. av_get_sample_fmt_name(dec_ctx->sample_fmt), dec_ctx->channel_layout);
  86. ret = avfilter_graph_create_filter(&buffersrc_ctx, abuffersrc, "in",
  87. args, NULL, filter_graph);
  88. if (ret < 0) {
  89. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
  90. return ret;
  91. }
  92. /* buffer audio sink: to terminate the filter chain. */
  93. abuffersink_params = av_abuffersink_params_alloc();
  94. abuffersink_params->sample_fmts = sample_fmts;
  95. ret = avfilter_graph_create_filter(&buffersink_ctx, abuffersink, "out",
  96. NULL, abuffersink_params, filter_graph);
  97. av_free(abuffersink_params);
  98. if (ret < 0) {
  99. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
  100. return ret;
  101. }
  102. /* Endpoints for the filter graph. */
  103. outputs->name = av_strdup("in");
  104. outputs->filter_ctx = buffersrc_ctx;
  105. outputs->pad_idx = 0;
  106. outputs->next = NULL;
  107. inputs->name = av_strdup("out");
  108. inputs->filter_ctx = buffersink_ctx;
  109. inputs->pad_idx = 0;
  110. inputs->next = NULL;
  111. if ((ret = avfilter_graph_parse(filter_graph, filters_descr,
  112. &inputs, &outputs, NULL)) < 0)
  113. return ret;
  114. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
  115. return ret;
  116. /* Print summary of the sink buffer
  117. * Note: args buffer is reused to store channel layout string */
  118. outlink = buffersink_ctx->inputs[0];
  119. av_get_channel_layout_string(args, sizeof(args), -1, outlink->channel_layout);
  120. av_log(NULL, AV_LOG_INFO, "Output: srate:%dHz fmt:%s chlayout:%s\n",
  121. (int)outlink->sample_rate,
  122. (char *)av_x_if_null(av_get_sample_fmt_name(outlink->format), "?"),
  123. args);
  124. return 0;
  125. }
  126. static void print_samplesref(AVFilterBufferRef *samplesref)
  127. {
  128. const AVFilterBufferRefAudioProps *props = samplesref->audio;
  129. const int n = props->nb_samples * av_get_channel_layout_nb_channels(props->channel_layout);
  130. const uint16_t *p = (uint16_t*)samplesref->data[0];
  131. const uint16_t *p_end = p + n;
  132. while (p < p_end) {
  133. fputc(*p & 0xff, stdout);
  134. fputc(*p>>8 & 0xff, stdout);
  135. p++;
  136. }
  137. fflush(stdout);
  138. }
  139. int main(int argc, char **argv)
  140. {
  141. int ret;
  142. AVPacket packet;
  143. AVFrame *frame = avcodec_alloc_frame();
  144. int got_frame;
  145. if (!frame) {
  146. perror("Could not allocate frame");
  147. exit(1);
  148. }
  149. if (argc != 2) {
  150. fprintf(stderr, "Usage: %s file | %s\n", argv[0], player);
  151. exit(1);
  152. }
  153. avcodec_register_all();
  154. av_register_all();
  155. avfilter_register_all();
  156. if ((ret = open_input_file(argv[1])) < 0)
  157. goto end;
  158. if ((ret = init_filters(filter_descr)) < 0)
  159. goto end;
  160. /* read all packets */
  161. while (1) {
  162. AVFilterBufferRef *samplesref;
  163. if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
  164. break;
  165. if (packet.stream_index == audio_stream_index) {
  166. avcodec_get_frame_defaults(frame);
  167. got_frame = 0;
  168. ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, &packet);
  169. if (ret < 0) {
  170. av_log(NULL, AV_LOG_ERROR, "Error decoding audio\n");
  171. continue;
  172. }
  173. if (got_frame) {
  174. /* push the audio data from decoded frame into the filtergraph */
  175. if (av_buffersrc_add_frame(buffersrc_ctx, frame, 0) < 0) {
  176. av_log(NULL, AV_LOG_ERROR, "Error while feeding the audio filtergraph\n");
  177. break;
  178. }
  179. /* pull filtered audio from the filtergraph */
  180. while (1) {
  181. ret = av_buffersink_get_buffer_ref(buffersink_ctx, &samplesref, 0);
  182. if(ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  183. break;
  184. if(ret < 0)
  185. goto end;
  186. if (samplesref) {
  187. print_samplesref(samplesref);
  188. avfilter_unref_bufferp(&samplesref);
  189. }
  190. }
  191. }
  192. }
  193. av_free_packet(&packet);
  194. }
  195. end:
  196. avfilter_graph_free(&filter_graph);
  197. if (dec_ctx)
  198. avcodec_close(dec_ctx);
  199. avformat_close_input(&fmt_ctx);
  200. av_freep(&frame);
  201. if (ret < 0 && ret != AVERROR_EOF) {
  202. char buf[1024];
  203. av_strerror(ret, buf, sizeof(buf));
  204. fprintf(stderr, "Error occurred: %s\n", buf);
  205. exit(1);
  206. }
  207. exit(0);
  208. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:40:03 | 显示全部楼层

ffmpeg 示例代码大全 - filtering_video.c

jackyhwei 发表于 2013-2-25 16:39
  1. /*
  2. * Copyright (c) 2010 Nicolas George
  3. * Copyright (c) 2011 Stefano Sabatini
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. */
  23. #define _XOPEN_SOURCE 600 /* for usleep */
  24. #include <unistd.h>
  25. #include <libavcodec/avcodec.h>
  26. #include <libavformat/avformat.h>
  27. #include <libavfilter/avfiltergraph.h>
  28. #include <libavfilter/avcodec.h>
  29. #include <libavfilter/buffersink.h>
  30. #include <libavfilter/buffersrc.h>
  31. const char *filter_descr = "scale=78:24";
  32. static AVFormatContext *fmt_ctx;
  33. static AVCodecContext *dec_ctx;
  34. AVFilterContext *buffersink_ctx;
  35. AVFilterContext *buffersrc_ctx;
  36. AVFilterGraph *filter_graph;
  37. static int video_stream_index = -1;
  38. static int64_t last_pts = AV_NOPTS_VALUE;
  39. static int open_input_file(const char *filename)
  40. {
  41. int ret;
  42. AVCodec *dec;
  43. if ((ret = avformat_open_input(&fmt_ctx, filename, NULL, NULL)) < 0) {
  44. av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
  45. return ret;
  46. }
  47. if ((ret = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  48. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  49. return ret;
  50. }
  51. /* select the video stream */
  52. ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);
  53. if (ret < 0) {
  54. av_log(NULL, AV_LOG_ERROR, "Cannot find a video stream in the input file\n");
  55. return ret;
  56. }
  57. video_stream_index = ret;
  58. dec_ctx = fmt_ctx->streams[video_stream_index]->codec;
  59. /* init the video decoder */
  60. if ((ret = avcodec_open2(dec_ctx, dec, NULL)) < 0) {
  61. av_log(NULL, AV_LOG_ERROR, "Cannot open video decoder\n");
  62. return ret;
  63. }
  64. return 0;
  65. }
  66. static int init_filters(const char *filters_descr)
  67. {
  68. char args[512];
  69. int ret;
  70. AVFilter *buffersrc = avfilter_get_by_name("buffer");
  71. AVFilter *buffersink = avfilter_get_by_name("ffbuffersink");
  72. AVFilterInOut *outputs = avfilter_inout_alloc();
  73. AVFilterInOut *inputs = avfilter_inout_alloc();
  74. enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_NONE };
  75. AVBufferSinkParams *buffersink_params;
  76. filter_graph = avfilter_graph_alloc();
  77. /* buffer video source: the decoded frames from the decoder will be inserted here. */
  78. snprintf(args, sizeof(args),
  79. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  80. dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
  81. dec_ctx->time_base.num, dec_ctx->time_base.den,
  82. dec_ctx->sample_aspect_ratio.num, dec_ctx->sample_aspect_ratio.den);
  83. ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
  84. args, NULL, filter_graph);
  85. if (ret < 0) {
  86. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
  87. return ret;
  88. }
  89. /* buffer video sink: to terminate the filter chain. */
  90. buffersink_params = av_buffersink_params_alloc();
  91. buffersink_params->pixel_fmts = pix_fmts;
  92. ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
  93. NULL, buffersink_params, filter_graph);
  94. av_free(buffersink_params);
  95. if (ret < 0) {
  96. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
  97. return ret;
  98. }
  99. /* Endpoints for the filter graph. */
  100. outputs->name = av_strdup("in");
  101. outputs->filter_ctx = buffersrc_ctx;
  102. outputs->pad_idx = 0;
  103. outputs->next = NULL;
  104. inputs->name = av_strdup("out");
  105. inputs->filter_ctx = buffersink_ctx;
  106. inputs->pad_idx = 0;
  107. inputs->next = NULL;
  108. if ((ret = avfilter_graph_parse(filter_graph, filters_descr,
  109. &inputs, &outputs, NULL)) < 0)
  110. return ret;
  111. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
  112. return ret;
  113. return 0;
  114. }
  115. static void display_picref(AVFilterBufferRef *picref, AVRational time_base)
  116. {
  117. int x, y;
  118. uint8_t *p0, *p;
  119. int64_t delay;
  120. if (picref->pts != AV_NOPTS_VALUE) {
  121. if (last_pts != AV_NOPTS_VALUE) {
  122. /* sleep roughly the right amount of time;
  123. * usleep is in microseconds, just like AV_TIME_BASE. */
  124. delay = av_rescale_q(picref->pts - last_pts,
  125. time_base, AV_TIME_BASE_Q);
  126. if (delay > 0 && delay < 1000000)
  127. usleep(delay);
  128. }
  129. last_pts = picref->pts;
  130. }
  131. /* Trivial ASCII grayscale display. */
  132. p0 = picref->data[0];
  133. puts("\033c");
  134. for (y = 0; y < picref->video->h; y++) {
  135. p = p0;
  136. for (x = 0; x < picref->video->w; x++)
  137. putchar(" .-+#"[*(p++) / 52]);
  138. putchar('\n');
  139. p0 += picref->linesize[0];
  140. }
  141. fflush(stdout);
  142. }
  143. int main(int argc, char **argv)
  144. {
  145. int ret;
  146. AVPacket packet;
  147. AVFrame *frame = avcodec_alloc_frame();
  148. int got_frame;
  149. if (!frame) {
  150. perror("Could not allocate frame");
  151. exit(1);
  152. }
  153. if (argc != 2) {
  154. fprintf(stderr, "Usage: %s file\n", argv[0]);
  155. exit(1);
  156. }
  157. avcodec_register_all();
  158. av_register_all();
  159. avfilter_register_all();
  160. if ((ret = open_input_file(argv[1])) < 0)
  161. goto end;
  162. if ((ret = init_filters(filter_descr)) < 0)
  163. goto end;
  164. /* read all packets */
  165. while (1) {
  166. AVFilterBufferRef *picref;
  167. if ((ret = av_read_frame(fmt_ctx, &packet)) < 0)
  168. break;
  169. if (packet.stream_index == video_stream_index) {
  170. avcodec_get_frame_defaults(frame);
  171. got_frame = 0;
  172. ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, &packet);
  173. if (ret < 0) {
  174. av_log(NULL, AV_LOG_ERROR, "Error decoding video\n");
  175. break;
  176. }
  177. if (got_frame) {
  178. frame->pts = av_frame_get_best_effort_timestamp(frame);
  179. /* push the decoded frame into the filtergraph */
  180. if (av_buffersrc_add_frame(buffersrc_ctx, frame, 0) < 0) {
  181. av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
  182. break;
  183. }
  184. /* pull filtered pictures from the filtergraph */
  185. while (1) {
  186. ret = av_buffersink_get_buffer_ref(buffersink_ctx, &picref, 0);
  187. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  188. break;
  189. if (ret < 0)
  190. goto end;
  191. if (picref) {
  192. display_picref(picref, buffersink_ctx->inputs[0]->time_base);
  193. avfilter_unref_bufferp(&picref);
  194. }
  195. }
  196. }
  197. }
  198. av_free_packet(&packet);
  199. }
  200. end:
  201. avfilter_graph_free(&filter_graph);
  202. if (dec_ctx)
  203. avcodec_close(dec_ctx);
  204. avformat_close_input(&fmt_ctx);
  205. av_freep(&frame);
  206. if (ret < 0 && ret != AVERROR_EOF) {
  207. char buf[1024];
  208. av_strerror(ret, buf, sizeof(buf));
  209. fprintf(stderr, "Error occurred: %s\n", buf);
  210. exit(1);
  211. }
  212. exit(0);
  213. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:41:04 | 显示全部楼层

ffmpeg 示例代码大全 - metadata.c

jackyhwei 发表于 2013-2-25 16:40
  1. /*
  2. * Copyright (c) 2011 Reinhard Tartler
  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. #include <stdio.h>
  23. #include <libavformat/avformat.h>
  24. #include <libavutil/dict.h>
  25. int main (int argc, char **argv)
  26. {
  27. AVFormatContext *fmt_ctx = NULL;
  28. AVDictionaryEntry *tag = NULL;
  29. int ret;
  30. if (argc != 2) {
  31. printf("usage: %s <input_file>\n"
  32. "example program to demonstrate the use of the libavformat metadata API.\n"
  33. "\n", argv[0]);
  34. return 1;
  35. }
  36. av_register_all();
  37. if ((ret = avformat_open_input(&fmt_ctx, argv[1], NULL, NULL)))
  38. return ret;
  39. while ((tag = av_dict_get(fmt_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
  40. printf("%s=%s\n", tag->key, tag->value);
  41. avformat_close_input(&fmt_ctx);
  42. return 0;
  43. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:41:46 | 显示全部楼层

ffmpeg 示例代码大全 - muxing.c

  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. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <math.h>
  26. #include <libavutil/mathematics.h>
  27. #include <libavformat/avformat.h>
  28. #include <libswscale/swscale.h>
  29. /* 5 seconds stream duration */
  30. #define STREAM_DURATION 200.0
  31. #define STREAM_FRAME_RATE 25 /* 25 images/s */
  32. #define STREAM_NB_FRAMES ((int)(STREAM_DURATION * STREAM_FRAME_RATE))
  33. #define STREAM_PIX_FMT AV_PIX_FMT_YUV420P /* default pix_fmt */
  34. static int sws_flags = SWS_BICUBIC;
  35. /**************************************************************/
  36. /* audio output */
  37. static float t, tincr, tincr2;
  38. static int16_t *samples;
  39. static int audio_input_frame_size;
  40. /* Add an output stream. */
  41. static AVStream *add_stream(AVFormatContext *oc, AVCodec **codec,
  42. enum AVCodecID codec_id)
  43. {
  44. AVCodecContext *c;
  45. AVStream *st;
  46. /* find the encoder */
  47. *codec = avcodec_find_encoder(codec_id);
  48. if (!(*codec)) {
  49. fprintf(stderr, "Could not find encoder for '%s'\n",
  50. avcodec_get_name(codec_id));
  51. exit(1);
  52. }
  53. st = avformat_new_stream(oc, *codec);
  54. if (!st) {
  55. fprintf(stderr, "Could not allocate stream\n");
  56. exit(1);
  57. }
  58. st->id = oc->nb_streams-1;
  59. c = st->codec;
  60. switch ((*codec)->type) {
  61. case AVMEDIA_TYPE_AUDIO:
  62. st->id = 1;
  63. c->sample_fmt = AV_SAMPLE_FMT_S16;
  64. c->bit_rate = 64000;
  65. c->sample_rate = 44100;
  66. c->channels = 2;
  67. break;
  68. case AVMEDIA_TYPE_VIDEO:
  69. avcodec_get_context_defaults3(c, *codec);
  70. c->codec_id = codec_id;
  71. c->bit_rate = 400000;
  72. /* Resolution must be a multiple of two. */
  73. c->width = 352;
  74. c->height = 288;
  75. /* timebase: This is the fundamental unit of time (in seconds) in terms
  76. * of which frame timestamps are represented. For fixed-fps content,
  77. * timebase should be 1/framerate and timestamp increments should be
  78. * identical to 1. */
  79. c->time_base.den = STREAM_FRAME_RATE;
  80. c->time_base.num = 1;
  81. c->gop_size = 12; /* emit one intra frame every twelve frames at most */
  82. c->pix_fmt = STREAM_PIX_FMT;
  83. if (c->codec_id == AV_CODEC_ID_MPEG2VIDEO) {
  84. /* just for testing, we also add B frames */
  85. c->max_b_frames = 2;
  86. }
  87. if (c->codec_id == AV_CODEC_ID_MPEG1VIDEO) {
  88. /* Needed to avoid using macroblocks in which some coeffs overflow.
  89. * This does not happen with normal video, it just happens here as
  90. * the motion of the chroma plane does not match the luma plane. */
  91. c->mb_decision = 2;
  92. }
  93. break;
  94. default:
  95. break;
  96. }
  97. /* Some formats want stream headers to be separate. */
  98. if (oc->oformat->flags & AVFMT_GLOBALHEADER)
  99. c->flags |= CODEC_FLAG_GLOBAL_HEADER;
  100. return st;
  101. }
  102. /**************************************************************/
  103. /* audio output */
  104. static float t, tincr, tincr2;
  105. static int16_t *samples;
  106. static int audio_input_frame_size;
  107. static void open_audio(AVFormatContext *oc, AVCodec *codec, AVStream *st)
  108. {
  109. AVCodecContext *c;
  110. int ret;
  111. c = st->codec;
  112. /* open it */
  113. ret = avcodec_open2(c, codec, NULL);
  114. if (ret < 0) {
  115. fprintf(stderr, "Could not open audio codec: %s\n", av_err2str(ret));
  116. exit(1);
  117. }
  118. /* init signal generator */
  119. t = 0;
  120. tincr = 2 * M_PI * 110.0 / c->sample_rate;
  121. /* increment frequency by 110 Hz per second */
  122. tincr2 = 2 * M_PI * 110.0 / c->sample_rate / c->sample_rate;
  123. if (c->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)
  124. audio_input_frame_size = 10000;
  125. else
  126. audio_input_frame_size = c->frame_size;
  127. samples = av_malloc(audio_input_frame_size *
  128. av_get_bytes_per_sample(c->sample_fmt) *
  129. c->channels);
  130. if (!samples) {
  131. fprintf(stderr, "Could not allocate audio samples buffer\n");
  132. exit(1);
  133. }
  134. }
  135. /* Prepare a 16 bit dummy audio frame of 'frame_size' samples and
  136. * 'nb_channels' channels. */
  137. static void get_audio_frame(int16_t *samples, int frame_size, int nb_channels)
  138. {
  139. int j, i, v;
  140. int16_t *q;
  141. q = samples;
  142. for (j = 0; j < frame_size; j++) {
  143. v = (int)(sin(t) * 10000);
  144. for (i = 0; i < nb_channels; i++)
  145. *q++ = v;
  146. t += tincr;
  147. tincr += tincr2;
  148. }
  149. }
  150. static void write_audio_frame(AVFormatContext *oc, AVStream *st)
  151. {
  152. AVCodecContext *c;
  153. AVPacket pkt = { 0 }; // data and size must be 0;
  154. AVFrame *frame = avcodec_alloc_frame();
  155. int got_packet, ret;
  156. av_init_packet(&pkt);
  157. c = st->codec;
  158. get_audio_frame(samples, audio_input_frame_size, c->channels);
  159. frame->nb_samples = audio_input_frame_size;
  160. avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt,
  161. (uint8_t *)samples,
  162. audio_input_frame_size *
  163. av_get_bytes_per_sample(c->sample_fmt) *
  164. c->channels, 1);
  165. ret = avcodec_encode_audio2(c, &pkt, frame, &got_packet);
  166. if (ret < 0) {
  167. fprintf(stderr, "Error encoding audio frame: %s\n", av_err2str(ret));
  168. exit(1);
  169. }
  170. if (!got_packet)
  171. return;
  172. pkt.stream_index = st->index;
  173. /* Write the compressed frame to the media file. */
  174. ret = av_interleaved_write_frame(oc, &pkt);
  175. if (ret != 0) {
  176. fprintf(stderr, "Error while writing audio frame: %s\n",
  177. av_err2str(ret));
  178. exit(1);
  179. }
  180. avcodec_free_frame(&frame);
  181. }
  182. static void close_audio(AVFormatContext *oc, AVStream *st)
  183. {
  184. avcodec_close(st->codec);
  185. av_free(samples);
  186. }
  187. /**************************************************************/
  188. /* video output */
  189. static AVFrame *frame;
  190. static AVPicture src_picture, dst_picture;
  191. static int frame_count;
  192. static void open_video(AVFormatContext *oc, AVCodec *codec, AVStream *st)
  193. {
  194. int ret;
  195. AVCodecContext *c = st->codec;
  196. /* open the codec */
  197. ret = avcodec_open2(c, codec, NULL);
  198. if (ret < 0) {
  199. fprintf(stderr, "Could not open video codec: %s\n", av_err2str(ret));
  200. exit(1);
  201. }
  202. /* allocate and init a re-usable frame */
  203. frame = avcodec_alloc_frame();
  204. if (!frame) {
  205. fprintf(stderr, "Could not allocate video frame\n");
  206. exit(1);
  207. }
  208. /* Allocate the encoded raw picture. */
  209. ret = avpicture_alloc(&dst_picture, c->pix_fmt, c->width, c->height);
  210. if (ret < 0) {
  211. fprintf(stderr, "Could not allocate picture: %s\n", av_err2str(ret));
  212. exit(1);
  213. }
  214. /* If the output format is not YUV420P, then a temporary YUV420P
  215. * picture is needed too. It is then converted to the required
  216. * output format. */
  217. if (c->pix_fmt != AV_PIX_FMT_YUV420P) {
  218. ret = avpicture_alloc(&src_picture, AV_PIX_FMT_YUV420P, c->width, c->height);
  219. if (ret < 0) {
  220. fprintf(stderr, "Could not allocate temporary picture: %s\n",
  221. av_err2str(ret));
  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: %s\n", av_err2str(ret));
  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: %s\n", av_err2str(ret));
  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 ret, 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. ret = avio_open(&oc->pb, filename, AVIO_FLAG_WRITE);
  376. if (ret < 0) {
  377. fprintf(stderr, "Could not open '%s': %s\n", filename,
  378. av_err2str(ret));
  379. return 1;
  380. }
  381. }
  382. /* Write the stream header, if any. */
  383. ret = avformat_write_header(oc, NULL);
  384. if (ret < 0) {
  385. fprintf(stderr, "Error occurred when opening output file: %s\n",
  386. av_err2str(ret));
  387. return 1;
  388. }
  389. if (frame)
  390. frame->pts = 0;
  391. for (;;) {
  392. /* Compute current audio and video time. */
  393. if (audio_st)
  394. audio_pts = (double)audio_st->pts.val * audio_st->time_base.num / audio_st->time_base.den;
  395. else
  396. audio_pts = 0.0;
  397. if (video_st)
  398. video_pts = (double)video_st->pts.val * video_st->time_base.num /
  399. video_st->time_base.den;
  400. else
  401. video_pts = 0.0;
  402. if ((!audio_st || audio_pts >= STREAM_DURATION) &&
  403. (!video_st || video_pts >= STREAM_DURATION))
  404. break;
  405. /* write interleaved audio and video frames */
  406. if (!video_st || (video_st && audio_st && audio_pts < video_pts)) {
  407. write_audio_frame(oc, audio_st);
  408. } else {
  409. write_video_frame(oc, video_st);
  410. frame->pts += av_rescale_q(1, video_st->codec->time_base, video_st->time_base);
  411. }
  412. }
  413. /* Write the trailer, if any. The trailer must be written before you
  414. * close the CodecContexts open when you wrote the header; otherwise
  415. * av_write_trailer() may try to use memory that was freed on
  416. * av_codec_close(). */
  417. av_write_trailer(oc);
  418. /* Close each codec. */
  419. if (video_st)
  420. close_video(oc, video_st);
  421. if (audio_st)
  422. close_audio(oc, audio_st);
  423. /* Free the streams. */
  424. for (i = 0; i < oc->nb_streams; i++) {
  425. av_freep(&oc->streams[i]->codec);
  426. av_freep(&oc->streams[i]);
  427. }
  428. if (!(fmt->flags & AVFMT_NOFILE))
  429. /* Close the output file. */
  430. avio_close(oc->pb);
  431. /* free the stream */
  432. av_free(oc);
  433. return 0;
  434. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:42:31 | 显示全部楼层

ffmpeg 示例代码大全 - resampling_audio.c

libswresample API use example.
  1. /*
  2. * Copyright (c) 2012 Stefano Sabatini
  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. #include <libavutil/opt.h>
  23. #include <libavutil/channel_layout.h>
  24. #include <libavutil/samplefmt.h>
  25. #include <libswresample/swresample.h>
  26. static int get_format_from_sample_fmt(const char **fmt,
  27. enum AVSampleFormat sample_fmt)
  28. {
  29. int i;
  30. struct sample_fmt_entry {
  31. enum AVSampleFormat sample_fmt; const char *fmt_be, *fmt_le;
  32. } sample_fmt_entries[] = {
  33. { AV_SAMPLE_FMT_U8, "u8", "u8" },
  34. { AV_SAMPLE_FMT_S16, "s16be", "s16le" },
  35. { AV_SAMPLE_FMT_S32, "s32be", "s32le" },
  36. { AV_SAMPLE_FMT_FLT, "f32be", "f32le" },
  37. { AV_SAMPLE_FMT_DBL, "f64be", "f64le" },
  38. };
  39. *fmt = NULL;
  40. for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
  41. struct sample_fmt_entry *entry = &sample_fmt_entries[i];
  42. if (sample_fmt == entry->sample_fmt) {
  43. *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
  44. return 0;
  45. }
  46. }
  47. fprintf(stderr,
  48. "Sample format %s not supported as output format\n",
  49. av_get_sample_fmt_name(sample_fmt));
  50. return AVERROR(EINVAL);
  51. }
  52. void fill_samples(double *dst, int nb_samples, int nb_channels, int sample_rate, double *t)
  53. {
  54. int i, j;
  55. double tincr = 1.0 / sample_rate, *dstp = dst;
  56. const double c = 2 * M_PI * 440.0;
  57. /* generate sin tone with 440Hz frequency and duplicated channels */
  58. for (i = 0; i < nb_samples; i++) {
  59. *dstp = sin(c * *t);
  60. for (j = 1; j < nb_channels; j++)
  61. dstp[j] = dstp[0];
  62. dstp += nb_channels;
  63. *t += tincr;
  64. }
  65. }
  66. int alloc_samples_array_and_data(uint8_t ***data, int *linesize, int nb_channels,
  67. int nb_samples, enum AVSampleFormat sample_fmt, int align)
  68. {
  69. int nb_planes = av_sample_fmt_is_planar(sample_fmt) ? nb_channels : 1;
  70. *data = av_malloc(sizeof(*data) * nb_planes);
  71. if (!*data)
  72. return AVERROR(ENOMEM);
  73. return av_samples_alloc(*data, linesize, nb_channels,
  74. nb_samples, sample_fmt, align);
  75. }
  76. int main(int argc, char **argv)
  77. {
  78. int64_t src_ch_layout = AV_CH_LAYOUT_STEREO, dst_ch_layout = AV_CH_LAYOUT_SURROUND;
  79. int src_rate = 48000, dst_rate = 44100;
  80. uint8_t **src_data = NULL, **dst_data = NULL;
  81. int src_nb_channels = 0, dst_nb_channels = 0;
  82. int src_linesize, dst_linesize;
  83. int src_nb_samples = 1024, dst_nb_samples, max_dst_nb_samples;
  84. enum AVSampleFormat src_sample_fmt = AV_SAMPLE_FMT_DBL, dst_sample_fmt = AV_SAMPLE_FMT_S16;
  85. const char *dst_filename = NULL;
  86. FILE *dst_file;
  87. int dst_bufsize;
  88. const char *fmt;
  89. struct SwrContext *swr_ctx;
  90. double t;
  91. int ret;
  92. if (argc != 2) {
  93. fprintf(stderr, "Usage: %s output_file\n"
  94. "API example program to show how to resample an audio stream with libswresample.\n"
  95. "This program generates a series of audio frames, resamples them to a specified "
  96. "output format and rate and saves them to an output file named output_file.\n",
  97. argv[0]);
  98. exit(1);
  99. }
  100. dst_filename = argv[1];
  101. dst_file = fopen(dst_filename, "wb");
  102. if (!dst_file) {
  103. fprintf(stderr, "Could not open destination file %s\n", dst_filename);
  104. exit(1);
  105. }
  106. /* create resampler context */
  107. swr_ctx = swr_alloc();
  108. if (!swr_ctx) {
  109. fprintf(stderr, "Could not allocate resampler context\n");
  110. ret = AVERROR(ENOMEM);
  111. goto end;
  112. }
  113. /* set options */
  114. av_opt_set_int(swr_ctx, "in_channel_layout", src_ch_layout, 0);
  115. av_opt_set_int(swr_ctx, "in_sample_rate", src_rate, 0);
  116. av_opt_set_sample_fmt(swr_ctx, "in_sample_fmt", src_sample_fmt, 0);
  117. av_opt_set_int(swr_ctx, "out_channel_layout", dst_ch_layout, 0);
  118. av_opt_set_int(swr_ctx, "out_sample_rate", dst_rate, 0);
  119. av_opt_set_sample_fmt(swr_ctx, "out_sample_fmt", dst_sample_fmt, 0);
  120. /* initialize the resampling context */
  121. if ((ret = swr_init(swr_ctx)) < 0) {
  122. fprintf(stderr, "Failed to initialize the resampling context\n");
  123. goto end;
  124. }
  125. /* allocate source and destination samples buffers */
  126. src_nb_channels = av_get_channel_layout_nb_channels(src_ch_layout);
  127. ret = alloc_samples_array_and_data(&src_data, &src_linesize, src_nb_channels,
  128. src_nb_samples, src_sample_fmt, 0);
  129. if (ret < 0) {
  130. fprintf(stderr, "Could not allocate source samples\n");
  131. goto end;
  132. }
  133. /* compute the number of converted samples: buffering is avoided
  134. * ensuring that the output buffer will contain at least all the
  135. * converted input samples */
  136. max_dst_nb_samples = dst_nb_samples =
  137. av_rescale_rnd(src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);
  138. /* buffer is going to be directly written to a rawaudio file, no alignment */
  139. dst_nb_channels = av_get_channel_layout_nb_channels(dst_ch_layout);
  140. ret = alloc_samples_array_and_data(&dst_data, &dst_linesize, dst_nb_channels,
  141. dst_nb_samples, dst_sample_fmt, 0);
  142. if (ret < 0) {
  143. fprintf(stderr, "Could not allocate destination samples\n");
  144. goto end;
  145. }
  146. t = 0;
  147. do {
  148. /* generate synthetic audio */
  149. fill_samples((double *)src_data[0], src_nb_samples, src_nb_channels, src_rate, &t);
  150. /* compute destination number of samples */
  151. dst_nb_samples = av_rescale_rnd(swr_get_delay(swr_ctx, src_rate) +
  152. src_nb_samples, dst_rate, src_rate, AV_ROUND_UP);
  153. if (dst_nb_samples > max_dst_nb_samples) {
  154. av_free(dst_data[0]);
  155. ret = av_samples_alloc(dst_data, &dst_linesize, dst_nb_channels,
  156. dst_nb_samples, dst_sample_fmt, 1);
  157. if (ret < 0)
  158. break;
  159. max_dst_nb_samples = dst_nb_samples;
  160. }
  161. /* convert to destination format */
  162. ret = swr_convert(swr_ctx, dst_data, dst_nb_samples, (const uint8_t **)src_data, src_nb_samples);
  163. if (ret < 0) {
  164. fprintf(stderr, "Error while converting\n");
  165. goto end;
  166. }
  167. dst_bufsize = av_samples_get_buffer_size(&dst_linesize, dst_nb_channels,
  168. ret, dst_sample_fmt, 1);
  169. printf("t:%f in:%d out:%d\n", t, src_nb_samples, ret);
  170. fwrite(dst_data[0], 1, dst_bufsize, dst_file);
  171. } while (t < 10);
  172. if ((ret = get_format_from_sample_fmt(&fmt, dst_sample_fmt)) < 0)
  173. goto end;
  174. fprintf(stderr, "Resampling succeeded. Play the output file with the command:\n"
  175. "ffplay -f %s -channel_layout %"PRId64" -channels %d -ar %d %s\n",
  176. fmt, dst_ch_layout, dst_nb_channels, dst_rate, dst_filename);
  177. end:
  178. if (dst_file)
  179. fclose(dst_file);
  180. if (src_data)
  181. av_freep(&src_data[0]);
  182. av_freep(&src_data);
  183. if (dst_data)
  184. av_freep(&dst_data[0]);
  185. av_freep(&dst_data);
  186. swr_free(&swr_ctx);
  187. return ret < 0;
  188. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

676

主题

2229

帖子

3万

积分

吼山居士

Rank: 9Rank: 9Rank: 9

积分
34932
QQ
 楼主| 发表于 2013-2-25 16:43:05 | 显示全部楼层

ffmpeg 示例代码大全 - scaling_video.c

  1. /*
  2. * Copyright (c) 2012 Stefano Sabatini
  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. #include <libavutil/imgutils.h>
  23. #include <libavutil/parseutils.h>
  24. #include <libswscale/swscale.h>
  25. static void fill_yuv_image(uint8_t *data[4], int linesize[4],
  26. int width, int height, int frame_index)
  27. {
  28. int x, y;
  29. /* Y */
  30. for (y = 0; y < height; y++)
  31. for (x = 0; x < width; x++)
  32. data[0][y * linesize[0] + x] = x + y + frame_index * 3;
  33. /* Cb and Cr */
  34. for (y = 0; y < height / 2; y++) {
  35. for (x = 0; x < width / 2; x++) {
  36. data[1][y * linesize[1] + x] = 128 + y + frame_index * 2;
  37. data[2][y * linesize[2] + x] = 64 + x + frame_index * 5;
  38. }
  39. }
  40. }
  41. int main(int argc, char **argv)
  42. {
  43. uint8_t *src_data[4], *dst_data[4];
  44. int src_linesize[4], dst_linesize[4];
  45. int src_w = 320, src_h = 240, dst_w, dst_h;
  46. enum AVPixelFormat src_pix_fmt = AV_PIX_FMT_YUV420P, dst_pix_fmt = AV_PIX_FMT_RGB24;
  47. const char *dst_size = NULL;
  48. const char *dst_filename = NULL;
  49. FILE *dst_file;
  50. int dst_bufsize;
  51. struct SwsContext *sws_ctx;
  52. int i, ret;
  53. if (argc != 3) {
  54. fprintf(stderr, "Usage: %s output_file output_size\n"
  55. "API example program to show how to scale an image with libswscale.\n"
  56. "This program generates a series of pictures, rescales them to the given "
  57. "output_size and saves them to an output file named output_file\n."
  58. "\n", argv[0]);
  59. exit(1);
  60. }
  61. dst_filename = argv[1];
  62. dst_size = argv[2];
  63. if (av_parse_video_size(&dst_w, &dst_h, dst_size) < 0) {
  64. fprintf(stderr,
  65. "Invalid size '%s', must be in the form WxH or a valid size abbreviation\n",
  66. dst_size);
  67. exit(1);
  68. }
  69. dst_file = fopen(dst_filename, "wb");
  70. if (!dst_file) {
  71. fprintf(stderr, "Could not open destination file %s\n", dst_filename);
  72. exit(1);
  73. }
  74. /* create scaling context */
  75. sws_ctx = sws_getContext(src_w, src_h, src_pix_fmt,
  76. dst_w, dst_h, dst_pix_fmt,
  77. SWS_BILINEAR, NULL, NULL, NULL);
  78. if (!sws_ctx) {
  79. fprintf(stderr,
  80. "Impossible to create scale context for the conversion "
  81. "fmt:%s s:%dx%d -> fmt:%s s:%dx%d\n",
  82. av_get_pix_fmt_name(src_pix_fmt), src_w, src_h,
  83. av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h);
  84. ret = AVERROR(EINVAL);
  85. goto end;
  86. }
  87. /* allocate source and destination image buffers */
  88. if ((ret = av_image_alloc(src_data, src_linesize,
  89. src_w, src_h, src_pix_fmt, 16)) < 0) {
  90. fprintf(stderr, "Could not allocate source image\n");
  91. goto end;
  92. }
  93. /* buffer is going to be written to rawvideo file, no alignment */
  94. if ((ret = av_image_alloc(dst_data, dst_linesize,
  95. dst_w, dst_h, dst_pix_fmt, 1)) < 0) {
  96. fprintf(stderr, "Could not allocate destination image\n");
  97. goto end;
  98. }
  99. dst_bufsize = ret;
  100. for (i = 0; i < 100; i++) {
  101. /* generate synthetic video */
  102. fill_yuv_image(src_data, src_linesize, src_w, src_h, i);
  103. /* convert to destination format */
  104. sws_scale(sws_ctx, (const uint8_t * const*)src_data,
  105. src_linesize, 0, src_h, dst_data, dst_linesize);
  106. /* write scaled image to file */
  107. fwrite(dst_data[0], 1, dst_bufsize, dst_file);
  108. }
  109. fprintf(stderr, "Scaling succeeded. Play the output file with the command:\n"
  110. "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
  111. av_get_pix_fmt_name(dst_pix_fmt), dst_w, dst_h, dst_filename);
  112. end:
  113. if (dst_file)
  114. fclose(dst_file);
  115. av_freep(&src_data[0]);
  116. av_freep(&dst_data[0]);
  117. sws_freeContext(sws_ctx);
  118. return ret < 0;
  119. }
复制代码
拒收论坛短消息,有问题请直接在论坛提问。

所有我的答复与微博同步,欢迎收听我的腾讯微博, 新浪微博,第一时间得到问题答复。

Item 1: Don't abuse your power        条款一:不要滥用权利
Item 2: Share expert knowledge        条款二:分享你的知识
Item 3: Respect other people's privacy        条款三:尊重他人的隐私
Item 4: Make yourself look good online        条款四:给自己网上留个好印象
Item 5: Help keep flame wars under control        条款五:平心静气地争论
Item 6: Respect other people's time and bandwidth        条款六:尊重别人的时间和带宽
回复 支持 反对

使用道具 举报

  发表于 2013-3-29 14:49:56
貌似只是贴了ffmpeg自带的例子吧
回复 支持 反对

使用道具

高级模式
B Color Image Link Quote Code Smilies

本版积分规则

Archiver||С|Comsenz Inc.  

GMT+8, 2017-12-13 19:06 , Processed in 0.050187 second(s), 26 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表