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.

2794 lines
98KB

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