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.

1243 lines
39KB

  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 Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
  254. static int writer_register(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 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 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 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. /* JSON output */
  575. typedef struct {
  576. int multiple_entries; ///< tells if the given chapter requires multiple entries
  577. char *buf;
  578. size_t buf_size;
  579. } JSONContext;
  580. static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
  581. {
  582. JSONContext *json = wctx->priv;
  583. json->buf_size = ESCAPE_INIT_BUF_SIZE;
  584. if (!(json->buf = av_malloc(json->buf_size)))
  585. return AVERROR(ENOMEM);
  586. return 0;
  587. }
  588. static av_cold void json_uninit(WriterContext *wctx)
  589. {
  590. JSONContext *json = wctx->priv;
  591. av_freep(&json->buf);
  592. }
  593. static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
  594. void *log_ctx)
  595. {
  596. static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
  597. static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
  598. const char *p;
  599. char *q;
  600. size_t size = 1;
  601. // compute the length of the escaped string
  602. for (p = src; *p; p++) {
  603. ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
  604. if (strchr(json_escape, *p)) size += 2; // simple escape
  605. else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
  606. else size += 1; // char copy
  607. }
  608. ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
  609. q = *dst;
  610. for (p = src; *p; p++) {
  611. char *s = strchr(json_escape, *p);
  612. if (s) {
  613. *q++ = '\\';
  614. *q++ = json_subst[s - json_escape];
  615. } else if ((unsigned char)*p < 32) {
  616. snprintf(q, 7, "\\u00%02x", *p & 0xff);
  617. q += 6;
  618. } else {
  619. *q++ = *p;
  620. }
  621. }
  622. *q = 0;
  623. return *dst;
  624. }
  625. static void json_print_header(WriterContext *wctx)
  626. {
  627. printf("{");
  628. }
  629. static void json_print_footer(WriterContext *wctx)
  630. {
  631. printf("\n}\n");
  632. }
  633. static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
  634. {
  635. JSONContext *json = wctx->priv;
  636. if (wctx->nb_chapter)
  637. printf(",");
  638. json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "streams");
  639. printf("\n \"%s\":%s", json_escape_str(&json->buf, &json->buf_size, chapter, wctx),
  640. json->multiple_entries ? " [" : " ");
  641. }
  642. static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
  643. {
  644. JSONContext *json = wctx->priv;
  645. if (json->multiple_entries)
  646. printf("]");
  647. }
  648. static void json_print_section_header(WriterContext *wctx, const char *section)
  649. {
  650. if (wctx->nb_section) printf(",");
  651. printf("{\n");
  652. }
  653. static void json_print_section_footer(WriterContext *wctx, const char *section)
  654. {
  655. printf("\n }");
  656. }
  657. static inline void json_print_item_str(WriterContext *wctx,
  658. const char *key, const char *value,
  659. const char *indent)
  660. {
  661. JSONContext *json = wctx->priv;
  662. printf("%s\"%s\":", indent, json_escape_str(&json->buf, &json->buf_size, key, wctx));
  663. printf(" \"%s\"", json_escape_str(&json->buf, &json->buf_size, value, wctx));
  664. }
  665. #define INDENT " "
  666. static void json_print_str(WriterContext *wctx, const char *key, const char *value)
  667. {
  668. if (wctx->nb_item) printf(",\n");
  669. json_print_item_str(wctx, key, value, INDENT);
  670. }
  671. static void json_print_int(WriterContext *wctx, const char *key, int value)
  672. {
  673. JSONContext *json = wctx->priv;
  674. if (wctx->nb_item) printf(",\n");
  675. printf(INDENT "\"%s\": %d",
  676. json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
  677. }
  678. static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
  679. {
  680. AVDictionaryEntry *tag = NULL;
  681. int is_first = 1;
  682. if (!dict)
  683. return;
  684. printf(",\n" INDENT "\"tags\": {\n");
  685. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  686. if (is_first) is_first = 0;
  687. else printf(",\n");
  688. json_print_item_str(wctx, tag->key, tag->value, INDENT INDENT);
  689. }
  690. printf("\n }");
  691. }
  692. static Writer json_writer = {
  693. .name = "json",
  694. .priv_size = sizeof(JSONContext),
  695. .init = json_init,
  696. .uninit = json_uninit,
  697. .print_header = json_print_header,
  698. .print_footer = json_print_footer,
  699. .print_chapter_header = json_print_chapter_header,
  700. .print_chapter_footer = json_print_chapter_footer,
  701. .print_section_header = json_print_section_header,
  702. .print_section_footer = json_print_section_footer,
  703. .print_integer = json_print_int,
  704. .print_string = json_print_str,
  705. .show_tags = json_show_tags,
  706. };
  707. static void writer_register_all(void)
  708. {
  709. static int initialized;
  710. if (initialized)
  711. return;
  712. initialized = 1;
  713. writer_register(&default_writer);
  714. writer_register(&compact_writer);
  715. writer_register(&json_writer);
  716. }
  717. #define print_fmt(k, f, ...) do { \
  718. if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
  719. writer_print_string(w, k, pbuf.s, 0); \
  720. } while (0)
  721. #define print_fmt_opt(k, f, ...) do { \
  722. if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
  723. writer_print_string(w, k, pbuf.s, 1); \
  724. } while (0)
  725. #define print_int(k, v) writer_print_integer(w, k, v)
  726. #define print_str(k, v) writer_print_string(w, k, v, 0)
  727. #define print_str_opt(k, v) writer_print_string(w, k, v, 1)
  728. #define print_time(k, v, tb) writer_print_time(w, k, v, tb)
  729. #define print_ts(k, v) writer_print_ts(w, k, v)
  730. #define print_val(k, v, u) writer_print_string(w, k, \
  731. value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 1)
  732. #define print_section_header(s) writer_print_section_header(w, s)
  733. #define print_section_footer(s) writer_print_section_footer(w, s)
  734. #define show_tags(metadata) writer_show_tags(w, metadata)
  735. static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
  736. {
  737. char val_str[128];
  738. AVStream *st = fmt_ctx->streams[pkt->stream_index];
  739. struct print_buf pbuf = {.s = NULL};
  740. const char *s;
  741. print_section_header("packet");
  742. s = av_get_media_type_string(st->codec->codec_type);
  743. if (s) print_str ("codec_type", s);
  744. else print_str_opt("codec_type", "unknown");
  745. print_int("stream_index", pkt->stream_index);
  746. print_ts ("pts", pkt->pts);
  747. print_time("pts_time", pkt->pts, &st->time_base);
  748. print_ts ("dts", pkt->dts);
  749. print_time("dts_time", pkt->dts, &st->time_base);
  750. print_ts ("duration", pkt->duration);
  751. print_time("duration_time", pkt->duration, &st->time_base);
  752. print_val("size", pkt->size, unit_byte_str);
  753. if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
  754. else print_str_opt("pos", "N/A");
  755. print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
  756. print_section_footer("packet");
  757. av_free(pbuf.s);
  758. fflush(stdout);
  759. }
  760. static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
  761. {
  762. AVPacket pkt;
  763. int i = 0;
  764. av_init_packet(&pkt);
  765. while (!av_read_frame(fmt_ctx, &pkt))
  766. show_packet(w, fmt_ctx, &pkt, i++);
  767. }
  768. static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
  769. {
  770. AVStream *stream = fmt_ctx->streams[stream_idx];
  771. AVCodecContext *dec_ctx;
  772. AVCodec *dec;
  773. char val_str[128];
  774. const char *s;
  775. AVRational display_aspect_ratio;
  776. struct print_buf pbuf = {.s = NULL};
  777. print_section_header("stream");
  778. print_int("index", stream->index);
  779. if ((dec_ctx = stream->codec)) {
  780. if ((dec = dec_ctx->codec)) {
  781. print_str("codec_name", dec->name);
  782. print_str("codec_long_name", dec->long_name);
  783. } else {
  784. print_str_opt("codec_name", "unknown");
  785. print_str_opt("codec_long_name", "unknown");
  786. }
  787. s = av_get_media_type_string(dec_ctx->codec_type);
  788. if (s) print_str ("codec_type", s);
  789. else print_str_opt("codec_type", "unknown");
  790. print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
  791. /* print AVI/FourCC tag */
  792. av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
  793. print_str("codec_tag_string", val_str);
  794. print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
  795. switch (dec_ctx->codec_type) {
  796. case AVMEDIA_TYPE_VIDEO:
  797. print_int("width", dec_ctx->width);
  798. print_int("height", dec_ctx->height);
  799. print_int("has_b_frames", dec_ctx->has_b_frames);
  800. if (dec_ctx->sample_aspect_ratio.num) {
  801. print_fmt("sample_aspect_ratio", "%d:%d",
  802. dec_ctx->sample_aspect_ratio.num,
  803. dec_ctx->sample_aspect_ratio.den);
  804. av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
  805. dec_ctx->width * dec_ctx->sample_aspect_ratio.num,
  806. dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
  807. 1024*1024);
  808. print_fmt("display_aspect_ratio", "%d:%d",
  809. display_aspect_ratio.num,
  810. display_aspect_ratio.den);
  811. } else {
  812. print_str_opt("sample_aspect_ratio", "N/A");
  813. print_str_opt("display_aspect_ratio", "N/A");
  814. }
  815. s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
  816. if (s) print_str ("pix_fmt", s);
  817. else print_str_opt("pix_fmt", "unknown");
  818. print_int("level", dec_ctx->level);
  819. break;
  820. case AVMEDIA_TYPE_AUDIO:
  821. s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
  822. if (s) print_str ("sample_fmt", s);
  823. else print_str_opt("sample_fmt", "unknown");
  824. print_val("sample_rate", dec_ctx->sample_rate, unit_hertz_str);
  825. print_int("channels", dec_ctx->channels);
  826. print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
  827. break;
  828. }
  829. } else {
  830. print_str_opt("codec_type", "unknown");
  831. }
  832. if (dec_ctx->codec && dec_ctx->codec->priv_class) {
  833. const AVOption *opt = NULL;
  834. while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
  835. uint8_t *str;
  836. if (opt->flags) continue;
  837. if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
  838. print_str(opt->name, str);
  839. av_free(str);
  840. }
  841. }
  842. }
  843. if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
  844. else print_str_opt("id", "N/A");
  845. print_fmt("r_frame_rate", "%d/%d", stream->r_frame_rate.num, stream->r_frame_rate.den);
  846. print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
  847. print_fmt("time_base", "%d/%d", stream->time_base.num, stream->time_base.den);
  848. print_time("start_time", stream->start_time, &stream->time_base);
  849. print_time("duration", stream->duration, &stream->time_base);
  850. if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
  851. else print_str_opt("nb_frames", "N/A");
  852. show_tags(stream->metadata);
  853. print_section_footer("stream");
  854. av_free(pbuf.s);
  855. fflush(stdout);
  856. }
  857. static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
  858. {
  859. int i;
  860. for (i = 0; i < fmt_ctx->nb_streams; i++)
  861. show_stream(w, fmt_ctx, i);
  862. }
  863. static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
  864. {
  865. char val_str[128];
  866. int64_t size = avio_size(fmt_ctx->pb);
  867. struct print_buf pbuf = {.s = NULL};
  868. print_section_header("format");
  869. print_str("filename", fmt_ctx->filename);
  870. print_int("nb_streams", fmt_ctx->nb_streams);
  871. print_str("format_name", fmt_ctx->iformat->name);
  872. print_str("format_long_name", fmt_ctx->iformat->long_name);
  873. print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
  874. print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
  875. if (size >= 0) print_val ("size", size, unit_byte_str);
  876. else print_str_opt("size", "N/A");
  877. if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
  878. else print_str_opt("bit_rate", "N/A");
  879. show_tags(fmt_ctx->metadata);
  880. print_section_footer("format");
  881. av_free(pbuf.s);
  882. fflush(stdout);
  883. }
  884. static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
  885. {
  886. int err, i;
  887. AVFormatContext *fmt_ctx = NULL;
  888. AVDictionaryEntry *t;
  889. if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
  890. print_error(filename, err);
  891. return err;
  892. }
  893. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  894. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  895. return AVERROR_OPTION_NOT_FOUND;
  896. }
  897. /* fill the streams in the format context */
  898. if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  899. print_error(filename, err);
  900. return err;
  901. }
  902. av_dump_format(fmt_ctx, 0, filename, 0);
  903. /* bind a decoder to each input stream */
  904. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  905. AVStream *stream = fmt_ctx->streams[i];
  906. AVCodec *codec;
  907. if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
  908. fprintf(stderr, "Unsupported codec with id %d for input stream %d\n",
  909. stream->codec->codec_id, stream->index);
  910. } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
  911. fprintf(stderr, "Error while opening codec for input stream %d\n",
  912. stream->index);
  913. }
  914. }
  915. *fmt_ctx_ptr = fmt_ctx;
  916. return 0;
  917. }
  918. #define PRINT_CHAPTER(name) do { \
  919. if (do_show_ ## name) { \
  920. writer_print_chapter_header(wctx, #name); \
  921. show_ ## name (wctx, fmt_ctx); \
  922. writer_print_chapter_footer(wctx, #name); \
  923. } \
  924. } while (0)
  925. static int probe_file(const char *filename)
  926. {
  927. AVFormatContext *fmt_ctx;
  928. int ret;
  929. Writer *w;
  930. char *buf;
  931. char *w_name = NULL, *w_args = NULL;
  932. WriterContext *wctx;
  933. writer_register_all();
  934. if (!print_format)
  935. print_format = av_strdup("default");
  936. w_name = av_strtok(print_format, "=", &buf);
  937. w_args = buf;
  938. w = writer_get_by_name(w_name);
  939. if (!w) {
  940. av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
  941. ret = AVERROR(EINVAL);
  942. goto end;
  943. }
  944. if ((ret = writer_open(&wctx, w, w_args, NULL)) < 0)
  945. goto end;
  946. if ((ret = open_input_file(&fmt_ctx, filename)))
  947. goto end;
  948. writer_print_header(wctx);
  949. PRINT_CHAPTER(packets);
  950. PRINT_CHAPTER(streams);
  951. PRINT_CHAPTER(format);
  952. writer_print_footer(wctx);
  953. av_close_input_file(fmt_ctx);
  954. writer_close(&wctx);
  955. end:
  956. av_freep(&print_format);
  957. return ret;
  958. }
  959. static void show_usage(void)
  960. {
  961. printf("Simple multimedia streams analyzer\n");
  962. printf("usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
  963. printf("\n");
  964. }
  965. static int opt_format(const char *opt, const char *arg)
  966. {
  967. iformat = av_find_input_format(arg);
  968. if (!iformat) {
  969. fprintf(stderr, "Unknown input format: %s\n", arg);
  970. return AVERROR(EINVAL);
  971. }
  972. return 0;
  973. }
  974. static void opt_input_file(void *optctx, const char *arg)
  975. {
  976. if (input_filename) {
  977. fprintf(stderr, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  978. arg, input_filename);
  979. exit(1);
  980. }
  981. if (!strcmp(arg, "-"))
  982. arg = "pipe:";
  983. input_filename = arg;
  984. }
  985. static int opt_help(const char *opt, const char *arg)
  986. {
  987. av_log_set_callback(log_callback_help);
  988. show_usage();
  989. show_help_options(options, "Main options:\n", 0, 0);
  990. printf("\n");
  991. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  992. return 0;
  993. }
  994. static int opt_pretty(const char *opt, const char *arg)
  995. {
  996. show_value_unit = 1;
  997. use_value_prefix = 1;
  998. use_byte_value_binary_prefix = 1;
  999. use_value_sexagesimal_format = 1;
  1000. return 0;
  1001. }
  1002. static const OptionDef options[] = {
  1003. #include "cmdutils_common_opts.h"
  1004. { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
  1005. { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
  1006. { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
  1007. { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
  1008. "use binary prefixes for byte units" },
  1009. { "sexagesimal", OPT_BOOL, {(void*)&use_value_sexagesimal_format},
  1010. "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
  1011. { "pretty", 0, {(void*)&opt_pretty},
  1012. "prettify the format of displayed values, make it more human readable" },
  1013. { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format}, "set the output printing format (available formats are: default, compact, json)", "format" },
  1014. { "show_format", OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
  1015. { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
  1016. { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
  1017. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
  1018. { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
  1019. { NULL, },
  1020. };
  1021. int main(int argc, char **argv)
  1022. {
  1023. int ret;
  1024. parse_loglevel(argc, argv, options);
  1025. av_register_all();
  1026. avformat_network_init();
  1027. init_opts();
  1028. #if CONFIG_AVDEVICE
  1029. avdevice_register_all();
  1030. #endif
  1031. show_banner();
  1032. parse_options(NULL, argc, argv, options, opt_input_file);
  1033. if (!input_filename) {
  1034. show_usage();
  1035. fprintf(stderr, "You have to specify one input file.\n");
  1036. fprintf(stderr, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
  1037. exit(1);
  1038. }
  1039. ret = probe_file(input_filename);
  1040. avformat_network_deinit();
  1041. return ret;
  1042. }