ffmpeg.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  1. /*
  2. * Copyright (c) 2000-2003 Fabrice Bellard
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * multimedia converter based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #include <errno.h>
  26. #include <limits.h>
  27. #include <stdatomic.h>
  28. #include <stdint.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #if HAVE_IO_H
  33. #include <io.h>
  34. #endif
  35. #if HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #if HAVE_SYS_RESOURCE_H
  39. #include <sys/time.h>
  40. #include <sys/types.h>
  41. #include <sys/resource.h>
  42. #elif HAVE_GETPROCESSTIMES
  43. #include <windows.h>
  44. #endif
  45. #if HAVE_GETPROCESSMEMORYINFO
  46. #include <windows.h>
  47. #include <psapi.h>
  48. #endif
  49. #if HAVE_SETCONSOLECTRLHANDLER
  50. #include <windows.h>
  51. #endif
  52. #if HAVE_SYS_SELECT_H
  53. #include <sys/select.h>
  54. #endif
  55. #if HAVE_TERMIOS_H
  56. #include <fcntl.h>
  57. #include <sys/ioctl.h>
  58. #include <sys/time.h>
  59. #include <termios.h>
  60. #elif HAVE_KBHIT
  61. #include <conio.h>
  62. #endif
  63. #include "libavutil/bprint.h"
  64. #include "libavutil/dict.h"
  65. #include "libavutil/mem.h"
  66. #include "libavutil/time.h"
  67. #include "libavformat/avformat.h"
  68. #include "libavdevice/avdevice.h"
  69. #include "cmdutils.h"
  70. #include "ffmpeg.h"
  71. #include "ffmpeg_sched.h"
  72. #include "ffmpeg_utils.h"
  73. const char program_name[] = "ffmpeg";
  74. const int program_birth_year = 2000;
  75. FILE *vstats_file;
  76. typedef struct BenchmarkTimeStamps {
  77. int64_t real_usec;
  78. int64_t user_usec;
  79. int64_t sys_usec;
  80. } BenchmarkTimeStamps;
  81. static BenchmarkTimeStamps get_benchmark_time_stamps(void);
  82. static int64_t getmaxrss(void);
  83. atomic_uint nb_output_dumped = 0;
  84. static BenchmarkTimeStamps current_time;
  85. AVIOContext *progress_avio = NULL;
  86. InputFile **input_files = NULL;
  87. int nb_input_files = 0;
  88. OutputFile **output_files = NULL;
  89. int nb_output_files = 0;
  90. FilterGraph **filtergraphs;
  91. int nb_filtergraphs;
  92. Decoder **decoders;
  93. int nb_decoders;
  94. #if HAVE_TERMIOS_H
  95. /* init terminal so that we can grab keys */
  96. static struct termios oldtty;
  97. static int restore_tty;
  98. #endif
  99. static void term_exit_sigsafe(void)
  100. {
  101. #if HAVE_TERMIOS_H
  102. if(restore_tty)
  103. tcsetattr (0, TCSANOW, &oldtty);
  104. #endif
  105. }
  106. void term_exit(void)
  107. {
  108. av_log(NULL, AV_LOG_QUIET, "%s", "");
  109. term_exit_sigsafe();
  110. }
  111. static volatile int received_sigterm = 0;
  112. static volatile int received_nb_signals = 0;
  113. static atomic_int transcode_init_done = 0;
  114. static volatile int ffmpeg_exited = 0;
  115. static int64_t copy_ts_first_pts = AV_NOPTS_VALUE;
  116. static void
  117. sigterm_handler(int sig)
  118. {
  119. int ret;
  120. received_sigterm = sig;
  121. received_nb_signals++;
  122. term_exit_sigsafe();
  123. if(received_nb_signals > 3) {
  124. ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
  125. strlen("Received > 3 system signals, hard exiting\n"));
  126. if (ret < 0) { /* Do nothing */ };
  127. exit(123);
  128. }
  129. }
  130. #if HAVE_SETCONSOLECTRLHANDLER
  131. static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
  132. {
  133. av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
  134. switch (fdwCtrlType)
  135. {
  136. case CTRL_C_EVENT:
  137. case CTRL_BREAK_EVENT:
  138. sigterm_handler(SIGINT);
  139. return TRUE;
  140. case CTRL_CLOSE_EVENT:
  141. case CTRL_LOGOFF_EVENT:
  142. case CTRL_SHUTDOWN_EVENT:
  143. sigterm_handler(SIGTERM);
  144. /* Basically, with these 3 events, when we return from this method the
  145. process is hard terminated, so stall as long as we need to
  146. to try and let the main thread(s) clean up and gracefully terminate
  147. (we have at most 5 seconds, but should be done far before that). */
  148. while (!ffmpeg_exited) {
  149. Sleep(0);
  150. }
  151. return TRUE;
  152. default:
  153. av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
  154. return FALSE;
  155. }
  156. }
  157. #endif
  158. #ifdef __linux__
  159. #define SIGNAL(sig, func) \
  160. do { \
  161. action.sa_handler = func; \
  162. sigaction(sig, &action, NULL); \
  163. } while (0)
  164. #else
  165. #define SIGNAL(sig, func) \
  166. signal(sig, func)
  167. #endif
  168. void term_init(void)
  169. {
  170. #if defined __linux__
  171. struct sigaction action = {0};
  172. action.sa_handler = sigterm_handler;
  173. /* block other interrupts while processing this one */
  174. sigfillset(&action.sa_mask);
  175. /* restart interruptible functions (i.e. don't fail with EINTR) */
  176. action.sa_flags = SA_RESTART;
  177. #endif
  178. #if HAVE_TERMIOS_H
  179. if (stdin_interaction) {
  180. struct termios tty;
  181. if (tcgetattr (0, &tty) == 0) {
  182. oldtty = tty;
  183. restore_tty = 1;
  184. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  185. |INLCR|IGNCR|ICRNL|IXON);
  186. tty.c_oflag |= OPOST;
  187. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  188. tty.c_cflag &= ~(CSIZE|PARENB);
  189. tty.c_cflag |= CS8;
  190. tty.c_cc[VMIN] = 1;
  191. tty.c_cc[VTIME] = 0;
  192. tcsetattr (0, TCSANOW, &tty);
  193. }
  194. SIGNAL(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  195. }
  196. #endif
  197. SIGNAL(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  198. SIGNAL(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  199. #ifdef SIGXCPU
  200. SIGNAL(SIGXCPU, sigterm_handler);
  201. #endif
  202. #ifdef SIGPIPE
  203. signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
  204. #endif
  205. #if HAVE_SETCONSOLECTRLHANDLER
  206. SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
  207. #endif
  208. }
  209. /* read a key without blocking */
  210. static int read_key(void)
  211. {
  212. unsigned char ch;
  213. #if HAVE_TERMIOS_H
  214. int n = 1;
  215. struct timeval tv;
  216. fd_set rfds;
  217. FD_ZERO(&rfds);
  218. FD_SET(0, &rfds);
  219. tv.tv_sec = 0;
  220. tv.tv_usec = 0;
  221. n = select(1, &rfds, NULL, NULL, &tv);
  222. if (n > 0) {
  223. n = read(0, &ch, 1);
  224. if (n == 1)
  225. return ch;
  226. return n;
  227. }
  228. #elif HAVE_KBHIT
  229. # if HAVE_PEEKNAMEDPIPE && HAVE_GETSTDHANDLE
  230. static int is_pipe;
  231. static HANDLE input_handle;
  232. DWORD dw, nchars;
  233. if(!input_handle){
  234. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  235. is_pipe = !GetConsoleMode(input_handle, &dw);
  236. }
  237. if (is_pipe) {
  238. /* When running under a GUI, you will end here. */
  239. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
  240. // input pipe may have been closed by the program that ran ffmpeg
  241. return -1;
  242. }
  243. //Read it
  244. if(nchars != 0) {
  245. if (read(0, &ch, 1) == 1)
  246. return ch;
  247. return 0;
  248. }else{
  249. return -1;
  250. }
  251. }
  252. # endif
  253. if(kbhit())
  254. return(getch());
  255. #endif
  256. return -1;
  257. }
  258. static int decode_interrupt_cb(void *ctx)
  259. {
  260. return received_nb_signals > atomic_load(&transcode_init_done);
  261. }
  262. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  263. static void ffmpeg_cleanup(int ret)
  264. {
  265. if (do_benchmark) {
  266. int64_t maxrss = getmaxrss() / 1024;
  267. av_log(NULL, AV_LOG_INFO, "bench: maxrss=%"PRId64"KiB\n", maxrss);
  268. }
  269. for (int i = 0; i < nb_filtergraphs; i++)
  270. fg_free(&filtergraphs[i]);
  271. av_freep(&filtergraphs);
  272. for (int i = 0; i < nb_output_files; i++)
  273. of_free(&output_files[i]);
  274. for (int i = 0; i < nb_input_files; i++)
  275. ifile_close(&input_files[i]);
  276. for (int i = 0; i < nb_decoders; i++)
  277. dec_free(&decoders[i]);
  278. av_freep(&decoders);
  279. if (vstats_file) {
  280. if (fclose(vstats_file))
  281. av_log(NULL, AV_LOG_ERROR,
  282. "Error closing vstats file, loss of information possible: %s\n",
  283. av_err2str(AVERROR(errno)));
  284. }
  285. av_freep(&vstats_filename);
  286. of_enc_stats_close();
  287. hw_device_free_all();
  288. av_freep(&filter_nbthreads);
  289. av_freep(&input_files);
  290. av_freep(&output_files);
  291. uninit_opts();
  292. avformat_network_deinit();
  293. if (received_sigterm) {
  294. av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
  295. (int) received_sigterm);
  296. } else if (ret && atomic_load(&transcode_init_done)) {
  297. av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
  298. }
  299. term_exit();
  300. ffmpeg_exited = 1;
  301. }
  302. OutputStream *ost_iter(OutputStream *prev)
  303. {
  304. int of_idx = prev ? prev->file->index : 0;
  305. int ost_idx = prev ? prev->index + 1 : 0;
  306. for (; of_idx < nb_output_files; of_idx++) {
  307. OutputFile *of = output_files[of_idx];
  308. if (ost_idx < of->nb_streams)
  309. return of->streams[ost_idx];
  310. ost_idx = 0;
  311. }
  312. return NULL;
  313. }
  314. InputStream *ist_iter(InputStream *prev)
  315. {
  316. int if_idx = prev ? prev->file->index : 0;
  317. int ist_idx = prev ? prev->index + 1 : 0;
  318. for (; if_idx < nb_input_files; if_idx++) {
  319. InputFile *f = input_files[if_idx];
  320. if (ist_idx < f->nb_streams)
  321. return f->streams[ist_idx];
  322. ist_idx = 0;
  323. }
  324. return NULL;
  325. }
  326. static void frame_data_free(void *opaque, uint8_t *data)
  327. {
  328. FrameData *fd = (FrameData *)data;
  329. avcodec_parameters_free(&fd->par_enc);
  330. av_free(data);
  331. }
  332. static int frame_data_ensure(AVBufferRef **dst, int writable)
  333. {
  334. AVBufferRef *src = *dst;
  335. if (!src || (writable && !av_buffer_is_writable(src))) {
  336. FrameData *fd;
  337. fd = av_mallocz(sizeof(*fd));
  338. if (!fd)
  339. return AVERROR(ENOMEM);
  340. *dst = av_buffer_create((uint8_t *)fd, sizeof(*fd),
  341. frame_data_free, NULL, 0);
  342. if (!*dst) {
  343. av_buffer_unref(&src);
  344. av_freep(&fd);
  345. return AVERROR(ENOMEM);
  346. }
  347. if (src) {
  348. const FrameData *fd_src = (const FrameData *)src->data;
  349. memcpy(fd, fd_src, sizeof(*fd));
  350. fd->par_enc = NULL;
  351. if (fd_src->par_enc) {
  352. int ret = 0;
  353. fd->par_enc = avcodec_parameters_alloc();
  354. ret = fd->par_enc ?
  355. avcodec_parameters_copy(fd->par_enc, fd_src->par_enc) :
  356. AVERROR(ENOMEM);
  357. if (ret < 0) {
  358. av_buffer_unref(dst);
  359. av_buffer_unref(&src);
  360. return ret;
  361. }
  362. }
  363. av_buffer_unref(&src);
  364. } else {
  365. fd->dec.frame_num = UINT64_MAX;
  366. fd->dec.pts = AV_NOPTS_VALUE;
  367. for (unsigned i = 0; i < FF_ARRAY_ELEMS(fd->wallclock); i++)
  368. fd->wallclock[i] = INT64_MIN;
  369. }
  370. }
  371. return 0;
  372. }
  373. FrameData *frame_data(AVFrame *frame)
  374. {
  375. int ret = frame_data_ensure(&frame->opaque_ref, 1);
  376. return ret < 0 ? NULL : (FrameData*)frame->opaque_ref->data;
  377. }
  378. const FrameData *frame_data_c(AVFrame *frame)
  379. {
  380. int ret = frame_data_ensure(&frame->opaque_ref, 0);
  381. return ret < 0 ? NULL : (const FrameData*)frame->opaque_ref->data;
  382. }
  383. FrameData *packet_data(AVPacket *pkt)
  384. {
  385. int ret = frame_data_ensure(&pkt->opaque_ref, 1);
  386. return ret < 0 ? NULL : (FrameData*)pkt->opaque_ref->data;
  387. }
  388. const FrameData *packet_data_c(AVPacket *pkt)
  389. {
  390. int ret = frame_data_ensure(&pkt->opaque_ref, 0);
  391. return ret < 0 ? NULL : (const FrameData*)pkt->opaque_ref->data;
  392. }
  393. int check_avoptions_used(const AVDictionary *opts, const AVDictionary *opts_used,
  394. void *logctx, int decode)
  395. {
  396. const AVClass *class = avcodec_get_class();
  397. const AVClass *fclass = avformat_get_class();
  398. const int flag = decode ? AV_OPT_FLAG_DECODING_PARAM :
  399. AV_OPT_FLAG_ENCODING_PARAM;
  400. const AVDictionaryEntry *e = NULL;
  401. while ((e = av_dict_iterate(opts, e))) {
  402. const AVOption *option, *foption;
  403. char *optname, *p;
  404. if (av_dict_get(opts_used, e->key, NULL, 0))
  405. continue;
  406. optname = av_strdup(e->key);
  407. if (!optname)
  408. return AVERROR(ENOMEM);
  409. p = strchr(optname, ':');
  410. if (p)
  411. *p = 0;
  412. option = av_opt_find(&class, optname, NULL, 0,
  413. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
  414. foption = av_opt_find(&fclass, optname, NULL, 0,
  415. AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ);
  416. av_freep(&optname);
  417. if (!option || foption)
  418. continue;
  419. if (!(option->flags & flag)) {
  420. av_log(logctx, AV_LOG_ERROR, "Codec AVOption %s (%s) is not a %s "
  421. "option.\n", e->key, option->help ? option->help : "",
  422. decode ? "decoding" : "encoding");
  423. return AVERROR(EINVAL);
  424. }
  425. av_log(logctx, AV_LOG_WARNING, "Codec AVOption %s (%s) has not been used "
  426. "for any stream. The most likely reason is either wrong type "
  427. "(e.g. a video option with no video streams) or that it is a "
  428. "private option of some decoder which was not actually used "
  429. "for any stream.\n", e->key, option->help ? option->help : "");
  430. }
  431. return 0;
  432. }
  433. void update_benchmark(const char *fmt, ...)
  434. {
  435. if (do_benchmark_all) {
  436. BenchmarkTimeStamps t = get_benchmark_time_stamps();
  437. va_list va;
  438. char buf[1024];
  439. if (fmt) {
  440. va_start(va, fmt);
  441. vsnprintf(buf, sizeof(buf), fmt, va);
  442. va_end(va);
  443. av_log(NULL, AV_LOG_INFO,
  444. "bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
  445. t.user_usec - current_time.user_usec,
  446. t.sys_usec - current_time.sys_usec,
  447. t.real_usec - current_time.real_usec, buf);
  448. }
  449. current_time = t;
  450. }
  451. }
  452. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time, int64_t pts)
  453. {
  454. AVBPrint buf, buf_script;
  455. int64_t total_size = of_filesize(output_files[0]);
  456. int vid;
  457. double bitrate;
  458. double speed;
  459. static int64_t last_time = -1;
  460. static int first_report = 1;
  461. uint64_t nb_frames_dup = 0, nb_frames_drop = 0;
  462. int mins, secs, us;
  463. int64_t hours;
  464. const char *hours_sign;
  465. int ret;
  466. float t;
  467. if (!print_stats && !is_last_report && !progress_avio)
  468. return;
  469. if (!is_last_report) {
  470. if (last_time == -1) {
  471. last_time = cur_time;
  472. }
  473. if (((cur_time - last_time) < stats_period && !first_report) ||
  474. (first_report && atomic_load(&nb_output_dumped) < nb_output_files))
  475. return;
  476. last_time = cur_time;
  477. }
  478. t = (cur_time-timer_start) / 1000000.0;
  479. vid = 0;
  480. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
  481. av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
  482. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  483. const float q = ost->enc ? atomic_load(&ost->quality) / (float) FF_QP2LAMBDA : -1;
  484. if (vid && ost->type == AVMEDIA_TYPE_VIDEO) {
  485. av_bprintf(&buf, "q=%2.1f ", q);
  486. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  487. ost->file->index, ost->index, q);
  488. }
  489. if (!vid && ost->type == AVMEDIA_TYPE_VIDEO && ost->filter) {
  490. float fps;
  491. uint64_t frame_number = atomic_load(&ost->packets_written);
  492. fps = t > 1 ? frame_number / t : 0;
  493. av_bprintf(&buf, "frame=%5"PRId64" fps=%3.*f q=%3.1f ",
  494. frame_number, fps < 9.95, fps, q);
  495. av_bprintf(&buf_script, "frame=%"PRId64"\n", frame_number);
  496. av_bprintf(&buf_script, "fps=%.2f\n", fps);
  497. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  498. ost->file->index, ost->index, q);
  499. if (is_last_report)
  500. av_bprintf(&buf, "L");
  501. nb_frames_dup = atomic_load(&ost->filter->nb_frames_dup);
  502. nb_frames_drop = atomic_load(&ost->filter->nb_frames_drop);
  503. vid = 1;
  504. }
  505. }
  506. if (copy_ts) {
  507. if (copy_ts_first_pts == AV_NOPTS_VALUE && pts > 1)
  508. copy_ts_first_pts = pts;
  509. if (copy_ts_first_pts != AV_NOPTS_VALUE)
  510. pts -= copy_ts_first_pts;
  511. }
  512. us = FFABS64U(pts) % AV_TIME_BASE;
  513. secs = FFABS64U(pts) / AV_TIME_BASE % 60;
  514. mins = FFABS64U(pts) / AV_TIME_BASE / 60 % 60;
  515. hours = FFABS64U(pts) / AV_TIME_BASE / 3600;
  516. hours_sign = (pts < 0) ? "-" : "";
  517. bitrate = pts != AV_NOPTS_VALUE && pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  518. speed = pts != AV_NOPTS_VALUE && t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
  519. if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
  520. else av_bprintf(&buf, "size=%8.0fKiB time=", total_size / 1024.0);
  521. if (pts == AV_NOPTS_VALUE) {
  522. av_bprintf(&buf, "N/A ");
  523. } else {
  524. av_bprintf(&buf, "%s%02"PRId64":%02d:%02d.%02d ",
  525. hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
  526. }
  527. if (bitrate < 0) {
  528. av_bprintf(&buf, "bitrate=N/A");
  529. av_bprintf(&buf_script, "bitrate=N/A\n");
  530. }else{
  531. av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
  532. av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
  533. }
  534. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  535. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  536. if (pts == AV_NOPTS_VALUE) {
  537. av_bprintf(&buf_script, "out_time_us=N/A\n");
  538. av_bprintf(&buf_script, "out_time_ms=N/A\n");
  539. av_bprintf(&buf_script, "out_time=N/A\n");
  540. } else {
  541. av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
  542. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  543. av_bprintf(&buf_script, "out_time=%s%02"PRId64":%02d:%02d.%06d\n",
  544. hours_sign, hours, mins, secs, us);
  545. }
  546. if (nb_frames_dup || nb_frames_drop)
  547. av_bprintf(&buf, " dup=%"PRId64" drop=%"PRId64, nb_frames_dup, nb_frames_drop);
  548. av_bprintf(&buf_script, "dup_frames=%"PRId64"\n", nb_frames_dup);
  549. av_bprintf(&buf_script, "drop_frames=%"PRId64"\n", nb_frames_drop);
  550. if (speed < 0) {
  551. av_bprintf(&buf, " speed=N/A");
  552. av_bprintf(&buf_script, "speed=N/A\n");
  553. } else {
  554. av_bprintf(&buf, " speed=%4.3gx", speed);
  555. av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
  556. }
  557. if (print_stats || is_last_report) {
  558. const char end = is_last_report ? '\n' : '\r';
  559. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  560. fprintf(stderr, "%s %c", buf.str, end);
  561. } else
  562. av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
  563. fflush(stderr);
  564. }
  565. av_bprint_finalize(&buf, NULL);
  566. if (progress_avio) {
  567. av_bprintf(&buf_script, "progress=%s\n",
  568. is_last_report ? "end" : "continue");
  569. avio_write(progress_avio, buf_script.str,
  570. FFMIN(buf_script.len, buf_script.size - 1));
  571. avio_flush(progress_avio);
  572. av_bprint_finalize(&buf_script, NULL);
  573. if (is_last_report) {
  574. if ((ret = avio_closep(&progress_avio)) < 0)
  575. av_log(NULL, AV_LOG_ERROR,
  576. "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
  577. }
  578. }
  579. first_report = 0;
  580. }
  581. static void print_stream_maps(void)
  582. {
  583. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  584. for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
  585. for (int j = 0; j < ist->nb_filters; j++) {
  586. if (!filtergraph_is_simple(ist->filters[j]->graph)) {
  587. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  588. ist->file->index, ist->index, ist->dec ? ist->dec->name : "?",
  589. ist->filters[j]->name);
  590. if (nb_filtergraphs > 1)
  591. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  592. av_log(NULL, AV_LOG_INFO, "\n");
  593. }
  594. }
  595. }
  596. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  597. if (ost->attachment_filename) {
  598. /* an attached file */
  599. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  600. ost->attachment_filename, ost->file->index, ost->index);
  601. continue;
  602. }
  603. if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
  604. /* output from a complex graph */
  605. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  606. if (nb_filtergraphs > 1)
  607. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  608. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file->index,
  609. ost->index, ost->enc_ctx->codec->name);
  610. continue;
  611. }
  612. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  613. ost->ist->file->index,
  614. ost->ist->index,
  615. ost->file->index,
  616. ost->index);
  617. if (ost->enc_ctx) {
  618. const AVCodec *in_codec = ost->ist->dec;
  619. const AVCodec *out_codec = ost->enc_ctx->codec;
  620. const char *decoder_name = "?";
  621. const char *in_codec_name = "?";
  622. const char *encoder_name = "?";
  623. const char *out_codec_name = "?";
  624. const AVCodecDescriptor *desc;
  625. if (in_codec) {
  626. decoder_name = in_codec->name;
  627. desc = avcodec_descriptor_get(in_codec->id);
  628. if (desc)
  629. in_codec_name = desc->name;
  630. if (!strcmp(decoder_name, in_codec_name))
  631. decoder_name = "native";
  632. }
  633. if (out_codec) {
  634. encoder_name = out_codec->name;
  635. desc = avcodec_descriptor_get(out_codec->id);
  636. if (desc)
  637. out_codec_name = desc->name;
  638. if (!strcmp(encoder_name, out_codec_name))
  639. encoder_name = "native";
  640. }
  641. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  642. in_codec_name, decoder_name,
  643. out_codec_name, encoder_name);
  644. } else
  645. av_log(NULL, AV_LOG_INFO, " (copy)");
  646. av_log(NULL, AV_LOG_INFO, "\n");
  647. }
  648. }
  649. static void set_tty_echo(int on)
  650. {
  651. #if HAVE_TERMIOS_H
  652. struct termios tty;
  653. if (tcgetattr(0, &tty) == 0) {
  654. if (on) tty.c_lflag |= ECHO;
  655. else tty.c_lflag &= ~ECHO;
  656. tcsetattr(0, TCSANOW, &tty);
  657. }
  658. #endif
  659. }
  660. static int check_keyboard_interaction(int64_t cur_time)
  661. {
  662. int i, key;
  663. static int64_t last_time;
  664. if (received_nb_signals)
  665. return AVERROR_EXIT;
  666. /* read_key() returns 0 on EOF */
  667. if (cur_time - last_time >= 100000) {
  668. key = read_key();
  669. last_time = cur_time;
  670. }else
  671. key = -1;
  672. if (key == 'q') {
  673. av_log(NULL, AV_LOG_INFO, "\n\n[q] command received. Exiting.\n\n");
  674. return AVERROR_EXIT;
  675. }
  676. if (key == '+') av_log_set_level(av_log_get_level()+10);
  677. if (key == '-') av_log_set_level(av_log_get_level()-10);
  678. if (key == 'c' || key == 'C'){
  679. char buf[4096], target[64], command[256], arg[256] = {0};
  680. double time;
  681. int k, n = 0;
  682. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  683. i = 0;
  684. set_tty_echo(1);
  685. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  686. if (k > 0)
  687. buf[i++] = k;
  688. buf[i] = 0;
  689. set_tty_echo(0);
  690. fprintf(stderr, "\n");
  691. if (k > 0 &&
  692. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  693. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  694. target, time, command, arg);
  695. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  696. if (ost->fg_simple)
  697. fg_send_command(ost->fg_simple, time, target, command, arg,
  698. key == 'C');
  699. }
  700. for (i = 0; i < nb_filtergraphs; i++)
  701. fg_send_command(filtergraphs[i], time, target, command, arg,
  702. key == 'C');
  703. } else {
  704. av_log(NULL, AV_LOG_ERROR,
  705. "Parse error, at least 3 arguments were expected, "
  706. "only %d given in string '%s'\n", n, buf);
  707. }
  708. }
  709. if (key == '?'){
  710. fprintf(stderr, "key function\n"
  711. "? show this help\n"
  712. "+ increase verbosity\n"
  713. "- decrease verbosity\n"
  714. "c Send command to first matching filter supporting it\n"
  715. "C Send/Queue command to all matching filters\n"
  716. "h dump packets/hex press to cycle through the 3 states\n"
  717. "q quit\n"
  718. "s Show QP histogram\n"
  719. );
  720. }
  721. return 0;
  722. }
  723. /*
  724. * The following code is the main loop of the file converter
  725. */
  726. static int transcode(Scheduler *sch)
  727. {
  728. int ret = 0;
  729. int64_t timer_start, transcode_ts = 0;
  730. print_stream_maps();
  731. atomic_store(&transcode_init_done, 1);
  732. ret = sch_start(sch);
  733. if (ret < 0)
  734. return ret;
  735. if (stdin_interaction) {
  736. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  737. }
  738. timer_start = av_gettime_relative();
  739. while (!sch_wait(sch, stats_period, &transcode_ts)) {
  740. int64_t cur_time= av_gettime_relative();
  741. /* if 'q' pressed, exits */
  742. if (stdin_interaction)
  743. if (check_keyboard_interaction(cur_time) < 0)
  744. break;
  745. /* dump report by using the output first video and audio streams */
  746. print_report(0, timer_start, cur_time, transcode_ts);
  747. }
  748. ret = sch_stop(sch, &transcode_ts);
  749. /* write the trailer if needed */
  750. for (int i = 0; i < nb_output_files; i++) {
  751. int err = of_write_trailer(output_files[i]);
  752. ret = err_merge(ret, err);
  753. }
  754. term_exit();
  755. /* dump report by using the first video and audio streams */
  756. print_report(1, timer_start, av_gettime_relative(), transcode_ts);
  757. return ret;
  758. }
  759. static BenchmarkTimeStamps get_benchmark_time_stamps(void)
  760. {
  761. BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
  762. #if HAVE_GETRUSAGE
  763. struct rusage rusage;
  764. getrusage(RUSAGE_SELF, &rusage);
  765. time_stamps.user_usec =
  766. (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  767. time_stamps.sys_usec =
  768. (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
  769. #elif HAVE_GETPROCESSTIMES
  770. HANDLE proc;
  771. FILETIME c, e, k, u;
  772. proc = GetCurrentProcess();
  773. GetProcessTimes(proc, &c, &e, &k, &u);
  774. time_stamps.user_usec =
  775. ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  776. time_stamps.sys_usec =
  777. ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
  778. #else
  779. time_stamps.user_usec = time_stamps.sys_usec = 0;
  780. #endif
  781. return time_stamps;
  782. }
  783. static int64_t getmaxrss(void)
  784. {
  785. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  786. struct rusage rusage;
  787. getrusage(RUSAGE_SELF, &rusage);
  788. return (int64_t)rusage.ru_maxrss * 1024;
  789. #elif HAVE_GETPROCESSMEMORYINFO
  790. HANDLE proc;
  791. PROCESS_MEMORY_COUNTERS memcounters;
  792. proc = GetCurrentProcess();
  793. memcounters.cb = sizeof(memcounters);
  794. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  795. return memcounters.PeakPagefileUsage;
  796. #else
  797. return 0;
  798. #endif
  799. }
  800. int main(int argc, char **argv)
  801. {
  802. Scheduler *sch = NULL;
  803. int ret;
  804. BenchmarkTimeStamps ti;
  805. init_dynload();
  806. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  807. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  808. parse_loglevel(argc, argv, options);
  809. #if CONFIG_AVDEVICE
  810. avdevice_register_all();
  811. #endif
  812. avformat_network_init();
  813. show_banner(argc, argv, options);
  814. sch = sch_alloc();
  815. if (!sch) {
  816. ret = AVERROR(ENOMEM);
  817. goto finish;
  818. }
  819. /* parse options and open all input/output files */
  820. ret = ffmpeg_parse_options(argc, argv, sch);
  821. if (ret < 0)
  822. goto finish;
  823. if (nb_output_files <= 0 && nb_input_files == 0) {
  824. show_usage();
  825. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  826. ret = 1;
  827. goto finish;
  828. }
  829. if (nb_output_files <= 0) {
  830. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  831. ret = 1;
  832. goto finish;
  833. }
  834. current_time = ti = get_benchmark_time_stamps();
  835. ret = transcode(sch);
  836. if (ret >= 0 && do_benchmark) {
  837. int64_t utime, stime, rtime;
  838. current_time = get_benchmark_time_stamps();
  839. utime = current_time.user_usec - ti.user_usec;
  840. stime = current_time.sys_usec - ti.sys_usec;
  841. rtime = current_time.real_usec - ti.real_usec;
  842. av_log(NULL, AV_LOG_INFO,
  843. "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
  844. utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
  845. }
  846. ret = received_nb_signals ? 255 :
  847. (ret == FFMPEG_ERROR_RATE_EXCEEDED) ? 69 : ret;
  848. finish:
  849. if (ret == AVERROR_EXIT)
  850. ret = 0;
  851. ffmpeg_cleanup(ret);
  852. sch_free(&sch);
  853. return ret;
  854. }