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.

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