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.

2148 lines
75KB

  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 <string.h>
  27. #include "libavformat/avformat.h"
  28. #include "libavcodec/avcodec.h"
  29. #include "libavutil/avassert.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/bprint.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "libavutil/dict.h"
  35. #include "libavutil/libm.h"
  36. #include "libavutil/timecode.h"
  37. #include "libavdevice/avdevice.h"
  38. #include "libswscale/swscale.h"
  39. #include "libswresample/swresample.h"
  40. #include "libpostproc/postprocess.h"
  41. #include "cmdutils.h"
  42. const char program_name[] = "ffprobe";
  43. const int program_birth_year = 2007;
  44. static int do_bitexact = 0;
  45. static int do_count_frames = 0;
  46. static int do_count_packets = 0;
  47. static int do_read_frames = 0;
  48. static int do_read_packets = 0;
  49. static int do_show_error = 0;
  50. static int do_show_format = 0;
  51. static int do_show_frames = 0;
  52. static AVDictionary *fmt_entries_to_show = NULL;
  53. static int do_show_packets = 0;
  54. static int do_show_streams = 0;
  55. static int do_show_data = 0;
  56. static int do_show_program_version = 0;
  57. static int do_show_library_versions = 0;
  58. static int show_value_unit = 0;
  59. static int use_value_prefix = 0;
  60. static int use_byte_value_binary_prefix = 0;
  61. static int use_value_sexagesimal_format = 0;
  62. static int show_private_data = 1;
  63. static char *print_format;
  64. /* section structure definition */
  65. struct section {
  66. int id; ///< unique id indentifying a section
  67. const char *name;
  68. #define SECTION_FLAG_IS_WRAPPER 1 ///< the section only contains other sections, but has no data at its own level
  69. #define SECTION_FLAG_IS_ARRAY 2 ///< the section contains an array of elements of the same type
  70. int flags;
  71. const char *element_name; ///< name of the contained element, if provided
  72. };
  73. typedef enum {
  74. SECTION_ID_NONE = -1,
  75. SECTION_ID_ERROR,
  76. SECTION_ID_FORMAT,
  77. SECTION_ID_FORMAT_TAGS,
  78. SECTION_ID_FRAME,
  79. SECTION_ID_FRAMES,
  80. SECTION_ID_FRAME_TAGS,
  81. SECTION_ID_LIBRARY_VERSION,
  82. SECTION_ID_LIBRARY_VERSIONS,
  83. SECTION_ID_PACKET,
  84. SECTION_ID_PACKETS,
  85. SECTION_ID_PACKETS_AND_FRAMES,
  86. SECTION_ID_PROGRAM_VERSION,
  87. SECTION_ID_ROOT,
  88. SECTION_ID_STREAM,
  89. SECTION_ID_STREAMS,
  90. SECTION_ID_STREAM_TAGS
  91. } SectionID;
  92. static const struct section sections[] = {
  93. [SECTION_ID_ERROR] = { SECTION_ID_ERROR, "error" },
  94. [SECTION_ID_FORMAT] = { SECTION_ID_FORMAT, "format" },
  95. [SECTION_ID_FORMAT_TAGS] = { SECTION_ID_FORMAT_TAGS, "tags", .element_name = "tag" },
  96. [SECTION_ID_FRAME] = { SECTION_ID_FRAME, "frame" },
  97. [SECTION_ID_FRAMES] = { SECTION_ID_FRAMES, "frames", SECTION_FLAG_IS_ARRAY },
  98. [SECTION_ID_FRAME_TAGS] = { SECTION_ID_FRAME_TAGS, "tags", .element_name = "tag" },
  99. [SECTION_ID_LIBRARY_VERSION] = { SECTION_ID_LIBRARY_VERSION, "library_version" },
  100. [SECTION_ID_LIBRARY_VERSIONS] = { SECTION_ID_LIBRARY_VERSIONS, "library_versions", SECTION_FLAG_IS_ARRAY },
  101. [SECTION_ID_PACKET] = { SECTION_ID_PACKET, "packet" },
  102. [SECTION_ID_PACKETS] = { SECTION_ID_PACKETS, "packets", SECTION_FLAG_IS_ARRAY },
  103. [SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY },
  104. [SECTION_ID_PROGRAM_VERSION] = { SECTION_ID_PROGRAM_VERSION, "program_version" },
  105. [SECTION_ID_ROOT] = { SECTION_ID_ROOT, "root", SECTION_FLAG_IS_WRAPPER },
  106. [SECTION_ID_STREAM] = { SECTION_ID_STREAM, "stream" },
  107. [SECTION_ID_STREAMS] = { SECTION_ID_STREAMS, "streams", SECTION_FLAG_IS_ARRAY },
  108. [SECTION_ID_STREAM_TAGS] = { SECTION_ID_STREAM_TAGS, "tags", .element_name = "tag" },
  109. };
  110. static const OptionDef *options;
  111. /* FFprobe context */
  112. static const char *input_filename;
  113. static AVInputFormat *iformat = NULL;
  114. static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
  115. static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P" };
  116. static const char unit_second_str[] = "s" ;
  117. static const char unit_hertz_str[] = "Hz" ;
  118. static const char unit_byte_str[] = "byte" ;
  119. static const char unit_bit_per_second_str[] = "bit/s";
  120. static uint64_t *nb_streams_packets;
  121. static uint64_t *nb_streams_frames;
  122. void av_noreturn exit_program(int ret)
  123. {
  124. av_dict_free(&fmt_entries_to_show);
  125. exit(ret);
  126. }
  127. struct unit_value {
  128. union { double d; long long int i; } val;
  129. const char *unit;
  130. };
  131. static char *value_string(char *buf, int buf_size, struct unit_value uv)
  132. {
  133. double vald;
  134. long long int vali;
  135. int show_float = 0;
  136. if (uv.unit == unit_second_str) {
  137. vald = uv.val.d;
  138. show_float = 1;
  139. } else {
  140. vald = vali = uv.val.i;
  141. }
  142. if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
  143. double secs;
  144. int hours, mins;
  145. secs = vald;
  146. mins = (int)secs / 60;
  147. secs = secs - mins * 60;
  148. hours = mins / 60;
  149. mins %= 60;
  150. snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
  151. } else {
  152. const char *prefix_string = "";
  153. if (use_value_prefix && vald > 1) {
  154. long long int index;
  155. if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
  156. index = (long long int) (log2(vald)) / 10;
  157. index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
  158. vald /= exp2(index * 10);
  159. prefix_string = binary_unit_prefixes[index];
  160. } else {
  161. index = (long long int) (log10(vald)) / 3;
  162. index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
  163. vald /= pow(10, index * 3);
  164. prefix_string = decimal_unit_prefixes[index];
  165. }
  166. }
  167. if (show_float || (use_value_prefix && vald != (long long int)vald))
  168. snprintf(buf, buf_size, "%f", vald);
  169. else
  170. snprintf(buf, buf_size, "%lld", vali);
  171. av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
  172. prefix_string, show_value_unit ? uv.unit : "");
  173. }
  174. return buf;
  175. }
  176. /* WRITERS API */
  177. typedef struct WriterContext WriterContext;
  178. #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
  179. #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
  180. typedef struct Writer {
  181. const AVClass *priv_class; ///< private class of the writer, if any
  182. int priv_size; ///< private size for the writer context
  183. const char *name;
  184. int (*init) (WriterContext *wctx);
  185. void (*uninit)(WriterContext *wctx);
  186. void (*print_section_header)(WriterContext *wctx);
  187. void (*print_section_footer)(WriterContext *wctx);
  188. void (*print_integer) (WriterContext *wctx, const char *, long long int);
  189. void (*print_rational) (WriterContext *wctx, AVRational *q, char *sep);
  190. void (*print_string) (WriterContext *wctx, const char *, const char *);
  191. int flags; ///< a combination or WRITER_FLAG_*
  192. } Writer;
  193. #define SECTION_MAX_NB_LEVELS 10
  194. struct WriterContext {
  195. const AVClass *class; ///< class of the writer
  196. const Writer *writer; ///< the Writer of which this is an instance
  197. char *name; ///< name of this writer instance
  198. void *priv; ///< private data for use by the filter
  199. const struct section *sections; ///< array containing all sections
  200. int nb_sections; ///< number of sections
  201. int level; ///< current level, starting from 0
  202. /** number of the item printed in the given section, starting from 0 */
  203. unsigned int nb_item[SECTION_MAX_NB_LEVELS];
  204. /** section per each level */
  205. const struct section *section[SECTION_MAX_NB_LEVELS];
  206. unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
  207. unsigned int nb_section_frame; ///< number of the frame section in case we are in "packets_and_frames" section
  208. unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
  209. };
  210. static const char *writer_get_name(void *p)
  211. {
  212. WriterContext *wctx = p;
  213. return wctx->writer->name;
  214. }
  215. static const AVClass writer_class = {
  216. "Writer",
  217. writer_get_name,
  218. NULL,
  219. LIBAVUTIL_VERSION_INT,
  220. };
  221. static void writer_close(WriterContext **wctx)
  222. {
  223. if (!*wctx)
  224. return;
  225. if ((*wctx)->writer->uninit)
  226. (*wctx)->writer->uninit(*wctx);
  227. if ((*wctx)->writer->priv_class)
  228. av_opt_free((*wctx)->priv);
  229. av_freep(&((*wctx)->priv));
  230. av_freep(wctx);
  231. }
  232. static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
  233. const struct section *sections, int nb_sections)
  234. {
  235. int ret = 0;
  236. if (!(*wctx = av_malloc(sizeof(WriterContext)))) {
  237. ret = AVERROR(ENOMEM);
  238. goto fail;
  239. }
  240. if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
  241. ret = AVERROR(ENOMEM);
  242. goto fail;
  243. }
  244. (*wctx)->class = &writer_class;
  245. (*wctx)->writer = writer;
  246. (*wctx)->level = -1;
  247. (*wctx)->sections = sections;
  248. (*wctx)->nb_sections = nb_sections;
  249. if (writer->priv_class) {
  250. void *priv_ctx = (*wctx)->priv;
  251. *((const AVClass **)priv_ctx) = writer->priv_class;
  252. av_opt_set_defaults(priv_ctx);
  253. if (args &&
  254. (ret = av_set_options_string(priv_ctx, args, "=", ":")) < 0)
  255. goto fail;
  256. }
  257. if ((*wctx)->writer->init)
  258. ret = (*wctx)->writer->init(*wctx);
  259. if (ret < 0)
  260. goto fail;
  261. return 0;
  262. fail:
  263. writer_close(wctx);
  264. return ret;
  265. }
  266. static inline void writer_print_section_header(WriterContext *wctx,
  267. int section_id)
  268. {
  269. int parent_section_id;
  270. wctx->level++;
  271. av_assert0(wctx->level < SECTION_MAX_NB_LEVELS);
  272. parent_section_id = wctx->level ?
  273. (wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
  274. wctx->nb_item[wctx->level] = 0;
  275. wctx->section[wctx->level] = &wctx->sections[section_id];
  276. if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
  277. wctx->nb_section_packet = wctx->nb_section_frame =
  278. wctx->nb_section_packet_frame = 0;
  279. } else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
  280. wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
  281. wctx->nb_section_packet : wctx->nb_section_frame;
  282. }
  283. if (wctx->writer->print_section_header)
  284. wctx->writer->print_section_header(wctx);
  285. }
  286. static inline void writer_print_section_footer(WriterContext *wctx)
  287. {
  288. int section_id = wctx->section[wctx->level]->id;
  289. int parent_section_id = wctx->level ?
  290. wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
  291. if (parent_section_id != SECTION_ID_NONE)
  292. wctx->nb_item[wctx->level-1]++;
  293. if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
  294. if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
  295. else wctx->nb_section_frame++;
  296. }
  297. if (wctx->writer->print_section_footer)
  298. wctx->writer->print_section_footer(wctx);
  299. wctx->level--;
  300. }
  301. static inline void writer_print_integer(WriterContext *wctx,
  302. const char *key, long long int val)
  303. {
  304. if ((wctx->section[wctx->level]->id != SECTION_ID_FORMAT
  305. && wctx->section[wctx->level]->id != SECTION_ID_FORMAT_TAGS) ||
  306. !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
  307. wctx->writer->print_integer(wctx, key, val);
  308. wctx->nb_item[wctx->level]++;
  309. }
  310. }
  311. static inline void writer_print_string(WriterContext *wctx,
  312. const char *key, const char *val, int opt)
  313. {
  314. if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
  315. return;
  316. if ((wctx->section[wctx->level]->id != SECTION_ID_FORMAT
  317. && wctx->section[wctx->level]->id != SECTION_ID_FORMAT_TAGS) ||
  318. !fmt_entries_to_show || av_dict_get(fmt_entries_to_show, key, NULL, 0)) {
  319. wctx->writer->print_string(wctx, key, val);
  320. wctx->nb_item[wctx->level]++;
  321. }
  322. }
  323. static inline void writer_print_rational(WriterContext *wctx,
  324. const char *key, AVRational q, char sep)
  325. {
  326. AVBPrint buf;
  327. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
  328. av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
  329. writer_print_string(wctx, key, buf.str, 0);
  330. }
  331. static void writer_print_time(WriterContext *wctx, const char *key,
  332. int64_t ts, const AVRational *time_base, int is_duration)
  333. {
  334. char buf[128];
  335. if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
  336. writer_print_string(wctx, key, "N/A", 1);
  337. } else {
  338. double d = ts * av_q2d(*time_base);
  339. struct unit_value uv;
  340. uv.val.d = d;
  341. uv.unit = unit_second_str;
  342. value_string(buf, sizeof(buf), uv);
  343. writer_print_string(wctx, key, buf, 0);
  344. }
  345. }
  346. static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
  347. {
  348. if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
  349. writer_print_string(wctx, key, "N/A", 1);
  350. } else {
  351. writer_print_integer(wctx, key, ts);
  352. }
  353. }
  354. static void writer_print_data(WriterContext *wctx, const char *name,
  355. uint8_t *data, int size)
  356. {
  357. AVBPrint bp;
  358. int offset = 0, l, i;
  359. av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
  360. av_bprintf(&bp, "\n");
  361. while (size) {
  362. av_bprintf(&bp, "%08x: ", offset);
  363. l = FFMIN(size, 16);
  364. for (i = 0; i < l; i++) {
  365. av_bprintf(&bp, "%02x", data[i]);
  366. if (i & 1)
  367. av_bprintf(&bp, " ");
  368. }
  369. av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
  370. for (i = 0; i < l; i++)
  371. av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
  372. av_bprintf(&bp, "\n");
  373. offset += l;
  374. data += l;
  375. size -= l;
  376. }
  377. writer_print_string(wctx, name, bp.str, 0);
  378. av_bprint_finalize(&bp, NULL);
  379. }
  380. #define MAX_REGISTERED_WRITERS_NB 64
  381. static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
  382. static int writer_register(const Writer *writer)
  383. {
  384. static int next_registered_writer_idx = 0;
  385. if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
  386. return AVERROR(ENOMEM);
  387. registered_writers[next_registered_writer_idx++] = writer;
  388. return 0;
  389. }
  390. static const Writer *writer_get_by_name(const char *name)
  391. {
  392. int i;
  393. for (i = 0; registered_writers[i]; i++)
  394. if (!strcmp(registered_writers[i]->name, name))
  395. return registered_writers[i];
  396. return NULL;
  397. }
  398. /* WRITERS */
  399. #define DEFINE_WRITER_CLASS(name) \
  400. static const char *name##_get_name(void *ctx) \
  401. { \
  402. return #name ; \
  403. } \
  404. static const AVClass name##_class = { \
  405. #name, \
  406. name##_get_name, \
  407. name##_options \
  408. }
  409. /* Default output */
  410. typedef struct DefaultContext {
  411. const AVClass *class;
  412. int nokey;
  413. int noprint_wrappers;
  414. int nested_section[SECTION_MAX_NB_LEVELS];
  415. AVBPrint prefix[SECTION_MAX_NB_LEVELS];
  416. } DefaultContext;
  417. #define OFFSET(x) offsetof(DefaultContext, x)
  418. static const AVOption default_options[] = {
  419. { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  420. { "nw", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  421. { "nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  422. { "nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  423. {NULL},
  424. };
  425. DEFINE_WRITER_CLASS(default);
  426. /* lame uppercasing routine, assumes the string is lower case ASCII */
  427. static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
  428. {
  429. int i;
  430. for (i = 0; src[i] && i < dst_size-1; i++)
  431. dst[i] = av_toupper(src[i]);
  432. dst[i] = 0;
  433. return dst;
  434. }
  435. static int default_init(WriterContext *wctx)
  436. {
  437. DefaultContext *def = wctx->priv;
  438. int i;
  439. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  440. av_bprint_init(&def->prefix[i], 1, AV_BPRINT_SIZE_UNLIMITED);
  441. return 0;
  442. }
  443. static void default_uninit(WriterContext *wctx)
  444. {
  445. DefaultContext *def = wctx->priv;
  446. int i;
  447. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  448. av_bprint_finalize(&def->prefix[i], NULL);
  449. }
  450. static void default_print_section_header(WriterContext *wctx)
  451. {
  452. DefaultContext *def = wctx->priv;
  453. char buf[32];
  454. const struct section *section = wctx->section[wctx->level];
  455. const struct section *parent_section = wctx->level ?
  456. wctx->section[wctx->level-1] : NULL;
  457. av_bprint_clear(&def->prefix[wctx->level]);
  458. if (parent_section &&
  459. !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
  460. def->nested_section[wctx->level] = 1;
  461. av_bprintf(&def->prefix[wctx->level], "%s%s:", def->prefix[wctx->level-1].str,
  462. upcase_string(buf, sizeof(buf),
  463. av_x_if_null(section->element_name, section->name)));
  464. }
  465. if (def->noprint_wrappers || def->nested_section[wctx->level])
  466. return;
  467. if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  468. printf("[%s]\n", upcase_string(buf, sizeof(buf), section->name));
  469. }
  470. static void default_print_section_footer(WriterContext *wctx)
  471. {
  472. DefaultContext *def = wctx->priv;
  473. const struct section *section = wctx->section[wctx->level];
  474. char buf[32];
  475. if (def->noprint_wrappers || def->nested_section[wctx->level])
  476. return;
  477. if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  478. printf("[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
  479. }
  480. static void default_print_str(WriterContext *wctx, const char *key, const char *value)
  481. {
  482. DefaultContext *def = wctx->priv;
  483. if (!def->nokey)
  484. printf("%s%s=", def->prefix[wctx->level].str, key);
  485. printf("%s\n", value);
  486. }
  487. static void default_print_int(WriterContext *wctx, const char *key, long long int value)
  488. {
  489. DefaultContext *def = wctx->priv;
  490. if (!def->nokey)
  491. printf("%s%s=", def->prefix[wctx->level].str, key);
  492. printf("%lld\n", value);
  493. }
  494. static const Writer default_writer = {
  495. .name = "default",
  496. .priv_size = sizeof(DefaultContext),
  497. .init = default_init,
  498. .uninit = default_uninit,
  499. .print_section_header = default_print_section_header,
  500. .print_section_footer = default_print_section_footer,
  501. .print_integer = default_print_int,
  502. .print_string = default_print_str,
  503. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  504. .priv_class = &default_class,
  505. };
  506. /* Compact output */
  507. /**
  508. * Apply C-language-like string escaping.
  509. */
  510. static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  511. {
  512. const char *p;
  513. for (p = src; *p; p++) {
  514. switch (*p) {
  515. case '\b': av_bprintf(dst, "%s", "\\b"); break;
  516. case '\f': av_bprintf(dst, "%s", "\\f"); break;
  517. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  518. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  519. case '\\': av_bprintf(dst, "%s", "\\\\"); break;
  520. default:
  521. if (*p == sep)
  522. av_bprint_chars(dst, '\\', 1);
  523. av_bprint_chars(dst, *p, 1);
  524. }
  525. }
  526. return dst->str;
  527. }
  528. /**
  529. * Quote fields containing special characters, check RFC4180.
  530. */
  531. static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  532. {
  533. char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
  534. int needs_quoting = !!src[strcspn(src, meta_chars)];
  535. if (needs_quoting)
  536. av_bprint_chars(dst, '\"', 1);
  537. for (; *src; src++) {
  538. if (*src == '"')
  539. av_bprint_chars(dst, '\"', 1);
  540. av_bprint_chars(dst, *src, 1);
  541. }
  542. if (needs_quoting)
  543. av_bprint_chars(dst, '\"', 1);
  544. return dst->str;
  545. }
  546. static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  547. {
  548. return src;
  549. }
  550. typedef struct CompactContext {
  551. const AVClass *class;
  552. char *item_sep_str;
  553. char item_sep;
  554. int nokey;
  555. int print_section;
  556. char *escape_mode_str;
  557. const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
  558. int nested_section[SECTION_MAX_NB_LEVELS];
  559. AVBPrint prefix[SECTION_MAX_NB_LEVELS];
  560. } CompactContext;
  561. #undef OFFSET
  562. #define OFFSET(x) offsetof(CompactContext, x)
  563. static const AVOption compact_options[]= {
  564. {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  565. {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  566. {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  567. {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  568. {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  569. {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  570. {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  571. {"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  572. {NULL},
  573. };
  574. DEFINE_WRITER_CLASS(compact);
  575. static av_cold int compact_init(WriterContext *wctx)
  576. {
  577. CompactContext *compact = wctx->priv;
  578. int i;
  579. if (strlen(compact->item_sep_str) != 1) {
  580. av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
  581. compact->item_sep_str);
  582. return AVERROR(EINVAL);
  583. }
  584. compact->item_sep = compact->item_sep_str[0];
  585. if (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
  586. else if (!strcmp(compact->escape_mode_str, "c" )) compact->escape_str = c_escape_str;
  587. else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
  588. else {
  589. av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
  590. return AVERROR(EINVAL);
  591. }
  592. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  593. av_bprint_init(&compact->prefix[i], 1, AV_BPRINT_SIZE_UNLIMITED);
  594. return 0;
  595. }
  596. static void compact_uninit(WriterContext *wctx)
  597. {
  598. CompactContext *compact = wctx->priv;
  599. int i;
  600. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  601. av_bprint_finalize(&compact->prefix[i], NULL);
  602. }
  603. static void compact_print_section_header(WriterContext *wctx)
  604. {
  605. CompactContext *compact = wctx->priv;
  606. const struct section *section = wctx->section[wctx->level];
  607. const struct section *parent_section = wctx->level ?
  608. wctx->section[wctx->level-1] : NULL;
  609. av_bprint_clear(&compact->prefix[wctx->level]);
  610. if (parent_section &&
  611. !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
  612. compact->nested_section[wctx->level] = 1;
  613. av_bprintf(&compact->prefix[wctx->level], "%s%s:",
  614. compact->prefix[wctx->level-1].str,
  615. (char *)av_x_if_null(section->element_name, section->name));
  616. wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
  617. } else if (compact->print_section &&
  618. !(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  619. printf("%s%c", section->name, compact->item_sep);
  620. }
  621. static void compact_print_section_footer(WriterContext *wctx)
  622. {
  623. CompactContext *compact = wctx->priv;
  624. if (!compact->nested_section[wctx->level] &&
  625. !(wctx->section[wctx->level]->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  626. printf("\n");
  627. }
  628. static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
  629. {
  630. CompactContext *compact = wctx->priv;
  631. AVBPrint buf;
  632. if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
  633. if (!compact->nokey)
  634. printf("%s%s=", compact->prefix[wctx->level].str, key);
  635. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  636. printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
  637. av_bprint_finalize(&buf, NULL);
  638. }
  639. static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
  640. {
  641. CompactContext *compact = wctx->priv;
  642. if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
  643. if (!compact->nokey)
  644. printf("%s%s=", compact->prefix[wctx->level].str, key);
  645. printf("%lld", value);
  646. }
  647. static const Writer compact_writer = {
  648. .name = "compact",
  649. .priv_size = sizeof(CompactContext),
  650. .init = compact_init,
  651. .uninit = compact_uninit,
  652. .print_section_header = compact_print_section_header,
  653. .print_section_footer = compact_print_section_footer,
  654. .print_integer = compact_print_int,
  655. .print_string = compact_print_str,
  656. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  657. .priv_class = &compact_class,
  658. };
  659. /* CSV output */
  660. #undef OFFSET
  661. #define OFFSET(x) offsetof(CompactContext, x)
  662. static const AVOption csv_options[] = {
  663. {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
  664. {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
  665. {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  666. {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  667. {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
  668. {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
  669. {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  670. {"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  671. {NULL},
  672. };
  673. DEFINE_WRITER_CLASS(csv);
  674. static const Writer csv_writer = {
  675. .name = "csv",
  676. .priv_size = sizeof(CompactContext),
  677. .init = compact_init,
  678. .print_section_header = compact_print_section_header,
  679. .print_section_footer = compact_print_section_footer,
  680. .print_integer = compact_print_int,
  681. .print_string = compact_print_str,
  682. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  683. .priv_class = &csv_class,
  684. };
  685. /* Flat output */
  686. typedef struct FlatContext {
  687. const AVClass *class;
  688. AVBPrint section_header[SECTION_MAX_NB_LEVELS];
  689. const char *sep_str;
  690. char sep;
  691. int hierarchical;
  692. } FlatContext;
  693. #undef OFFSET
  694. #define OFFSET(x) offsetof(FlatContext, x)
  695. static const AVOption flat_options[]= {
  696. {"sep_char", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
  697. {"s", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
  698. {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  699. {"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  700. {NULL},
  701. };
  702. DEFINE_WRITER_CLASS(flat);
  703. static av_cold int flat_init(WriterContext *wctx)
  704. {
  705. FlatContext *flat = wctx->priv;
  706. int i;
  707. if (strlen(flat->sep_str) != 1) {
  708. av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
  709. flat->sep_str);
  710. return AVERROR(EINVAL);
  711. }
  712. flat->sep = flat->sep_str[0];
  713. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  714. av_bprint_init(&flat->section_header[i], 1, AV_BPRINT_SIZE_UNLIMITED);
  715. return 0;
  716. }
  717. static void flat_uninit(WriterContext *wctx)
  718. {
  719. FlatContext *flat = wctx->priv;
  720. int i;
  721. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  722. av_bprint_finalize(&flat->section_header[i], NULL);
  723. }
  724. static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
  725. {
  726. const char *p;
  727. for (p = src; *p; p++) {
  728. if (!((*p >= '0' && *p <= '9') ||
  729. (*p >= 'a' && *p <= 'z') ||
  730. (*p >= 'A' && *p <= 'Z')))
  731. av_bprint_chars(dst, '_', 1);
  732. else
  733. av_bprint_chars(dst, *p, 1);
  734. }
  735. return dst->str;
  736. }
  737. static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
  738. {
  739. const char *p;
  740. for (p = src; *p; p++) {
  741. switch (*p) {
  742. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  743. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  744. case '\\': av_bprintf(dst, "%s", "\\\\"); break;
  745. case '"': av_bprintf(dst, "%s", "\\\""); break;
  746. case '`': av_bprintf(dst, "%s", "\\`"); break;
  747. case '$': av_bprintf(dst, "%s", "\\$"); break;
  748. default: av_bprint_chars(dst, *p, 1); break;
  749. }
  750. }
  751. return dst->str;
  752. }
  753. static void flat_print_section_header(WriterContext *wctx)
  754. {
  755. FlatContext *flat = wctx->priv;
  756. AVBPrint *buf = &flat->section_header[wctx->level];
  757. const struct section *section = wctx->section[wctx->level];
  758. const struct section *parent_section = wctx->level ?
  759. wctx->section[wctx->level-1] : NULL;
  760. /* build section header */
  761. av_bprint_clear(buf);
  762. if (!parent_section)
  763. return;
  764. av_bprintf(buf, "%s", flat->section_header[wctx->level-1].str);
  765. if (flat->hierarchical ||
  766. !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
  767. av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
  768. if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
  769. int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
  770. wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
  771. av_bprintf(buf, "%d%s", n, flat->sep_str);
  772. }
  773. }
  774. }
  775. static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
  776. {
  777. FlatContext *flat = wctx->priv;
  778. printf("%s%s=%lld\n", flat->section_header[wctx->level].str, key, value);
  779. }
  780. static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
  781. {
  782. FlatContext *flat = wctx->priv;
  783. AVBPrint buf;
  784. printf("%s", flat->section_header[wctx->level].str);
  785. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  786. printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
  787. av_bprint_clear(&buf);
  788. printf("\"%s\"\n", flat_escape_value_str(&buf, value));
  789. av_bprint_finalize(&buf, NULL);
  790. }
  791. static const Writer flat_writer = {
  792. .name = "flat",
  793. .priv_size = sizeof(FlatContext),
  794. .init = flat_init,
  795. .uninit = flat_uninit,
  796. .print_section_header = flat_print_section_header,
  797. .print_integer = flat_print_int,
  798. .print_string = flat_print_str,
  799. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  800. .priv_class = &flat_class,
  801. };
  802. /* INI format output */
  803. typedef struct {
  804. const AVClass *class;
  805. int hierarchical;
  806. AVBPrint section_header[SECTION_MAX_NB_LEVELS];
  807. } INIContext;
  808. #undef OFFSET
  809. #define OFFSET(x) offsetof(INIContext, x)
  810. static const AVOption ini_options[] = {
  811. {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  812. {"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  813. {NULL},
  814. };
  815. DEFINE_WRITER_CLASS(ini);
  816. static int ini_init(WriterContext *wctx)
  817. {
  818. INIContext *ini = wctx->priv;
  819. int i;
  820. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  821. av_bprint_init(&ini->section_header[i], 1, AV_BPRINT_SIZE_UNLIMITED);
  822. return 0;
  823. }
  824. static void ini_uninit(WriterContext *wctx)
  825. {
  826. INIContext *ini = wctx->priv;
  827. int i;
  828. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  829. av_bprint_finalize(&ini->section_header[i], NULL);
  830. }
  831. static char *ini_escape_str(AVBPrint *dst, const char *src)
  832. {
  833. int i = 0;
  834. char c = 0;
  835. while (c = src[i++]) {
  836. switch (c) {
  837. case '\b': av_bprintf(dst, "%s", "\\b"); break;
  838. case '\f': av_bprintf(dst, "%s", "\\f"); break;
  839. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  840. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  841. case '\t': av_bprintf(dst, "%s", "\\t"); break;
  842. case '\\':
  843. case '#' :
  844. case '=' :
  845. case ':' : av_bprint_chars(dst, '\\', 1);
  846. default:
  847. if ((unsigned char)c < 32)
  848. av_bprintf(dst, "\\x00%02x", c & 0xff);
  849. else
  850. av_bprint_chars(dst, c, 1);
  851. break;
  852. }
  853. }
  854. return dst->str;
  855. }
  856. static void ini_print_section_header(WriterContext *wctx)
  857. {
  858. INIContext *ini = wctx->priv;
  859. AVBPrint *buf = &ini->section_header[wctx->level];
  860. const struct section *section = wctx->section[wctx->level];
  861. const struct section *parent_section = wctx->level ?
  862. wctx->section[wctx->level-1] : NULL;
  863. av_bprint_clear(buf);
  864. if (!parent_section) {
  865. printf("# ffprobe output\n\n");
  866. return;
  867. }
  868. if (wctx->nb_item[wctx->level-1])
  869. printf("\n");
  870. av_bprintf(buf, "%s", ini->section_header[wctx->level-1].str);
  871. if (ini->hierarchical ||
  872. !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
  873. av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
  874. if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
  875. int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
  876. wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
  877. av_bprintf(buf, ".%d", n);
  878. }
  879. }
  880. if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
  881. printf("[%s]\n", buf->str);
  882. }
  883. static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
  884. {
  885. AVBPrint buf;
  886. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  887. printf("%s=", ini_escape_str(&buf, key));
  888. av_bprint_clear(&buf);
  889. printf("%s\n", ini_escape_str(&buf, value));
  890. av_bprint_finalize(&buf, NULL);
  891. }
  892. static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
  893. {
  894. printf("%s=%lld\n", key, value);
  895. }
  896. static const Writer ini_writer = {
  897. .name = "ini",
  898. .priv_size = sizeof(INIContext),
  899. .init = ini_init,
  900. .uninit = ini_uninit,
  901. .print_section_header = ini_print_section_header,
  902. .print_integer = ini_print_int,
  903. .print_string = ini_print_str,
  904. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  905. .priv_class = &ini_class,
  906. };
  907. /* JSON output */
  908. typedef struct {
  909. const AVClass *class;
  910. int indent_level;
  911. int compact;
  912. const char *item_sep, *item_start_end;
  913. } JSONContext;
  914. #undef OFFSET
  915. #define OFFSET(x) offsetof(JSONContext, x)
  916. static const AVOption json_options[]= {
  917. { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  918. { "c", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  919. { NULL }
  920. };
  921. DEFINE_WRITER_CLASS(json);
  922. static av_cold int json_init(WriterContext *wctx)
  923. {
  924. JSONContext *json = wctx->priv;
  925. json->item_sep = json->compact ? ", " : ",\n";
  926. json->item_start_end = json->compact ? " " : "\n";
  927. return 0;
  928. }
  929. static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  930. {
  931. static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
  932. static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
  933. const char *p;
  934. for (p = src; *p; p++) {
  935. char *s = strchr(json_escape, *p);
  936. if (s) {
  937. av_bprint_chars(dst, '\\', 1);
  938. av_bprint_chars(dst, json_subst[s - json_escape], 1);
  939. } else if ((unsigned char)*p < 32) {
  940. av_bprintf(dst, "\\u00%02x", *p & 0xff);
  941. } else {
  942. av_bprint_chars(dst, *p, 1);
  943. }
  944. }
  945. return dst->str;
  946. }
  947. #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
  948. static void json_print_section_header(WriterContext *wctx)
  949. {
  950. JSONContext *json = wctx->priv;
  951. AVBPrint buf;
  952. const struct section *section = wctx->section[wctx->level];
  953. const struct section *parent_section = wctx->level ?
  954. wctx->section[wctx->level-1] : NULL;
  955. if (wctx->level && wctx->nb_item[wctx->level-1])
  956. printf(",\n");
  957. if (section->flags & SECTION_FLAG_IS_WRAPPER) {
  958. printf("{\n");
  959. json->indent_level++;
  960. } else {
  961. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  962. json_escape_str(&buf, section->name, wctx);
  963. JSON_INDENT();
  964. json->indent_level++;
  965. if (section->flags & SECTION_FLAG_IS_ARRAY) {
  966. printf("\"%s\": [\n", buf.str);
  967. } else if (!(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
  968. printf("\"%s\": {%s", buf.str, json->item_start_end);
  969. } else {
  970. printf("{%s", json->item_start_end);
  971. /* this is required so the parser can distinguish between packets and frames */
  972. if (parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
  973. if (!json->compact)
  974. JSON_INDENT();
  975. printf("\"type\": \"%s\"%s", section->name, json->item_sep);
  976. }
  977. }
  978. av_bprint_finalize(&buf, NULL);
  979. }
  980. }
  981. static void json_print_section_footer(WriterContext *wctx)
  982. {
  983. JSONContext *json = wctx->priv;
  984. const struct section *section = wctx->section[wctx->level];
  985. if (wctx->level == 0) {
  986. json->indent_level--;
  987. printf("\n}\n");
  988. } else if (section->flags & SECTION_FLAG_IS_ARRAY) {
  989. printf("\n");
  990. json->indent_level--;
  991. JSON_INDENT();
  992. printf("]");
  993. } else {
  994. printf("%s", json->item_start_end);
  995. json->indent_level--;
  996. if (!json->compact)
  997. JSON_INDENT();
  998. printf("}");
  999. }
  1000. }
  1001. static inline void json_print_item_str(WriterContext *wctx,
  1002. const char *key, const char *value)
  1003. {
  1004. AVBPrint buf;
  1005. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1006. printf("\"%s\":", json_escape_str(&buf, key, wctx));
  1007. av_bprint_clear(&buf);
  1008. printf(" \"%s\"", json_escape_str(&buf, value, wctx));
  1009. av_bprint_finalize(&buf, NULL);
  1010. }
  1011. static void json_print_str(WriterContext *wctx, const char *key, const char *value)
  1012. {
  1013. JSONContext *json = wctx->priv;
  1014. if (wctx->nb_item[wctx->level])
  1015. printf("%s", json->item_sep);
  1016. if (!json->compact)
  1017. JSON_INDENT();
  1018. json_print_item_str(wctx, key, value);
  1019. }
  1020. static void json_print_int(WriterContext *wctx, const char *key, long long int value)
  1021. {
  1022. JSONContext *json = wctx->priv;
  1023. AVBPrint buf;
  1024. if (wctx->nb_item[wctx->level])
  1025. printf("%s", json->item_sep);
  1026. if (!json->compact)
  1027. JSON_INDENT();
  1028. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1029. printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
  1030. av_bprint_finalize(&buf, NULL);
  1031. }
  1032. static const Writer json_writer = {
  1033. .name = "json",
  1034. .priv_size = sizeof(JSONContext),
  1035. .init = json_init,
  1036. .print_section_header = json_print_section_header,
  1037. .print_section_footer = json_print_section_footer,
  1038. .print_integer = json_print_int,
  1039. .print_string = json_print_str,
  1040. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1041. .priv_class = &json_class,
  1042. };
  1043. /* XML output */
  1044. typedef struct {
  1045. const AVClass *class;
  1046. int within_tag;
  1047. int indent_level;
  1048. int fully_qualified;
  1049. int xsd_strict;
  1050. } XMLContext;
  1051. #undef OFFSET
  1052. #define OFFSET(x) offsetof(XMLContext, x)
  1053. static const AVOption xml_options[] = {
  1054. {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1055. {"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1056. {"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1057. {"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1058. {NULL},
  1059. };
  1060. DEFINE_WRITER_CLASS(xml);
  1061. static av_cold int xml_init(WriterContext *wctx)
  1062. {
  1063. XMLContext *xml = wctx->priv;
  1064. if (xml->xsd_strict) {
  1065. xml->fully_qualified = 1;
  1066. #define CHECK_COMPLIANCE(opt, opt_name) \
  1067. if (opt) { \
  1068. av_log(wctx, AV_LOG_ERROR, \
  1069. "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
  1070. "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
  1071. return AVERROR(EINVAL); \
  1072. }
  1073. CHECK_COMPLIANCE(show_private_data, "private");
  1074. CHECK_COMPLIANCE(show_value_unit, "unit");
  1075. CHECK_COMPLIANCE(use_value_prefix, "prefix");
  1076. if (do_show_frames && do_show_packets) {
  1077. av_log(wctx, AV_LOG_ERROR,
  1078. "Interleaved frames and packets are not allowed in XSD. "
  1079. "Select only one between the -show_frames and the -show_packets options.\n");
  1080. return AVERROR(EINVAL);
  1081. }
  1082. }
  1083. return 0;
  1084. }
  1085. static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  1086. {
  1087. const char *p;
  1088. for (p = src; *p; p++) {
  1089. switch (*p) {
  1090. case '&' : av_bprintf(dst, "%s", "&amp;"); break;
  1091. case '<' : av_bprintf(dst, "%s", "&lt;"); break;
  1092. case '>' : av_bprintf(dst, "%s", "&gt;"); break;
  1093. case '\"': av_bprintf(dst, "%s", "&quot;"); break;
  1094. case '\'': av_bprintf(dst, "%s", "&apos;"); break;
  1095. default: av_bprint_chars(dst, *p, 1);
  1096. }
  1097. }
  1098. return dst->str;
  1099. }
  1100. #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
  1101. static void xml_print_section_header(WriterContext *wctx)
  1102. {
  1103. XMLContext *xml = wctx->priv;
  1104. const struct section *section = wctx->section[wctx->level];
  1105. const struct section *parent_section = wctx->level ?
  1106. wctx->section[wctx->level-1] : NULL;
  1107. if (wctx->level == 0) {
  1108. const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
  1109. "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
  1110. "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
  1111. printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  1112. printf("<%sffprobe%s>\n",
  1113. xml->fully_qualified ? "ffprobe:" : "",
  1114. xml->fully_qualified ? qual : "");
  1115. return;
  1116. }
  1117. if (xml->within_tag) {
  1118. xml->within_tag = 0;
  1119. printf(">\n");
  1120. }
  1121. if (!strcmp(section->name, "tags")) {
  1122. xml->indent_level++;
  1123. } else {
  1124. if (!(parent_section->flags & SECTION_FLAG_IS_ARRAY) &&
  1125. (wctx->level && wctx->nb_item[wctx->level-1]))
  1126. printf("\n");
  1127. xml->indent_level++;
  1128. if (section->flags & SECTION_FLAG_IS_ARRAY) {
  1129. XML_INDENT(); printf("<%s>\n", section->name);
  1130. } else {
  1131. XML_INDENT(); printf("<%s ", section->name);
  1132. xml->within_tag = 1;
  1133. }
  1134. }
  1135. }
  1136. static void xml_print_section_footer(WriterContext *wctx)
  1137. {
  1138. XMLContext *xml = wctx->priv;
  1139. const struct section *section = wctx->section[wctx->level];
  1140. if (wctx->level == 0) {
  1141. printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
  1142. } else if (xml->within_tag) {
  1143. xml->within_tag = 0;
  1144. printf("/>\n");
  1145. xml->indent_level--;
  1146. } else if (!strcmp(section->name, "tags")) {
  1147. xml->indent_level--;
  1148. } else {
  1149. XML_INDENT(); printf("</%s>\n", section->name);
  1150. xml->indent_level--;
  1151. }
  1152. }
  1153. static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
  1154. {
  1155. AVBPrint buf;
  1156. XMLContext *xml = wctx->priv;
  1157. const struct section *section = wctx->section[wctx->level];
  1158. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1159. if (!strcmp(section->name, "tags")) {
  1160. XML_INDENT();
  1161. printf("<tag key=\"%s\"", xml_escape_str(&buf, key, wctx));
  1162. av_bprint_clear(&buf);
  1163. printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
  1164. } else {
  1165. if (wctx->nb_item[wctx->level])
  1166. printf(" ");
  1167. printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
  1168. }
  1169. av_bprint_finalize(&buf, NULL);
  1170. }
  1171. static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
  1172. {
  1173. if (wctx->nb_item[wctx->level])
  1174. printf(" ");
  1175. printf("%s=\"%lld\"", key, value);
  1176. }
  1177. static Writer xml_writer = {
  1178. .name = "xml",
  1179. .priv_size = sizeof(XMLContext),
  1180. .init = xml_init,
  1181. .print_section_header = xml_print_section_header,
  1182. .print_section_footer = xml_print_section_footer,
  1183. .print_integer = xml_print_int,
  1184. .print_string = xml_print_str,
  1185. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1186. .priv_class = &xml_class,
  1187. };
  1188. static void writer_register_all(void)
  1189. {
  1190. static int initialized;
  1191. if (initialized)
  1192. return;
  1193. initialized = 1;
  1194. writer_register(&default_writer);
  1195. writer_register(&compact_writer);
  1196. writer_register(&csv_writer);
  1197. writer_register(&flat_writer);
  1198. writer_register(&ini_writer);
  1199. writer_register(&json_writer);
  1200. writer_register(&xml_writer);
  1201. }
  1202. #define print_fmt(k, f, ...) do { \
  1203. av_bprint_clear(&pbuf); \
  1204. av_bprintf(&pbuf, f, __VA_ARGS__); \
  1205. writer_print_string(w, k, pbuf.str, 0); \
  1206. } while (0)
  1207. #define print_int(k, v) writer_print_integer(w, k, v)
  1208. #define print_q(k, v, s) writer_print_rational(w, k, v, s)
  1209. #define print_str(k, v) writer_print_string(w, k, v, 0)
  1210. #define print_str_opt(k, v) writer_print_string(w, k, v, 1)
  1211. #define print_time(k, v, tb) writer_print_time(w, k, v, tb, 0)
  1212. #define print_ts(k, v) writer_print_ts(w, k, v, 0)
  1213. #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
  1214. #define print_duration_ts(k, v) writer_print_ts(w, k, v, 1)
  1215. #define print_val(k, v, u) do { \
  1216. struct unit_value uv; \
  1217. uv.val.i = v; \
  1218. uv.unit = u; \
  1219. writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
  1220. } while (0)
  1221. #define print_section_header(s) writer_print_section_header(w, s)
  1222. #define print_section_footer(s) writer_print_section_footer(w, s)
  1223. static inline void show_tags(WriterContext *wctx, AVDictionary *tags, int section_id)
  1224. {
  1225. AVDictionaryEntry *tag = NULL;
  1226. if (!tags)
  1227. return;
  1228. writer_print_section_header(wctx, section_id);
  1229. while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX)))
  1230. writer_print_string(wctx, tag->key, tag->value, 0);
  1231. writer_print_section_footer(wctx);
  1232. }
  1233. static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
  1234. {
  1235. char val_str[128];
  1236. AVStream *st = fmt_ctx->streams[pkt->stream_index];
  1237. AVBPrint pbuf;
  1238. const char *s;
  1239. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1240. writer_print_section_header(w, SECTION_ID_PACKET);
  1241. s = av_get_media_type_string(st->codec->codec_type);
  1242. if (s) print_str ("codec_type", s);
  1243. else print_str_opt("codec_type", "unknown");
  1244. print_int("stream_index", pkt->stream_index);
  1245. print_ts ("pts", pkt->pts);
  1246. print_time("pts_time", pkt->pts, &st->time_base);
  1247. print_ts ("dts", pkt->dts);
  1248. print_time("dts_time", pkt->dts, &st->time_base);
  1249. print_duration_ts("duration", pkt->duration);
  1250. print_duration_time("duration_time", pkt->duration, &st->time_base);
  1251. print_duration_ts("convergence_duration", pkt->convergence_duration);
  1252. print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
  1253. print_val("size", pkt->size, unit_byte_str);
  1254. if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
  1255. else print_str_opt("pos", "N/A");
  1256. print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
  1257. if (do_show_data)
  1258. writer_print_data(w, "data", pkt->data, pkt->size);
  1259. writer_print_section_footer(w);
  1260. av_bprint_finalize(&pbuf, NULL);
  1261. fflush(stdout);
  1262. }
  1263. static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
  1264. AVFormatContext *fmt_ctx)
  1265. {
  1266. AVBPrint pbuf;
  1267. const char *s;
  1268. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1269. writer_print_section_header(w, SECTION_ID_FRAME);
  1270. s = av_get_media_type_string(stream->codec->codec_type);
  1271. if (s) print_str ("media_type", s);
  1272. else print_str_opt("media_type", "unknown");
  1273. print_int("key_frame", frame->key_frame);
  1274. print_ts ("pkt_pts", frame->pkt_pts);
  1275. print_time("pkt_pts_time", frame->pkt_pts, &stream->time_base);
  1276. print_ts ("pkt_dts", frame->pkt_dts);
  1277. print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
  1278. print_duration_ts ("pkt_duration", frame->pkt_duration);
  1279. print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
  1280. if (frame->pkt_pos != -1) print_fmt ("pkt_pos", "%"PRId64, frame->pkt_pos);
  1281. else print_str_opt("pkt_pos", "N/A");
  1282. switch (stream->codec->codec_type) {
  1283. AVRational sar;
  1284. case AVMEDIA_TYPE_VIDEO:
  1285. print_int("width", frame->width);
  1286. print_int("height", frame->height);
  1287. s = av_get_pix_fmt_name(frame->format);
  1288. if (s) print_str ("pix_fmt", s);
  1289. else print_str_opt("pix_fmt", "unknown");
  1290. sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
  1291. if (sar.num) {
  1292. print_q("sample_aspect_ratio", sar, ':');
  1293. } else {
  1294. print_str_opt("sample_aspect_ratio", "N/A");
  1295. }
  1296. print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
  1297. print_int("coded_picture_number", frame->coded_picture_number);
  1298. print_int("display_picture_number", frame->display_picture_number);
  1299. print_int("interlaced_frame", frame->interlaced_frame);
  1300. print_int("top_field_first", frame->top_field_first);
  1301. print_int("repeat_pict", frame->repeat_pict);
  1302. print_int("reference", frame->reference);
  1303. break;
  1304. case AVMEDIA_TYPE_AUDIO:
  1305. s = av_get_sample_fmt_name(frame->format);
  1306. if (s) print_str ("sample_fmt", s);
  1307. else print_str_opt("sample_fmt", "unknown");
  1308. print_int("nb_samples", frame->nb_samples);
  1309. print_int("channels", av_frame_get_channels(frame));
  1310. if (av_frame_get_channel_layout(frame)) {
  1311. av_bprint_clear(&pbuf);
  1312. av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
  1313. av_frame_get_channel_layout(frame));
  1314. print_str ("channel_layout", pbuf.str);
  1315. } else
  1316. print_str_opt("channel_layout", "unknown");
  1317. break;
  1318. }
  1319. show_tags(w, av_frame_get_metadata(frame), SECTION_ID_FRAME_TAGS);
  1320. writer_print_section_footer(w);
  1321. av_bprint_finalize(&pbuf, NULL);
  1322. fflush(stdout);
  1323. }
  1324. static av_always_inline int process_frame(WriterContext *w,
  1325. AVFormatContext *fmt_ctx,
  1326. AVFrame *frame, AVPacket *pkt)
  1327. {
  1328. AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  1329. int ret = 0, got_frame = 0;
  1330. avcodec_get_frame_defaults(frame);
  1331. if (dec_ctx->codec) {
  1332. switch (dec_ctx->codec_type) {
  1333. case AVMEDIA_TYPE_VIDEO:
  1334. ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
  1335. break;
  1336. case AVMEDIA_TYPE_AUDIO:
  1337. ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
  1338. break;
  1339. }
  1340. }
  1341. if (ret < 0)
  1342. return ret;
  1343. ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
  1344. pkt->data += ret;
  1345. pkt->size -= ret;
  1346. if (got_frame) {
  1347. nb_streams_frames[pkt->stream_index]++;
  1348. if (do_show_frames)
  1349. show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
  1350. }
  1351. return got_frame;
  1352. }
  1353. static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
  1354. {
  1355. AVPacket pkt, pkt1;
  1356. AVFrame frame;
  1357. int i = 0;
  1358. av_init_packet(&pkt);
  1359. while (!av_read_frame(fmt_ctx, &pkt)) {
  1360. if (do_read_packets) {
  1361. if (do_show_packets)
  1362. show_packet(w, fmt_ctx, &pkt, i++);
  1363. nb_streams_packets[pkt.stream_index]++;
  1364. }
  1365. if (do_read_frames) {
  1366. pkt1 = pkt;
  1367. while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
  1368. }
  1369. av_free_packet(&pkt);
  1370. }
  1371. av_init_packet(&pkt);
  1372. pkt.data = NULL;
  1373. pkt.size = 0;
  1374. //Flush remaining frames that are cached in the decoder
  1375. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1376. pkt.stream_index = i;
  1377. if (do_read_frames)
  1378. while (process_frame(w, fmt_ctx, &frame, &pkt) > 0);
  1379. }
  1380. }
  1381. static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
  1382. {
  1383. AVStream *stream = fmt_ctx->streams[stream_idx];
  1384. AVCodecContext *dec_ctx;
  1385. const AVCodec *dec;
  1386. char val_str[128];
  1387. const char *s;
  1388. AVRational sar, dar;
  1389. AVBPrint pbuf;
  1390. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1391. writer_print_section_header(w, SECTION_ID_STREAM);
  1392. print_int("index", stream->index);
  1393. if ((dec_ctx = stream->codec)) {
  1394. const char *profile = NULL;
  1395. dec = dec_ctx->codec;
  1396. if (dec) {
  1397. print_str("codec_name", dec->name);
  1398. if (!do_bitexact) {
  1399. if (dec->long_name) print_str ("codec_long_name", dec->long_name);
  1400. else print_str_opt("codec_long_name", "unknown");
  1401. }
  1402. } else {
  1403. print_str_opt("codec_name", "unknown");
  1404. if (!do_bitexact) {
  1405. print_str_opt("codec_long_name", "unknown");
  1406. }
  1407. }
  1408. if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
  1409. print_str("profile", profile);
  1410. else
  1411. print_str_opt("profile", "unknown");
  1412. s = av_get_media_type_string(dec_ctx->codec_type);
  1413. if (s) print_str ("codec_type", s);
  1414. else print_str_opt("codec_type", "unknown");
  1415. print_q("codec_time_base", dec_ctx->time_base, '/');
  1416. /* print AVI/FourCC tag */
  1417. av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
  1418. print_str("codec_tag_string", val_str);
  1419. print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
  1420. /* Print useful disposition */
  1421. print_int("default", !!(stream->disposition & AV_DISPOSITION_DEFAULT));
  1422. print_int("forced", !!(stream->disposition & AV_DISPOSITION_FORCED));
  1423. switch (dec_ctx->codec_type) {
  1424. case AVMEDIA_TYPE_VIDEO:
  1425. print_int("width", dec_ctx->width);
  1426. print_int("height", dec_ctx->height);
  1427. print_int("has_b_frames", dec_ctx->has_b_frames);
  1428. sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
  1429. if (sar.den) {
  1430. print_q("sample_aspect_ratio", sar, ':');
  1431. av_reduce(&dar.num, &dar.den,
  1432. dec_ctx->width * sar.num,
  1433. dec_ctx->height * sar.den,
  1434. 1024*1024);
  1435. print_q("display_aspect_ratio", dar, ':');
  1436. } else {
  1437. print_str_opt("sample_aspect_ratio", "N/A");
  1438. print_str_opt("display_aspect_ratio", "N/A");
  1439. }
  1440. s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
  1441. if (s) print_str ("pix_fmt", s);
  1442. else print_str_opt("pix_fmt", "unknown");
  1443. print_int("level", dec_ctx->level);
  1444. if (dec_ctx->timecode_frame_start >= 0) {
  1445. char tcbuf[AV_TIMECODE_STR_SIZE];
  1446. av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
  1447. print_str("timecode", tcbuf);
  1448. } else {
  1449. print_str_opt("timecode", "N/A");
  1450. }
  1451. print_int("attached_pic",
  1452. !!(stream->disposition & AV_DISPOSITION_ATTACHED_PIC));
  1453. break;
  1454. case AVMEDIA_TYPE_AUDIO:
  1455. s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
  1456. if (s) print_str ("sample_fmt", s);
  1457. else print_str_opt("sample_fmt", "unknown");
  1458. print_val("sample_rate", dec_ctx->sample_rate, unit_hertz_str);
  1459. print_int("channels", dec_ctx->channels);
  1460. print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
  1461. break;
  1462. }
  1463. } else {
  1464. print_str_opt("codec_type", "unknown");
  1465. }
  1466. if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
  1467. const AVOption *opt = NULL;
  1468. while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
  1469. uint8_t *str;
  1470. if (opt->flags) continue;
  1471. if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
  1472. print_str(opt->name, str);
  1473. av_free(str);
  1474. }
  1475. }
  1476. }
  1477. if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
  1478. else print_str_opt("id", "N/A");
  1479. print_q("r_frame_rate", stream->r_frame_rate, '/');
  1480. print_q("avg_frame_rate", stream->avg_frame_rate, '/');
  1481. print_q("time_base", stream->time_base, '/');
  1482. print_ts ("start_pts", stream->start_time);
  1483. print_time("start_time", stream->start_time, &stream->time_base);
  1484. print_ts ("duration_ts", stream->duration);
  1485. print_time("duration", stream->duration, &stream->time_base);
  1486. if (dec_ctx->bit_rate > 0) print_val ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
  1487. else print_str_opt("bit_rate", "N/A");
  1488. if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
  1489. else print_str_opt("nb_frames", "N/A");
  1490. if (nb_streams_frames[stream_idx]) print_fmt ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
  1491. else print_str_opt("nb_read_frames", "N/A");
  1492. if (nb_streams_packets[stream_idx]) print_fmt ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
  1493. else print_str_opt("nb_read_packets", "N/A");
  1494. if (do_show_data)
  1495. writer_print_data(w, "extradata", dec_ctx->extradata,
  1496. dec_ctx->extradata_size);
  1497. show_tags(w, stream->metadata, SECTION_ID_STREAM_TAGS);
  1498. writer_print_section_footer(w);
  1499. av_bprint_finalize(&pbuf, NULL);
  1500. fflush(stdout);
  1501. }
  1502. static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
  1503. {
  1504. int i;
  1505. writer_print_section_header(w, SECTION_ID_STREAMS);
  1506. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1507. show_stream(w, fmt_ctx, i);
  1508. writer_print_section_footer(w);
  1509. }
  1510. static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
  1511. {
  1512. char val_str[128];
  1513. int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
  1514. writer_print_section_header(w, SECTION_ID_FORMAT);
  1515. print_str("filename", fmt_ctx->filename);
  1516. print_int("nb_streams", fmt_ctx->nb_streams);
  1517. print_str("format_name", fmt_ctx->iformat->name);
  1518. if (!do_bitexact) {
  1519. if (fmt_ctx->iformat->long_name) print_str ("format_long_name", fmt_ctx->iformat->long_name);
  1520. else print_str_opt("format_long_name", "unknown");
  1521. }
  1522. print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
  1523. print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
  1524. if (size >= 0) print_val ("size", size, unit_byte_str);
  1525. else print_str_opt("size", "N/A");
  1526. if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
  1527. else print_str_opt("bit_rate", "N/A");
  1528. show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
  1529. writer_print_section_footer(w);
  1530. fflush(stdout);
  1531. }
  1532. static void show_error(WriterContext *w, int err)
  1533. {
  1534. char errbuf[128];
  1535. const char *errbuf_ptr = errbuf;
  1536. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  1537. errbuf_ptr = strerror(AVUNERROR(err));
  1538. writer_print_section_header(w, SECTION_ID_ERROR);
  1539. print_int("code", err);
  1540. print_str("string", errbuf_ptr);
  1541. writer_print_section_footer(w);
  1542. }
  1543. static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
  1544. {
  1545. int err, i;
  1546. AVFormatContext *fmt_ctx = NULL;
  1547. AVDictionaryEntry *t;
  1548. if ((err = avformat_open_input(&fmt_ctx, filename,
  1549. iformat, &format_opts)) < 0) {
  1550. print_error(filename, err);
  1551. return err;
  1552. }
  1553. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  1554. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  1555. return AVERROR_OPTION_NOT_FOUND;
  1556. }
  1557. /* fill the streams in the format context */
  1558. if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  1559. print_error(filename, err);
  1560. return err;
  1561. }
  1562. av_dump_format(fmt_ctx, 0, filename, 0);
  1563. /* bind a decoder to each input stream */
  1564. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1565. AVStream *stream = fmt_ctx->streams[i];
  1566. AVCodec *codec;
  1567. if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
  1568. av_log(NULL, AV_LOG_ERROR,
  1569. "Failed to probe codec for input stream %d\n",
  1570. stream->index);
  1571. } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
  1572. av_log(NULL, AV_LOG_ERROR,
  1573. "Unsupported codec with id %d for input stream %d\n",
  1574. stream->codec->codec_id, stream->index);
  1575. } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
  1576. av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
  1577. stream->index);
  1578. }
  1579. }
  1580. *fmt_ctx_ptr = fmt_ctx;
  1581. return 0;
  1582. }
  1583. static void close_input_file(AVFormatContext **ctx_ptr)
  1584. {
  1585. int i;
  1586. AVFormatContext *fmt_ctx = *ctx_ptr;
  1587. /* close decoder for each stream */
  1588. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1589. if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
  1590. avcodec_close(fmt_ctx->streams[i]->codec);
  1591. avformat_close_input(ctx_ptr);
  1592. }
  1593. static int probe_file(WriterContext *wctx, const char *filename)
  1594. {
  1595. AVFormatContext *fmt_ctx;
  1596. int ret;
  1597. int section_id;
  1598. do_read_frames = do_show_frames || do_count_frames;
  1599. do_read_packets = do_show_packets || do_count_packets;
  1600. ret = open_input_file(&fmt_ctx, filename);
  1601. if (ret >= 0) {
  1602. nb_streams_frames = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
  1603. nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
  1604. if (do_read_frames || do_read_packets) {
  1605. if (do_show_frames && do_show_packets &&
  1606. wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
  1607. section_id = SECTION_ID_PACKETS_AND_FRAMES;
  1608. else if (do_show_packets && !do_show_frames)
  1609. section_id = SECTION_ID_PACKETS;
  1610. else // (!do_show_packets && do_show_frames)
  1611. section_id = SECTION_ID_FRAMES;
  1612. if (do_show_frames || do_show_packets)
  1613. writer_print_section_header(wctx, section_id);
  1614. read_packets(wctx, fmt_ctx);
  1615. if (do_show_frames || do_show_packets)
  1616. writer_print_section_footer(wctx);
  1617. }
  1618. if (do_show_streams)
  1619. show_streams(wctx, fmt_ctx);
  1620. if (do_show_format)
  1621. show_format(wctx, fmt_ctx);
  1622. close_input_file(&fmt_ctx);
  1623. av_freep(&nb_streams_frames);
  1624. av_freep(&nb_streams_packets);
  1625. }
  1626. return ret;
  1627. }
  1628. static void show_usage(void)
  1629. {
  1630. av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
  1631. av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
  1632. av_log(NULL, AV_LOG_INFO, "\n");
  1633. }
  1634. static void ffprobe_show_program_version(WriterContext *w)
  1635. {
  1636. AVBPrint pbuf;
  1637. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1638. writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
  1639. print_str("version", FFMPEG_VERSION);
  1640. print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
  1641. program_birth_year, this_year);
  1642. print_str("build_date", __DATE__);
  1643. print_str("build_time", __TIME__);
  1644. print_str("compiler_ident", CC_IDENT);
  1645. print_str("configuration", FFMPEG_CONFIGURATION);
  1646. writer_print_section_footer(w);
  1647. av_bprint_finalize(&pbuf, NULL);
  1648. }
  1649. #define SHOW_LIB_VERSION(libname, LIBNAME) \
  1650. do { \
  1651. if (CONFIG_##LIBNAME) { \
  1652. unsigned int version = libname##_version(); \
  1653. writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
  1654. print_str("name", "lib" #libname); \
  1655. print_int("major", LIB##LIBNAME##_VERSION_MAJOR); \
  1656. print_int("minor", LIB##LIBNAME##_VERSION_MINOR); \
  1657. print_int("micro", LIB##LIBNAME##_VERSION_MICRO); \
  1658. print_int("version", version); \
  1659. print_str("ident", LIB##LIBNAME##_IDENT); \
  1660. writer_print_section_footer(w); \
  1661. } \
  1662. } while (0)
  1663. static void ffprobe_show_library_versions(WriterContext *w)
  1664. {
  1665. writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
  1666. SHOW_LIB_VERSION(avutil, AVUTIL);
  1667. SHOW_LIB_VERSION(avcodec, AVCODEC);
  1668. SHOW_LIB_VERSION(avformat, AVFORMAT);
  1669. SHOW_LIB_VERSION(avdevice, AVDEVICE);
  1670. SHOW_LIB_VERSION(avfilter, AVFILTER);
  1671. SHOW_LIB_VERSION(swscale, SWSCALE);
  1672. SHOW_LIB_VERSION(swresample, SWRESAMPLE);
  1673. SHOW_LIB_VERSION(postproc, POSTPROC);
  1674. writer_print_section_footer(w);
  1675. }
  1676. static int opt_format(void *optctx, const char *opt, const char *arg)
  1677. {
  1678. iformat = av_find_input_format(arg);
  1679. if (!iformat) {
  1680. av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
  1681. return AVERROR(EINVAL);
  1682. }
  1683. return 0;
  1684. }
  1685. static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
  1686. {
  1687. do_show_format = 1;
  1688. av_dict_set(&fmt_entries_to_show, arg, "", 0);
  1689. return 0;
  1690. }
  1691. static void opt_input_file(void *optctx, const char *arg)
  1692. {
  1693. if (input_filename) {
  1694. av_log(NULL, AV_LOG_ERROR,
  1695. "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  1696. arg, input_filename);
  1697. exit(1);
  1698. }
  1699. if (!strcmp(arg, "-"))
  1700. arg = "pipe:";
  1701. input_filename = arg;
  1702. }
  1703. static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
  1704. {
  1705. opt_input_file(optctx, arg);
  1706. return 0;
  1707. }
  1708. void show_help_default(const char *opt, const char *arg)
  1709. {
  1710. av_log_set_callback(log_callback_help);
  1711. show_usage();
  1712. show_help_options(options, "Main options:", 0, 0, 0);
  1713. printf("\n");
  1714. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  1715. }
  1716. static int opt_pretty(void *optctx, const char *opt, const char *arg)
  1717. {
  1718. show_value_unit = 1;
  1719. use_value_prefix = 1;
  1720. use_byte_value_binary_prefix = 1;
  1721. use_value_sexagesimal_format = 1;
  1722. return 0;
  1723. }
  1724. static int opt_show_versions(const char *opt, const char *arg)
  1725. {
  1726. do_show_program_version = 1;
  1727. do_show_library_versions = 1;
  1728. return 0;
  1729. }
  1730. static const OptionDef real_options[] = {
  1731. #include "cmdutils_common_opts.h"
  1732. { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
  1733. { "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
  1734. { "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
  1735. { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
  1736. "use binary prefixes for byte units" },
  1737. { "sexagesimal", OPT_BOOL, {&use_value_sexagesimal_format},
  1738. "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
  1739. { "pretty", 0, {.func_arg = opt_pretty},
  1740. "prettify the format of displayed values, make it more human readable" },
  1741. { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
  1742. "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
  1743. { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
  1744. { "show_data", OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
  1745. { "show_error", OPT_BOOL, {(void*)&do_show_error} , "show probing error" },
  1746. { "show_format", OPT_BOOL, {&do_show_format} , "show format/container info" },
  1747. { "show_frames", OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
  1748. { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
  1749. "show a particular entry from the format/container info", "entry" },
  1750. { "show_packets", OPT_BOOL, {&do_show_packets}, "show packets info" },
  1751. { "show_streams", OPT_BOOL, {&do_show_streams}, "show streams info" },
  1752. { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
  1753. { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
  1754. { "show_program_version", OPT_BOOL, {(void*)&do_show_program_version}, "show ffprobe version" },
  1755. { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
  1756. { "show_versions", 0, {(void*)&opt_show_versions}, "show program and library versions" },
  1757. { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
  1758. { "private", OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
  1759. { "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
  1760. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
  1761. { "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
  1762. { NULL, },
  1763. };
  1764. int main(int argc, char **argv)
  1765. {
  1766. const Writer *w;
  1767. WriterContext *wctx;
  1768. char *buf;
  1769. char *w_name = NULL, *w_args = NULL;
  1770. int ret;
  1771. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  1772. options = real_options;
  1773. parse_loglevel(argc, argv, options);
  1774. av_register_all();
  1775. avformat_network_init();
  1776. init_opts();
  1777. #if CONFIG_AVDEVICE
  1778. avdevice_register_all();
  1779. #endif
  1780. show_banner(argc, argv, options);
  1781. parse_options(NULL, argc, argv, options, opt_input_file);
  1782. if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
  1783. av_log(NULL, AV_LOG_ERROR,
  1784. "-bitexact and -show_program_version or -show_library_versions "
  1785. "options are incompatible\n");
  1786. ret = AVERROR(EINVAL);
  1787. goto end;
  1788. }
  1789. writer_register_all();
  1790. if (!print_format)
  1791. print_format = av_strdup("default");
  1792. w_name = av_strtok(print_format, "=", &buf);
  1793. w_args = buf;
  1794. w = writer_get_by_name(w_name);
  1795. if (!w) {
  1796. av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
  1797. ret = AVERROR(EINVAL);
  1798. goto end;
  1799. }
  1800. if ((ret = writer_open(&wctx, w, w_args,
  1801. sections, FF_ARRAY_ELEMS(sections))) >= 0) {
  1802. writer_print_section_header(wctx, SECTION_ID_ROOT);
  1803. if (do_show_program_version)
  1804. ffprobe_show_program_version(wctx);
  1805. if (do_show_library_versions)
  1806. ffprobe_show_library_versions(wctx);
  1807. if (!input_filename &&
  1808. ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
  1809. (!do_show_program_version && !do_show_library_versions))) {
  1810. show_usage();
  1811. av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
  1812. av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
  1813. ret = AVERROR(EINVAL);
  1814. } else if (input_filename) {
  1815. ret = probe_file(wctx, input_filename);
  1816. if (ret < 0 && do_show_error)
  1817. show_error(wctx, ret);
  1818. }
  1819. writer_print_section_footer(wctx);
  1820. writer_close(&wctx);
  1821. }
  1822. end:
  1823. av_freep(&print_format);
  1824. uninit_opts();
  1825. av_dict_free(&fmt_entries_to_show);
  1826. avformat_network_deinit();
  1827. return ret;
  1828. }