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.

2990 lines
105KB

  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 "libavutil/ffversion.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/parseutils.h"
  37. #include "libavutil/timecode.h"
  38. #include "libavutil/timestamp.h"
  39. #include "libavdevice/avdevice.h"
  40. #include "libswscale/swscale.h"
  41. #include "libswresample/swresample.h"
  42. #include "libpostproc/postprocess.h"
  43. #include "cmdutils.h"
  44. const char program_name[] = "ffprobe";
  45. const int program_birth_year = 2007;
  46. static int do_bitexact = 0;
  47. static int do_count_frames = 0;
  48. static int do_count_packets = 0;
  49. static int do_read_frames = 0;
  50. static int do_read_packets = 0;
  51. static int do_show_chapters = 0;
  52. static int do_show_error = 0;
  53. static int do_show_format = 0;
  54. static int do_show_frames = 0;
  55. static int do_show_packets = 0;
  56. static int do_show_programs = 0;
  57. static int do_show_streams = 0;
  58. static int do_show_stream_disposition = 0;
  59. static int do_show_data = 0;
  60. static int do_show_program_version = 0;
  61. static int do_show_library_versions = 0;
  62. static int do_show_chapter_tags = 0;
  63. static int do_show_format_tags = 0;
  64. static int do_show_frame_tags = 0;
  65. static int do_show_program_tags = 0;
  66. static int do_show_stream_tags = 0;
  67. static int show_value_unit = 0;
  68. static int use_value_prefix = 0;
  69. static int use_byte_value_binary_prefix = 0;
  70. static int use_value_sexagesimal_format = 0;
  71. static int show_private_data = 1;
  72. static char *print_format;
  73. static char *stream_specifier;
  74. typedef struct {
  75. int id; ///< identifier
  76. int64_t start, end; ///< start, end in second/AV_TIME_BASE units
  77. int has_start, has_end;
  78. int start_is_offset, end_is_offset;
  79. int duration_frames;
  80. } ReadInterval;
  81. static ReadInterval *read_intervals;
  82. static int read_intervals_nb = 0;
  83. /* section structure definition */
  84. #define SECTION_MAX_NB_CHILDREN 10
  85. struct section {
  86. int id; ///< unique id identifying a section
  87. const char *name;
  88. #define SECTION_FLAG_IS_WRAPPER 1 ///< the section only contains other sections, but has no data at its own level
  89. #define SECTION_FLAG_IS_ARRAY 2 ///< the section contains an array of elements of the same type
  90. #define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
  91. /// For these sections the element_name field is mandatory.
  92. int flags;
  93. int children_ids[SECTION_MAX_NB_CHILDREN+1]; ///< list of children section IDS, terminated by -1
  94. const char *element_name; ///< name of the contained element, if provided
  95. const char *unique_name; ///< unique section name, in case the name is ambiguous
  96. AVDictionary *entries_to_show;
  97. int show_all_entries;
  98. };
  99. typedef enum {
  100. SECTION_ID_NONE = -1,
  101. SECTION_ID_CHAPTER,
  102. SECTION_ID_CHAPTER_TAGS,
  103. SECTION_ID_CHAPTERS,
  104. SECTION_ID_ERROR,
  105. SECTION_ID_FORMAT,
  106. SECTION_ID_FORMAT_TAGS,
  107. SECTION_ID_FRAME,
  108. SECTION_ID_FRAMES,
  109. SECTION_ID_FRAME_TAGS,
  110. SECTION_ID_LIBRARY_VERSION,
  111. SECTION_ID_LIBRARY_VERSIONS,
  112. SECTION_ID_PACKET,
  113. SECTION_ID_PACKETS,
  114. SECTION_ID_PACKETS_AND_FRAMES,
  115. SECTION_ID_PROGRAM_STREAM_DISPOSITION,
  116. SECTION_ID_PROGRAM_STREAM_TAGS,
  117. SECTION_ID_PROGRAM,
  118. SECTION_ID_PROGRAM_STREAMS,
  119. SECTION_ID_PROGRAM_STREAM,
  120. SECTION_ID_PROGRAM_TAGS,
  121. SECTION_ID_PROGRAM_VERSION,
  122. SECTION_ID_PROGRAMS,
  123. SECTION_ID_ROOT,
  124. SECTION_ID_STREAM,
  125. SECTION_ID_STREAM_DISPOSITION,
  126. SECTION_ID_STREAMS,
  127. SECTION_ID_STREAM_TAGS,
  128. SECTION_ID_SUBTITLE,
  129. } SectionID;
  130. static struct section sections[] = {
  131. [SECTION_ID_CHAPTERS] = { SECTION_ID_CHAPTERS, "chapters", SECTION_FLAG_IS_ARRAY, { SECTION_ID_CHAPTER, -1 } },
  132. [SECTION_ID_CHAPTER] = { SECTION_ID_CHAPTER, "chapter", 0, { SECTION_ID_CHAPTER_TAGS, -1 } },
  133. [SECTION_ID_CHAPTER_TAGS] = { SECTION_ID_CHAPTER_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "chapter_tags" },
  134. [SECTION_ID_ERROR] = { SECTION_ID_ERROR, "error", 0, { -1 } },
  135. [SECTION_ID_FORMAT] = { SECTION_ID_FORMAT, "format", 0, { SECTION_ID_FORMAT_TAGS, -1 } },
  136. [SECTION_ID_FORMAT_TAGS] = { SECTION_ID_FORMAT_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "format_tags" },
  137. [SECTION_ID_FRAMES] = { SECTION_ID_FRAMES, "frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME, SECTION_ID_SUBTITLE, -1 } },
  138. [SECTION_ID_FRAME] = { SECTION_ID_FRAME, "frame", 0, { SECTION_ID_FRAME_TAGS, -1 } },
  139. [SECTION_ID_FRAME_TAGS] = { SECTION_ID_FRAME_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "frame_tags" },
  140. [SECTION_ID_LIBRARY_VERSIONS] = { SECTION_ID_LIBRARY_VERSIONS, "library_versions", SECTION_FLAG_IS_ARRAY, { SECTION_ID_LIBRARY_VERSION, -1 } },
  141. [SECTION_ID_LIBRARY_VERSION] = { SECTION_ID_LIBRARY_VERSION, "library_version", 0, { -1 } },
  142. [SECTION_ID_PACKETS] = { SECTION_ID_PACKETS, "packets", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
  143. [SECTION_ID_PACKETS_AND_FRAMES] = { SECTION_ID_PACKETS_AND_FRAMES, "packets_and_frames", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET, -1} },
  144. [SECTION_ID_PACKET] = { SECTION_ID_PACKET, "packet", 0, { -1 } },
  145. [SECTION_ID_PROGRAM_STREAM_DISPOSITION] = { SECTION_ID_PROGRAM_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "program_stream_disposition" },
  146. [SECTION_ID_PROGRAM_STREAM_TAGS] = { SECTION_ID_PROGRAM_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_stream_tags" },
  147. [SECTION_ID_PROGRAM] = { SECTION_ID_PROGRAM, "program", 0, { SECTION_ID_PROGRAM_TAGS, SECTION_ID_PROGRAM_STREAMS, -1 } },
  148. [SECTION_ID_PROGRAM_STREAMS] = { SECTION_ID_PROGRAM_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM_STREAM, -1 }, .unique_name = "program_streams" },
  149. [SECTION_ID_PROGRAM_STREAM] = { SECTION_ID_PROGRAM_STREAM, "stream", 0, { SECTION_ID_PROGRAM_STREAM_DISPOSITION, SECTION_ID_PROGRAM_STREAM_TAGS, -1 }, .unique_name = "program_stream" },
  150. [SECTION_ID_PROGRAM_TAGS] = { SECTION_ID_PROGRAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_tags" },
  151. [SECTION_ID_PROGRAM_VERSION] = { SECTION_ID_PROGRAM_VERSION, "program_version", 0, { -1 } },
  152. [SECTION_ID_PROGRAMS] = { SECTION_ID_PROGRAMS, "programs", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM, -1 } },
  153. [SECTION_ID_ROOT] = { SECTION_ID_ROOT, "root", SECTION_FLAG_IS_WRAPPER,
  154. { SECTION_ID_CHAPTERS, SECTION_ID_FORMAT, SECTION_ID_FRAMES, SECTION_ID_PROGRAMS, SECTION_ID_STREAMS,
  155. SECTION_ID_PACKETS, SECTION_ID_ERROR, SECTION_ID_PROGRAM_VERSION, SECTION_ID_LIBRARY_VERSIONS, -1} },
  156. [SECTION_ID_STREAMS] = { SECTION_ID_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM, -1 } },
  157. [SECTION_ID_STREAM] = { SECTION_ID_STREAM, "stream", 0, { SECTION_ID_STREAM_DISPOSITION, SECTION_ID_STREAM_TAGS, -1 } },
  158. [SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "stream_disposition" },
  159. [SECTION_ID_STREAM_TAGS] = { SECTION_ID_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "stream_tags" },
  160. [SECTION_ID_SUBTITLE] = { SECTION_ID_SUBTITLE, "subtitle", 0, { -1 } },
  161. };
  162. static const OptionDef *options;
  163. /* FFprobe context */
  164. static const char *input_filename;
  165. static AVInputFormat *iformat = NULL;
  166. static const char *const binary_unit_prefixes [] = { "", "Ki", "Mi", "Gi", "Ti", "Pi" };
  167. static const char *const decimal_unit_prefixes[] = { "", "K" , "M" , "G" , "T" , "P" };
  168. static const char unit_second_str[] = "s" ;
  169. static const char unit_hertz_str[] = "Hz" ;
  170. static const char unit_byte_str[] = "byte" ;
  171. static const char unit_bit_per_second_str[] = "bit/s";
  172. static uint64_t *nb_streams_packets;
  173. static uint64_t *nb_streams_frames;
  174. static int *selected_streams;
  175. static void ffprobe_cleanup(int ret)
  176. {
  177. int i;
  178. for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
  179. av_dict_free(&(sections[i].entries_to_show));
  180. }
  181. struct unit_value {
  182. union { double d; long long int i; } val;
  183. const char *unit;
  184. };
  185. static char *value_string(char *buf, int buf_size, struct unit_value uv)
  186. {
  187. double vald;
  188. long long int vali;
  189. int show_float = 0;
  190. if (uv.unit == unit_second_str) {
  191. vald = uv.val.d;
  192. show_float = 1;
  193. } else {
  194. vald = vali = uv.val.i;
  195. }
  196. if (uv.unit == unit_second_str && use_value_sexagesimal_format) {
  197. double secs;
  198. int hours, mins;
  199. secs = vald;
  200. mins = (int)secs / 60;
  201. secs = secs - mins * 60;
  202. hours = mins / 60;
  203. mins %= 60;
  204. snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
  205. } else {
  206. const char *prefix_string = "";
  207. if (use_value_prefix && vald > 1) {
  208. long long int index;
  209. if (uv.unit == unit_byte_str && use_byte_value_binary_prefix) {
  210. index = (long long int) (log2(vald)) / 10;
  211. index = av_clip(index, 0, FF_ARRAY_ELEMS(binary_unit_prefixes) - 1);
  212. vald /= exp2(index * 10);
  213. prefix_string = binary_unit_prefixes[index];
  214. } else {
  215. index = (long long int) (log10(vald)) / 3;
  216. index = av_clip(index, 0, FF_ARRAY_ELEMS(decimal_unit_prefixes) - 1);
  217. vald /= pow(10, index * 3);
  218. prefix_string = decimal_unit_prefixes[index];
  219. }
  220. vali = vald;
  221. }
  222. if (show_float || (use_value_prefix && vald != (long long int)vald))
  223. snprintf(buf, buf_size, "%f", vald);
  224. else
  225. snprintf(buf, buf_size, "%lld", vali);
  226. av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
  227. prefix_string, show_value_unit ? uv.unit : "");
  228. }
  229. return buf;
  230. }
  231. /* WRITERS API */
  232. typedef struct WriterContext WriterContext;
  233. #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
  234. #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
  235. typedef enum {
  236. WRITER_STRING_VALIDATION_FAIL,
  237. WRITER_STRING_VALIDATION_REPLACE,
  238. WRITER_STRING_VALIDATION_IGNORE,
  239. WRITER_STRING_VALIDATION_NB
  240. } StringValidation;
  241. typedef struct Writer {
  242. const AVClass *priv_class; ///< private class of the writer, if any
  243. int priv_size; ///< private size for the writer context
  244. const char *name;
  245. int (*init) (WriterContext *wctx);
  246. void (*uninit)(WriterContext *wctx);
  247. void (*print_section_header)(WriterContext *wctx);
  248. void (*print_section_footer)(WriterContext *wctx);
  249. void (*print_integer) (WriterContext *wctx, const char *, long long int);
  250. void (*print_rational) (WriterContext *wctx, AVRational *q, char *sep);
  251. void (*print_string) (WriterContext *wctx, const char *, const char *);
  252. int flags; ///< a combination or WRITER_FLAG_*
  253. } Writer;
  254. #define SECTION_MAX_NB_LEVELS 10
  255. struct WriterContext {
  256. const AVClass *class; ///< class of the writer
  257. const Writer *writer; ///< the Writer of which this is an instance
  258. char *name; ///< name of this writer instance
  259. void *priv; ///< private data for use by the filter
  260. const struct section *sections; ///< array containing all sections
  261. int nb_sections; ///< number of sections
  262. int level; ///< current level, starting from 0
  263. /** number of the item printed in the given section, starting from 0 */
  264. unsigned int nb_item[SECTION_MAX_NB_LEVELS];
  265. /** section per each level */
  266. const struct section *section[SECTION_MAX_NB_LEVELS];
  267. AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
  268. /// used by various writers
  269. unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
  270. unsigned int nb_section_frame; ///< number of the frame section in case we are in "packets_and_frames" section
  271. unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
  272. StringValidation string_validation;
  273. char *string_validation_replacement;
  274. unsigned int string_validation_utf8_flags;
  275. };
  276. static const char *writer_get_name(void *p)
  277. {
  278. WriterContext *wctx = p;
  279. return wctx->writer->name;
  280. }
  281. #define OFFSET(x) offsetof(WriterContext, x)
  282. static const AVOption writer_options[] = {
  283. { "string_validation", "set string validation mode",
  284. OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
  285. { "sv", "set string validation mode",
  286. OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
  287. { "ignore", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_IGNORE}, .unit = "sv" },
  288. { "replace", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_REPLACE}, .unit = "sv" },
  289. { "fail", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_FAIL}, .unit = "sv" },
  290. { "string_validation_replacement", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
  291. { "svr", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str="\xEF\xBF\xBD"}},
  292. { NULL }
  293. };
  294. static void *writer_child_next(void *obj, void *prev)
  295. {
  296. WriterContext *ctx = obj;
  297. if (!prev && ctx->writer && ctx->writer->priv_class && ctx->priv)
  298. return ctx->priv;
  299. return NULL;
  300. }
  301. static const AVClass writer_class = {
  302. .class_name = "Writer",
  303. .item_name = writer_get_name,
  304. .option = writer_options,
  305. .version = LIBAVUTIL_VERSION_INT,
  306. .child_next = writer_child_next,
  307. };
  308. static void writer_close(WriterContext **wctx)
  309. {
  310. int i;
  311. if (!*wctx)
  312. return;
  313. if ((*wctx)->writer->uninit)
  314. (*wctx)->writer->uninit(*wctx);
  315. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  316. av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
  317. if ((*wctx)->writer->priv_class)
  318. av_opt_free((*wctx)->priv);
  319. av_freep(&((*wctx)->priv));
  320. av_opt_free(*wctx);
  321. av_freep(wctx);
  322. }
  323. static void bprint_bytes(AVBPrint *bp, const uint8_t *ubuf, size_t ubuf_size)
  324. {
  325. int i;
  326. av_bprintf(bp, "0X");
  327. for (i = 0; i < ubuf_size; i++)
  328. av_bprintf(bp, "%02X", ubuf[i]);
  329. }
  330. static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
  331. const struct section *sections, int nb_sections)
  332. {
  333. int i, ret = 0;
  334. if (!(*wctx = av_mallocz(sizeof(WriterContext)))) {
  335. ret = AVERROR(ENOMEM);
  336. goto fail;
  337. }
  338. if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
  339. ret = AVERROR(ENOMEM);
  340. goto fail;
  341. }
  342. (*wctx)->class = &writer_class;
  343. (*wctx)->writer = writer;
  344. (*wctx)->level = -1;
  345. (*wctx)->sections = sections;
  346. (*wctx)->nb_sections = nb_sections;
  347. av_opt_set_defaults(*wctx);
  348. if (writer->priv_class) {
  349. void *priv_ctx = (*wctx)->priv;
  350. *((const AVClass **)priv_ctx) = writer->priv_class;
  351. av_opt_set_defaults(priv_ctx);
  352. }
  353. /* convert options to dictionary */
  354. if (args) {
  355. AVDictionary *opts = NULL;
  356. AVDictionaryEntry *opt = NULL;
  357. if ((ret = av_dict_parse_string(&opts, args, "=", ":", 0)) < 0) {
  358. av_log(*wctx, AV_LOG_ERROR, "Failed to parse option string '%s' provided to writer context\n", args);
  359. av_dict_free(&opts);
  360. goto fail;
  361. }
  362. while ((opt = av_dict_get(opts, "", opt, AV_DICT_IGNORE_SUFFIX))) {
  363. if ((ret = av_opt_set(*wctx, opt->key, opt->value, AV_OPT_SEARCH_CHILDREN)) < 0) {
  364. av_log(*wctx, AV_LOG_ERROR, "Failed to set option '%s' with value '%s' provided to writer context\n",
  365. opt->key, opt->value);
  366. av_dict_free(&opts);
  367. goto fail;
  368. }
  369. }
  370. av_dict_free(&opts);
  371. }
  372. /* validate replace string */
  373. {
  374. const uint8_t *p = (*wctx)->string_validation_replacement;
  375. const uint8_t *endp = p + strlen(p);
  376. while (*p) {
  377. const uint8_t *p0 = p;
  378. int32_t code;
  379. ret = av_utf8_decode(&code, &p, endp, (*wctx)->string_validation_utf8_flags);
  380. if (ret < 0) {
  381. AVBPrint bp;
  382. av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
  383. bprint_bytes(&bp, p0, p-p0),
  384. av_log(wctx, AV_LOG_ERROR,
  385. "Invalid UTF8 sequence %s found in string validation replace '%s'\n",
  386. bp.str, (*wctx)->string_validation_replacement);
  387. return ret;
  388. }
  389. }
  390. }
  391. for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
  392. av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
  393. if ((*wctx)->writer->init)
  394. ret = (*wctx)->writer->init(*wctx);
  395. if (ret < 0)
  396. goto fail;
  397. return 0;
  398. fail:
  399. writer_close(wctx);
  400. return ret;
  401. }
  402. static inline void writer_print_section_header(WriterContext *wctx,
  403. int section_id)
  404. {
  405. int parent_section_id;
  406. wctx->level++;
  407. av_assert0(wctx->level < SECTION_MAX_NB_LEVELS);
  408. parent_section_id = wctx->level ?
  409. (wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
  410. wctx->nb_item[wctx->level] = 0;
  411. wctx->section[wctx->level] = &wctx->sections[section_id];
  412. if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
  413. wctx->nb_section_packet = wctx->nb_section_frame =
  414. wctx->nb_section_packet_frame = 0;
  415. } else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
  416. wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
  417. wctx->nb_section_packet : wctx->nb_section_frame;
  418. }
  419. if (wctx->writer->print_section_header)
  420. wctx->writer->print_section_header(wctx);
  421. }
  422. static inline void writer_print_section_footer(WriterContext *wctx)
  423. {
  424. int section_id = wctx->section[wctx->level]->id;
  425. int parent_section_id = wctx->level ?
  426. wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
  427. if (parent_section_id != SECTION_ID_NONE)
  428. wctx->nb_item[wctx->level-1]++;
  429. if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
  430. if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
  431. else wctx->nb_section_frame++;
  432. }
  433. if (wctx->writer->print_section_footer)
  434. wctx->writer->print_section_footer(wctx);
  435. wctx->level--;
  436. }
  437. static inline void writer_print_integer(WriterContext *wctx,
  438. const char *key, long long int val)
  439. {
  440. const struct section *section = wctx->section[wctx->level];
  441. if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
  442. wctx->writer->print_integer(wctx, key, val);
  443. wctx->nb_item[wctx->level]++;
  444. }
  445. }
  446. static inline int validate_string(WriterContext *wctx, char **dstp, const char *src)
  447. {
  448. const uint8_t *p, *endp;
  449. AVBPrint dstbuf;
  450. int invalid_chars_nb = 0, ret = 0;
  451. av_bprint_init(&dstbuf, 0, AV_BPRINT_SIZE_UNLIMITED);
  452. endp = src + strlen(src);
  453. for (p = (uint8_t *)src; *p;) {
  454. uint32_t code;
  455. int invalid = 0;
  456. const uint8_t *p0 = p;
  457. if (av_utf8_decode(&code, &p, endp, wctx->string_validation_utf8_flags) < 0) {
  458. AVBPrint bp;
  459. av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);
  460. bprint_bytes(&bp, p0, p-p0);
  461. av_log(wctx, AV_LOG_DEBUG,
  462. "Invalid UTF-8 sequence %s found in string '%s'\n", bp.str, src);
  463. invalid = 1;
  464. }
  465. if (invalid) {
  466. invalid_chars_nb++;
  467. switch (wctx->string_validation) {
  468. case WRITER_STRING_VALIDATION_FAIL:
  469. av_log(wctx, AV_LOG_ERROR,
  470. "Invalid UTF-8 sequence found in string '%s'\n", src);
  471. ret = AVERROR_INVALIDDATA;
  472. goto end;
  473. break;
  474. case WRITER_STRING_VALIDATION_REPLACE:
  475. av_bprintf(&dstbuf, "%s", wctx->string_validation_replacement);
  476. break;
  477. }
  478. }
  479. if (!invalid || wctx->string_validation == WRITER_STRING_VALIDATION_IGNORE)
  480. av_bprint_append_data(&dstbuf, p0, p-p0);
  481. }
  482. if (invalid_chars_nb && wctx->string_validation == WRITER_STRING_VALIDATION_REPLACE) {
  483. av_log(wctx, AV_LOG_WARNING,
  484. "%d invalid UTF-8 sequence(s) found in string '%s', replaced with '%s'\n",
  485. invalid_chars_nb, src, wctx->string_validation_replacement);
  486. }
  487. end:
  488. av_bprint_finalize(&dstbuf, dstp);
  489. return ret;
  490. }
  491. #define PRINT_STRING_OPT 1
  492. #define PRINT_STRING_VALIDATE 2
  493. static inline int writer_print_string(WriterContext *wctx,
  494. const char *key, const char *val, int flags)
  495. {
  496. const struct section *section = wctx->section[wctx->level];
  497. int ret = 0;
  498. if ((flags & PRINT_STRING_OPT)
  499. && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))
  500. return 0;
  501. if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {
  502. if (flags & PRINT_STRING_VALIDATE) {
  503. char *key1 = NULL, *val1 = NULL;
  504. ret = validate_string(wctx, &key1, key);
  505. if (ret < 0) goto end;
  506. ret = validate_string(wctx, &val1, val);
  507. if (ret < 0) goto end;
  508. wctx->writer->print_string(wctx, key1, val1);
  509. end:
  510. if (ret < 0) {
  511. av_log(wctx, AV_LOG_ERROR,
  512. "Invalid key=value string combination %s=%s in section %s\n",
  513. key, val, section->unique_name);
  514. }
  515. av_free(key1);
  516. av_free(val1);
  517. } else {
  518. wctx->writer->print_string(wctx, key, val);
  519. }
  520. wctx->nb_item[wctx->level]++;
  521. }
  522. return ret;
  523. }
  524. static inline void writer_print_rational(WriterContext *wctx,
  525. const char *key, AVRational q, char sep)
  526. {
  527. AVBPrint buf;
  528. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
  529. av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
  530. writer_print_string(wctx, key, buf.str, 0);
  531. }
  532. static void writer_print_time(WriterContext *wctx, const char *key,
  533. int64_t ts, const AVRational *time_base, int is_duration)
  534. {
  535. char buf[128];
  536. if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
  537. writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
  538. } else {
  539. double d = ts * av_q2d(*time_base);
  540. struct unit_value uv;
  541. uv.val.d = d;
  542. uv.unit = unit_second_str;
  543. value_string(buf, sizeof(buf), uv);
  544. writer_print_string(wctx, key, buf, 0);
  545. }
  546. }
  547. static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
  548. {
  549. if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
  550. writer_print_string(wctx, key, "N/A", PRINT_STRING_OPT);
  551. } else {
  552. writer_print_integer(wctx, key, ts);
  553. }
  554. }
  555. static void writer_print_data(WriterContext *wctx, const char *name,
  556. uint8_t *data, int size)
  557. {
  558. AVBPrint bp;
  559. int offset = 0, l, i;
  560. av_bprint_init(&bp, 0, AV_BPRINT_SIZE_UNLIMITED);
  561. av_bprintf(&bp, "\n");
  562. while (size) {
  563. av_bprintf(&bp, "%08x: ", offset);
  564. l = FFMIN(size, 16);
  565. for (i = 0; i < l; i++) {
  566. av_bprintf(&bp, "%02x", data[i]);
  567. if (i & 1)
  568. av_bprintf(&bp, " ");
  569. }
  570. av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
  571. for (i = 0; i < l; i++)
  572. av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
  573. av_bprintf(&bp, "\n");
  574. offset += l;
  575. data += l;
  576. size -= l;
  577. }
  578. writer_print_string(wctx, name, bp.str, 0);
  579. av_bprint_finalize(&bp, NULL);
  580. }
  581. #define MAX_REGISTERED_WRITERS_NB 64
  582. static const Writer *registered_writers[MAX_REGISTERED_WRITERS_NB + 1];
  583. static int writer_register(const Writer *writer)
  584. {
  585. static int next_registered_writer_idx = 0;
  586. if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
  587. return AVERROR(ENOMEM);
  588. registered_writers[next_registered_writer_idx++] = writer;
  589. return 0;
  590. }
  591. static const Writer *writer_get_by_name(const char *name)
  592. {
  593. int i;
  594. for (i = 0; registered_writers[i]; i++)
  595. if (!strcmp(registered_writers[i]->name, name))
  596. return registered_writers[i];
  597. return NULL;
  598. }
  599. /* WRITERS */
  600. #define DEFINE_WRITER_CLASS(name) \
  601. static const char *name##_get_name(void *ctx) \
  602. { \
  603. return #name ; \
  604. } \
  605. static const AVClass name##_class = { \
  606. .class_name = #name, \
  607. .item_name = name##_get_name, \
  608. .option = name##_options \
  609. }
  610. /* Default output */
  611. typedef struct DefaultContext {
  612. const AVClass *class;
  613. int nokey;
  614. int noprint_wrappers;
  615. int nested_section[SECTION_MAX_NB_LEVELS];
  616. } DefaultContext;
  617. #undef OFFSET
  618. #define OFFSET(x) offsetof(DefaultContext, x)
  619. static const AVOption default_options[] = {
  620. { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  621. { "nw", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  622. { "nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  623. { "nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  624. {NULL},
  625. };
  626. DEFINE_WRITER_CLASS(default);
  627. /* lame uppercasing routine, assumes the string is lower case ASCII */
  628. static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
  629. {
  630. int i;
  631. for (i = 0; src[i] && i < dst_size-1; i++)
  632. dst[i] = av_toupper(src[i]);
  633. dst[i] = 0;
  634. return dst;
  635. }
  636. static void default_print_section_header(WriterContext *wctx)
  637. {
  638. DefaultContext *def = wctx->priv;
  639. char buf[32];
  640. const struct section *section = wctx->section[wctx->level];
  641. const struct section *parent_section = wctx->level ?
  642. wctx->section[wctx->level-1] : NULL;
  643. av_bprint_clear(&wctx->section_pbuf[wctx->level]);
  644. if (parent_section &&
  645. !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
  646. def->nested_section[wctx->level] = 1;
  647. av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
  648. wctx->section_pbuf[wctx->level-1].str,
  649. upcase_string(buf, sizeof(buf),
  650. av_x_if_null(section->element_name, section->name)));
  651. }
  652. if (def->noprint_wrappers || def->nested_section[wctx->level])
  653. return;
  654. if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  655. printf("[%s]\n", upcase_string(buf, sizeof(buf), section->name));
  656. }
  657. static void default_print_section_footer(WriterContext *wctx)
  658. {
  659. DefaultContext *def = wctx->priv;
  660. const struct section *section = wctx->section[wctx->level];
  661. char buf[32];
  662. if (def->noprint_wrappers || def->nested_section[wctx->level])
  663. return;
  664. if (!(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  665. printf("[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
  666. }
  667. static void default_print_str(WriterContext *wctx, const char *key, const char *value)
  668. {
  669. DefaultContext *def = wctx->priv;
  670. if (!def->nokey)
  671. printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
  672. printf("%s\n", value);
  673. }
  674. static void default_print_int(WriterContext *wctx, const char *key, long long int value)
  675. {
  676. DefaultContext *def = wctx->priv;
  677. if (!def->nokey)
  678. printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
  679. printf("%lld\n", value);
  680. }
  681. static const Writer default_writer = {
  682. .name = "default",
  683. .priv_size = sizeof(DefaultContext),
  684. .print_section_header = default_print_section_header,
  685. .print_section_footer = default_print_section_footer,
  686. .print_integer = default_print_int,
  687. .print_string = default_print_str,
  688. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  689. .priv_class = &default_class,
  690. };
  691. /* Compact output */
  692. /**
  693. * Apply C-language-like string escaping.
  694. */
  695. static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  696. {
  697. const char *p;
  698. for (p = src; *p; p++) {
  699. switch (*p) {
  700. case '\b': av_bprintf(dst, "%s", "\\b"); break;
  701. case '\f': av_bprintf(dst, "%s", "\\f"); break;
  702. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  703. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  704. case '\\': av_bprintf(dst, "%s", "\\\\"); break;
  705. default:
  706. if (*p == sep)
  707. av_bprint_chars(dst, '\\', 1);
  708. av_bprint_chars(dst, *p, 1);
  709. }
  710. }
  711. return dst->str;
  712. }
  713. /**
  714. * Quote fields containing special characters, check RFC4180.
  715. */
  716. static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  717. {
  718. char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
  719. int needs_quoting = !!src[strcspn(src, meta_chars)];
  720. if (needs_quoting)
  721. av_bprint_chars(dst, '"', 1);
  722. for (; *src; src++) {
  723. if (*src == '"')
  724. av_bprint_chars(dst, '"', 1);
  725. av_bprint_chars(dst, *src, 1);
  726. }
  727. if (needs_quoting)
  728. av_bprint_chars(dst, '"', 1);
  729. return dst->str;
  730. }
  731. static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
  732. {
  733. return src;
  734. }
  735. typedef struct CompactContext {
  736. const AVClass *class;
  737. char *item_sep_str;
  738. char item_sep;
  739. int nokey;
  740. int print_section;
  741. char *escape_mode_str;
  742. const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
  743. int nested_section[SECTION_MAX_NB_LEVELS];
  744. int has_nested_elems[SECTION_MAX_NB_LEVELS];
  745. int terminate_line[SECTION_MAX_NB_LEVELS];
  746. } CompactContext;
  747. #undef OFFSET
  748. #define OFFSET(x) offsetof(CompactContext, x)
  749. static const AVOption compact_options[]= {
  750. {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  751. {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, CHAR_MIN, CHAR_MAX },
  752. {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  753. {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  754. {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  755. {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, CHAR_MIN, CHAR_MAX },
  756. {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  757. {"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  758. {NULL},
  759. };
  760. DEFINE_WRITER_CLASS(compact);
  761. static av_cold int compact_init(WriterContext *wctx)
  762. {
  763. CompactContext *compact = wctx->priv;
  764. if (strlen(compact->item_sep_str) != 1) {
  765. av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
  766. compact->item_sep_str);
  767. return AVERROR(EINVAL);
  768. }
  769. compact->item_sep = compact->item_sep_str[0];
  770. if (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
  771. else if (!strcmp(compact->escape_mode_str, "c" )) compact->escape_str = c_escape_str;
  772. else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
  773. else {
  774. av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
  775. return AVERROR(EINVAL);
  776. }
  777. return 0;
  778. }
  779. static void compact_print_section_header(WriterContext *wctx)
  780. {
  781. CompactContext *compact = wctx->priv;
  782. const struct section *section = wctx->section[wctx->level];
  783. const struct section *parent_section = wctx->level ?
  784. wctx->section[wctx->level-1] : NULL;
  785. compact->terminate_line[wctx->level] = 1;
  786. compact->has_nested_elems[wctx->level] = 0;
  787. av_bprint_clear(&wctx->section_pbuf[wctx->level]);
  788. if (!(section->flags & SECTION_FLAG_IS_ARRAY) && parent_section &&
  789. !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
  790. compact->nested_section[wctx->level] = 1;
  791. compact->has_nested_elems[wctx->level-1] = 1;
  792. av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
  793. wctx->section_pbuf[wctx->level-1].str,
  794. (char *)av_x_if_null(section->element_name, section->name));
  795. wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
  796. } else {
  797. if (parent_section && compact->has_nested_elems[wctx->level-1] &&
  798. (section->flags & SECTION_FLAG_IS_ARRAY)) {
  799. compact->terminate_line[wctx->level-1] = 0;
  800. printf("\n");
  801. }
  802. if (compact->print_section &&
  803. !(section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  804. printf("%s%c", section->name, compact->item_sep);
  805. }
  806. }
  807. static void compact_print_section_footer(WriterContext *wctx)
  808. {
  809. CompactContext *compact = wctx->priv;
  810. if (!compact->nested_section[wctx->level] &&
  811. compact->terminate_line[wctx->level] &&
  812. !(wctx->section[wctx->level]->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)))
  813. printf("\n");
  814. }
  815. static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
  816. {
  817. CompactContext *compact = wctx->priv;
  818. AVBPrint buf;
  819. if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
  820. if (!compact->nokey)
  821. printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
  822. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  823. printf("%s", compact->escape_str(&buf, value, compact->item_sep, wctx));
  824. av_bprint_finalize(&buf, NULL);
  825. }
  826. static void compact_print_int(WriterContext *wctx, const char *key, long long int value)
  827. {
  828. CompactContext *compact = wctx->priv;
  829. if (wctx->nb_item[wctx->level]) printf("%c", compact->item_sep);
  830. if (!compact->nokey)
  831. printf("%s%s=", wctx->section_pbuf[wctx->level].str, key);
  832. printf("%lld", value);
  833. }
  834. static const Writer compact_writer = {
  835. .name = "compact",
  836. .priv_size = sizeof(CompactContext),
  837. .init = compact_init,
  838. .print_section_header = compact_print_section_header,
  839. .print_section_footer = compact_print_section_footer,
  840. .print_integer = compact_print_int,
  841. .print_string = compact_print_str,
  842. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  843. .priv_class = &compact_class,
  844. };
  845. /* CSV output */
  846. #undef OFFSET
  847. #define OFFSET(x) offsetof(CompactContext, x)
  848. static const AVOption csv_options[] = {
  849. {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
  850. {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, CHAR_MIN, CHAR_MAX },
  851. {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  852. {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  853. {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
  854. {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, CHAR_MIN, CHAR_MAX },
  855. {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  856. {"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  857. {NULL},
  858. };
  859. DEFINE_WRITER_CLASS(csv);
  860. static const Writer csv_writer = {
  861. .name = "csv",
  862. .priv_size = sizeof(CompactContext),
  863. .init = compact_init,
  864. .print_section_header = compact_print_section_header,
  865. .print_section_footer = compact_print_section_footer,
  866. .print_integer = compact_print_int,
  867. .print_string = compact_print_str,
  868. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS,
  869. .priv_class = &csv_class,
  870. };
  871. /* Flat output */
  872. typedef struct FlatContext {
  873. const AVClass *class;
  874. const char *sep_str;
  875. char sep;
  876. int hierarchical;
  877. } FlatContext;
  878. #undef OFFSET
  879. #define OFFSET(x) offsetof(FlatContext, x)
  880. static const AVOption flat_options[]= {
  881. {"sep_char", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
  882. {"s", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, CHAR_MIN, CHAR_MAX },
  883. {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  884. {"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  885. {NULL},
  886. };
  887. DEFINE_WRITER_CLASS(flat);
  888. static av_cold int flat_init(WriterContext *wctx)
  889. {
  890. FlatContext *flat = wctx->priv;
  891. if (strlen(flat->sep_str) != 1) {
  892. av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
  893. flat->sep_str);
  894. return AVERROR(EINVAL);
  895. }
  896. flat->sep = flat->sep_str[0];
  897. return 0;
  898. }
  899. static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
  900. {
  901. const char *p;
  902. for (p = src; *p; p++) {
  903. if (!((*p >= '0' && *p <= '9') ||
  904. (*p >= 'a' && *p <= 'z') ||
  905. (*p >= 'A' && *p <= 'Z')))
  906. av_bprint_chars(dst, '_', 1);
  907. else
  908. av_bprint_chars(dst, *p, 1);
  909. }
  910. return dst->str;
  911. }
  912. static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
  913. {
  914. const char *p;
  915. for (p = src; *p; p++) {
  916. switch (*p) {
  917. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  918. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  919. case '\\': av_bprintf(dst, "%s", "\\\\"); break;
  920. case '"': av_bprintf(dst, "%s", "\\\""); break;
  921. case '`': av_bprintf(dst, "%s", "\\`"); break;
  922. case '$': av_bprintf(dst, "%s", "\\$"); break;
  923. default: av_bprint_chars(dst, *p, 1); break;
  924. }
  925. }
  926. return dst->str;
  927. }
  928. static void flat_print_section_header(WriterContext *wctx)
  929. {
  930. FlatContext *flat = wctx->priv;
  931. AVBPrint *buf = &wctx->section_pbuf[wctx->level];
  932. const struct section *section = wctx->section[wctx->level];
  933. const struct section *parent_section = wctx->level ?
  934. wctx->section[wctx->level-1] : NULL;
  935. /* build section header */
  936. av_bprint_clear(buf);
  937. if (!parent_section)
  938. return;
  939. av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
  940. if (flat->hierarchical ||
  941. !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
  942. av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
  943. if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
  944. int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
  945. wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
  946. av_bprintf(buf, "%d%s", n, flat->sep_str);
  947. }
  948. }
  949. }
  950. static void flat_print_int(WriterContext *wctx, const char *key, long long int value)
  951. {
  952. printf("%s%s=%lld\n", wctx->section_pbuf[wctx->level].str, key, value);
  953. }
  954. static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
  955. {
  956. FlatContext *flat = wctx->priv;
  957. AVBPrint buf;
  958. printf("%s", wctx->section_pbuf[wctx->level].str);
  959. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  960. printf("%s=", flat_escape_key_str(&buf, key, flat->sep));
  961. av_bprint_clear(&buf);
  962. printf("\"%s\"\n", flat_escape_value_str(&buf, value));
  963. av_bprint_finalize(&buf, NULL);
  964. }
  965. static const Writer flat_writer = {
  966. .name = "flat",
  967. .priv_size = sizeof(FlatContext),
  968. .init = flat_init,
  969. .print_section_header = flat_print_section_header,
  970. .print_integer = flat_print_int,
  971. .print_string = flat_print_str,
  972. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  973. .priv_class = &flat_class,
  974. };
  975. /* INI format output */
  976. typedef struct {
  977. const AVClass *class;
  978. int hierarchical;
  979. } INIContext;
  980. #undef OFFSET
  981. #define OFFSET(x) offsetof(INIContext, x)
  982. static const AVOption ini_options[] = {
  983. {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  984. {"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_INT, {.i64=1}, 0, 1 },
  985. {NULL},
  986. };
  987. DEFINE_WRITER_CLASS(ini);
  988. static char *ini_escape_str(AVBPrint *dst, const char *src)
  989. {
  990. int i = 0;
  991. char c = 0;
  992. while (c = src[i++]) {
  993. switch (c) {
  994. case '\b': av_bprintf(dst, "%s", "\\b"); break;
  995. case '\f': av_bprintf(dst, "%s", "\\f"); break;
  996. case '\n': av_bprintf(dst, "%s", "\\n"); break;
  997. case '\r': av_bprintf(dst, "%s", "\\r"); break;
  998. case '\t': av_bprintf(dst, "%s", "\\t"); break;
  999. case '\\':
  1000. case '#' :
  1001. case '=' :
  1002. case ':' : av_bprint_chars(dst, '\\', 1);
  1003. default:
  1004. if ((unsigned char)c < 32)
  1005. av_bprintf(dst, "\\x00%02x", c & 0xff);
  1006. else
  1007. av_bprint_chars(dst, c, 1);
  1008. break;
  1009. }
  1010. }
  1011. return dst->str;
  1012. }
  1013. static void ini_print_section_header(WriterContext *wctx)
  1014. {
  1015. INIContext *ini = wctx->priv;
  1016. AVBPrint *buf = &wctx->section_pbuf[wctx->level];
  1017. const struct section *section = wctx->section[wctx->level];
  1018. const struct section *parent_section = wctx->level ?
  1019. wctx->section[wctx->level-1] : NULL;
  1020. av_bprint_clear(buf);
  1021. if (!parent_section) {
  1022. printf("# ffprobe output\n\n");
  1023. return;
  1024. }
  1025. if (wctx->nb_item[wctx->level-1])
  1026. printf("\n");
  1027. av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
  1028. if (ini->hierarchical ||
  1029. !(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER))) {
  1030. av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
  1031. if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
  1032. int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
  1033. wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
  1034. av_bprintf(buf, ".%d", n);
  1035. }
  1036. }
  1037. if (!(section->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))
  1038. printf("[%s]\n", buf->str);
  1039. }
  1040. static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
  1041. {
  1042. AVBPrint buf;
  1043. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1044. printf("%s=", ini_escape_str(&buf, key));
  1045. av_bprint_clear(&buf);
  1046. printf("%s\n", ini_escape_str(&buf, value));
  1047. av_bprint_finalize(&buf, NULL);
  1048. }
  1049. static void ini_print_int(WriterContext *wctx, const char *key, long long int value)
  1050. {
  1051. printf("%s=%lld\n", key, value);
  1052. }
  1053. static const Writer ini_writer = {
  1054. .name = "ini",
  1055. .priv_size = sizeof(INIContext),
  1056. .print_section_header = ini_print_section_header,
  1057. .print_integer = ini_print_int,
  1058. .print_string = ini_print_str,
  1059. .flags = WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS|WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1060. .priv_class = &ini_class,
  1061. };
  1062. /* JSON output */
  1063. typedef struct {
  1064. const AVClass *class;
  1065. int indent_level;
  1066. int compact;
  1067. const char *item_sep, *item_start_end;
  1068. } JSONContext;
  1069. #undef OFFSET
  1070. #define OFFSET(x) offsetof(JSONContext, x)
  1071. static const AVOption json_options[]= {
  1072. { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1073. { "c", "enable compact output", OFFSET(compact), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1074. { NULL }
  1075. };
  1076. DEFINE_WRITER_CLASS(json);
  1077. static av_cold int json_init(WriterContext *wctx)
  1078. {
  1079. JSONContext *json = wctx->priv;
  1080. json->item_sep = json->compact ? ", " : ",\n";
  1081. json->item_start_end = json->compact ? " " : "\n";
  1082. return 0;
  1083. }
  1084. static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  1085. {
  1086. static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
  1087. static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
  1088. const char *p;
  1089. for (p = src; *p; p++) {
  1090. char *s = strchr(json_escape, *p);
  1091. if (s) {
  1092. av_bprint_chars(dst, '\\', 1);
  1093. av_bprint_chars(dst, json_subst[s - json_escape], 1);
  1094. } else if ((unsigned char)*p < 32) {
  1095. av_bprintf(dst, "\\u00%02x", *p & 0xff);
  1096. } else {
  1097. av_bprint_chars(dst, *p, 1);
  1098. }
  1099. }
  1100. return dst->str;
  1101. }
  1102. #define JSON_INDENT() printf("%*c", json->indent_level * 4, ' ')
  1103. static void json_print_section_header(WriterContext *wctx)
  1104. {
  1105. JSONContext *json = wctx->priv;
  1106. AVBPrint buf;
  1107. const struct section *section = wctx->section[wctx->level];
  1108. const struct section *parent_section = wctx->level ?
  1109. wctx->section[wctx->level-1] : NULL;
  1110. if (wctx->level && wctx->nb_item[wctx->level-1])
  1111. printf(",\n");
  1112. if (section->flags & SECTION_FLAG_IS_WRAPPER) {
  1113. printf("{\n");
  1114. json->indent_level++;
  1115. } else {
  1116. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1117. json_escape_str(&buf, section->name, wctx);
  1118. JSON_INDENT();
  1119. json->indent_level++;
  1120. if (section->flags & SECTION_FLAG_IS_ARRAY) {
  1121. printf("\"%s\": [\n", buf.str);
  1122. } else if (parent_section && !(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
  1123. printf("\"%s\": {%s", buf.str, json->item_start_end);
  1124. } else {
  1125. printf("{%s", json->item_start_end);
  1126. /* this is required so the parser can distinguish between packets and frames */
  1127. if (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
  1128. if (!json->compact)
  1129. JSON_INDENT();
  1130. printf("\"type\": \"%s\"%s", section->name, json->item_sep);
  1131. }
  1132. }
  1133. av_bprint_finalize(&buf, NULL);
  1134. }
  1135. }
  1136. static void json_print_section_footer(WriterContext *wctx)
  1137. {
  1138. JSONContext *json = wctx->priv;
  1139. const struct section *section = wctx->section[wctx->level];
  1140. if (wctx->level == 0) {
  1141. json->indent_level--;
  1142. printf("\n}\n");
  1143. } else if (section->flags & SECTION_FLAG_IS_ARRAY) {
  1144. printf("\n");
  1145. json->indent_level--;
  1146. JSON_INDENT();
  1147. printf("]");
  1148. } else {
  1149. printf("%s", json->item_start_end);
  1150. json->indent_level--;
  1151. if (!json->compact)
  1152. JSON_INDENT();
  1153. printf("}");
  1154. }
  1155. }
  1156. static inline void json_print_item_str(WriterContext *wctx,
  1157. const char *key, const char *value)
  1158. {
  1159. AVBPrint buf;
  1160. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1161. printf("\"%s\":", json_escape_str(&buf, key, wctx));
  1162. av_bprint_clear(&buf);
  1163. printf(" \"%s\"", json_escape_str(&buf, value, wctx));
  1164. av_bprint_finalize(&buf, NULL);
  1165. }
  1166. static void json_print_str(WriterContext *wctx, const char *key, const char *value)
  1167. {
  1168. JSONContext *json = wctx->priv;
  1169. if (wctx->nb_item[wctx->level])
  1170. printf("%s", json->item_sep);
  1171. if (!json->compact)
  1172. JSON_INDENT();
  1173. json_print_item_str(wctx, key, value);
  1174. }
  1175. static void json_print_int(WriterContext *wctx, const char *key, long long int value)
  1176. {
  1177. JSONContext *json = wctx->priv;
  1178. AVBPrint buf;
  1179. if (wctx->nb_item[wctx->level])
  1180. printf("%s", json->item_sep);
  1181. if (!json->compact)
  1182. JSON_INDENT();
  1183. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1184. printf("\"%s\": %lld", json_escape_str(&buf, key, wctx), value);
  1185. av_bprint_finalize(&buf, NULL);
  1186. }
  1187. static const Writer json_writer = {
  1188. .name = "json",
  1189. .priv_size = sizeof(JSONContext),
  1190. .init = json_init,
  1191. .print_section_header = json_print_section_header,
  1192. .print_section_footer = json_print_section_footer,
  1193. .print_integer = json_print_int,
  1194. .print_string = json_print_str,
  1195. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1196. .priv_class = &json_class,
  1197. };
  1198. /* XML output */
  1199. typedef struct {
  1200. const AVClass *class;
  1201. int within_tag;
  1202. int indent_level;
  1203. int fully_qualified;
  1204. int xsd_strict;
  1205. } XMLContext;
  1206. #undef OFFSET
  1207. #define OFFSET(x) offsetof(XMLContext, x)
  1208. static const AVOption xml_options[] = {
  1209. {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1210. {"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1211. {"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1212. {"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 },
  1213. {NULL},
  1214. };
  1215. DEFINE_WRITER_CLASS(xml);
  1216. static av_cold int xml_init(WriterContext *wctx)
  1217. {
  1218. XMLContext *xml = wctx->priv;
  1219. if (xml->xsd_strict) {
  1220. xml->fully_qualified = 1;
  1221. #define CHECK_COMPLIANCE(opt, opt_name) \
  1222. if (opt) { \
  1223. av_log(wctx, AV_LOG_ERROR, \
  1224. "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
  1225. "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
  1226. return AVERROR(EINVAL); \
  1227. }
  1228. CHECK_COMPLIANCE(show_private_data, "private");
  1229. CHECK_COMPLIANCE(show_value_unit, "unit");
  1230. CHECK_COMPLIANCE(use_value_prefix, "prefix");
  1231. if (do_show_frames && do_show_packets) {
  1232. av_log(wctx, AV_LOG_ERROR,
  1233. "Interleaved frames and packets are not allowed in XSD. "
  1234. "Select only one between the -show_frames and the -show_packets options.\n");
  1235. return AVERROR(EINVAL);
  1236. }
  1237. }
  1238. return 0;
  1239. }
  1240. static const char *xml_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
  1241. {
  1242. const char *p;
  1243. for (p = src; *p; p++) {
  1244. switch (*p) {
  1245. case '&' : av_bprintf(dst, "%s", "&amp;"); break;
  1246. case '<' : av_bprintf(dst, "%s", "&lt;"); break;
  1247. case '>' : av_bprintf(dst, "%s", "&gt;"); break;
  1248. case '"' : av_bprintf(dst, "%s", "&quot;"); break;
  1249. case '\'': av_bprintf(dst, "%s", "&apos;"); break;
  1250. default: av_bprint_chars(dst, *p, 1);
  1251. }
  1252. }
  1253. return dst->str;
  1254. }
  1255. #define XML_INDENT() printf("%*c", xml->indent_level * 4, ' ')
  1256. static void xml_print_section_header(WriterContext *wctx)
  1257. {
  1258. XMLContext *xml = wctx->priv;
  1259. const struct section *section = wctx->section[wctx->level];
  1260. const struct section *parent_section = wctx->level ?
  1261. wctx->section[wctx->level-1] : NULL;
  1262. if (wctx->level == 0) {
  1263. const char *qual = " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
  1264. "xmlns:ffprobe='http://www.ffmpeg.org/schema/ffprobe' "
  1265. "xsi:schemaLocation='http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd'";
  1266. printf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  1267. printf("<%sffprobe%s>\n",
  1268. xml->fully_qualified ? "ffprobe:" : "",
  1269. xml->fully_qualified ? qual : "");
  1270. return;
  1271. }
  1272. if (xml->within_tag) {
  1273. xml->within_tag = 0;
  1274. printf(">\n");
  1275. }
  1276. if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
  1277. xml->indent_level++;
  1278. } else {
  1279. if (parent_section && (parent_section->flags & SECTION_FLAG_IS_WRAPPER) &&
  1280. wctx->level && wctx->nb_item[wctx->level-1])
  1281. printf("\n");
  1282. xml->indent_level++;
  1283. if (section->flags & SECTION_FLAG_IS_ARRAY) {
  1284. XML_INDENT(); printf("<%s>\n", section->name);
  1285. } else {
  1286. XML_INDENT(); printf("<%s ", section->name);
  1287. xml->within_tag = 1;
  1288. }
  1289. }
  1290. }
  1291. static void xml_print_section_footer(WriterContext *wctx)
  1292. {
  1293. XMLContext *xml = wctx->priv;
  1294. const struct section *section = wctx->section[wctx->level];
  1295. if (wctx->level == 0) {
  1296. printf("</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
  1297. } else if (xml->within_tag) {
  1298. xml->within_tag = 0;
  1299. printf("/>\n");
  1300. xml->indent_level--;
  1301. } else if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
  1302. xml->indent_level--;
  1303. } else {
  1304. XML_INDENT(); printf("</%s>\n", section->name);
  1305. xml->indent_level--;
  1306. }
  1307. }
  1308. static void xml_print_str(WriterContext *wctx, const char *key, const char *value)
  1309. {
  1310. AVBPrint buf;
  1311. XMLContext *xml = wctx->priv;
  1312. const struct section *section = wctx->section[wctx->level];
  1313. av_bprint_init(&buf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1314. if (section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS) {
  1315. XML_INDENT();
  1316. printf("<%s key=\"%s\"",
  1317. section->element_name, xml_escape_str(&buf, key, wctx));
  1318. av_bprint_clear(&buf);
  1319. printf(" value=\"%s\"/>\n", xml_escape_str(&buf, value, wctx));
  1320. } else {
  1321. if (wctx->nb_item[wctx->level])
  1322. printf(" ");
  1323. printf("%s=\"%s\"", key, xml_escape_str(&buf, value, wctx));
  1324. }
  1325. av_bprint_finalize(&buf, NULL);
  1326. }
  1327. static void xml_print_int(WriterContext *wctx, const char *key, long long int value)
  1328. {
  1329. if (wctx->nb_item[wctx->level])
  1330. printf(" ");
  1331. printf("%s=\"%lld\"", key, value);
  1332. }
  1333. static Writer xml_writer = {
  1334. .name = "xml",
  1335. .priv_size = sizeof(XMLContext),
  1336. .init = xml_init,
  1337. .print_section_header = xml_print_section_header,
  1338. .print_section_footer = xml_print_section_footer,
  1339. .print_integer = xml_print_int,
  1340. .print_string = xml_print_str,
  1341. .flags = WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER,
  1342. .priv_class = &xml_class,
  1343. };
  1344. static void writer_register_all(void)
  1345. {
  1346. static int initialized;
  1347. if (initialized)
  1348. return;
  1349. initialized = 1;
  1350. writer_register(&default_writer);
  1351. writer_register(&compact_writer);
  1352. writer_register(&csv_writer);
  1353. writer_register(&flat_writer);
  1354. writer_register(&ini_writer);
  1355. writer_register(&json_writer);
  1356. writer_register(&xml_writer);
  1357. }
  1358. #define print_fmt(k, f, ...) do { \
  1359. av_bprint_clear(&pbuf); \
  1360. av_bprintf(&pbuf, f, __VA_ARGS__); \
  1361. writer_print_string(w, k, pbuf.str, 0); \
  1362. } while (0)
  1363. #define print_int(k, v) writer_print_integer(w, k, v)
  1364. #define print_q(k, v, s) writer_print_rational(w, k, v, s)
  1365. #define print_str(k, v) writer_print_string(w, k, v, 0)
  1366. #define print_str_opt(k, v) writer_print_string(w, k, v, PRINT_STRING_OPT)
  1367. #define print_str_validate(k, v) writer_print_string(w, k, v, PRINT_STRING_VALIDATE)
  1368. #define print_time(k, v, tb) writer_print_time(w, k, v, tb, 0)
  1369. #define print_ts(k, v) writer_print_ts(w, k, v, 0)
  1370. #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
  1371. #define print_duration_ts(k, v) writer_print_ts(w, k, v, 1)
  1372. #define print_val(k, v, u) do { \
  1373. struct unit_value uv; \
  1374. uv.val.i = v; \
  1375. uv.unit = u; \
  1376. writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
  1377. } while (0)
  1378. #define print_section_header(s) writer_print_section_header(w, s)
  1379. #define print_section_footer(s) writer_print_section_footer(w, s)
  1380. static inline int show_tags(WriterContext *w, AVDictionary *tags, int section_id)
  1381. {
  1382. AVDictionaryEntry *tag = NULL;
  1383. int ret = 0;
  1384. if (!tags)
  1385. return 0;
  1386. writer_print_section_header(w, section_id);
  1387. while ((tag = av_dict_get(tags, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  1388. if ((ret = print_str_validate(tag->key, tag->value)) < 0)
  1389. break;
  1390. }
  1391. writer_print_section_footer(w);
  1392. return ret;
  1393. }
  1394. static void show_packet(WriterContext *w, AVFormatContext *fmt_ctx, AVPacket *pkt, int packet_idx)
  1395. {
  1396. char val_str[128];
  1397. AVStream *st = fmt_ctx->streams[pkt->stream_index];
  1398. AVBPrint pbuf;
  1399. const char *s;
  1400. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1401. writer_print_section_header(w, SECTION_ID_PACKET);
  1402. s = av_get_media_type_string(st->codec->codec_type);
  1403. if (s) print_str ("codec_type", s);
  1404. else print_str_opt("codec_type", "unknown");
  1405. print_int("stream_index", pkt->stream_index);
  1406. print_ts ("pts", pkt->pts);
  1407. print_time("pts_time", pkt->pts, &st->time_base);
  1408. print_ts ("dts", pkt->dts);
  1409. print_time("dts_time", pkt->dts, &st->time_base);
  1410. print_duration_ts("duration", pkt->duration);
  1411. print_duration_time("duration_time", pkt->duration, &st->time_base);
  1412. print_duration_ts("convergence_duration", pkt->convergence_duration);
  1413. print_duration_time("convergence_duration_time", pkt->convergence_duration, &st->time_base);
  1414. print_val("size", pkt->size, unit_byte_str);
  1415. if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
  1416. else print_str_opt("pos", "N/A");
  1417. print_fmt("flags", "%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');
  1418. if (do_show_data)
  1419. writer_print_data(w, "data", pkt->data, pkt->size);
  1420. writer_print_section_footer(w);
  1421. av_bprint_finalize(&pbuf, NULL);
  1422. fflush(stdout);
  1423. }
  1424. static void show_subtitle(WriterContext *w, AVSubtitle *sub, AVStream *stream,
  1425. AVFormatContext *fmt_ctx)
  1426. {
  1427. AVBPrint pbuf;
  1428. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1429. writer_print_section_header(w, SECTION_ID_SUBTITLE);
  1430. print_str ("media_type", "subtitle");
  1431. print_ts ("pts", sub->pts);
  1432. print_time("pts_time", sub->pts, &AV_TIME_BASE_Q);
  1433. print_int ("format", sub->format);
  1434. print_int ("start_display_time", sub->start_display_time);
  1435. print_int ("end_display_time", sub->end_display_time);
  1436. print_int ("num_rects", sub->num_rects);
  1437. writer_print_section_footer(w);
  1438. av_bprint_finalize(&pbuf, NULL);
  1439. fflush(stdout);
  1440. }
  1441. static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,
  1442. AVFormatContext *fmt_ctx)
  1443. {
  1444. AVBPrint pbuf;
  1445. const char *s;
  1446. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1447. writer_print_section_header(w, SECTION_ID_FRAME);
  1448. s = av_get_media_type_string(stream->codec->codec_type);
  1449. if (s) print_str ("media_type", s);
  1450. else print_str_opt("media_type", "unknown");
  1451. print_int("key_frame", frame->key_frame);
  1452. print_ts ("pkt_pts", frame->pkt_pts);
  1453. print_time("pkt_pts_time", frame->pkt_pts, &stream->time_base);
  1454. print_ts ("pkt_dts", frame->pkt_dts);
  1455. print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
  1456. print_ts ("best_effort_timestamp", av_frame_get_best_effort_timestamp(frame));
  1457. print_time("best_effort_timestamp_time", av_frame_get_best_effort_timestamp(frame), &stream->time_base);
  1458. print_duration_ts ("pkt_duration", av_frame_get_pkt_duration(frame));
  1459. print_duration_time("pkt_duration_time", av_frame_get_pkt_duration(frame), &stream->time_base);
  1460. if (av_frame_get_pkt_pos (frame) != -1) print_fmt ("pkt_pos", "%"PRId64, av_frame_get_pkt_pos(frame));
  1461. else print_str_opt("pkt_pos", "N/A");
  1462. if (av_frame_get_pkt_size(frame) != -1) print_fmt ("pkt_size", "%d", av_frame_get_pkt_size(frame));
  1463. else print_str_opt("pkt_size", "N/A");
  1464. switch (stream->codec->codec_type) {
  1465. AVRational sar;
  1466. case AVMEDIA_TYPE_VIDEO:
  1467. print_int("width", frame->width);
  1468. print_int("height", frame->height);
  1469. s = av_get_pix_fmt_name(frame->format);
  1470. if (s) print_str ("pix_fmt", s);
  1471. else print_str_opt("pix_fmt", "unknown");
  1472. sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
  1473. if (sar.num) {
  1474. print_q("sample_aspect_ratio", sar, ':');
  1475. } else {
  1476. print_str_opt("sample_aspect_ratio", "N/A");
  1477. }
  1478. print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
  1479. print_int("coded_picture_number", frame->coded_picture_number);
  1480. print_int("display_picture_number", frame->display_picture_number);
  1481. print_int("interlaced_frame", frame->interlaced_frame);
  1482. print_int("top_field_first", frame->top_field_first);
  1483. print_int("repeat_pict", frame->repeat_pict);
  1484. break;
  1485. case AVMEDIA_TYPE_AUDIO:
  1486. s = av_get_sample_fmt_name(frame->format);
  1487. if (s) print_str ("sample_fmt", s);
  1488. else print_str_opt("sample_fmt", "unknown");
  1489. print_int("nb_samples", frame->nb_samples);
  1490. print_int("channels", av_frame_get_channels(frame));
  1491. if (av_frame_get_channel_layout(frame)) {
  1492. av_bprint_clear(&pbuf);
  1493. av_bprint_channel_layout(&pbuf, av_frame_get_channels(frame),
  1494. av_frame_get_channel_layout(frame));
  1495. print_str ("channel_layout", pbuf.str);
  1496. } else
  1497. print_str_opt("channel_layout", "unknown");
  1498. break;
  1499. }
  1500. if (do_show_frame_tags)
  1501. show_tags(w, av_frame_get_metadata(frame), SECTION_ID_FRAME_TAGS);
  1502. writer_print_section_footer(w);
  1503. av_bprint_finalize(&pbuf, NULL);
  1504. fflush(stdout);
  1505. }
  1506. static av_always_inline int process_frame(WriterContext *w,
  1507. AVFormatContext *fmt_ctx,
  1508. AVFrame *frame, AVPacket *pkt)
  1509. {
  1510. AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;
  1511. AVSubtitle sub;
  1512. int ret = 0, got_frame = 0;
  1513. if (dec_ctx->codec) {
  1514. switch (dec_ctx->codec_type) {
  1515. case AVMEDIA_TYPE_VIDEO:
  1516. ret = avcodec_decode_video2(dec_ctx, frame, &got_frame, pkt);
  1517. break;
  1518. case AVMEDIA_TYPE_AUDIO:
  1519. ret = avcodec_decode_audio4(dec_ctx, frame, &got_frame, pkt);
  1520. break;
  1521. case AVMEDIA_TYPE_SUBTITLE:
  1522. ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_frame, pkt);
  1523. break;
  1524. }
  1525. }
  1526. if (ret < 0)
  1527. return ret;
  1528. ret = FFMIN(ret, pkt->size); /* guard against bogus return values */
  1529. pkt->data += ret;
  1530. pkt->size -= ret;
  1531. if (got_frame) {
  1532. int is_sub = (dec_ctx->codec_type == AVMEDIA_TYPE_SUBTITLE);
  1533. nb_streams_frames[pkt->stream_index]++;
  1534. if (do_show_frames)
  1535. if (is_sub)
  1536. show_subtitle(w, &sub, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
  1537. else
  1538. show_frame(w, frame, fmt_ctx->streams[pkt->stream_index], fmt_ctx);
  1539. if (is_sub)
  1540. avsubtitle_free(&sub);
  1541. }
  1542. return got_frame;
  1543. }
  1544. static void log_read_interval(const ReadInterval *interval, void *log_ctx, int log_level)
  1545. {
  1546. av_log(log_ctx, log_level, "id:%d", interval->id);
  1547. if (interval->has_start) {
  1548. av_log(log_ctx, log_level, " start:%s%s", interval->start_is_offset ? "+" : "",
  1549. av_ts2timestr(interval->start, &AV_TIME_BASE_Q));
  1550. } else {
  1551. av_log(log_ctx, log_level, " start:N/A");
  1552. }
  1553. if (interval->has_end) {
  1554. av_log(log_ctx, log_level, " end:%s", interval->end_is_offset ? "+" : "");
  1555. if (interval->duration_frames)
  1556. av_log(log_ctx, log_level, "#%"PRId64, interval->end);
  1557. else
  1558. av_log(log_ctx, log_level, "%s", av_ts2timestr(interval->end, &AV_TIME_BASE_Q));
  1559. } else {
  1560. av_log(log_ctx, log_level, " end:N/A");
  1561. }
  1562. av_log(log_ctx, log_level, "\n");
  1563. }
  1564. static int read_interval_packets(WriterContext *w, AVFormatContext *fmt_ctx,
  1565. const ReadInterval *interval, int64_t *cur_ts)
  1566. {
  1567. AVPacket pkt, pkt1;
  1568. AVFrame *frame = NULL;
  1569. int ret = 0, i = 0, frame_count = 0;
  1570. int64_t start = -INT64_MAX, end = interval->end;
  1571. int has_start = 0, has_end = interval->has_end && !interval->end_is_offset;
  1572. av_init_packet(&pkt);
  1573. av_log(NULL, AV_LOG_VERBOSE, "Processing read interval ");
  1574. log_read_interval(interval, NULL, AV_LOG_VERBOSE);
  1575. if (interval->has_start) {
  1576. int64_t target;
  1577. if (interval->start_is_offset) {
  1578. if (*cur_ts == AV_NOPTS_VALUE) {
  1579. av_log(NULL, AV_LOG_ERROR,
  1580. "Could not seek to relative position since current "
  1581. "timestamp is not defined\n");
  1582. ret = AVERROR(EINVAL);
  1583. goto end;
  1584. }
  1585. target = *cur_ts + interval->start;
  1586. } else {
  1587. target = interval->start;
  1588. }
  1589. av_log(NULL, AV_LOG_VERBOSE, "Seeking to read interval start point %s\n",
  1590. av_ts2timestr(target, &AV_TIME_BASE_Q));
  1591. if ((ret = avformat_seek_file(fmt_ctx, -1, -INT64_MAX, target, INT64_MAX, 0)) < 0) {
  1592. av_log(NULL, AV_LOG_ERROR, "Could not seek to position %"PRId64": %s\n",
  1593. interval->start, av_err2str(ret));
  1594. goto end;
  1595. }
  1596. }
  1597. frame = av_frame_alloc();
  1598. if (!frame) {
  1599. ret = AVERROR(ENOMEM);
  1600. goto end;
  1601. }
  1602. while (!av_read_frame(fmt_ctx, &pkt)) {
  1603. if (selected_streams[pkt.stream_index]) {
  1604. AVRational tb = fmt_ctx->streams[pkt.stream_index]->time_base;
  1605. if (pkt.pts != AV_NOPTS_VALUE)
  1606. *cur_ts = av_rescale_q(pkt.pts, tb, AV_TIME_BASE_Q);
  1607. if (!has_start && *cur_ts != AV_NOPTS_VALUE) {
  1608. start = *cur_ts;
  1609. has_start = 1;
  1610. }
  1611. if (has_start && !has_end && interval->end_is_offset) {
  1612. end = start + interval->end;
  1613. has_end = 1;
  1614. }
  1615. if (interval->end_is_offset && interval->duration_frames) {
  1616. if (frame_count >= interval->end)
  1617. break;
  1618. } else if (has_end && *cur_ts != AV_NOPTS_VALUE && *cur_ts >= end) {
  1619. break;
  1620. }
  1621. frame_count++;
  1622. if (do_read_packets) {
  1623. if (do_show_packets)
  1624. show_packet(w, fmt_ctx, &pkt, i++);
  1625. nb_streams_packets[pkt.stream_index]++;
  1626. }
  1627. if (do_read_frames) {
  1628. pkt1 = pkt;
  1629. while (pkt1.size && process_frame(w, fmt_ctx, frame, &pkt1) > 0);
  1630. }
  1631. }
  1632. av_free_packet(&pkt);
  1633. }
  1634. av_init_packet(&pkt);
  1635. pkt.data = NULL;
  1636. pkt.size = 0;
  1637. //Flush remaining frames that are cached in the decoder
  1638. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1639. pkt.stream_index = i;
  1640. if (do_read_frames)
  1641. while (process_frame(w, fmt_ctx, frame, &pkt) > 0);
  1642. }
  1643. end:
  1644. av_frame_free(&frame);
  1645. if (ret < 0) {
  1646. av_log(NULL, AV_LOG_ERROR, "Could not read packets in interval ");
  1647. log_read_interval(interval, NULL, AV_LOG_ERROR);
  1648. }
  1649. return ret;
  1650. }
  1651. static int read_packets(WriterContext *w, AVFormatContext *fmt_ctx)
  1652. {
  1653. int i, ret = 0;
  1654. int64_t cur_ts = fmt_ctx->start_time;
  1655. if (read_intervals_nb == 0) {
  1656. ReadInterval interval = (ReadInterval) { .has_start = 0, .has_end = 0 };
  1657. ret = read_interval_packets(w, fmt_ctx, &interval, &cur_ts);
  1658. } else {
  1659. for (i = 0; i < read_intervals_nb; i++) {
  1660. ret = read_interval_packets(w, fmt_ctx, &read_intervals[i], &cur_ts);
  1661. if (ret < 0)
  1662. break;
  1663. }
  1664. }
  1665. return ret;
  1666. }
  1667. static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx, int in_program)
  1668. {
  1669. AVStream *stream = fmt_ctx->streams[stream_idx];
  1670. AVCodecContext *dec_ctx;
  1671. const AVCodec *dec;
  1672. char val_str[128];
  1673. const char *s;
  1674. AVRational sar, dar;
  1675. AVBPrint pbuf;
  1676. int ret = 0;
  1677. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  1678. writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM : SECTION_ID_STREAM);
  1679. print_int("index", stream->index);
  1680. if ((dec_ctx = stream->codec)) {
  1681. const char *profile = NULL;
  1682. dec = dec_ctx->codec;
  1683. if (dec) {
  1684. print_str("codec_name", dec->name);
  1685. if (!do_bitexact) {
  1686. if (dec->long_name) print_str ("codec_long_name", dec->long_name);
  1687. else print_str_opt("codec_long_name", "unknown");
  1688. }
  1689. } else {
  1690. print_str_opt("codec_name", "unknown");
  1691. if (!do_bitexact) {
  1692. print_str_opt("codec_long_name", "unknown");
  1693. }
  1694. }
  1695. if (dec && (profile = av_get_profile_name(dec, dec_ctx->profile)))
  1696. print_str("profile", profile);
  1697. else
  1698. print_str_opt("profile", "unknown");
  1699. s = av_get_media_type_string(dec_ctx->codec_type);
  1700. if (s) print_str ("codec_type", s);
  1701. else print_str_opt("codec_type", "unknown");
  1702. print_q("codec_time_base", dec_ctx->time_base, '/');
  1703. /* print AVI/FourCC tag */
  1704. av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);
  1705. print_str("codec_tag_string", val_str);
  1706. print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);
  1707. switch (dec_ctx->codec_type) {
  1708. case AVMEDIA_TYPE_VIDEO:
  1709. print_int("width", dec_ctx->width);
  1710. print_int("height", dec_ctx->height);
  1711. print_int("has_b_frames", dec_ctx->has_b_frames);
  1712. sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
  1713. if (sar.den) {
  1714. print_q("sample_aspect_ratio", sar, ':');
  1715. av_reduce(&dar.num, &dar.den,
  1716. dec_ctx->width * sar.num,
  1717. dec_ctx->height * sar.den,
  1718. 1024*1024);
  1719. print_q("display_aspect_ratio", dar, ':');
  1720. } else {
  1721. print_str_opt("sample_aspect_ratio", "N/A");
  1722. print_str_opt("display_aspect_ratio", "N/A");
  1723. }
  1724. s = av_get_pix_fmt_name(dec_ctx->pix_fmt);
  1725. if (s) print_str ("pix_fmt", s);
  1726. else print_str_opt("pix_fmt", "unknown");
  1727. print_int("level", dec_ctx->level);
  1728. if (dec_ctx->timecode_frame_start >= 0) {
  1729. char tcbuf[AV_TIMECODE_STR_SIZE];
  1730. av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);
  1731. print_str("timecode", tcbuf);
  1732. } else {
  1733. print_str_opt("timecode", "N/A");
  1734. }
  1735. break;
  1736. case AVMEDIA_TYPE_AUDIO:
  1737. s = av_get_sample_fmt_name(dec_ctx->sample_fmt);
  1738. if (s) print_str ("sample_fmt", s);
  1739. else print_str_opt("sample_fmt", "unknown");
  1740. print_val("sample_rate", dec_ctx->sample_rate, unit_hertz_str);
  1741. print_int("channels", dec_ctx->channels);
  1742. if (dec_ctx->channel_layout) {
  1743. av_bprint_clear(&pbuf);
  1744. av_bprint_channel_layout(&pbuf, dec_ctx->channels, dec_ctx->channel_layout);
  1745. print_str ("channel_layout", pbuf.str);
  1746. } else {
  1747. print_str_opt("channel_layout", "unknown");
  1748. }
  1749. print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));
  1750. break;
  1751. case AVMEDIA_TYPE_SUBTITLE:
  1752. if (dec_ctx->width)
  1753. print_int("width", dec_ctx->width);
  1754. else
  1755. print_str_opt("width", "N/A");
  1756. if (dec_ctx->height)
  1757. print_int("height", dec_ctx->height);
  1758. else
  1759. print_str_opt("height", "N/A");
  1760. break;
  1761. }
  1762. } else {
  1763. print_str_opt("codec_type", "unknown");
  1764. }
  1765. if (dec_ctx->codec && dec_ctx->codec->priv_class && show_private_data) {
  1766. const AVOption *opt = NULL;
  1767. while (opt = av_opt_next(dec_ctx->priv_data,opt)) {
  1768. uint8_t *str;
  1769. if (opt->flags) continue;
  1770. if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {
  1771. print_str(opt->name, str);
  1772. av_free(str);
  1773. }
  1774. }
  1775. }
  1776. if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
  1777. else print_str_opt("id", "N/A");
  1778. print_q("r_frame_rate", stream->r_frame_rate, '/');
  1779. print_q("avg_frame_rate", stream->avg_frame_rate, '/');
  1780. print_q("time_base", stream->time_base, '/');
  1781. print_ts ("start_pts", stream->start_time);
  1782. print_time("start_time", stream->start_time, &stream->time_base);
  1783. print_ts ("duration_ts", stream->duration);
  1784. print_time("duration", stream->duration, &stream->time_base);
  1785. if (dec_ctx->bit_rate > 0) print_val ("bit_rate", dec_ctx->bit_rate, unit_bit_per_second_str);
  1786. else print_str_opt("bit_rate", "N/A");
  1787. if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
  1788. else print_str_opt("nb_frames", "N/A");
  1789. if (nb_streams_frames[stream_idx]) print_fmt ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
  1790. else print_str_opt("nb_read_frames", "N/A");
  1791. if (nb_streams_packets[stream_idx]) print_fmt ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
  1792. else print_str_opt("nb_read_packets", "N/A");
  1793. if (do_show_data)
  1794. writer_print_data(w, "extradata", dec_ctx->extradata,
  1795. dec_ctx->extradata_size);
  1796. /* Print disposition information */
  1797. #define PRINT_DISPOSITION(flagname, name) do { \
  1798. print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
  1799. } while (0)
  1800. if (do_show_stream_disposition) {
  1801. writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM_DISPOSITION : SECTION_ID_STREAM_DISPOSITION);
  1802. PRINT_DISPOSITION(DEFAULT, "default");
  1803. PRINT_DISPOSITION(DUB, "dub");
  1804. PRINT_DISPOSITION(ORIGINAL, "original");
  1805. PRINT_DISPOSITION(COMMENT, "comment");
  1806. PRINT_DISPOSITION(LYRICS, "lyrics");
  1807. PRINT_DISPOSITION(KARAOKE, "karaoke");
  1808. PRINT_DISPOSITION(FORCED, "forced");
  1809. PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");
  1810. PRINT_DISPOSITION(VISUAL_IMPAIRED, "visual_impaired");
  1811. PRINT_DISPOSITION(CLEAN_EFFECTS, "clean_effects");
  1812. PRINT_DISPOSITION(ATTACHED_PIC, "attached_pic");
  1813. writer_print_section_footer(w);
  1814. }
  1815. if (do_show_stream_tags)
  1816. ret = show_tags(w, stream->metadata, in_program ? SECTION_ID_PROGRAM_STREAM_TAGS : SECTION_ID_STREAM_TAGS);
  1817. writer_print_section_footer(w);
  1818. av_bprint_finalize(&pbuf, NULL);
  1819. fflush(stdout);
  1820. return ret;
  1821. }
  1822. static int show_streams(WriterContext *w, AVFormatContext *fmt_ctx)
  1823. {
  1824. int i, ret = 0;
  1825. writer_print_section_header(w, SECTION_ID_STREAMS);
  1826. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1827. if (selected_streams[i]) {
  1828. ret = show_stream(w, fmt_ctx, i, 0);
  1829. if (ret < 0)
  1830. break;
  1831. }
  1832. writer_print_section_footer(w);
  1833. return ret;
  1834. }
  1835. static int show_program(WriterContext *w, AVFormatContext *fmt_ctx, AVProgram *program)
  1836. {
  1837. int i, ret = 0;
  1838. writer_print_section_header(w, SECTION_ID_PROGRAM);
  1839. print_int("program_id", program->id);
  1840. print_int("program_num", program->program_num);
  1841. print_int("nb_streams", program->nb_stream_indexes);
  1842. print_int("pmt_pid", program->pmt_pid);
  1843. print_int("pcr_pid", program->pcr_pid);
  1844. print_ts("start_pts", program->start_time);
  1845. print_time("start_time", program->start_time, &AV_TIME_BASE_Q);
  1846. print_ts("end_pts", program->end_time);
  1847. print_time("end_time", program->end_time, &AV_TIME_BASE_Q);
  1848. if (do_show_program_tags)
  1849. ret = show_tags(w, program->metadata, SECTION_ID_PROGRAM_TAGS);
  1850. if (ret < 0)
  1851. goto end;
  1852. writer_print_section_header(w, SECTION_ID_PROGRAM_STREAMS);
  1853. for (i = 0; i < program->nb_stream_indexes; i++) {
  1854. if (selected_streams[program->stream_index[i]]) {
  1855. ret = show_stream(w, fmt_ctx, program->stream_index[i], 1);
  1856. if (ret < 0)
  1857. break;
  1858. }
  1859. }
  1860. writer_print_section_footer(w);
  1861. end:
  1862. writer_print_section_footer(w);
  1863. return ret;
  1864. }
  1865. static int show_programs(WriterContext *w, AVFormatContext *fmt_ctx)
  1866. {
  1867. int i, ret = 0;
  1868. writer_print_section_header(w, SECTION_ID_PROGRAMS);
  1869. for (i = 0; i < fmt_ctx->nb_programs; i++) {
  1870. AVProgram *program = fmt_ctx->programs[i];
  1871. if (!program)
  1872. continue;
  1873. ret = show_program(w, fmt_ctx, program);
  1874. if (ret < 0)
  1875. break;
  1876. }
  1877. writer_print_section_footer(w);
  1878. return ret;
  1879. }
  1880. static int show_chapters(WriterContext *w, AVFormatContext *fmt_ctx)
  1881. {
  1882. int i, ret = 0;
  1883. writer_print_section_header(w, SECTION_ID_CHAPTERS);
  1884. for (i = 0; i < fmt_ctx->nb_chapters; i++) {
  1885. AVChapter *chapter = fmt_ctx->chapters[i];
  1886. writer_print_section_header(w, SECTION_ID_CHAPTER);
  1887. print_int("id", chapter->id);
  1888. print_q ("time_base", chapter->time_base, '/');
  1889. print_int("start", chapter->start);
  1890. print_time("start_time", chapter->start, &chapter->time_base);
  1891. print_int("end", chapter->end);
  1892. print_time("end_time", chapter->end, &chapter->time_base);
  1893. if (do_show_chapter_tags)
  1894. ret = show_tags(w, chapter->metadata, SECTION_ID_CHAPTER_TAGS);
  1895. writer_print_section_footer(w);
  1896. }
  1897. writer_print_section_footer(w);
  1898. return ret;
  1899. }
  1900. static int show_format(WriterContext *w, AVFormatContext *fmt_ctx)
  1901. {
  1902. char val_str[128];
  1903. int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
  1904. int ret = 0;
  1905. writer_print_section_header(w, SECTION_ID_FORMAT);
  1906. print_str_validate("filename", fmt_ctx->filename);
  1907. print_int("nb_streams", fmt_ctx->nb_streams);
  1908. print_int("nb_programs", fmt_ctx->nb_programs);
  1909. print_str("format_name", fmt_ctx->iformat->name);
  1910. if (!do_bitexact) {
  1911. if (fmt_ctx->iformat->long_name) print_str ("format_long_name", fmt_ctx->iformat->long_name);
  1912. else print_str_opt("format_long_name", "unknown");
  1913. }
  1914. print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
  1915. print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
  1916. if (size >= 0) print_val ("size", size, unit_byte_str);
  1917. else print_str_opt("size", "N/A");
  1918. if (fmt_ctx->bit_rate > 0) print_val ("bit_rate", fmt_ctx->bit_rate, unit_bit_per_second_str);
  1919. else print_str_opt("bit_rate", "N/A");
  1920. print_int("probe_score", av_format_get_probe_score(fmt_ctx));
  1921. if (do_show_format_tags)
  1922. ret = show_tags(w, fmt_ctx->metadata, SECTION_ID_FORMAT_TAGS);
  1923. writer_print_section_footer(w);
  1924. fflush(stdout);
  1925. return ret;
  1926. }
  1927. static void show_error(WriterContext *w, int err)
  1928. {
  1929. char errbuf[128];
  1930. const char *errbuf_ptr = errbuf;
  1931. if (av_strerror(err, errbuf, sizeof(errbuf)) < 0)
  1932. errbuf_ptr = strerror(AVUNERROR(err));
  1933. writer_print_section_header(w, SECTION_ID_ERROR);
  1934. print_int("code", err);
  1935. print_str("string", errbuf_ptr);
  1936. writer_print_section_footer(w);
  1937. }
  1938. static int open_input_file(AVFormatContext **fmt_ctx_ptr, const char *filename)
  1939. {
  1940. int err, i, orig_nb_streams;
  1941. AVFormatContext *fmt_ctx = NULL;
  1942. AVDictionaryEntry *t;
  1943. AVDictionary **opts;
  1944. if ((err = avformat_open_input(&fmt_ctx, filename,
  1945. iformat, &format_opts)) < 0) {
  1946. print_error(filename, err);
  1947. return err;
  1948. }
  1949. if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  1950. av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
  1951. return AVERROR_OPTION_NOT_FOUND;
  1952. }
  1953. /* fill the streams in the format context */
  1954. opts = setup_find_stream_info_opts(fmt_ctx, codec_opts);
  1955. orig_nb_streams = fmt_ctx->nb_streams;
  1956. if ((err = avformat_find_stream_info(fmt_ctx, opts)) < 0) {
  1957. print_error(filename, err);
  1958. return err;
  1959. }
  1960. for (i = 0; i < orig_nb_streams; i++)
  1961. av_dict_free(&opts[i]);
  1962. av_freep(&opts);
  1963. av_dump_format(fmt_ctx, 0, filename, 0);
  1964. /* bind a decoder to each input stream */
  1965. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  1966. AVStream *stream = fmt_ctx->streams[i];
  1967. AVCodec *codec;
  1968. if (stream->codec->codec_id == AV_CODEC_ID_PROBE) {
  1969. av_log(NULL, AV_LOG_WARNING,
  1970. "Failed to probe codec for input stream %d\n",
  1971. stream->index);
  1972. } else if (!(codec = avcodec_find_decoder(stream->codec->codec_id))) {
  1973. av_log(NULL, AV_LOG_WARNING,
  1974. "Unsupported codec with id %d for input stream %d\n",
  1975. stream->codec->codec_id, stream->index);
  1976. } else {
  1977. AVDictionary *opts = filter_codec_opts(codec_opts, stream->codec->codec_id,
  1978. fmt_ctx, stream, codec);
  1979. if (avcodec_open2(stream->codec, codec, &opts) < 0) {
  1980. av_log(NULL, AV_LOG_WARNING, "Could not open codec for input stream %d\n",
  1981. stream->index);
  1982. }
  1983. if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  1984. av_log(NULL, AV_LOG_ERROR, "Option %s for input stream %d not found\n",
  1985. t->key, stream->index);
  1986. return AVERROR_OPTION_NOT_FOUND;
  1987. }
  1988. }
  1989. }
  1990. *fmt_ctx_ptr = fmt_ctx;
  1991. return 0;
  1992. }
  1993. static void close_input_file(AVFormatContext **ctx_ptr)
  1994. {
  1995. int i;
  1996. AVFormatContext *fmt_ctx = *ctx_ptr;
  1997. /* close decoder for each stream */
  1998. for (i = 0; i < fmt_ctx->nb_streams; i++)
  1999. if (fmt_ctx->streams[i]->codec->codec_id != AV_CODEC_ID_NONE)
  2000. avcodec_close(fmt_ctx->streams[i]->codec);
  2001. avformat_close_input(ctx_ptr);
  2002. }
  2003. static int probe_file(WriterContext *wctx, const char *filename)
  2004. {
  2005. AVFormatContext *fmt_ctx;
  2006. int ret, i;
  2007. int section_id;
  2008. do_read_frames = do_show_frames || do_count_frames;
  2009. do_read_packets = do_show_packets || do_count_packets;
  2010. ret = open_input_file(&fmt_ctx, filename);
  2011. if (ret < 0)
  2012. return ret;
  2013. #define CHECK_END if (ret < 0) goto end
  2014. nb_streams_frames = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_frames));
  2015. nb_streams_packets = av_calloc(fmt_ctx->nb_streams, sizeof(*nb_streams_packets));
  2016. selected_streams = av_calloc(fmt_ctx->nb_streams, sizeof(*selected_streams));
  2017. for (i = 0; i < fmt_ctx->nb_streams; i++) {
  2018. if (stream_specifier) {
  2019. ret = avformat_match_stream_specifier(fmt_ctx,
  2020. fmt_ctx->streams[i],
  2021. stream_specifier);
  2022. CHECK_END;
  2023. else
  2024. selected_streams[i] = ret;
  2025. ret = 0;
  2026. } else {
  2027. selected_streams[i] = 1;
  2028. }
  2029. }
  2030. if (do_read_frames || do_read_packets) {
  2031. if (do_show_frames && do_show_packets &&
  2032. wctx->writer->flags & WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER)
  2033. section_id = SECTION_ID_PACKETS_AND_FRAMES;
  2034. else if (do_show_packets && !do_show_frames)
  2035. section_id = SECTION_ID_PACKETS;
  2036. else // (!do_show_packets && do_show_frames)
  2037. section_id = SECTION_ID_FRAMES;
  2038. if (do_show_frames || do_show_packets)
  2039. writer_print_section_header(wctx, section_id);
  2040. ret = read_packets(wctx, fmt_ctx);
  2041. if (do_show_frames || do_show_packets)
  2042. writer_print_section_footer(wctx);
  2043. CHECK_END;
  2044. }
  2045. if (do_show_programs) {
  2046. ret = show_programs(wctx, fmt_ctx);
  2047. CHECK_END;
  2048. }
  2049. if (do_show_streams) {
  2050. ret = show_streams(wctx, fmt_ctx);
  2051. CHECK_END;
  2052. }
  2053. if (do_show_chapters) {
  2054. ret = show_chapters(wctx, fmt_ctx);
  2055. CHECK_END;
  2056. }
  2057. if (do_show_format) {
  2058. ret = show_format(wctx, fmt_ctx);
  2059. CHECK_END;
  2060. }
  2061. end:
  2062. close_input_file(&fmt_ctx);
  2063. av_freep(&nb_streams_frames);
  2064. av_freep(&nb_streams_packets);
  2065. av_freep(&selected_streams);
  2066. return ret;
  2067. }
  2068. static void show_usage(void)
  2069. {
  2070. av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
  2071. av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] [INPUT_FILE]\n", program_name);
  2072. av_log(NULL, AV_LOG_INFO, "\n");
  2073. }
  2074. static void ffprobe_show_program_version(WriterContext *w)
  2075. {
  2076. AVBPrint pbuf;
  2077. av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);
  2078. writer_print_section_header(w, SECTION_ID_PROGRAM_VERSION);
  2079. print_str("version", FFMPEG_VERSION);
  2080. print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
  2081. program_birth_year, CONFIG_THIS_YEAR);
  2082. print_str("build_date", __DATE__);
  2083. print_str("build_time", __TIME__);
  2084. print_str("compiler_ident", CC_IDENT);
  2085. print_str("configuration", FFMPEG_CONFIGURATION);
  2086. writer_print_section_footer(w);
  2087. av_bprint_finalize(&pbuf, NULL);
  2088. }
  2089. #define SHOW_LIB_VERSION(libname, LIBNAME) \
  2090. do { \
  2091. if (CONFIG_##LIBNAME) { \
  2092. unsigned int version = libname##_version(); \
  2093. writer_print_section_header(w, SECTION_ID_LIBRARY_VERSION); \
  2094. print_str("name", "lib" #libname); \
  2095. print_int("major", LIB##LIBNAME##_VERSION_MAJOR); \
  2096. print_int("minor", LIB##LIBNAME##_VERSION_MINOR); \
  2097. print_int("micro", LIB##LIBNAME##_VERSION_MICRO); \
  2098. print_int("version", version); \
  2099. print_str("ident", LIB##LIBNAME##_IDENT); \
  2100. writer_print_section_footer(w); \
  2101. } \
  2102. } while (0)
  2103. static void ffprobe_show_library_versions(WriterContext *w)
  2104. {
  2105. writer_print_section_header(w, SECTION_ID_LIBRARY_VERSIONS);
  2106. SHOW_LIB_VERSION(avutil, AVUTIL);
  2107. SHOW_LIB_VERSION(avcodec, AVCODEC);
  2108. SHOW_LIB_VERSION(avformat, AVFORMAT);
  2109. SHOW_LIB_VERSION(avdevice, AVDEVICE);
  2110. SHOW_LIB_VERSION(avfilter, AVFILTER);
  2111. SHOW_LIB_VERSION(swscale, SWSCALE);
  2112. SHOW_LIB_VERSION(swresample, SWRESAMPLE);
  2113. SHOW_LIB_VERSION(postproc, POSTPROC);
  2114. writer_print_section_footer(w);
  2115. }
  2116. static int opt_format(void *optctx, const char *opt, const char *arg)
  2117. {
  2118. iformat = av_find_input_format(arg);
  2119. if (!iformat) {
  2120. av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
  2121. return AVERROR(EINVAL);
  2122. }
  2123. return 0;
  2124. }
  2125. static inline void mark_section_show_entries(SectionID section_id,
  2126. int show_all_entries, AVDictionary *entries)
  2127. {
  2128. struct section *section = &sections[section_id];
  2129. section->show_all_entries = show_all_entries;
  2130. if (show_all_entries) {
  2131. SectionID *id;
  2132. for (id = section->children_ids; *id != -1; id++)
  2133. mark_section_show_entries(*id, show_all_entries, entries);
  2134. } else {
  2135. av_dict_copy(&section->entries_to_show, entries, 0);
  2136. }
  2137. }
  2138. static int match_section(const char *section_name,
  2139. int show_all_entries, AVDictionary *entries)
  2140. {
  2141. int i, ret = 0;
  2142. for (i = 0; i < FF_ARRAY_ELEMS(sections); i++) {
  2143. const struct section *section = &sections[i];
  2144. if (!strcmp(section_name, section->name) ||
  2145. (section->unique_name && !strcmp(section_name, section->unique_name))) {
  2146. av_log(NULL, AV_LOG_DEBUG,
  2147. "'%s' matches section with unique name '%s'\n", section_name,
  2148. (char *)av_x_if_null(section->unique_name, section->name));
  2149. ret++;
  2150. mark_section_show_entries(section->id, show_all_entries, entries);
  2151. }
  2152. }
  2153. return ret;
  2154. }
  2155. static int opt_show_entries(void *optctx, const char *opt, const char *arg)
  2156. {
  2157. const char *p = arg;
  2158. int ret = 0;
  2159. while (*p) {
  2160. AVDictionary *entries = NULL;
  2161. char *section_name = av_get_token(&p, "=:");
  2162. int show_all_entries = 0;
  2163. if (!section_name) {
  2164. av_log(NULL, AV_LOG_ERROR,
  2165. "Missing section name for option '%s'\n", opt);
  2166. return AVERROR(EINVAL);
  2167. }
  2168. if (*p == '=') {
  2169. p++;
  2170. while (*p && *p != ':') {
  2171. char *entry = av_get_token(&p, ",:");
  2172. if (!entry)
  2173. break;
  2174. av_log(NULL, AV_LOG_VERBOSE,
  2175. "Adding '%s' to the entries to show in section '%s'\n",
  2176. entry, section_name);
  2177. av_dict_set(&entries, entry, "", AV_DICT_DONT_STRDUP_KEY);
  2178. if (*p == ',')
  2179. p++;
  2180. }
  2181. } else {
  2182. show_all_entries = 1;
  2183. }
  2184. ret = match_section(section_name, show_all_entries, entries);
  2185. if (ret == 0) {
  2186. av_log(NULL, AV_LOG_ERROR, "No match for section '%s'\n", section_name);
  2187. ret = AVERROR(EINVAL);
  2188. }
  2189. av_dict_free(&entries);
  2190. av_free(section_name);
  2191. if (ret <= 0)
  2192. break;
  2193. if (*p)
  2194. p++;
  2195. }
  2196. return ret;
  2197. }
  2198. static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
  2199. {
  2200. char *buf = av_asprintf("format=%s", arg);
  2201. int ret;
  2202. av_log(NULL, AV_LOG_WARNING,
  2203. "Option '%s' is deprecated, use '-show_entries format=%s' instead\n",
  2204. opt, arg);
  2205. ret = opt_show_entries(optctx, opt, buf);
  2206. av_free(buf);
  2207. return ret;
  2208. }
  2209. static void opt_input_file(void *optctx, const char *arg)
  2210. {
  2211. if (input_filename) {
  2212. av_log(NULL, AV_LOG_ERROR,
  2213. "Argument '%s' provided as input filename, but '%s' was already specified.\n",
  2214. arg, input_filename);
  2215. exit_program(1);
  2216. }
  2217. if (!strcmp(arg, "-"))
  2218. arg = "pipe:";
  2219. input_filename = arg;
  2220. }
  2221. static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
  2222. {
  2223. opt_input_file(optctx, arg);
  2224. return 0;
  2225. }
  2226. void show_help_default(const char *opt, const char *arg)
  2227. {
  2228. av_log_set_callback(log_callback_help);
  2229. show_usage();
  2230. show_help_options(options, "Main options:", 0, 0, 0);
  2231. printf("\n");
  2232. show_help_children(avformat_get_class(), AV_OPT_FLAG_DECODING_PARAM);
  2233. }
  2234. /**
  2235. * Parse interval specification, according to the format:
  2236. * INTERVAL ::= [START|+START_OFFSET][%[END|+END_OFFSET]]
  2237. * INTERVALS ::= INTERVAL[,INTERVALS]
  2238. */
  2239. static int parse_read_interval(const char *interval_spec,
  2240. ReadInterval *interval)
  2241. {
  2242. int ret = 0;
  2243. char *next, *p, *spec = av_strdup(interval_spec);
  2244. if (!spec)
  2245. return AVERROR(ENOMEM);
  2246. if (!*spec) {
  2247. av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n");
  2248. ret = AVERROR(EINVAL);
  2249. goto end;
  2250. }
  2251. p = spec;
  2252. next = strchr(spec, '%');
  2253. if (next)
  2254. *next++ = 0;
  2255. /* parse first part */
  2256. if (*p) {
  2257. interval->has_start = 1;
  2258. if (*p == '+') {
  2259. interval->start_is_offset = 1;
  2260. p++;
  2261. } else {
  2262. interval->start_is_offset = 0;
  2263. }
  2264. ret = av_parse_time(&interval->start, p, 1);
  2265. if (ret < 0) {
  2266. av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p);
  2267. goto end;
  2268. }
  2269. } else {
  2270. interval->has_start = 0;
  2271. }
  2272. /* parse second part */
  2273. p = next;
  2274. if (p && *p) {
  2275. int64_t us;
  2276. interval->has_end = 1;
  2277. if (*p == '+') {
  2278. interval->end_is_offset = 1;
  2279. p++;
  2280. } else {
  2281. interval->end_is_offset = 0;
  2282. }
  2283. if (interval->end_is_offset && *p == '#') {
  2284. long long int lli;
  2285. char *tail;
  2286. interval->duration_frames = 1;
  2287. p++;
  2288. lli = strtoll(p, &tail, 10);
  2289. if (*tail || lli < 0) {
  2290. av_log(NULL, AV_LOG_ERROR,
  2291. "Invalid or negative value '%s' for duration number of frames\n", p);
  2292. goto end;
  2293. }
  2294. interval->end = lli;
  2295. } else {
  2296. ret = av_parse_time(&us, p, 1);
  2297. if (ret < 0) {
  2298. av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p);
  2299. goto end;
  2300. }
  2301. interval->end = us;
  2302. }
  2303. } else {
  2304. interval->has_end = 0;
  2305. }
  2306. end:
  2307. av_free(spec);
  2308. return ret;
  2309. }
  2310. static int parse_read_intervals(const char *intervals_spec)
  2311. {
  2312. int ret, n, i;
  2313. char *p, *spec = av_strdup(intervals_spec);
  2314. if (!spec)
  2315. return AVERROR(ENOMEM);
  2316. /* preparse specification, get number of intervals */
  2317. for (n = 0, p = spec; *p; p++)
  2318. if (*p == ',')
  2319. n++;
  2320. n++;
  2321. read_intervals = av_malloc(n * sizeof(*read_intervals));
  2322. if (!read_intervals) {
  2323. ret = AVERROR(ENOMEM);
  2324. goto end;
  2325. }
  2326. read_intervals_nb = n;
  2327. /* parse intervals */
  2328. p = spec;
  2329. for (i = 0; p; i++) {
  2330. char *next;
  2331. av_assert0(i < read_intervals_nb);
  2332. next = strchr(p, ',');
  2333. if (next)
  2334. *next++ = 0;
  2335. read_intervals[i].id = i;
  2336. ret = parse_read_interval(p, &read_intervals[i]);
  2337. if (ret < 0) {
  2338. av_log(NULL, AV_LOG_ERROR, "Error parsing read interval #%d '%s'\n",
  2339. i, p);
  2340. goto end;
  2341. }
  2342. av_log(NULL, AV_LOG_VERBOSE, "Parsed log interval ");
  2343. log_read_interval(&read_intervals[i], NULL, AV_LOG_VERBOSE);
  2344. p = next;
  2345. }
  2346. av_assert0(i == read_intervals_nb);
  2347. end:
  2348. av_free(spec);
  2349. return ret;
  2350. }
  2351. static int opt_read_intervals(void *optctx, const char *opt, const char *arg)
  2352. {
  2353. return parse_read_intervals(arg);
  2354. }
  2355. static int opt_pretty(void *optctx, const char *opt, const char *arg)
  2356. {
  2357. show_value_unit = 1;
  2358. use_value_prefix = 1;
  2359. use_byte_value_binary_prefix = 1;
  2360. use_value_sexagesimal_format = 1;
  2361. return 0;
  2362. }
  2363. static void print_section(SectionID id, int level)
  2364. {
  2365. const SectionID *pid;
  2366. const struct section *section = &sections[id];
  2367. printf("%c%c%c",
  2368. section->flags & SECTION_FLAG_IS_WRAPPER ? 'W' : '.',
  2369. section->flags & SECTION_FLAG_IS_ARRAY ? 'A' : '.',
  2370. section->flags & SECTION_FLAG_HAS_VARIABLE_FIELDS ? 'V' : '.');
  2371. printf("%*c %s", level * 4, ' ', section->name);
  2372. if (section->unique_name)
  2373. printf("/%s", section->unique_name);
  2374. printf("\n");
  2375. for (pid = section->children_ids; *pid != -1; pid++)
  2376. print_section(*pid, level+1);
  2377. }
  2378. static int opt_sections(void *optctx, const char *opt, const char *arg)
  2379. {
  2380. printf("Sections:\n"
  2381. "W.. = Section is a wrapper (contains other sections, no local entries)\n"
  2382. ".A. = Section contains an array of elements of the same type\n"
  2383. "..V = Section may contain a variable number of fields with variable keys\n"
  2384. "FLAGS NAME/UNIQUE_NAME\n"
  2385. "---\n");
  2386. print_section(SECTION_ID_ROOT, 0);
  2387. return 0;
  2388. }
  2389. static int opt_show_versions(const char *opt, const char *arg)
  2390. {
  2391. mark_section_show_entries(SECTION_ID_PROGRAM_VERSION, 1, NULL);
  2392. mark_section_show_entries(SECTION_ID_LIBRARY_VERSION, 1, NULL);
  2393. return 0;
  2394. }
  2395. #define DEFINE_OPT_SHOW_SECTION(section, target_section_id) \
  2396. static int opt_show_##section(const char *opt, const char *arg) \
  2397. { \
  2398. mark_section_show_entries(SECTION_ID_##target_section_id, 1, NULL); \
  2399. return 0; \
  2400. }
  2401. DEFINE_OPT_SHOW_SECTION(chapters, CHAPTERS);
  2402. DEFINE_OPT_SHOW_SECTION(error, ERROR);
  2403. DEFINE_OPT_SHOW_SECTION(format, FORMAT);
  2404. DEFINE_OPT_SHOW_SECTION(frames, FRAMES);
  2405. DEFINE_OPT_SHOW_SECTION(library_versions, LIBRARY_VERSIONS);
  2406. DEFINE_OPT_SHOW_SECTION(packets, PACKETS);
  2407. DEFINE_OPT_SHOW_SECTION(program_version, PROGRAM_VERSION);
  2408. DEFINE_OPT_SHOW_SECTION(streams, STREAMS);
  2409. DEFINE_OPT_SHOW_SECTION(programs, PROGRAMS);
  2410. static const OptionDef real_options[] = {
  2411. #include "cmdutils_common_opts.h"
  2412. { "f", HAS_ARG, {.func_arg = opt_format}, "force format", "format" },
  2413. { "unit", OPT_BOOL, {&show_value_unit}, "show unit of the displayed values" },
  2414. { "prefix", OPT_BOOL, {&use_value_prefix}, "use SI prefixes for the displayed values" },
  2415. { "byte_binary_prefix", OPT_BOOL, {&use_byte_value_binary_prefix},
  2416. "use binary prefixes for byte units" },
  2417. { "sexagesimal", OPT_BOOL, {&use_value_sexagesimal_format},
  2418. "use sexagesimal format HOURS:MM:SS.MICROSECONDS for time units" },
  2419. { "pretty", 0, {.func_arg = opt_pretty},
  2420. "prettify the format of displayed values, make it more human readable" },
  2421. { "print_format", OPT_STRING | HAS_ARG, {(void*)&print_format},
  2422. "set the output printing format (available formats are: default, compact, csv, flat, ini, json, xml)", "format" },
  2423. { "of", OPT_STRING | HAS_ARG, {(void*)&print_format}, "alias for -print_format", "format" },
  2424. { "select_streams", OPT_STRING | HAS_ARG, {(void*)&stream_specifier}, "select the specified streams", "stream_specifier" },
  2425. { "sections", OPT_EXIT, {.func_arg = opt_sections}, "print sections structure and section information, and exit" },
  2426. { "show_data", OPT_BOOL, {(void*)&do_show_data}, "show packets data" },
  2427. { "show_error", 0, {(void*)&opt_show_error}, "show probing error" },
  2428. { "show_format", 0, {(void*)&opt_show_format}, "show format/container info" },
  2429. { "show_frames", 0, {(void*)&opt_show_frames}, "show frames info" },
  2430. { "show_format_entry", HAS_ARG, {.func_arg = opt_show_format_entry},
  2431. "show a particular entry from the format/container info", "entry" },
  2432. { "show_entries", HAS_ARG, {.func_arg = opt_show_entries},
  2433. "show a set of specified entries", "entry_list" },
  2434. { "show_packets", 0, {(void*)&opt_show_packets}, "show packets info" },
  2435. { "show_programs", 0, {(void*)&opt_show_programs}, "show programs info" },
  2436. { "show_streams", 0, {(void*)&opt_show_streams}, "show streams info" },
  2437. { "show_chapters", 0, {(void*)&opt_show_chapters}, "show chapters info" },
  2438. { "count_frames", OPT_BOOL, {(void*)&do_count_frames}, "count the number of frames per stream" },
  2439. { "count_packets", OPT_BOOL, {(void*)&do_count_packets}, "count the number of packets per stream" },
  2440. { "show_program_version", 0, {(void*)&opt_show_program_version}, "show ffprobe version" },
  2441. { "show_library_versions", 0, {(void*)&opt_show_library_versions}, "show library versions" },
  2442. { "show_versions", 0, {(void*)&opt_show_versions}, "show program and library versions" },
  2443. { "show_private_data", OPT_BOOL, {(void*)&show_private_data}, "show private data" },
  2444. { "private", OPT_BOOL, {(void*)&show_private_data}, "same as show_private_data" },
  2445. { "bitexact", OPT_BOOL, {&do_bitexact}, "force bitexact output" },
  2446. { "read_intervals", HAS_ARG, {.func_arg = opt_read_intervals}, "set read intervals", "read_intervals" },
  2447. { "default", HAS_ARG | OPT_AUDIO | OPT_VIDEO | OPT_EXPERT, {.func_arg = opt_default}, "generic catch all option", "" },
  2448. { "i", HAS_ARG, {.func_arg = opt_input_file_i}, "read specified file", "input_file"},
  2449. { NULL, },
  2450. };
  2451. static inline int check_section_show_entries(int section_id)
  2452. {
  2453. int *id;
  2454. struct section *section = &sections[section_id];
  2455. if (sections[section_id].show_all_entries || sections[section_id].entries_to_show)
  2456. return 1;
  2457. for (id = section->children_ids; *id != -1; id++)
  2458. if (check_section_show_entries(*id))
  2459. return 1;
  2460. return 0;
  2461. }
  2462. #define SET_DO_SHOW(id, varname) do { \
  2463. if (check_section_show_entries(SECTION_ID_##id)) \
  2464. do_show_##varname = 1; \
  2465. } while (0)
  2466. int main(int argc, char **argv)
  2467. {
  2468. const Writer *w;
  2469. WriterContext *wctx;
  2470. char *buf;
  2471. char *w_name = NULL, *w_args = NULL;
  2472. int ret, i;
  2473. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2474. register_exit(ffprobe_cleanup);
  2475. options = real_options;
  2476. parse_loglevel(argc, argv, options);
  2477. av_register_all();
  2478. avformat_network_init();
  2479. init_opts();
  2480. #if CONFIG_AVDEVICE
  2481. avdevice_register_all();
  2482. #endif
  2483. show_banner(argc, argv, options);
  2484. parse_options(NULL, argc, argv, options, opt_input_file);
  2485. /* mark things to show, based on -show_entries */
  2486. SET_DO_SHOW(CHAPTERS, chapters);
  2487. SET_DO_SHOW(ERROR, error);
  2488. SET_DO_SHOW(FORMAT, format);
  2489. SET_DO_SHOW(FRAMES, frames);
  2490. SET_DO_SHOW(LIBRARY_VERSIONS, library_versions);
  2491. SET_DO_SHOW(PACKETS, packets);
  2492. SET_DO_SHOW(PROGRAM_VERSION, program_version);
  2493. SET_DO_SHOW(PROGRAMS, programs);
  2494. SET_DO_SHOW(STREAMS, streams);
  2495. SET_DO_SHOW(STREAM_DISPOSITION, stream_disposition);
  2496. SET_DO_SHOW(PROGRAM_STREAM_DISPOSITION, stream_disposition);
  2497. SET_DO_SHOW(CHAPTER_TAGS, chapter_tags);
  2498. SET_DO_SHOW(FORMAT_TAGS, format_tags);
  2499. SET_DO_SHOW(FRAME_TAGS, frame_tags);
  2500. SET_DO_SHOW(PROGRAM_TAGS, program_tags);
  2501. SET_DO_SHOW(STREAM_TAGS, stream_tags);
  2502. if (do_bitexact && (do_show_program_version || do_show_library_versions)) {
  2503. av_log(NULL, AV_LOG_ERROR,
  2504. "-bitexact and -show_program_version or -show_library_versions "
  2505. "options are incompatible\n");
  2506. ret = AVERROR(EINVAL);
  2507. goto end;
  2508. }
  2509. writer_register_all();
  2510. if (!print_format)
  2511. print_format = av_strdup("default");
  2512. if (!print_format) {
  2513. ret = AVERROR(ENOMEM);
  2514. goto end;
  2515. }
  2516. w_name = av_strtok(print_format, "=", &buf);
  2517. w_args = buf;
  2518. w = writer_get_by_name(w_name);
  2519. if (!w) {
  2520. av_log(NULL, AV_LOG_ERROR, "Unknown output format with name '%s'\n", w_name);
  2521. ret = AVERROR(EINVAL);
  2522. goto end;
  2523. }
  2524. if ((ret = writer_open(&wctx, w, w_args,
  2525. sections, FF_ARRAY_ELEMS(sections))) >= 0) {
  2526. if (w == &xml_writer)
  2527. wctx->string_validation_utf8_flags |= AV_UTF8_FLAG_EXCLUDE_XML_INVALID_CONTROL_CODES;
  2528. writer_print_section_header(wctx, SECTION_ID_ROOT);
  2529. if (do_show_program_version)
  2530. ffprobe_show_program_version(wctx);
  2531. if (do_show_library_versions)
  2532. ffprobe_show_library_versions(wctx);
  2533. if (!input_filename &&
  2534. ((do_show_format || do_show_programs || do_show_streams || do_show_chapters || do_show_packets || do_show_error) ||
  2535. (!do_show_program_version && !do_show_library_versions))) {
  2536. show_usage();
  2537. av_log(NULL, AV_LOG_ERROR, "You have to specify one input file.\n");
  2538. av_log(NULL, AV_LOG_ERROR, "Use -h to get full help or, even better, run 'man %s'.\n", program_name);
  2539. ret = AVERROR(EINVAL);
  2540. } else if (input_filename) {
  2541. ret = probe_file(wctx, input_filename);
  2542. if (ret < 0 && do_show_error)
  2543. show_error(wctx, ret);
  2544. }
  2545. writer_print_section_footer(wctx);
  2546. writer_close(&wctx);
  2547. }
  2548. end:
  2549. av_freep(&print_format);
  2550. av_freep(&read_intervals);
  2551. uninit_opts();
  2552. for (i = 0; i < FF_ARRAY_ELEMS(sections); i++)
  2553. av_dict_free(&(sections[i].entries_to_show));
  2554. avformat_network_deinit();
  2555. return ret < 0;
  2556. }