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.

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