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.

3041 lines
108KB

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