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.

1539 lines
48KB

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