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.

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