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.

1278 lines
40KB

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