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.

1263 lines
40KB

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