You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2577 lines
81KB

  1. /*
  2. * FFmpeg main
  3. * Copyright (c) 2000, 2001, 2002 Fabrice Bellard
  4. *
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Lesser General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Lesser General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Lesser General Public
  16. * License along with this library; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. */
  19. #define HAVE_AV_CONFIG_H
  20. #include "avformat.h"
  21. #ifndef CONFIG_WIN32
  22. #include <unistd.h>
  23. #include <fcntl.h>
  24. #include <sys/ioctl.h>
  25. #include <sys/time.h>
  26. #include <termios.h>
  27. #include <sys/resource.h>
  28. #endif
  29. #ifdef __BEOS__
  30. /* for snooze() */
  31. #include <OS.h>
  32. #endif
  33. #include <time.h>
  34. #include <ctype.h>
  35. #define MAXINT64 INT64_C(0x7fffffffffffffff)
  36. typedef struct {
  37. const char *name;
  38. int flags;
  39. #define HAS_ARG 0x0001
  40. #define OPT_BOOL 0x0002
  41. #define OPT_EXPERT 0x0004
  42. #define OPT_STRING 0x0008
  43. union {
  44. void (*func_arg)();
  45. int *int_arg;
  46. char **str_arg;
  47. } u;
  48. const char *help;
  49. const char *argname;
  50. } OptionDef;
  51. /* select an input stream for an output stream */
  52. typedef struct AVStreamMap {
  53. int file_index;
  54. int stream_index;
  55. } AVStreamMap;
  56. extern const OptionDef options[];
  57. void show_help(void);
  58. #define MAX_FILES 20
  59. static AVFormatContext *input_files[MAX_FILES];
  60. static int nb_input_files = 0;
  61. static AVFormatContext *output_files[MAX_FILES];
  62. static int nb_output_files = 0;
  63. static AVStreamMap stream_maps[MAX_FILES];
  64. static int nb_stream_maps;
  65. static AVInputFormat *file_iformat;
  66. static AVOutputFormat *file_oformat;
  67. static int frame_width = 160;
  68. static int frame_height = 128;
  69. static int frame_topBand = 0;
  70. static int frame_bottomBand = 0;
  71. static int frame_leftBand = 0;
  72. static int frame_rightBand = 0;
  73. static int frame_rate = 25 * FRAME_RATE_BASE;
  74. static int video_bit_rate = 200*1000;
  75. static int video_bit_rate_tolerance = 4000*1000;
  76. static int video_qscale = 0;
  77. static int video_qmin = 2;
  78. static int video_qmax = 31;
  79. static int video_qdiff = 3;
  80. static float video_qblur = 0.5;
  81. static float video_qcomp = 0.5;
  82. #if 0 //experimental, (can be removed)
  83. static float video_rc_qsquish=1.0;
  84. static float video_rc_qmod_amp=0;
  85. static int video_rc_qmod_freq=0;
  86. #endif
  87. static char *video_rc_override_string=NULL;
  88. static char *video_rc_eq="tex^qComp";
  89. static int video_rc_buffer_size=0;
  90. static float video_rc_buffer_aggressivity=1.0;
  91. static int video_rc_max_rate=0;
  92. static int video_rc_min_rate=0;
  93. static float video_rc_initial_cplx=0;
  94. static float video_b_qfactor = 1.25;
  95. static float video_b_qoffset = 1.25;
  96. static float video_i_qfactor = -0.8;
  97. static float video_i_qoffset = 0.0;
  98. static int me_method = 0;
  99. static int video_disable = 0;
  100. static int video_codec_id = CODEC_ID_NONE;
  101. static int same_quality = 0;
  102. static int b_frames = 0;
  103. static int use_hq = 0;
  104. static int use_4mv = 0;
  105. static int do_deinterlace = 0;
  106. static int workaround_bugs = FF_BUG_AUTODETECT;
  107. static int error_resilience = 2;
  108. static int error_concealment = 3;
  109. static int dct_algo = 0;
  110. static int idct_algo = 0;
  111. static int use_part = 0;
  112. static int packet_size = 0;
  113. static int gop_size = 12;
  114. static int intra_only = 0;
  115. static int audio_sample_rate = 44100;
  116. static int audio_bit_rate = 64000;
  117. static int audio_disable = 0;
  118. static int audio_channels = 1;
  119. static int audio_codec_id = CODEC_ID_NONE;
  120. static INT64 recording_time = 0;
  121. static int file_overwrite = 0;
  122. static char *str_title = NULL;
  123. static char *str_author = NULL;
  124. static char *str_copyright = NULL;
  125. static char *str_comment = NULL;
  126. static int do_benchmark = 0;
  127. static int do_hex_dump = 0;
  128. static int do_play = 0;
  129. static int do_psnr = 0;
  130. static int do_vstats = 0;
  131. static int do_pass = 0;
  132. static char *pass_logfilename = NULL;
  133. static int audio_stream_copy = 0;
  134. static int video_stream_copy = 0;
  135. #define DEFAULT_PASS_LOGFILENAME "ffmpeg2pass"
  136. #ifndef CONFIG_AUDIO_OSS
  137. const char *audio_device = "none";
  138. #endif
  139. #ifndef CONFIG_VIDEO4LINUX
  140. const char *v4l_device = "none";
  141. #endif
  142. typedef struct AVOutputStream {
  143. int file_index; /* file index */
  144. int index; /* stream index in the output file */
  145. int source_index; /* AVInputStream index */
  146. AVStream *st; /* stream in the output file */
  147. int encoding_needed; /* true if encoding needed for this stream */
  148. int frame_number;
  149. /* input pts and corresponding output pts
  150. for A/V sync */
  151. double sync_ipts;
  152. INT64 sync_opts;
  153. /* video only */
  154. AVPicture pict_tmp; /* temporary image for resizing */
  155. int video_resample;
  156. ImgReSampleContext *img_resample_ctx; /* for image resampling */
  157. /* audio only */
  158. int audio_resample;
  159. ReSampleContext *resample; /* for audio resampling */
  160. FifoBuffer fifo; /* for compression: one audio fifo per codec */
  161. FILE *logfile;
  162. } AVOutputStream;
  163. typedef struct AVInputStream {
  164. int file_index;
  165. int index;
  166. AVStream *st;
  167. int discard; /* true if stream data should be discarded */
  168. int decoding_needed; /* true if the packets must be decoded in 'raw_fifo' */
  169. INT64 sample_index; /* current sample */
  170. int frame_decoded; /* true if a video or audio frame has been decoded */
  171. } AVInputStream;
  172. typedef struct AVInputFile {
  173. int eof_reached; /* true if eof reached */
  174. int ist_index; /* index of first stream in ist_table */
  175. int buffer_size; /* current total buffer size */
  176. int buffer_size_max; /* buffer size at which we consider we can stop
  177. buffering */
  178. int nb_streams; /* nb streams we are aware of */
  179. } AVInputFile;
  180. #ifndef CONFIG_WIN32
  181. /* init terminal so that we can grab keys */
  182. static struct termios oldtty;
  183. static void term_exit(void)
  184. {
  185. tcsetattr (0, TCSANOW, &oldtty);
  186. }
  187. static void term_init(void)
  188. {
  189. struct termios tty;
  190. tcgetattr (0, &tty);
  191. oldtty = tty;
  192. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  193. |INLCR|IGNCR|ICRNL|IXON);
  194. tty.c_oflag |= OPOST;
  195. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  196. tty.c_cflag &= ~(CSIZE|PARENB);
  197. tty.c_cflag |= CS8;
  198. tty.c_cc[VMIN] = 1;
  199. tty.c_cc[VTIME] = 0;
  200. tcsetattr (0, TCSANOW, &tty);
  201. atexit(term_exit);
  202. }
  203. /* read a key without blocking */
  204. static int read_key(void)
  205. {
  206. struct timeval tv;
  207. int n;
  208. unsigned char ch;
  209. fd_set rfds;
  210. FD_ZERO(&rfds);
  211. FD_SET(0, &rfds);
  212. tv.tv_sec = 0;
  213. tv.tv_usec = 0;
  214. n = select(1, &rfds, NULL, NULL, &tv);
  215. if (n > 0) {
  216. n = read(0, &ch, 1);
  217. if (n == 1)
  218. return ch;
  219. return n;
  220. }
  221. return -1;
  222. }
  223. #else
  224. /* no interactive support */
  225. static void term_exit(void)
  226. {
  227. }
  228. static void term_init(void)
  229. {
  230. }
  231. static int read_key(void)
  232. {
  233. return 0;
  234. }
  235. #endif
  236. int read_ffserver_streams(AVFormatContext *s, const char *filename)
  237. {
  238. int i, err;
  239. AVFormatContext *ic;
  240. err = av_open_input_file(&ic, filename, NULL, FFM_PACKET_SIZE, NULL);
  241. if (err < 0)
  242. return err;
  243. /* copy stream format */
  244. s->nb_streams = ic->nb_streams;
  245. for(i=0;i<ic->nb_streams;i++) {
  246. AVStream *st;
  247. st = av_mallocz(sizeof(AVFormatContext));
  248. memcpy(st, ic->streams[i], sizeof(AVStream));
  249. s->streams[i] = st;
  250. }
  251. av_close_input_file(ic);
  252. return 0;
  253. }
  254. #define MAX_AUDIO_PACKET_SIZE 16384
  255. static void do_audio_out(AVFormatContext *s,
  256. AVOutputStream *ost,
  257. AVInputStream *ist,
  258. unsigned char *buf, int size)
  259. {
  260. UINT8 *buftmp;
  261. UINT8 audio_buf[2*MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
  262. UINT8 audio_out[MAX_AUDIO_PACKET_SIZE]; /* XXX: allocate it */
  263. int size_out, frame_bytes, ret;
  264. AVCodecContext *enc;
  265. enc = &ost->st->codec;
  266. if (ost->audio_resample) {
  267. buftmp = audio_buf;
  268. size_out = audio_resample(ost->resample,
  269. (short *)buftmp, (short *)buf,
  270. size / (ist->st->codec.channels * 2));
  271. size_out = size_out * enc->channels * 2;
  272. } else {
  273. buftmp = buf;
  274. size_out = size;
  275. }
  276. /* now encode as many frames as possible */
  277. if (enc->frame_size > 1) {
  278. /* output resampled raw samples */
  279. fifo_write(&ost->fifo, buftmp, size_out,
  280. &ost->fifo.wptr);
  281. frame_bytes = enc->frame_size * 2 * enc->channels;
  282. while (fifo_read(&ost->fifo, audio_buf, frame_bytes,
  283. &ost->fifo.rptr) == 0) {
  284. ret = avcodec_encode_audio(enc, audio_out, sizeof(audio_out),
  285. (short *)audio_buf);
  286. av_write_frame(s, ost->index, audio_out, ret);
  287. }
  288. } else {
  289. /* output a pcm frame */
  290. /* XXX: change encoding codec API to avoid this ? */
  291. switch(enc->codec->id) {
  292. case CODEC_ID_PCM_S16LE:
  293. case CODEC_ID_PCM_S16BE:
  294. case CODEC_ID_PCM_U16LE:
  295. case CODEC_ID_PCM_U16BE:
  296. break;
  297. default:
  298. size_out = size_out >> 1;
  299. break;
  300. }
  301. ret = avcodec_encode_audio(enc, audio_out, size_out,
  302. (short *)buftmp);
  303. av_write_frame(s, ost->index, audio_out, ret);
  304. }
  305. }
  306. /* write a picture to a raw mux */
  307. static void write_picture(AVFormatContext *s, int index, AVPicture *picture,
  308. int pix_fmt, int w, int h)
  309. {
  310. UINT8 *buf, *src, *dest;
  311. int size, j, i;
  312. /* XXX: not efficient, should add test if we can take
  313. directly the AVPicture */
  314. switch(pix_fmt) {
  315. case PIX_FMT_YUV420P:
  316. size = avpicture_get_size(pix_fmt, w, h);
  317. buf = av_malloc(size);
  318. if (!buf)
  319. return;
  320. dest = buf;
  321. for(i=0;i<3;i++) {
  322. if (i == 1) {
  323. w >>= 1;
  324. h >>= 1;
  325. }
  326. src = picture->data[i];
  327. for(j=0;j<h;j++) {
  328. memcpy(dest, src, w);
  329. dest += w;
  330. src += picture->linesize[i];
  331. }
  332. }
  333. break;
  334. case PIX_FMT_YUV422P:
  335. size = (w * h) * 2;
  336. buf = av_malloc(size);
  337. if (!buf)
  338. return;
  339. dest = buf;
  340. for(i=0;i<3;i++) {
  341. if (i == 1) {
  342. w >>= 1;
  343. }
  344. src = picture->data[i];
  345. for(j=0;j<h;j++) {
  346. memcpy(dest, src, w);
  347. dest += w;
  348. src += picture->linesize[i];
  349. }
  350. }
  351. break;
  352. case PIX_FMT_YUV444P:
  353. size = (w * h) * 3;
  354. buf = av_malloc(size);
  355. if (!buf)
  356. return;
  357. dest = buf;
  358. for(i=0;i<3;i++) {
  359. src = picture->data[i];
  360. for(j=0;j<h;j++) {
  361. memcpy(dest, src, w);
  362. dest += w;
  363. src += picture->linesize[i];
  364. }
  365. }
  366. break;
  367. case PIX_FMT_YUV422:
  368. size = (w * h) * 2;
  369. buf = av_malloc(size);
  370. if (!buf)
  371. return;
  372. dest = buf;
  373. src = picture->data[0];
  374. for(j=0;j<h;j++) {
  375. memcpy(dest, src, w * 2);
  376. dest += w * 2;
  377. src += picture->linesize[0];
  378. }
  379. break;
  380. case PIX_FMT_RGB24:
  381. case PIX_FMT_BGR24:
  382. size = (w * h) * 3;
  383. buf = av_malloc(size);
  384. if (!buf)
  385. return;
  386. dest = buf;
  387. src = picture->data[0];
  388. for(j=0;j<h;j++) {
  389. memcpy(dest, src, w * 3);
  390. dest += w * 3;
  391. src += picture->linesize[0];
  392. }
  393. break;
  394. default:
  395. return;
  396. }
  397. av_write_frame(s, index, buf, size);
  398. av_free(buf);
  399. }
  400. /* we begin to correct av delay at this threshold */
  401. #define AV_DELAY_MAX 0.100
  402. static void do_video_out(AVFormatContext *s,
  403. AVOutputStream *ost,
  404. AVInputStream *ist,
  405. AVPicture *picture1,
  406. int *frame_size, AVOutputStream *audio_sync)
  407. {
  408. int nb_frames, i, ret;
  409. AVPicture *picture, *picture2, *pict;
  410. AVPicture picture_tmp1, picture_tmp2;
  411. static UINT8 *video_buffer;
  412. UINT8 *buf = NULL, *buf1 = NULL;
  413. AVCodecContext *enc, *dec;
  414. #define VIDEO_BUFFER_SIZE (1024*1024)
  415. enc = &ost->st->codec;
  416. dec = &ist->st->codec;
  417. /* by default, we output a single frame */
  418. nb_frames = 1;
  419. /* NOTE: the A/V sync is always done by considering the audio is
  420. the master clock. It is suffisant for transcoding or playing,
  421. but not for the general case */
  422. if (audio_sync) {
  423. /* compute the A-V delay and duplicate/remove frames if needed */
  424. double adelta, vdelta, apts, vpts, av_delay;
  425. if (audio_sync->sync_ipts != AV_NOPTS_VALUE &&
  426. ost->sync_ipts != AV_NOPTS_VALUE) {
  427. adelta = (double)(ost->st->pts.val - audio_sync->sync_opts) *
  428. s->pts_num / s->pts_den;
  429. apts = audio_sync->sync_ipts + adelta;
  430. vdelta = (double)(ost->st->pts.val - ost->sync_opts) *
  431. s->pts_num / s->pts_den;
  432. vpts = ost->sync_ipts + vdelta;
  433. av_delay = apts - vpts;
  434. // printf("delay=%f\n", av_delay);
  435. if (av_delay < -AV_DELAY_MAX)
  436. nb_frames = 2;
  437. else if (av_delay > AV_DELAY_MAX)
  438. nb_frames = 0;
  439. }
  440. }
  441. /* XXX: also handle frame rate conversion */
  442. if (nb_frames <= 0)
  443. return;
  444. if (!video_buffer)
  445. video_buffer = av_malloc(VIDEO_BUFFER_SIZE);
  446. if (!video_buffer)
  447. return;
  448. /* deinterlace : must be done before any resize */
  449. if (do_deinterlace) {
  450. int size;
  451. /* create temporary picture */
  452. size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
  453. buf1 = av_malloc(size);
  454. if (!buf1)
  455. return;
  456. picture2 = &picture_tmp2;
  457. avpicture_fill(picture2, buf1, dec->pix_fmt, dec->width, dec->height);
  458. if (avpicture_deinterlace(picture2, picture1,
  459. dec->pix_fmt, dec->width, dec->height) < 0) {
  460. /* if error, do not deinterlace */
  461. av_free(buf1);
  462. buf1 = NULL;
  463. picture2 = picture1;
  464. }
  465. } else {
  466. picture2 = picture1;
  467. }
  468. /* convert pixel format if needed */
  469. if (enc->pix_fmt != dec->pix_fmt) {
  470. int size;
  471. /* create temporary picture */
  472. size = avpicture_get_size(enc->pix_fmt, dec->width, dec->height);
  473. buf = av_malloc(size);
  474. if (!buf)
  475. return;
  476. pict = &picture_tmp1;
  477. avpicture_fill(pict, buf, enc->pix_fmt, dec->width, dec->height);
  478. if (img_convert(pict, enc->pix_fmt,
  479. picture2, dec->pix_fmt,
  480. dec->width, dec->height) < 0) {
  481. fprintf(stderr, "pixel format conversion not handled\n");
  482. goto the_end;
  483. }
  484. } else {
  485. pict = picture2;
  486. }
  487. /* XXX: resampling could be done before raw format convertion in
  488. some cases to go faster */
  489. /* XXX: only works for YUV420P */
  490. if (ost->video_resample) {
  491. picture = &ost->pict_tmp;
  492. img_resample(ost->img_resample_ctx, picture, pict);
  493. } else {
  494. picture = pict;
  495. }
  496. /* duplicates frame if needed */
  497. /* XXX: pb because no interleaving */
  498. for(i=0;i<nb_frames;i++) {
  499. if (enc->codec_id != CODEC_ID_RAWVIDEO) {
  500. /* handles sameq here. This is not correct because it may
  501. not be a global option */
  502. if (same_quality) {
  503. enc->quality = dec->quality;
  504. }
  505. ret = avcodec_encode_video(enc,
  506. video_buffer, VIDEO_BUFFER_SIZE,
  507. picture);
  508. //enc->frame_number = enc->real_pict_num;
  509. av_write_frame(s, ost->index, video_buffer, ret);
  510. *frame_size = ret;
  511. //fprintf(stderr,"\nFrame: %3d %3d size: %5d type: %d",
  512. // enc->frame_number-1, enc->real_pict_num, ret,
  513. // enc->pict_type);
  514. /* if two pass, output log */
  515. if (ost->logfile && enc->stats_out) {
  516. fprintf(ost->logfile, "%s", enc->stats_out);
  517. }
  518. } else {
  519. if (s->oformat->flags & AVFMT_RAWPICTURE) {
  520. /* raw pictures are written as AVPicture structure to
  521. avoid any copies. We support temorarily the older
  522. method. */
  523. av_write_frame(s, ost->index,
  524. (UINT8 *)picture, sizeof(AVPicture));
  525. } else {
  526. write_picture(s, ost->index, picture, enc->pix_fmt,
  527. enc->width, enc->height);
  528. }
  529. }
  530. ost->frame_number++;
  531. }
  532. the_end:
  533. av_free(buf);
  534. av_free(buf1);
  535. }
  536. static void do_video_stats(AVFormatContext *os, AVOutputStream *ost,
  537. int frame_size)
  538. {
  539. static FILE *fvstats=NULL;
  540. static INT64 total_size = 0;
  541. char filename[40];
  542. time_t today2;
  543. struct tm *today;
  544. AVCodecContext *enc;
  545. int frame_number;
  546. INT64 ti;
  547. double ti1, bitrate, avg_bitrate;
  548. if (!fvstats) {
  549. today2 = time(NULL);
  550. today = localtime(&today2);
  551. sprintf(filename, "vstats_%02d%02d%02d.log", today->tm_hour,
  552. today->tm_min,
  553. today->tm_sec);
  554. fvstats = fopen(filename,"w");
  555. if (!fvstats) {
  556. perror("fopen");
  557. exit(1);
  558. }
  559. }
  560. ti = MAXINT64;
  561. enc = &ost->st->codec;
  562. total_size += frame_size;
  563. if (enc->codec_type == CODEC_TYPE_VIDEO) {
  564. frame_number = ost->frame_number;
  565. fprintf(fvstats, "frame= %5d q= %2d ", frame_number, enc->quality);
  566. if (do_psnr)
  567. fprintf(fvstats, "PSNR= %6.2f ", enc->psnr_y);
  568. fprintf(fvstats,"f_size= %6d ", frame_size);
  569. /* compute pts value */
  570. ti1 = (double)ost->st->pts.val * os->pts_num / os->pts_den;
  571. if (ti1 < 0.01)
  572. ti1 = 0.01;
  573. bitrate = (double)(frame_size * 8) * enc->frame_rate / FRAME_RATE_BASE / 1000.0;
  574. avg_bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  575. fprintf(fvstats, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  576. (double)total_size / 1024, ti1, bitrate, avg_bitrate);
  577. fprintf(fvstats,"type= %s\n", enc->key_frame == 1 ? "I" : "P");
  578. }
  579. }
  580. void print_report(AVFormatContext **output_files,
  581. AVOutputStream **ost_table, int nb_ostreams,
  582. int is_last_report)
  583. {
  584. char buf[1024];
  585. AVOutputStream *ost;
  586. AVFormatContext *oc, *os;
  587. INT64 total_size;
  588. AVCodecContext *enc;
  589. int frame_number, vid, i;
  590. double bitrate, ti1, pts;
  591. static INT64 last_time = -1;
  592. if (!is_last_report) {
  593. INT64 cur_time;
  594. /* display the report every 0.5 seconds */
  595. cur_time = av_gettime();
  596. if (last_time == -1) {
  597. last_time = cur_time;
  598. return;
  599. }
  600. if ((cur_time - last_time) < 500000)
  601. return;
  602. last_time = cur_time;
  603. }
  604. oc = output_files[0];
  605. total_size = url_ftell(&oc->pb);
  606. buf[0] = '\0';
  607. ti1 = 1e10;
  608. vid = 0;
  609. for(i=0;i<nb_ostreams;i++) {
  610. ost = ost_table[i];
  611. os = output_files[ost->file_index];
  612. enc = &ost->st->codec;
  613. if (!vid && enc->codec_type == CODEC_TYPE_VIDEO) {
  614. frame_number = ost->frame_number;
  615. sprintf(buf + strlen(buf), "frame=%5d q=%2d ",
  616. frame_number, enc->quality);
  617. if (do_psnr)
  618. sprintf(buf + strlen(buf), "PSNR=%6.2f ", enc->psnr_y);
  619. vid = 1;
  620. }
  621. /* compute min output value */
  622. pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
  623. if ((pts < ti1) && (pts > 0))
  624. ti1 = pts;
  625. }
  626. if (ti1 < 0.01)
  627. ti1 = 0.01;
  628. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  629. sprintf(buf + strlen(buf),
  630. "size=%8.0fkB time=%0.1f bitrate=%6.1fkbits/s",
  631. (double)total_size / 1024, ti1, bitrate);
  632. fprintf(stderr, "%s ", buf);
  633. if (is_last_report) {
  634. fprintf(stderr, "\n");
  635. } else {
  636. fprintf(stderr, "\r");
  637. fflush(stderr);
  638. }
  639. }
  640. /*
  641. * The following code is the main loop of the file converter
  642. */
  643. static int av_encode(AVFormatContext **output_files,
  644. int nb_output_files,
  645. AVFormatContext **input_files,
  646. int nb_input_files,
  647. AVStreamMap *stream_maps, int nb_stream_maps)
  648. {
  649. int ret, i, j, k, n, nb_istreams = 0, nb_ostreams = 0, pts_set;
  650. AVFormatContext *is, *os;
  651. AVCodecContext *codec, *icodec;
  652. AVOutputStream *ost, **ost_table = NULL;
  653. AVInputStream *ist, **ist_table = NULL;
  654. AVInputFile *file_table;
  655. AVFormatContext *stream_no_data;
  656. int key;
  657. file_table= (AVInputFile*) av_mallocz(nb_input_files * sizeof(AVInputFile));
  658. if (!file_table)
  659. goto fail;
  660. /* input stream init */
  661. j = 0;
  662. for(i=0;i<nb_input_files;i++) {
  663. is = input_files[i];
  664. file_table[i].ist_index = j;
  665. file_table[i].nb_streams = is->nb_streams;
  666. j += is->nb_streams;
  667. }
  668. nb_istreams = j;
  669. ist_table = av_mallocz(nb_istreams * sizeof(AVInputStream *));
  670. if (!ist_table)
  671. goto fail;
  672. for(i=0;i<nb_istreams;i++) {
  673. ist = av_mallocz(sizeof(AVInputStream));
  674. if (!ist)
  675. goto fail;
  676. ist_table[i] = ist;
  677. }
  678. j = 0;
  679. for(i=0;i<nb_input_files;i++) {
  680. is = input_files[i];
  681. for(k=0;k<is->nb_streams;k++) {
  682. ist = ist_table[j++];
  683. ist->st = is->streams[k];
  684. ist->file_index = i;
  685. ist->index = k;
  686. ist->discard = 1; /* the stream is discarded by default
  687. (changed later) */
  688. }
  689. }
  690. /* output stream init */
  691. nb_ostreams = 0;
  692. for(i=0;i<nb_output_files;i++) {
  693. os = output_files[i];
  694. nb_ostreams += os->nb_streams;
  695. }
  696. if (nb_stream_maps > 0 && nb_stream_maps != nb_ostreams) {
  697. fprintf(stderr, "Number of stream maps must match number of output streams\n");
  698. exit(1);
  699. }
  700. ost_table = av_mallocz(sizeof(AVOutputStream *) * nb_ostreams);
  701. if (!ost_table)
  702. goto fail;
  703. for(i=0;i<nb_ostreams;i++) {
  704. ost = av_mallocz(sizeof(AVOutputStream));
  705. if (!ost)
  706. goto fail;
  707. ost_table[i] = ost;
  708. }
  709. n = 0;
  710. for(k=0;k<nb_output_files;k++) {
  711. os = output_files[k];
  712. for(i=0;i<os->nb_streams;i++) {
  713. int found;
  714. ost = ost_table[n++];
  715. ost->file_index = k;
  716. ost->index = i;
  717. ost->st = os->streams[i];
  718. if (nb_stream_maps > 0) {
  719. ost->source_index = file_table[stream_maps[n-1].file_index].ist_index +
  720. stream_maps[n-1].stream_index;
  721. } else {
  722. /* get corresponding input stream index : we select the first one with the right type */
  723. found = 0;
  724. for(j=0;j<nb_istreams;j++) {
  725. ist = ist_table[j];
  726. if (ist->discard &&
  727. ist->st->codec.codec_type == ost->st->codec.codec_type) {
  728. ost->source_index = j;
  729. found = 1;
  730. }
  731. }
  732. if (!found) {
  733. /* try again and reuse existing stream */
  734. for(j=0;j<nb_istreams;j++) {
  735. ist = ist_table[j];
  736. if (ist->st->codec.codec_type == ost->st->codec.codec_type) {
  737. ost->source_index = j;
  738. found = 1;
  739. }
  740. }
  741. if (!found) {
  742. fprintf(stderr, "Could not find input stream matching output stream #%d.%d\n",
  743. ost->file_index, ost->index);
  744. exit(1);
  745. }
  746. }
  747. }
  748. ist = ist_table[ost->source_index];
  749. ist->discard = 0;
  750. }
  751. }
  752. /* for each output stream, we compute the right encoding parameters */
  753. for(i=0;i<nb_ostreams;i++) {
  754. ost = ost_table[i];
  755. ist = ist_table[ost->source_index];
  756. codec = &ost->st->codec;
  757. icodec = &ist->st->codec;
  758. if (ost->st->stream_copy) {
  759. /* if stream_copy is selected, no need to decode or encode */
  760. codec->codec_id = icodec->codec_id;
  761. codec->codec_type = icodec->codec_type;
  762. codec->codec_tag = icodec->codec_tag;
  763. codec->bit_rate = icodec->bit_rate;
  764. switch(codec->codec_type) {
  765. case CODEC_TYPE_AUDIO:
  766. codec->sample_rate = icodec->sample_rate;
  767. codec->channels = icodec->channels;
  768. break;
  769. case CODEC_TYPE_VIDEO:
  770. codec->frame_rate = icodec->frame_rate;
  771. codec->width = icodec->width;
  772. codec->height = icodec->height;
  773. break;
  774. default:
  775. av_abort();
  776. }
  777. } else {
  778. switch(codec->codec_type) {
  779. case CODEC_TYPE_AUDIO:
  780. if (fifo_init(&ost->fifo, 2 * MAX_AUDIO_PACKET_SIZE))
  781. goto fail;
  782. if (codec->channels == icodec->channels &&
  783. codec->sample_rate == icodec->sample_rate) {
  784. ost->audio_resample = 0;
  785. } else {
  786. if (codec->channels != icodec->channels &&
  787. icodec->codec_id == CODEC_ID_AC3) {
  788. /* Special case for 5:1 AC3 input */
  789. /* and mono or stereo output */
  790. /* Request specific number of channels */
  791. icodec->channels = codec->channels;
  792. if (codec->sample_rate == icodec->sample_rate)
  793. ost->audio_resample = 0;
  794. else {
  795. ost->audio_resample = 1;
  796. ost->resample = audio_resample_init(codec->channels, icodec->channels,
  797. codec->sample_rate,
  798. icodec->sample_rate);
  799. }
  800. /* Request specific number of channels */
  801. icodec->channels = codec->channels;
  802. } else {
  803. ost->audio_resample = 1;
  804. ost->resample = audio_resample_init(codec->channels, icodec->channels,
  805. codec->sample_rate,
  806. icodec->sample_rate);
  807. }
  808. }
  809. ist->decoding_needed = 1;
  810. ost->encoding_needed = 1;
  811. break;
  812. case CODEC_TYPE_VIDEO:
  813. if (codec->width == icodec->width &&
  814. codec->height == icodec->height) {
  815. ost->video_resample = 0;
  816. } else {
  817. UINT8 *buf;
  818. ost->video_resample = 1;
  819. buf = av_malloc((codec->width * codec->height * 3) / 2);
  820. if (!buf)
  821. goto fail;
  822. ost->pict_tmp.data[0] = buf;
  823. ost->pict_tmp.data[1] = ost->pict_tmp.data[0] + (codec->width * codec->height);
  824. ost->pict_tmp.data[2] = ost->pict_tmp.data[1] + (codec->width * codec->height) / 4;
  825. ost->pict_tmp.linesize[0] = codec->width;
  826. ost->pict_tmp.linesize[1] = codec->width / 2;
  827. ost->pict_tmp.linesize[2] = codec->width / 2;
  828. ost->img_resample_ctx = img_resample_full_init(
  829. ost->st->codec.width, ost->st->codec.height,
  830. ist->st->codec.width, ist->st->codec.height,
  831. frame_topBand, frame_bottomBand,
  832. frame_leftBand, frame_rightBand);
  833. }
  834. ost->encoding_needed = 1;
  835. ist->decoding_needed = 1;
  836. break;
  837. default:
  838. av_abort();
  839. }
  840. /* two pass mode */
  841. if (ost->encoding_needed &&
  842. (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
  843. char logfilename[1024];
  844. FILE *f;
  845. int size;
  846. char *logbuffer;
  847. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  848. pass_logfilename ?
  849. pass_logfilename : DEFAULT_PASS_LOGFILENAME, i);
  850. if (codec->flags & CODEC_FLAG_PASS1) {
  851. f = fopen(logfilename, "w");
  852. if (!f) {
  853. perror(logfilename);
  854. exit(1);
  855. }
  856. ost->logfile = f;
  857. } else {
  858. /* read the log file */
  859. f = fopen(logfilename, "r");
  860. if (!f) {
  861. perror(logfilename);
  862. exit(1);
  863. }
  864. fseek(f, 0, SEEK_END);
  865. size = ftell(f);
  866. fseek(f, 0, SEEK_SET);
  867. logbuffer = av_malloc(size + 1);
  868. if (!logbuffer) {
  869. fprintf(stderr, "Could not allocate log buffer\n");
  870. exit(1);
  871. }
  872. fread(logbuffer, 1, size, f);
  873. fclose(f);
  874. logbuffer[size] = '\0';
  875. codec->stats_in = logbuffer;
  876. }
  877. }
  878. }
  879. }
  880. /* dump the file output parameters - cannot be done before in case
  881. of stream copy */
  882. for(i=0;i<nb_output_files;i++) {
  883. dump_format(output_files[i], i, output_files[i]->filename, 1);
  884. }
  885. /* dump the stream mapping */
  886. fprintf(stderr, "Stream mapping:\n");
  887. for(i=0;i<nb_ostreams;i++) {
  888. ost = ost_table[i];
  889. fprintf(stderr, " Stream #%d.%d -> #%d.%d\n",
  890. ist_table[ost->source_index]->file_index,
  891. ist_table[ost->source_index]->index,
  892. ost->file_index,
  893. ost->index);
  894. }
  895. /* open each encoder */
  896. for(i=0;i<nb_ostreams;i++) {
  897. ost = ost_table[i];
  898. if (ost->encoding_needed) {
  899. AVCodec *codec;
  900. codec = avcodec_find_encoder(ost->st->codec.codec_id);
  901. if (!codec) {
  902. fprintf(stderr, "Unsupported codec for output stream #%d.%d\n",
  903. ost->file_index, ost->index);
  904. exit(1);
  905. }
  906. if (avcodec_open(&ost->st->codec, codec) < 0) {
  907. fprintf(stderr, "Error while opening codec for stream #%d.%d - maybe incorrect parameters such as bit_rate, rate, width or height\n",
  908. ost->file_index, ost->index);
  909. exit(1);
  910. }
  911. }
  912. }
  913. /* open each decoder */
  914. for(i=0;i<nb_istreams;i++) {
  915. ist = ist_table[i];
  916. if (ist->decoding_needed) {
  917. AVCodec *codec;
  918. codec = avcodec_find_decoder(ist->st->codec.codec_id);
  919. if (!codec) {
  920. fprintf(stderr, "Unsupported codec for input stream #%d.%d\n",
  921. ist->file_index, ist->index);
  922. exit(1);
  923. }
  924. if (avcodec_open(&ist->st->codec, codec) < 0) {
  925. fprintf(stderr, "Error while opening codec for input stream #%d.%d\n",
  926. ist->file_index, ist->index);
  927. exit(1);
  928. }
  929. //if (ist->st->codec.codec_type == CODEC_TYPE_VIDEO)
  930. // ist->st->codec.flags |= CODEC_FLAG_REPEAT_FIELD;
  931. ist->frame_decoded = 1;
  932. }
  933. }
  934. /* init pts */
  935. for(i=0;i<nb_istreams;i++) {
  936. ist = ist_table[i];
  937. }
  938. /* compute buffer size max (should use a complete heuristic) */
  939. for(i=0;i<nb_input_files;i++) {
  940. file_table[i].buffer_size_max = 2048;
  941. }
  942. /* open files and write file headers */
  943. for(i=0;i<nb_output_files;i++) {
  944. os = output_files[i];
  945. if (av_write_header(os) < 0) {
  946. fprintf(stderr, "Could not write header for output file #%d (incorrect codec paramters ?)\n", i);
  947. ret = -EINVAL;
  948. goto fail;
  949. }
  950. }
  951. #ifndef CONFIG_WIN32
  952. if (!do_play) {
  953. fprintf(stderr, "Press [q] to stop encoding\n");
  954. } else {
  955. fprintf(stderr, "Press [q] to stop playing\n");
  956. }
  957. #endif
  958. term_init();
  959. stream_no_data = 0;
  960. key = -1;
  961. for(;;) {
  962. int file_index, ist_index;
  963. AVPacket pkt;
  964. UINT8 *ptr;
  965. int len;
  966. UINT8 *data_buf;
  967. int data_size, got_picture;
  968. AVPicture picture;
  969. short samples[AVCODEC_MAX_AUDIO_FRAME_SIZE / 2];
  970. double pts_min;
  971. redo:
  972. /* if 'q' pressed, exits */
  973. if (key) {
  974. /* read_key() returns 0 on EOF */
  975. key = read_key();
  976. if (key == 'q')
  977. break;
  978. }
  979. /* select the stream that we must read now by looking at the
  980. smallest output pts */
  981. file_index = -1;
  982. pts_min = 1e10;
  983. for(i=0;i<nb_ostreams;i++) {
  984. double pts;
  985. ost = ost_table[i];
  986. os = output_files[ost->file_index];
  987. ist = ist_table[ost->source_index];
  988. pts = (double)ost->st->pts.val * os->pts_num / os->pts_den;
  989. if (!file_table[ist->file_index].eof_reached &&
  990. pts < pts_min) {
  991. pts_min = pts;
  992. file_index = ist->file_index;
  993. }
  994. }
  995. /* if none, if is finished */
  996. if (file_index < 0) {
  997. break;
  998. }
  999. /* finish if recording time exhausted */
  1000. if (recording_time > 0 && pts_min >= (recording_time / 1000000.0))
  1001. break;
  1002. /* read a packet from it and output it in the fifo */
  1003. is = input_files[file_index];
  1004. if (av_read_packet(is, &pkt) < 0) {
  1005. file_table[file_index].eof_reached = 1;
  1006. continue;
  1007. }
  1008. if (!pkt.size) {
  1009. stream_no_data = is;
  1010. } else {
  1011. stream_no_data = 0;
  1012. }
  1013. /* the following test is needed in case new streams appear
  1014. dynamically in stream : we ignore them */
  1015. if (pkt.stream_index >= file_table[file_index].nb_streams)
  1016. goto discard_packet;
  1017. ist_index = file_table[file_index].ist_index + pkt.stream_index;
  1018. ist = ist_table[ist_index];
  1019. if (ist->discard)
  1020. goto discard_packet;
  1021. if (do_hex_dump) {
  1022. printf("stream #%d, size=%d:\n", pkt.stream_index, pkt.size);
  1023. av_hex_dump(pkt.data, pkt.size);
  1024. }
  1025. // printf("read #%d.%d size=%d\n", ist->file_index, ist->index, pkt.size);
  1026. len = pkt.size;
  1027. ptr = pkt.data;
  1028. pts_set = 0;
  1029. while (len > 0) {
  1030. INT64 ipts;
  1031. ipts = AV_NOPTS_VALUE;
  1032. /* decode the packet if needed */
  1033. data_buf = NULL; /* fail safe */
  1034. data_size = 0;
  1035. if (ist->decoding_needed) {
  1036. /* NOTE1: we only take into account the PTS if a new
  1037. frame has begun (MPEG semantics) */
  1038. /* NOTE2: even if the fraction is not initialized,
  1039. av_frac_set can be used to set the integer part */
  1040. if (ist->frame_decoded &&
  1041. pkt.pts != AV_NOPTS_VALUE &&
  1042. !pts_set) {
  1043. ipts = pkt.pts;
  1044. ist->frame_decoded = 0;
  1045. pts_set = 1;
  1046. }
  1047. switch(ist->st->codec.codec_type) {
  1048. case CODEC_TYPE_AUDIO:
  1049. /* XXX: could avoid copy if PCM 16 bits with same
  1050. endianness as CPU */
  1051. ret = avcodec_decode_audio(&ist->st->codec, samples, &data_size,
  1052. ptr, len);
  1053. if (ret < 0)
  1054. goto fail_decode;
  1055. /* Some bug in mpeg audio decoder gives */
  1056. /* data_size < 0, it seems they are overflows */
  1057. if (data_size <= 0) {
  1058. /* no audio frame */
  1059. ptr += ret;
  1060. len -= ret;
  1061. continue;
  1062. }
  1063. data_buf = (UINT8 *)samples;
  1064. break;
  1065. case CODEC_TYPE_VIDEO:
  1066. if (ist->st->codec.codec_id == CODEC_ID_RAWVIDEO) {
  1067. int size;
  1068. size = (ist->st->codec.width * ist->st->codec.height);
  1069. avpicture_fill(&picture, ptr,
  1070. ist->st->codec.pix_fmt,
  1071. ist->st->codec.width,
  1072. ist->st->codec.height);
  1073. ret = len;
  1074. } else {
  1075. data_size = (ist->st->codec.width * ist->st->codec.height * 3) / 2;
  1076. ret = avcodec_decode_video(&ist->st->codec,
  1077. &picture, &got_picture, ptr, len);
  1078. if (ret < 0) {
  1079. fail_decode:
  1080. fprintf(stderr, "Error while decoding stream #%d.%d\n",
  1081. ist->file_index, ist->index);
  1082. av_free_packet(&pkt);
  1083. goto redo;
  1084. }
  1085. if (!got_picture) {
  1086. /* no picture yet */
  1087. ptr += ret;
  1088. len -= ret;
  1089. continue;
  1090. }
  1091. }
  1092. break;
  1093. default:
  1094. goto fail_decode;
  1095. }
  1096. } else {
  1097. data_buf = ptr;
  1098. data_size = len;
  1099. ret = len;
  1100. }
  1101. ptr += ret;
  1102. len -= ret;
  1103. ist->frame_decoded = 1;
  1104. #if 0
  1105. /* mpeg PTS deordering : if it is a P or I frame, the PTS
  1106. is the one of the next displayed one */
  1107. /* XXX: add mpeg4 too ? */
  1108. if (ist->st->codec.codec_id == CODEC_ID_MPEG1VIDEO) {
  1109. if (ist->st->codec.pict_type != B_TYPE) {
  1110. INT64 tmp;
  1111. tmp = ist->last_ip_pts;
  1112. ist->last_ip_pts = ist->frac_pts.val;
  1113. ist->frac_pts.val = tmp;
  1114. }
  1115. }
  1116. #endif
  1117. /* transcode raw format, encode packets and output them */
  1118. for(i=0;i<nb_ostreams;i++) {
  1119. int frame_size;
  1120. ost = ost_table[i];
  1121. if (ost->source_index == ist_index) {
  1122. os = output_files[ost->file_index];
  1123. if (ipts != AV_NOPTS_VALUE) {
  1124. #if 0
  1125. printf("%d: got pts=%f %f\n",
  1126. i, pkt.pts / 90000.0,
  1127. (ipts - ost->st->pts.val) / 90000.0);
  1128. #endif
  1129. /* set the input output pts pairs */
  1130. ost->sync_ipts = (double)ipts * is->pts_num /
  1131. is->pts_den;
  1132. /* XXX: take into account the various fifos,
  1133. in particular for audio */
  1134. ost->sync_opts = ost->st->pts.val;
  1135. }
  1136. if (ost->encoding_needed) {
  1137. switch(ost->st->codec.codec_type) {
  1138. case CODEC_TYPE_AUDIO:
  1139. do_audio_out(os, ost, ist, data_buf, data_size);
  1140. break;
  1141. case CODEC_TYPE_VIDEO:
  1142. /* find an audio stream for synchro */
  1143. {
  1144. int i;
  1145. AVOutputStream *audio_sync, *ost1;
  1146. audio_sync = NULL;
  1147. for(i=0;i<nb_ostreams;i++) {
  1148. ost1 = ost_table[i];
  1149. if (ost1->file_index == ost->file_index &&
  1150. ost1->st->codec.codec_type == CODEC_TYPE_AUDIO) {
  1151. audio_sync = ost1;
  1152. break;
  1153. }
  1154. }
  1155. do_video_out(os, ost, ist, &picture, &frame_size, audio_sync);
  1156. if (do_vstats)
  1157. do_video_stats(os, ost, frame_size);
  1158. }
  1159. break;
  1160. default:
  1161. av_abort();
  1162. }
  1163. } else {
  1164. /* no reencoding needed : output the packet directly */
  1165. /* force the input stream PTS */
  1166. av_write_frame(os, ost->index, data_buf, data_size);
  1167. ost->st->codec.frame_number++;
  1168. }
  1169. }
  1170. }
  1171. ipts = AV_NOPTS_VALUE;
  1172. }
  1173. discard_packet:
  1174. av_free_packet(&pkt);
  1175. /* dump report by using the output first video and audio streams */
  1176. print_report(output_files, ost_table, nb_ostreams, 0);
  1177. }
  1178. term_exit();
  1179. /* dump report by using the first video and audio streams */
  1180. print_report(output_files, ost_table, nb_ostreams, 1);
  1181. /* close each encoder */
  1182. for(i=0;i<nb_ostreams;i++) {
  1183. ost = ost_table[i];
  1184. if (ost->encoding_needed) {
  1185. av_freep(&ost->st->codec.stats_in);
  1186. avcodec_close(&ost->st->codec);
  1187. }
  1188. }
  1189. /* close each decoder */
  1190. for(i=0;i<nb_istreams;i++) {
  1191. ist = ist_table[i];
  1192. if (ist->decoding_needed) {
  1193. avcodec_close(&ist->st->codec);
  1194. }
  1195. }
  1196. /* write the trailer if needed and close file */
  1197. for(i=0;i<nb_output_files;i++) {
  1198. os = output_files[i];
  1199. av_write_trailer(os);
  1200. }
  1201. /* finished ! */
  1202. ret = 0;
  1203. fail1:
  1204. av_free(file_table);
  1205. if (ist_table) {
  1206. for(i=0;i<nb_istreams;i++) {
  1207. ist = ist_table[i];
  1208. av_free(ist);
  1209. }
  1210. av_free(ist_table);
  1211. }
  1212. if (ost_table) {
  1213. for(i=0;i<nb_ostreams;i++) {
  1214. ost = ost_table[i];
  1215. if (ost) {
  1216. if (ost->logfile) {
  1217. fclose(ost->logfile);
  1218. ost->logfile = NULL;
  1219. }
  1220. fifo_free(&ost->fifo); /* works even if fifo is not
  1221. initialized but set to zero */
  1222. av_free(ost->pict_tmp.data[0]);
  1223. if (ost->video_resample)
  1224. img_resample_close(ost->img_resample_ctx);
  1225. if (ost->audio_resample)
  1226. audio_resample_close(ost->resample);
  1227. av_free(ost);
  1228. }
  1229. }
  1230. av_free(ost_table);
  1231. }
  1232. return ret;
  1233. fail:
  1234. ret = -ENOMEM;
  1235. goto fail1;
  1236. }
  1237. #if 0
  1238. int file_read(const char *filename)
  1239. {
  1240. URLContext *h;
  1241. unsigned char buffer[1024];
  1242. int len, i;
  1243. if (url_open(&h, filename, O_RDONLY) < 0) {
  1244. printf("could not open '%s'\n", filename);
  1245. return -1;
  1246. }
  1247. for(;;) {
  1248. len = url_read(h, buffer, sizeof(buffer));
  1249. if (len <= 0)
  1250. break;
  1251. for(i=0;i<len;i++) putchar(buffer[i]);
  1252. }
  1253. url_close(h);
  1254. return 0;
  1255. }
  1256. #endif
  1257. void show_licence(void)
  1258. {
  1259. printf(
  1260. "ffmpeg version " FFMPEG_VERSION "\n"
  1261. "Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n"
  1262. "This library is free software; you can redistribute it and/or\n"
  1263. "modify it under the terms of the GNU Lesser General Public\n"
  1264. "License as published by the Free Software Foundation; either\n"
  1265. "version 2 of the License, or (at your option) any later version.\n"
  1266. "\n"
  1267. "This library is distributed in the hope that it will be useful,\n"
  1268. "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
  1269. "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"
  1270. "Lesser General Public License for more details.\n"
  1271. "\n"
  1272. "You should have received a copy of the GNU Lesser General Public\n"
  1273. "License along with this library; if not, write to the Free Software\n"
  1274. "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n"
  1275. );
  1276. exit(1);
  1277. }
  1278. void opt_format(const char *arg)
  1279. {
  1280. file_iformat = av_find_input_format(arg);
  1281. file_oformat = guess_format(arg, NULL, NULL);
  1282. if (!file_iformat && !file_oformat) {
  1283. fprintf(stderr, "Unknown input or output format: %s\n", arg);
  1284. exit(1);
  1285. }
  1286. }
  1287. void opt_video_bitrate(const char *arg)
  1288. {
  1289. video_bit_rate = atoi(arg) * 1000;
  1290. }
  1291. void opt_video_bitrate_tolerance(const char *arg)
  1292. {
  1293. video_bit_rate_tolerance = atoi(arg) * 1000;
  1294. }
  1295. void opt_video_bitrate_max(const char *arg)
  1296. {
  1297. video_rc_max_rate = atoi(arg) * 1000;
  1298. }
  1299. void opt_video_bitrate_min(const char *arg)
  1300. {
  1301. video_rc_min_rate = atoi(arg) * 1000;
  1302. }
  1303. void opt_video_buffer_size(const char *arg)
  1304. {
  1305. video_rc_buffer_size = atoi(arg) * 1000;
  1306. }
  1307. void opt_video_rc_eq(char *arg)
  1308. {
  1309. video_rc_eq = arg;
  1310. }
  1311. void opt_video_rc_override_string(char *arg)
  1312. {
  1313. video_rc_override_string = arg;
  1314. }
  1315. void opt_workaround_bugs(const char *arg)
  1316. {
  1317. workaround_bugs = atoi(arg);
  1318. }
  1319. void opt_dct_algo(const char *arg)
  1320. {
  1321. dct_algo = atoi(arg);
  1322. }
  1323. void opt_idct_algo(const char *arg)
  1324. {
  1325. idct_algo = atoi(arg);
  1326. }
  1327. void opt_error_resilience(const char *arg)
  1328. {
  1329. error_resilience = atoi(arg);
  1330. }
  1331. void opt_error_concealment(const char *arg)
  1332. {
  1333. error_concealment = atoi(arg);
  1334. }
  1335. void opt_frame_rate(const char *arg)
  1336. {
  1337. frame_rate = (int)(strtod(arg, 0) * FRAME_RATE_BASE);
  1338. }
  1339. void opt_frame_crop_top(const char *arg)
  1340. {
  1341. frame_topBand = atoi(arg);
  1342. if (frame_topBand < 0) {
  1343. fprintf(stderr, "Incorrect top crop size\n");
  1344. exit(1);
  1345. }
  1346. if ((frame_topBand % 2) != 0) {
  1347. fprintf(stderr, "Top crop size must be a multiple of 2\n");
  1348. exit(1);
  1349. }
  1350. if ((frame_topBand) >= frame_height){
  1351. fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1352. exit(1);
  1353. }
  1354. frame_height -= frame_topBand;
  1355. }
  1356. void opt_frame_crop_bottom(const char *arg)
  1357. {
  1358. frame_bottomBand = atoi(arg);
  1359. if (frame_bottomBand < 0) {
  1360. fprintf(stderr, "Incorrect bottom crop size\n");
  1361. exit(1);
  1362. }
  1363. if ((frame_bottomBand % 2) != 0) {
  1364. fprintf(stderr, "Bottom crop size must be a multiple of 2\n");
  1365. exit(1);
  1366. }
  1367. if ((frame_bottomBand) >= frame_height){
  1368. fprintf(stderr, "Vertical crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1369. exit(1);
  1370. }
  1371. frame_height -= frame_bottomBand;
  1372. }
  1373. void opt_frame_crop_left(const char *arg)
  1374. {
  1375. frame_leftBand = atoi(arg);
  1376. if (frame_leftBand < 0) {
  1377. fprintf(stderr, "Incorrect left crop size\n");
  1378. exit(1);
  1379. }
  1380. if ((frame_leftBand % 2) != 0) {
  1381. fprintf(stderr, "Left crop size must be a multiple of 2\n");
  1382. exit(1);
  1383. }
  1384. if ((frame_leftBand) >= frame_width){
  1385. fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1386. exit(1);
  1387. }
  1388. frame_width -= frame_leftBand;
  1389. }
  1390. void opt_frame_crop_right(const char *arg)
  1391. {
  1392. frame_rightBand = atoi(arg);
  1393. if (frame_rightBand < 0) {
  1394. fprintf(stderr, "Incorrect right crop size\n");
  1395. exit(1);
  1396. }
  1397. if ((frame_rightBand % 2) != 0) {
  1398. fprintf(stderr, "Right crop size must be a multiple of 2\n");
  1399. exit(1);
  1400. }
  1401. if ((frame_rightBand) >= frame_width){
  1402. fprintf(stderr, "Horizontal crop dimensions are outside the range of the original image.\nRemember to crop first and scale second.\n");
  1403. exit(1);
  1404. }
  1405. frame_width -= frame_rightBand;
  1406. }
  1407. void opt_frame_size(const char *arg)
  1408. {
  1409. parse_image_size(&frame_width, &frame_height, arg);
  1410. if (frame_width <= 0 || frame_height <= 0) {
  1411. fprintf(stderr, "Incorrect frame size\n");
  1412. exit(1);
  1413. }
  1414. if ((frame_width % 2) != 0 || (frame_height % 2) != 0) {
  1415. fprintf(stderr, "Frame size must be a multiple of 2\n");
  1416. exit(1);
  1417. }
  1418. }
  1419. void opt_gop_size(const char *arg)
  1420. {
  1421. gop_size = atoi(arg);
  1422. }
  1423. void opt_b_frames(const char *arg)
  1424. {
  1425. b_frames = atoi(arg);
  1426. if (b_frames > FF_MAX_B_FRAMES) {
  1427. fprintf(stderr, "\nCannot have more than %d B frames, increase FF_MAX_B_FRAMES.\n", FF_MAX_B_FRAMES);
  1428. exit(1);
  1429. } else if (b_frames < 1) {
  1430. fprintf(stderr, "\nNumber of B frames must be higher than 0\n");
  1431. exit(1);
  1432. }
  1433. }
  1434. void opt_qscale(const char *arg)
  1435. {
  1436. video_qscale = atoi(arg);
  1437. if (video_qscale < 0 ||
  1438. video_qscale > 31) {
  1439. fprintf(stderr, "qscale must be >= 1 and <= 31\n");
  1440. exit(1);
  1441. }
  1442. }
  1443. void opt_qmin(const char *arg)
  1444. {
  1445. video_qmin = atoi(arg);
  1446. if (video_qmin < 0 ||
  1447. video_qmin > 31) {
  1448. fprintf(stderr, "qmin must be >= 1 and <= 31\n");
  1449. exit(1);
  1450. }
  1451. }
  1452. void opt_qmax(const char *arg)
  1453. {
  1454. video_qmax = atoi(arg);
  1455. if (video_qmax < 0 ||
  1456. video_qmax > 31) {
  1457. fprintf(stderr, "qmax must be >= 1 and <= 31\n");
  1458. exit(1);
  1459. }
  1460. }
  1461. void opt_qdiff(const char *arg)
  1462. {
  1463. video_qdiff = atoi(arg);
  1464. if (video_qdiff < 0 ||
  1465. video_qdiff > 31) {
  1466. fprintf(stderr, "qdiff must be >= 1 and <= 31\n");
  1467. exit(1);
  1468. }
  1469. }
  1470. void opt_qblur(const char *arg)
  1471. {
  1472. video_qblur = atof(arg);
  1473. }
  1474. void opt_qcomp(const char *arg)
  1475. {
  1476. video_qcomp = atof(arg);
  1477. }
  1478. void opt_rc_initial_cplx(const char *arg)
  1479. {
  1480. video_rc_initial_cplx = atof(arg);
  1481. }
  1482. void opt_b_qfactor(const char *arg)
  1483. {
  1484. video_b_qfactor = atof(arg);
  1485. }
  1486. void opt_i_qfactor(const char *arg)
  1487. {
  1488. video_i_qfactor = atof(arg);
  1489. }
  1490. void opt_b_qoffset(const char *arg)
  1491. {
  1492. video_b_qoffset = atof(arg);
  1493. }
  1494. void opt_i_qoffset(const char *arg)
  1495. {
  1496. video_i_qoffset = atof(arg);
  1497. }
  1498. void opt_packet_size(const char *arg)
  1499. {
  1500. packet_size= atoi(arg);
  1501. }
  1502. void opt_audio_bitrate(const char *arg)
  1503. {
  1504. audio_bit_rate = atoi(arg) * 1000;
  1505. }
  1506. void opt_audio_rate(const char *arg)
  1507. {
  1508. audio_sample_rate = atoi(arg);
  1509. }
  1510. void opt_audio_channels(const char *arg)
  1511. {
  1512. audio_channels = atoi(arg);
  1513. }
  1514. void opt_video_device(const char *arg)
  1515. {
  1516. v4l_device = strdup(arg);
  1517. }
  1518. void opt_audio_device(const char *arg)
  1519. {
  1520. audio_device = strdup(arg);
  1521. }
  1522. void opt_audio_codec(const char *arg)
  1523. {
  1524. AVCodec *p;
  1525. if (!strcmp(arg, "copy")) {
  1526. audio_stream_copy = 1;
  1527. } else {
  1528. p = first_avcodec;
  1529. while (p) {
  1530. if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO)
  1531. break;
  1532. p = p->next;
  1533. }
  1534. if (p == NULL) {
  1535. fprintf(stderr, "Unknown audio codec '%s'\n", arg);
  1536. exit(1);
  1537. } else {
  1538. audio_codec_id = p->id;
  1539. }
  1540. }
  1541. }
  1542. const char *motion_str[] = {
  1543. "zero",
  1544. "full",
  1545. "log",
  1546. "phods",
  1547. "epzs",
  1548. "x1",
  1549. NULL,
  1550. };
  1551. void opt_motion_estimation(const char *arg)
  1552. {
  1553. const char **p;
  1554. p = motion_str;
  1555. for(;;) {
  1556. if (!*p) {
  1557. fprintf(stderr, "Unknown motion estimation method '%s'\n", arg);
  1558. exit(1);
  1559. }
  1560. if (!strcmp(*p, arg))
  1561. break;
  1562. p++;
  1563. }
  1564. me_method = (p - motion_str) + 1;
  1565. }
  1566. void opt_video_codec(const char *arg)
  1567. {
  1568. AVCodec *p;
  1569. if (!strcmp(arg, "copy")) {
  1570. video_stream_copy = 1;
  1571. } else {
  1572. p = first_avcodec;
  1573. while (p) {
  1574. if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO)
  1575. break;
  1576. p = p->next;
  1577. }
  1578. if (p == NULL) {
  1579. fprintf(stderr, "Unknown video codec '%s'\n", arg);
  1580. exit(1);
  1581. } else {
  1582. video_codec_id = p->id;
  1583. }
  1584. }
  1585. }
  1586. void opt_map(const char *arg)
  1587. {
  1588. AVStreamMap *m;
  1589. const char *p;
  1590. p = arg;
  1591. m = &stream_maps[nb_stream_maps++];
  1592. m->file_index = strtol(arg, (char **)&p, 0);
  1593. if (*p)
  1594. p++;
  1595. m->stream_index = strtol(p, (char **)&p, 0);
  1596. }
  1597. void opt_recording_time(const char *arg)
  1598. {
  1599. recording_time = parse_date(arg, 1);
  1600. }
  1601. void print_error(const char *filename, int err)
  1602. {
  1603. switch(err) {
  1604. case AVERROR_NUMEXPECTED:
  1605. fprintf(stderr, "%s: Incorrect image filename syntax.\n"
  1606. "Use '%%d' to specify the image number:\n"
  1607. " for img1.jpg, img2.jpg, ..., use 'img%%d.jpg';\n"
  1608. " for img001.jpg, img002.jpg, ..., use 'img%%03d.jpg'.\n",
  1609. filename);
  1610. break;
  1611. case AVERROR_INVALIDDATA:
  1612. fprintf(stderr, "%s: Error while parsing header\n", filename);
  1613. break;
  1614. case AVERROR_NOFMT:
  1615. fprintf(stderr, "%s: Unknown format\n", filename);
  1616. break;
  1617. default:
  1618. fprintf(stderr, "%s: Error while opening file\n", filename);
  1619. break;
  1620. }
  1621. }
  1622. void opt_input_file(const char *filename)
  1623. {
  1624. AVFormatContext *ic;
  1625. AVFormatParameters params, *ap = &params;
  1626. int err, i, ret, rfps;
  1627. /* get default parameters from command line */
  1628. memset(ap, 0, sizeof(*ap));
  1629. ap->sample_rate = audio_sample_rate;
  1630. ap->channels = audio_channels;
  1631. ap->frame_rate = frame_rate;
  1632. ap->width = frame_width;
  1633. ap->height = frame_height;
  1634. /* open the input file with generic libav function */
  1635. err = av_open_input_file(&ic, filename, file_iformat, 0, ap);
  1636. if (err < 0) {
  1637. print_error(filename, err);
  1638. exit(1);
  1639. }
  1640. /* If not enough info to get the stream parameters, we decode the
  1641. first frames to get it. (used in mpeg case for example) */
  1642. ret = av_find_stream_info(ic);
  1643. if (ret < 0) {
  1644. fprintf(stderr, "%s: could not find codec parameters\n", filename);
  1645. exit(1);
  1646. }
  1647. /* update the current parameters so that they match the one of the input stream */
  1648. for(i=0;i<ic->nb_streams;i++) {
  1649. AVCodecContext *enc = &ic->streams[i]->codec;
  1650. switch(enc->codec_type) {
  1651. case CODEC_TYPE_AUDIO:
  1652. //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);
  1653. audio_channels = enc->channels;
  1654. audio_sample_rate = enc->sample_rate;
  1655. break;
  1656. case CODEC_TYPE_VIDEO:
  1657. frame_height = enc->height;
  1658. frame_width = enc->width;
  1659. rfps = ic->streams[i]->r_frame_rate;
  1660. enc->workaround_bugs = workaround_bugs;
  1661. enc->error_resilience = error_resilience;
  1662. enc->error_concealment = error_concealment;
  1663. enc->idct_algo= idct_algo;
  1664. if (enc->frame_rate != rfps) {
  1665. fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",
  1666. i, (float)enc->frame_rate / FRAME_RATE_BASE,
  1667. (float)rfps / FRAME_RATE_BASE);
  1668. }
  1669. /* update the current frame rate to match the stream frame rate */
  1670. frame_rate = rfps;
  1671. break;
  1672. default:
  1673. av_abort();
  1674. }
  1675. }
  1676. input_files[nb_input_files] = ic;
  1677. /* dump the file content */
  1678. dump_format(ic, nb_input_files, filename, 0);
  1679. nb_input_files++;
  1680. file_iformat = NULL;
  1681. file_oformat = NULL;
  1682. }
  1683. void check_audio_video_inputs(int *has_video_ptr, int *has_audio_ptr)
  1684. {
  1685. int has_video, has_audio, i, j;
  1686. AVFormatContext *ic;
  1687. has_video = 0;
  1688. has_audio = 0;
  1689. for(j=0;j<nb_input_files;j++) {
  1690. ic = input_files[j];
  1691. for(i=0;i<ic->nb_streams;i++) {
  1692. AVCodecContext *enc = &ic->streams[i]->codec;
  1693. switch(enc->codec_type) {
  1694. case CODEC_TYPE_AUDIO:
  1695. has_audio = 1;
  1696. break;
  1697. case CODEC_TYPE_VIDEO:
  1698. has_video = 1;
  1699. break;
  1700. default:
  1701. av_abort();
  1702. }
  1703. }
  1704. }
  1705. *has_video_ptr = has_video;
  1706. *has_audio_ptr = has_audio;
  1707. }
  1708. void opt_output_file(const char *filename)
  1709. {
  1710. AVStream *st;
  1711. AVFormatContext *oc;
  1712. int use_video, use_audio, nb_streams, input_has_video, input_has_audio;
  1713. int codec_id;
  1714. if (!strcmp(filename, "-"))
  1715. filename = "pipe:";
  1716. oc = av_mallocz(sizeof(AVFormatContext));
  1717. if (!file_oformat) {
  1718. file_oformat = guess_format(NULL, filename, NULL);
  1719. if (!file_oformat) {
  1720. fprintf(stderr, "Unable for find a suitable output format for '%s'\n",
  1721. filename);
  1722. exit(1);
  1723. }
  1724. }
  1725. oc->oformat = file_oformat;
  1726. if (!strcmp(file_oformat->name, "ffm") &&
  1727. strstart(filename, "http:", NULL)) {
  1728. /* special case for files sent to ffserver: we get the stream
  1729. parameters from ffserver */
  1730. if (read_ffserver_streams(oc, filename) < 0) {
  1731. fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);
  1732. exit(1);
  1733. }
  1734. } else {
  1735. use_video = file_oformat->video_codec != CODEC_ID_NONE;
  1736. use_audio = file_oformat->audio_codec != CODEC_ID_NONE;
  1737. /* disable if no corresponding type found and at least one
  1738. input file */
  1739. if (nb_input_files > 0) {
  1740. check_audio_video_inputs(&input_has_video, &input_has_audio);
  1741. if (!input_has_video)
  1742. use_video = 0;
  1743. if (!input_has_audio)
  1744. use_audio = 0;
  1745. }
  1746. /* manual disable */
  1747. if (audio_disable) {
  1748. use_audio = 0;
  1749. }
  1750. if (video_disable) {
  1751. use_video = 0;
  1752. }
  1753. nb_streams = 0;
  1754. if (use_video) {
  1755. AVCodecContext *video_enc;
  1756. st = av_mallocz(sizeof(AVStream));
  1757. if (!st) {
  1758. fprintf(stderr, "Could not alloc stream\n");
  1759. exit(1);
  1760. }
  1761. video_enc = &st->codec;
  1762. if (video_stream_copy) {
  1763. st->stream_copy = 1;
  1764. video_enc->codec_type = CODEC_TYPE_VIDEO;
  1765. } else {
  1766. char *p;
  1767. int i;
  1768. codec_id = file_oformat->video_codec;
  1769. if (video_codec_id != CODEC_ID_NONE)
  1770. codec_id = video_codec_id;
  1771. video_enc->codec_id = codec_id;
  1772. video_enc->bit_rate = video_bit_rate;
  1773. video_enc->bit_rate_tolerance = video_bit_rate_tolerance;
  1774. video_enc->frame_rate = frame_rate;
  1775. video_enc->width = frame_width;
  1776. video_enc->height = frame_height;
  1777. if (!intra_only)
  1778. video_enc->gop_size = gop_size;
  1779. else
  1780. video_enc->gop_size = 0;
  1781. if (video_qscale || same_quality) {
  1782. video_enc->flags |= CODEC_FLAG_QSCALE;
  1783. video_enc->quality = video_qscale;
  1784. }
  1785. if (use_hq) {
  1786. video_enc->flags |= CODEC_FLAG_HQ;
  1787. }
  1788. if (use_4mv) {
  1789. video_enc->flags |= CODEC_FLAG_HQ;
  1790. video_enc->flags |= CODEC_FLAG_4MV;
  1791. }
  1792. if(use_part)
  1793. video_enc->flags |= CODEC_FLAG_PART;
  1794. if (b_frames) {
  1795. if (codec_id != CODEC_ID_MPEG4) {
  1796. fprintf(stderr, "\nB frames encoding only supported by MPEG-4.\n");
  1797. exit(1);
  1798. }
  1799. video_enc->max_b_frames = b_frames;
  1800. video_enc->b_frame_strategy = 0;
  1801. video_enc->b_quant_factor = 2.0;
  1802. }
  1803. video_enc->qmin = video_qmin;
  1804. video_enc->qmax = video_qmax;
  1805. video_enc->max_qdiff = video_qdiff;
  1806. video_enc->qblur = video_qblur;
  1807. video_enc->qcompress = video_qcomp;
  1808. video_enc->rc_eq = video_rc_eq;
  1809. p= video_rc_override_string;
  1810. for(i=0; p; i++){
  1811. int start, end, q;
  1812. int e=sscanf(p, "%d,%d,%d", &start, &end, &q);
  1813. if(e!=3){
  1814. fprintf(stderr, "error parsing rc_override\n");
  1815. exit(1);
  1816. }
  1817. video_enc->rc_override=
  1818. realloc(video_enc->rc_override, sizeof(RcOverride)*(i+1));
  1819. video_enc->rc_override[i].start_frame= start;
  1820. video_enc->rc_override[i].end_frame = end;
  1821. if(q>0){
  1822. video_enc->rc_override[i].qscale= q;
  1823. video_enc->rc_override[i].quality_factor= 1.0;
  1824. }
  1825. else{
  1826. video_enc->rc_override[i].qscale= 0;
  1827. video_enc->rc_override[i].quality_factor= -q/100.0;
  1828. }
  1829. p= strchr(p, '/');
  1830. if(p) p++;
  1831. }
  1832. video_enc->rc_override_count=i;
  1833. video_enc->rc_max_rate = video_rc_max_rate;
  1834. video_enc->rc_min_rate = video_rc_min_rate;
  1835. video_enc->rc_buffer_size = video_rc_buffer_size;
  1836. video_enc->rc_buffer_aggressivity= video_rc_buffer_aggressivity;
  1837. video_enc->rc_initial_cplx= video_rc_initial_cplx;
  1838. video_enc->i_quant_factor = video_i_qfactor;
  1839. video_enc->b_quant_factor = video_b_qfactor;
  1840. video_enc->i_quant_offset = video_i_qoffset;
  1841. video_enc->b_quant_offset = video_b_qoffset;
  1842. video_enc->dct_algo = dct_algo;
  1843. video_enc->idct_algo = idct_algo;
  1844. if(packet_size){
  1845. video_enc->rtp_mode= 1;
  1846. video_enc->rtp_payload_size= packet_size;
  1847. }
  1848. if (do_psnr)
  1849. video_enc->get_psnr = 1;
  1850. else
  1851. video_enc->get_psnr = 0;
  1852. video_enc->me_method = me_method;
  1853. /* two pass mode */
  1854. if (do_pass) {
  1855. if (do_pass == 1) {
  1856. video_enc->flags |= CODEC_FLAG_PASS1;
  1857. } else {
  1858. video_enc->flags |= CODEC_FLAG_PASS2;
  1859. }
  1860. }
  1861. /* XXX: need to find a way to set codec parameters */
  1862. if (oc->oformat->flags & AVFMT_RGB24) {
  1863. video_enc->pix_fmt = PIX_FMT_RGB24;
  1864. }
  1865. }
  1866. oc->streams[nb_streams] = st;
  1867. nb_streams++;
  1868. }
  1869. if (use_audio) {
  1870. AVCodecContext *audio_enc;
  1871. st = av_mallocz(sizeof(AVStream));
  1872. if (!st) {
  1873. fprintf(stderr, "Could not alloc stream\n");
  1874. exit(1);
  1875. }
  1876. audio_enc = &st->codec;
  1877. audio_enc->codec_type = CODEC_TYPE_AUDIO;
  1878. if (audio_stream_copy) {
  1879. st->stream_copy = 1;
  1880. } else {
  1881. codec_id = file_oformat->audio_codec;
  1882. if (audio_codec_id != CODEC_ID_NONE)
  1883. codec_id = audio_codec_id;
  1884. audio_enc->codec_id = codec_id;
  1885. audio_enc->bit_rate = audio_bit_rate;
  1886. audio_enc->sample_rate = audio_sample_rate;
  1887. /* For audio codecs other than AC3 we limit */
  1888. /* the number of coded channels to stereo */
  1889. if (audio_channels > 2 && codec_id != CODEC_ID_AC3) {
  1890. audio_enc->channels = 2;
  1891. } else
  1892. audio_enc->channels = audio_channels;
  1893. }
  1894. oc->streams[nb_streams] = st;
  1895. nb_streams++;
  1896. }
  1897. oc->nb_streams = nb_streams;
  1898. if (!nb_streams) {
  1899. fprintf(stderr, "No audio or video streams available\n");
  1900. exit(1);
  1901. }
  1902. if (str_title)
  1903. pstrcpy(oc->title, sizeof(oc->title), str_title);
  1904. if (str_author)
  1905. pstrcpy(oc->author, sizeof(oc->author), str_author);
  1906. if (str_copyright)
  1907. pstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);
  1908. if (str_comment)
  1909. pstrcpy(oc->comment, sizeof(oc->comment), str_comment);
  1910. }
  1911. output_files[nb_output_files++] = oc;
  1912. strcpy(oc->filename, filename);
  1913. /* check filename in case of an image number is expected */
  1914. if (oc->oformat->flags & AVFMT_NEEDNUMBER) {
  1915. if (filename_number_test(oc->filename) < 0) {
  1916. print_error(oc->filename, AVERROR_NUMEXPECTED);
  1917. exit(1);
  1918. }
  1919. }
  1920. if (!(oc->oformat->flags & AVFMT_NOFILE)) {
  1921. /* test if it already exists to avoid loosing precious files */
  1922. if (!file_overwrite &&
  1923. (strchr(filename, ':') == NULL ||
  1924. strstart(filename, "file:", NULL))) {
  1925. if (url_exist(filename)) {
  1926. int c;
  1927. printf("File '%s' already exists. Overwrite ? [y/N] ", filename);
  1928. fflush(stdout);
  1929. c = getchar();
  1930. if (toupper(c) != 'Y') {
  1931. fprintf(stderr, "Not overwriting - exiting\n");
  1932. exit(1);
  1933. }
  1934. }
  1935. }
  1936. /* open the file */
  1937. if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {
  1938. fprintf(stderr, "Could not open '%s'\n", filename);
  1939. exit(1);
  1940. }
  1941. }
  1942. /* reset some options */
  1943. file_oformat = NULL;
  1944. file_iformat = NULL;
  1945. audio_disable = 0;
  1946. video_disable = 0;
  1947. audio_codec_id = CODEC_ID_NONE;
  1948. video_codec_id = CODEC_ID_NONE;
  1949. audio_stream_copy = 0;
  1950. video_stream_copy = 0;
  1951. }
  1952. /* prepare dummy protocols for grab */
  1953. void prepare_grab(void)
  1954. {
  1955. int has_video, has_audio, i, j;
  1956. AVFormatContext *oc;
  1957. AVFormatContext *ic;
  1958. AVFormatParameters ap1, *ap = &ap1;
  1959. /* see if audio/video inputs are needed */
  1960. has_video = 0;
  1961. has_audio = 0;
  1962. memset(ap, 0, sizeof(*ap));
  1963. for(j=0;j<nb_output_files;j++) {
  1964. oc = output_files[j];
  1965. for(i=0;i<oc->nb_streams;i++) {
  1966. AVCodecContext *enc = &oc->streams[i]->codec;
  1967. switch(enc->codec_type) {
  1968. case CODEC_TYPE_AUDIO:
  1969. if (enc->sample_rate > ap->sample_rate)
  1970. ap->sample_rate = enc->sample_rate;
  1971. if (enc->channels > ap->channels)
  1972. ap->channels = enc->channels;
  1973. has_audio = 1;
  1974. break;
  1975. case CODEC_TYPE_VIDEO:
  1976. if (enc->width > ap->width)
  1977. ap->width = enc->width;
  1978. if (enc->height > ap->height)
  1979. ap->height = enc->height;
  1980. if (enc->frame_rate > ap->frame_rate)
  1981. ap->frame_rate = enc->frame_rate;
  1982. has_video = 1;
  1983. break;
  1984. default:
  1985. av_abort();
  1986. }
  1987. }
  1988. }
  1989. if (has_video == 0 && has_audio == 0) {
  1990. fprintf(stderr, "Output file must have at least one audio or video stream\n");
  1991. exit(1);
  1992. }
  1993. if (has_video) {
  1994. AVInputFormat *fmt1;
  1995. fmt1 = av_find_input_format("video_grab_device");
  1996. if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
  1997. fprintf(stderr, "Could not find video grab device\n");
  1998. exit(1);
  1999. }
  2000. /* by now video grab has one stream */
  2001. ic->streams[0]->r_frame_rate = ap->frame_rate;
  2002. input_files[nb_input_files] = ic;
  2003. dump_format(ic, nb_input_files, v4l_device, 0);
  2004. nb_input_files++;
  2005. }
  2006. if (has_audio) {
  2007. AVInputFormat *fmt1;
  2008. fmt1 = av_find_input_format("audio_device");
  2009. if (av_open_input_file(&ic, "", fmt1, 0, ap) < 0) {
  2010. fprintf(stderr, "Could not find audio grab device\n");
  2011. exit(1);
  2012. }
  2013. input_files[nb_input_files] = ic;
  2014. dump_format(ic, nb_input_files, audio_device, 0);
  2015. nb_input_files++;
  2016. }
  2017. }
  2018. /* open the necessary output devices for playing */
  2019. void prepare_play(void)
  2020. {
  2021. file_iformat = NULL;
  2022. file_oformat = guess_format("audio_device", NULL, NULL);
  2023. if (!file_oformat) {
  2024. fprintf(stderr, "Could not find audio device\n");
  2025. exit(1);
  2026. }
  2027. opt_output_file(audio_device);
  2028. }
  2029. /* same option as mencoder */
  2030. void opt_pass(const char *pass_str)
  2031. {
  2032. int pass;
  2033. pass = atoi(pass_str);
  2034. if (pass != 1 && pass != 2) {
  2035. fprintf(stderr, "pass number can be only 1 or 2\n");
  2036. exit(1);
  2037. }
  2038. do_pass = pass;
  2039. }
  2040. #ifndef CONFIG_WIN32
  2041. INT64 getutime(void)
  2042. {
  2043. struct rusage rusage;
  2044. getrusage(RUSAGE_SELF, &rusage);
  2045. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2046. }
  2047. #else
  2048. INT64 getutime(void)
  2049. {
  2050. return av_gettime();
  2051. }
  2052. #endif
  2053. extern int ffm_nopts;
  2054. void opt_bitexact(void)
  2055. {
  2056. avcodec_set_bit_exact();
  2057. /* disable generate of real time pts in ffm (need to be supressed anyway) */
  2058. ffm_nopts = 1;
  2059. }
  2060. void show_formats(void)
  2061. {
  2062. AVInputFormat *ifmt;
  2063. AVOutputFormat *ofmt;
  2064. URLProtocol *up;
  2065. AVCodec *p;
  2066. const char **pp;
  2067. printf("File formats:\n");
  2068. printf(" Encoding:");
  2069. for(ofmt = first_oformat; ofmt != NULL; ofmt = ofmt->next) {
  2070. printf(" %s", ofmt->name);
  2071. }
  2072. printf("\n");
  2073. printf(" Decoding:");
  2074. for(ifmt = first_iformat; ifmt != NULL; ifmt = ifmt->next) {
  2075. printf(" %s", ifmt->name);
  2076. }
  2077. printf("\n");
  2078. printf("Codecs:\n");
  2079. printf(" Encoders:");
  2080. for(p = first_avcodec; p != NULL; p = p->next) {
  2081. if (p->encode)
  2082. printf(" %s", p->name);
  2083. }
  2084. printf("\n");
  2085. printf(" Decoders:");
  2086. for(p = first_avcodec; p != NULL; p = p->next) {
  2087. if (p->decode)
  2088. printf(" %s", p->name);
  2089. }
  2090. printf("\n");
  2091. printf("Supported file protocols:");
  2092. for(up = first_protocol; up != NULL; up = up->next)
  2093. printf(" %s:", up->name);
  2094. printf("\n");
  2095. printf("Frame size abbreviations: sqcif qcif cif 4cif\n");
  2096. printf("Motion estimation methods:");
  2097. pp = motion_str;
  2098. while (*pp) {
  2099. printf(" %s", *pp);
  2100. if ((pp - motion_str + 1) == ME_ZERO)
  2101. printf("(fastest)");
  2102. else if ((pp - motion_str + 1) == ME_FULL)
  2103. printf("(slowest)");
  2104. else if ((pp - motion_str + 1) == ME_EPZS)
  2105. printf("(default)");
  2106. pp++;
  2107. }
  2108. printf("\n");
  2109. exit(1);
  2110. }
  2111. void show_help(void)
  2112. {
  2113. const char *prog;
  2114. const OptionDef *po;
  2115. int i, expert;
  2116. prog = do_play ? "ffplay" : "ffmpeg";
  2117. printf("%s version " FFMPEG_VERSION ", Copyright (c) 2000, 2001, 2002 Fabrice Bellard\n",
  2118. prog);
  2119. if (!do_play) {
  2120. printf("usage: ffmpeg [[options] -i input_file]... {[options] outfile}...\n"
  2121. "Hyper fast MPEG1/MPEG4/H263/RV and AC3/MPEG audio encoder\n");
  2122. } else {
  2123. printf("usage: ffplay [options] input_file...\n"
  2124. "Simple audio player\n");
  2125. }
  2126. printf("\n"
  2127. "Main options are:\n");
  2128. for(i=0;i<2;i++) {
  2129. if (i == 1)
  2130. printf("\nAdvanced options are:\n");
  2131. for(po = options; po->name != NULL; po++) {
  2132. char buf[64];
  2133. expert = (po->flags & OPT_EXPERT) != 0;
  2134. if (expert == i) {
  2135. strcpy(buf, po->name);
  2136. if (po->flags & HAS_ARG) {
  2137. strcat(buf, " ");
  2138. strcat(buf, po->argname);
  2139. }
  2140. printf("-%-17s %s\n", buf, po->help);
  2141. }
  2142. }
  2143. }
  2144. exit(1);
  2145. }
  2146. const OptionDef options[] = {
  2147. { "L", 0, {(void*)show_licence}, "show license" },
  2148. { "h", 0, {(void*)show_help}, "show help" },
  2149. { "formats", 0, {(void*)show_formats}, "show available formats, codecs, protocols, ..." },
  2150. { "f", HAS_ARG, {(void*)opt_format}, "force format", "fmt" },
  2151. { "i", HAS_ARG, {(void*)opt_input_file}, "input file name", "filename" },
  2152. { "y", OPT_BOOL, {(void*)&file_overwrite}, "overwrite output files" },
  2153. { "map", HAS_ARG | OPT_EXPERT, {(void*)opt_map}, "set input stream mapping", "file:stream" },
  2154. { "t", HAS_ARG, {(void*)opt_recording_time}, "set the recording time", "duration" },
  2155. { "title", HAS_ARG | OPT_STRING, {(void*)&str_title}, "set the title", "string" },
  2156. { "author", HAS_ARG | OPT_STRING, {(void*)&str_author}, "set the author", "string" },
  2157. { "copyright", HAS_ARG | OPT_STRING, {(void*)&str_copyright}, "set the copyright", "string" },
  2158. { "comment", HAS_ARG | OPT_STRING, {(void*)&str_comment}, "set the comment", "string" },
  2159. { "pass", HAS_ARG, {(void*)&opt_pass}, "select the pass number (1 or 2)", "n" },
  2160. { "passlogfile", HAS_ARG | OPT_STRING, {(void*)&pass_logfilename}, "select two pass log file name", "file" },
  2161. /* video options */
  2162. { "b", HAS_ARG, {(void*)opt_video_bitrate}, "set video bitrate (in kbit/s)", "bitrate" },
  2163. { "r", HAS_ARG, {(void*)opt_frame_rate}, "set frame rate (in Hz)", "rate" },
  2164. { "s", HAS_ARG, {(void*)opt_frame_size}, "set frame size (WxH or abbreviation)", "size" },
  2165. { "croptop", HAS_ARG, {(void*)opt_frame_crop_top}, "set top crop band size (in pixels)", "size" },
  2166. { "cropbottom", HAS_ARG, {(void*)opt_frame_crop_bottom}, "set bottom crop band size (in pixels)", "size" },
  2167. { "cropleft", HAS_ARG, {(void*)opt_frame_crop_left}, "set left crop band size (in pixels)", "size" },
  2168. { "cropright", HAS_ARG, {(void*)opt_frame_crop_right}, "set right crop band size (in pixels)", "size" },
  2169. { "g", HAS_ARG | OPT_EXPERT, {(void*)opt_gop_size}, "set the group of picture size", "gop_size" },
  2170. { "intra", OPT_BOOL | OPT_EXPERT, {(void*)&intra_only}, "use only intra frames"},
  2171. { "vn", OPT_BOOL, {(void*)&video_disable}, "disable video" },
  2172. { "qscale", HAS_ARG | OPT_EXPERT, {(void*)opt_qscale}, "use fixed video quantiser scale (VBR)", "q" },
  2173. { "qmin", HAS_ARG | OPT_EXPERT, {(void*)opt_qmin}, "min video quantiser scale (VBR)", "q" },
  2174. { "qmax", HAS_ARG | OPT_EXPERT, {(void*)opt_qmax}, "max video quantiser scale (VBR)", "q" },
  2175. { "qdiff", HAS_ARG | OPT_EXPERT, {(void*)opt_qdiff}, "max difference between the quantiser scale (VBR)", "q" },
  2176. { "qblur", HAS_ARG | OPT_EXPERT, {(void*)opt_qblur}, "video quantiser scale blur (VBR)", "blur" },
  2177. { "qcomp", HAS_ARG | OPT_EXPERT, {(void*)opt_qcomp}, "video quantiser scale compression (VBR)", "compression" },
  2178. { "rc_init_cplx", HAS_ARG | OPT_EXPERT, {(void*)opt_rc_initial_cplx}, "initial complexity for 1-pass encoding", "complexity" },
  2179. { "b_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qfactor}, "qp factor between p and b frames", "factor" },
  2180. { "i_qfactor", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qfactor}, "qp factor between p and i frames", "factor" },
  2181. { "b_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_b_qoffset}, "qp offset between p and b frames", "offset" },
  2182. { "i_qoffset", HAS_ARG | OPT_EXPERT, {(void*)opt_i_qoffset}, "qp offset between p and i frames", "offset" },
  2183. { "rc_eq", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_eq}, "", "equation" },
  2184. { "rc_override", HAS_ARG | OPT_EXPERT, {(void*)opt_video_rc_override_string}, "Rate control override", "qualities for specific intervals" },
  2185. { "bt", HAS_ARG, {(void*)opt_video_bitrate_tolerance}, "set video bitrate tolerance (in kbit/s)", "tolerance" },
  2186. { "maxrate", HAS_ARG, {(void*)opt_video_bitrate_max}, "set max video bitrate tolerance (in kbit/s)", "bitrate" },
  2187. { "minrate", HAS_ARG, {(void*)opt_video_bitrate_min}, "set min video bitrate tolerance (in kbit/s)", "bitrate" },
  2188. { "bufsize", HAS_ARG, {(void*)opt_video_buffer_size}, "set ratecontrol buffere size (in kbit)", "size" },
  2189. { "vd", HAS_ARG | OPT_EXPERT, {(void*)opt_video_device}, "set video grab device", "device" },
  2190. { "vcodec", HAS_ARG | OPT_EXPERT, {(void*)opt_video_codec}, "force video codec ('copy' to copy stream)", "codec" },
  2191. { "me", HAS_ARG | OPT_EXPERT, {(void*)opt_motion_estimation}, "set motion estimation method",
  2192. "method" },
  2193. { "dct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_dct_algo}, "set dct algo", "algo" },
  2194. { "idct_algo", HAS_ARG | OPT_EXPERT, {(void*)opt_idct_algo}, "set idct algo", "algo" },
  2195. { "er", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error resilience", "" },
  2196. { "ec", HAS_ARG | OPT_EXPERT, {(void*)opt_error_resilience}, "set error concealment", "" },
  2197. { "bf", HAS_ARG | OPT_EXPERT, {(void*)opt_b_frames}, "use 'frames' B frames (only MPEG-4)", "frames" },
  2198. { "hq", OPT_BOOL | OPT_EXPERT, {(void*)&use_hq}, "activate high quality settings" },
  2199. { "4mv", OPT_BOOL | OPT_EXPERT, {(void*)&use_4mv}, "use four motion vector by macroblock (only MPEG-4)" },
  2200. { "part", OPT_BOOL | OPT_EXPERT, {(void*)&use_part}, "use data partitioning (only MPEG-4)" },
  2201. { "bug", HAS_ARG | OPT_EXPERT, {(void*)opt_workaround_bugs}, "workaround not auto detected encoder bugs", "param" },
  2202. { "ps", HAS_ARG | OPT_EXPERT, {(void*)opt_packet_size}, "packet size", "size in bits" },
  2203. { "sameq", OPT_BOOL, {(void*)&same_quality},
  2204. "use same video quality as source (implies VBR)" },
  2205. /* audio options */
  2206. { "ab", HAS_ARG, {(void*)opt_audio_bitrate}, "set audio bitrate (in kbit/s)", "bitrate", },
  2207. { "ar", HAS_ARG, {(void*)opt_audio_rate}, "set audio sampling rate (in Hz)", "rate" },
  2208. { "ac", HAS_ARG, {(void*)opt_audio_channels}, "set number of audio channels", "channels" },
  2209. { "an", OPT_BOOL, {(void*)&audio_disable}, "disable audio" },
  2210. { "ad", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_device}, "set audio device", "device" },
  2211. { "acodec", HAS_ARG | OPT_EXPERT, {(void*)opt_audio_codec}, "force audio codec ('copy' to copy stream)", "codec" },
  2212. { "deinterlace", OPT_BOOL | OPT_EXPERT, {(void*)&do_deinterlace},
  2213. "deinterlace pictures" },
  2214. { "benchmark", OPT_BOOL | OPT_EXPERT, {(void*)&do_benchmark},
  2215. "add timings for benchmarking" },
  2216. { "hex", OPT_BOOL | OPT_EXPERT, {(void*)&do_hex_dump},
  2217. "dump each input packet" },
  2218. { "psnr", OPT_BOOL | OPT_EXPERT, {(void*)&do_psnr}, "calculate PSNR of compressed frames" },
  2219. { "vstats", OPT_BOOL | OPT_EXPERT, {(void*)&do_vstats}, "dump video coding statistics to file" },
  2220. { "bitexact", OPT_EXPERT, {(void*)opt_bitexact}, "only use bit exact algorithms (for codec testing)" },
  2221. { NULL, },
  2222. };
  2223. int main(int argc, char **argv)
  2224. {
  2225. int optindex, i;
  2226. const char *opt, *arg;
  2227. const OptionDef *po;
  2228. INT64 ti;
  2229. av_register_all();
  2230. /* detect if invoked as player */
  2231. i = strlen(argv[0]);
  2232. if (i >= 6 && !strcmp(argv[0] + i - 6, "ffplay"))
  2233. do_play = 1;
  2234. if (argc <= 1)
  2235. show_help();
  2236. /* parse options */
  2237. optindex = 1;
  2238. while (optindex < argc) {
  2239. opt = argv[optindex++];
  2240. if (opt[0] == '-' && opt[1] != '\0') {
  2241. po = options;
  2242. while (po->name != NULL) {
  2243. if (!strcmp(opt + 1, po->name))
  2244. break;
  2245. po++;
  2246. }
  2247. if (!po->name) {
  2248. fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], opt);
  2249. exit(1);
  2250. }
  2251. arg = NULL;
  2252. if (po->flags & HAS_ARG)
  2253. arg = argv[optindex++];
  2254. if (po->flags & OPT_STRING) {
  2255. char *str;
  2256. str = strdup(arg);
  2257. *po->u.str_arg = str;
  2258. } else if (po->flags & OPT_BOOL) {
  2259. *po->u.int_arg = 1;
  2260. } else {
  2261. po->u.func_arg(arg);
  2262. }
  2263. } else {
  2264. if (!do_play) {
  2265. opt_output_file(opt);
  2266. } else {
  2267. opt_input_file(opt);
  2268. }
  2269. }
  2270. }
  2271. if (!do_play) {
  2272. /* file converter / grab */
  2273. if (nb_output_files <= 0) {
  2274. fprintf(stderr, "Must supply at least one output file\n");
  2275. exit(1);
  2276. }
  2277. if (nb_input_files == 0) {
  2278. prepare_grab();
  2279. }
  2280. } else {
  2281. /* player */
  2282. if (nb_input_files <= 0) {
  2283. fprintf(stderr, "Must supply at least one input file\n");
  2284. exit(1);
  2285. }
  2286. prepare_play();
  2287. }
  2288. ti = getutime();
  2289. av_encode(output_files, nb_output_files, input_files, nb_input_files,
  2290. stream_maps, nb_stream_maps);
  2291. ti = getutime() - ti;
  2292. if (do_benchmark) {
  2293. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  2294. }
  2295. /* close files */
  2296. for(i=0;i<nb_output_files;i++) {
  2297. if (!(output_files[i]->oformat->flags & AVFMT_NOFILE))
  2298. url_fclose(&output_files[i]->pb);
  2299. }
  2300. for(i=0;i<nb_input_files;i++)
  2301. av_close_input_file(input_files[i]);
  2302. return 0;
  2303. }