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.

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