ffmpeg.c 28 KB

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