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.

3054 lines
101KB

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