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.

1782 lines
58KB

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