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.

3111 lines
111KB

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