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.

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