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.

1675 lines
54KB

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