You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1844 lines
60KB

  1. /*
  2. * Copyright (c) 2007-2010 Stefano Sabatini
  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. * simple media prober based on the FFmpeg libraries
  23. */
  24. #include "config.h"
  25. #include "version.h"
  26. #include "libavformat/avformat.h"
  27. #include "libavcodec/avcodec.h"
  28. #include "libavutil/avstring.h"
  29. #include "libavutil/bprint.h"
  30. #include "libavutil/opt.h"
  31. #include "libavutil/pixdesc.h"
  32. #include "libavutil/dict.h"
  33. #include "libavutil/timecode.h"
  34. #include "libavdevice/avdevice.h"
  35. #include "libswscale/swscale.h"
  36. #include "libswresample/swresample.h"
  37. #include "libpostproc/postprocess.h"
  38. #include "cmdutils.h"
  39. const char program_name[] = "ffprobe";
  40. const int program_birth_year = 2007;
  41. static int do_count_frames = 0;
  42. static int do_count_packets = 0;
  43. static int do_read_frames = 0;
  44. static int do_read_packets = 0;
  45. static int do_show_error = 0;
  46. static int do_show_format = 0;
  47. static int do_show_frames = 0;
  48. static AVDictionary *fmt_entries_to_show = NULL;
  49. static int do_show_packets = 0;
  50. static int do_show_streams = 0;
  51. static int do_show_program_version = 0;
  52. static int do_show_library_versions = 0;
  53. static int show_value_unit = 0;
  54. static int use_value_prefix = 0;
  55. static int use_byte_value_binary_prefix = 0;
  56. static int use_value_sexagesimal_format = 0;
  57. static int show_private_data = 1;
  58. static char *print_format;
  59. static const OptionDef options[];
  60. /* FFprobe context */
  61. static const char *input_filename;
  62. static AVInputFormat *iformat = NULL;
  63. static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
  64. static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P" };
  65. static const char unit_second_str[] = "s" ;
  66. static const char unit_hertz_str[] = "Hz" ;
  67. static const char unit_byte_str[] = "byte" ;
  68. static const char unit_bit_per_second_str[] = "bit/s";
  69. static uint64_t *nb_streams_packets;
  70. static uint64_t *nb_streams_frames;
  71. void av_noreturn exit_program(int ret)
  72. {
  73. av_dict_free(&fmt_entries_to_show);
  74. exit(ret);
  75. }
  76. struct unit_value {
  77. union { double d; long long int i; } val;
  78. const char *unit;
  79. };
  80. static char *value_string(char *buf, int buf_size, struct unit_value uv)
  81. {
  82. double vald;
  83. int show_float = 0;
  84. if (uv.unit == unit_second_str) {
  85. vald = uv.val.d;
  86. show_float = 1;
  87. } else {
  88. vald = uv.val.i;
  89. }
  90. if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
  91. double secs;
  92. int hours, mins;
  93. secs = vald;
  94. mins = (int)secs / 60;
  95. secs = secs - mins * 60;
  96. hours = mins / 60;
  97. mins %= 60;
  98. snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
  99. } else {
  100. const char *prefix_string = "";
  101. int l;
  102. if (use_value_prefix && vald > 1) {
  103. long long int index;
  104. if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
  105. index = (long long int) (log(vald)/log(2)) / 10;
  106. index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
  107. vald /= pow(2, index * 10);
  108. prefix_string = binary_unit_prefixes[index];
  109. } else {
  110. index = (long long int) (log10(vald)) / 3;
  111. index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
  112. vald /= pow(10, index * 3);
  113. prefix_string = decimal_unit_prefixes[index];
  114. }
  115. }
  116. if (show_float || (use_value_prefix && vald != (long long int)vald))
  117. l = snprintf(buf, buf_size, "%f", vald);
  118. else
  119. l = snprintf(buf, buf_size, "%lld", (long long int)vald);
  120. snprintf(buf+l, buf_size-l, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
  121. prefix_string, show_value_unit ? uv.unit : "");
  122. }
  123. return buf;
  124. }
  125. /* WRITERS API */
  126. typedef struct WriterContext WriterContext;
  127. #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
  128. #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
  129. typedef struct Writer {
  130. int priv_size; ///< private size for the writer context
  131. const char *name;
  132. int (*init) (WriterContext *wctx, const char *args, void *opaque);
  133. void (*uninit)(WriterContext *wctx);
  134. void (*print_header)(WriterContext *ctx);
  135. void (*print_footer)(WriterContext *ctx);
  136. void (*print_chapter_header)(WriterContext *wctx, const char *);
  137. void (*print_chapter_footer)(WriterContext *wctx, const char *);
  138. void (*print_section_header)(WriterContext *wctx, const char *);
  139. void (*print_section_footer)(WriterContext *wctx, const char *);
  140. void (*print_integer) (WriterContext *wctx, const char *, long long int);
  141. void (*print_string) (WriterContext *wctx, const char *, const char *);
  142. void (*show_tags) (WriterContext *wctx, AVDictionary *dict);
  143. int flags; ///< a combination or WRITER_FLAG_*
  144. } Writer;
  145. struct WriterContext {
  146. const AVClass *class; ///< class of the writer
  147. const Writer *writer; ///< the Writer of which this is an instance
  148. char *name; ///< name of this writer instance
  149. void *priv; ///< private data for use by the filter
  150. unsigned int nb_item; ///< number of the item printed in the given section, starting at 0
  151. unsigned int nb_section; ///< number of the section printed in the given section sequence, starting at 0
  152. unsigned int nb_chapter; ///< number of the chapter, starting at 0
  153. int is_fmt_chapter; ///< tells if the current chapter is "format", required by the print_format_entry option
  154. };
  155. static const char *writer_get_name(void *p)
  156. {
  157. WriterContext *wctx = p;
  158. return wctx->writer->name;
  159. }
  160. static const AVClass writer_class = {
  161. "Writer",
  162. writer_get_name,
  163. NULL,
  164. LIBAVUTIL_VERSION_INT,
  165. };
  166. static void writer_close(WriterContext **wctx)
  167. {
  168. if (!*wctx)
  169. return;
  170. if ((*wctx)->writer->uninit)
  171. (*wctx)->writer->uninit(*wctx);
  172. av_freep(&((*wctx)->priv));
  173. av_freep(wctx);
  174. }
  175. static int writer_open(WriterContext **wctx, const Writer *writer,
  176. const char *args, void *opaque)
  177. {
  178. int ret = 0;
  179. if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
  180. ret = AVERROR(ENOMEM);
  181. goto fail;
  182. }
  183. if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
  184. ret = AVERROR(ENOMEM);
  185. goto fail;
  186. }
  187. (*wctx)->class = &writer_class;
  188. (*wctx)->writer = writer;
  189. if ((*wctx)->writer->init)
  190. ret = (*wctx)->writer->init(*wctx, args, opaque);
  191. if (ret < 0)
  192. goto fail;
  193. return 0;
  194. fail:
  195. writer_close(wctx);
  196. return ret;
  197. }
  198. static inline void writer_print_header(WriterContext *wctx)
  199. {
  200. if (wctx->writer->print_header)
  201. wctx->writer->print_header(wctx);
  202. wctx->nb_chapter = 0;
  203. }
  204. static inline void writer_print_footer(WriterContext *wctx)
  205. {
  206. if (wctx->writer->print_footer)
  207. wctx->writer->print_footer(wctx);
  208. }
  209. static inline void writer_print_chapter_header(WriterContext *wctx,
  210. const char *chapter)
  211. {
  212. if (wctx->writer->print_chapter_header)
  213. wctx->writer->print_chapter_header(wctx, chapter);
  214. wctx->nb_section = 0;
  215. wctx->is_fmt_chapter = !strcmp(chapter, "format");
  216. }
  217. static inline void writer_print_chapter_footer(WriterContext *wctx,
  218. const char *chapter)
  219. {
  220. if (wctx->writer->print_chapter_footer)
  221. wctx->writer->print_chapter_footer(wctx, chapter);
  222. wctx->nb_chapter++;
  223. }
  224. static inline void writer_print_section_header(WriterContext *wctx,
  225. const char *section)
  226. {
  227. if (wctx->writer->print_section_header)
  228. wctx->writer->print_section_header(wctx, section);
  229. wctx->nb_item = 0;
  230. }
  231. static inline void writer_print_section_footer(WriterContext *wctx,
  232. const char *section)
  233. {
  234. if (wctx->writer->print_section_footer)
  235. wctx->writer->print_section_footer(wctx, section);
  236. wctx->nb_section++;
  237. }
  238. static inline void writer_print_integer(WriterContext *wctx,
  239. const char *key, long long int val)
  240. {
  241. if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
  242. wctx->writer->print_integer(wctx, key, val);
  243. wctx->nb_item++;
  244. }
  245. }
  246. static inline void writer_print_string(WriterContext *wctx,
  247. const char *key, const char *val, int opt)
  248. {
  249. if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
  250. return;
  251. if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
  252. wctx->writer->print_string(wctx, key, val);
  253. wctx->nb_item++;
  254. }
  255. }
  256. static void writer_print_time(WriterContext *wctx, const char *key,
  257. int64_t ts, const AVRational *time_base)
  258. {
  259. char buf[128];
  260. if (!wctx->is_fmt_chapter || !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
  261. if (ts == AV_NOPTS_VALUE) {
  262. writer_print_string(wctx, key, "N/A", 1);
  263. } else {
  264. double d = ts * av_q2d(*time_base);
  265. value_string(buf, sizeof(buf), (struct unit_value){.val.d=d, .unit=unit_second_str});
  266. writer_print_string(wctx, key, buf, 0);
  267. }
  268. }
  269. }
  270. static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts)
  271. {
  272. if (ts == AV_NOPTS_VALUE) {
  273. writer_print_string(wctx, key, "N/A", 1);
  274. } else {
  275. writer_print_integer(wctx, key, ts);
  276. }
  277. }
  278. static inline void writer_show_tags(WriterContext *wctx, AVDictionary *dict)
  279. {
  280. wctx->writer->show_tags(wctx, dict);
  281. }
  282. #define MAX_REGISTERED_WRITERS_NB 64
  283. static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
  284. static int writer_register(const Writer *writer)
  285. {
  286. static int next_registered_writer_idx = 0;
  287. if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
  288. return AVERROR(ENOMEM);
  289. registered_writers[next_registered_writer_idx++] = writer;
  290. return 0;
  291. }
  292. static const Writer *writer_get_by_name(const char *name)
  293. {
  294. int i;
  295. for (i = 0; registered_writers[i]; i++)
  296. if (!strcmp(registered_writers[i]->name, name))
  297. return registered_writers[i];
  298. return NULL;
  299. }
  300. /* Print helpers */
  301. struct print_buf {
  302. char *s;
  303. int len;
  304. };
  305. static char *fast_asprintf(struct print_buf *pbuf, const char *fmt, ...)
  306. {
  307. va_list va;
  308. int len;
  309. va_start(va, fmt);
  310. len = vsnprintf(NULL, 0, fmt, va);
  311. va_end(va);
  312. if (len < 0)
  313. goto fail;
  314. if (pbuf->len < len) {
  315. char *p = av_realloc(pbuf->s, len + 1);
  316. if (!p)
  317. goto fail;
  318. pbuf->s = p;
  319. pbuf->len = len;
  320. }
  321. va_start(va, fmt);
  322. len = vsnprintf(pbuf->s, len + 1, fmt, va);
  323. va_end(va);
  324. if (len < 0)
  325. goto fail;
  326. return pbuf->s;
  327. fail:
  328. av_freep(&pbuf->s);
  329. pbuf->len = 0;
  330. return NULL;
  331. }
  332. /* WRITERS */
  333. /* Default output */
  334. typedef struct DefaultContext {
  335. const AVClass *class;
  336. int nokey;
  337. int noprint_wrappers;
  338. } DefaultContext;
  339. #define OFFSET(x) offsetof(DefaultContext, x)
  340. static const AVOption default_options[] = {
  341. { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  342. { "nw", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  343. { "nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  344. { "nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  345. {NULL},
  346. };
  347. static const char *default_get_name(void *ctx)
  348. {
  349. return "default";
  350. }
  351. static const AVClass default_class = {
  352. "DefaultContext",
  353. default_get_name,
  354. default_options
  355. };
  356. static av_cold int default_init(WriterContext *wctx, const char *args, void *opaque)
  357. {
  358. DefaultContext *def = wctx->priv;
  359. int err;
  360. def->class = &default_class;
  361. av_opt_set_defaults(def);
  362. if (args &&
  363. (err = (av_set_options_string(def, args, "=", ":"))) < 0) {
  364. av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  365. return err;
  366. }
  367. return 0;
  368. }
  369. static void default_print_footer(WriterContext *wctx)
  370. {
  371. DefaultContext *def = wctx->priv;
  372. if (!def->noprint_wrappers)
  373. printf("\n");
  374. }
  375. static void default_print_chapter_header(WriterContext *wctx, const char *chapter)
  376. {
  377. DefaultContext *def = wctx->priv;
  378. if (!def->noprint_wrappers && wctx->nb_chapter)
  379. printf("\n");
  380. }
  381. /* lame uppercasing routine, assumes the string is lower case ASCII */
  382. static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
  383. {
  384. int i;
  385. for (i = 0; src[i] && i < dst_size-1; i++)
  386. dst[i] = av_toupper(src[i]);
  387. dst[i] = 0;
  388. return dst;
  389. }
  390. static void default_print_section_header(WriterContext *wctx, const char *section)
  391. {
  392. DefaultContext *def = wctx->priv;
  393. char buf[32];
  394. if (wctx->nb_section)
  395. printf("\n");
  396. if (!def->noprint_wrappers)
  397. printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
  398. }
  399. static void default_print_section_footer(WriterContext *wctx, const char *section)
  400. {
  401. DefaultContext *def = wctx->priv;
  402. char buf[32];
  403. if (!def->noprint_wrappers)
  404. printf("[/%s]", upcase_string(buf, sizeof(buf), section));
  405. }
  406. static void default_print_str(WriterContext *wctx, const char *key, const char *value)
  407. {
  408. DefaultContext *def = wctx->priv;
  409. if (!def->nokey)
  410. printf("%s=", key);
  411. printf("%s\n", value);
  412. }
  413. static void default_print_int(WriterContext *wctx, const char *key, long long int value)
  414. {
  415. DefaultContext *def = wctx->priv;
  416. if (!def->nokey)
  417. printf("%s=", key);
  418. printf("%lld\n", value);
  419. }
  420. static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
  421. {
  422. AVDictionaryEntry *tag = NULL;
  423. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  424. if (!fmt_entries_to_show || (tag->key && av_dict_get(fmt_entries_to_show, tag->key, NULL, 0)))
  425. printf("TAG:");
  426. writer_print_string(wctx, tag->key, tag->value, 0);
  427. }
  428. }
  429. static const Writer default_writer = {
  430. .name = "default",
  431. .init = default_init,
  432. .print_footer = default_print_footer,
  433. .print_chapter_header = default_print_chapter_header,
  434. .print_section_header = default_print_section_header,
  435. .print_section_footer = default_print_section_footer,
  436. .print_integer = default_print_int,
  437. .print_string = default_print_str,
  438. .show_tags = default_show_tags,
  439. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  440. };
  441. /* Compact output */
  442. /**
  443. * Escape \n, \r, \\ and sep characters contained in s, and print the
  444. * resulting string.
  445. */
  446. static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  447. {
  448. const char *p;
  449. for (p = src; *p; p++) {
  450. switch (*src) {
  451. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  452. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  453. case '\\': av_bprintf(dst, "%s", "\\\\"); break;
  454. default:
  455. if (*p == sep)
  456. av_bprint_chars(dst, '\\', 1);
  457. av_bprint_chars(dst, *p, 1);
  458. }
  459. }
  460. return dst->str;
  461. }
  462. /**
  463. * Quote fields containing special characters, check RFC4180.
  464. */
  465. static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  466. {
  467. const char *p;
  468. int quote = 0;
  469. /* check if input needs quoting */
  470. for (p = src; *p; p++)
  471. if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
  472. quote = 1;
  473. if (quote)
  474. av_bprint_chars(dst, '\"', 1);
  475. for (p = src; *p; p++) {
  476. if (*p == '"')
  477. av_bprint_chars(dst, '\"', 1);
  478. av_bprint_chars(dst, *p, 1);
  479. }
  480. if (quote)
  481. av_bprint_chars(dst, '\"', 1);
  482. return dst->str;
  483. }
  484. static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  485. {
  486. return src;
  487. }
  488. typedef struct CompactContext {
  489. const AVClass *class;
  490. char *item_sep_str;
  491. char item_sep;
  492. int nokey;
  493. char *escape_mode_str;
  494. const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
  495. } CompactContext;
  496. #undef OFFSET
  497. #define OFFSET(x) offsetof(CompactContext, x)
  498. static const AVOption compact_options[]= {
  499. {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  500. {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  501. {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  502. {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  503. {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  504. {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  505. {NULL},
  506. };
  507. static const char *compact_get_name(void *ctx)
  508. {
  509. return "compact";
  510. }
  511. static const AVClass compact_class = {
  512. "CompactContext",
  513. compact_get_name,
  514. compact_options
  515. };
  516. static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
  517. {
  518. CompactContext *compact = wctx->priv;
  519. int err;
  520. compact->class = &compact_class;
  521. av_opt_set_defaults(compact);
  522. if (args &&
  523. (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
  524. av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  525. return err;
  526. }
  527. if (strlen(compact->item_sep_str) != 1) {
  528. av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
  529. compact->item_sep_str);
  530. return AVERROR(EINVAL);
  531. }
  532. compact->item_sep = compact->item_sep_str[0];
  533. if (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
  534. else if (!strcmp(compact->escape_mode_str, "c" )) compact->escape_str = c_escape_str;
  535. else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
  536. else {
  537. av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
  538. return AVERROR(EINVAL);
  539. }
  540. return 0;
  541. }
  542. static av_cold void compact_uninit(WriterContext *wctx)
  543. {
  544. CompactContext *compact = wctx->priv;
  545. av_freep(&compact->item_sep_str);
  546. av_freep(&compact->escape_mode_str);
  547. }
  548. static void compact_print_section_header(WriterContext *wctx, const char *section)
  549. {
  550. CompactContext *compact = wctx->priv;
  551. printf("%s%c", section, compact->item_sep);
  552. }
  553. static void compact_print_section_footer(WriterContext *wctx, const char *section)
  554. {
  555. printf("\n");
  556. }
  557. static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
  558. {
  559. CompactContext *compact = wctx->priv;
  560. AVBPrint buf;
  561. if (wctx->nb_item) printf("%c", compact->item_sep);
  562. if (!compact->nokey)
  563. printf("%s=", key);
  564. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  565. printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
  566. av_bprint_finalize(&buf, NULL);
  567. }
  568. static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
  569. {
  570. CompactContext *compact = wctx->priv;
  571. if (wctx->nb_item) printf("%c", compact->item_sep);
  572. if (!compact->nokey)
  573. printf("%s=", key);
  574. printf("%lld", value);
  575. }
  576. static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
  577. {
  578. CompactContext *compact = wctx->priv;
  579. AVDictionaryEntry *tag = NULL;
  580. AVBPrint buf;
  581. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  582. if (wctx->nb_item) printf("%c", compact->item_sep);
  583. if (!compact->nokey) {
  584. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  585. printf("tag:%s=", compact->escape_str(&buf, tag->key, compact->item_sep, wctx));
  586. av_bprint_finalize(&buf, NULL);
  587. }
  588. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  589. printf("%s", compact->escape_str(&buf, tag->value, compact->item_sep, wctx));
  590. av_bprint_finalize(&buf, NULL);
  591. }
  592. }
  593. static const Writer compact_writer = {
  594. .name = "compact",
  595. .priv_size = sizeof(CompactContext),
  596. .init = compact_init,
  597. .uninit = compact_uninit,
  598. .print_section_header = compact_print_section_header,
  599. .print_section_footer = compact_print_section_footer,
  600. .print_integer = compact_print_int,
  601. .print_string = compact_print_str,
  602. .show_tags = compact_show_tags,
  603. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  604. };
  605. /* CSV output */
  606. static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
  607. {
  608. return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
  609. }
  610. static const Writer csv_writer = {
  611. .name = "csv",
  612. .priv_size = sizeof(CompactContext),
  613. .init = csv_init,
  614. .uninit = compact_uninit,
  615. .print_section_header = compact_print_section_header,
  616. .print_section_footer = compact_print_section_footer,
  617. .print_integer = compact_print_int,
  618. .print_string = compact_print_str,
  619. .show_tags = compact_show_tags,
  620. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  621. };
  622. /* JSON output */
  623. typedef struct {
  624. const AVClass *class;
  625. int multiple_entries; ///< tells if the given chapter requires multiple entries
  626. int print_packets_and_frames;
  627. int indent_level;
  628. int compact;
  629. const char *item_sep, *item_start_end;
  630. } JSONContext;
  631. #undef OFFSET
  632. #define OFFSET(x) offsetof(JSONContext, x)
  633. static const AVOption json_options[]= {
  634. { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  635. { "c", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  636. { NULL }
  637. };
  638. static const char *json_get_name(void *ctx)
  639. {
  640. return "json";
  641. }
  642. static const AVClass json_class = {
  643. "JSONContext",
  644. json_get_name,
  645. json_options
  646. };
  647. static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
  648. {
  649. JSONContext *json = wctx->priv;
  650. int err;
  651. json->class = &json_class;
  652. av_opt_set_defaults(json);
  653. if (args &&
  654. (err = (av_set_options_string(json, args, "=", ":"))) < 0) {
  655. av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  656. return err;
  657. }
  658. json->item_sep = json->compact ? ", " : ",\n";
  659. json->item_start_end = json->compact ? " " : "\n";
  660. return 0;
  661. }
  662. static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  663. {
  664. static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
  665. static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
  666. const char *p;
  667. for (p = src; *p; p++) {
  668. char *s = strchr(json_escape, *p);
  669. if (s) {
  670. av_bprint_chars(dst, '\\', 1);
  671. av_bprint_chars(dst, json_subst[s - json_escape], 1);
  672. } else if ((unsigned char)*p < 32) {
  673. av_bprintf(dst, "\\u00%02x", *p & 0xff);
  674. } else {
  675. av_bprint_chars(dst, *p, 1);
  676. }
  677. }
  678. return dst->str;
  679. }
  680. static void json_print_header(WriterContext *wctx)
  681. {
  682. JSONContext *json = wctx->priv;
  683. printf("{");
  684. json->indent_level++;
  685. }
  686. static void json_print_footer(WriterContext *wctx)
  687. {
  688. JSONContext *json = wctx->priv;
  689. json->indent_level--;
  690. printf("\n}\n");
  691. }
  692. #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
  693. static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
  694. {
  695. JSONContext *json = wctx->priv;
  696. AVBPrint buf;
  697. if (wctx->nb_chapter)
  698. printf(",");
  699. printf("\n");
  700. json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
  701. !strcmp(chapter, "packets_and_frames") ||
  702. !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
  703. if (json->multiple_entries) {
  704. JSON_INDENT();
  705. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  706. printf("\"%s\": [\n", json_escape_str(&buf, chapter, wctx));
  707. av_bprint_finalize(&buf, NULL);
  708. json->print_packets_and_frames = !strcmp(chapter, "packets_and_frames");
  709. json->indent_level++;
  710. }
  711. }
  712. static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
  713. {
  714. JSONContext *json = wctx->priv;
  715. if (json->multiple_entries) {
  716. printf("\n");
  717. json->indent_level--;
  718. JSON_INDENT();
  719. printf("]");
  720. }
  721. }
  722. static void json_print_section_header(WriterContext *wctx, const char *section)
  723. {
  724. JSONContext *json = wctx->priv;
  725. if (wctx->nb_section)
  726. printf(",\n");
  727. JSON_INDENT();
  728. if (!json->multiple_entries)
  729. printf("\"%s\": ", section);
  730. printf("{%s", json->item_start_end);
  731. json->indent_level++;
  732. /* this is required so the parser can distinguish between packets and frames */
  733. if (json->print_packets_and_frames) {
  734. if (!json->compact)
  735. JSON_INDENT();
  736. printf("\"type\": \"%s\"%s", section, json->item_sep);
  737. }
  738. }
  739. static void json_print_section_footer(WriterContext *wctx, const char *section)
  740. {
  741. JSONContext *json = wctx->priv;
  742. printf("%s", json->item_start_end);
  743. json->indent_level--;
  744. if (!json->compact)
  745. JSON_INDENT();
  746. printf("}");
  747. }
  748. static inline void json_print_item_str(WriterContext *wctx,
  749. const char *key, const char *value)
  750. {
  751. AVBPrint buf;
  752. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  753. printf("\"%s\":", json_escape_str(&buf, key, wctx));
  754. av_bprint_finalize(&buf, NULL);
  755. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  756. printf(" \"%s\"", json_escape_str(&buf, value, wctx));
  757. av_bprint_finalize(&buf, NULL);
  758. }
  759. static void json_print_str(WriterContext *wctx, const char *key, const char *value)
  760. {
  761. JSONContext *json = wctx->priv;
  762. if (wctx->nb_item) printf("%s", json->item_sep);
  763. if (!json->compact)
  764. JSON_INDENT();
  765. json_print_item_str(wctx, key, value);
  766. }
  767. static void json_print_int(WriterContext *wctx, const char *key, long long int value)
  768. {
  769. JSONContext *json = wctx->priv;
  770. AVBPrint buf;
  771. if (wctx->nb_item) printf("%s", json->item_sep);
  772. if (!json->compact)
  773. JSON_INDENT();
  774. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  775. printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
  776. av_bprint_finalize(&buf, NULL);
  777. }
  778. static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
  779. {
  780. JSONContext *json = wctx->priv;
  781. AVDictionaryEntry *tag = NULL;
  782. int is_first = 1;
  783. if (!dict)
  784. return;
  785. printf("%s", json->item_sep);
  786. if (!json->compact)
  787. JSON_INDENT();
  788. printf("\"tags\": {%s", json->item_start_end);
  789. json->indent_level++;
  790. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  791. if (is_first) is_first = 0;
  792. else printf("%s", json->item_sep);
  793. if (!json->compact)
  794. JSON_INDENT();
  795. json_print_item_str(wctx, tag->key, tag->value);
  796. }
  797. json->indent_level--;
  798. printf("%s", json->item_start_end);
  799. if (!json->compact)
  800. JSON_INDENT();
  801. printf("}");
  802. }
  803. static const Writer json_writer = {
  804. .name = "json",
  805. .priv_size = sizeof(JSONContext),
  806. .init = json_init,
  807. .print_header = json_print_header,
  808. .print_footer = json_print_footer,
  809. .print_chapter_header = json_print_chapter_header,
  810. .print_chapter_footer = json_print_chapter_footer,
  811. .print_section_header = json_print_section_header,
  812. .print_section_footer = json_print_section_footer,
  813. .print_integer = json_print_int,
  814. .print_string = json_print_str,
  815. .show_tags = json_show_tags,
  816. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  817. };
  818. /* XML output */
  819. typedef struct {
  820. const AVClass *class;
  821. int within_tag;
  822. int multiple_entries; ///< tells if the given chapter requires multiple entries
  823. int indent_level;
  824. int fully_qualified;
  825. int xsd_strict;
  826. } XMLContext;
  827. #undef OFFSET
  828. #define OFFSET(x) offsetof(XMLContext, x)
  829. static const AVOption xml_options[] = {
  830. {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  831. {"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  832. {"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  833. {"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  834. {NULL},
  835. };
  836. static const char *xml_get_name(void *ctx)
  837. {
  838. return "xml";
  839. }
  840. static const AVClass xml_class = {
  841. "XMLContext",
  842. xml_get_name,
  843. xml_options
  844. };
  845. static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
  846. {
  847. XMLContext *xml = wctx->priv;
  848. int err;
  849. xml->class = &xml_class;
  850. av_opt_set_defaults(xml);
  851. if (args &&
  852. (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
  853. av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  854. return err;
  855. }
  856. if (xml->xsd_strict) {
  857. xml->fully_qualified = 1;
  858. #define CHECK_COMPLIANCE(opt, opt_name) \
  859. if (opt) { \
  860. av_log(wctx, AV_LOG_ERROR, \
  861. "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
  862. "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
  863. return AVERROR(EINVAL); \
  864. }
  865. CHECK_COMPLIANCE(show_private_data, "private");
  866. CHECK_COMPLIANCE(show_value_unit, "unit");
  867. CHECK_COMPLIANCE(use_value_prefix, "prefix");
  868. if (do_show_frames && do_show_packets) {
  869. av_log(wctx, AV_LOG_ERROR,
  870. "Interleaved frames and packets are not allowed in XSD. "
  871. "Select only one between the -show_frames and the -show_packets options.\n");
  872. return AVERROR(EINVAL);
  873. }
  874. }
  875. return 0;
  876. }
  877. static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  878. {
  879. const char *p;
  880. for (p = src; *p; p++) {
  881. switch (*p) {
  882. case '&' : av_bprintf(dst, "%s", "&amp;"); break;
  883. case '<' : av_bprintf(dst, "%s", "&lt;"); break;
  884. case '>' : av_bprintf(dst, "%s", "&gt;"); break;
  885. case '\"': av_bprintf(dst, "%s", "&quot;"); break;
  886. case '\'': av_bprintf(dst, "%s", "&apos;"); break;
  887. default: av_bprint_chars(dst, *p, 1);
  888. }
  889. }
  890. return dst->str;
  891. }
  892. static void xml_print_header(WriterContext *wctx)
  893. {
  894. XMLContext *xml = wctx->priv;
  895. const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
  896. "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
  897. "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
  898. printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  899. printf("<%sffprobe%s>\n",
  900. xml->fully_qualified ? "ffprobe:" : "",
  901. xml->fully_qualified ? qual : "");
  902. xml->indent_level++;
  903. }
  904. static void xml_print_footer(WriterContext *wctx)
  905. {
  906. XMLContext *xml = wctx->priv;
  907. xml->indent_level--;
  908. printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
  909. }
  910. #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
  911. static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
  912. {
  913. XMLContext *xml = wctx->priv;
  914. if (wctx->nb_chapter)
  915. printf("\n");
  916. xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames") ||
  917. !strcmp(chapter, "packets_and_frames") ||
  918. !strcmp(chapter, "streams") || !strcmp(chapter, "library_versions");
  919. if (xml->multiple_entries) {
  920. XML_INDENT(); printf("<%s>\n", chapter);
  921. xml->indent_level++;
  922. }
  923. }
  924. static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
  925. {
  926. XMLContext *xml = wctx->priv;
  927. if (xml->multiple_entries) {
  928. xml->indent_level--;
  929. XML_INDENT(); printf("</%s>\n", chapter);
  930. }
  931. }
  932. static void xml_print_section_header(WriterContext *wctx, const char *section)
  933. {
  934. XMLContext *xml = wctx->priv;
  935. XML_INDENT(); printf("<%s ", section);
  936. xml->within_tag = 1;
  937. }
  938. static void xml_print_section_footer(WriterContext *wctx, const char *section)
  939. {
  940. XMLContext *xml = wctx->priv;
  941. if (xml->within_tag)
  942. printf("/>\n");
  943. else {
  944. XML_INDENT(); printf("</%s>\n", section);
  945. }
  946. }
  947. static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
  948. {
  949. AVBPrint buf;
  950. if (wctx->nb_item)
  951. printf(" ");
  952. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  953. printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
  954. av_bprint_finalize(&buf, NULL);
  955. }
  956. static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
  957. {
  958. if (wctx->nb_item)
  959. printf(" ");
  960. printf("%s=\"%lld\"", key, value);
  961. }
  962. static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
  963. {
  964. XMLContext *xml = wctx->priv;
  965. AVDictionaryEntry *tag = NULL;
  966. int is_first = 1;
  967. AVBPrint buf;
  968. xml->indent_level++;
  969. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  970. if (is_first) {
  971. /* close section tag */
  972. printf(">\n");
  973. xml->within_tag = 0;
  974. is_first = 0;
  975. }
  976. XML_INDENT();
  977. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  978. printf("<tag key=\"%s\"", xml_escape_str(&buf, tag->key, wctx));
  979. av_bprint_finalize(&buf, NULL);
  980. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  981. printf(" value=\"%s\"/>\n", xml_escape_str(&buf, tag->value, wctx));
  982. av_bprint_finalize(&buf, NULL);
  983. }
  984. xml->indent_level--;
  985. }
  986. static Writer xml_writer = {
  987. .name = "xml",
  988. .priv_size = sizeof(XMLContext),
  989. .init = xml_init,
  990. .print_header = xml_print_header,
  991. .print_footer = xml_print_footer,
  992. .print_chapter_header = xml_print_chapter_header,
  993. .print_chapter_footer = xml_print_chapter_footer,
  994. .print_section_header = xml_print_section_header,
  995. .print_section_footer = xml_print_section_footer,
  996. .print_integer = xml_print_int,
  997. .print_string = xml_print_str,
  998. .show_tags = xml_show_tags,
  999. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1000. };
  1001. static void writer_register_all(void)
  1002. {
  1003. static int initialized;
  1004. if (initialized)
  1005. return;
  1006. initialized = 1;
  1007. writer_register(&default_writer);
  1008. writer_register(&compact_writer);
  1009. writer_register(&csv_writer);
  1010. writer_register(&json_writer);
  1011. writer_register(&xml_writer);
  1012. }
  1013. #define print_fmt(k, f, ...) do { \
  1014. if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
  1015. writer_print_string(w, k, pbuf.s, 0); \
  1016. } while (0)
  1017. #define print_fmt_opt(k, f, ...) do { \
  1018. if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
  1019. writer_print_string(w, k, pbuf.s, 1); \
  1020. } while (0)
  1021. #define print_int(k, v) writer_print_integer(w, k, v)
  1022. #define print_str(k, v) writer_print_string(w, k, v, 0)
  1023. #define print_str_opt(k, v) writer_print_string(w, k, v, 1)
  1024. #define print_time(k, v, tb) writer_print_time(w, k, v, tb)
  1025. #define print_ts(k, v) writer_print_ts(w, k, v)
  1026. #define print_val(k, v, u) writer_print_string(w, k, \
  1027. value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
  1028. #define print_section_header(s) writer_print_section_header(w, s)
  1029. #define print_section_footer(s) writer_print_section_footer(w, s)
  1030. #define show_tags(metadata) writer_show_tags(w, metadata)
  1031. static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
  1032. {
  1033. char val_str[128];
  1034. AVStream *st = fmt_ctx->streams[pkt->stream_index];
  1035. struct print_buf pbuf = {.s = NULL};
  1036. const char *s;
  1037. print_section_header("packet");
  1038. s = av_get_media_type_string(st->codec->codec_type);
  1039. if (s) print_str ("codec_type", s);
  1040. else print_str_opt("codec_type", "unknown");
  1041. print_int("stream_index", pkt->stream_index);
  1042. print_ts ("pts", pkt->pts);
  1043. print_time("pts_time", pkt->pts, &st->time_base);
  1044. print_ts ("dts", pkt->dts);
  1045. print_time("dts_time", pkt->dts, &st->time_base);
  1046. print_ts ("duration", pkt->duration);
  1047. print_time("duration_time", pkt->duration, &st->time_base);
  1048. print_val("size", pkt->size, unit_byte_str);
  1049. if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
  1050. else print_str_opt("pos", "N/A");
  1051. print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
  1052. print_section_footer("packet");
  1053. av_free(pbuf.s);
  1054. fflush(stdout);
  1055. }
  1056. static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
  1057. {
  1058. struct print_buf pbuf = {.s = NULL};
  1059. const char *s;
  1060. print_section_header("frame");
  1061. s = av_get_media_type_string(stream->codec->codec_type);
  1062. if (s) print_str ("media_type", s);
  1063. else print_str_opt("media_type", "unknown");
  1064. print_int("key_frame", frame->key_frame);
  1065. print_ts ("pkt_pts", frame->pkt_pts);
  1066. print_time("pkt_pts_time", frame->pkt_pts, &stream->time_base);
  1067. print_ts ("pkt_dts", frame->pkt_dts);
  1068. print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
  1069. if (frame->pkt_pos != -1) print_fmt ("pkt_pos", "%"PRId64, frame->pkt_pos);
  1070. else print_str_opt("pkt_pos", "N/A");
  1071. switch (stream->codec->codec_type) {
  1072. case AVMEDIA_TYPE_VIDEO:
  1073. print_int("width", frame->width);
  1074. print_int("height", frame->height);
  1075. s = av_get_pix_fmt_name(frame->format);
  1076. if (s) print_str ("pix_fmt", s);
  1077. else print_str_opt("pix_fmt", "unknown");
  1078. if (frame->sample_aspect_ratio.num) {
  1079. print_fmt("sample_aspect_ratio", "%d:%d",
  1080. frame->sample_aspect_ratio.num,
  1081. frame->sample_aspect_ratio.den);
  1082. } else {
  1083. print_str_opt("sample_aspect_ratio", "N/A");
  1084. }
  1085. print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
  1086. print_int("coded_picture_number", frame->coded_picture_number);
  1087. print_int("display_picture_number", frame->display_picture_number);
  1088. print_int("interlaced_frame", frame->interlaced_frame);
  1089. print_int("top_field_first", frame->top_field_first);
  1090. print_int("repeat_pict", frame->repeat_pict);
  1091. print_int("reference", frame->reference);
  1092. break;
  1093. case AVMEDIA_TYPE_AUDIO:
  1094. s = av_get_sample_fmt_name(frame->format);
  1095. if (s) print_str ("sample_fmt", s);
  1096. else print_str_opt("sample_fmt", "unknown");
  1097. print_int("nb_samples", frame->nb_samples);
  1098. break;
  1099. }
  1100. print_section_footer("frame");
  1101. av_free(pbuf.s);
  1102. fflush(stdout);
  1103. }
  1104. static av_always_inline int get_decoded_frame(AVFormatContext *fmt_ctx,
  1105. AVFrame *frame, int *got_frame,
  1106. AVPacket *pkt)
  1107. {
  1108. AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  1109. int ret = 0;
  1110. *got_frame = 0;
  1111. switch (dec_ctx->codec_type) {
  1112. case AVMEDIA_TYPE_VIDEO:
  1113. ret = avcodec_decode_video2(dec_ctx, frame, got_frame, pkt);
  1114. break;
  1115. case AVMEDIA_TYPE_AUDIO:
  1116. ret = avcodec_decode_audio4(dec_ctx, frame, got_frame, pkt);
  1117. break;
  1118. }
  1119. return ret;
  1120. }
  1121. static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
  1122. {
  1123. AVPacket pkt, pkt1;
  1124. AVFrame frame;
  1125. int i = 0, ret, got_frame;
  1126. av_init_packet(&pkt);
  1127. while (!av_read_frame(fmt_ctx, &pkt)) {
  1128. if (do_read_packets) {
  1129. if (do_show_packets)
  1130. show_packet(w, fmt_ctx, &pkt, i++);
  1131. nb_streams_packets[pkt.stream_index]++;
  1132. }
  1133. if (do_read_frames) {
  1134. pkt1 = pkt;
  1135. while (pkt1.size) {
  1136. avcodec_get_frame_defaults(&frame);
  1137. ret = get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt1);
  1138. if (ret < 0 || !got_frame)
  1139. break;
  1140. if (do_show_frames)
  1141. show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
  1142. pkt1.data += ret;
  1143. pkt1.size -= ret;
  1144. nb_streams_frames[pkt.stream_index]++;
  1145. }
  1146. }
  1147. av_free_packet(&pkt);
  1148. }
  1149. av_init_packet(&pkt);
  1150. pkt.data = NULL;
  1151. pkt.size = 0;
  1152. //Flush remaining frames that are cached in the decoder
  1153. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1154. pkt.stream_index = i;
  1155. while (get_decoded_frame(fmt_ctx, &frame, &got_frame, &pkt) >= 0 && got_frame) {
  1156. if (do_read_frames) {
  1157. if (do_show_frames)
  1158. show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
  1159. nb_streams_frames[pkt.stream_index]++;
  1160. }
  1161. }
  1162. }
  1163. }
  1164. static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
  1165. {
  1166. AVStream *stream = fmt_ctx->streams[stream_idx];
  1167. AVCodecContext *dec_ctx;
  1168. AVCodec *dec;
  1169. char val_str[128];
  1170. const char *s;
  1171. AVRational display_aspect_ratio;
  1172. struct print_buf pbuf = {.s = NULL};
  1173. print_section_header("stream");
  1174. print_int("index", stream->index);
  1175. if ((dec_ctx = stream->codec)) {
  1176. if ((dec = dec_ctx->codec)) {
  1177. print_str("codec_name", dec->name);
  1178. print_str("codec_long_name", dec->long_name);
  1179. } else {
  1180. print_str_opt("codec_name", "unknown");
  1181. print_str_opt("codec_long_name", "unknown");
  1182. }
  1183. s = av_get_media_type_string(dec_ctx->codec_type);
  1184. if (s) print_str ("codec_type", s);
  1185. else print_str_opt("codec_type", "unknown");
  1186. print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
  1187. /* print AVI/FourCC tag */
  1188. av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
  1189. print_str("codec_tag_string", val_str);
  1190. print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
  1191. switch (dec_ctx->codec_type) {
  1192. case AVMEDIA_TYPE_VIDEO:
  1193. print_int("width", dec_ctx->width);
  1194. print_int("height", dec_ctx->height);
  1195. print_int("has_b_frames", dec_ctx->has_b_frames);
  1196. if (dec_ctx->sample_aspect_ratio.num) {
  1197. print_fmt("sample_aspect_ratio", "%d:%d",
  1198. dec_ctx->sample_aspect_ratio.num,
  1199. dec_ctx->sample_aspect_ratio.den);
  1200. av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
  1201. dec_ctx->width * dec_ctx->sample_aspect_ratio.num,
  1202. dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
  1203. 1024*1024);
  1204. print_fmt("display_aspect_ratio", "%d:%d",
  1205. display_aspect_ratio.num,
  1206. display_aspect_ratio.den);
  1207. } else {
  1208. print_str_opt("sample_aspect_ratio", "N/A");
  1209. print_str_opt("display_aspect_ratio", "N/A");
  1210. }
  1211. s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
  1212. if (s) print_str ("pix_fmt", s);
  1213. else print_str_opt("pix_fmt", "unknown");
  1214. print_int("level", dec_ctx->level);
  1215. if (dec_ctx->timecode_frame_start >= 0) {
  1216. char tcbuf[AV_TIMECODE_STR_SIZE];
  1217. av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
  1218. print_str("timecode", tcbuf);
  1219. } else {
  1220. print_str_opt("timecode", "N/A");
  1221. }
  1222. break;
  1223. case AVMEDIA_TYPE_AUDIO:
  1224. s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
  1225. if (s) print_str ("sample_fmt", s);
  1226. else print_str_opt("sample_fmt", "unknown");
  1227. print_val("sample_rate", dec_ctx->sample_rate, unit_hertz_str);
  1228. print_int("channels", dec_ctx->channels);
  1229. print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
  1230. break;
  1231. }
  1232. } else {
  1233. print_str_opt("codec_type", "unknown");
  1234. }
  1235. if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
  1236. const AVOption *opt = NULL;
  1237. while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
  1238. uint8_t *str;
  1239. if (opt->flags) continue;
  1240. if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
  1241. print_str(opt->name, str);
  1242. av_free(str);
  1243. }
  1244. }
  1245. }
  1246. if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
  1247. else print_str_opt("id", "N/A");
  1248. print_fmt("r_frame_rate", "%d/%d", stream->r_frame_rate.num, stream->r_frame_rate.den);
  1249. print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
  1250. print_fmt("time_base", "%d/%d", stream->time_base.num, stream->time_base.den);
  1251. print_time("start_time", stream->start_time, &stream->time_base);
  1252. print_time("duration", stream->duration, &stream->time_base);
  1253. if (dec_ctx->bit_rate > 0) print_val ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
  1254. else print_str_opt("bit_rate", "N/A");
  1255. if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
  1256. else print_str_opt("nb_frames", "N/A");
  1257. if (nb_streams_frames[stream_idx]) print_fmt ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
  1258. else print_str_opt("nb_read_frames", "N/A");
  1259. if (nb_streams_packets[stream_idx]) print_fmt ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
  1260. else print_str_opt("nb_read_packets", "N/A");
  1261. show_tags(stream->metadata);
  1262. print_section_footer("stream");
  1263. av_free(pbuf.s);
  1264. fflush(stdout);
  1265. }
  1266. static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
  1267. {
  1268. int i;
  1269. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1270. show_stream(w, fmt_ctx, i);
  1271. }
  1272. static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
  1273. {
  1274. char val_str[128];
  1275. int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
  1276. print_section_header("format");
  1277. print_str("filename", fmt_ctx->filename);
  1278. print_int("nb_streams", fmt_ctx->nb_streams);
  1279. print_str("format_name", fmt_ctx->iformat->name);
  1280. print_str("format_long_name", fmt_ctx->iformat->long_name);
  1281. print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
  1282. print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
  1283. if (size >= 0) print_val ("size", size, unit_byte_str);
  1284. else print_str_opt("size", "N/A");
  1285. if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
  1286. else print_str_opt("bit_rate", "N/A");
  1287. show_tags(fmt_ctx->metadata);
  1288. print_section_footer("format");
  1289. fflush(stdout);
  1290. }
  1291. static void show_error(WriterContext *w, int err)
  1292. {
  1293. char errbuf[128];
  1294. const char *errbuf_ptr = errbuf;
  1295. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  1296. errbuf_ptr = strerror(AVUNERROR(err));
  1297. writer_print_chapter_header(w, "error");
  1298. print_section_header("error");
  1299. print_int("code", err);
  1300. print_str("string", errbuf_ptr);
  1301. print_section_footer("error");
  1302. writer_print_chapter_footer(w, "error");
  1303. }
  1304. static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
  1305. {
  1306. int err, i;
  1307. AVFormatContext *fmt_ctx = NULL;
  1308. AVDictionaryEntry *t;
  1309. if ((err = avformat_open_input(&fmt_ctx, filename,
  1310. iformat, &format_opts)) < 0) {
  1311. print_error(filename, err);
  1312. return err;
  1313. }
  1314. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  1315. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  1316. return AVERROR_OPTION_NOT_FOUND;
  1317. }
  1318. /* fill the streams in the format context */
  1319. if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  1320. print_error(filename, err);
  1321. return err;
  1322. }
  1323. av_dump_format(fmt_ctx, 0, filename, 0);
  1324. /* bind a decoder to each input stream */
  1325. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1326. AVStream *stream = fmt_ctx->streams[i];
  1327. AVCodec *codec;
  1328. if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
  1329. av_log(NULL, AV_LOG_ERROR,
  1330. "Unsupported codec with id %d for input stream %d\n",
  1331. stream->codec->codec_id, stream->index);
  1332. } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
  1333. av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
  1334. stream->index);
  1335. }
  1336. }
  1337. *fmt_ctx_ptr = fmt_ctx;
  1338. return 0;
  1339. }
  1340. #define PRINT_CHAPTER(name) do { \
  1341. if (do_show_ ## name) { \
  1342. writer_print_chapter_header(wctx, #name); \
  1343. show_ ## name (wctx, fmt_ctx); \
  1344. writer_print_chapter_footer(wctx, #name); \
  1345. } \
  1346. } while (0)
  1347. static int probe_file(WriterContext *wctx, const char *filename)
  1348. {
  1349. AVFormatContext *fmt_ctx;
  1350. int ret, i;
  1351. do_read_frames = do_show_frames || do_count_frames;
  1352. do_read_packets = do_show_packets || do_count_packets;
  1353. ret = open_input_file(&fmt_ctx, filename);
  1354. if (ret >= 0) {
  1355. nb_streams_frames = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
  1356. nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
  1357. if (do_read_frames || do_read_packets) {
  1358. const char *chapter;
  1359. if (do_show_frames && do_show_packets &&
  1360. wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
  1361. chapter = "packets_and_frames";
  1362. else if (do_show_packets && !do_show_frames)
  1363. chapter = "packets";
  1364. else // (!do_show_packets && do_show_frames)
  1365. chapter = "frames";
  1366. if (do_show_frames || do_show_packets)
  1367. writer_print_chapter_header(wctx, chapter);
  1368. read_packets(wctx, fmt_ctx);
  1369. if (do_show_frames || do_show_packets)
  1370. writer_print_chapter_footer(wctx, chapter);
  1371. }
  1372. PRINT_CHAPTER(streams);
  1373. PRINT_CHAPTER(format);
  1374. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1375. if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
  1376. avcodec_close(fmt_ctx->streams[i]->codec);
  1377. avformat_close_input(&fmt_ctx);
  1378. av_freep(&nb_streams_frames);
  1379. av_freep(&nb_streams_packets);
  1380. }
  1381. return ret;
  1382. }
  1383. static void show_usage(void)
  1384. {
  1385. av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
  1386. av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
  1387. av_log(NULL, AV_LOG_INFO, "\n");
  1388. }
  1389. static void ffprobe_show_program_version(WriterContext *w)
  1390. {
  1391. struct print_buf pbuf = {.s = NULL};
  1392. writer_print_chapter_header(w, "program_version");
  1393. print_section_header("program_version");
  1394. print_str("version", FFMPEG_VERSION);
  1395. print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
  1396. program_birth_year, this_year);
  1397. print_str("build_date", __DATE__);
  1398. print_str("build_time", __TIME__);
  1399. print_str("compiler_type", CC_TYPE);
  1400. print_str("compiler_version", CC_VERSION);
  1401. print_str("configuration", FFMPEG_CONFIGURATION);
  1402. print_section_footer("program_version");
  1403. writer_print_chapter_footer(w, "program_version");
  1404. av_free(pbuf.s);
  1405. }
  1406. #define SHOW_LIB_VERSION(libname, LIBNAME) \
  1407. do { \
  1408. if (CONFIG_##LIBNAME) { \
  1409. unsigned int version = libname##_version(); \
  1410. print_section_header("library_version"); \
  1411. print_str("name", "lib" #libname); \
  1412. print_int("major", LIB##LIBNAME##_VERSION_MAJOR); \
  1413. print_int("minor", LIB##LIBNAME##_VERSION_MINOR); \
  1414. print_int("micro", LIB##LIBNAME##_VERSION_MICRO); \
  1415. print_int("version", version); \
  1416. print_section_footer("library_version"); \
  1417. } \
  1418. } while (0)
  1419. static void ffprobe_show_library_versions(WriterContext *w)
  1420. {
  1421. writer_print_chapter_header(w, "library_versions");
  1422. SHOW_LIB_VERSION(avutil, AVUTIL);
  1423. SHOW_LIB_VERSION(avcodec, AVCODEC);
  1424. SHOW_LIB_VERSION(avformat, AVFORMAT);
  1425. SHOW_LIB_VERSION(avdevice, AVDEVICE);
  1426. SHOW_LIB_VERSION(avfilter, AVFILTER);
  1427. SHOW_LIB_VERSION(swscale, SWSCALE);
  1428. SHOW_LIB_VERSION(swresample, SWRESAMPLE);
  1429. SHOW_LIB_VERSION(postproc, POSTPROC);
  1430. writer_print_chapter_footer(w, "library_versions");
  1431. }
  1432. static int opt_format(const char *opt, const char *arg)
  1433. {
  1434. iformat = av_find_input_format(arg);
  1435. if (!iformat) {
  1436. av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
  1437. return AVERROR(EINVAL);
  1438. }
  1439. return 0;
  1440. }
  1441. static int opt_show_format_entry(const char *opt, const char *arg)
  1442. {
  1443. do_show_format = 1;
  1444. av_dict_set(&fmt_entries_to_show, arg, "", 0);
  1445. return 0;
  1446. }
  1447. static void opt_input_file(void *optctx, const char *arg)
  1448. {
  1449. if (input_filename) {
  1450. av_log(NULL, AV_LOG_ERROR,
  1451. "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  1452. arg, input_filename);
  1453. exit(1);
  1454. }
  1455. if (!strcmp(arg, "-"))
  1456. arg = "pipe:";
  1457. input_filename = arg;
  1458. }
  1459. static int opt_help(const char *opt, const char *arg)
  1460. {
  1461. av_log_set_callback(log_callback_help);
  1462. show_usage();
  1463. show_help_options(options, "Main options:\n", 0, 0);
  1464. printf("\n");
  1465. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  1466. return 0;
  1467. }
  1468. static int opt_pretty(const char *opt, const char *arg)
  1469. {
  1470. show_value_unit = 1;
  1471. use_value_prefix = 1;
  1472. use_byte_value_binary_prefix = 1;
  1473. use_value_sexagesimal_format = 1;
  1474. return 0;
  1475. }
  1476. static int opt_show_versions(const char *opt, const char *arg)
  1477. {
  1478. do_show_program_version = 1;
  1479. do_show_library_versions = 1;
  1480. return 0;
  1481. }
  1482. static const OptionDef options[] = {
  1483. #include "cmdutils_common_opts.h"
  1484. { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
  1485. { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
  1486. { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
  1487. { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
  1488. "use binary prefixes for byte units" },
  1489. { "sexagesimal", OPT_BOOL, {(void*)&use_value_sexagesimal_format},
  1490. "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
  1491. { "pretty", 0, {(void*)&opt_pretty},
  1492. "prettify the format of displayed values, make it more human readable" },
  1493. { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
  1494. "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
  1495. { "show_error", OPT_BOOL, {(void*)&do_show_error} , "show probing error" },
  1496. { "show_format", OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
  1497. { "show_frames", OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
  1498. { "show_format_entry", HAS_ARG, {(void*)opt_show_format_entry},
  1499. "show a particular entry from the format/container info", "entry" },
  1500. { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
  1501. { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
  1502. { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
  1503. { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
  1504. { "show_program_version", OPT_BOOL, {(void*)&do_show_program_version}, "show ffprobe version" },
  1505. { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
  1506. { "show_versions", 0, {(void*)&opt_show_versions}, "show program and library versions" },
  1507. { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
  1508. { "private", OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
  1509. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
  1510. { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
  1511. { NULL, },
  1512. };
  1513. int main(int argc, char **argv)
  1514. {
  1515. const Writer *w;
  1516. WriterContext *wctx;
  1517. char *buf;
  1518. char *w_name = NULL, *w_args = NULL;
  1519. int ret;
  1520. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  1521. parse_loglevel(argc, argv, options);
  1522. av_register_all();
  1523. avformat_network_init();
  1524. init_opts();
  1525. #if CONFIG_AVDEVICE
  1526. avdevice_register_all();
  1527. #endif
  1528. show_banner(argc, argv, options);
  1529. parse_options(NULL, argc, argv, options, opt_input_file);
  1530. writer_register_all();
  1531. if (!print_format)
  1532. print_format = av_strdup("default");
  1533. w_name = av_strtok(print_format, "=", &buf);
  1534. w_args = buf;
  1535. w = writer_get_by_name(w_name);
  1536. if (!w) {
  1537. av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
  1538. ret = AVERROR(EINVAL);
  1539. goto end;
  1540. }
  1541. if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
  1542. writer_print_header(wctx);
  1543. if (do_show_program_version)
  1544. ffprobe_show_program_version(wctx);
  1545. if (do_show_library_versions)
  1546. ffprobe_show_library_versions(wctx);
  1547. if (!input_filename &&
  1548. ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
  1549. (!do_show_program_version && !do_show_library_versions))) {
  1550. show_usage();
  1551. av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
  1552. av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
  1553. ret = AVERROR(EINVAL);
  1554. } else if (input_filename) {
  1555. ret = probe_file(wctx, input_filename);
  1556. if (ret < 0 && do_show_error)
  1557. show_error(wctx, ret);
  1558. }
  1559. writer_print_footer(wctx);
  1560. writer_close(&wctx);
  1561. }
  1562. end:
  1563. av_freep(&print_format);
  1564. avformat_network_deinit();
  1565. return ret;
  1566. }