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.

1836 lines
59KB

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