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.

3049 lines
100KB

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