ffmpeg.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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. int maxrss = getmaxrss() / 1024;
  267. av_log(NULL, AV_LOG_INFO, "bench: maxrss=%iKiB\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. void update_benchmark(const char *fmt, ...)
  394. {
  395. if (do_benchmark_all) {
  396. BenchmarkTimeStamps t = get_benchmark_time_stamps();
  397. va_list va;
  398. char buf[1024];
  399. if (fmt) {
  400. va_start(va, fmt);
  401. vsnprintf(buf, sizeof(buf), fmt, va);
  402. va_end(va);
  403. av_log(NULL, AV_LOG_INFO,
  404. "bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
  405. t.user_usec - current_time.user_usec,
  406. t.sys_usec - current_time.sys_usec,
  407. t.real_usec - current_time.real_usec, buf);
  408. }
  409. current_time = t;
  410. }
  411. }
  412. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time, int64_t pts)
  413. {
  414. AVBPrint buf, buf_script;
  415. int64_t total_size = of_filesize(output_files[0]);
  416. int vid;
  417. double bitrate;
  418. double speed;
  419. static int64_t last_time = -1;
  420. static int first_report = 1;
  421. uint64_t nb_frames_dup = 0, nb_frames_drop = 0;
  422. int mins, secs, us;
  423. int64_t hours;
  424. const char *hours_sign;
  425. int ret;
  426. float t;
  427. if (!print_stats && !is_last_report && !progress_avio)
  428. return;
  429. if (!is_last_report) {
  430. if (last_time == -1) {
  431. last_time = cur_time;
  432. }
  433. if (((cur_time - last_time) < stats_period && !first_report) ||
  434. (first_report && atomic_load(&nb_output_dumped) < nb_output_files))
  435. return;
  436. last_time = cur_time;
  437. }
  438. t = (cur_time-timer_start) / 1000000.0;
  439. vid = 0;
  440. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
  441. av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
  442. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  443. const float q = ost->enc ? atomic_load(&ost->quality) / (float) FF_QP2LAMBDA : -1;
  444. if (vid && ost->type == AVMEDIA_TYPE_VIDEO) {
  445. av_bprintf(&buf, "q=%2.1f ", q);
  446. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  447. ost->file->index, ost->index, q);
  448. }
  449. if (!vid && ost->type == AVMEDIA_TYPE_VIDEO && ost->filter) {
  450. float fps;
  451. uint64_t frame_number = atomic_load(&ost->packets_written);
  452. fps = t > 1 ? frame_number / t : 0;
  453. av_bprintf(&buf, "frame=%5"PRId64" fps=%3.*f q=%3.1f ",
  454. frame_number, fps < 9.95, fps, q);
  455. av_bprintf(&buf_script, "frame=%"PRId64"\n", frame_number);
  456. av_bprintf(&buf_script, "fps=%.2f\n", fps);
  457. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  458. ost->file->index, ost->index, q);
  459. if (is_last_report)
  460. av_bprintf(&buf, "L");
  461. nb_frames_dup = atomic_load(&ost->filter->nb_frames_dup);
  462. nb_frames_drop = atomic_load(&ost->filter->nb_frames_drop);
  463. vid = 1;
  464. }
  465. }
  466. if (copy_ts) {
  467. if (copy_ts_first_pts == AV_NOPTS_VALUE && pts > 1)
  468. copy_ts_first_pts = pts;
  469. if (copy_ts_first_pts != AV_NOPTS_VALUE)
  470. pts -= copy_ts_first_pts;
  471. }
  472. us = FFABS64U(pts) % AV_TIME_BASE;
  473. secs = FFABS64U(pts) / AV_TIME_BASE % 60;
  474. mins = FFABS64U(pts) / AV_TIME_BASE / 60 % 60;
  475. hours = FFABS64U(pts) / AV_TIME_BASE / 3600;
  476. hours_sign = (pts < 0) ? "-" : "";
  477. bitrate = pts != AV_NOPTS_VALUE && pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  478. speed = pts != AV_NOPTS_VALUE && t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
  479. if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
  480. else av_bprintf(&buf, "size=%8.0fKiB time=", total_size / 1024.0);
  481. if (pts == AV_NOPTS_VALUE) {
  482. av_bprintf(&buf, "N/A ");
  483. } else {
  484. av_bprintf(&buf, "%s%02"PRId64":%02d:%02d.%02d ",
  485. hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
  486. }
  487. if (bitrate < 0) {
  488. av_bprintf(&buf, "bitrate=N/A");
  489. av_bprintf(&buf_script, "bitrate=N/A\n");
  490. }else{
  491. av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
  492. av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
  493. }
  494. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  495. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  496. if (pts == AV_NOPTS_VALUE) {
  497. av_bprintf(&buf_script, "out_time_us=N/A\n");
  498. av_bprintf(&buf_script, "out_time_ms=N/A\n");
  499. av_bprintf(&buf_script, "out_time=N/A\n");
  500. } else {
  501. av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
  502. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  503. av_bprintf(&buf_script, "out_time=%s%02"PRId64":%02d:%02d.%06d\n",
  504. hours_sign, hours, mins, secs, us);
  505. }
  506. if (nb_frames_dup || nb_frames_drop)
  507. av_bprintf(&buf, " dup=%"PRId64" drop=%"PRId64, nb_frames_dup, nb_frames_drop);
  508. av_bprintf(&buf_script, "dup_frames=%"PRId64"\n", nb_frames_dup);
  509. av_bprintf(&buf_script, "drop_frames=%"PRId64"\n", nb_frames_drop);
  510. if (speed < 0) {
  511. av_bprintf(&buf, " speed=N/A");
  512. av_bprintf(&buf_script, "speed=N/A\n");
  513. } else {
  514. av_bprintf(&buf, " speed=%4.3gx", speed);
  515. av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
  516. }
  517. if (print_stats || is_last_report) {
  518. const char end = is_last_report ? '\n' : '\r';
  519. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  520. fprintf(stderr, "%s %c", buf.str, end);
  521. } else
  522. av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
  523. fflush(stderr);
  524. }
  525. av_bprint_finalize(&buf, NULL);
  526. if (progress_avio) {
  527. av_bprintf(&buf_script, "progress=%s\n",
  528. is_last_report ? "end" : "continue");
  529. avio_write(progress_avio, buf_script.str,
  530. FFMIN(buf_script.len, buf_script.size - 1));
  531. avio_flush(progress_avio);
  532. av_bprint_finalize(&buf_script, NULL);
  533. if (is_last_report) {
  534. if ((ret = avio_closep(&progress_avio)) < 0)
  535. av_log(NULL, AV_LOG_ERROR,
  536. "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
  537. }
  538. }
  539. first_report = 0;
  540. }
  541. static void print_stream_maps(void)
  542. {
  543. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  544. for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
  545. for (int j = 0; j < ist->nb_filters; j++) {
  546. if (!filtergraph_is_simple(ist->filters[j]->graph)) {
  547. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  548. ist->file->index, ist->index, ist->dec ? ist->dec->name : "?",
  549. ist->filters[j]->name);
  550. if (nb_filtergraphs > 1)
  551. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  552. av_log(NULL, AV_LOG_INFO, "\n");
  553. }
  554. }
  555. }
  556. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  557. if (ost->attachment_filename) {
  558. /* an attached file */
  559. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  560. ost->attachment_filename, ost->file->index, ost->index);
  561. continue;
  562. }
  563. if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
  564. /* output from a complex graph */
  565. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  566. if (nb_filtergraphs > 1)
  567. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  568. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file->index,
  569. ost->index, ost->enc_ctx->codec->name);
  570. continue;
  571. }
  572. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  573. ost->ist->file->index,
  574. ost->ist->index,
  575. ost->file->index,
  576. ost->index);
  577. if (ost->enc_ctx) {
  578. const AVCodec *in_codec = ost->ist->dec;
  579. const AVCodec *out_codec = ost->enc_ctx->codec;
  580. const char *decoder_name = "?";
  581. const char *in_codec_name = "?";
  582. const char *encoder_name = "?";
  583. const char *out_codec_name = "?";
  584. const AVCodecDescriptor *desc;
  585. if (in_codec) {
  586. decoder_name = in_codec->name;
  587. desc = avcodec_descriptor_get(in_codec->id);
  588. if (desc)
  589. in_codec_name = desc->name;
  590. if (!strcmp(decoder_name, in_codec_name))
  591. decoder_name = "native";
  592. }
  593. if (out_codec) {
  594. encoder_name = out_codec->name;
  595. desc = avcodec_descriptor_get(out_codec->id);
  596. if (desc)
  597. out_codec_name = desc->name;
  598. if (!strcmp(encoder_name, out_codec_name))
  599. encoder_name = "native";
  600. }
  601. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  602. in_codec_name, decoder_name,
  603. out_codec_name, encoder_name);
  604. } else
  605. av_log(NULL, AV_LOG_INFO, " (copy)");
  606. av_log(NULL, AV_LOG_INFO, "\n");
  607. }
  608. }
  609. static void set_tty_echo(int on)
  610. {
  611. #if HAVE_TERMIOS_H
  612. struct termios tty;
  613. if (tcgetattr(0, &tty) == 0) {
  614. if (on) tty.c_lflag |= ECHO;
  615. else tty.c_lflag &= ~ECHO;
  616. tcsetattr(0, TCSANOW, &tty);
  617. }
  618. #endif
  619. }
  620. static int check_keyboard_interaction(int64_t cur_time)
  621. {
  622. int i, key;
  623. static int64_t last_time;
  624. if (received_nb_signals)
  625. return AVERROR_EXIT;
  626. /* read_key() returns 0 on EOF */
  627. if (cur_time - last_time >= 100000) {
  628. key = read_key();
  629. last_time = cur_time;
  630. }else
  631. key = -1;
  632. if (key == 'q') {
  633. av_log(NULL, AV_LOG_INFO, "\n\n[q] command received. Exiting.\n\n");
  634. return AVERROR_EXIT;
  635. }
  636. if (key == '+') av_log_set_level(av_log_get_level()+10);
  637. if (key == '-') av_log_set_level(av_log_get_level()-10);
  638. if (key == 'c' || key == 'C'){
  639. char buf[4096], target[64], command[256], arg[256] = {0};
  640. double time;
  641. int k, n = 0;
  642. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  643. i = 0;
  644. set_tty_echo(1);
  645. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  646. if (k > 0)
  647. buf[i++] = k;
  648. buf[i] = 0;
  649. set_tty_echo(0);
  650. fprintf(stderr, "\n");
  651. if (k > 0 &&
  652. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  653. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  654. target, time, command, arg);
  655. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  656. if (ost->fg_simple)
  657. fg_send_command(ost->fg_simple, time, target, command, arg,
  658. key == 'C');
  659. }
  660. for (i = 0; i < nb_filtergraphs; i++)
  661. fg_send_command(filtergraphs[i], time, target, command, arg,
  662. key == 'C');
  663. } else {
  664. av_log(NULL, AV_LOG_ERROR,
  665. "Parse error, at least 3 arguments were expected, "
  666. "only %d given in string '%s'\n", n, buf);
  667. }
  668. }
  669. if (key == '?'){
  670. fprintf(stderr, "key function\n"
  671. "? show this help\n"
  672. "+ increase verbosity\n"
  673. "- decrease verbosity\n"
  674. "c Send command to first matching filter supporting it\n"
  675. "C Send/Queue command to all matching filters\n"
  676. "h dump packets/hex press to cycle through the 3 states\n"
  677. "q quit\n"
  678. "s Show QP histogram\n"
  679. );
  680. }
  681. return 0;
  682. }
  683. /*
  684. * The following code is the main loop of the file converter
  685. */
  686. static int transcode(Scheduler *sch)
  687. {
  688. int ret = 0;
  689. int64_t timer_start, transcode_ts = 0;
  690. print_stream_maps();
  691. atomic_store(&transcode_init_done, 1);
  692. ret = sch_start(sch);
  693. if (ret < 0)
  694. return ret;
  695. if (stdin_interaction) {
  696. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  697. }
  698. timer_start = av_gettime_relative();
  699. while (!sch_wait(sch, stats_period, &transcode_ts)) {
  700. int64_t cur_time= av_gettime_relative();
  701. /* if 'q' pressed, exits */
  702. if (stdin_interaction)
  703. if (check_keyboard_interaction(cur_time) < 0)
  704. break;
  705. /* dump report by using the output first video and audio streams */
  706. print_report(0, timer_start, cur_time, transcode_ts);
  707. }
  708. ret = sch_stop(sch, &transcode_ts);
  709. /* write the trailer if needed */
  710. for (int i = 0; i < nb_output_files; i++) {
  711. int err = of_write_trailer(output_files[i]);
  712. ret = err_merge(ret, err);
  713. }
  714. term_exit();
  715. /* dump report by using the first video and audio streams */
  716. print_report(1, timer_start, av_gettime_relative(), transcode_ts);
  717. return ret;
  718. }
  719. static BenchmarkTimeStamps get_benchmark_time_stamps(void)
  720. {
  721. BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
  722. #if HAVE_GETRUSAGE
  723. struct rusage rusage;
  724. getrusage(RUSAGE_SELF, &rusage);
  725. time_stamps.user_usec =
  726. (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  727. time_stamps.sys_usec =
  728. (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
  729. #elif HAVE_GETPROCESSTIMES
  730. HANDLE proc;
  731. FILETIME c, e, k, u;
  732. proc = GetCurrentProcess();
  733. GetProcessTimes(proc, &c, &e, &k, &u);
  734. time_stamps.user_usec =
  735. ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  736. time_stamps.sys_usec =
  737. ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
  738. #else
  739. time_stamps.user_usec = time_stamps.sys_usec = 0;
  740. #endif
  741. return time_stamps;
  742. }
  743. static int64_t getmaxrss(void)
  744. {
  745. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  746. struct rusage rusage;
  747. getrusage(RUSAGE_SELF, &rusage);
  748. return (int64_t)rusage.ru_maxrss * 1024;
  749. #elif HAVE_GETPROCESSMEMORYINFO
  750. HANDLE proc;
  751. PROCESS_MEMORY_COUNTERS memcounters;
  752. proc = GetCurrentProcess();
  753. memcounters.cb = sizeof(memcounters);
  754. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  755. return memcounters.PeakPagefileUsage;
  756. #else
  757. return 0;
  758. #endif
  759. }
  760. int main(int argc, char **argv)
  761. {
  762. Scheduler *sch = NULL;
  763. int ret;
  764. BenchmarkTimeStamps ti;
  765. init_dynload();
  766. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  767. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  768. parse_loglevel(argc, argv, options);
  769. #if CONFIG_AVDEVICE
  770. avdevice_register_all();
  771. #endif
  772. avformat_network_init();
  773. show_banner(argc, argv, options);
  774. sch = sch_alloc();
  775. if (!sch) {
  776. ret = AVERROR(ENOMEM);
  777. goto finish;
  778. }
  779. /* parse options and open all input/output files */
  780. ret = ffmpeg_parse_options(argc, argv, sch);
  781. if (ret < 0)
  782. goto finish;
  783. if (nb_output_files <= 0 && nb_input_files == 0) {
  784. show_usage();
  785. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  786. ret = 1;
  787. goto finish;
  788. }
  789. if (nb_output_files <= 0) {
  790. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  791. ret = 1;
  792. goto finish;
  793. }
  794. current_time = ti = get_benchmark_time_stamps();
  795. ret = transcode(sch);
  796. if (ret >= 0 && do_benchmark) {
  797. int64_t utime, stime, rtime;
  798. current_time = get_benchmark_time_stamps();
  799. utime = current_time.user_usec - ti.user_usec;
  800. stime = current_time.sys_usec - ti.sys_usec;
  801. rtime = current_time.real_usec - ti.real_usec;
  802. av_log(NULL, AV_LOG_INFO,
  803. "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
  804. utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
  805. }
  806. ret = received_nb_signals ? 255 :
  807. (ret == FFMPEG_ERROR_RATE_EXCEEDED) ? 69 : ret;
  808. finish:
  809. if (ret == AVERROR_EXIT)
  810. ret = 0;
  811. ffmpeg_cleanup(ret);
  812. sch_free(&sch);
  813. return ret;
  814. }