ffmpeg.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  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/avassert.h"
  64. #include "libavutil/avstring.h"
  65. #include "libavutil/bprint.h"
  66. #include "libavutil/channel_layout.h"
  67. #include "libavutil/dict.h"
  68. #include "libavutil/display.h"
  69. #include "libavutil/fifo.h"
  70. #include "libavutil/hwcontext.h"
  71. #include "libavutil/imgutils.h"
  72. #include "libavutil/intreadwrite.h"
  73. #include "libavutil/libm.h"
  74. #include "libavutil/mathematics.h"
  75. #include "libavutil/opt.h"
  76. #include "libavutil/parseutils.h"
  77. #include "libavutil/pixdesc.h"
  78. #include "libavutil/samplefmt.h"
  79. #include "libavutil/thread.h"
  80. #include "libavutil/threadmessage.h"
  81. #include "libavutil/time.h"
  82. #include "libavutil/timestamp.h"
  83. #include "libavcodec/version.h"
  84. #include "libavformat/avformat.h"
  85. #include "libavdevice/avdevice.h"
  86. #include "libswresample/swresample.h"
  87. #include "cmdutils.h"
  88. #include "ffmpeg.h"
  89. #include "sync_queue.h"
  90. const char program_name[] = "ffmpeg";
  91. const int program_birth_year = 2000;
  92. FILE *vstats_file;
  93. typedef struct BenchmarkTimeStamps {
  94. int64_t real_usec;
  95. int64_t user_usec;
  96. int64_t sys_usec;
  97. } BenchmarkTimeStamps;
  98. static BenchmarkTimeStamps get_benchmark_time_stamps(void);
  99. static int64_t getmaxrss(void);
  100. unsigned nb_output_dumped = 0;
  101. static BenchmarkTimeStamps current_time;
  102. AVIOContext *progress_avio = NULL;
  103. InputFile **input_files = NULL;
  104. int nb_input_files = 0;
  105. OutputFile **output_files = NULL;
  106. int nb_output_files = 0;
  107. FilterGraph **filtergraphs;
  108. int nb_filtergraphs;
  109. #if HAVE_TERMIOS_H
  110. /* init terminal so that we can grab keys */
  111. static struct termios oldtty;
  112. static int restore_tty;
  113. #endif
  114. /* sub2video hack:
  115. Convert subtitles to video with alpha to insert them in filter graphs.
  116. This is a temporary solution until libavfilter gets real subtitles support.
  117. */
  118. static void sub2video_heartbeat(InputFile *infile, int64_t pts, AVRational tb)
  119. {
  120. /* When a frame is read from a file, examine all sub2video streams in
  121. the same file and send the sub2video frame again. Otherwise, decoded
  122. video frames could be accumulating in the filter graph while a filter
  123. (possibly overlay) is desperately waiting for a subtitle frame. */
  124. for (int i = 0; i < infile->nb_streams; i++) {
  125. InputStream *ist = infile->streams[i];
  126. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE)
  127. continue;
  128. for (int j = 0; j < ist->nb_filters; j++)
  129. ifilter_sub2video_heartbeat(ist->filters[j], pts, tb);
  130. }
  131. }
  132. /* end of sub2video hack */
  133. static void term_exit_sigsafe(void)
  134. {
  135. #if HAVE_TERMIOS_H
  136. if(restore_tty)
  137. tcsetattr (0, TCSANOW, &oldtty);
  138. #endif
  139. }
  140. void term_exit(void)
  141. {
  142. av_log(NULL, AV_LOG_QUIET, "%s", "");
  143. term_exit_sigsafe();
  144. }
  145. static volatile int received_sigterm = 0;
  146. static volatile int received_nb_signals = 0;
  147. static atomic_int transcode_init_done = ATOMIC_VAR_INIT(0);
  148. static volatile int ffmpeg_exited = 0;
  149. static int64_t copy_ts_first_pts = AV_NOPTS_VALUE;
  150. static void
  151. sigterm_handler(int sig)
  152. {
  153. int ret;
  154. received_sigterm = sig;
  155. received_nb_signals++;
  156. term_exit_sigsafe();
  157. if(received_nb_signals > 3) {
  158. ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
  159. strlen("Received > 3 system signals, hard exiting\n"));
  160. if (ret < 0) { /* Do nothing */ };
  161. exit(123);
  162. }
  163. }
  164. #if HAVE_SETCONSOLECTRLHANDLER
  165. static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
  166. {
  167. av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
  168. switch (fdwCtrlType)
  169. {
  170. case CTRL_C_EVENT:
  171. case CTRL_BREAK_EVENT:
  172. sigterm_handler(SIGINT);
  173. return TRUE;
  174. case CTRL_CLOSE_EVENT:
  175. case CTRL_LOGOFF_EVENT:
  176. case CTRL_SHUTDOWN_EVENT:
  177. sigterm_handler(SIGTERM);
  178. /* Basically, with these 3 events, when we return from this method the
  179. process is hard terminated, so stall as long as we need to
  180. to try and let the main thread(s) clean up and gracefully terminate
  181. (we have at most 5 seconds, but should be done far before that). */
  182. while (!ffmpeg_exited) {
  183. Sleep(0);
  184. }
  185. return TRUE;
  186. default:
  187. av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
  188. return FALSE;
  189. }
  190. }
  191. #endif
  192. #ifdef __linux__
  193. #define SIGNAL(sig, func) \
  194. do { \
  195. action.sa_handler = func; \
  196. sigaction(sig, &action, NULL); \
  197. } while (0)
  198. #else
  199. #define SIGNAL(sig, func) \
  200. signal(sig, func)
  201. #endif
  202. void term_init(void)
  203. {
  204. #if defined __linux__
  205. struct sigaction action = {0};
  206. action.sa_handler = sigterm_handler;
  207. /* block other interrupts while processing this one */
  208. sigfillset(&action.sa_mask);
  209. /* restart interruptible functions (i.e. don't fail with EINTR) */
  210. action.sa_flags = SA_RESTART;
  211. #endif
  212. #if HAVE_TERMIOS_H
  213. if (stdin_interaction) {
  214. struct termios tty;
  215. if (tcgetattr (0, &tty) == 0) {
  216. oldtty = tty;
  217. restore_tty = 1;
  218. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  219. |INLCR|IGNCR|ICRNL|IXON);
  220. tty.c_oflag |= OPOST;
  221. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  222. tty.c_cflag &= ~(CSIZE|PARENB);
  223. tty.c_cflag |= CS8;
  224. tty.c_cc[VMIN] = 1;
  225. tty.c_cc[VTIME] = 0;
  226. tcsetattr (0, TCSANOW, &tty);
  227. }
  228. SIGNAL(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  229. }
  230. #endif
  231. SIGNAL(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  232. SIGNAL(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  233. #ifdef SIGXCPU
  234. SIGNAL(SIGXCPU, sigterm_handler);
  235. #endif
  236. #ifdef SIGPIPE
  237. signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
  238. #endif
  239. #if HAVE_SETCONSOLECTRLHANDLER
  240. SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
  241. #endif
  242. }
  243. /* read a key without blocking */
  244. static int read_key(void)
  245. {
  246. unsigned char ch;
  247. #if HAVE_TERMIOS_H
  248. int n = 1;
  249. struct timeval tv;
  250. fd_set rfds;
  251. FD_ZERO(&rfds);
  252. FD_SET(0, &rfds);
  253. tv.tv_sec = 0;
  254. tv.tv_usec = 0;
  255. n = select(1, &rfds, NULL, NULL, &tv);
  256. if (n > 0) {
  257. n = read(0, &ch, 1);
  258. if (n == 1)
  259. return ch;
  260. return n;
  261. }
  262. #elif HAVE_KBHIT
  263. # if HAVE_PEEKNAMEDPIPE && HAVE_GETSTDHANDLE
  264. static int is_pipe;
  265. static HANDLE input_handle;
  266. DWORD dw, nchars;
  267. if(!input_handle){
  268. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  269. is_pipe = !GetConsoleMode(input_handle, &dw);
  270. }
  271. if (is_pipe) {
  272. /* When running under a GUI, you will end here. */
  273. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
  274. // input pipe may have been closed by the program that ran ffmpeg
  275. return -1;
  276. }
  277. //Read it
  278. if(nchars != 0) {
  279. read(0, &ch, 1);
  280. return ch;
  281. }else{
  282. return -1;
  283. }
  284. }
  285. # endif
  286. if(kbhit())
  287. return(getch());
  288. #endif
  289. return -1;
  290. }
  291. static int decode_interrupt_cb(void *ctx)
  292. {
  293. return received_nb_signals > atomic_load(&transcode_init_done);
  294. }
  295. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  296. static void ffmpeg_cleanup(int ret)
  297. {
  298. int i;
  299. if (do_benchmark) {
  300. int maxrss = getmaxrss() / 1024;
  301. av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
  302. }
  303. for (i = 0; i < nb_filtergraphs; i++)
  304. fg_free(&filtergraphs[i]);
  305. av_freep(&filtergraphs);
  306. for (i = 0; i < nb_output_files; i++)
  307. of_free(&output_files[i]);
  308. for (i = 0; i < nb_input_files; i++)
  309. ifile_close(&input_files[i]);
  310. if (vstats_file) {
  311. if (fclose(vstats_file))
  312. av_log(NULL, AV_LOG_ERROR,
  313. "Error closing vstats file, loss of information possible: %s\n",
  314. av_err2str(AVERROR(errno)));
  315. }
  316. av_freep(&vstats_filename);
  317. of_enc_stats_close();
  318. hw_device_free_all();
  319. av_freep(&filter_nbthreads);
  320. av_freep(&input_files);
  321. av_freep(&output_files);
  322. uninit_opts();
  323. avformat_network_deinit();
  324. if (received_sigterm) {
  325. av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
  326. (int) received_sigterm);
  327. } else if (ret && atomic_load(&transcode_init_done)) {
  328. av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
  329. }
  330. term_exit();
  331. ffmpeg_exited = 1;
  332. }
  333. OutputStream *ost_iter(OutputStream *prev)
  334. {
  335. int of_idx = prev ? prev->file_index : 0;
  336. int ost_idx = prev ? prev->index + 1 : 0;
  337. for (; of_idx < nb_output_files; of_idx++) {
  338. OutputFile *of = output_files[of_idx];
  339. if (ost_idx < of->nb_streams)
  340. return of->streams[ost_idx];
  341. ost_idx = 0;
  342. }
  343. return NULL;
  344. }
  345. InputStream *ist_iter(InputStream *prev)
  346. {
  347. int if_idx = prev ? prev->file_index : 0;
  348. int ist_idx = prev ? prev->index + 1 : 0;
  349. for (; if_idx < nb_input_files; if_idx++) {
  350. InputFile *f = input_files[if_idx];
  351. if (ist_idx < f->nb_streams)
  352. return f->streams[ist_idx];
  353. ist_idx = 0;
  354. }
  355. return NULL;
  356. }
  357. FrameData *frame_data(AVFrame *frame)
  358. {
  359. if (!frame->opaque_ref) {
  360. FrameData *fd;
  361. frame->opaque_ref = av_buffer_allocz(sizeof(*fd));
  362. if (!frame->opaque_ref)
  363. return NULL;
  364. fd = (FrameData*)frame->opaque_ref->data;
  365. fd->dec.frame_num = UINT64_MAX;
  366. fd->dec.pts = AV_NOPTS_VALUE;
  367. }
  368. return (FrameData*)frame->opaque_ref->data;
  369. }
  370. void remove_avoptions(AVDictionary **a, AVDictionary *b)
  371. {
  372. const AVDictionaryEntry *t = NULL;
  373. while ((t = av_dict_iterate(b, t))) {
  374. av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
  375. }
  376. }
  377. int check_avoptions(AVDictionary *m)
  378. {
  379. const AVDictionaryEntry *t;
  380. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  381. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  382. return AVERROR_OPTION_NOT_FOUND;
  383. }
  384. return 0;
  385. }
  386. void update_benchmark(const char *fmt, ...)
  387. {
  388. if (do_benchmark_all) {
  389. BenchmarkTimeStamps t = get_benchmark_time_stamps();
  390. va_list va;
  391. char buf[1024];
  392. if (fmt) {
  393. va_start(va, fmt);
  394. vsnprintf(buf, sizeof(buf), fmt, va);
  395. va_end(va);
  396. av_log(NULL, AV_LOG_INFO,
  397. "bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
  398. t.user_usec - current_time.user_usec,
  399. t.sys_usec - current_time.sys_usec,
  400. t.real_usec - current_time.real_usec, buf);
  401. }
  402. current_time = t;
  403. }
  404. }
  405. void close_output_stream(OutputStream *ost)
  406. {
  407. OutputFile *of = output_files[ost->file_index];
  408. ost->finished |= ENCODER_FINISHED;
  409. if (ost->sq_idx_encode >= 0)
  410. sq_send(of->sq_encode, ost->sq_idx_encode, SQFRAME(NULL));
  411. }
  412. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  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. int64_t pts = AV_NOPTS_VALUE;
  420. static int64_t last_time = -1;
  421. static int first_report = 1;
  422. uint64_t nb_frames_dup = 0, nb_frames_drop = 0;
  423. int mins, secs, us;
  424. int64_t hours;
  425. const char *hours_sign;
  426. int ret;
  427. float t;
  428. if (!print_stats && !is_last_report && !progress_avio)
  429. return;
  430. if (!is_last_report) {
  431. if (last_time == -1) {
  432. last_time = cur_time;
  433. }
  434. if (((cur_time - last_time) < stats_period && !first_report) ||
  435. (first_report && nb_output_dumped < nb_output_files))
  436. return;
  437. last_time = cur_time;
  438. }
  439. t = (cur_time-timer_start) / 1000000.0;
  440. vid = 0;
  441. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
  442. av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
  443. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  444. const float q = ost->enc ? ost->quality / (float) FF_QP2LAMBDA : -1;
  445. if (vid && ost->type == AVMEDIA_TYPE_VIDEO) {
  446. av_bprintf(&buf, "q=%2.1f ", q);
  447. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  448. ost->file_index, ost->index, q);
  449. }
  450. if (!vid && ost->type == AVMEDIA_TYPE_VIDEO && ost->filter) {
  451. float fps;
  452. uint64_t frame_number = atomic_load(&ost->packets_written);
  453. fps = t > 1 ? frame_number / t : 0;
  454. av_bprintf(&buf, "frame=%5"PRId64" fps=%3.*f q=%3.1f ",
  455. frame_number, fps < 9.95, fps, q);
  456. av_bprintf(&buf_script, "frame=%"PRId64"\n", frame_number);
  457. av_bprintf(&buf_script, "fps=%.2f\n", fps);
  458. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  459. ost->file_index, ost->index, q);
  460. if (is_last_report)
  461. av_bprintf(&buf, "L");
  462. nb_frames_dup = ost->filter->nb_frames_dup;
  463. nb_frames_drop = ost->filter->nb_frames_drop;
  464. vid = 1;
  465. }
  466. /* compute min output value */
  467. if (ost->last_mux_dts != AV_NOPTS_VALUE) {
  468. if (pts == AV_NOPTS_VALUE || ost->last_mux_dts > pts)
  469. pts = ost->last_mux_dts;
  470. if (copy_ts) {
  471. if (copy_ts_first_pts == AV_NOPTS_VALUE && pts > 1)
  472. copy_ts_first_pts = pts;
  473. if (copy_ts_first_pts != AV_NOPTS_VALUE)
  474. pts -= copy_ts_first_pts;
  475. }
  476. }
  477. }
  478. us = FFABS64U(pts) % AV_TIME_BASE;
  479. secs = FFABS64U(pts) / AV_TIME_BASE % 60;
  480. mins = FFABS64U(pts) / AV_TIME_BASE / 60 % 60;
  481. hours = FFABS64U(pts) / AV_TIME_BASE / 3600;
  482. hours_sign = (pts < 0) ? "-" : "";
  483. bitrate = pts != AV_NOPTS_VALUE && pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
  484. speed = pts != AV_NOPTS_VALUE && t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
  485. if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
  486. else av_bprintf(&buf, "size=%8.0fkB time=", total_size / 1024.0);
  487. if (pts == AV_NOPTS_VALUE) {
  488. av_bprintf(&buf, "N/A ");
  489. } else {
  490. av_bprintf(&buf, "%s%02"PRId64":%02d:%02d.%02d ",
  491. hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
  492. }
  493. if (bitrate < 0) {
  494. av_bprintf(&buf, "bitrate=N/A");
  495. av_bprintf(&buf_script, "bitrate=N/A\n");
  496. }else{
  497. av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
  498. av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
  499. }
  500. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  501. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  502. if (pts == AV_NOPTS_VALUE) {
  503. av_bprintf(&buf_script, "out_time_us=N/A\n");
  504. av_bprintf(&buf_script, "out_time_ms=N/A\n");
  505. av_bprintf(&buf_script, "out_time=N/A\n");
  506. } else {
  507. av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
  508. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  509. av_bprintf(&buf_script, "out_time=%s%02"PRId64":%02d:%02d.%06d\n",
  510. hours_sign, hours, mins, secs, us);
  511. }
  512. if (nb_frames_dup || nb_frames_drop)
  513. av_bprintf(&buf, " dup=%"PRId64" drop=%"PRId64, nb_frames_dup, nb_frames_drop);
  514. av_bprintf(&buf_script, "dup_frames=%"PRId64"\n", nb_frames_dup);
  515. av_bprintf(&buf_script, "drop_frames=%"PRId64"\n", nb_frames_drop);
  516. if (speed < 0) {
  517. av_bprintf(&buf, " speed=N/A");
  518. av_bprintf(&buf_script, "speed=N/A\n");
  519. } else {
  520. av_bprintf(&buf, " speed=%4.3gx", speed);
  521. av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
  522. }
  523. if (print_stats || is_last_report) {
  524. const char end = is_last_report ? '\n' : '\r';
  525. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  526. fprintf(stderr, "%s %c", buf.str, end);
  527. } else
  528. av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
  529. fflush(stderr);
  530. }
  531. av_bprint_finalize(&buf, NULL);
  532. if (progress_avio) {
  533. av_bprintf(&buf_script, "progress=%s\n",
  534. is_last_report ? "end" : "continue");
  535. avio_write(progress_avio, buf_script.str,
  536. FFMIN(buf_script.len, buf_script.size - 1));
  537. avio_flush(progress_avio);
  538. av_bprint_finalize(&buf_script, NULL);
  539. if (is_last_report) {
  540. if ((ret = avio_closep(&progress_avio)) < 0)
  541. av_log(NULL, AV_LOG_ERROR,
  542. "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
  543. }
  544. }
  545. first_report = 0;
  546. }
  547. int copy_av_subtitle(AVSubtitle *dst, const AVSubtitle *src)
  548. {
  549. int ret = AVERROR_BUG;
  550. AVSubtitle tmp = {
  551. .format = src->format,
  552. .start_display_time = src->start_display_time,
  553. .end_display_time = src->end_display_time,
  554. .num_rects = 0,
  555. .rects = NULL,
  556. .pts = src->pts
  557. };
  558. if (!src->num_rects)
  559. goto success;
  560. if (!(tmp.rects = av_calloc(src->num_rects, sizeof(*tmp.rects))))
  561. return AVERROR(ENOMEM);
  562. for (int i = 0; i < src->num_rects; i++) {
  563. AVSubtitleRect *src_rect = src->rects[i];
  564. AVSubtitleRect *dst_rect;
  565. if (!(dst_rect = tmp.rects[i] = av_mallocz(sizeof(*tmp.rects[0])))) {
  566. ret = AVERROR(ENOMEM);
  567. goto cleanup;
  568. }
  569. tmp.num_rects++;
  570. dst_rect->type = src_rect->type;
  571. dst_rect->flags = src_rect->flags;
  572. dst_rect->x = src_rect->x;
  573. dst_rect->y = src_rect->y;
  574. dst_rect->w = src_rect->w;
  575. dst_rect->h = src_rect->h;
  576. dst_rect->nb_colors = src_rect->nb_colors;
  577. if (src_rect->text)
  578. if (!(dst_rect->text = av_strdup(src_rect->text))) {
  579. ret = AVERROR(ENOMEM);
  580. goto cleanup;
  581. }
  582. if (src_rect->ass)
  583. if (!(dst_rect->ass = av_strdup(src_rect->ass))) {
  584. ret = AVERROR(ENOMEM);
  585. goto cleanup;
  586. }
  587. for (int j = 0; j < 4; j++) {
  588. // SUBTITLE_BITMAP images are special in the sense that they
  589. // are like PAL8 images. first pointer to data, second to
  590. // palette. This makes the size calculation match this.
  591. size_t buf_size = src_rect->type == SUBTITLE_BITMAP && j == 1 ?
  592. AVPALETTE_SIZE :
  593. src_rect->h * src_rect->linesize[j];
  594. if (!src_rect->data[j])
  595. continue;
  596. if (!(dst_rect->data[j] = av_memdup(src_rect->data[j], buf_size))) {
  597. ret = AVERROR(ENOMEM);
  598. goto cleanup;
  599. }
  600. dst_rect->linesize[j] = src_rect->linesize[j];
  601. }
  602. }
  603. success:
  604. *dst = tmp;
  605. return 0;
  606. cleanup:
  607. avsubtitle_free(&tmp);
  608. return ret;
  609. }
  610. static void subtitle_free(void *opaque, uint8_t *data)
  611. {
  612. AVSubtitle *sub = (AVSubtitle*)data;
  613. avsubtitle_free(sub);
  614. av_free(sub);
  615. }
  616. int subtitle_wrap_frame(AVFrame *frame, AVSubtitle *subtitle, int copy)
  617. {
  618. AVBufferRef *buf;
  619. AVSubtitle *sub;
  620. int ret;
  621. if (copy) {
  622. sub = av_mallocz(sizeof(*sub));
  623. ret = sub ? copy_av_subtitle(sub, subtitle) : AVERROR(ENOMEM);
  624. if (ret < 0) {
  625. av_freep(&sub);
  626. return ret;
  627. }
  628. } else {
  629. sub = av_memdup(subtitle, sizeof(*subtitle));
  630. if (!sub)
  631. return AVERROR(ENOMEM);
  632. memset(subtitle, 0, sizeof(*subtitle));
  633. }
  634. buf = av_buffer_create((uint8_t*)sub, sizeof(*sub),
  635. subtitle_free, NULL, 0);
  636. if (!buf) {
  637. avsubtitle_free(sub);
  638. av_freep(&sub);
  639. return AVERROR(ENOMEM);
  640. }
  641. frame->buf[0] = buf;
  642. return 0;
  643. }
  644. int trigger_fix_sub_duration_heartbeat(OutputStream *ost, const AVPacket *pkt)
  645. {
  646. OutputFile *of = output_files[ost->file_index];
  647. int64_t signal_pts = av_rescale_q(pkt->pts, pkt->time_base,
  648. AV_TIME_BASE_Q);
  649. if (!ost->fix_sub_duration_heartbeat || !(pkt->flags & AV_PKT_FLAG_KEY))
  650. // we are only interested in heartbeats on streams configured, and
  651. // only on random access points.
  652. return 0;
  653. for (int i = 0; i < of->nb_streams; i++) {
  654. OutputStream *iter_ost = of->streams[i];
  655. InputStream *ist = iter_ost->ist;
  656. int ret = AVERROR_BUG;
  657. if (iter_ost == ost || !ist || !ist->decoding_needed ||
  658. ist->dec_ctx->codec_type != AVMEDIA_TYPE_SUBTITLE)
  659. // We wish to skip the stream that causes the heartbeat,
  660. // output streams without an input stream, streams not decoded
  661. // (as fix_sub_duration is only done for decoded subtitles) as
  662. // well as non-subtitle streams.
  663. continue;
  664. if ((ret = fix_sub_duration_heartbeat(ist, signal_pts)) < 0)
  665. return ret;
  666. }
  667. return 0;
  668. }
  669. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  670. static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
  671. {
  672. InputFile *f = input_files[ist->file_index];
  673. int64_t dts_est = AV_NOPTS_VALUE;
  674. int ret = 0;
  675. int eof_reached = 0;
  676. if (ist->decoding_needed) {
  677. ret = dec_packet(ist, pkt, no_eof);
  678. if (ret < 0 && ret != AVERROR_EOF)
  679. return ret;
  680. }
  681. if (ret == AVERROR_EOF || (!pkt && !ist->decoding_needed))
  682. eof_reached = 1;
  683. if (pkt && pkt->opaque_ref) {
  684. DemuxPktData *pd = (DemuxPktData*)pkt->opaque_ref->data;
  685. dts_est = pd->dts_est;
  686. }
  687. if (f->recording_time != INT64_MAX) {
  688. int64_t start_time = 0;
  689. if (copy_ts) {
  690. start_time += f->start_time != AV_NOPTS_VALUE ? f->start_time : 0;
  691. start_time += start_at_zero ? 0 : f->start_time_effective;
  692. }
  693. if (dts_est >= f->recording_time + start_time)
  694. pkt = NULL;
  695. }
  696. for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
  697. OutputStream *ost = ist->outputs[oidx];
  698. if (ost->enc || (!pkt && no_eof))
  699. continue;
  700. ret = of_streamcopy(ost, pkt, dts_est);
  701. if (ret < 0)
  702. return ret;
  703. }
  704. return !eof_reached;
  705. }
  706. static void print_stream_maps(void)
  707. {
  708. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  709. for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
  710. for (int j = 0; j < ist->nb_filters; j++) {
  711. if (!filtergraph_is_simple(ist->filters[j]->graph)) {
  712. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  713. ist->file_index, ist->index, ist->dec ? ist->dec->name : "?",
  714. ist->filters[j]->name);
  715. if (nb_filtergraphs > 1)
  716. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  717. av_log(NULL, AV_LOG_INFO, "\n");
  718. }
  719. }
  720. }
  721. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  722. if (ost->attachment_filename) {
  723. /* an attached file */
  724. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  725. ost->attachment_filename, ost->file_index, ost->index);
  726. continue;
  727. }
  728. if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
  729. /* output from a complex graph */
  730. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  731. if (nb_filtergraphs > 1)
  732. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  733. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  734. ost->index, ost->enc_ctx->codec->name);
  735. continue;
  736. }
  737. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  738. ost->ist->file_index,
  739. ost->ist->index,
  740. ost->file_index,
  741. ost->index);
  742. if (ost->enc_ctx) {
  743. const AVCodec *in_codec = ost->ist->dec;
  744. const AVCodec *out_codec = ost->enc_ctx->codec;
  745. const char *decoder_name = "?";
  746. const char *in_codec_name = "?";
  747. const char *encoder_name = "?";
  748. const char *out_codec_name = "?";
  749. const AVCodecDescriptor *desc;
  750. if (in_codec) {
  751. decoder_name = in_codec->name;
  752. desc = avcodec_descriptor_get(in_codec->id);
  753. if (desc)
  754. in_codec_name = desc->name;
  755. if (!strcmp(decoder_name, in_codec_name))
  756. decoder_name = "native";
  757. }
  758. if (out_codec) {
  759. encoder_name = out_codec->name;
  760. desc = avcodec_descriptor_get(out_codec->id);
  761. if (desc)
  762. out_codec_name = desc->name;
  763. if (!strcmp(encoder_name, out_codec_name))
  764. encoder_name = "native";
  765. }
  766. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  767. in_codec_name, decoder_name,
  768. out_codec_name, encoder_name);
  769. } else
  770. av_log(NULL, AV_LOG_INFO, " (copy)");
  771. av_log(NULL, AV_LOG_INFO, "\n");
  772. }
  773. }
  774. /**
  775. * Select the output stream to process.
  776. *
  777. * @retval 0 an output stream was selected
  778. * @retval AVERROR(EAGAIN) need to wait until more input is available
  779. * @retval AVERROR_EOF no more streams need output
  780. */
  781. static int choose_output(OutputStream **post)
  782. {
  783. int64_t opts_min = INT64_MAX;
  784. OutputStream *ost_min = NULL;
  785. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
  786. int64_t opts;
  787. if (ost->filter && ost->filter->last_pts != AV_NOPTS_VALUE) {
  788. opts = ost->filter->last_pts;
  789. } else {
  790. opts = ost->last_mux_dts == AV_NOPTS_VALUE ?
  791. INT64_MIN : ost->last_mux_dts;
  792. }
  793. if (!ost->initialized && !ost->finished) {
  794. ost_min = ost;
  795. break;
  796. }
  797. if (!ost->finished && opts < opts_min) {
  798. opts_min = opts;
  799. ost_min = ost;
  800. }
  801. }
  802. if (!ost_min)
  803. return AVERROR_EOF;
  804. *post = ost_min;
  805. return ost_min->unavailable ? AVERROR(EAGAIN) : 0;
  806. }
  807. static void set_tty_echo(int on)
  808. {
  809. #if HAVE_TERMIOS_H
  810. struct termios tty;
  811. if (tcgetattr(0, &tty) == 0) {
  812. if (on) tty.c_lflag |= ECHO;
  813. else tty.c_lflag &= ~ECHO;
  814. tcsetattr(0, TCSANOW, &tty);
  815. }
  816. #endif
  817. }
  818. static int check_keyboard_interaction(int64_t cur_time)
  819. {
  820. int i, key;
  821. static int64_t last_time;
  822. if (received_nb_signals)
  823. return AVERROR_EXIT;
  824. /* read_key() returns 0 on EOF */
  825. if (cur_time - last_time >= 100000) {
  826. key = read_key();
  827. last_time = cur_time;
  828. }else
  829. key = -1;
  830. if (key == 'q') {
  831. av_log(NULL, AV_LOG_INFO, "\n\n[q] command received. Exiting.\n\n");
  832. return AVERROR_EXIT;
  833. }
  834. if (key == '+') av_log_set_level(av_log_get_level()+10);
  835. if (key == '-') av_log_set_level(av_log_get_level()-10);
  836. if (key == 'c' || key == 'C'){
  837. char buf[4096], target[64], command[256], arg[256] = {0};
  838. double time;
  839. int k, n = 0;
  840. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  841. i = 0;
  842. set_tty_echo(1);
  843. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  844. if (k > 0)
  845. buf[i++] = k;
  846. buf[i] = 0;
  847. set_tty_echo(0);
  848. fprintf(stderr, "\n");
  849. if (k > 0 &&
  850. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  851. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  852. target, time, command, arg);
  853. for (i = 0; i < nb_filtergraphs; i++)
  854. fg_send_command(filtergraphs[i], time, target, command, arg,
  855. key == 'C');
  856. } else {
  857. av_log(NULL, AV_LOG_ERROR,
  858. "Parse error, at least 3 arguments were expected, "
  859. "only %d given in string '%s'\n", n, buf);
  860. }
  861. }
  862. if (key == '?'){
  863. fprintf(stderr, "key function\n"
  864. "? show this help\n"
  865. "+ increase verbosity\n"
  866. "- decrease verbosity\n"
  867. "c Send command to first matching filter supporting it\n"
  868. "C Send/Queue command to all matching filters\n"
  869. "h dump packets/hex press to cycle through the 3 states\n"
  870. "q quit\n"
  871. "s Show QP histogram\n"
  872. );
  873. }
  874. return 0;
  875. }
  876. static void reset_eagain(void)
  877. {
  878. int i;
  879. for (i = 0; i < nb_input_files; i++)
  880. input_files[i]->eagain = 0;
  881. for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost))
  882. ost->unavailable = 0;
  883. }
  884. static void decode_flush(InputFile *ifile)
  885. {
  886. for (int i = 0; i < ifile->nb_streams; i++) {
  887. InputStream *ist = ifile->streams[i];
  888. if (ist->discard || !ist->decoding_needed)
  889. continue;
  890. dec_packet(ist, NULL, 1);
  891. }
  892. }
  893. /*
  894. * Return
  895. * - 0 -- one packet was read and processed
  896. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  897. * this function should be called again
  898. * - AVERROR_EOF -- this function should not be called again
  899. */
  900. static int process_input(int file_index)
  901. {
  902. InputFile *ifile = input_files[file_index];
  903. InputStream *ist;
  904. AVPacket *pkt;
  905. int ret, i;
  906. ret = ifile_get_packet(ifile, &pkt);
  907. if (ret == AVERROR(EAGAIN)) {
  908. ifile->eagain = 1;
  909. return ret;
  910. }
  911. if (ret == 1) {
  912. /* the input file is looped: flush the decoders */
  913. decode_flush(ifile);
  914. return AVERROR(EAGAIN);
  915. }
  916. if (ret < 0) {
  917. if (ret != AVERROR_EOF) {
  918. av_log(ifile, AV_LOG_ERROR,
  919. "Error retrieving a packet from demuxer: %s\n", av_err2str(ret));
  920. if (exit_on_error)
  921. return ret;
  922. }
  923. for (i = 0; i < ifile->nb_streams; i++) {
  924. ist = ifile->streams[i];
  925. if (!ist->discard) {
  926. ret = process_input_packet(ist, NULL, 0);
  927. if (ret>0)
  928. return 0;
  929. else if (ret < 0)
  930. return ret;
  931. }
  932. /* mark all outputs that don't go through lavfi as finished */
  933. for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
  934. OutputStream *ost = ist->outputs[oidx];
  935. OutputFile *of = output_files[ost->file_index];
  936. ret = of_output_packet(of, ost, NULL);
  937. if (ret < 0)
  938. return ret;
  939. }
  940. }
  941. ifile->eof_reached = 1;
  942. return AVERROR(EAGAIN);
  943. }
  944. reset_eagain();
  945. ist = ifile->streams[pkt->stream_index];
  946. sub2video_heartbeat(ifile, pkt->pts, pkt->time_base);
  947. ret = process_input_packet(ist, pkt, 0);
  948. av_packet_free(&pkt);
  949. return ret < 0 ? ret : 0;
  950. }
  951. /**
  952. * Run a single step of transcoding.
  953. *
  954. * @return 0 for success, <0 for error
  955. */
  956. static int transcode_step(OutputStream *ost)
  957. {
  958. InputStream *ist = NULL;
  959. int ret;
  960. if (ost->filter) {
  961. if ((ret = fg_transcode_step(ost->filter->graph, &ist)) < 0)
  962. return ret;
  963. if (!ist)
  964. return 0;
  965. } else {
  966. ist = ost->ist;
  967. av_assert0(ist);
  968. }
  969. ret = process_input(ist->file_index);
  970. if (ret == AVERROR(EAGAIN)) {
  971. if (input_files[ist->file_index]->eagain)
  972. ost->unavailable = 1;
  973. return 0;
  974. }
  975. if (ret < 0)
  976. return ret == AVERROR_EOF ? 0 : ret;
  977. // process_input() above might have caused output to become available
  978. // in multiple filtergraphs, so we process all of them
  979. for (int i = 0; i < nb_filtergraphs; i++) {
  980. ret = reap_filters(filtergraphs[i], 0);
  981. if (ret < 0)
  982. return ret;
  983. }
  984. return 0;
  985. }
  986. /*
  987. * The following code is the main loop of the file converter
  988. */
  989. static int transcode(int *err_rate_exceeded)
  990. {
  991. int ret = 0, i;
  992. InputStream *ist;
  993. int64_t timer_start;
  994. print_stream_maps();
  995. *err_rate_exceeded = 0;
  996. atomic_store(&transcode_init_done, 1);
  997. if (stdin_interaction) {
  998. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  999. }
  1000. timer_start = av_gettime_relative();
  1001. while (!received_sigterm) {
  1002. OutputStream *ost;
  1003. int64_t cur_time= av_gettime_relative();
  1004. /* if 'q' pressed, exits */
  1005. if (stdin_interaction)
  1006. if (check_keyboard_interaction(cur_time) < 0)
  1007. break;
  1008. ret = choose_output(&ost);
  1009. if (ret == AVERROR(EAGAIN)) {
  1010. reset_eagain();
  1011. av_usleep(10000);
  1012. ret = 0;
  1013. continue;
  1014. } else if (ret < 0) {
  1015. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  1016. ret = 0;
  1017. break;
  1018. }
  1019. ret = transcode_step(ost);
  1020. if (ret < 0 && ret != AVERROR_EOF) {
  1021. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
  1022. break;
  1023. }
  1024. /* dump report by using the output first video and audio streams */
  1025. print_report(0, timer_start, cur_time);
  1026. }
  1027. /* at the end of stream, we must flush the decoder buffers */
  1028. for (ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
  1029. float err_rate;
  1030. if (!input_files[ist->file_index]->eof_reached) {
  1031. int err = process_input_packet(ist, NULL, 0);
  1032. ret = err_merge(ret, err);
  1033. }
  1034. err_rate = (ist->frames_decoded || ist->decode_errors) ?
  1035. ist->decode_errors / (ist->frames_decoded + ist->decode_errors) : 0.f;
  1036. if (err_rate > max_error_rate) {
  1037. av_log(ist, AV_LOG_FATAL, "Decode error rate %g exceeds maximum %g\n",
  1038. err_rate, max_error_rate);
  1039. *err_rate_exceeded = 1;
  1040. } else if (err_rate)
  1041. av_log(ist, AV_LOG_VERBOSE, "Decode error rate %g\n", err_rate);
  1042. }
  1043. ret = err_merge(ret, enc_flush());
  1044. term_exit();
  1045. /* write the trailer if needed */
  1046. for (i = 0; i < nb_output_files; i++) {
  1047. int err = of_write_trailer(output_files[i]);
  1048. ret = err_merge(ret, err);
  1049. }
  1050. /* dump report by using the first video and audio streams */
  1051. print_report(1, timer_start, av_gettime_relative());
  1052. return ret;
  1053. }
  1054. static BenchmarkTimeStamps get_benchmark_time_stamps(void)
  1055. {
  1056. BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
  1057. #if HAVE_GETRUSAGE
  1058. struct rusage rusage;
  1059. getrusage(RUSAGE_SELF, &rusage);
  1060. time_stamps.user_usec =
  1061. (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  1062. time_stamps.sys_usec =
  1063. (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
  1064. #elif HAVE_GETPROCESSTIMES
  1065. HANDLE proc;
  1066. FILETIME c, e, k, u;
  1067. proc = GetCurrentProcess();
  1068. GetProcessTimes(proc, &c, &e, &k, &u);
  1069. time_stamps.user_usec =
  1070. ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  1071. time_stamps.sys_usec =
  1072. ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
  1073. #else
  1074. time_stamps.user_usec = time_stamps.sys_usec = 0;
  1075. #endif
  1076. return time_stamps;
  1077. }
  1078. static int64_t getmaxrss(void)
  1079. {
  1080. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  1081. struct rusage rusage;
  1082. getrusage(RUSAGE_SELF, &rusage);
  1083. return (int64_t)rusage.ru_maxrss * 1024;
  1084. #elif HAVE_GETPROCESSMEMORYINFO
  1085. HANDLE proc;
  1086. PROCESS_MEMORY_COUNTERS memcounters;
  1087. proc = GetCurrentProcess();
  1088. memcounters.cb = sizeof(memcounters);
  1089. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  1090. return memcounters.PeakPagefileUsage;
  1091. #else
  1092. return 0;
  1093. #endif
  1094. }
  1095. int main(int argc, char **argv)
  1096. {
  1097. int ret, err_rate_exceeded;
  1098. BenchmarkTimeStamps ti;
  1099. init_dynload();
  1100. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  1101. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  1102. parse_loglevel(argc, argv, options);
  1103. #if CONFIG_AVDEVICE
  1104. avdevice_register_all();
  1105. #endif
  1106. avformat_network_init();
  1107. show_banner(argc, argv, options);
  1108. /* parse options and open all input/output files */
  1109. ret = ffmpeg_parse_options(argc, argv);
  1110. if (ret < 0)
  1111. goto finish;
  1112. if (nb_output_files <= 0 && nb_input_files == 0) {
  1113. show_usage();
  1114. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  1115. ret = 1;
  1116. goto finish;
  1117. }
  1118. if (nb_output_files <= 0) {
  1119. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  1120. ret = 1;
  1121. goto finish;
  1122. }
  1123. current_time = ti = get_benchmark_time_stamps();
  1124. ret = transcode(&err_rate_exceeded);
  1125. if (ret >= 0 && do_benchmark) {
  1126. int64_t utime, stime, rtime;
  1127. current_time = get_benchmark_time_stamps();
  1128. utime = current_time.user_usec - ti.user_usec;
  1129. stime = current_time.sys_usec - ti.sys_usec;
  1130. rtime = current_time.real_usec - ti.real_usec;
  1131. av_log(NULL, AV_LOG_INFO,
  1132. "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
  1133. utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
  1134. }
  1135. ret = received_nb_signals ? 255 :
  1136. err_rate_exceeded ? 69 : ret;
  1137. finish:
  1138. if (ret == AVERROR_EXIT)
  1139. ret = 0;
  1140. ffmpeg_cleanup(ret);
  1141. return ret;
  1142. }