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.

1679 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. if (src[i] >= 'a' && src[i] <= 'z') {
  348. dst[i] = src[i]-32;
  349. } else {
  350. dst[i] = src[i];
  351. }
  352. dst[i] = 0;
  353. return dst;
  354. }
  355. static void default_print_section_header(WriterContext *wctx, const char *section)
  356. {
  357. char buf[32];
  358. if (wctx->nb_section)
  359. printf("\n");
  360. printf("[%s]\n", upcase_string(buf, sizeof(buf), section));
  361. }
  362. static void default_print_section_footer(WriterContext *wctx, const char *section)
  363. {
  364. char buf[32];
  365. printf("[/%s]", upcase_string(buf, sizeof(buf), section));
  366. }
  367. static void default_print_str(WriterContext *wctx, const char *key, const char *value)
  368. {
  369. printf("%s=%s\n", key, value);
  370. }
  371. static void default_print_int(WriterContext *wctx, const char *key, long long int value)
  372. {
  373. printf("%s=%lld\n", key, value);
  374. }
  375. static void default_show_tags(WriterContext *wctx, AVDictionary *dict)
  376. {
  377. AVDictionaryEntry *tag = NULL;
  378. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  379. printf("TAG:");
  380. writer_print_string(wctx, tag->key, tag->value, 0);
  381. }
  382. }
  383. static const Writer default_writer = {
  384. .name = "default",
  385. .print_footer = default_print_footer,
  386. .print_chapter_header = default_print_chapter_header,
  387. .print_section_header = default_print_section_header,
  388. .print_section_footer = default_print_section_footer,
  389. .print_integer = default_print_int,
  390. .print_string = default_print_str,
  391. .show_tags = default_show_tags,
  392. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  393. };
  394. /* Compact output */
  395. /**
  396. * Escape \n, \r, \\ and sep characters contained in s, and print the
  397. * resulting string.
  398. */
  399. static const char *c_escape_str(char **dst, size_t *dst_size,
  400. const char *src, const char sep, void *log_ctx)
  401. {
  402. const char *p;
  403. char *q;
  404. size_t size = 1;
  405. /* precompute size */
  406. for (p = src; *p; p++, size++) {
  407. ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-2);
  408. if (*p == '\n' || *p == '\r' || *p == '\\')
  409. size++;
  410. }
  411. ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
  412. q = *dst;
  413. for (p = src; *p; p++) {
  414. switch (*src) {
  415. case '\n': *q++ = '\\'; *q++ = 'n'; break;
  416. case '\r': *q++ = '\\'; *q++ = 'r'; break;
  417. case '\\': *q++ = '\\'; *q++ = '\\'; break;
  418. default:
  419. if (*p == sep)
  420. *q++ = '\\';
  421. *q++ = *p;
  422. }
  423. }
  424. *q = 0;
  425. return *dst;
  426. }
  427. /**
  428. * Quote fields containing special characters, check RFC4180.
  429. */
  430. static const char *csv_escape_str(char **dst, size_t *dst_size,
  431. const char *src, const char sep, void *log_ctx)
  432. {
  433. const char *p;
  434. char *q;
  435. size_t size = 1;
  436. int quote = 0;
  437. /* precompute size */
  438. for (p = src; *p; p++, size++) {
  439. ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-4);
  440. if (*p == '"' || *p == sep || *p == '\n' || *p == '\r')
  441. if (!quote) {
  442. quote = 1;
  443. size += 2;
  444. }
  445. if (*p == '"')
  446. size++;
  447. }
  448. ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
  449. q = *dst;
  450. p = src;
  451. if (quote)
  452. *q++ = '\"';
  453. while (*p) {
  454. if (*p == '"')
  455. *q++ = '\"';
  456. *q++ = *p++;
  457. }
  458. if (quote)
  459. *q++ = '\"';
  460. *q = 0;
  461. return *dst;
  462. }
  463. static const char *none_escape_str(char **dst, size_t *dst_size,
  464. const char *src, const char sep, void *log_ctx)
  465. {
  466. return src;
  467. }
  468. typedef struct CompactContext {
  469. const AVClass *class;
  470. char *item_sep_str;
  471. char item_sep;
  472. int nokey;
  473. char *buf;
  474. size_t buf_size;
  475. char *escape_mode_str;
  476. const char * (*escape_str)(char **dst, size_t *dst_size,
  477. const char *src, const char sep, void *log_ctx);
  478. } CompactContext;
  479. #define OFFSET(x) offsetof(CompactContext, x)
  480. static const AVOption compact_options[]= {
  481. {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  482. {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  483. {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  484. {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  485. {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  486. {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  487. {NULL},
  488. };
  489. static const char *compact_get_name(void *ctx)
  490. {
  491. return "compact";
  492. }
  493. static const AVClass compact_class = {
  494. "CompactContext",
  495. compact_get_name,
  496. compact_options
  497. };
  498. static av_cold int compact_init(WriterContext *wctx, const char *args, void *opaque)
  499. {
  500. CompactContext *compact = wctx->priv;
  501. int err;
  502. compact->class = &compact_class;
  503. av_opt_set_defaults(compact);
  504. if (args &&
  505. (err = (av_set_options_string(compact, args, "=", ":"))) < 0) {
  506. av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  507. return err;
  508. }
  509. if (strlen(compact->item_sep_str) != 1) {
  510. av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
  511. compact->item_sep_str);
  512. return AVERROR(EINVAL);
  513. }
  514. compact->item_sep = compact->item_sep_str[0];
  515. compact->buf_size = ESCAPE_INIT_BUF_SIZE;
  516. if (!(compact->buf = av_malloc(compact->buf_size)))
  517. return AVERROR(ENOMEM);
  518. if (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
  519. else if (!strcmp(compact->escape_mode_str, "c" )) compact->escape_str = c_escape_str;
  520. else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
  521. else {
  522. av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
  523. return AVERROR(EINVAL);
  524. }
  525. return 0;
  526. }
  527. static av_cold void compact_uninit(WriterContext *wctx)
  528. {
  529. CompactContext *compact = wctx->priv;
  530. av_freep(&compact->item_sep_str);
  531. av_freep(&compact->buf);
  532. av_freep(&compact->escape_mode_str);
  533. }
  534. static void compact_print_section_header(WriterContext *wctx, const char *section)
  535. {
  536. CompactContext *compact = wctx->priv;
  537. printf("%s%c", section, compact->item_sep);
  538. }
  539. static void compact_print_section_footer(WriterContext *wctx, const char *section)
  540. {
  541. printf("\n");
  542. }
  543. static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
  544. {
  545. CompactContext *compact = wctx->priv;
  546. if (wctx->nb_item) printf("%c", compact->item_sep);
  547. if (!compact->nokey)
  548. printf("%s=", key);
  549. printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
  550. value, compact->item_sep, wctx));
  551. }
  552. static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
  553. {
  554. CompactContext *compact = wctx->priv;
  555. if (wctx->nb_item) printf("%c", compact->item_sep);
  556. if (!compact->nokey)
  557. printf("%s=", key);
  558. printf("%lld", value);
  559. }
  560. static void compact_show_tags(WriterContext *wctx, AVDictionary *dict)
  561. {
  562. CompactContext *compact = wctx->priv;
  563. AVDictionaryEntry *tag = NULL;
  564. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  565. if (wctx->nb_item) printf("%c", compact->item_sep);
  566. if (!compact->nokey)
  567. printf("tag:%s=", compact->escape_str(&compact->buf, &compact->buf_size,
  568. tag->key, compact->item_sep, wctx));
  569. printf("%s", compact->escape_str(&compact->buf, &compact->buf_size,
  570. tag->value, compact->item_sep, wctx));
  571. }
  572. }
  573. static const Writer compact_writer = {
  574. .name = "compact",
  575. .priv_size = sizeof(CompactContext),
  576. .init = compact_init,
  577. .uninit = compact_uninit,
  578. .print_section_header = compact_print_section_header,
  579. .print_section_footer = compact_print_section_footer,
  580. .print_integer = compact_print_int,
  581. .print_string = compact_print_str,
  582. .show_tags = compact_show_tags,
  583. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  584. };
  585. /* CSV output */
  586. static av_cold int csv_init(WriterContext *wctx, const char *args, void *opaque)
  587. {
  588. return compact_init(wctx, "item_sep=,:nokey=1:escape=csv", opaque);
  589. }
  590. static const Writer csv_writer = {
  591. .name = "csv",
  592. .priv_size = sizeof(CompactContext),
  593. .init = csv_init,
  594. .uninit = compact_uninit,
  595. .print_section_header = compact_print_section_header,
  596. .print_section_footer = compact_print_section_footer,
  597. .print_integer = compact_print_int,
  598. .print_string = compact_print_str,
  599. .show_tags = compact_show_tags,
  600. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  601. };
  602. /* JSON output */
  603. typedef struct {
  604. int multiple_entries; ///< tells if the given chapter requires multiple entries
  605. char *buf;
  606. size_t buf_size;
  607. int print_packets_and_frames;
  608. int indent_level;
  609. } JSONContext;
  610. static av_cold int json_init(WriterContext *wctx, const char *args, void *opaque)
  611. {
  612. JSONContext *json = wctx->priv;
  613. json->buf_size = ESCAPE_INIT_BUF_SIZE;
  614. if (!(json->buf = av_malloc(json->buf_size)))
  615. return AVERROR(ENOMEM);
  616. return 0;
  617. }
  618. static av_cold void json_uninit(WriterContext *wctx)
  619. {
  620. JSONContext *json = wctx->priv;
  621. av_freep(&json->buf);
  622. }
  623. static const char *json_escape_str(char **dst, size_t *dst_size, const char *src,
  624. void *log_ctx)
  625. {
  626. static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
  627. static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
  628. const char *p;
  629. char *q;
  630. size_t size = 1;
  631. // compute the length of the escaped string
  632. for (p = src; *p; p++) {
  633. ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-6);
  634. if (strchr(json_escape, *p)) size += 2; // simple escape
  635. else if ((unsigned char)*p < 32) size += 6; // handle non-printable chars
  636. else size += 1; // char copy
  637. }
  638. ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
  639. q = *dst;
  640. for (p = src; *p; p++) {
  641. char *s = strchr(json_escape, *p);
  642. if (s) {
  643. *q++ = '\\';
  644. *q++ = json_subst[s - json_escape];
  645. } else if ((unsigned char)*p < 32) {
  646. snprintf(q, 7, "\\u00%02x", *p & 0xff);
  647. q += 6;
  648. } else {
  649. *q++ = *p;
  650. }
  651. }
  652. *q = 0;
  653. return *dst;
  654. }
  655. static void json_print_header(WriterContext *wctx)
  656. {
  657. JSONContext *json = wctx->priv;
  658. printf("{");
  659. json->indent_level++;
  660. }
  661. static void json_print_footer(WriterContext *wctx)
  662. {
  663. JSONContext *json = wctx->priv;
  664. json->indent_level--;
  665. printf("\n}\n");
  666. }
  667. #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
  668. static void json_print_chapter_header(WriterContext *wctx, const char *chapter)
  669. {
  670. JSONContext *json = wctx->priv;
  671. if (wctx->nb_chapter)
  672. printf(",");
  673. printf("\n");
  674. json->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames" ) ||
  675. !strcmp(chapter, "packets_and_frames") ||
  676. !strcmp(chapter, "streams");
  677. if (json->multiple_entries) {
  678. JSON_INDENT();
  679. printf("\"%s\": [\n", json_escape_str(&json->buf, &json->buf_size, chapter, wctx));
  680. json->print_packets_and_frames = !strcmp(chapter, "packets_and_frames");
  681. json->indent_level++;
  682. }
  683. }
  684. static void json_print_chapter_footer(WriterContext *wctx, const char *chapter)
  685. {
  686. JSONContext *json = wctx->priv;
  687. if (json->multiple_entries) {
  688. printf("\n");
  689. json->indent_level--;
  690. JSON_INDENT();
  691. printf("]");
  692. }
  693. }
  694. static void json_print_section_header(WriterContext *wctx, const char *section)
  695. {
  696. JSONContext *json = wctx->priv;
  697. if (wctx->nb_section)
  698. printf(",\n");
  699. JSON_INDENT();
  700. if (!json->multiple_entries)
  701. printf("\"%s\": ", section);
  702. printf("{\n");
  703. json->indent_level++;
  704. /* this is required so the parser can distinguish between packets and frames */
  705. if (json->print_packets_and_frames) {
  706. JSON_INDENT(); printf("\"type\": \"%s\",\n", section);
  707. }
  708. }
  709. static void json_print_section_footer(WriterContext *wctx, const char *section)
  710. {
  711. JSONContext *json = wctx->priv;
  712. printf("\n");
  713. json->indent_level--;
  714. JSON_INDENT(); printf("}");
  715. }
  716. static inline void json_print_item_str(WriterContext *wctx,
  717. const char *key, const char *value)
  718. {
  719. JSONContext *json = wctx->priv;
  720. JSON_INDENT();
  721. printf("\"%s\":", json_escape_str(&json->buf, &json->buf_size, key, wctx));
  722. printf(" \"%s\"", json_escape_str(&json->buf, &json->buf_size, value, wctx));
  723. }
  724. static void json_print_str(WriterContext *wctx, const char *key, const char *value)
  725. {
  726. if (wctx->nb_item) printf(",\n");
  727. json_print_item_str(wctx, key, value);
  728. }
  729. static void json_print_int(WriterContext *wctx, const char *key, long long int value)
  730. {
  731. JSONContext *json = wctx->priv;
  732. if (wctx->nb_item) printf(",\n");
  733. JSON_INDENT();
  734. printf("\"%s\": %lld",
  735. json_escape_str(&json->buf, &json->buf_size, key, wctx), value);
  736. }
  737. static void json_show_tags(WriterContext *wctx, AVDictionary *dict)
  738. {
  739. JSONContext *json = wctx->priv;
  740. AVDictionaryEntry *tag = NULL;
  741. int is_first = 1;
  742. if (!dict)
  743. return;
  744. printf(",\n"); JSON_INDENT(); printf("\"tags\": {\n");
  745. json->indent_level++;
  746. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  747. if (is_first) is_first = 0;
  748. else printf(",\n");
  749. json_print_item_str(wctx, tag->key, tag->value);
  750. }
  751. json->indent_level--;
  752. printf("\n"); JSON_INDENT(); printf("}");
  753. }
  754. static const Writer json_writer = {
  755. .name = "json",
  756. .priv_size = sizeof(JSONContext),
  757. .init = json_init,
  758. .uninit = json_uninit,
  759. .print_header = json_print_header,
  760. .print_footer = json_print_footer,
  761. .print_chapter_header = json_print_chapter_header,
  762. .print_chapter_footer = json_print_chapter_footer,
  763. .print_section_header = json_print_section_header,
  764. .print_section_footer = json_print_section_footer,
  765. .print_integer = json_print_int,
  766. .print_string = json_print_str,
  767. .show_tags = json_show_tags,
  768. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  769. };
  770. /* XML output */
  771. typedef struct {
  772. const AVClass *class;
  773. int within_tag;
  774. int multiple_entries; ///< tells if the given chapter requires multiple entries
  775. int indent_level;
  776. int fully_qualified;
  777. int xsd_strict;
  778. char *buf;
  779. size_t buf_size;
  780. } XMLContext;
  781. #undef OFFSET
  782. #define OFFSET(x) offsetof(XMLContext, x)
  783. static const AVOption xml_options[] = {
  784. {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  785. {"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  786. {"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  787. {"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  788. {NULL},
  789. };
  790. static const char *xml_get_name(void *ctx)
  791. {
  792. return "xml";
  793. }
  794. static const AVClass xml_class = {
  795. "XMLContext",
  796. xml_get_name,
  797. xml_options
  798. };
  799. static av_cold int xml_init(WriterContext *wctx, const char *args, void *opaque)
  800. {
  801. XMLContext *xml = wctx->priv;
  802. int err;
  803. xml->class = &xml_class;
  804. av_opt_set_defaults(xml);
  805. if (args &&
  806. (err = (av_set_options_string(xml, args, "=", ":"))) < 0) {
  807. av_log(wctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  808. return err;
  809. }
  810. if (xml->xsd_strict) {
  811. xml->fully_qualified = 1;
  812. #define CHECK_COMPLIANCE(opt, opt_name) \
  813. if (opt) { \
  814. av_log(wctx, AV_LOG_ERROR, \
  815. "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
  816. "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
  817. return AVERROR(EINVAL); \
  818. }
  819. CHECK_COMPLIANCE(show_private_data, "private");
  820. CHECK_COMPLIANCE(show_value_unit, "unit");
  821. CHECK_COMPLIANCE(use_value_prefix, "prefix");
  822. if (do_show_frames && do_show_packets) {
  823. av_log(wctx, AV_LOG_ERROR,
  824. "Interleaved frames and packets are not allowed in XSD. "
  825. "Select only one between the -show_frames and the -show_packets options.\n");
  826. return AVERROR(EINVAL);
  827. }
  828. }
  829. xml->buf_size = ESCAPE_INIT_BUF_SIZE;
  830. if (!(xml->buf = av_malloc(xml->buf_size)))
  831. return AVERROR(ENOMEM);
  832. return 0;
  833. }
  834. static av_cold void xml_uninit(WriterContext *wctx)
  835. {
  836. XMLContext *xml = wctx->priv;
  837. av_freep(&xml->buf);
  838. }
  839. static const char *xml_escape_str(char **dst, size_t *dst_size, const char *src,
  840. void *log_ctx)
  841. {
  842. const char *p;
  843. char *q;
  844. size_t size = 1;
  845. /* precompute size */
  846. for (p = src; *p; p++, size++) {
  847. ESCAPE_CHECK_SIZE(src, size, SIZE_MAX-10);
  848. switch (*p) {
  849. case '&' : size += strlen("&amp;"); break;
  850. case '<' : size += strlen("&lt;"); break;
  851. case '>' : size += strlen("&gt;"); break;
  852. case '\"': size += strlen("&quot;"); break;
  853. case '\'': size += strlen("&apos;"); break;
  854. default: size++;
  855. }
  856. }
  857. ESCAPE_REALLOC_BUF(dst_size, dst, src, size);
  858. #define COPY_STR(str) { \
  859. const char *s = str; \
  860. while (*s) \
  861. *q++ = *s++; \
  862. }
  863. p = src;
  864. q = *dst;
  865. while (*p) {
  866. switch (*p) {
  867. case '&' : COPY_STR("&amp;"); break;
  868. case '<' : COPY_STR("&lt;"); break;
  869. case '>' : COPY_STR("&gt;"); break;
  870. case '\"': COPY_STR("&quot;"); break;
  871. case '\'': COPY_STR("&apos;"); break;
  872. default: *q++ = *p;
  873. }
  874. p++;
  875. }
  876. *q = 0;
  877. return *dst;
  878. }
  879. static void xml_print_header(WriterContext *wctx)
  880. {
  881. XMLContext *xml = wctx->priv;
  882. const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
  883. "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
  884. "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
  885. printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  886. printf("<%sffprobe%s>\n",
  887. xml->fully_qualified ? "ffprobe:" : "",
  888. xml->fully_qualified ? qual : "");
  889. xml->indent_level++;
  890. }
  891. static void xml_print_footer(WriterContext *wctx)
  892. {
  893. XMLContext *xml = wctx->priv;
  894. xml->indent_level--;
  895. printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
  896. }
  897. #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
  898. static void xml_print_chapter_header(WriterContext *wctx, const char *chapter)
  899. {
  900. XMLContext *xml = wctx->priv;
  901. if (wctx->nb_chapter)
  902. printf("\n");
  903. xml->multiple_entries = !strcmp(chapter, "packets") || !strcmp(chapter, "frames") ||
  904. !strcmp(chapter, "packets_and_frames") ||
  905. !strcmp(chapter, "streams");
  906. if (xml->multiple_entries) {
  907. XML_INDENT(); printf("<%s>\n", chapter);
  908. xml->indent_level++;
  909. }
  910. }
  911. static void xml_print_chapter_footer(WriterContext *wctx, const char *chapter)
  912. {
  913. XMLContext *xml = wctx->priv;
  914. if (xml->multiple_entries) {
  915. xml->indent_level--;
  916. XML_INDENT(); printf("</%s>\n", chapter);
  917. }
  918. }
  919. static void xml_print_section_header(WriterContext *wctx, const char *section)
  920. {
  921. XMLContext *xml = wctx->priv;
  922. XML_INDENT(); printf("<%s ", section);
  923. xml->within_tag = 1;
  924. }
  925. static void xml_print_section_footer(WriterContext *wctx, const char *section)
  926. {
  927. XMLContext *xml = wctx->priv;
  928. if (xml->within_tag)
  929. printf("/>\n");
  930. else {
  931. XML_INDENT(); printf("</%s>\n", section);
  932. }
  933. }
  934. static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
  935. {
  936. XMLContext *xml = wctx->priv;
  937. if (wctx->nb_item)
  938. printf(" ");
  939. printf("%s=\"%s\"", key, xml_escape_str(&xml->buf, &xml->buf_size, value, wctx));
  940. }
  941. static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
  942. {
  943. if (wctx->nb_item)
  944. printf(" ");
  945. printf("%s=\"%lld\"", key, value);
  946. }
  947. static void xml_show_tags(WriterContext *wctx, AVDictionary *dict)
  948. {
  949. XMLContext *xml = wctx->priv;
  950. AVDictionaryEntry *tag = NULL;
  951. int is_first = 1;
  952. xml->indent_level++;
  953. while ((tag = av_dict_get(dict, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  954. if (is_first) {
  955. /* close section tag */
  956. printf(">\n");
  957. xml->within_tag = 0;
  958. is_first = 0;
  959. }
  960. XML_INDENT();
  961. printf("<tag key=\"%s\"",
  962. xml_escape_str(&xml->buf, &xml->buf_size, tag->key, wctx));
  963. printf(" value=\"%s\"/>\n",
  964. xml_escape_str(&xml->buf, &xml->buf_size, tag->value, wctx));
  965. }
  966. xml->indent_level--;
  967. }
  968. static Writer xml_writer = {
  969. .name = "xml",
  970. .priv_size = sizeof(XMLContext),
  971. .init = xml_init,
  972. .uninit = xml_uninit,
  973. .print_header = xml_print_header,
  974. .print_footer = xml_print_footer,
  975. .print_chapter_header = xml_print_chapter_header,
  976. .print_chapter_footer = xml_print_chapter_footer,
  977. .print_section_header = xml_print_section_header,
  978. .print_section_footer = xml_print_section_footer,
  979. .print_integer = xml_print_int,
  980. .print_string = xml_print_str,
  981. .show_tags = xml_show_tags,
  982. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  983. };
  984. static void writer_register_all(void)
  985. {
  986. static int initialized;
  987. if (initialized)
  988. return;
  989. initialized = 1;
  990. writer_register(&default_writer);
  991. writer_register(&compact_writer);
  992. writer_register(&csv_writer);
  993. writer_register(&json_writer);
  994. writer_register(&xml_writer);
  995. }
  996. #define print_fmt(k, f, ...) do { \
  997. if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
  998. writer_print_string(w, k, pbuf.s, 0); \
  999. } while (0)
  1000. #define print_fmt_opt(k, f, ...) do { \
  1001. if (fast_asprintf(&pbuf, f, __VA_ARGS__)) \
  1002. writer_print_string(w, k, pbuf.s, 1); \
  1003. } while (0)
  1004. #define print_int(k, v) writer_print_integer(w, k, v)
  1005. #define print_str(k, v) writer_print_string(w, k, v, 0)
  1006. #define print_str_opt(k, v) writer_print_string(w, k, v, 1)
  1007. #define print_time(k, v, tb) writer_print_time(w, k, v, tb)
  1008. #define print_ts(k, v) writer_print_ts(w, k, v)
  1009. #define print_val(k, v, u) writer_print_string(w, k, \
  1010. value_string(val_str, sizeof(val_str), (struct unit_value){.val.i = v, .unit=u}), 0)
  1011. #define print_section_header(s) writer_print_section_header(w, s)
  1012. #define print_section_footer(s) writer_print_section_footer(w, s)
  1013. #define show_tags(metadata) writer_show_tags(w, metadata)
  1014. static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
  1015. {
  1016. char val_str[128];
  1017. AVStream *st = fmt_ctx->streams[pkt->stream_index];
  1018. struct print_buf pbuf = {.s = NULL};
  1019. const char *s;
  1020. print_section_header("packet");
  1021. s = av_get_media_type_string(st->codec->codec_type);
  1022. if (s) print_str ("codec_type", s);
  1023. else print_str_opt("codec_type", "unknown");
  1024. print_int("stream_index", pkt->stream_index);
  1025. print_ts ("pts", pkt->pts);
  1026. print_time("pts_time", pkt->pts, &st->time_base);
  1027. print_ts ("dts", pkt->dts);
  1028. print_time("dts_time", pkt->dts, &st->time_base);
  1029. print_ts ("duration", pkt->duration);
  1030. print_time("duration_time", pkt->duration, &st->time_base);
  1031. print_val("size", pkt->size, unit_byte_str);
  1032. if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
  1033. else print_str_opt("pos", "N/A");
  1034. print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
  1035. print_section_footer("packet");
  1036. av_free(pbuf.s);
  1037. fflush(stdout);
  1038. }
  1039. static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream)
  1040. {
  1041. struct print_buf pbuf = {.s = NULL};
  1042. const char *s;
  1043. print_section_header("frame");
  1044. print_str("media_type", "video");
  1045. print_int("width", frame->width);
  1046. print_int("height", frame->height);
  1047. s = av_get_pix_fmt_name(frame->format);
  1048. if (s) print_str ("pix_fmt", s);
  1049. else print_str_opt("pix_fmt", "unknown");
  1050. if (frame->sample_aspect_ratio.num) {
  1051. print_fmt("sample_aspect_ratio", "%d:%d",
  1052. frame->sample_aspect_ratio.num,
  1053. frame->sample_aspect_ratio.den);
  1054. } else {
  1055. print_str_opt("sample_aspect_ratio", "N/A");
  1056. }
  1057. print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
  1058. print_int("coded_picture_number", frame->coded_picture_number);
  1059. print_int("display_picture_number", frame->display_picture_number);
  1060. print_int("interlaced_frame", frame->interlaced_frame);
  1061. print_int("top_field_first", frame->top_field_first);
  1062. print_int("repeat_pict", frame->repeat_pict);
  1063. print_int("reference", frame->reference);
  1064. print_int("key_frame", frame->key_frame);
  1065. print_ts ("pkt_pts", frame->pkt_pts);
  1066. print_time("pkt_pts_time", frame->pkt_pts, &stream->time_base);
  1067. print_ts ("pkt_dts", frame->pkt_dts);
  1068. print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
  1069. if (frame->pkt_pos != -1) print_fmt ("pkt_pos", "%"PRId64, frame->pkt_pos);
  1070. else print_str_opt("pkt_pos", "N/A");
  1071. print_section_footer("frame");
  1072. av_free(pbuf.s);
  1073. fflush(stdout);
  1074. }
  1075. static av_always_inline int get_video_frame(AVFormatContext *fmt_ctx,
  1076. AVFrame *frame, AVPacket *pkt)
  1077. {
  1078. AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  1079. int got_picture = 0;
  1080. if (dec_ctx->codec_id != CODEC_ID_NONE &&
  1081. dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  1082. avcodec_decode_video2(dec_ctx, frame, &got_picture, pkt);
  1083. return got_picture;
  1084. }
  1085. static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)
  1086. {
  1087. AVPacket pkt;
  1088. AVFrame frame;
  1089. int i = 0;
  1090. av_init_packet(&pkt);
  1091. while (!av_read_frame(fmt_ctx, &pkt)) {
  1092. if (do_show_packets)
  1093. show_packet(w, fmt_ctx, &pkt, i++);
  1094. if (do_show_frames &&
  1095. get_video_frame(fmt_ctx, &frame, &pkt)) {
  1096. show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
  1097. av_destruct_packet(&pkt);
  1098. }
  1099. }
  1100. av_init_packet(&pkt);
  1101. pkt.data = NULL;
  1102. pkt.size = 0;
  1103. //Flush remaining frames that are cached in the decoder
  1104. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1105. pkt.stream_index = i;
  1106. while (get_video_frame(fmt_ctx, &frame, &pkt))
  1107. show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);
  1108. }
  1109. }
  1110. static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
  1111. {
  1112. AVStream *stream = fmt_ctx->streams[stream_idx];
  1113. AVCodecContext *dec_ctx;
  1114. AVCodec *dec;
  1115. char val_str[128];
  1116. const char *s;
  1117. AVRational display_aspect_ratio;
  1118. struct print_buf pbuf = {.s = NULL};
  1119. print_section_header("stream");
  1120. print_int("index", stream->index);
  1121. if ((dec_ctx = stream->codec)) {
  1122. if ((dec = dec_ctx->codec)) {
  1123. print_str("codec_name", dec->name);
  1124. print_str("codec_long_name", dec->long_name);
  1125. } else {
  1126. print_str_opt("codec_name", "unknown");
  1127. print_str_opt("codec_long_name", "unknown");
  1128. }
  1129. s = av_get_media_type_string(dec_ctx->codec_type);
  1130. if (s) print_str ("codec_type", s);
  1131. else print_str_opt("codec_type", "unknown");
  1132. print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);
  1133. /* print AVI/FourCC tag */
  1134. av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
  1135. print_str("codec_tag_string", val_str);
  1136. print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
  1137. switch (dec_ctx->codec_type) {
  1138. case AVMEDIA_TYPE_VIDEO:
  1139. print_int("width", dec_ctx->width);
  1140. print_int("height", dec_ctx->height);
  1141. print_int("has_b_frames", dec_ctx->has_b_frames);
  1142. if (dec_ctx->sample_aspect_ratio.num) {
  1143. print_fmt("sample_aspect_ratio", "%d:%d",
  1144. dec_ctx->sample_aspect_ratio.num,
  1145. dec_ctx->sample_aspect_ratio.den);
  1146. av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,
  1147. dec_ctx->width * dec_ctx->sample_aspect_ratio.num,
  1148. dec_ctx->height * dec_ctx->sample_aspect_ratio.den,
  1149. 1024*1024);
  1150. print_fmt("display_aspect_ratio", "%d:%d",
  1151. display_aspect_ratio.num,
  1152. display_aspect_ratio.den);
  1153. } else {
  1154. print_str_opt("sample_aspect_ratio", "N/A");
  1155. print_str_opt("display_aspect_ratio", "N/A");
  1156. }
  1157. s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
  1158. if (s) print_str ("pix_fmt", s);
  1159. else print_str_opt("pix_fmt", "unknown");
  1160. print_int("level", dec_ctx->level);
  1161. if (dec_ctx->timecode_frame_start >= 0) {
  1162. uint32_t tc = dec_ctx->timecode_frame_start;
  1163. print_fmt("timecode", "%02d:%02d:%02d%c%02d",
  1164. tc>>19 & 0x1f, // hours
  1165. tc>>13 & 0x3f, // minutes
  1166. tc>>6 & 0x3f, // seconds
  1167. tc & 1<<24 ? ';' : ':', // drop
  1168. tc & 0x3f); // frames
  1169. } else {
  1170. print_str_opt("timecode", "N/A");
  1171. }
  1172. break;
  1173. case AVMEDIA_TYPE_AUDIO:
  1174. s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
  1175. if (s) print_str ("sample_fmt", s);
  1176. else print_str_opt("sample_fmt", "unknown");
  1177. print_val("sample_rate", dec_ctx->sample_rate, unit_hertz_str);
  1178. print_int("channels", dec_ctx->channels);
  1179. print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
  1180. break;
  1181. }
  1182. } else {
  1183. print_str_opt("codec_type", "unknown");
  1184. }
  1185. if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
  1186. const AVOption *opt = NULL;
  1187. while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
  1188. uint8_t *str;
  1189. if (opt->flags) continue;
  1190. if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
  1191. print_str(opt->name, str);
  1192. av_free(str);
  1193. }
  1194. }
  1195. }
  1196. if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
  1197. else print_str_opt("id", "N/A");
  1198. print_fmt("r_frame_rate", "%d/%d", stream->r_frame_rate.num, stream->r_frame_rate.den);
  1199. print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);
  1200. print_fmt("time_base", "%d/%d", stream->time_base.num, stream->time_base.den);
  1201. print_time("start_time", stream->start_time, &stream->time_base);
  1202. print_time("duration", stream->duration, &stream->time_base);
  1203. if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
  1204. else print_str_opt("nb_frames", "N/A");
  1205. show_tags(stream->metadata);
  1206. print_section_footer("stream");
  1207. av_free(pbuf.s);
  1208. fflush(stdout);
  1209. }
  1210. static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
  1211. {
  1212. int i;
  1213. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1214. show_stream(w, fmt_ctx, i);
  1215. }
  1216. static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
  1217. {
  1218. char val_str[128];
  1219. int64_t size = avio_size(fmt_ctx->pb);
  1220. print_section_header("format");
  1221. print_str("filename", fmt_ctx->filename);
  1222. print_int("nb_streams", fmt_ctx->nb_streams);
  1223. print_str("format_name", fmt_ctx->iformat->name);
  1224. print_str("format_long_name", fmt_ctx->iformat->long_name);
  1225. print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
  1226. print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
  1227. if (size >= 0) print_val ("size", size, unit_byte_str);
  1228. else print_str_opt("size", "N/A");
  1229. if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
  1230. else print_str_opt("bit_rate", "N/A");
  1231. show_tags(fmt_ctx->metadata);
  1232. print_section_footer("format");
  1233. fflush(stdout);
  1234. }
  1235. static void show_error(WriterContext *w, int err)
  1236. {
  1237. char errbuf[128];
  1238. const char *errbuf_ptr = errbuf;
  1239. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  1240. errbuf_ptr = strerror(AVUNERROR(err));
  1241. writer_print_chapter_header(w, "error");
  1242. print_section_header("error");
  1243. print_int("code", err);
  1244. print_str("string", errbuf_ptr);
  1245. print_section_footer("error");
  1246. writer_print_chapter_footer(w, "error");
  1247. }
  1248. static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
  1249. {
  1250. int err, i;
  1251. AVFormatContext *fmt_ctx = NULL;
  1252. AVDictionaryEntry *t;
  1253. if ((err = avformat_open_input(&fmt_ctx, filename, iformat, &format_opts)) < 0) {
  1254. print_error(filename, err);
  1255. return err;
  1256. }
  1257. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  1258. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  1259. return AVERROR_OPTION_NOT_FOUND;
  1260. }
  1261. /* fill the streams in the format context */
  1262. if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  1263. print_error(filename, err);
  1264. return err;
  1265. }
  1266. av_dump_format(fmt_ctx, 0, filename, 0);
  1267. /* bind a decoder to each input stream */
  1268. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1269. AVStream *stream = fmt_ctx->streams[i];
  1270. AVCodec *codec;
  1271. if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
  1272. av_log(NULL, AV_LOG_ERROR, "Unsupported codec with id %d for input stream %d\n",
  1273. stream->codec->codec_id, stream->index);
  1274. } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
  1275. av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
  1276. stream->index);
  1277. }
  1278. }
  1279. *fmt_ctx_ptr = fmt_ctx;
  1280. return 0;
  1281. }
  1282. #define PRINT_CHAPTER(name) do { \
  1283. if (do_show_ ## name) { \
  1284. writer_print_chapter_header(wctx, #name); \
  1285. show_ ## name (wctx, fmt_ctx); \
  1286. writer_print_chapter_footer(wctx, #name); \
  1287. } \
  1288. } while (0)
  1289. static int probe_file(WriterContext *wctx, const char *filename)
  1290. {
  1291. AVFormatContext *fmt_ctx;
  1292. int ret, i;
  1293. ret = open_input_file(&fmt_ctx, filename);
  1294. if (ret >= 0) {
  1295. if (do_show_packets || do_show_frames) {
  1296. const char *chapter;
  1297. if (do_show_frames && do_show_packets &&
  1298. wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
  1299. chapter = "packets_and_frames";
  1300. else if (do_show_packets && !do_show_frames)
  1301. chapter = "packets";
  1302. else // (!do_show_packets && do_show_frames)
  1303. chapter = "frames";
  1304. writer_print_chapter_header(wctx, chapter);
  1305. show_packets(wctx, fmt_ctx);
  1306. writer_print_chapter_footer(wctx, chapter);
  1307. }
  1308. PRINT_CHAPTER(streams);
  1309. PRINT_CHAPTER(format);
  1310. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1311. if (fmt_ctx->streams[i]->codec->codec_id != CODEC_ID_NONE)
  1312. avcodec_close(fmt_ctx->streams[i]->codec);
  1313. avformat_close_input(&fmt_ctx);
  1314. }
  1315. return ret;
  1316. }
  1317. static void show_usage(void)
  1318. {
  1319. av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
  1320. av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
  1321. av_log(NULL, AV_LOG_INFO, "\n");
  1322. }
  1323. static int opt_format(const char *opt, const char *arg)
  1324. {
  1325. iformat = av_find_input_format(arg);
  1326. if (!iformat) {
  1327. av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
  1328. return AVERROR(EINVAL);
  1329. }
  1330. return 0;
  1331. }
  1332. static void opt_input_file(void *optctx, const char *arg)
  1333. {
  1334. if (input_filename) {
  1335. av_log(NULL, AV_LOG_ERROR, "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  1336. arg, input_filename);
  1337. exit(1);
  1338. }
  1339. if (!strcmp(arg, "-"))
  1340. arg = "pipe:";
  1341. input_filename = arg;
  1342. }
  1343. static int opt_help(const char *opt, const char *arg)
  1344. {
  1345. av_log_set_callback(log_callback_help);
  1346. show_usage();
  1347. show_help_options(options, "Main options:\n", 0, 0);
  1348. printf("\n");
  1349. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  1350. return 0;
  1351. }
  1352. static int opt_pretty(const char *opt, const char *arg)
  1353. {
  1354. show_value_unit = 1;
  1355. use_value_prefix = 1;
  1356. use_byte_value_binary_prefix = 1;
  1357. use_value_sexagesimal_format = 1;
  1358. return 0;
  1359. }
  1360. static const OptionDef options[] = {
  1361. #include "cmdutils_common_opts.h"
  1362. { "f", HAS_ARG, {(void*)opt_format}, "force format", "format" },
  1363. { "unit", OPT_BOOL, {(void*)&show_value_unit}, "show unit of the displayed values" },
  1364. { "prefix", OPT_BOOL, {(void*)&use_value_prefix}, "use SI prefixes for the displayed values" },
  1365. { "byte_binary_prefix", OPT_BOOL, {(void*)&use_byte_value_binary_prefix},
  1366. "use binary prefixes for byte units" },
  1367. { "sexagesimal", OPT_BOOL, {(void*)&use_value_sexagesimal_format},
  1368. "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
  1369. { "pretty", 0, {(void*)&opt_pretty},
  1370. "prettify the format of displayed values, make it more human readable" },
  1371. { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
  1372. "set the output printing format (available formats are: default, compact, csv, json, xml)", "format" },
  1373. { "show_error", OPT_BOOL, {(void*)&do_show_error} , "show probing error" },
  1374. { "show_format", OPT_BOOL, {(void*)&do_show_format} , "show format/container info" },
  1375. { "show_frames", OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
  1376. { "show_packets", OPT_BOOL, {(void*)&do_show_packets}, "show packets info" },
  1377. { "show_streams", OPT_BOOL, {(void*)&do_show_streams}, "show streams info" },
  1378. { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
  1379. { "private", OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
  1380. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {(void*)opt_default}, "generic catch all option", "" },
  1381. { "i", HAS_ARG, {(void *)opt_input_file}, "read specified file", "input_file"},
  1382. { NULL, },
  1383. };
  1384. int main(int argc, char **argv)
  1385. {
  1386. const Writer *w;
  1387. WriterContext *wctx;
  1388. char *buf;
  1389. char *w_name = NULL, *w_args = NULL;
  1390. int ret;
  1391. parse_loglevel(argc, argv, options);
  1392. av_register_all();
  1393. avformat_network_init();
  1394. init_opts();
  1395. #if CONFIG_AVDEVICE
  1396. avdevice_register_all();
  1397. #endif
  1398. show_banner(argc, argv, options);
  1399. parse_options(NULL, argc, argv, options, opt_input_file);
  1400. writer_register_all();
  1401. if (!print_format)
  1402. print_format = av_strdup("default");
  1403. w_name = av_strtok(print_format, "=", &buf);
  1404. w_args = buf;
  1405. w = writer_get_by_name(w_name);
  1406. if (!w) {
  1407. av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
  1408. ret = AVERROR(EINVAL);
  1409. goto end;
  1410. }
  1411. if ((ret = writer_open(&wctx, w, w_args, NULL)) >= 0) {
  1412. writer_print_header(wctx);
  1413. if (!input_filename) {
  1414. show_usage();
  1415. av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
  1416. av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
  1417. ret = AVERROR(EINVAL);
  1418. } else {
  1419. ret = probe_file(wctx, input_filename);
  1420. if (ret < 0 && do_show_error)
  1421. show_error(wctx, ret);
  1422. }
  1423. writer_print_footer(wctx);
  1424. writer_close(&wctx);
  1425. }
  1426. end:
  1427. av_freep(&print_format);
  1428. avformat_network_deinit();
  1429. return ret;
  1430. }