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.

3042 lines
100KB

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