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.

2131 lines
74KB

  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. int i;
  758. /* build section header */
  759. av_bprint_clear(buf);
  760. for (i = 1; i <= wctx->level; i++) {
  761. if (flat->hierarchical ||
  762. !(wctx->section[i]->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
  763. av_bprintf(buf, "%s%s", wctx->section[i]->name, flat->sep_str);
  764. }
  765. }
  766. static void flat_print_key_prefix(WriterContext *wctx)
  767. {
  768. FlatContext *flat = wctx->priv;
  769. const struct section *parent_section = wctx->section[wctx->level-1];
  770. printf("%s", flat->section_header[wctx->level].str);
  771. if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
  772. int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
  773. wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
  774. printf("%d%s", n, flat->sep_str);
  775. }
  776. }
  777. static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
  778. {
  779. flat_print_key_prefix(wctx);
  780. printf("%s=%lld\n", key, value);
  781. }
  782. static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
  783. {
  784. FlatContext *flat = wctx->priv;
  785. AVBPrint buf;
  786. flat_print_key_prefix(wctx);
  787. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  788. printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
  789. av_bprint_clear(&buf);
  790. printf("\"%s\"\n", flat_escape_value_str(&buf, value));
  791. av_bprint_finalize(&buf, NULL);
  792. }
  793. static const Writer flat_writer = {
  794. .name = "flat",
  795. .priv_size = sizeof(FlatContext),
  796. .init = flat_init,
  797. .uninit = flat_uninit,
  798. .print_section_header = flat_print_section_header,
  799. .print_integer = flat_print_int,
  800. .print_string = flat_print_str,
  801. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  802. .priv_class = &flat_class,
  803. };
  804. /* INI format output */
  805. typedef struct {
  806. const AVClass *class;
  807. int hierarchical;
  808. } INIContext;
  809. #undef OFFSET
  810. #define OFFSET(x) offsetof(INIContext, x)
  811. static const AVOption ini_options[] = {
  812. {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  813. {"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  814. {NULL},
  815. };
  816. DEFINE_WRITER_CLASS(ini);
  817. static char *ini_escape_str(AVBPrint *dst, const char *src)
  818. {
  819. int i = 0;
  820. char c = 0;
  821. while (c = src[i++]) {
  822. switch (c) {
  823. case '\b': av_bprintf(dst, "%s", "\\b"); break;
  824. case '\f': av_bprintf(dst, "%s", "\\f"); break;
  825. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  826. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  827. case '\t': av_bprintf(dst, "%s", "\\t"); break;
  828. case '\\':
  829. case '#' :
  830. case '=' :
  831. case ':' : av_bprint_chars(dst, '\\', 1);
  832. default:
  833. if ((unsigned char)c < 32)
  834. av_bprintf(dst, "\\x00%02x", c & 0xff);
  835. else
  836. av_bprint_chars(dst, c, 1);
  837. break;
  838. }
  839. }
  840. return dst->str;
  841. }
  842. static void ini_print_section_header(WriterContext *wctx)
  843. {
  844. INIContext *ini = wctx->priv;
  845. AVBPrint buf;
  846. int i;
  847. const struct section *section = wctx->section[wctx->level];
  848. const struct section *parent_section = wctx->level ?
  849. wctx->section[wctx->level-1] : NULL;
  850. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  851. if (wctx->level == 0) {
  852. printf("# ffprobe output\n\n");
  853. return;
  854. }
  855. if (wctx->nb_item[wctx->level-1])
  856. printf("\n");
  857. for (i = 1; i <= wctx->level; i++) {
  858. if (ini->hierarchical ||
  859. !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
  860. av_bprintf(&buf, "%s%s", i>1 ? "." : "", wctx->section[i]->name);
  861. }
  862. if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
  863. int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
  864. wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
  865. av_bprintf(&buf, ".%d", n);
  866. }
  867. if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
  868. printf("[%s]\n", buf.str);
  869. av_bprint_finalize(&buf, NULL);
  870. }
  871. static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
  872. {
  873. AVBPrint buf;
  874. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  875. printf("%s=", ini_escape_str(&buf, key));
  876. av_bprint_clear(&buf);
  877. printf("%s\n", ini_escape_str(&buf, value));
  878. av_bprint_finalize(&buf, NULL);
  879. }
  880. static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
  881. {
  882. printf("%s=%lld\n", key, value);
  883. }
  884. static const Writer ini_writer = {
  885. .name = "ini",
  886. .priv_size = sizeof(INIContext),
  887. .print_section_header = ini_print_section_header,
  888. .print_integer = ini_print_int,
  889. .print_string = ini_print_str,
  890. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  891. .priv_class = &ini_class,
  892. };
  893. /* JSON output */
  894. typedef struct {
  895. const AVClass *class;
  896. int indent_level;
  897. int compact;
  898. const char *item_sep, *item_start_end;
  899. } JSONContext;
  900. #undef OFFSET
  901. #define OFFSET(x) offsetof(JSONContext, x)
  902. static const AVOption json_options[]= {
  903. { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  904. { "c", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  905. { NULL }
  906. };
  907. DEFINE_WRITER_CLASS(json);
  908. static av_cold int json_init(WriterContext *wctx)
  909. {
  910. JSONContext *json = wctx->priv;
  911. json->item_sep = json->compact ? ", " : ",\n";
  912. json->item_start_end = json->compact ? " " : "\n";
  913. return 0;
  914. }
  915. static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  916. {
  917. static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
  918. static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
  919. const char *p;
  920. for (p = src; *p; p++) {
  921. char *s = strchr(json_escape, *p);
  922. if (s) {
  923. av_bprint_chars(dst, '\\', 1);
  924. av_bprint_chars(dst, json_subst[s - json_escape], 1);
  925. } else if ((unsigned char)*p < 32) {
  926. av_bprintf(dst, "\\u00%02x", *p & 0xff);
  927. } else {
  928. av_bprint_chars(dst, *p, 1);
  929. }
  930. }
  931. return dst->str;
  932. }
  933. #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
  934. static void json_print_section_header(WriterContext *wctx)
  935. {
  936. JSONContext *json = wctx->priv;
  937. AVBPrint buf;
  938. const struct section *section = wctx->section[wctx->level];
  939. const struct section *parent_section = wctx->level ?
  940. wctx->section[wctx->level-1] : NULL;
  941. if (wctx->level && wctx->nb_item[wctx->level-1])
  942. printf(",\n");
  943. if (section->flags & SECTION_FLAG_IS_WRAPPER) {
  944. printf("{\n");
  945. json->indent_level++;
  946. } else {
  947. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  948. json_escape_str(&buf, section->name, wctx);
  949. JSON_INDENT();
  950. json->indent_level++;
  951. if (section->flags & SECTION_FLAG_IS_ARRAY) {
  952. printf("\"%s\": [\n", buf.str);
  953. } else if (!(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
  954. printf("\"%s\": {%s", buf.str, json->item_start_end);
  955. } else {
  956. printf("{%s", json->item_start_end);
  957. /* this is required so the parser can distinguish between packets and frames */
  958. if (parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
  959. if (!json->compact)
  960. JSON_INDENT();
  961. printf("\"type\": \"%s\"%s", section->name, json->item_sep);
  962. }
  963. }
  964. av_bprint_finalize(&buf, NULL);
  965. }
  966. }
  967. static void json_print_section_footer(WriterContext *wctx)
  968. {
  969. JSONContext *json = wctx->priv;
  970. const struct section *section = wctx->section[wctx->level];
  971. if (wctx->level == 0) {
  972. json->indent_level--;
  973. printf("\n}\n");
  974. } else if (section->flags & SECTION_FLAG_IS_ARRAY) {
  975. printf("\n");
  976. json->indent_level--;
  977. JSON_INDENT();
  978. printf("]");
  979. } else {
  980. printf("%s", json->item_start_end);
  981. json->indent_level--;
  982. if (!json->compact)
  983. JSON_INDENT();
  984. printf("}");
  985. }
  986. }
  987. static inline void json_print_item_str(WriterContext *wctx,
  988. const char *key, const char *value)
  989. {
  990. AVBPrint buf;
  991. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  992. printf("\"%s\":", json_escape_str(&buf, key, wctx));
  993. av_bprint_clear(&buf);
  994. printf(" \"%s\"", json_escape_str(&buf, value, wctx));
  995. av_bprint_finalize(&buf, NULL);
  996. }
  997. static void json_print_str(WriterContext *wctx, const char *key, const char *value)
  998. {
  999. JSONContext *json = wctx->priv;
  1000. if (wctx->nb_item[wctx->level])
  1001. printf("%s", json->item_sep);
  1002. if (!json->compact)
  1003. JSON_INDENT();
  1004. json_print_item_str(wctx, key, value);
  1005. }
  1006. static void json_print_int(WriterContext *wctx, const char *key, long long int value)
  1007. {
  1008. JSONContext *json = wctx->priv;
  1009. AVBPrint buf;
  1010. if (wctx->nb_item[wctx->level])
  1011. printf("%s", json->item_sep);
  1012. if (!json->compact)
  1013. JSON_INDENT();
  1014. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1015. printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
  1016. av_bprint_finalize(&buf, NULL);
  1017. }
  1018. static const Writer json_writer = {
  1019. .name = "json",
  1020. .priv_size = sizeof(JSONContext),
  1021. .init = json_init,
  1022. .print_section_header = json_print_section_header,
  1023. .print_section_footer = json_print_section_footer,
  1024. .print_integer = json_print_int,
  1025. .print_string = json_print_str,
  1026. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1027. .priv_class = &json_class,
  1028. };
  1029. /* XML output */
  1030. typedef struct {
  1031. const AVClass *class;
  1032. int within_tag;
  1033. int indent_level;
  1034. int fully_qualified;
  1035. int xsd_strict;
  1036. } XMLContext;
  1037. #undef OFFSET
  1038. #define OFFSET(x) offsetof(XMLContext, x)
  1039. static const AVOption xml_options[] = {
  1040. {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1041. {"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1042. {"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1043. {"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1044. {NULL},
  1045. };
  1046. DEFINE_WRITER_CLASS(xml);
  1047. static av_cold int xml_init(WriterContext *wctx)
  1048. {
  1049. XMLContext *xml = wctx->priv;
  1050. if (xml->xsd_strict) {
  1051. xml->fully_qualified = 1;
  1052. #define CHECK_COMPLIANCE(opt, opt_name) \
  1053. if (opt) { \
  1054. av_log(wctx, AV_LOG_ERROR, \
  1055. "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
  1056. "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
  1057. return AVERROR(EINVAL); \
  1058. }
  1059. CHECK_COMPLIANCE(show_private_data, "private");
  1060. CHECK_COMPLIANCE(show_value_unit, "unit");
  1061. CHECK_COMPLIANCE(use_value_prefix, "prefix");
  1062. if (do_show_frames && do_show_packets) {
  1063. av_log(wctx, AV_LOG_ERROR,
  1064. "Interleaved frames and packets are not allowed in XSD. "
  1065. "Select only one between the -show_frames and the -show_packets options.\n");
  1066. return AVERROR(EINVAL);
  1067. }
  1068. }
  1069. return 0;
  1070. }
  1071. static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  1072. {
  1073. const char *p;
  1074. for (p = src; *p; p++) {
  1075. switch (*p) {
  1076. case '&' : av_bprintf(dst, "%s", "&amp;"); break;
  1077. case '<' : av_bprintf(dst, "%s", "&lt;"); break;
  1078. case '>' : av_bprintf(dst, "%s", "&gt;"); break;
  1079. case '\"': av_bprintf(dst, "%s", "&quot;"); break;
  1080. case '\'': av_bprintf(dst, "%s", "&apos;"); break;
  1081. default: av_bprint_chars(dst, *p, 1);
  1082. }
  1083. }
  1084. return dst->str;
  1085. }
  1086. #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
  1087. static void xml_print_section_header(WriterContext *wctx)
  1088. {
  1089. XMLContext *xml = wctx->priv;
  1090. const struct section *section = wctx->section[wctx->level];
  1091. const struct section *parent_section = wctx->level ?
  1092. wctx->section[wctx->level-1] : NULL;
  1093. if (wctx->level == 0) {
  1094. const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
  1095. "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
  1096. "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
  1097. printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  1098. printf("<%sffprobe%s>\n",
  1099. xml->fully_qualified ? "ffprobe:" : "",
  1100. xml->fully_qualified ? qual : "");
  1101. return;
  1102. }
  1103. if (xml->within_tag) {
  1104. xml->within_tag = 0;
  1105. printf(">\n");
  1106. }
  1107. if (!strcmp(section->name, "tags")) {
  1108. xml->indent_level++;
  1109. } else {
  1110. if (!(parent_section->flags & SECTION_FLAG_IS_ARRAY) &&
  1111. (wctx->level && wctx->nb_item[wctx->level-1]))
  1112. printf("\n");
  1113. xml->indent_level++;
  1114. if (section->flags & SECTION_FLAG_IS_ARRAY) {
  1115. XML_INDENT(); printf("<%s>\n", section->name);
  1116. } else {
  1117. XML_INDENT(); printf("<%s ", section->name);
  1118. xml->within_tag = 1;
  1119. }
  1120. }
  1121. }
  1122. static void xml_print_section_footer(WriterContext *wctx)
  1123. {
  1124. XMLContext *xml = wctx->priv;
  1125. const struct section *section = wctx->section[wctx->level];
  1126. if (wctx->level == 0) {
  1127. printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
  1128. } else if (xml->within_tag) {
  1129. xml->within_tag = 0;
  1130. printf("/>\n");
  1131. xml->indent_level--;
  1132. } else if (!strcmp(section->name, "tags")) {
  1133. xml->indent_level--;
  1134. } else {
  1135. XML_INDENT(); printf("</%s>\n", section->name);
  1136. xml->indent_level--;
  1137. }
  1138. }
  1139. static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
  1140. {
  1141. AVBPrint buf;
  1142. XMLContext *xml = wctx->priv;
  1143. const struct section *section = wctx->section[wctx->level];
  1144. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1145. if (!strcmp(section->name, "tags")) {
  1146. XML_INDENT();
  1147. printf("<tag key=\"%s\"", xml_escape_str(&buf, key, wctx));
  1148. av_bprint_clear(&buf);
  1149. printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
  1150. } else {
  1151. if (wctx->nb_item[wctx->level])
  1152. printf(" ");
  1153. printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
  1154. }
  1155. av_bprint_finalize(&buf, NULL);
  1156. }
  1157. static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
  1158. {
  1159. if (wctx->nb_item[wctx->level])
  1160. printf(" ");
  1161. printf("%s=\"%lld\"", key, value);
  1162. }
  1163. static Writer xml_writer = {
  1164. .name = "xml",
  1165. .priv_size = sizeof(XMLContext),
  1166. .init = xml_init,
  1167. .print_section_header = xml_print_section_header,
  1168. .print_section_footer = xml_print_section_footer,
  1169. .print_integer = xml_print_int,
  1170. .print_string = xml_print_str,
  1171. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1172. .priv_class = &xml_class,
  1173. };
  1174. static void writer_register_all(void)
  1175. {
  1176. static int initialized;
  1177. if (initialized)
  1178. return;
  1179. initialized = 1;
  1180. writer_register(&default_writer);
  1181. writer_register(&compact_writer);
  1182. writer_register(&csv_writer);
  1183. writer_register(&flat_writer);
  1184. writer_register(&ini_writer);
  1185. writer_register(&json_writer);
  1186. writer_register(&xml_writer);
  1187. }
  1188. #define print_fmt(k, f, ...) do { \
  1189. av_bprint_clear(&pbuf); \
  1190. av_bprintf(&pbuf, f, __VA_ARGS__); \
  1191. writer_print_string(w, k, pbuf.str, 0); \
  1192. } while (0)
  1193. #define print_int(k, v) writer_print_integer(w, k, v)
  1194. #define print_q(k, v, s) writer_print_rational(w, k, v, s)
  1195. #define print_str(k, v) writer_print_string(w, k, v, 0)
  1196. #define print_str_opt(k, v) writer_print_string(w, k, v, 1)
  1197. #define print_time(k, v, tb) writer_print_time(w, k, v, tb, 0)
  1198. #define print_ts(k, v) writer_print_ts(w, k, v, 0)
  1199. #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
  1200. #define print_duration_ts(k, v) writer_print_ts(w, k, v, 1)
  1201. #define print_val(k, v, u) do { \
  1202. struct unit_value uv; \
  1203. uv.val.i = v; \
  1204. uv.unit = u; \
  1205. writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
  1206. } while (0)
  1207. #define print_section_header(s) writer_print_section_header(w, s)
  1208. #define print_section_footer(s) writer_print_section_footer(w, s)
  1209. static inline void show_tags(WriterContext *wctx, AVDictionary *tags, int section_id)
  1210. {
  1211. AVDictionaryEntry *tag = NULL;
  1212. if (!tags)
  1213. return;
  1214. writer_print_section_header(wctx, section_id);
  1215. while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX)))
  1216. writer_print_string(wctx, tag->key, tag->value, 0);
  1217. writer_print_section_footer(wctx);
  1218. }
  1219. static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
  1220. {
  1221. char val_str[128];
  1222. AVStream *st = fmt_ctx->streams[pkt->stream_index];
  1223. AVBPrint pbuf;
  1224. const char *s;
  1225. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1226. writer_print_section_header(w, SECTION_ID_PACKET);
  1227. s = av_get_media_type_string(st->codec->codec_type);
  1228. if (s) print_str ("codec_type", s);
  1229. else print_str_opt("codec_type", "unknown");
  1230. print_int("stream_index", pkt->stream_index);
  1231. print_ts ("pts", pkt->pts);
  1232. print_time("pts_time", pkt->pts, &st->time_base);
  1233. print_ts ("dts", pkt->dts);
  1234. print_time("dts_time", pkt->dts, &st->time_base);
  1235. print_duration_ts("duration", pkt->duration);
  1236. print_duration_time("duration_time", pkt->duration, &st->time_base);
  1237. print_duration_ts("convergence_duration", pkt->convergence_duration);
  1238. print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
  1239. print_val("size", pkt->size, unit_byte_str);
  1240. if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
  1241. else print_str_opt("pos", "N/A");
  1242. print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
  1243. if (do_show_data)
  1244. writer_print_data(w, "data", pkt->data, pkt->size);
  1245. writer_print_section_footer(w);
  1246. av_bprint_finalize(&pbuf, NULL);
  1247. fflush(stdout);
  1248. }
  1249. static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
  1250. AVFormatContext *fmt_ctx)
  1251. {
  1252. AVBPrint pbuf;
  1253. const char *s;
  1254. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1255. writer_print_section_header(w, SECTION_ID_FRAME);
  1256. s = av_get_media_type_string(stream->codec->codec_type);
  1257. if (s) print_str ("media_type", s);
  1258. else print_str_opt("media_type", "unknown");
  1259. print_int("key_frame", frame->key_frame);
  1260. print_ts ("pkt_pts", frame->pkt_pts);
  1261. print_time("pkt_pts_time", frame->pkt_pts, &stream->time_base);
  1262. print_ts ("pkt_dts", frame->pkt_dts);
  1263. print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
  1264. print_duration_ts ("pkt_duration", frame->pkt_duration);
  1265. print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
  1266. if (frame->pkt_pos != -1) print_fmt ("pkt_pos", "%"PRId64, frame->pkt_pos);
  1267. else print_str_opt("pkt_pos", "N/A");
  1268. switch (stream->codec->codec_type) {
  1269. AVRational sar;
  1270. case AVMEDIA_TYPE_VIDEO:
  1271. print_int("width", frame->width);
  1272. print_int("height", frame->height);
  1273. s = av_get_pix_fmt_name(frame->format);
  1274. if (s) print_str ("pix_fmt", s);
  1275. else print_str_opt("pix_fmt", "unknown");
  1276. sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
  1277. if (sar.num) {
  1278. print_q("sample_aspect_ratio", sar, ':');
  1279. } else {
  1280. print_str_opt("sample_aspect_ratio", "N/A");
  1281. }
  1282. print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
  1283. print_int("coded_picture_number", frame->coded_picture_number);
  1284. print_int("display_picture_number", frame->display_picture_number);
  1285. print_int("interlaced_frame", frame->interlaced_frame);
  1286. print_int("top_field_first", frame->top_field_first);
  1287. print_int("repeat_pict", frame->repeat_pict);
  1288. print_int("reference", frame->reference);
  1289. break;
  1290. case AVMEDIA_TYPE_AUDIO:
  1291. s = av_get_sample_fmt_name(frame->format);
  1292. if (s) print_str ("sample_fmt", s);
  1293. else print_str_opt("sample_fmt", "unknown");
  1294. print_int("nb_samples", frame->nb_samples);
  1295. print_int("channels", av_frame_get_channels(frame));
  1296. if (av_frame_get_channel_layout(frame)) {
  1297. av_bprint_clear(&pbuf);
  1298. av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
  1299. av_frame_get_channel_layout(frame));
  1300. print_str ("channel_layout", pbuf.str);
  1301. } else
  1302. print_str_opt("channel_layout", "unknown");
  1303. break;
  1304. }
  1305. show_tags(w, av_frame_get_metadata(frame), SECTION_ID_FRAME_TAGS);
  1306. writer_print_section_footer(w);
  1307. av_bprint_finalize(&pbuf, NULL);
  1308. fflush(stdout);
  1309. }
  1310. static av_always_inline int process_frame(WriterContext *w,
  1311. AVFormatContext *fmt_ctx,
  1312. AVFrame *frame, AVPacket *pkt)
  1313. {
  1314. AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  1315. int ret = 0, got_frame = 0;
  1316. avcodec_get_frame_defaults(frame);
  1317. if (dec_ctx->codec) {
  1318. switch (dec_ctx->codec_type) {
  1319. case AVMEDIA_TYPE_VIDEO:
  1320. ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
  1321. break;
  1322. case AVMEDIA_TYPE_AUDIO:
  1323. ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
  1324. break;
  1325. }
  1326. }
  1327. if (ret < 0)
  1328. return ret;
  1329. ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
  1330. pkt->data += ret;
  1331. pkt->size -= ret;
  1332. if (got_frame) {
  1333. nb_streams_frames[pkt->stream_index]++;
  1334. if (do_show_frames)
  1335. show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
  1336. }
  1337. return got_frame;
  1338. }
  1339. static void read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
  1340. {
  1341. AVPacket pkt, pkt1;
  1342. AVFrame frame;
  1343. int i = 0;
  1344. av_init_packet(&pkt);
  1345. while (!av_read_frame(fmt_ctx, &pkt)) {
  1346. if (do_read_packets) {
  1347. if (do_show_packets)
  1348. show_packet(w, fmt_ctx, &pkt, i++);
  1349. nb_streams_packets[pkt.stream_index]++;
  1350. }
  1351. if (do_read_frames) {
  1352. pkt1 = pkt;
  1353. while (pkt1.size && process_frame(w, fmt_ctx, &frame, &pkt1) > 0);
  1354. }
  1355. av_free_packet(&pkt);
  1356. }
  1357. av_init_packet(&pkt);
  1358. pkt.data = NULL;
  1359. pkt.size = 0;
  1360. //Flush remaining frames that are cached in the decoder
  1361. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1362. pkt.stream_index = i;
  1363. if (do_read_frames)
  1364. while (process_frame(w, fmt_ctx, &frame, &pkt) > 0);
  1365. }
  1366. }
  1367. static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)
  1368. {
  1369. AVStream *stream = fmt_ctx->streams[stream_idx];
  1370. AVCodecContext *dec_ctx;
  1371. const AVCodec *dec;
  1372. char val_str[128];
  1373. const char *s;
  1374. AVRational sar, dar;
  1375. AVBPrint pbuf;
  1376. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1377. writer_print_section_header(w, SECTION_ID_STREAM);
  1378. print_int("index", stream->index);
  1379. if ((dec_ctx = stream->codec)) {
  1380. const char *profile = NULL;
  1381. dec = dec_ctx->codec;
  1382. if (dec) {
  1383. print_str("codec_name", dec->name);
  1384. if (!do_bitexact) {
  1385. if (dec->long_name) print_str ("codec_long_name", dec->long_name);
  1386. else print_str_opt("codec_long_name", "unknown");
  1387. }
  1388. } else {
  1389. print_str_opt("codec_name", "unknown");
  1390. if (!do_bitexact) {
  1391. print_str_opt("codec_long_name", "unknown");
  1392. }
  1393. }
  1394. if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
  1395. print_str("profile", profile);
  1396. else
  1397. print_str_opt("profile", "unknown");
  1398. s = av_get_media_type_string(dec_ctx->codec_type);
  1399. if (s) print_str ("codec_type", s);
  1400. else print_str_opt("codec_type", "unknown");
  1401. print_q("codec_time_base", dec_ctx->time_base, '/');
  1402. /* print AVI/FourCC tag */
  1403. av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
  1404. print_str("codec_tag_string", val_str);
  1405. print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
  1406. /* Print useful disposition */
  1407. print_int("default", !!(stream->disposition & AV_DISPOSITION_DEFAULT));
  1408. print_int("forced", !!(stream->disposition & AV_DISPOSITION_FORCED));
  1409. switch (dec_ctx->codec_type) {
  1410. case AVMEDIA_TYPE_VIDEO:
  1411. print_int("width", dec_ctx->width);
  1412. print_int("height", dec_ctx->height);
  1413. print_int("has_b_frames", dec_ctx->has_b_frames);
  1414. sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
  1415. if (sar.den) {
  1416. print_q("sample_aspect_ratio", sar, ':');
  1417. av_reduce(&dar.num, &dar.den,
  1418. dec_ctx->width * sar.num,
  1419. dec_ctx->height * sar.den,
  1420. 1024*1024);
  1421. print_q("display_aspect_ratio", dar, ':');
  1422. } else {
  1423. print_str_opt("sample_aspect_ratio", "N/A");
  1424. print_str_opt("display_aspect_ratio", "N/A");
  1425. }
  1426. s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
  1427. if (s) print_str ("pix_fmt", s);
  1428. else print_str_opt("pix_fmt", "unknown");
  1429. print_int("level", dec_ctx->level);
  1430. if (dec_ctx->timecode_frame_start >= 0) {
  1431. char tcbuf[AV_TIMECODE_STR_SIZE];
  1432. av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
  1433. print_str("timecode", tcbuf);
  1434. } else {
  1435. print_str_opt("timecode", "N/A");
  1436. }
  1437. print_int("attached_pic",
  1438. !!(stream->disposition & AV_DISPOSITION_ATTACHED_PIC));
  1439. break;
  1440. case AVMEDIA_TYPE_AUDIO:
  1441. s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
  1442. if (s) print_str ("sample_fmt", s);
  1443. else print_str_opt("sample_fmt", "unknown");
  1444. print_val("sample_rate", dec_ctx->sample_rate, unit_hertz_str);
  1445. print_int("channels", dec_ctx->channels);
  1446. print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
  1447. break;
  1448. }
  1449. } else {
  1450. print_str_opt("codec_type", "unknown");
  1451. }
  1452. if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
  1453. const AVOption *opt = NULL;
  1454. while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
  1455. uint8_t *str;
  1456. if (opt->flags) continue;
  1457. if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
  1458. print_str(opt->name, str);
  1459. av_free(str);
  1460. }
  1461. }
  1462. }
  1463. if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
  1464. else print_str_opt("id", "N/A");
  1465. print_q("r_frame_rate", stream->r_frame_rate, '/');
  1466. print_q("avg_frame_rate", stream->avg_frame_rate, '/');
  1467. print_q("time_base", stream->time_base, '/');
  1468. print_ts ("start_pts", stream->start_time);
  1469. print_time("start_time", stream->start_time, &stream->time_base);
  1470. print_ts ("duration_ts", stream->duration);
  1471. print_time("duration", stream->duration, &stream->time_base);
  1472. if (dec_ctx->bit_rate > 0) print_val ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
  1473. else print_str_opt("bit_rate", "N/A");
  1474. if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
  1475. else print_str_opt("nb_frames", "N/A");
  1476. if (nb_streams_frames[stream_idx]) print_fmt ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
  1477. else print_str_opt("nb_read_frames", "N/A");
  1478. if (nb_streams_packets[stream_idx]) print_fmt ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
  1479. else print_str_opt("nb_read_packets", "N/A");
  1480. if (do_show_data)
  1481. writer_print_data(w, "extradata", dec_ctx->extradata,
  1482. dec_ctx->extradata_size);
  1483. show_tags(w, stream->metadata, SECTION_ID_STREAM_TAGS);
  1484. writer_print_section_footer(w);
  1485. av_bprint_finalize(&pbuf, NULL);
  1486. fflush(stdout);
  1487. }
  1488. static void show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
  1489. {
  1490. int i;
  1491. writer_print_section_header(w, SECTION_ID_STREAMS);
  1492. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1493. show_stream(w, fmt_ctx, i);
  1494. writer_print_section_footer(w);
  1495. }
  1496. static void show_format(WriterContext *w, AVFormatContext *fmt_ctx)
  1497. {
  1498. char val_str[128];
  1499. int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
  1500. writer_print_section_header(w, SECTION_ID_FORMAT);
  1501. print_str("filename", fmt_ctx->filename);
  1502. print_int("nb_streams", fmt_ctx->nb_streams);
  1503. print_str("format_name", fmt_ctx->iformat->name);
  1504. if (!do_bitexact) {
  1505. if (fmt_ctx->iformat->long_name) print_str ("format_long_name", fmt_ctx->iformat->long_name);
  1506. else print_str_opt("format_long_name", "unknown");
  1507. }
  1508. print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
  1509. print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
  1510. if (size >= 0) print_val ("size", size, unit_byte_str);
  1511. else print_str_opt("size", "N/A");
  1512. if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
  1513. else print_str_opt("bit_rate", "N/A");
  1514. show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
  1515. writer_print_section_footer(w);
  1516. fflush(stdout);
  1517. }
  1518. static void show_error(WriterContext *w, int err)
  1519. {
  1520. char errbuf[128];
  1521. const char *errbuf_ptr = errbuf;
  1522. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  1523. errbuf_ptr = strerror(AVUNERROR(err));
  1524. writer_print_section_header(w, SECTION_ID_ERROR);
  1525. print_int("code", err);
  1526. print_str("string", errbuf_ptr);
  1527. writer_print_section_footer(w);
  1528. }
  1529. static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
  1530. {
  1531. int err, i;
  1532. AVFormatContext *fmt_ctx = NULL;
  1533. AVDictionaryEntry *t;
  1534. if ((err = avformat_open_input(&fmt_ctx, filename,
  1535. iformat, &format_opts)) < 0) {
  1536. print_error(filename, err);
  1537. return err;
  1538. }
  1539. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  1540. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  1541. return AVERROR_OPTION_NOT_FOUND;
  1542. }
  1543. /* fill the streams in the format context */
  1544. if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
  1545. print_error(filename, err);
  1546. return err;
  1547. }
  1548. av_dump_format(fmt_ctx, 0, filename, 0);
  1549. /* bind a decoder to each input stream */
  1550. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1551. AVStream *stream = fmt_ctx->streams[i];
  1552. AVCodec *codec;
  1553. if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
  1554. av_log(NULL, AV_LOG_ERROR,
  1555. "Failed to probe codec for input stream %d\n",
  1556. stream->index);
  1557. } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
  1558. av_log(NULL, AV_LOG_ERROR,
  1559. "Unsupported codec with id %d for input stream %d\n",
  1560. stream->codec->codec_id, stream->index);
  1561. } else if (avcodec_open2(stream->codec, codec, NULL) < 0) {
  1562. av_log(NULL, AV_LOG_ERROR, "Error while opening codec for input stream %d\n",
  1563. stream->index);
  1564. }
  1565. }
  1566. *fmt_ctx_ptr = fmt_ctx;
  1567. return 0;
  1568. }
  1569. static void close_input_file(AVFormatContext **ctx_ptr)
  1570. {
  1571. int i;
  1572. AVFormatContext *fmt_ctx = *ctx_ptr;
  1573. /* close decoder for each stream */
  1574. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1575. if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
  1576. avcodec_close(fmt_ctx->streams[i]->codec);
  1577. avformat_close_input(ctx_ptr);
  1578. }
  1579. static int probe_file(WriterContext *wctx, const char *filename)
  1580. {
  1581. AVFormatContext *fmt_ctx;
  1582. int ret;
  1583. int section_id;
  1584. do_read_frames = do_show_frames || do_count_frames;
  1585. do_read_packets = do_show_packets || do_count_packets;
  1586. ret = open_input_file(&fmt_ctx, filename);
  1587. if (ret >= 0) {
  1588. nb_streams_frames = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
  1589. nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
  1590. if (do_read_frames || do_read_packets) {
  1591. if (do_show_frames && do_show_packets &&
  1592. wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
  1593. section_id = SECTION_ID_PACKETS_AND_FRAMES;
  1594. else if (do_show_packets && !do_show_frames)
  1595. section_id = SECTION_ID_PACKETS;
  1596. else // (!do_show_packets && do_show_frames)
  1597. section_id = SECTION_ID_FRAMES;
  1598. if (do_show_frames || do_show_packets)
  1599. writer_print_section_header(wctx, section_id);
  1600. read_packets(wctx, fmt_ctx);
  1601. if (do_show_frames || do_show_packets)
  1602. writer_print_section_footer(wctx);
  1603. }
  1604. if (do_show_streams)
  1605. show_streams(wctx, fmt_ctx);
  1606. if (do_show_format)
  1607. show_format(wctx, fmt_ctx);
  1608. close_input_file(&fmt_ctx);
  1609. av_freep(&nb_streams_frames);
  1610. av_freep(&nb_streams_packets);
  1611. }
  1612. return ret;
  1613. }
  1614. static void show_usage(void)
  1615. {
  1616. av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
  1617. av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
  1618. av_log(NULL, AV_LOG_INFO, "\n");
  1619. }
  1620. static void ffprobe_show_program_version(WriterContext *w)
  1621. {
  1622. AVBPrint pbuf;
  1623. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1624. writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
  1625. print_str("version", FFMPEG_VERSION);
  1626. print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
  1627. program_birth_year, this_year);
  1628. print_str("build_date", __DATE__);
  1629. print_str("build_time", __TIME__);
  1630. print_str("compiler_ident", CC_IDENT);
  1631. print_str("configuration", FFMPEG_CONFIGURATION);
  1632. writer_print_section_footer(w);
  1633. av_bprint_finalize(&pbuf, NULL);
  1634. }
  1635. #define SHOW_LIB_VERSION(libname, LIBNAME) \
  1636. do { \
  1637. if (CONFIG_##LIBNAME) { \
  1638. unsigned int version = libname##_version(); \
  1639. writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
  1640. print_str("name", "lib" #libname); \
  1641. print_int("major", LIB##LIBNAME##_VERSION_MAJOR); \
  1642. print_int("minor", LIB##LIBNAME##_VERSION_MINOR); \
  1643. print_int("micro", LIB##LIBNAME##_VERSION_MICRO); \
  1644. print_int("version", version); \
  1645. print_str("ident", LIB##LIBNAME##_IDENT); \
  1646. writer_print_section_footer(w); \
  1647. } \
  1648. } while (0)
  1649. static void ffprobe_show_library_versions(WriterContext *w)
  1650. {
  1651. writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
  1652. SHOW_LIB_VERSION(avutil, AVUTIL);
  1653. SHOW_LIB_VERSION(avcodec, AVCODEC);
  1654. SHOW_LIB_VERSION(avformat, AVFORMAT);
  1655. SHOW_LIB_VERSION(avdevice, AVDEVICE);
  1656. SHOW_LIB_VERSION(avfilter, AVFILTER);
  1657. SHOW_LIB_VERSION(swscale, SWSCALE);
  1658. SHOW_LIB_VERSION(swresample, SWRESAMPLE);
  1659. SHOW_LIB_VERSION(postproc, POSTPROC);
  1660. writer_print_section_footer(w);
  1661. }
  1662. static int opt_format(void *optctx, const char *opt, const char *arg)
  1663. {
  1664. iformat = av_find_input_format(arg);
  1665. if (!iformat) {
  1666. av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
  1667. return AVERROR(EINVAL);
  1668. }
  1669. return 0;
  1670. }
  1671. static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
  1672. {
  1673. do_show_format = 1;
  1674. av_dict_set(&fmt_entries_to_show, arg, "", 0);
  1675. return 0;
  1676. }
  1677. static void opt_input_file(void *optctx, const char *arg)
  1678. {
  1679. if (input_filename) {
  1680. av_log(NULL, AV_LOG_ERROR,
  1681. "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  1682. arg, input_filename);
  1683. exit(1);
  1684. }
  1685. if (!strcmp(arg, "-"))
  1686. arg = "pipe:";
  1687. input_filename = arg;
  1688. }
  1689. static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
  1690. {
  1691. opt_input_file(optctx, arg);
  1692. return 0;
  1693. }
  1694. void show_help_default(const char *opt, const char *arg)
  1695. {
  1696. av_log_set_callback(log_callback_help);
  1697. show_usage();
  1698. show_help_options(options, "Main options:", 0, 0, 0);
  1699. printf("\n");
  1700. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  1701. }
  1702. static int opt_pretty(void *optctx, const char *opt, const char *arg)
  1703. {
  1704. show_value_unit = 1;
  1705. use_value_prefix = 1;
  1706. use_byte_value_binary_prefix = 1;
  1707. use_value_sexagesimal_format = 1;
  1708. return 0;
  1709. }
  1710. static int opt_show_versions(const char *opt, const char *arg)
  1711. {
  1712. do_show_program_version = 1;
  1713. do_show_library_versions = 1;
  1714. return 0;
  1715. }
  1716. static const OptionDef real_options[] = {
  1717. #include "cmdutils_common_opts.h"
  1718. { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
  1719. { "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
  1720. { "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
  1721. { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
  1722. "use binary prefixes for byte units" },
  1723. { "sexagesimal", OPT_BOOL, {&use_value_sexagesimal_format},
  1724. "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
  1725. { "pretty", 0, {.func_arg = opt_pretty},
  1726. "prettify the format of displayed values, make it more human readable" },
  1727. { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
  1728. "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
  1729. { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
  1730. { "show_data", OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
  1731. { "show_error", OPT_BOOL, {(void*)&do_show_error} , "show probing error" },
  1732. { "show_format", OPT_BOOL, {&do_show_format} , "show format/container info" },
  1733. { "show_frames", OPT_BOOL, {(void*)&do_show_frames} , "show frames info" },
  1734. { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
  1735. "show a particular entry from the format/container info", "entry" },
  1736. { "show_packets", OPT_BOOL, {&do_show_packets}, "show packets info" },
  1737. { "show_streams", OPT_BOOL, {&do_show_streams}, "show streams info" },
  1738. { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
  1739. { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
  1740. { "show_program_version", OPT_BOOL, {(void*)&do_show_program_version}, "show ffprobe version" },
  1741. { "show_library_versions", OPT_BOOL, {(void*)&do_show_library_versions}, "show library versions" },
  1742. { "show_versions", 0, {(void*)&opt_show_versions}, "show program and library versions" },
  1743. { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
  1744. { "private", OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
  1745. { "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
  1746. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
  1747. { "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
  1748. { NULL, },
  1749. };
  1750. int main(int argc, char **argv)
  1751. {
  1752. const Writer *w;
  1753. WriterContext *wctx;
  1754. char *buf;
  1755. char *w_name = NULL, *w_args = NULL;
  1756. int ret;
  1757. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  1758. options = real_options;
  1759. parse_loglevel(argc, argv, options);
  1760. av_register_all();
  1761. avformat_network_init();
  1762. init_opts();
  1763. #if CONFIG_AVDEVICE
  1764. avdevice_register_all();
  1765. #endif
  1766. show_banner(argc, argv, options);
  1767. parse_options(NULL, argc, argv, options, opt_input_file);
  1768. if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
  1769. av_log(NULL, AV_LOG_ERROR,
  1770. "-bitexact and -show_program_version or -show_library_versions "
  1771. "options are incompatible\n");
  1772. ret = AVERROR(EINVAL);
  1773. goto end;
  1774. }
  1775. writer_register_all();
  1776. if (!print_format)
  1777. print_format = av_strdup("default");
  1778. w_name = av_strtok(print_format, "=", &buf);
  1779. w_args = buf;
  1780. w = writer_get_by_name(w_name);
  1781. if (!w) {
  1782. av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
  1783. ret = AVERROR(EINVAL);
  1784. goto end;
  1785. }
  1786. if ((ret = writer_open(&wctx, w, w_args,
  1787. sections, FF_ARRAY_ELEMS(sections))) >= 0) {
  1788. writer_print_section_header(wctx, SECTION_ID_ROOT);
  1789. if (do_show_program_version)
  1790. ffprobe_show_program_version(wctx);
  1791. if (do_show_library_versions)
  1792. ffprobe_show_library_versions(wctx);
  1793. if (!input_filename &&
  1794. ((do_show_format || do_show_streams || do_show_packets || do_show_error) ||
  1795. (!do_show_program_version && !do_show_library_versions))) {
  1796. show_usage();
  1797. av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
  1798. av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
  1799. ret = AVERROR(EINVAL);
  1800. } else if (input_filename) {
  1801. ret = probe_file(wctx, input_filename);
  1802. if (ret < 0 && do_show_error)
  1803. show_error(wctx, ret);
  1804. }
  1805. writer_print_section_footer(wctx);
  1806. writer_close(&wctx);
  1807. }
  1808. end:
  1809. av_freep(&print_format);
  1810. uninit_opts();
  1811. av_dict_free(&fmt_entries_to_show);
  1812. avformat_network_deinit();
  1813. return ret;
  1814. }