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.

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