FFmpeg
ffprobe.c
Go to the documentation of this file.
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 /**
22  * @file
23  * simple media prober based on the FFmpeg libraries
24  */
25 
26 #include "config.h"
27 #include "libavutil/ffversion.h"
28 
29 #include <string.h>
30 #include <math.h>
31 
32 #include "libavformat/avformat.h"
33 #include "libavformat/version.h"
34 #include "libavcodec/avcodec.h"
35 #include "libavcodec/version.h"
37 #include "libavutil/avassert.h"
38 #include "libavutil/avstring.h"
39 #include "libavutil/bprint.h"
41 #include "libavutil/display.h"
42 #include "libavutil/hash.h"
46 #include "libavutil/dovi_meta.h"
47 #include "libavutil/opt.h"
48 #include "libavutil/pixdesc.h"
49 #include "libavutil/spherical.h"
50 #include "libavutil/stereo3d.h"
51 #include "libavutil/dict.h"
52 #include "libavutil/intreadwrite.h"
53 #include "libavutil/libm.h"
54 #include "libavutil/parseutils.h"
55 #include "libavutil/timecode.h"
56 #include "libavutil/timestamp.h"
57 #include "libavdevice/avdevice.h"
58 #include "libavdevice/version.h"
59 #include "libswscale/swscale.h"
60 #include "libswscale/version.h"
62 #include "libswresample/version.h"
64 #include "libpostproc/version.h"
65 #include "libavfilter/version.h"
66 #include "cmdutils.h"
67 #include "opt_common.h"
68 
69 #include "libavutil/thread.h"
70 
71 #if !HAVE_THREADS
72 # ifdef pthread_mutex_lock
73 # undef pthread_mutex_lock
74 # endif
75 # define pthread_mutex_lock(a) do{}while(0)
76 # ifdef pthread_mutex_unlock
77 # undef pthread_mutex_unlock
78 # endif
79 # define pthread_mutex_unlock(a) do{}while(0)
80 #endif
81 
82 // attached as opaque_ref to packets/frames
83 typedef struct FrameData {
84  int64_t pkt_pos;
85  int pkt_size;
86 } FrameData;
87 
88 typedef struct InputStream {
89  AVStream *st;
90 
92 } InputStream;
93 
94 typedef struct InputFile {
96 
98  int nb_streams;
99 } InputFile;
100 
101 const char program_name[] = "ffprobe";
102 const int program_birth_year = 2007;
103 
104 static int do_bitexact = 0;
105 static int do_count_frames = 0;
106 static int do_count_packets = 0;
107 static int do_read_frames = 0;
108 static int do_read_packets = 0;
109 static int do_show_chapters = 0;
110 static int do_show_error = 0;
111 static int do_show_format = 0;
112 static int do_show_frames = 0;
113 static int do_show_packets = 0;
114 static int do_show_programs = 0;
115 static int do_show_streams = 0;
117 static int do_show_data = 0;
118 static int do_show_program_version = 0;
120 static int do_show_pixel_formats = 0;
123 static int do_show_log = 0;
124 
125 static int do_show_chapter_tags = 0;
126 static int do_show_format_tags = 0;
127 static int do_show_frame_tags = 0;
128 static int do_show_program_tags = 0;
129 static int do_show_stream_tags = 0;
130 static int do_show_packet_tags = 0;
131 
132 static int show_value_unit = 0;
133 static int use_value_prefix = 0;
136 static int show_private_data = 1;
137 
138 #define SHOW_OPTIONAL_FIELDS_AUTO -1
139 #define SHOW_OPTIONAL_FIELDS_NEVER 0
140 #define SHOW_OPTIONAL_FIELDS_ALWAYS 1
142 
143 static char *output_format;
144 static char *stream_specifier;
145 static char *show_data_hash;
146 
147 typedef struct ReadInterval {
148  int id; ///< identifier
149  int64_t start, end; ///< start, end in second/AV_TIME_BASE units
153 } ReadInterval;
154 
156 static int read_intervals_nb = 0;
157 
158 static int find_stream_info = 1;
159 
160 /* section structure definition */
161 
162 #define SECTION_MAX_NB_CHILDREN 10
163 
164 typedef enum {
214 } SectionID;
215 
216 struct section {
217  int id; ///< unique id identifying a section
218  const char *name;
219 
220 #define SECTION_FLAG_IS_WRAPPER 1 ///< the section only contains other sections, but has no data at its own level
221 #define SECTION_FLAG_IS_ARRAY 2 ///< the section contains an array of elements of the same type
222 #define SECTION_FLAG_HAS_VARIABLE_FIELDS 4 ///< the section may contain a variable number of fields with variable keys.
223  /// For these sections the element_name field is mandatory.
224 #define SECTION_FLAG_HAS_TYPE 8 ///< the section contains a type to distinguish multiple nested elements
225 
226  int flags;
227  const SectionID children_ids[SECTION_MAX_NB_CHILDREN+1]; ///< list of children section IDS, terminated by -1
228  const char *element_name; ///< name of the contained element, if provided
229  const char *unique_name; ///< unique section name, in case the name is ambiguous
231  const char *(* get_type)(const void *data); ///< function returning a type if defined, must be defined when SECTION_FLAG_HAS_TYPE is defined
233 };
234 
235 static const char *get_packet_side_data_type(const void *data)
236 {
237  const AVPacketSideData *sd = (const AVPacketSideData *)data;
238  return av_x_if_null(av_packet_side_data_name(sd->type), "unknown");
239 }
240 
241 static const char *get_frame_side_data_type(const void *data)
242 {
243  const AVFrameSideData *sd = (const AVFrameSideData *)data;
244  return av_x_if_null(av_frame_side_data_name(sd->type), "unknown");
245 }
246 
247 static struct section sections[] = {
249  [SECTION_ID_CHAPTER] = { SECTION_ID_CHAPTER, "chapter", 0, { SECTION_ID_CHAPTER_TAGS, -1 } },
250  [SECTION_ID_CHAPTER_TAGS] = { SECTION_ID_CHAPTER_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "chapter_tags" },
251  [SECTION_ID_ERROR] = { SECTION_ID_ERROR, "error", 0, { -1 } },
252  [SECTION_ID_FORMAT] = { SECTION_ID_FORMAT, "format", 0, { SECTION_ID_FORMAT_TAGS, -1 } },
253  [SECTION_ID_FORMAT_TAGS] = { SECTION_ID_FORMAT_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "format_tags" },
256  [SECTION_ID_FRAME_TAGS] = { SECTION_ID_FRAME_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "frame_tags" },
257  [SECTION_ID_FRAME_SIDE_DATA_LIST] ={ SECTION_ID_FRAME_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_FRAME_SIDE_DATA, -1 }, .element_name = "side_data", .unique_name = "frame_side_data_list" },
266  [SECTION_ID_FRAME_LOG] = { SECTION_ID_FRAME_LOG, "log", 0, { -1 }, },
268  [SECTION_ID_LIBRARY_VERSION] = { SECTION_ID_LIBRARY_VERSION, "library_version", 0, { -1 } },
272  [SECTION_ID_PACKET_TAGS] = { SECTION_ID_PACKET_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "packet_tags" },
273  [SECTION_ID_PACKET_SIDE_DATA_LIST] ={ SECTION_ID_PACKET_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PACKET_SIDE_DATA, -1 }, .element_name = "side_data", .unique_name = "packet_side_data_list" },
274  [SECTION_ID_PACKET_SIDE_DATA] = { SECTION_ID_PACKET_SIDE_DATA, "side_data", SECTION_FLAG_HAS_VARIABLE_FIELDS|SECTION_FLAG_HAS_TYPE, { -1 }, .unique_name = "packet_side_data", .element_name = "side_datum", .get_type = get_packet_side_data_type },
277  [SECTION_ID_PIXEL_FORMAT_FLAGS] = { SECTION_ID_PIXEL_FORMAT_FLAGS, "flags", 0, { -1 }, .unique_name = "pixel_format_flags" },
278  [SECTION_ID_PIXEL_FORMAT_COMPONENTS] = { SECTION_ID_PIXEL_FORMAT_COMPONENTS, "components", SECTION_FLAG_IS_ARRAY, {SECTION_ID_PIXEL_FORMAT_COMPONENT, -1 }, .unique_name = "pixel_format_components" },
280  [SECTION_ID_PROGRAM_STREAM_DISPOSITION] = { SECTION_ID_PROGRAM_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "program_stream_disposition" },
281  [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" },
283  [SECTION_ID_PROGRAM_STREAMS] = { SECTION_ID_PROGRAM_STREAMS, "streams", SECTION_FLAG_IS_ARRAY, { SECTION_ID_PROGRAM_STREAM, -1 }, .unique_name = "program_streams" },
285  [SECTION_ID_PROGRAM_TAGS] = { SECTION_ID_PROGRAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "program_tags" },
286  [SECTION_ID_PROGRAM_VERSION] = { SECTION_ID_PROGRAM_VERSION, "program_version", 0, { -1 } },
294  [SECTION_ID_STREAM_DISPOSITION] = { SECTION_ID_STREAM_DISPOSITION, "disposition", 0, { -1 }, .unique_name = "stream_disposition" },
295  [SECTION_ID_STREAM_TAGS] = { SECTION_ID_STREAM_TAGS, "tags", SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .element_name = "tag", .unique_name = "stream_tags" },
296  [SECTION_ID_STREAM_SIDE_DATA_LIST] ={ SECTION_ID_STREAM_SIDE_DATA_LIST, "side_data_list", SECTION_FLAG_IS_ARRAY, { SECTION_ID_STREAM_SIDE_DATA, -1 }, .element_name = "side_data", .unique_name = "stream_side_data_list" },
297  [SECTION_ID_STREAM_SIDE_DATA] = { SECTION_ID_STREAM_SIDE_DATA, "side_data", SECTION_FLAG_HAS_TYPE|SECTION_FLAG_HAS_VARIABLE_FIELDS, { -1 }, .unique_name = "stream_side_data", .element_name = "side_datum", .get_type = get_packet_side_data_type },
298  [SECTION_ID_SUBTITLE] = { SECTION_ID_SUBTITLE, "subtitle", 0, { -1 } },
299 };
300 
301 static const OptionDef *options;
302 
303 /* FFprobe context */
304 static const char *input_filename;
305 static const char *print_input_filename;
306 static const AVInputFormat *iformat = NULL;
307 static const char *output_filename = NULL;
308 
309 static struct AVHashContext *hash;
310 
311 static const struct {
312  double bin_val;
313  double dec_val;
314  const char *bin_str;
315  const char *dec_str;
316 } si_prefixes[] = {
317  { 1.0, 1.0, "", "" },
318  { 1.024e3, 1e3, "Ki", "K" },
319  { 1.048576e6, 1e6, "Mi", "M" },
320  { 1.073741824e9, 1e9, "Gi", "G" },
321  { 1.099511627776e12, 1e12, "Ti", "T" },
322  { 1.125899906842624e15, 1e15, "Pi", "P" },
323 };
324 
325 static const char unit_second_str[] = "s" ;
326 static const char unit_hertz_str[] = "Hz" ;
327 static const char unit_byte_str[] = "byte" ;
328 static const char unit_bit_per_second_str[] = "bit/s";
329 
330 static int nb_streams;
331 static uint64_t *nb_streams_packets;
332 static uint64_t *nb_streams_frames;
333 static int *selected_streams;
334 
335 #if HAVE_THREADS
336 pthread_mutex_t log_mutex;
337 #endif
338 typedef struct LogBuffer {
341  char *log_message;
343  char *parent_name;
345 }LogBuffer;
346 
348 static int log_buffer_size;
349 
350 static void log_callback(void *ptr, int level, const char *fmt, va_list vl)
351 {
352  AVClass* avc = ptr ? *(AVClass **) ptr : NULL;
353  va_list vl2;
354  char line[1024];
355  static int print_prefix = 1;
356  void *new_log_buffer;
357 
358  va_copy(vl2, vl);
359  av_log_default_callback(ptr, level, fmt, vl);
360  av_log_format_line(ptr, level, fmt, vl2, line, sizeof(line), &print_prefix);
361  va_end(vl2);
362 
363 #if HAVE_THREADS
364  pthread_mutex_lock(&log_mutex);
365 
366  new_log_buffer = av_realloc_array(log_buffer, log_buffer_size + 1, sizeof(*log_buffer));
367  if (new_log_buffer) {
368  char *msg;
369  int i;
370 
371  log_buffer = new_log_buffer;
372  memset(&log_buffer[log_buffer_size], 0, sizeof(log_buffer[log_buffer_size]));
374  if (avc) {
377  }
380  for (i=strlen(msg) - 1; i>=0 && msg[i] == '\n'; i--) {
381  msg[i] = 0;
382  }
383  if (avc && avc->parent_log_context_offset) {
384  AVClass** parent = *(AVClass ***) (((uint8_t *) ptr) +
386  if (parent && *parent) {
387  log_buffer[log_buffer_size].parent_name = av_strdup((*parent)->item_name(parent));
389  (*parent)->get_category ? (*parent)->get_category(parent) :(*parent)->category;
390  }
391  }
392  log_buffer_size ++;
393  }
394 
395  pthread_mutex_unlock(&log_mutex);
396 #endif
397 }
398 
399 struct unit_value {
400  union { double d; int64_t i; } val;
401  const char *unit;
402 };
403 
404 static char *value_string(char *buf, int buf_size, struct unit_value uv)
405 {
406  double vald;
407  int64_t vali;
408  int show_float = 0;
409 
410  if (uv.unit == unit_second_str) {
411  vald = uv.val.d;
412  show_float = 1;
413  } else {
414  vald = vali = uv.val.i;
415  }
416 
418  double secs;
419  int hours, mins;
420  secs = vald;
421  mins = (int)secs / 60;
422  secs = secs - mins * 60;
423  hours = mins / 60;
424  mins %= 60;
425  snprintf(buf, buf_size, "%d:%02d:%09.6f", hours, mins, secs);
426  } else {
427  const char *prefix_string = "";
428 
429  if (use_value_prefix && vald > 1) {
430  int64_t index;
431 
433  index = (int64_t) (log2(vald)) / 10;
435  vald /= si_prefixes[index].bin_val;
436  prefix_string = si_prefixes[index].bin_str;
437  } else {
438  index = (int64_t) (log10(vald)) / 3;
440  vald /= si_prefixes[index].dec_val;
441  prefix_string = si_prefixes[index].dec_str;
442  }
443  vali = vald;
444  }
445 
446  if (show_float || (use_value_prefix && vald != (int64_t)vald))
447  snprintf(buf, buf_size, "%f", vald);
448  else
449  snprintf(buf, buf_size, "%"PRId64, vali);
450  av_strlcatf(buf, buf_size, "%s%s%s", *prefix_string || show_value_unit ? " " : "",
451  prefix_string, show_value_unit ? uv.unit : "");
452  }
453 
454  return buf;
455 }
456 
457 /* WRITERS API */
458 
459 typedef struct WriterContext WriterContext;
460 
461 #define WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS 1
462 #define WRITER_FLAG_PUT_PACKETS_AND_FRAMES_IN_SAME_CHAPTER 2
463 
464 typedef enum {
470 
471 typedef struct Writer {
472  const AVClass *priv_class; ///< private class of the writer, if any
473  int priv_size; ///< private size for the writer context
474  const char *name;
475 
476  int (*init) (WriterContext *wctx);
477  void (*uninit)(WriterContext *wctx);
478 
479  void (*print_section_header)(WriterContext *wctx, const void *data);
481  void (*print_integer) (WriterContext *wctx, const char *, int64_t);
482  void (*print_rational) (WriterContext *wctx, AVRational *q, char *sep);
483  void (*print_string) (WriterContext *wctx, const char *, const char *);
484  int flags; ///< a combination or WRITER_FLAG_*
485 } Writer;
486 
487 #define SECTION_MAX_NB_LEVELS 10
488 
490  const AVClass *class; ///< class of the writer
491  const Writer *writer; ///< the Writer of which this is an instance
492  AVIOContext *avio; ///< the I/O context used to write
493 
494  void (* writer_w8)(WriterContext *wctx, int b);
495  void (* writer_put_str)(WriterContext *wctx, const char *str);
496  void (* writer_printf)(WriterContext *wctx, const char *fmt, ...);
497 
498  char *name; ///< name of this writer instance
499  void *priv; ///< private data for use by the filter
500 
501  const struct section *sections; ///< array containing all sections
502  int nb_sections; ///< number of sections
503 
504  int level; ///< current level, starting from 0
505 
506  /** number of the item printed in the given section, starting from 0 */
508 
509  /** section per each level */
511  AVBPrint section_pbuf[SECTION_MAX_NB_LEVELS]; ///< generic print buffer dedicated to each section,
512  /// used by various writers
513 
514  unsigned int nb_section_packet; ///< number of the packet section in case we are in "packets_and_frames" section
515  unsigned int nb_section_frame; ///< number of the frame section in case we are in "packets_and_frames" section
516  unsigned int nb_section_packet_frame; ///< nb_section_packet or nb_section_frame according if is_packets_and_frames
517 
521 };
522 
523 static const char *writer_get_name(void *p)
524 {
525  WriterContext *wctx = p;
526  return wctx->writer->name;
527 }
528 
529 #define OFFSET(x) offsetof(WriterContext, x)
530 
531 static const AVOption writer_options[] = {
532  { "string_validation", "set string validation mode",
533  OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
534  { "sv", "set string validation mode",
535  OFFSET(string_validation), AV_OPT_TYPE_INT, {.i64=WRITER_STRING_VALIDATION_REPLACE}, 0, WRITER_STRING_VALIDATION_NB-1, .unit = "sv" },
536  { "ignore", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_IGNORE}, .unit = "sv" },
537  { "replace", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_REPLACE}, .unit = "sv" },
538  { "fail", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = WRITER_STRING_VALIDATION_FAIL}, .unit = "sv" },
539  { "string_validation_replacement", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str=""}},
540  { "svr", "set string validation replacement string", OFFSET(string_validation_replacement), AV_OPT_TYPE_STRING, {.str="\xEF\xBF\xBD"}},
541  { NULL }
542 };
543 
544 static void *writer_child_next(void *obj, void *prev)
545 {
546  WriterContext *ctx = obj;
547  if (!prev && ctx->writer && ctx->writer->priv_class && ctx->priv)
548  return ctx->priv;
549  return NULL;
550 }
551 
552 static const AVClass writer_class = {
553  .class_name = "Writer",
554  .item_name = writer_get_name,
555  .option = writer_options,
556  .version = LIBAVUTIL_VERSION_INT,
557  .child_next = writer_child_next,
558 };
559 
560 static int writer_close(WriterContext **wctx)
561 {
562  int i;
563  int ret = 0;
564 
565  if (!*wctx)
566  return -1;
567 
568  if ((*wctx)->writer->uninit)
569  (*wctx)->writer->uninit(*wctx);
570  for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
571  av_bprint_finalize(&(*wctx)->section_pbuf[i], NULL);
572  if ((*wctx)->writer->priv_class)
573  av_opt_free((*wctx)->priv);
574  av_freep(&((*wctx)->priv));
575  av_opt_free(*wctx);
576  if ((*wctx)->avio) {
577  avio_flush((*wctx)->avio);
578  ret = avio_close((*wctx)->avio);
579  }
580  av_freep(wctx);
581  return ret;
582 }
583 
584 static void bprint_bytes(AVBPrint *bp, const uint8_t *ubuf, size_t ubuf_size)
585 {
586  int i;
587  av_bprintf(bp, "0X");
588  for (i = 0; i < ubuf_size; i++)
589  av_bprintf(bp, "%02X", ubuf[i]);
590 }
591 
592 static inline void writer_w8_avio(WriterContext *wctx, int b)
593 {
594  avio_w8(wctx->avio, b);
595 }
596 
597 static inline void writer_put_str_avio(WriterContext *wctx, const char *str)
598 {
599  avio_write(wctx->avio, str, strlen(str));
600 }
601 
602 static inline void writer_printf_avio(WriterContext *wctx, const char *fmt, ...)
603 {
604  va_list ap;
605 
606  va_start(ap, fmt);
607  avio_vprintf(wctx->avio, fmt, ap);
608  va_end(ap);
609 }
610 
611 static inline void writer_w8_printf(WriterContext *wctx, int b)
612 {
613  printf("%c", b);
614 }
615 
616 static inline void writer_put_str_printf(WriterContext *wctx, const char *str)
617 {
618  printf("%s", str);
619 }
620 
621 static inline void writer_printf_printf(WriterContext *wctx, const char *fmt, ...)
622 {
623  va_list ap;
624 
625  va_start(ap, fmt);
626  vprintf(fmt, ap);
627  va_end(ap);
628 }
629 
630 static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,
631  const struct section *sections, int nb_sections, const char *output)
632 {
633  int i, ret = 0;
634 
635  if (!(*wctx = av_mallocz(sizeof(WriterContext)))) {
636  ret = AVERROR(ENOMEM);
637  goto fail;
638  }
639 
640  if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {
641  ret = AVERROR(ENOMEM);
642  goto fail;
643  }
644 
645  (*wctx)->class = &writer_class;
646  (*wctx)->writer = writer;
647  (*wctx)->level = -1;
648  (*wctx)->sections = sections;
649  (*wctx)->nb_sections = nb_sections;
650 
651  av_opt_set_defaults(*wctx);
652 
653  if (writer->priv_class) {
654  void *priv_ctx = (*wctx)->priv;
655  *((const AVClass **)priv_ctx) = writer->priv_class;
656  av_opt_set_defaults(priv_ctx);
657  }
658 
659  /* convert options to dictionary */
660  if (args) {
662  const AVDictionaryEntry *opt = NULL;
663 
664  if ((ret = av_dict_parse_string(&opts, args, "=", ":", 0)) < 0) {
665  av_log(*wctx, AV_LOG_ERROR, "Failed to parse option string '%s' provided to writer context\n", args);
666  av_dict_free(&opts);
667  goto fail;
668  }
669 
670  while ((opt = av_dict_iterate(opts, opt))) {
671  if ((ret = av_opt_set(*wctx, opt->key, opt->value, AV_OPT_SEARCH_CHILDREN)) < 0) {
672  av_log(*wctx, AV_LOG_ERROR, "Failed to set option '%s' with value '%s' provided to writer context\n",
673  opt->key, opt->value);
674  av_dict_free(&opts);
675  goto fail;
676  }
677  }
678 
679  av_dict_free(&opts);
680  }
681 
682  /* validate replace string */
683  {
684  const uint8_t *p = (*wctx)->string_validation_replacement;
685  const uint8_t *endp = p + strlen(p);
686  while (*p) {
687  const uint8_t *p0 = p;
688  int32_t code;
689  ret = av_utf8_decode(&code, &p, endp, (*wctx)->string_validation_utf8_flags);
690  if (ret < 0) {
691  AVBPrint bp;
693  bprint_bytes(&bp, p0, p-p0),
694  av_log(wctx, AV_LOG_ERROR,
695  "Invalid UTF8 sequence %s found in string validation replace '%s'\n",
696  bp.str, (*wctx)->string_validation_replacement);
697  return ret;
698  }
699  }
700  }
701 
702  if (!output_filename) {
703  (*wctx)->writer_w8 = writer_w8_printf;
704  (*wctx)->writer_put_str = writer_put_str_printf;
705  (*wctx)->writer_printf = writer_printf_printf;
706  } else {
707  if ((ret = avio_open(&(*wctx)->avio, output, AVIO_FLAG_WRITE)) < 0) {
708  av_log(*wctx, AV_LOG_ERROR,
709  "Failed to open output '%s' with error: %s\n", output, av_err2str(ret));
710  goto fail;
711  }
712  (*wctx)->writer_w8 = writer_w8_avio;
713  (*wctx)->writer_put_str = writer_put_str_avio;
714  (*wctx)->writer_printf = writer_printf_avio;
715  }
716 
717  for (i = 0; i < SECTION_MAX_NB_LEVELS; i++)
718  av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);
719 
720  if ((*wctx)->writer->init)
721  ret = (*wctx)->writer->init(*wctx);
722  if (ret < 0)
723  goto fail;
724 
725  return 0;
726 
727 fail:
728  writer_close(wctx);
729  return ret;
730 }
731 
733  const void *data,
734  int section_id)
735 {
736  int parent_section_id;
737  wctx->level++;
739  parent_section_id = wctx->level ?
740  (wctx->section[wctx->level-1])->id : SECTION_ID_NONE;
741 
742  wctx->nb_item[wctx->level] = 0;
743  wctx->section[wctx->level] = &wctx->sections[section_id];
744 
745  if (section_id == SECTION_ID_PACKETS_AND_FRAMES) {
746  wctx->nb_section_packet = wctx->nb_section_frame =
747  wctx->nb_section_packet_frame = 0;
748  } else if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
749  wctx->nb_section_packet_frame = section_id == SECTION_ID_PACKET ?
750  wctx->nb_section_packet : wctx->nb_section_frame;
751  }
752 
753  if (wctx->writer->print_section_header)
754  wctx->writer->print_section_header(wctx, data);
755 }
756 
758 {
759  int section_id = wctx->section[wctx->level]->id;
760  int parent_section_id = wctx->level ?
761  wctx->section[wctx->level-1]->id : SECTION_ID_NONE;
762 
763  if (parent_section_id != SECTION_ID_NONE)
764  wctx->nb_item[wctx->level-1]++;
765  if (parent_section_id == SECTION_ID_PACKETS_AND_FRAMES) {
766  if (section_id == SECTION_ID_PACKET) wctx->nb_section_packet++;
767  else wctx->nb_section_frame++;
768  }
769  if (wctx->writer->print_section_footer)
770  wctx->writer->print_section_footer(wctx);
771  wctx->level--;
772 }
773 
774 static inline void writer_print_integer(WriterContext *wctx,
775  const char *key, int64_t val)
776 {
777  const struct section *section = wctx->section[wctx->level];
778 
780  wctx->writer->print_integer(wctx, key, val);
781  wctx->nb_item[wctx->level]++;
782  }
783 }
784 
785 static inline int validate_string(WriterContext *wctx, char **dstp, const char *src)
786 {
787  const uint8_t *p, *endp;
788  AVBPrint dstbuf;
789  int invalid_chars_nb = 0, ret = 0;
790 
792 
793  endp = src + strlen(src);
794  for (p = src; *p;) {
795  uint32_t code;
796  int invalid = 0;
797  const uint8_t *p0 = p;
798 
799  if (av_utf8_decode(&code, &p, endp, wctx->string_validation_utf8_flags) < 0) {
800  AVBPrint bp;
802  bprint_bytes(&bp, p0, p-p0);
803  av_log(wctx, AV_LOG_DEBUG,
804  "Invalid UTF-8 sequence %s found in string '%s'\n", bp.str, src);
805  invalid = 1;
806  }
807 
808  if (invalid) {
809  invalid_chars_nb++;
810 
811  switch (wctx->string_validation) {
813  av_log(wctx, AV_LOG_ERROR,
814  "Invalid UTF-8 sequence found in string '%s'\n", src);
816  goto end;
817  break;
818 
820  av_bprintf(&dstbuf, "%s", wctx->string_validation_replacement);
821  break;
822  }
823  }
824 
825  if (!invalid || wctx->string_validation == WRITER_STRING_VALIDATION_IGNORE)
826  av_bprint_append_data(&dstbuf, p0, p-p0);
827  }
828 
829  if (invalid_chars_nb && wctx->string_validation == WRITER_STRING_VALIDATION_REPLACE) {
830  av_log(wctx, AV_LOG_WARNING,
831  "%d invalid UTF-8 sequence(s) found in string '%s', replaced with '%s'\n",
832  invalid_chars_nb, src, wctx->string_validation_replacement);
833  }
834 
835 end:
836  av_bprint_finalize(&dstbuf, dstp);
837  return ret;
838 }
839 
840 #define PRINT_STRING_OPT 1
841 #define PRINT_STRING_VALIDATE 2
842 
843 static inline int writer_print_string(WriterContext *wctx,
844  const char *key, const char *val, int flags)
845 {
846  const struct section *section = wctx->section[wctx->level];
847  int ret = 0;
848 
851  && (flags & PRINT_STRING_OPT)
853  return 0;
854 
857  char *key1 = NULL, *val1 = NULL;
858  ret = validate_string(wctx, &key1, key);
859  if (ret < 0) goto end;
860  ret = validate_string(wctx, &val1, val);
861  if (ret < 0) goto end;
862  wctx->writer->print_string(wctx, key1, val1);
863  end:
864  if (ret < 0) {
865  av_log(wctx, AV_LOG_ERROR,
866  "Invalid key=value string combination %s=%s in section %s\n",
868  }
869  av_free(key1);
870  av_free(val1);
871  } else {
872  wctx->writer->print_string(wctx, key, val);
873  }
874 
875  wctx->nb_item[wctx->level]++;
876  }
877 
878  return ret;
879 }
880 
881 static inline void writer_print_rational(WriterContext *wctx,
882  const char *key, AVRational q, char sep)
883 {
884  AVBPrint buf;
886  av_bprintf(&buf, "%d%c%d", q.num, sep, q.den);
887  writer_print_string(wctx, key, buf.str, 0);
888 }
889 
890 static void writer_print_time(WriterContext *wctx, const char *key,
891  int64_t ts, const AVRational *time_base, int is_duration)
892 {
893  char buf[128];
894 
895  if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
897  } else {
898  double d = ts * av_q2d(*time_base);
899  struct unit_value uv;
900  uv.val.d = d;
901  uv.unit = unit_second_str;
902  value_string(buf, sizeof(buf), uv);
903  writer_print_string(wctx, key, buf, 0);
904  }
905 }
906 
907 static void writer_print_ts(WriterContext *wctx, const char *key, int64_t ts, int is_duration)
908 {
909  if ((!is_duration && ts == AV_NOPTS_VALUE) || (is_duration && ts == 0)) {
911  } else {
912  writer_print_integer(wctx, key, ts);
913  }
914 }
915 
916 static void writer_print_data(WriterContext *wctx, const char *name,
917  const uint8_t *data, int size)
918 {
919  AVBPrint bp;
920  int offset = 0, l, i;
921 
923  av_bprintf(&bp, "\n");
924  while (size) {
925  av_bprintf(&bp, "%08x: ", offset);
926  l = FFMIN(size, 16);
927  for (i = 0; i < l; i++) {
928  av_bprintf(&bp, "%02x", data[i]);
929  if (i & 1)
930  av_bprintf(&bp, " ");
931  }
932  av_bprint_chars(&bp, ' ', 41 - 2 * i - i / 2);
933  for (i = 0; i < l; i++)
934  av_bprint_chars(&bp, data[i] - 32U < 95 ? data[i] : '.', 1);
935  av_bprintf(&bp, "\n");
936  offset += l;
937  data += l;
938  size -= l;
939  }
940  writer_print_string(wctx, name, bp.str, 0);
941  av_bprint_finalize(&bp, NULL);
942 }
943 
944 static void writer_print_data_hash(WriterContext *wctx, const char *name,
945  const uint8_t *data, int size)
946 {
947  char *p, buf[AV_HASH_MAX_SIZE * 2 + 64] = { 0 };
948 
949  if (!hash)
950  return;
953  snprintf(buf, sizeof(buf), "%s:", av_hash_get_name(hash));
954  p = buf + strlen(buf);
955  av_hash_final_hex(hash, p, buf + sizeof(buf) - p);
956  writer_print_string(wctx, name, buf, 0);
957 }
958 
959 static void writer_print_integers(WriterContext *wctx, const char *name,
960  uint8_t *data, int size, const char *format,
961  int columns, int bytes, int offset_add)
962 {
963  AVBPrint bp;
964  int offset = 0, l, i;
965 
967  av_bprintf(&bp, "\n");
968  while (size) {
969  av_bprintf(&bp, "%08x: ", offset);
970  l = FFMIN(size, columns);
971  for (i = 0; i < l; i++) {
972  if (bytes == 1) av_bprintf(&bp, format, *data);
973  else if (bytes == 2) av_bprintf(&bp, format, AV_RN16(data));
974  else if (bytes == 4) av_bprintf(&bp, format, AV_RN32(data));
975  data += bytes;
976  size --;
977  }
978  av_bprintf(&bp, "\n");
979  offset += offset_add;
980  }
981  writer_print_string(wctx, name, bp.str, 0);
982  av_bprint_finalize(&bp, NULL);
983 }
984 
985 #define writer_w8(wctx_, b_) (wctx_)->writer_w8(wctx_, b_)
986 #define writer_put_str(wctx_, str_) (wctx_)->writer_put_str(wctx_, str_)
987 #define writer_printf(wctx_, fmt_, ...) (wctx_)->writer_printf(wctx_, fmt_, __VA_ARGS__)
988 
989 #define MAX_REGISTERED_WRITERS_NB 64
990 
992 
993 static int writer_register(const Writer *writer)
994 {
995  static int next_registered_writer_idx = 0;
996 
997  if (next_registered_writer_idx == MAX_REGISTERED_WRITERS_NB)
998  return AVERROR(ENOMEM);
999 
1000  registered_writers[next_registered_writer_idx++] = writer;
1001  return 0;
1002 }
1003 
1004 static const Writer *writer_get_by_name(const char *name)
1005 {
1006  int i;
1007 
1008  for (i = 0; registered_writers[i]; i++)
1009  if (!strcmp(registered_writers[i]->name, name))
1010  return registered_writers[i];
1011 
1012  return NULL;
1013 }
1014 
1015 
1016 /* WRITERS */
1017 
1018 #define DEFINE_WRITER_CLASS(name) \
1019 static const char *name##_get_name(void *ctx) \
1020 { \
1021  return #name ; \
1022 } \
1023 static const AVClass name##_class = { \
1024  .class_name = #name, \
1025  .item_name = name##_get_name, \
1026  .option = name##_options \
1027 }
1028 
1029 /* Default output */
1030 
1031 typedef struct DefaultContext {
1032  const AVClass *class;
1033  int nokey;
1036 } DefaultContext;
1037 
1038 #undef OFFSET
1039 #define OFFSET(x) offsetof(DefaultContext, x)
1040 
1041 static const AVOption default_options[] = {
1042  { "noprint_wrappers", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1043  { "nw", "do not print headers and footers", OFFSET(noprint_wrappers), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1044  { "nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1045  { "nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1046  {NULL},
1047 };
1048 
1049 DEFINE_WRITER_CLASS(default);
1050 
1051 /* lame uppercasing routine, assumes the string is lower case ASCII */
1052 static inline char *upcase_string(char *dst, size_t dst_size, const char *src)
1053 {
1054  int i;
1055  for (i = 0; src[i] && i < dst_size-1; i++)
1056  dst[i] = av_toupper(src[i]);
1057  dst[i] = 0;
1058  return dst;
1059 }
1060 
1061 static void default_print_section_header(WriterContext *wctx, const void *data)
1062 {
1063  DefaultContext *def = wctx->priv;
1064  char buf[32];
1065  const struct section *section = wctx->section[wctx->level];
1066  const struct section *parent_section = wctx->level ?
1067  wctx->section[wctx->level-1] : NULL;
1068 
1069  av_bprint_clear(&wctx->section_pbuf[wctx->level]);
1070  if (parent_section &&
1071  !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))) {
1072  def->nested_section[wctx->level] = 1;
1073  av_bprintf(&wctx->section_pbuf[wctx->level], "%s%s:",
1074  wctx->section_pbuf[wctx->level-1].str,
1075  upcase_string(buf, sizeof(buf),
1077  }
1078 
1079  if (def->noprint_wrappers || def->nested_section[wctx->level])
1080  return;
1081 
1083  writer_printf(wctx, "[%s]\n", upcase_string(buf, sizeof(buf), section->name));
1084 }
1085 
1087 {
1088  DefaultContext *def = wctx->priv;
1089  const struct section *section = wctx->section[wctx->level];
1090  char buf[32];
1091 
1092  if (def->noprint_wrappers || def->nested_section[wctx->level])
1093  return;
1094 
1096  writer_printf(wctx, "[/%s]\n", upcase_string(buf, sizeof(buf), section->name));
1097 }
1098 
1099 static void default_print_str(WriterContext *wctx, const char *key, const char *value)
1100 {
1101  DefaultContext *def = wctx->priv;
1102 
1103  if (!def->nokey)
1104  writer_printf(wctx, "%s%s=", wctx->section_pbuf[wctx->level].str, key);
1105  writer_printf(wctx, "%s\n", value);
1106 }
1107 
1108 static void default_print_int(WriterContext *wctx, const char *key, int64_t value)
1109 {
1110  DefaultContext *def = wctx->priv;
1111 
1112  if (!def->nokey)
1113  writer_printf(wctx, "%s%s=", wctx->section_pbuf[wctx->level].str, key);
1114  writer_printf(wctx, "%"PRId64"\n", value);
1115 }
1116 
1117 static const Writer default_writer = {
1118  .name = "default",
1119  .priv_size = sizeof(DefaultContext),
1122  .print_integer = default_print_int,
1123  .print_string = default_print_str,
1125  .priv_class = &default_class,
1126 };
1127 
1128 /* Compact output */
1129 
1130 /**
1131  * Apply C-language-like string escaping.
1132  */
1133 static const char *c_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
1134 {
1135  const char *p;
1136 
1137  for (p = src; *p; p++) {
1138  switch (*p) {
1139  case '\b': av_bprintf(dst, "%s", "\\b"); break;
1140  case '\f': av_bprintf(dst, "%s", "\\f"); break;
1141  case '\n': av_bprintf(dst, "%s", "\\n"); break;
1142  case '\r': av_bprintf(dst, "%s", "\\r"); break;
1143  case '\\': av_bprintf(dst, "%s", "\\\\"); break;
1144  default:
1145  if (*p == sep)
1146  av_bprint_chars(dst, '\\', 1);
1147  av_bprint_chars(dst, *p, 1);
1148  }
1149  }
1150  return dst->str;
1151 }
1152 
1153 /**
1154  * Quote fields containing special characters, check RFC4180.
1155  */
1156 static const char *csv_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
1157 {
1158  char meta_chars[] = { sep, '"', '\n', '\r', '\0' };
1159  int needs_quoting = !!src[strcspn(src, meta_chars)];
1160 
1161  if (needs_quoting)
1162  av_bprint_chars(dst, '"', 1);
1163 
1164  for (; *src; src++) {
1165  if (*src == '"')
1166  av_bprint_chars(dst, '"', 1);
1167  av_bprint_chars(dst, *src, 1);
1168  }
1169  if (needs_quoting)
1170  av_bprint_chars(dst, '"', 1);
1171  return dst->str;
1172 }
1173 
1174 static const char *none_escape_str(AVBPrint *dst, const char *src, const char sep, void *log_ctx)
1175 {
1176  return src;
1177 }
1178 
1179 typedef struct CompactContext {
1180  const AVClass *class;
1182  char item_sep;
1183  int nokey;
1186  const char * (*escape_str)(AVBPrint *dst, const char *src, const char sep, void *log_ctx);
1190 } CompactContext;
1191 
1192 #undef OFFSET
1193 #define OFFSET(x) offsetof(CompactContext, x)
1194 
1195 static const AVOption compact_options[]= {
1196  {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, 0, 0 },
1197  {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str="|"}, 0, 0 },
1198  {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1199  {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1200  {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, 0, 0 },
1201  {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="c"}, 0, 0 },
1202  {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1203  {"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1204  {NULL},
1205 };
1206 
1207 DEFINE_WRITER_CLASS(compact);
1208 
1210 {
1211  CompactContext *compact = wctx->priv;
1212 
1213  if (strlen(compact->item_sep_str) != 1) {
1214  av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
1215  compact->item_sep_str);
1216  return AVERROR(EINVAL);
1217  }
1218  compact->item_sep = compact->item_sep_str[0];
1219 
1220  if (!strcmp(compact->escape_mode_str, "none")) compact->escape_str = none_escape_str;
1221  else if (!strcmp(compact->escape_mode_str, "c" )) compact->escape_str = c_escape_str;
1222  else if (!strcmp(compact->escape_mode_str, "csv" )) compact->escape_str = csv_escape_str;
1223  else {
1224  av_log(wctx, AV_LOG_ERROR, "Unknown escape mode '%s'\n", compact->escape_mode_str);
1225  return AVERROR(EINVAL);
1226  }
1227 
1228  return 0;
1229 }
1230 
1231 static void compact_print_section_header(WriterContext *wctx, const void *data)
1232 {
1233  CompactContext *compact = wctx->priv;
1234  const struct section *section = wctx->section[wctx->level];
1235  const struct section *parent_section = wctx->level ?
1236  wctx->section[wctx->level-1] : NULL;
1237  compact->terminate_line[wctx->level] = 1;
1238  compact->has_nested_elems[wctx->level] = 0;
1239 
1240  av_bprint_clear(&wctx->section_pbuf[wctx->level]);
1241  if (parent_section &&
1244  !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY))))) {
1245 
1246  /* define a prefix for elements not contained in an array or
1247  in a wrapper, or for array elements with a type */
1248  const char *element_name = (char *)av_x_if_null(section->element_name, section->name);
1249  AVBPrint *section_pbuf = &wctx->section_pbuf[wctx->level];
1250 
1251  compact->nested_section[wctx->level] = 1;
1252  compact->has_nested_elems[wctx->level-1] = 1;
1253 
1254  av_bprintf(section_pbuf, "%s%s",
1255  wctx->section_pbuf[wctx->level-1].str, element_name);
1256 
1258  // add /TYPE to prefix
1259  av_bprint_chars(section_pbuf, '/', 1);
1260 
1261  // normalize section type, replace special characters and lower case
1262  for (const char *p = section->get_type(data); *p; p++) {
1263  char c =
1264  (*p >= '0' && *p <= '9') ||
1265  (*p >= 'a' && *p <= 'z') ||
1266  (*p >= 'A' && *p <= 'Z') ? av_tolower(*p) : '_';
1267  av_bprint_chars(section_pbuf, c, 1);
1268  }
1269  }
1270  av_bprint_chars(section_pbuf, ':', 1);
1271 
1272  wctx->nb_item[wctx->level] = wctx->nb_item[wctx->level-1];
1273  } else {
1274  if (parent_section && !(parent_section->flags & (SECTION_FLAG_IS_WRAPPER|SECTION_FLAG_IS_ARRAY)) &&
1275  wctx->level && wctx->nb_item[wctx->level-1])
1276  writer_w8(wctx, compact->item_sep);
1277  if (compact->print_section &&
1279  writer_printf(wctx, "%s%c", section->name, compact->item_sep);
1280  }
1281 }
1282 
1284 {
1285  CompactContext *compact = wctx->priv;
1286 
1287  if (!compact->nested_section[wctx->level] &&
1288  compact->terminate_line[wctx->level] &&
1290  writer_w8(wctx, '\n');
1291 }
1292 
1293 static void compact_print_str(WriterContext *wctx, const char *key, const char *value)
1294 {
1295  CompactContext *compact = wctx->priv;
1296  AVBPrint buf;
1297 
1298  if (wctx->nb_item[wctx->level]) writer_w8(wctx, compact->item_sep);
1299  if (!compact->nokey)
1300  writer_printf(wctx, "%s%s=", wctx->section_pbuf[wctx->level].str, key);
1302  writer_put_str(wctx, compact->escape_str(&buf, value, compact->item_sep, wctx));
1303  av_bprint_finalize(&buf, NULL);
1304 }
1305 
1306 static void compact_print_int(WriterContext *wctx, const char *key, int64_t value)
1307 {
1308  CompactContext *compact = wctx->priv;
1309 
1310  if (wctx->nb_item[wctx->level]) writer_w8(wctx, compact->item_sep);
1311  if (!compact->nokey)
1312  writer_printf(wctx, "%s%s=", wctx->section_pbuf[wctx->level].str, key);
1313  writer_printf(wctx, "%"PRId64, value);
1314 }
1315 
1316 static const Writer compact_writer = {
1317  .name = "compact",
1318  .priv_size = sizeof(CompactContext),
1319  .init = compact_init,
1322  .print_integer = compact_print_int,
1323  .print_string = compact_print_str,
1325  .priv_class = &compact_class,
1326 };
1327 
1328 /* CSV output */
1329 
1330 #undef OFFSET
1331 #define OFFSET(x) offsetof(CompactContext, x)
1332 
1333 static const AVOption csv_options[] = {
1334  {"item_sep", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, 0, 0 },
1335  {"s", "set item separator", OFFSET(item_sep_str), AV_OPT_TYPE_STRING, {.str=","}, 0, 0 },
1336  {"nokey", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1337  {"nk", "force no key printing", OFFSET(nokey), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1338  {"escape", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, 0, 0 },
1339  {"e", "set escape mode", OFFSET(escape_mode_str), AV_OPT_TYPE_STRING, {.str="csv"}, 0, 0 },
1340  {"print_section", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1341  {"p", "print section name", OFFSET(print_section), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1342  {NULL},
1343 };
1344 
1345 DEFINE_WRITER_CLASS(csv);
1346 
1347 static const Writer csv_writer = {
1348  .name = "csv",
1349  .priv_size = sizeof(CompactContext),
1350  .init = compact_init,
1353  .print_integer = compact_print_int,
1354  .print_string = compact_print_str,
1356  .priv_class = &csv_class,
1357 };
1358 
1359 /* Flat output */
1360 
1361 typedef struct FlatContext {
1362  const AVClass *class;
1363  const char *sep_str;
1364  char sep;
1366 } FlatContext;
1367 
1368 #undef OFFSET
1369 #define OFFSET(x) offsetof(FlatContext, x)
1370 
1371 static const AVOption flat_options[]= {
1372  {"sep_char", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, 0, 0 },
1373  {"s", "set separator", OFFSET(sep_str), AV_OPT_TYPE_STRING, {.str="."}, 0, 0 },
1374  {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1375  {"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1376  {NULL},
1377 };
1378 
1380 
1382 {
1383  FlatContext *flat = wctx->priv;
1384 
1385  if (strlen(flat->sep_str) != 1) {
1386  av_log(wctx, AV_LOG_ERROR, "Item separator '%s' specified, but must contain a single character\n",
1387  flat->sep_str);
1388  return AVERROR(EINVAL);
1389  }
1390  flat->sep = flat->sep_str[0];
1391 
1392  return 0;
1393 }
1394 
1395 static const char *flat_escape_key_str(AVBPrint *dst, const char *src, const char sep)
1396 {
1397  const char *p;
1398 
1399  for (p = src; *p; p++) {
1400  if (!((*p >= '0' && *p <= '9') ||
1401  (*p >= 'a' && *p <= 'z') ||
1402  (*p >= 'A' && *p <= 'Z')))
1403  av_bprint_chars(dst, '_', 1);
1404  else
1405  av_bprint_chars(dst, *p, 1);
1406  }
1407  return dst->str;
1408 }
1409 
1410 static const char *flat_escape_value_str(AVBPrint *dst, const char *src)
1411 {
1412  const char *p;
1413 
1414  for (p = src; *p; p++) {
1415  switch (*p) {
1416  case '\n': av_bprintf(dst, "%s", "\\n"); break;
1417  case '\r': av_bprintf(dst, "%s", "\\r"); break;
1418  case '\\': av_bprintf(dst, "%s", "\\\\"); break;
1419  case '"': av_bprintf(dst, "%s", "\\\""); break;
1420  case '`': av_bprintf(dst, "%s", "\\`"); break;
1421  case '$': av_bprintf(dst, "%s", "\\$"); break;
1422  default: av_bprint_chars(dst, *p, 1); break;
1423  }
1424  }
1425  return dst->str;
1426 }
1427 
1428 static void flat_print_section_header(WriterContext *wctx, const void *data)
1429 {
1430  FlatContext *flat = wctx->priv;
1431  AVBPrint *buf = &wctx->section_pbuf[wctx->level];
1432  const struct section *section = wctx->section[wctx->level];
1433  const struct section *parent_section = wctx->level ?
1434  wctx->section[wctx->level-1] : NULL;
1435 
1436  /* build section header */
1437  av_bprint_clear(buf);
1438  if (!parent_section)
1439  return;
1440  av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
1441 
1442  if (flat->hierarchical ||
1444  av_bprintf(buf, "%s%s", wctx->section[wctx->level]->name, flat->sep_str);
1445 
1446  if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
1447  int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
1448  wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
1449  av_bprintf(buf, "%d%s", n, flat->sep_str);
1450  }
1451  }
1452 }
1453 
1454 static void flat_print_int(WriterContext *wctx, const char *key, int64_t value)
1455 {
1456  writer_printf(wctx, "%s%s=%"PRId64"\n", wctx->section_pbuf[wctx->level].str, key, value);
1457 }
1458 
1459 static void flat_print_str(WriterContext *wctx, const char *key, const char *value)
1460 {
1461  FlatContext *flat = wctx->priv;
1462  AVBPrint buf;
1463 
1464  writer_put_str(wctx, wctx->section_pbuf[wctx->level].str);
1466  writer_printf(wctx, "%s=", flat_escape_key_str(&buf, key, flat->sep));
1467  av_bprint_clear(&buf);
1468  writer_printf(wctx, "\"%s\"\n", flat_escape_value_str(&buf, value));
1469  av_bprint_finalize(&buf, NULL);
1470 }
1471 
1472 static const Writer flat_writer = {
1473  .name = "flat",
1474  .priv_size = sizeof(FlatContext),
1475  .init = flat_init,
1477  .print_integer = flat_print_int,
1478  .print_string = flat_print_str,
1480  .priv_class = &flat_class,
1481 };
1482 
1483 /* INI format output */
1484 
1485 typedef struct INIContext {
1486  const AVClass *class;
1488 } INIContext;
1489 
1490 #undef OFFSET
1491 #define OFFSET(x) offsetof(INIContext, x)
1492 
1493 static const AVOption ini_options[] = {
1494  {"hierarchical", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1495  {"h", "specify if the section specification should be hierarchical", OFFSET(hierarchical), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1 },
1496  {NULL},
1497 };
1498 
1499 DEFINE_WRITER_CLASS(ini);
1500 
1501 static char *ini_escape_str(AVBPrint *dst, const char *src)
1502 {
1503  int i = 0;
1504  char c = 0;
1505 
1506  while (c = src[i++]) {
1507  switch (c) {
1508  case '\b': av_bprintf(dst, "%s", "\\b"); break;
1509  case '\f': av_bprintf(dst, "%s", "\\f"); break;
1510  case '\n': av_bprintf(dst, "%s", "\\n"); break;
1511  case '\r': av_bprintf(dst, "%s", "\\r"); break;
1512  case '\t': av_bprintf(dst, "%s", "\\t"); break;
1513  case '\\':
1514  case '#' :
1515  case '=' :
1516  case ':' : av_bprint_chars(dst, '\\', 1);
1517  default:
1518  if ((unsigned char)c < 32)
1519  av_bprintf(dst, "\\x00%02x", c & 0xff);
1520  else
1521  av_bprint_chars(dst, c, 1);
1522  break;
1523  }
1524  }
1525  return dst->str;
1526 }
1527 
1528 static void ini_print_section_header(WriterContext *wctx, const void *data)
1529 {
1530  INIContext *ini = wctx->priv;
1531  AVBPrint *buf = &wctx->section_pbuf[wctx->level];
1532  const struct section *section = wctx->section[wctx->level];
1533  const struct section *parent_section = wctx->level ?
1534  wctx->section[wctx->level-1] : NULL;
1535 
1536  av_bprint_clear(buf);
1537  if (!parent_section) {
1538  writer_put_str(wctx, "# ffprobe output\n\n");
1539  return;
1540  }
1541 
1542  if (wctx->nb_item[wctx->level-1])
1543  writer_w8(wctx, '\n');
1544 
1545  av_bprintf(buf, "%s", wctx->section_pbuf[wctx->level-1].str);
1546  if (ini->hierarchical ||
1548  av_bprintf(buf, "%s%s", buf->str[0] ? "." : "", wctx->section[wctx->level]->name);
1549 
1550  if (parent_section->flags & SECTION_FLAG_IS_ARRAY) {
1551  int n = parent_section->id == SECTION_ID_PACKETS_AND_FRAMES ?
1552  wctx->nb_section_packet_frame : wctx->nb_item[wctx->level-1];
1553  av_bprintf(buf, ".%d", n);
1554  }
1555  }
1556 
1558  writer_printf(wctx, "[%s]\n", buf->str);
1559 }
1560 
1561 static void ini_print_str(WriterContext *wctx, const char *key, const char *value)
1562 {
1563  AVBPrint buf;
1564 
1566  writer_printf(wctx, "%s=", ini_escape_str(&buf, key));
1567  av_bprint_clear(&buf);
1568  writer_printf(wctx, "%s\n", ini_escape_str(&buf, value));
1569  av_bprint_finalize(&buf, NULL);
1570 }
1571 
1572 static void ini_print_int(WriterContext *wctx, const char *key, int64_t value)
1573 {
1574  writer_printf(wctx, "%s=%"PRId64"\n", key, value);
1575 }
1576 
1577 static const Writer ini_writer = {
1578  .name = "ini",
1579  .priv_size = sizeof(INIContext),
1581  .print_integer = ini_print_int,
1582  .print_string = ini_print_str,
1584  .priv_class = &ini_class,
1585 };
1586 
1587 /* JSON output */
1588 
1589 typedef struct JSONContext {
1590  const AVClass *class;
1592  int compact;
1593  const char *item_sep, *item_start_end;
1594 } JSONContext;
1595 
1596 #undef OFFSET
1597 #define OFFSET(x) offsetof(JSONContext, x)
1598 
1599 static const AVOption json_options[]= {
1600  { "compact", "enable compact output", OFFSET(compact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1601  { "c", "enable compact output", OFFSET(compact), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1602  { NULL }
1603 };
1604 
1605 DEFINE_WRITER_CLASS(json);
1606 
1608 {
1609  JSONContext *json = wctx->priv;
1610 
1611  json->item_sep = json->compact ? ", " : ",\n";
1612  json->item_start_end = json->compact ? " " : "\n";
1613 
1614  return 0;
1615 }
1616 
1617 static const char *json_escape_str(AVBPrint *dst, const char *src, void *log_ctx)
1618 {
1619  static const char json_escape[] = {'"', '\\', '\b', '\f', '\n', '\r', '\t', 0};
1620  static const char json_subst[] = {'"', '\\', 'b', 'f', 'n', 'r', 't', 0};
1621  const char *p;
1622 
1623  for (p = src; *p; p++) {
1624  char *s = strchr(json_escape, *p);
1625  if (s) {
1626  av_bprint_chars(dst, '\\', 1);
1627  av_bprint_chars(dst, json_subst[s - json_escape], 1);
1628  } else if ((unsigned char)*p < 32) {
1629  av_bprintf(dst, "\\u00%02x", *p & 0xff);
1630  } else {
1631  av_bprint_chars(dst, *p, 1);
1632  }
1633  }
1634  return dst->str;
1635 }
1636 
1637 #define JSON_INDENT() writer_printf(wctx, "%*c", json->indent_level * 4, ' ')
1638 
1639 static void json_print_section_header(WriterContext *wctx, const void *data)
1640 {
1641  JSONContext *json = wctx->priv;
1642  AVBPrint buf;
1643  const struct section *section = wctx->section[wctx->level];
1644  const struct section *parent_section = wctx->level ?
1645  wctx->section[wctx->level-1] : NULL;
1646 
1647  if (wctx->level && wctx->nb_item[wctx->level-1])
1648  writer_put_str(wctx, ",\n");
1649 
1651  writer_put_str(wctx, "{\n");
1652  json->indent_level++;
1653  } else {
1655  json_escape_str(&buf, section->name, wctx);
1656  JSON_INDENT();
1657 
1658  json->indent_level++;
1660  writer_printf(wctx, "\"%s\": [\n", buf.str);
1661  } else if (parent_section && !(parent_section->flags & SECTION_FLAG_IS_ARRAY)) {
1662  writer_printf(wctx, "\"%s\": {%s", buf.str, json->item_start_end);
1663  } else {
1664  writer_printf(wctx, "{%s", json->item_start_end);
1665 
1666  /* this is required so the parser can distinguish between packets and frames */
1667  if (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES) {
1668  if (!json->compact)
1669  JSON_INDENT();
1670  writer_printf(wctx, "\"type\": \"%s\"", section->name);
1671  wctx->nb_item[wctx->level]++;
1672  }
1673  }
1674  av_bprint_finalize(&buf, NULL);
1675  }
1676 }
1677 
1679 {
1680  JSONContext *json = wctx->priv;
1681  const struct section *section = wctx->section[wctx->level];
1682 
1683  if (wctx->level == 0) {
1684  json->indent_level--;
1685  writer_put_str(wctx, "\n}\n");
1686  } else if (section->flags & SECTION_FLAG_IS_ARRAY) {
1687  writer_w8(wctx, '\n');
1688  json->indent_level--;
1689  JSON_INDENT();
1690  writer_w8(wctx, ']');
1691  } else {
1692  writer_put_str(wctx, json->item_start_end);
1693  json->indent_level--;
1694  if (!json->compact)
1695  JSON_INDENT();
1696  writer_w8(wctx, '}');
1697  }
1698 }
1699 
1700 static inline void json_print_item_str(WriterContext *wctx,
1701  const char *key, const char *value)
1702 {
1703  AVBPrint buf;
1704 
1706  writer_printf(wctx, "\"%s\":", json_escape_str(&buf, key, wctx));
1707  av_bprint_clear(&buf);
1708  writer_printf(wctx, " \"%s\"", json_escape_str(&buf, value, wctx));
1709  av_bprint_finalize(&buf, NULL);
1710 }
1711 
1712 static void json_print_str(WriterContext *wctx, const char *key, const char *value)
1713 {
1714  JSONContext *json = wctx->priv;
1715  const struct section *parent_section = wctx->level ?
1716  wctx->section[wctx->level-1] : NULL;
1717 
1718  if (wctx->nb_item[wctx->level] || (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES))
1719  writer_put_str(wctx, json->item_sep);
1720  if (!json->compact)
1721  JSON_INDENT();
1722  json_print_item_str(wctx, key, value);
1723 }
1724 
1725 static void json_print_int(WriterContext *wctx, const char *key, int64_t value)
1726 {
1727  JSONContext *json = wctx->priv;
1728  const struct section *parent_section = wctx->level ?
1729  wctx->section[wctx->level-1] : NULL;
1730  AVBPrint buf;
1731 
1732  if (wctx->nb_item[wctx->level] || (parent_section && parent_section->id == SECTION_ID_PACKETS_AND_FRAMES))
1733  writer_put_str(wctx, json->item_sep);
1734  if (!json->compact)
1735  JSON_INDENT();
1736 
1738  writer_printf(wctx, "\"%s\": %"PRId64, json_escape_str(&buf, key, wctx), value);
1739  av_bprint_finalize(&buf, NULL);
1740 }
1741 
1742 static const Writer json_writer = {
1743  .name = "json",
1744  .priv_size = sizeof(JSONContext),
1745  .init = json_init,
1748  .print_integer = json_print_int,
1749  .print_string = json_print_str,
1751  .priv_class = &json_class,
1752 };
1753 
1754 /* XML output */
1755 
1756 typedef struct XMLContext {
1757  const AVClass *class;
1762 } XMLContext;
1763 
1764 #undef OFFSET
1765 #define OFFSET(x) offsetof(XMLContext, x)
1766 
1767 static const AVOption xml_options[] = {
1768  {"fully_qualified", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1769  {"q", "specify if the output should be fully qualified", OFFSET(fully_qualified), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1770  {"xsd_strict", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1771  {"x", "ensure that the output is XSD compliant", OFFSET(xsd_strict), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 },
1772  {NULL},
1773 };
1774 
1775 DEFINE_WRITER_CLASS(xml);
1776 
1777 static av_cold int xml_init(WriterContext *wctx)
1778 {
1779  XMLContext *xml = wctx->priv;
1780 
1781  if (xml->xsd_strict) {
1782  xml->fully_qualified = 1;
1783 #define CHECK_COMPLIANCE(opt, opt_name) \
1784  if (opt) { \
1785  av_log(wctx, AV_LOG_ERROR, \
1786  "XSD-compliant output selected but option '%s' was selected, XML output may be non-compliant.\n" \
1787  "You need to disable such option with '-no%s'\n", opt_name, opt_name); \
1788  return AVERROR(EINVAL); \
1789  }
1790  CHECK_COMPLIANCE(show_private_data, "private");
1793  }
1794 
1795  return 0;
1796 }
1797 
1798 #define XML_INDENT() writer_printf(wctx, "%*c", xml->indent_level * 4, ' ')
1799 
1800 static void xml_print_section_header(WriterContext *wctx, const void *data)
1801 {
1802  XMLContext *xml = wctx->priv;
1803  const struct section *section = wctx->section[wctx->level];
1804  const struct section *parent_section = wctx->level ?
1805  wctx->section[wctx->level-1] : NULL;
1806 
1807  if (wctx->level == 0) {
1808  const char *qual = " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
1809  "xmlns:ffprobe=\"http://www.ffmpeg.org/schema/ffprobe\" "
1810  "xsi:schemaLocation=\"http://www.ffmpeg.org/schema/ffprobe ffprobe.xsd\"";
1811 
1812  writer_put_str(wctx, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
1813  writer_printf(wctx, "<%sffprobe%s>\n",
1814  xml->fully_qualified ? "ffprobe:" : "",
1815  xml->fully_qualified ? qual : "");
1816  return;
1817  }
1818 
1819  if (xml->within_tag) {
1820  xml->within_tag = 0;
1821  writer_put_str(wctx, ">\n");
1822  }
1823 
1824  if (parent_section && (parent_section->flags & SECTION_FLAG_IS_WRAPPER) &&
1825  wctx->level && wctx->nb_item[wctx->level-1])
1826  writer_w8(wctx, '\n');
1827  xml->indent_level++;
1828 
1830  XML_INDENT(); writer_printf(wctx, "<%s", section->name);
1831 
1833  AVBPrint buf;
1837  writer_printf(wctx, " type=\"%s\"", buf.str);
1838  }
1839  writer_printf(wctx, ">\n", section->name);
1840  } else {
1841  XML_INDENT(); writer_printf(wctx, "<%s ", section->name);
1842  xml->within_tag = 1;
1843  }
1844 }
1845 
1847 {
1848  XMLContext *xml = wctx->priv;
1849  const struct section *section = wctx->section[wctx->level];
1850 
1851  if (wctx->level == 0) {
1852  writer_printf(wctx, "</%sffprobe>\n", xml->fully_qualified ? "ffprobe:" : "");
1853  } else if (xml->within_tag) {
1854  xml->within_tag = 0;
1855  writer_put_str(wctx, "/>\n");
1856  xml->indent_level--;
1857  } else {
1858  XML_INDENT(); writer_printf(wctx, "</%s>\n", section->name);
1859  xml->indent_level--;
1860  }
1861 }
1862 
1863 static void xml_print_value(WriterContext *wctx, const char *key,
1864  const char *str, int64_t num, const int is_int)
1865 {
1866  AVBPrint buf;
1867  XMLContext *xml = wctx->priv;
1868  const struct section *section = wctx->section[wctx->level];
1869 
1871 
1873  xml->indent_level++;
1874  XML_INDENT();
1875  av_bprint_escape(&buf, key, NULL,
1877  writer_printf(wctx, "<%s key=\"%s\"",
1878  section->element_name, buf.str);
1879  av_bprint_clear(&buf);
1880 
1881  if (is_int) {
1882  writer_printf(wctx, " value=\"%"PRId64"\"/>\n", num);
1883  } else {
1884  av_bprint_escape(&buf, str, NULL,
1886  writer_printf(wctx, " value=\"%s\"/>\n", buf.str);
1887  }
1888  xml->indent_level--;
1889  } else {
1890  if (wctx->nb_item[wctx->level])
1891  writer_w8(wctx, ' ');
1892 
1893  if (is_int) {
1894  writer_printf(wctx, "%s=\"%"PRId64"\"", key, num);
1895  } else {
1896  av_bprint_escape(&buf, str, NULL,
1898  writer_printf(wctx, "%s=\"%s\"", key, buf.str);
1899  }
1900  }
1901 
1902  av_bprint_finalize(&buf, NULL);
1903 }
1904 
1905 static inline void xml_print_str(WriterContext *wctx, const char *key, const char *value) {
1906  xml_print_value(wctx, key, value, 0, 0);
1907 }
1908 
1909 static void xml_print_int(WriterContext *wctx, const char *key, int64_t value)
1910 {
1911  xml_print_value(wctx, key, NULL, value, 1);
1912 }
1913 
1914 static Writer xml_writer = {
1915  .name = "xml",
1916  .priv_size = sizeof(XMLContext),
1917  .init = xml_init,
1920  .print_integer = xml_print_int,
1921  .print_string = xml_print_str,
1923  .priv_class = &xml_class,
1924 };
1925 
1926 static void writer_register_all(void)
1927 {
1928  static int initialized;
1929 
1930  if (initialized)
1931  return;
1932  initialized = 1;
1933 
1941 }
1942 
1943 #define print_fmt(k, f, ...) do { \
1944  av_bprint_clear(&pbuf); \
1945  av_bprintf(&pbuf, f, __VA_ARGS__); \
1946  writer_print_string(w, k, pbuf.str, 0); \
1947 } while (0)
1948 
1949 #define print_list_fmt(k, f, n, m, ...) do { \
1950  av_bprint_clear(&pbuf); \
1951  for (int idx = 0; idx < n; idx++) { \
1952  for (int idx2 = 0; idx2 < m; idx2++) { \
1953  if (idx > 0 || idx2 > 0) \
1954  av_bprint_chars(&pbuf, ' ', 1); \
1955  av_bprintf(&pbuf, f, __VA_ARGS__); \
1956  } \
1957  } \
1958  writer_print_string(w, k, pbuf.str, 0); \
1959 } while (0)
1960 
1961 #define print_int(k, v) writer_print_integer(w, k, v)
1962 #define print_q(k, v, s) writer_print_rational(w, k, v, s)
1963 #define print_str(k, v) writer_print_string(w, k, v, 0)
1964 #define print_str_opt(k, v) writer_print_string(w, k, v, PRINT_STRING_OPT)
1965 #define print_str_validate(k, v) writer_print_string(w, k, v, PRINT_STRING_VALIDATE)
1966 #define print_time(k, v, tb) writer_print_time(w, k, v, tb, 0)
1967 #define print_ts(k, v) writer_print_ts(w, k, v, 0)
1968 #define print_duration_time(k, v, tb) writer_print_time(w, k, v, tb, 1)
1969 #define print_duration_ts(k, v) writer_print_ts(w, k, v, 1)
1970 #define print_val(k, v, u) do { \
1971  struct unit_value uv; \
1972  uv.val.i = v; \
1973  uv.unit = u; \
1974  writer_print_string(w, k, value_string(val_str, sizeof(val_str), uv), 0); \
1975 } while (0)
1976 
1977 #define print_section_header(s) writer_print_section_header(w, NULL, s)
1978 #define print_section_header_data(s, d) writer_print_section_header(w, d, s)
1979 #define print_section_footer(s) writer_print_section_footer(w, s)
1980 
1981 #define REALLOCZ_ARRAY_STREAM(ptr, cur_n, new_n) \
1982 { \
1983  ret = av_reallocp_array(&(ptr), (new_n), sizeof(*(ptr))); \
1984  if (ret < 0) \
1985  goto end; \
1986  memset( (ptr) + (cur_n), 0, ((new_n) - (cur_n)) * sizeof(*(ptr)) ); \
1987 }
1988 
1989 static inline int show_tags(WriterContext *w, AVDictionary *tags, int section_id)
1990 {
1991  const AVDictionaryEntry *tag = NULL;
1992  int ret = 0;
1993 
1994  if (!tags)
1995  return 0;
1996  writer_print_section_header(w, NULL, section_id);
1997 
1998  while ((tag = av_dict_iterate(tags, tag))) {
1999  if ((ret = print_str_validate(tag->key, tag->value)) < 0)
2000  break;
2001  }
2003 
2004  return ret;
2005 }
2006 
2008 {
2009  if (!dovi)
2010  return;
2011 
2012  {
2013  const AVDOVIRpuDataHeader *hdr = av_dovi_get_header(dovi);
2014  const AVDOVIDataMapping *mapping = av_dovi_get_mapping(dovi);
2016  AVBPrint pbuf;
2017 
2019 
2020  // header
2021  print_int("rpu_type", hdr->rpu_type);
2022  print_int("rpu_format", hdr->rpu_format);
2023  print_int("vdr_rpu_profile", hdr->vdr_rpu_profile);
2024  print_int("vdr_rpu_level", hdr->vdr_rpu_level);
2025  print_int("chroma_resampling_explicit_filter_flag",
2027  print_int("coef_data_type", hdr->coef_data_type);
2028  print_int("coef_log2_denom", hdr->coef_log2_denom);
2029  print_int("vdr_rpu_normalized_idc", hdr->vdr_rpu_normalized_idc);
2030  print_int("bl_video_full_range_flag", hdr->bl_video_full_range_flag);
2031  print_int("bl_bit_depth", hdr->bl_bit_depth);
2032  print_int("el_bit_depth", hdr->el_bit_depth);
2033  print_int("vdr_bit_depth", hdr->vdr_bit_depth);
2034  print_int("spatial_resampling_filter_flag",
2036  print_int("el_spatial_resampling_filter_flag",
2038  print_int("disable_residual_flag", hdr->disable_residual_flag);
2039 
2040  // data mapping values
2041  print_int("vdr_rpu_id", mapping->vdr_rpu_id);
2042  print_int("mapping_color_space", mapping->mapping_color_space);
2043  print_int("mapping_chroma_format_idc",
2044  mapping->mapping_chroma_format_idc);
2045 
2046  print_int("nlq_method_idc", mapping->nlq_method_idc);
2047  switch (mapping->nlq_method_idc) {
2048  case AV_DOVI_NLQ_NONE:
2049  print_str("nlq_method_idc_name", "none");
2050  break;
2051  case AV_DOVI_NLQ_LINEAR_DZ:
2052  print_str("nlq_method_idc_name", "linear_dz");
2053  break;
2054  default:
2055  print_str("nlq_method_idc_name", "unknown");
2056  break;
2057  }
2058 
2059  print_int("num_x_partitions", mapping->num_x_partitions);
2060  print_int("num_y_partitions", mapping->num_y_partitions);
2061 
2063 
2064  for (int c = 0; c < 3; c++) {
2065  const AVDOVIReshapingCurve *curve = &mapping->curves[c];
2067 
2068  print_list_fmt("pivots", "%"PRIu16, curve->num_pivots, 1, curve->pivots[idx]);
2069 
2071  for (int i = 0; i < curve->num_pivots - 1; i++) {
2072 
2074  print_int("mapping_idc", curve->mapping_idc[i]);
2075  switch (curve->mapping_idc[i]) {
2077  print_str("mapping_idc_name", "polynomial");
2078  print_int("poly_order", curve->poly_order[i]);
2079  print_list_fmt("poly_coef", "%"PRIi64,
2080  curve->poly_order[i] + 1, 1,
2081  curve->poly_coef[i][idx]);
2082  break;
2083  case AV_DOVI_MAPPING_MMR:
2084  print_str("mapping_idc_name", "mmr");
2085  print_int("mmr_order", curve->mmr_order[i]);
2086  print_int("mmr_constant", curve->mmr_constant[i]);
2087  print_list_fmt("mmr_coef", "%"PRIi64,
2088  curve->mmr_order[i], 7,
2089  curve->mmr_coef[i][idx][idx2]);
2090  break;
2091  default:
2092  print_str("mapping_idc_name", "unknown");
2093  break;
2094  }
2095 
2096  // SECTION_ID_FRAME_SIDE_DATA_PIECE
2098  }
2099 
2100  // SECTION_ID_FRAME_SIDE_DATA_PIECE_LIST
2102 
2103  if (mapping->nlq_method_idc != AV_DOVI_NLQ_NONE) {
2104  const AVDOVINLQParams *nlq = &mapping->nlq[c];
2105  print_int("nlq_offset", nlq->nlq_offset);
2106  print_int("vdr_in_max", nlq->vdr_in_max);
2107 
2108  switch (mapping->nlq_method_idc) {
2109  case AV_DOVI_NLQ_LINEAR_DZ:
2110  print_int("linear_deadzone_slope", nlq->linear_deadzone_slope);
2111  print_int("linear_deadzone_threshold", nlq->linear_deadzone_threshold);
2112  break;
2113  }
2114  }
2115 
2116  // SECTION_ID_FRAME_SIDE_DATA_COMPONENT
2118  }
2119 
2120  // SECTION_ID_FRAME_SIDE_DATA_COMPONENT_LIST
2122 
2123  // color metadata
2124  print_int("dm_metadata_id", color->dm_metadata_id);
2125  print_int("scene_refresh_flag", color->scene_refresh_flag);
2126  print_list_fmt("ycc_to_rgb_matrix", "%d/%d",
2127  FF_ARRAY_ELEMS(color->ycc_to_rgb_matrix), 1,
2128  color->ycc_to_rgb_matrix[idx].num,
2129  color->ycc_to_rgb_matrix[idx].den);
2130  print_list_fmt("ycc_to_rgb_offset", "%d/%d",
2131  FF_ARRAY_ELEMS(color->ycc_to_rgb_offset), 1,
2132  color->ycc_to_rgb_offset[idx].num,
2133  color->ycc_to_rgb_offset[idx].den);
2134  print_list_fmt("rgb_to_lms_matrix", "%d/%d",
2135  FF_ARRAY_ELEMS(color->rgb_to_lms_matrix), 1,
2136  color->rgb_to_lms_matrix[idx].num,
2137  color->rgb_to_lms_matrix[idx].den);
2138  print_int("signal_eotf", color->signal_eotf);
2139  print_int("signal_eotf_param0", color->signal_eotf_param0);
2140  print_int("signal_eotf_param1", color->signal_eotf_param1);
2141  print_int("signal_eotf_param2", color->signal_eotf_param2);
2142  print_int("signal_bit_depth", color->signal_bit_depth);
2143  print_int("signal_color_space", color->signal_color_space);
2144  print_int("signal_chroma_format", color->signal_chroma_format);
2145  print_int("signal_full_range_flag", color->signal_full_range_flag);
2146  print_int("source_min_pq", color->source_min_pq);
2147  print_int("source_max_pq", color->source_max_pq);
2148  print_int("source_diagonal", color->source_diagonal);
2149 
2150  av_bprint_finalize(&pbuf, NULL);
2151  }
2152 }
2153 
2155 {
2156  if (!metadata)
2157  return;
2158  print_int("application version", metadata->application_version);
2159  print_int("num_windows", metadata->num_windows);
2160  for (int n = 1; n < metadata->num_windows; n++) {
2161  const AVHDRPlusColorTransformParams *params = &metadata->params[n];
2162  print_q("window_upper_left_corner_x",
2163  params->window_upper_left_corner_x,'/');
2164  print_q("window_upper_left_corner_y",
2165  params->window_upper_left_corner_y,'/');
2166  print_q("window_lower_right_corner_x",
2167  params->window_lower_right_corner_x,'/');
2168  print_q("window_lower_right_corner_y",
2169  params->window_lower_right_corner_y,'/');
2170  print_q("window_upper_left_corner_x",
2171  params->window_upper_left_corner_x,'/');
2172  print_q("window_upper_left_corner_y",
2173  params->window_upper_left_corner_y,'/');
2174  print_int("center_of_ellipse_x",
2175  params->center_of_ellipse_x ) ;
2176  print_int("center_of_ellipse_y",
2177  params->center_of_ellipse_y );
2178  print_int("rotation_angle",
2179  params->rotation_angle);
2180  print_int("semimajor_axis_internal_ellipse",
2182  print_int("semimajor_axis_external_ellipse",
2184  print_int("semiminor_axis_external_ellipse",
2186  print_int("overlap_process_option",
2187  params->overlap_process_option);
2188  }
2189  print_q("targeted_system_display_maximum_luminance",
2192  print_int("num_rows_targeted_system_display_actual_peak_luminance",
2194  print_int("num_cols_targeted_system_display_actual_peak_luminance",
2196  for (int i = 0; i < metadata->num_rows_targeted_system_display_actual_peak_luminance; i++) {
2197  for (int j = 0; j < metadata->num_cols_targeted_system_display_actual_peak_luminance; j++) {
2198  print_q("targeted_system_display_actual_peak_luminance",
2200  }
2201  }
2202  }
2203  for (int n = 0; n < metadata->num_windows; n++) {
2204  const AVHDRPlusColorTransformParams *params = &metadata->params[n];
2205  for (int i = 0; i < 3; i++) {
2206  print_q("maxscl",params->maxscl[i],'/');
2207  }
2208  print_q("average_maxrgb",
2209  params->average_maxrgb,'/');
2210  print_int("num_distribution_maxrgb_percentiles",
2212  for (int i = 0; i < params->num_distribution_maxrgb_percentiles; i++) {
2213  print_int("distribution_maxrgb_percentage",
2214  params->distribution_maxrgb[i].percentage);
2215  print_q("distribution_maxrgb_percentile",
2216  params->distribution_maxrgb[i].percentile,'/');
2217  }
2218  print_q("fraction_bright_pixels",
2219  params->fraction_bright_pixels,'/');
2220  }
2222  print_int("num_rows_mastering_display_actual_peak_luminance",
2224  print_int("num_cols_mastering_display_actual_peak_luminance",
2226  for (int i = 0; i < metadata->num_rows_mastering_display_actual_peak_luminance; i++) {
2227  for (int j = 0; j < metadata->num_cols_mastering_display_actual_peak_luminance; j++) {
2228  print_q("mastering_display_actual_peak_luminance",
2229  metadata->mastering_display_actual_peak_luminance[i][j],'/');
2230  }
2231  }
2232  }
2233 
2234  for (int n = 0; n < metadata->num_windows; n++) {
2235  const AVHDRPlusColorTransformParams *params = &metadata->params[n];
2236  if (params->tone_mapping_flag) {
2237  print_q("knee_point_x", params->knee_point_x,'/');
2238  print_q("knee_point_y", params->knee_point_y,'/');
2239  print_int("num_bezier_curve_anchors",
2240  params->num_bezier_curve_anchors );
2241  for (int i = 0; i < params->num_bezier_curve_anchors; i++) {
2242  print_q("bezier_curve_anchors",
2243  params->bezier_curve_anchors[i],'/');
2244  }
2245  }
2246  if (params->color_saturation_mapping_flag) {
2247  print_q("color_saturation_weight",
2248  params->color_saturation_weight,'/');
2249  }
2250  }
2251 }
2252 
2254 {
2255  if (!metadata)
2256  return;
2257  print_int("system_start_code", metadata->system_start_code);
2258  print_int("num_windows", metadata->num_windows);
2259 
2260  for (int n = 0; n < metadata->num_windows; n++) {
2261  const AVHDRVividColorTransformParams *params = &metadata->params[n];
2262 
2263  print_q("minimum_maxrgb", params->minimum_maxrgb, '/');
2264  print_q("average_maxrgb", params->average_maxrgb, '/');
2265  print_q("variance_maxrgb", params->variance_maxrgb, '/');
2266  print_q("maximum_maxrgb", params->maximum_maxrgb, '/');
2267  }
2268 
2269  for (int n = 0; n < metadata->num_windows; n++) {
2270  const AVHDRVividColorTransformParams *params = &metadata->params[n];
2271 
2272  print_int("tone_mapping_mode_flag", params->tone_mapping_mode_flag);
2273  if (params->tone_mapping_mode_flag) {
2274  print_int("tone_mapping_param_num", params->tone_mapping_param_num);
2275  for (int i = 0; i < params->tone_mapping_param_num; i++) {
2276  const AVHDRVividColorToneMappingParams *tm_params = &params->tm_params[i];
2277 
2278  print_q("targeted_system_display_maximum_luminance",
2280  print_int("base_enable_flag", tm_params->base_enable_flag);
2281  if (tm_params->base_enable_flag) {
2282  print_q("base_param_m_p", tm_params->base_param_m_p, '/');
2283  print_q("base_param_m_m", tm_params->base_param_m_m, '/');
2284  print_q("base_param_m_a", tm_params->base_param_m_a, '/');
2285  print_q("base_param_m_b", tm_params->base_param_m_b, '/');
2286  print_q("base_param_m_n", tm_params->base_param_m_n, '/');
2287 
2288  print_int("base_param_k1", tm_params->base_param_k1);
2289  print_int("base_param_k2", tm_params->base_param_k2);
2290  print_int("base_param_k3", tm_params->base_param_k3);
2291  print_int("base_param_Delta_enable_mode",
2292  tm_params->base_param_Delta_enable_mode);
2293  print_q("base_param_Delta", tm_params->base_param_Delta, '/');
2294  }
2295  print_int("3Spline_enable_flag", tm_params->three_Spline_enable_flag);
2296  if (tm_params->three_Spline_enable_flag) {
2297  print_int("3Spline_num", tm_params->three_Spline_num);
2298 
2299  for (int j = 0; j < tm_params->three_Spline_num; j++) {
2300  const AVHDRVivid3SplineParams *three_spline = &tm_params->three_spline[j];
2301  print_int("3Spline_TH_mode", three_spline->th_mode);
2302  if (three_spline->th_mode == 0 || three_spline->th_mode == 2)
2303  print_q("3Spline_TH_enable_MB", three_spline->th_enable_mb, '/');
2304  print_q("3Spline_TH_enable", three_spline->th_enable, '/');
2305  print_q("3Spline_TH_Delta1", three_spline->th_delta1, '/');
2306  print_q("3Spline_TH_Delta2", three_spline->th_delta2, '/');
2307  print_q("3Spline_enable_Strength", three_spline->enable_strength, '/');
2308  }
2309  }
2310  }
2311  }
2312 
2313  print_int("color_saturation_mapping_flag", params->color_saturation_mapping_flag);
2314  if (params->color_saturation_mapping_flag) {
2315  print_int("color_saturation_num", params->color_saturation_num);
2316  for (int i = 0; i < params->color_saturation_num; i++) {
2317  print_q("color_saturation_gain", params->color_saturation_gain[i], '/');
2318  }
2319  }
2320  }
2321 }
2322 
2324  const AVAmbientViewingEnvironment *env)
2325 {
2326  if (!env)
2327  return;
2328 
2329  print_q("ambient_illuminance", env->ambient_illuminance, '/');
2330  print_q("ambient_light_x", env->ambient_light_x, '/');
2331  print_q("ambient_light_y", env->ambient_light_y, '/');
2332 }
2333 
2335  AVCodecParameters *par,
2336  const AVPacketSideData *sd,
2337  SectionID id_data)
2338 {
2339  const char *name = av_packet_side_data_name(sd->type);
2340 
2341  writer_print_section_header(w, sd, id_data);
2342  print_str("side_data_type", name ? name : "unknown");
2343  if (sd->type == AV_PKT_DATA_DISPLAYMATRIX && sd->size >= 9*4) {
2344  double rotation = av_display_rotation_get((int32_t *)sd->data);
2345  if (isnan(rotation))
2346  rotation = 0;
2347  writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);
2348  print_int("rotation", rotation);
2349  } else if (sd->type == AV_PKT_DATA_STEREO3D) {
2350  const AVStereo3D *stereo = (AVStereo3D *)sd->data;
2351  print_str("type", av_stereo3d_type_name(stereo->type));
2352  print_int("inverted", !!(stereo->flags & AV_STEREO3D_FLAG_INVERT));
2353  } else if (sd->type == AV_PKT_DATA_SPHERICAL) {
2354  const AVSphericalMapping *spherical = (AVSphericalMapping *)sd->data;
2355  print_str("projection", av_spherical_projection_name(spherical->projection));
2356  if (spherical->projection == AV_SPHERICAL_CUBEMAP) {
2357  print_int("padding", spherical->padding);
2358  } else if (spherical->projection == AV_SPHERICAL_EQUIRECTANGULAR_TILE) {
2359  size_t l, t, r, b;
2360  av_spherical_tile_bounds(spherical, par->width, par->height,
2361  &l, &t, &r, &b);
2362  print_int("bound_left", l);
2363  print_int("bound_top", t);
2364  print_int("bound_right", r);
2365  print_int("bound_bottom", b);
2366  }
2367 
2368  print_int("yaw", (double) spherical->yaw / (1 << 16));
2369  print_int("pitch", (double) spherical->pitch / (1 << 16));
2370  print_int("roll", (double) spherical->roll / (1 << 16));
2371  } else if (sd->type == AV_PKT_DATA_SKIP_SAMPLES && sd->size == 10) {
2372  print_int("skip_samples", AV_RL32(sd->data));
2373  print_int("discard_padding", AV_RL32(sd->data + 4));
2374  print_int("skip_reason", AV_RL8(sd->data + 8));
2375  print_int("discard_reason", AV_RL8(sd->data + 9));
2376  } else if (sd->type == AV_PKT_DATA_MASTERING_DISPLAY_METADATA) {
2378 
2379  if (metadata->has_primaries) {
2380  print_q("red_x", metadata->display_primaries[0][0], '/');
2381  print_q("red_y", metadata->display_primaries[0][1], '/');
2382  print_q("green_x", metadata->display_primaries[1][0], '/');
2383  print_q("green_y", metadata->display_primaries[1][1], '/');
2384  print_q("blue_x", metadata->display_primaries[2][0], '/');
2385  print_q("blue_y", metadata->display_primaries[2][1], '/');
2386 
2387  print_q("white_point_x", metadata->white_point[0], '/');
2388  print_q("white_point_y", metadata->white_point[1], '/');
2389  }
2390 
2391  if (metadata->has_luminance) {
2392  print_q("min_luminance", metadata->min_luminance, '/');
2393  print_q("max_luminance", metadata->max_luminance, '/');
2394  }
2395  } else if (sd->type == AV_PKT_DATA_CONTENT_LIGHT_LEVEL) {
2397  print_int("max_content", metadata->MaxCLL);
2398  print_int("max_average", metadata->MaxFALL);
2399  } else if (sd->type == AV_PKT_DATA_AMBIENT_VIEWING_ENVIRONMENT) {
2401  w, (const AVAmbientViewingEnvironment *)sd->data);
2402  } else if (sd->type == AV_PKT_DATA_DYNAMIC_HDR10_PLUS) {
2403  AVDynamicHDRPlus *metadata = (AVDynamicHDRPlus *)sd->data;
2404  print_dynamic_hdr10_plus(w, metadata);
2405  } else if (sd->type == AV_PKT_DATA_DOVI_CONF) {
2407  print_int("dv_version_major", dovi->dv_version_major);
2408  print_int("dv_version_minor", dovi->dv_version_minor);
2409  print_int("dv_profile", dovi->dv_profile);
2410  print_int("dv_level", dovi->dv_level);
2411  print_int("rpu_present_flag", dovi->rpu_present_flag);
2412  print_int("el_present_flag", dovi->el_present_flag);
2413  print_int("bl_present_flag", dovi->bl_present_flag);
2414  print_int("dv_bl_signal_compatibility_id", dovi->dv_bl_signal_compatibility_id);
2415  } else if (sd->type == AV_PKT_DATA_AUDIO_SERVICE_TYPE) {
2416  enum AVAudioServiceType *t = (enum AVAudioServiceType *)sd->data;
2417  print_int("service_type", *t);
2418  } else if (sd->type == AV_PKT_DATA_MPEGTS_STREAM_ID) {
2419  print_int("id", *sd->data);
2420  } else if (sd->type == AV_PKT_DATA_CPB_PROPERTIES) {
2421  const AVCPBProperties *prop = (AVCPBProperties *)sd->data;
2422  print_int("max_bitrate", prop->max_bitrate);
2423  print_int("min_bitrate", prop->min_bitrate);
2424  print_int("avg_bitrate", prop->avg_bitrate);
2425  print_int("buffer_size", prop->buffer_size);
2426  print_int("vbv_delay", prop->vbv_delay);
2427  } else if (sd->type == AV_PKT_DATA_WEBVTT_IDENTIFIER ||
2429  if (do_show_data)
2430  writer_print_data(w, "data", sd->data, sd->size);
2431  writer_print_data_hash(w, "data_hash", sd->data, sd->size);
2432  } else if (sd->type == AV_PKT_DATA_AFD && sd->size > 0) {
2433  print_int("active_format", *sd->data);
2434  }
2435 }
2436 
2437 static void print_private_data(WriterContext *w, void *priv_data)
2438 {
2439  const AVOption *opt = NULL;
2440  while (opt = av_opt_next(priv_data, opt)) {
2441  uint8_t *str;
2442  if (!(opt->flags & AV_OPT_FLAG_EXPORT)) continue;
2443  if (av_opt_get(priv_data, opt->name, 0, &str) >= 0) {
2444  print_str(opt->name, str);
2445  av_free(str);
2446  }
2447  }
2448 }
2449 
2451 {
2452  const char *val = av_color_range_name(color_range);
2454  print_str_opt("color_range", "unknown");
2455  } else {
2456  print_str("color_range", val);
2457  }
2458 }
2459 
2460 static void print_color_space(WriterContext *w, enum AVColorSpace color_space)
2461 {
2462  const char *val = av_color_space_name(color_space);
2463  if (!val || color_space == AVCOL_SPC_UNSPECIFIED) {
2464  print_str_opt("color_space", "unknown");
2465  } else {
2466  print_str("color_space", val);
2467  }
2468 }
2469 
2471 {
2474  print_str_opt("color_primaries", "unknown");
2475  } else {
2476  print_str("color_primaries", val);
2477  }
2478 }
2479 
2481 {
2482  const char *val = av_color_transfer_name(color_trc);
2483  if (!val || color_trc == AVCOL_TRC_UNSPECIFIED) {
2484  print_str_opt("color_transfer", "unknown");
2485  } else {
2486  print_str("color_transfer", val);
2487  }
2488 }
2489 
2490 static void print_chroma_location(WriterContext *w, enum AVChromaLocation chroma_location)
2491 {
2492  const char *val = av_chroma_location_name(chroma_location);
2493  if (!val || chroma_location == AVCHROMA_LOC_UNSPECIFIED) {
2494  print_str_opt("chroma_location", "unspecified");
2495  } else {
2496  print_str("chroma_location", val);
2497  }
2498 }
2499 
2500 static void clear_log(int need_lock)
2501 {
2502  int i;
2503 
2504  if (need_lock)
2505  pthread_mutex_lock(&log_mutex);
2506  for (i=0; i<log_buffer_size; i++) {
2507  av_freep(&log_buffer[i].context_name);
2508  av_freep(&log_buffer[i].parent_name);
2509  av_freep(&log_buffer[i].log_message);
2510  }
2511  log_buffer_size = 0;
2512  if(need_lock)
2513  pthread_mutex_unlock(&log_mutex);
2514 }
2515 
2516 static int show_log(WriterContext *w, int section_ids, int section_id, int log_level)
2517 {
2518  int i;
2519  pthread_mutex_lock(&log_mutex);
2520  if (!log_buffer_size) {
2521  pthread_mutex_unlock(&log_mutex);
2522  return 0;
2523  }
2524  writer_print_section_header(w, NULL, section_ids);
2525 
2526  for (i=0; i<log_buffer_size; i++) {
2527  if (log_buffer[i].log_level <= log_level) {
2528  writer_print_section_header(w, NULL, section_id);
2529  print_str("context", log_buffer[i].context_name);
2530  print_int("level", log_buffer[i].log_level);
2531  print_int("category", log_buffer[i].category);
2532  if (log_buffer[i].parent_name) {
2533  print_str("parent_context", log_buffer[i].parent_name);
2534  print_int("parent_category", log_buffer[i].parent_category);
2535  } else {
2536  print_str_opt("parent_context", "N/A");
2537  print_str_opt("parent_category", "N/A");
2538  }
2539  print_str("message", log_buffer[i].log_message);
2541  }
2542  }
2543  clear_log(0);
2544  pthread_mutex_unlock(&log_mutex);
2545 
2547 
2548  return 0;
2549 }
2550 
2551 static void show_packet(WriterContext *w, InputFile *ifile, AVPacket *pkt, int packet_idx)
2552 {
2553  char val_str[128];
2554  AVStream *st = ifile->streams[pkt->stream_index].st;
2555  AVBPrint pbuf;
2556  const char *s;
2557 
2559 
2561 
2563  if (s) print_str ("codec_type", s);
2564  else print_str_opt("codec_type", "unknown");
2565  print_int("stream_index", pkt->stream_index);
2566  print_ts ("pts", pkt->pts);
2567  print_time("pts_time", pkt->pts, &st->time_base);
2568  print_ts ("dts", pkt->dts);
2569  print_time("dts_time", pkt->dts, &st->time_base);
2570  print_duration_ts("duration", pkt->duration);
2571  print_duration_time("duration_time", pkt->duration, &st->time_base);
2572  print_val("size", pkt->size, unit_byte_str);
2573  if (pkt->pos != -1) print_fmt ("pos", "%"PRId64, pkt->pos);
2574  else print_str_opt("pos", "N/A");
2575  print_fmt("flags", "%c%c%c", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_',
2576  pkt->flags & AV_PKT_FLAG_DISCARD ? 'D' : '_',
2577  pkt->flags & AV_PKT_FLAG_CORRUPT ? 'C' : '_');
2578  if (do_show_data)
2579  writer_print_data(w, "data", pkt->data, pkt->size);
2580  writer_print_data_hash(w, "data_hash", pkt->data, pkt->size);
2581 
2582  if (pkt->side_data_elems) {
2583  size_t size;
2584  const uint8_t *side_metadata;
2585 
2587  if (side_metadata && size && do_show_packet_tags) {
2588  AVDictionary *dict = NULL;
2589  if (av_packet_unpack_dictionary(side_metadata, size, &dict) >= 0)
2591  av_dict_free(&dict);
2592  }
2593 
2595  for (int i = 0; i < pkt->side_data_elems; i++) {
2599  }
2601  }
2602 
2604 
2605  av_bprint_finalize(&pbuf, NULL);
2606  fflush(stdout);
2607 }
2608 
2609 static void show_subtitle(WriterContext *w, AVSubtitle *sub, AVStream *stream,
2611 {
2612  AVBPrint pbuf;
2613 
2615 
2617 
2618  print_str ("media_type", "subtitle");
2619  print_ts ("pts", sub->pts);
2620  print_time("pts_time", sub->pts, &AV_TIME_BASE_Q);
2621  print_int ("format", sub->format);
2622  print_int ("start_display_time", sub->start_display_time);
2623  print_int ("end_display_time", sub->end_display_time);
2624  print_int ("num_rects", sub->num_rects);
2625 
2627 
2628  av_bprint_finalize(&pbuf, NULL);
2629  fflush(stdout);
2630 }
2631 
2633  const AVFrame *frame,
2634  const AVStream *stream)
2635 {
2637 
2638  for (int i = 0; i < frame->nb_side_data; i++) {
2639  const AVFrameSideData *sd = frame->side_data[i];
2640  const char *name;
2641 
2644  print_str("side_data_type", name ? name : "unknown");
2645  if (sd->type == AV_FRAME_DATA_DISPLAYMATRIX && sd->size >= 9*4) {
2646  double rotation = av_display_rotation_get((int32_t *)sd->data);
2647  if (isnan(rotation))
2648  rotation = 0;
2649  writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);
2650  print_int("rotation", rotation);
2651  } else if (sd->type == AV_FRAME_DATA_AFD && sd->size > 0) {
2652  print_int("active_format", *sd->data);
2653  } else if (sd->type == AV_FRAME_DATA_GOP_TIMECODE && sd->size >= 8) {
2654  char tcbuf[AV_TIMECODE_STR_SIZE];
2655  av_timecode_make_mpeg_tc_string(tcbuf, *(int64_t *)(sd->data));
2656  print_str("timecode", tcbuf);
2657  } else if (sd->type == AV_FRAME_DATA_S12M_TIMECODE && sd->size == 16) {
2658  uint32_t *tc = (uint32_t*)sd->data;
2659  int m = FFMIN(tc[0],3);
2661  for (int j = 1; j <= m ; j++) {
2662  char tcbuf[AV_TIMECODE_STR_SIZE];
2663  av_timecode_make_smpte_tc_string2(tcbuf, stream->avg_frame_rate, tc[j], 0, 0);
2665  print_str("value", tcbuf);
2667  }
2669  } else if (sd->type == AV_FRAME_DATA_MASTERING_DISPLAY_METADATA) {
2671 
2672  if (metadata->has_primaries) {
2673  print_q("red_x", metadata->display_primaries[0][0], '/');
2674  print_q("red_y", metadata->display_primaries[0][1], '/');
2675  print_q("green_x", metadata->display_primaries[1][0], '/');
2676  print_q("green_y", metadata->display_primaries[1][1], '/');
2677  print_q("blue_x", metadata->display_primaries[2][0], '/');
2678  print_q("blue_y", metadata->display_primaries[2][1], '/');
2679 
2680  print_q("white_point_x", metadata->white_point[0], '/');
2681  print_q("white_point_y", metadata->white_point[1], '/');
2682  }
2683 
2684  if (metadata->has_luminance) {
2685  print_q("min_luminance", metadata->min_luminance, '/');
2686  print_q("max_luminance", metadata->max_luminance, '/');
2687  }
2688  } else if (sd->type == AV_FRAME_DATA_DYNAMIC_HDR_PLUS) {
2689  AVDynamicHDRPlus *metadata = (AVDynamicHDRPlus *)sd->data;
2690  print_dynamic_hdr10_plus(w, metadata);
2691  } else if (sd->type == AV_FRAME_DATA_CONTENT_LIGHT_LEVEL) {
2693  print_int("max_content", metadata->MaxCLL);
2694  print_int("max_average", metadata->MaxFALL);
2695  } else if (sd->type == AV_FRAME_DATA_ICC_PROFILE) {
2697  if (tag)
2698  print_str(tag->key, tag->value);
2699  print_int("size", sd->size);
2700  } else if (sd->type == AV_FRAME_DATA_DOVI_METADATA) {
2701  print_dovi_metadata(w, (const AVDOVIMetadata *)sd->data);
2702  } else if (sd->type == AV_FRAME_DATA_DYNAMIC_HDR_VIVID) {
2703  AVDynamicHDRVivid *metadata = (AVDynamicHDRVivid *)sd->data;
2704  print_dynamic_hdr_vivid(w, metadata);
2705  } else if (sd->type == AV_FRAME_DATA_AMBIENT_VIEWING_ENVIRONMENT) {
2707  }
2709  }
2711 }
2712 
2715 {
2717  AVBPrint pbuf;
2718  char val_str[128];
2719  const char *s;
2720 
2722 
2724 
2726  if (s) print_str ("media_type", s);
2727  else print_str_opt("media_type", "unknown");
2728  print_int("stream_index", stream->index);
2729  print_int("key_frame", !!(frame->flags & AV_FRAME_FLAG_KEY));
2730  print_ts ("pts", frame->pts);
2731  print_time("pts_time", frame->pts, &stream->time_base);
2732  print_ts ("pkt_dts", frame->pkt_dts);
2733  print_time("pkt_dts_time", frame->pkt_dts, &stream->time_base);
2734  print_ts ("best_effort_timestamp", frame->best_effort_timestamp);
2735  print_time("best_effort_timestamp_time", frame->best_effort_timestamp, &stream->time_base);
2736 #if LIBAVUTIL_VERSION_MAJOR < 59
2738  print_duration_ts ("pkt_duration", frame->pkt_duration);
2739  print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);
2740  )
2741 #endif
2742  print_duration_ts ("duration", frame->duration);
2743  print_duration_time("duration_time", frame->duration, &stream->time_base);
2744  if (fd && fd->pkt_pos != -1) print_fmt ("pkt_pos", "%"PRId64, fd->pkt_pos);
2745  else print_str_opt("pkt_pos", "N/A");
2746  if (fd && fd->pkt_size != -1) print_val ("pkt_size", fd->pkt_size, unit_byte_str);
2747  else print_str_opt("pkt_size", "N/A");
2748 
2749  switch (stream->codecpar->codec_type) {
2750  AVRational sar;
2751 
2752  case AVMEDIA_TYPE_VIDEO:
2753  print_int("width", frame->width);
2754  print_int("height", frame->height);
2755  print_int("crop_top", frame->crop_top);
2756  print_int("crop_bottom", frame->crop_bottom);
2757  print_int("crop_left", frame->crop_left);
2758  print_int("crop_right", frame->crop_right);
2760  if (s) print_str ("pix_fmt", s);
2761  else print_str_opt("pix_fmt", "unknown");
2762  sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);
2763  if (sar.num) {
2764  print_q("sample_aspect_ratio", sar, ':');
2765  } else {
2766  print_str_opt("sample_aspect_ratio", "N/A");
2767  }
2768  print_fmt("pict_type", "%c", av_get_picture_type_char(frame->pict_type));
2769 #if LIBAVUTIL_VERSION_MAJOR < 59
2771  print_int("coded_picture_number", frame->coded_picture_number);
2772  print_int("display_picture_number", frame->display_picture_number);
2773  )
2774 #endif
2775  print_int("interlaced_frame", !!(frame->flags & AV_FRAME_FLAG_INTERLACED));
2776  print_int("top_field_first", !!(frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST));
2777  print_int("repeat_pict", frame->repeat_pict);
2778 
2784  break;
2785 
2786  case AVMEDIA_TYPE_AUDIO:
2788  if (s) print_str ("sample_fmt", s);
2789  else print_str_opt("sample_fmt", "unknown");
2790  print_int("nb_samples", frame->nb_samples);
2791  print_int("channels", frame->ch_layout.nb_channels);
2793  av_channel_layout_describe(&frame->ch_layout, val_str, sizeof(val_str));
2794  print_str ("channel_layout", val_str);
2795  } else
2796  print_str_opt("channel_layout", "unknown");
2797  break;
2798  }
2799  if (do_show_frame_tags)
2801  if (do_show_log)
2803  if (frame->nb_side_data)
2804  print_frame_side_data(w, frame, stream);
2805 
2807 
2808  av_bprint_finalize(&pbuf, NULL);
2809  fflush(stdout);
2810 }
2811 
2813  InputFile *ifile,
2814  AVFrame *frame, const AVPacket *pkt,
2815  int *packet_new)
2816 {
2817  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
2820  AVSubtitle sub;
2821  int ret = 0, got_frame = 0;
2822 
2823  clear_log(1);
2824  if (dec_ctx) {
2825  switch (par->codec_type) {
2826  case AVMEDIA_TYPE_VIDEO:
2827  case AVMEDIA_TYPE_AUDIO:
2828  if (*packet_new) {
2830  if (ret == AVERROR(EAGAIN)) {
2831  ret = 0;
2832  } else if (ret >= 0 || ret == AVERROR_EOF) {
2833  ret = 0;
2834  *packet_new = 0;
2835  }
2836  }
2837  if (ret >= 0) {
2839  if (ret >= 0) {
2840  got_frame = 1;
2841  } else if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
2842  ret = 0;
2843  }
2844  }
2845  break;
2846 
2847  case AVMEDIA_TYPE_SUBTITLE:
2848  if (*packet_new)
2849  ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_frame, pkt);
2850  *packet_new = 0;
2851  break;
2852  default:
2853  *packet_new = 0;
2854  }
2855  } else {
2856  *packet_new = 0;
2857  }
2858 
2859  if (ret < 0)
2860  return ret;
2861  if (got_frame) {
2862  int is_sub = (par->codec_type == AVMEDIA_TYPE_SUBTITLE);
2864  if (do_show_frames)
2865  if (is_sub)
2866  show_subtitle(w, &sub, ifile->streams[pkt->stream_index].st, fmt_ctx);
2867  else
2869  if (is_sub)
2870  avsubtitle_free(&sub);
2871  }
2872  return got_frame || *packet_new;
2873 }
2874 
2875 static void log_read_interval(const ReadInterval *interval, void *log_ctx, int log_level)
2876 {
2877  av_log(log_ctx, log_level, "id:%d", interval->id);
2878 
2879  if (interval->has_start) {
2880  av_log(log_ctx, log_level, " start:%s%s", interval->start_is_offset ? "+" : "",
2881  av_ts2timestr(interval->start, &AV_TIME_BASE_Q));
2882  } else {
2883  av_log(log_ctx, log_level, " start:N/A");
2884  }
2885 
2886  if (interval->has_end) {
2887  av_log(log_ctx, log_level, " end:%s", interval->end_is_offset ? "+" : "");
2888  if (interval->duration_frames)
2889  av_log(log_ctx, log_level, "#%"PRId64, interval->end);
2890  else
2891  av_log(log_ctx, log_level, "%s", av_ts2timestr(interval->end, &AV_TIME_BASE_Q));
2892  } else {
2893  av_log(log_ctx, log_level, " end:N/A");
2894  }
2895 
2896  av_log(log_ctx, log_level, "\n");
2897 }
2898 
2900  const ReadInterval *interval, int64_t *cur_ts)
2901 {
2902  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
2903  AVPacket *pkt = NULL;
2904  AVFrame *frame = NULL;
2905  int ret = 0, i = 0, frame_count = 0;
2906  int64_t start = -INT64_MAX, end = interval->end;
2907  int has_start = 0, has_end = interval->has_end && !interval->end_is_offset;
2908 
2909  av_log(NULL, AV_LOG_VERBOSE, "Processing read interval ");
2911 
2912  if (interval->has_start) {
2913  int64_t target;
2914  if (interval->start_is_offset) {
2915  if (*cur_ts == AV_NOPTS_VALUE) {
2917  "Could not seek to relative position since current "
2918  "timestamp is not defined\n");
2919  ret = AVERROR(EINVAL);
2920  goto end;
2921  }
2922  target = *cur_ts + interval->start;
2923  } else {
2924  target = interval->start;
2925  }
2926 
2927  av_log(NULL, AV_LOG_VERBOSE, "Seeking to read interval start point %s\n",
2928  av_ts2timestr(target, &AV_TIME_BASE_Q));
2929  if ((ret = avformat_seek_file(fmt_ctx, -1, -INT64_MAX, target, INT64_MAX, 0)) < 0) {
2930  av_log(NULL, AV_LOG_ERROR, "Could not seek to position %"PRId64": %s\n",
2931  interval->start, av_err2str(ret));
2932  goto end;
2933  }
2934  }
2935 
2936  frame = av_frame_alloc();
2937  if (!frame) {
2938  ret = AVERROR(ENOMEM);
2939  goto end;
2940  }
2941  pkt = av_packet_alloc();
2942  if (!pkt) {
2943  ret = AVERROR(ENOMEM);
2944  goto end;
2945  }
2946  while (!av_read_frame(fmt_ctx, pkt)) {
2947  if (fmt_ctx->nb_streams > nb_streams) {
2952  }
2955  int64_t pts = pkt->pts != AV_NOPTS_VALUE ? pkt->pts : pkt->dts;
2956 
2957  if (pts != AV_NOPTS_VALUE)
2958  *cur_ts = av_rescale_q(pts, tb, AV_TIME_BASE_Q);
2959 
2960  if (!has_start && *cur_ts != AV_NOPTS_VALUE) {
2961  start = *cur_ts;
2962  has_start = 1;
2963  }
2964 
2965  if (has_start && !has_end && interval->end_is_offset) {
2966  end = start + interval->end;
2967  has_end = 1;
2968  }
2969 
2970  if (interval->end_is_offset && interval->duration_frames) {
2971  if (frame_count >= interval->end)
2972  break;
2973  } else if (has_end && *cur_ts != AV_NOPTS_VALUE && *cur_ts >= end) {
2974  break;
2975  }
2976 
2977  frame_count++;
2978  if (do_read_packets) {
2979  if (do_show_packets)
2980  show_packet(w, ifile, pkt, i++);
2982  }
2983  if (do_read_frames) {
2984  int packet_new = 1;
2985  FrameData *fd;
2986 
2987  pkt->opaque_ref = av_buffer_allocz(sizeof(*fd));
2988  if (!pkt->opaque_ref) {
2989  ret = AVERROR(ENOMEM);
2990  goto end;
2991  }
2992  fd = (FrameData*)pkt->opaque_ref->data;
2993  fd->pkt_pos = pkt->pos;
2994  fd->pkt_size = pkt->size;
2995 
2996  while (process_frame(w, ifile, frame, pkt, &packet_new) > 0);
2997  }
2998  }
3000  }
3002  //Flush remaining frames that are cached in the decoder
3003  for (i = 0; i < ifile->nb_streams; i++) {
3004  pkt->stream_index = i;
3005  if (do_read_frames) {
3006  while (process_frame(w, ifile, frame, pkt, &(int){1}) > 0);
3007  if (ifile->streams[i].dec_ctx)
3009  }
3010  }
3011 
3012 end:
3013  av_frame_free(&frame);
3014  av_packet_free(&pkt);
3015  if (ret < 0) {
3016  av_log(NULL, AV_LOG_ERROR, "Could not read packets in interval ");
3017  log_read_interval(interval, NULL, AV_LOG_ERROR);
3018  }
3019  return ret;
3020 }
3021 
3023 {
3024  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
3025  int i, ret = 0;
3026  int64_t cur_ts = fmt_ctx->start_time;
3027 
3028  if (read_intervals_nb == 0) {
3029  ReadInterval interval = (ReadInterval) { .has_start = 0, .has_end = 0 };
3030  ret = read_interval_packets(w, ifile, &interval, &cur_ts);
3031  } else {
3032  for (i = 0; i < read_intervals_nb; i++) {
3033  ret = read_interval_packets(w, ifile, &read_intervals[i], &cur_ts);
3034  if (ret < 0)
3035  break;
3036  }
3037  }
3038 
3039  return ret;
3040 }
3041 
3042 static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx, InputStream *ist, int in_program)
3043 {
3044  AVStream *stream = ist->st;
3045  AVCodecParameters *par;
3047  char val_str[128];
3048  const char *s;
3049  AVRational sar, dar;
3050  AVBPrint pbuf;
3051  const AVCodecDescriptor *cd;
3052  int ret = 0;
3053  const char *profile = NULL;
3054 
3056 
3058 
3059  print_int("index", stream->index);
3060 
3061  par = stream->codecpar;
3062  dec_ctx = ist->dec_ctx;
3063  if (cd = avcodec_descriptor_get(par->codec_id)) {
3064  print_str("codec_name", cd->name);
3065  if (!do_bitexact) {
3066  print_str("codec_long_name",
3067  cd->long_name ? cd->long_name : "unknown");
3068  }
3069  } else {
3070  print_str_opt("codec_name", "unknown");
3071  if (!do_bitexact) {
3072  print_str_opt("codec_long_name", "unknown");
3073  }
3074  }
3075 
3076  if (!do_bitexact && (profile = avcodec_profile_name(par->codec_id, par->profile)))
3077  print_str("profile", profile);
3078  else {
3079  if (par->profile != AV_PROFILE_UNKNOWN) {
3080  char profile_num[12];
3081  snprintf(profile_num, sizeof(profile_num), "%d", par->profile);
3082  print_str("profile", profile_num);
3083  } else
3084  print_str_opt("profile", "unknown");
3085  }
3086 
3088  if (s) print_str ("codec_type", s);
3089  else print_str_opt("codec_type", "unknown");
3090 
3091  /* print AVI/FourCC tag */
3092  print_str("codec_tag_string", av_fourcc2str(par->codec_tag));
3093  print_fmt("codec_tag", "0x%04"PRIx32, par->codec_tag);
3094 
3095  switch (par->codec_type) {
3096  case AVMEDIA_TYPE_VIDEO:
3097  print_int("width", par->width);
3098  print_int("height", par->height);
3099  if (dec_ctx) {
3100  print_int("coded_width", dec_ctx->coded_width);
3101  print_int("coded_height", dec_ctx->coded_height);
3104  }
3105  print_int("has_b_frames", par->video_delay);
3106  sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);
3107  if (sar.num) {
3108  print_q("sample_aspect_ratio", sar, ':');
3109  av_reduce(&dar.num, &dar.den,
3110  par->width * sar.num,
3111  par->height * sar.den,
3112  1024*1024);
3113  print_q("display_aspect_ratio", dar, ':');
3114  } else {
3115  print_str_opt("sample_aspect_ratio", "N/A");
3116  print_str_opt("display_aspect_ratio", "N/A");
3117  }
3118  s = av_get_pix_fmt_name(par->format);
3119  if (s) print_str ("pix_fmt", s);
3120  else print_str_opt("pix_fmt", "unknown");
3121  print_int("level", par->level);
3122 
3125  print_color_trc(w, par->color_trc);
3128 
3129  if (par->field_order == AV_FIELD_PROGRESSIVE)
3130  print_str("field_order", "progressive");
3131  else if (par->field_order == AV_FIELD_TT)
3132  print_str("field_order", "tt");
3133  else if (par->field_order == AV_FIELD_BB)
3134  print_str("field_order", "bb");
3135  else if (par->field_order == AV_FIELD_TB)
3136  print_str("field_order", "tb");
3137  else if (par->field_order == AV_FIELD_BT)
3138  print_str("field_order", "bt");
3139  else
3140  print_str_opt("field_order", "unknown");
3141 
3142  if (dec_ctx)
3143  print_int("refs", dec_ctx->refs);
3144  break;
3145 
3146  case AVMEDIA_TYPE_AUDIO:
3148  if (s) print_str ("sample_fmt", s);
3149  else print_str_opt("sample_fmt", "unknown");
3150  print_val("sample_rate", par->sample_rate, unit_hertz_str);
3151  print_int("channels", par->ch_layout.nb_channels);
3152 
3153  if (par->ch_layout.order != AV_CHANNEL_ORDER_UNSPEC) {
3154  av_channel_layout_describe(&par->ch_layout, val_str, sizeof(val_str));
3155  print_str ("channel_layout", val_str);
3156  } else {
3157  print_str_opt("channel_layout", "unknown");
3158  }
3159 
3160  print_int("bits_per_sample", av_get_bits_per_sample(par->codec_id));
3161 
3162  print_int("initial_padding", par->initial_padding);
3163  break;
3164 
3165  case AVMEDIA_TYPE_SUBTITLE:
3166  if (par->width)
3167  print_int("width", par->width);
3168  else
3169  print_str_opt("width", "N/A");
3170  if (par->height)
3171  print_int("height", par->height);
3172  else
3173  print_str_opt("height", "N/A");
3174  break;
3175  }
3176 
3177  if (show_private_data) {
3178  if (dec_ctx && dec_ctx->codec->priv_class)
3180  if (fmt_ctx->iformat->priv_class)
3182  }
3183 
3184  if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt ("id", "0x%x", stream->id);
3185  else print_str_opt("id", "N/A");
3186  print_q("r_frame_rate", stream->r_frame_rate, '/');
3187  print_q("avg_frame_rate", stream->avg_frame_rate, '/');
3188  print_q("time_base", stream->time_base, '/');
3189  print_ts ("start_pts", stream->start_time);
3190  print_time("start_time", stream->start_time, &stream->time_base);
3191  print_ts ("duration_ts", stream->duration);
3192  print_time("duration", stream->duration, &stream->time_base);
3193  if (par->bit_rate > 0) print_val ("bit_rate", par->bit_rate, unit_bit_per_second_str);
3194  else print_str_opt("bit_rate", "N/A");
3195  if (dec_ctx && dec_ctx->rc_max_rate > 0)
3197  else
3198  print_str_opt("max_bit_rate", "N/A");
3199  if (dec_ctx && dec_ctx->bits_per_raw_sample > 0) print_fmt("bits_per_raw_sample", "%d", dec_ctx->bits_per_raw_sample);
3200  else print_str_opt("bits_per_raw_sample", "N/A");
3201  if (stream->nb_frames) print_fmt ("nb_frames", "%"PRId64, stream->nb_frames);
3202  else print_str_opt("nb_frames", "N/A");
3203  if (nb_streams_frames[stream_idx]) print_fmt ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);
3204  else print_str_opt("nb_read_frames", "N/A");
3205  if (nb_streams_packets[stream_idx]) print_fmt ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);
3206  else print_str_opt("nb_read_packets", "N/A");
3207  if (do_show_data)
3208  writer_print_data(w, "extradata", par->extradata,
3209  par->extradata_size);
3210 
3211  if (par->extradata_size > 0) {
3212  print_int("extradata_size", par->extradata_size);
3213  writer_print_data_hash(w, "extradata_hash", par->extradata,
3214  par->extradata_size);
3215  }
3216 
3217  /* Print disposition information */
3218 #define PRINT_DISPOSITION(flagname, name) do { \
3219  print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \
3220  } while (0)
3221 
3224  PRINT_DISPOSITION(DEFAULT, "default");
3225  PRINT_DISPOSITION(DUB, "dub");
3226  PRINT_DISPOSITION(ORIGINAL, "original");
3227  PRINT_DISPOSITION(COMMENT, "comment");
3228  PRINT_DISPOSITION(LYRICS, "lyrics");
3229  PRINT_DISPOSITION(KARAOKE, "karaoke");
3230  PRINT_DISPOSITION(FORCED, "forced");
3231  PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");
3232  PRINT_DISPOSITION(VISUAL_IMPAIRED, "visual_impaired");
3233  PRINT_DISPOSITION(CLEAN_EFFECTS, "clean_effects");
3234  PRINT_DISPOSITION(ATTACHED_PIC, "attached_pic");
3235  PRINT_DISPOSITION(TIMED_THUMBNAILS, "timed_thumbnails");
3236  PRINT_DISPOSITION(NON_DIEGETIC, "non_diegetic");
3237  PRINT_DISPOSITION(CAPTIONS, "captions");
3238  PRINT_DISPOSITION(DESCRIPTIONS, "descriptions");
3239  PRINT_DISPOSITION(METADATA, "metadata");
3240  PRINT_DISPOSITION(DEPENDENT, "dependent");
3241  PRINT_DISPOSITION(STILL_IMAGE, "still_image");
3243  }
3244 
3245  if (do_show_stream_tags)
3247 
3248  if (stream->codecpar->nb_coded_side_data) {
3250  for (int i = 0; i < stream->codecpar->nb_coded_side_data; i++) {
3251  print_pkt_side_data(w, stream->codecpar, &stream->codecpar->coded_side_data[i],
3254  }
3256  }
3257 
3259  av_bprint_finalize(&pbuf, NULL);
3260  fflush(stdout);
3261 
3262  return ret;
3263 }
3264 
3266 {
3267  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
3268  int i, ret = 0;
3269 
3271  for (i = 0; i < ifile->nb_streams; i++)
3272  if (selected_streams[i]) {
3273  ret = show_stream(w, fmt_ctx, i, &ifile->streams[i], 0);
3274  if (ret < 0)
3275  break;
3276  }
3278 
3279  return ret;
3280 }
3281 
3283 {
3284  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
3285  int i, ret = 0;
3286 
3288  print_int("program_id", program->id);
3289  print_int("program_num", program->program_num);
3290  print_int("nb_streams", program->nb_stream_indexes);
3291  print_int("pmt_pid", program->pmt_pid);
3292  print_int("pcr_pid", program->pcr_pid);
3295  if (ret < 0)
3296  goto end;
3297 
3299  for (i = 0; i < program->nb_stream_indexes; i++) {
3300  if (selected_streams[program->stream_index[i]]) {
3301  ret = show_stream(w, fmt_ctx, program->stream_index[i], &ifile->streams[program->stream_index[i]], 1);
3302  if (ret < 0)
3303  break;
3304  }
3305  }
3307 
3308 end:
3310  return ret;
3311 }
3312 
3314 {
3315  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
3316  int i, ret = 0;
3317 
3319  for (i = 0; i < fmt_ctx->nb_programs; i++) {
3321  if (!program)
3322  continue;
3323  ret = show_program(w, ifile, program);
3324  if (ret < 0)
3325  break;
3326  }
3328  return ret;
3329 }
3330 
3332 {
3333  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
3334  int i, ret = 0;
3335 
3337  for (i = 0; i < fmt_ctx->nb_chapters; i++) {
3338  AVChapter *chapter = fmt_ctx->chapters[i];
3339 
3341  print_int("id", chapter->id);
3342  print_q ("time_base", chapter->time_base, '/');
3343  print_int("start", chapter->start);
3344  print_time("start_time", chapter->start, &chapter->time_base);
3345  print_int("end", chapter->end);
3346  print_time("end_time", chapter->end, &chapter->time_base);
3350  }
3352 
3353  return ret;
3354 }
3355 
3356 static int show_format(WriterContext *w, InputFile *ifile)
3357 {
3358  AVFormatContext *fmt_ctx = ifile->fmt_ctx;
3359  char val_str[128];
3360  int64_t size = fmt_ctx->pb ? avio_size(fmt_ctx->pb) : -1;
3361  int ret = 0;
3362 
3364  print_str_validate("filename", fmt_ctx->url);
3365  print_int("nb_streams", fmt_ctx->nb_streams);
3366  print_int("nb_programs", fmt_ctx->nb_programs);
3367  print_str("format_name", fmt_ctx->iformat->name);
3368  if (!do_bitexact) {
3369  if (fmt_ctx->iformat->long_name) print_str ("format_long_name", fmt_ctx->iformat->long_name);
3370  else print_str_opt("format_long_name", "unknown");
3371  }
3372  print_time("start_time", fmt_ctx->start_time, &AV_TIME_BASE_Q);
3373  print_time("duration", fmt_ctx->duration, &AV_TIME_BASE_Q);
3374  if (size >= 0) print_val ("size", size, unit_byte_str);
3375  else print_str_opt("size", "N/A");
3377  else print_str_opt("bit_rate", "N/A");
3378  print_int("probe_score", fmt_ctx->probe_score);
3379  if (do_show_format_tags)
3381 
3383  fflush(stdout);
3384  return ret;
3385 }
3386 
3387 static void show_error(WriterContext *w, int err)
3388 {
3390  print_int("code", err);
3391  print_str("string", av_err2str(err));
3393 }
3394 
3395 static int open_input_file(InputFile *ifile, const char *filename,
3396  const char *print_filename)
3397 {
3398  int err, i;
3400  const AVDictionaryEntry *t = NULL;
3401  int scan_all_pmts_set = 0;
3402 
3404  if (!fmt_ctx)
3405  return AVERROR(ENOMEM);
3406 
3407  if (!av_dict_get(format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE)) {
3408  av_dict_set(&format_opts, "scan_all_pmts", "1", AV_DICT_DONT_OVERWRITE);
3409  scan_all_pmts_set = 1;
3410  }
3411  if ((err = avformat_open_input(&fmt_ctx, filename,
3412  iformat, &format_opts)) < 0) {
3413  print_error(filename, err);
3414  return err;
3415  }
3416  if (print_filename) {
3417  av_freep(&fmt_ctx->url);
3418  fmt_ctx->url = av_strdup(print_filename);
3419  }
3420  ifile->fmt_ctx = fmt_ctx;
3421  if (scan_all_pmts_set)
3422  av_dict_set(&format_opts, "scan_all_pmts", NULL, AV_DICT_MATCH_CASE);
3423  while ((t = av_dict_iterate(format_opts, t)))
3424  av_log(NULL, AV_LOG_WARNING, "Option %s skipped - not known to demuxer.\n", t->key);
3425 
3426  if (find_stream_info) {
3427  AVDictionary **opts;
3428  int orig_nb_streams = fmt_ctx->nb_streams;
3429 
3431  if (err < 0)
3432  return err;
3433 
3435 
3436  for (i = 0; i < orig_nb_streams; i++)
3437  av_dict_free(&opts[i]);
3438  av_freep(&opts);
3439 
3440  if (err < 0) {
3441  print_error(filename, err);
3442  return err;
3443  }
3444  }
3445 
3446  av_dump_format(fmt_ctx, 0, filename, 0);
3447 
3448  ifile->streams = av_calloc(fmt_ctx->nb_streams, sizeof(*ifile->streams));
3449  if (!ifile->streams)
3450  exit(1);
3451  ifile->nb_streams = fmt_ctx->nb_streams;
3452 
3453  /* bind a decoder to each input stream */
3454  for (i = 0; i < fmt_ctx->nb_streams; i++) {
3455  InputStream *ist = &ifile->streams[i];
3456  AVStream *stream = fmt_ctx->streams[i];
3457  const AVCodec *codec;
3458 
3459  ist->st = stream;
3460 
3461  if (stream->codecpar->codec_id == AV_CODEC_ID_PROBE) {
3463  "Failed to probe codec for input stream %d\n",
3464  stream->index);
3465  continue;
3466  }
3467 
3468  codec = avcodec_find_decoder(stream->codecpar->codec_id);
3469  if (!codec) {
3471  "Unsupported codec with id %d for input stream %d\n",
3472  stream->codecpar->codec_id, stream->index);
3473  continue;
3474  }
3475  {
3476  AVDictionary *opts;
3477 
3479  fmt_ctx, stream, codec, &opts);
3480  if (err < 0)
3481  exit(1);
3482 
3483  ist->dec_ctx = avcodec_alloc_context3(codec);
3484  if (!ist->dec_ctx)
3485  exit(1);
3486 
3487  err = avcodec_parameters_to_context(ist->dec_ctx, stream->codecpar);
3488  if (err < 0)
3489  exit(1);
3490 
3491  if (do_show_log) {
3492  // For loging it is needed to disable at least frame threads as otherwise
3493  // the log information would need to be reordered and matches up to contexts and frames
3494  // That is in fact possible but not trivial
3495  av_dict_set(&codec_opts, "threads", "1", 0);
3496  }
3497 
3498  av_dict_set(&opts, "flags", "+copy_opaque", AV_DICT_MULTIKEY);
3499 
3500  ist->dec_ctx->pkt_timebase = stream->time_base;
3501 
3502  if (avcodec_open2(ist->dec_ctx, codec, &opts) < 0) {
3503  av_log(NULL, AV_LOG_WARNING, "Could not open codec for input stream %d\n",
3504  stream->index);
3505  exit(1);
3506  }
3507 
3508  if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
3509  av_log(NULL, AV_LOG_ERROR, "Option %s for input stream %d not found\n",
3510  t->key, stream->index);
3511  return AVERROR_OPTION_NOT_FOUND;
3512  }
3513  }
3514  }
3515 
3516  ifile->fmt_ctx = fmt_ctx;
3517  return 0;
3518 }
3519 
3520 static void close_input_file(InputFile *ifile)
3521 {
3522  int i;
3523 
3524  /* close decoder for each stream */
3525  for (i = 0; i < ifile->nb_streams; i++)
3527 
3528  av_freep(&ifile->streams);
3529  ifile->nb_streams = 0;
3530 
3531  avformat_close_input(&ifile->fmt_ctx);
3532 }
3533 
3534 static int probe_file(WriterContext *wctx, const char *filename,
3535  const char *print_filename)
3536 {
3537  InputFile ifile = { 0 };
3538  int ret, i;
3539  int section_id;
3540 
3543 
3544  ret = open_input_file(&ifile, filename, print_filename);
3545  if (ret < 0)
3546  goto end;
3547 
3548 #define CHECK_END if (ret < 0) goto end
3549 
3550  nb_streams = ifile.fmt_ctx->nb_streams;
3554 
3555  for (i = 0; i < ifile.fmt_ctx->nb_streams; i++) {
3556  if (stream_specifier) {
3558  ifile.fmt_ctx->streams[i],
3560  CHECK_END;
3561  else
3562  selected_streams[i] = ret;
3563  ret = 0;
3564  } else {
3565  selected_streams[i] = 1;
3566  }
3567  if (!selected_streams[i])
3568  ifile.fmt_ctx->streams[i]->discard = AVDISCARD_ALL;
3569  }
3570 
3574  section_id = SECTION_ID_PACKETS_AND_FRAMES;
3575  else if (do_show_packets && !do_show_frames)
3576  section_id = SECTION_ID_PACKETS;
3577  else // (!do_show_packets && do_show_frames)
3578  section_id = SECTION_ID_FRAMES;
3580  writer_print_section_header(wctx, NULL, section_id);
3581  ret = read_packets(wctx, &ifile);
3584  CHECK_END;
3585  }
3586 
3587  if (do_show_programs) {
3588  ret = show_programs(wctx, &ifile);
3589  CHECK_END;
3590  }
3591 
3592  if (do_show_streams) {
3593  ret = show_streams(wctx, &ifile);
3594  CHECK_END;
3595  }
3596  if (do_show_chapters) {
3597  ret = show_chapters(wctx, &ifile);
3598  CHECK_END;
3599  }
3600  if (do_show_format) {
3601  ret = show_format(wctx, &ifile);
3602  CHECK_END;
3603  }
3604 
3605 end:
3606  if (ifile.fmt_ctx)
3607  close_input_file(&ifile);
3611 
3612  return ret;
3613 }
3614 
3615 static void show_usage(void)
3616 {
3617  av_log(NULL, AV_LOG_INFO, "Simple multimedia streams analyzer\n");
3618  av_log(NULL, AV_LOG_INFO, "usage: %s [OPTIONS] INPUT_FILE\n", program_name);
3619  av_log(NULL, AV_LOG_INFO, "\n");
3620 }
3621 
3623 {
3624  AVBPrint pbuf;
3626 
3628  print_str("version", FFMPEG_VERSION);
3629  print_fmt("copyright", "Copyright (c) %d-%d the FFmpeg developers",
3630  program_birth_year, CONFIG_THIS_YEAR);
3631  print_str("compiler_ident", CC_IDENT);
3632  print_str("configuration", FFMPEG_CONFIGURATION);
3634 
3635  av_bprint_finalize(&pbuf, NULL);
3636 }
3637 
3638 #define SHOW_LIB_VERSION(libname, LIBNAME) \
3639  do { \
3640  if (CONFIG_##LIBNAME) { \
3641  unsigned int version = libname##_version(); \
3642  writer_print_section_header(w, NULL, SECTION_ID_LIBRARY_VERSION); \
3643  print_str("name", "lib" #libname); \
3644  print_int("major", LIB##LIBNAME##_VERSION_MAJOR); \
3645  print_int("minor", LIB##LIBNAME##_VERSION_MINOR); \
3646  print_int("micro", LIB##LIBNAME##_VERSION_MICRO); \
3647  print_int("version", version); \
3648  print_str("ident", LIB##LIBNAME##_IDENT); \
3649  writer_print_section_footer(w); \
3650  } \
3651  } while (0)
3652 
3654 {
3656  SHOW_LIB_VERSION(avutil, AVUTIL);
3657  SHOW_LIB_VERSION(avcodec, AVCODEC);
3658  SHOW_LIB_VERSION(avformat, AVFORMAT);
3659  SHOW_LIB_VERSION(avdevice, AVDEVICE);
3660  SHOW_LIB_VERSION(avfilter, AVFILTER);
3661  SHOW_LIB_VERSION(swscale, SWSCALE);
3662  SHOW_LIB_VERSION(swresample, SWRESAMPLE);
3663  SHOW_LIB_VERSION(postproc, POSTPROC);
3665 }
3666 
3667 #define PRINT_PIX_FMT_FLAG(flagname, name) \
3668  do { \
3669  print_int(name, !!(pixdesc->flags & AV_PIX_FMT_FLAG_##flagname)); \
3670  } while (0)
3671 
3673 {
3674  const AVPixFmtDescriptor *pixdesc = NULL;
3675  int i, n;
3676 
3678  while (pixdesc = av_pix_fmt_desc_next(pixdesc)) {
3680  print_str("name", pixdesc->name);
3681  print_int("nb_components", pixdesc->nb_components);
3682  if ((pixdesc->nb_components >= 3) && !(pixdesc->flags & AV_PIX_FMT_FLAG_RGB)) {
3683  print_int ("log2_chroma_w", pixdesc->log2_chroma_w);
3684  print_int ("log2_chroma_h", pixdesc->log2_chroma_h);
3685  } else {
3686  print_str_opt("log2_chroma_w", "N/A");
3687  print_str_opt("log2_chroma_h", "N/A");
3688  }
3689  n = av_get_bits_per_pixel(pixdesc);
3690  if (n) print_int ("bits_per_pixel", n);
3691  else print_str_opt("bits_per_pixel", "N/A");
3694  PRINT_PIX_FMT_FLAG(BE, "big_endian");
3695  PRINT_PIX_FMT_FLAG(PAL, "palette");
3696  PRINT_PIX_FMT_FLAG(BITSTREAM, "bitstream");
3697  PRINT_PIX_FMT_FLAG(HWACCEL, "hwaccel");
3698  PRINT_PIX_FMT_FLAG(PLANAR, "planar");
3699  PRINT_PIX_FMT_FLAG(RGB, "rgb");
3700  PRINT_PIX_FMT_FLAG(ALPHA, "alpha");
3702  }
3703  if (do_show_pixel_format_components && (pixdesc->nb_components > 0)) {
3705  for (i = 0; i < pixdesc->nb_components; i++) {
3707  print_int("index", i + 1);
3708  print_int("bit_depth", pixdesc->comp[i].depth);
3710  }
3712  }
3714  }
3716 }
3717 
3718 static int opt_show_optional_fields(void *optctx, const char *opt, const char *arg)
3719 {
3723 
3725  double num;
3726  int ret = parse_number("show_optional_fields", arg, OPT_TYPE_INT,
3728  if (ret < 0)
3729  return ret;
3730  show_optional_fields = num;
3731  }
3732  return 0;
3733 }
3734 
3735 static int opt_format(void *optctx, const char *opt, const char *arg)
3736 {
3738  if (!iformat) {
3739  av_log(NULL, AV_LOG_ERROR, "Unknown input format: %s\n", arg);
3740  return AVERROR(EINVAL);
3741  }
3742  return 0;
3743 }
3744 
3745 static inline void mark_section_show_entries(SectionID section_id,
3746  int show_all_entries, AVDictionary *entries)
3747 {
3748  struct section *section = &sections[section_id];
3749 
3751  if (show_all_entries) {
3752  for (const SectionID *id = section->children_ids; *id != -1; id++)
3754  } else {
3755  av_dict_copy(&section->entries_to_show, entries, 0);
3756  }
3757 }
3758 
3759 static int match_section(const char *section_name,
3760  int show_all_entries, AVDictionary *entries)
3761 {
3762  int i, ret = 0;
3763 
3764  for (i = 0; i < FF_ARRAY_ELEMS(sections); i++) {
3765  const struct section *section = &sections[i];
3766  if (!strcmp(section_name, section->name) ||
3767  (section->unique_name && !strcmp(section_name, section->unique_name))) {
3769  "'%s' matches section with unique name '%s'\n", section_name,
3771  ret++;
3773  }
3774  }
3775  return ret;
3776 }
3777 
3778 static int opt_show_entries(void *optctx, const char *opt, const char *arg)
3779 {
3780  const char *p = arg;
3781  int ret = 0;
3782 
3783  while (*p) {
3784  AVDictionary *entries = NULL;
3785  char *section_name = av_get_token(&p, "=:");
3786  int show_all_entries = 0;
3787 
3788  if (!section_name) {
3790  "Missing section name for option '%s'\n", opt);
3791  return AVERROR(EINVAL);
3792  }
3793 
3794  if (*p == '=') {
3795  p++;
3796  while (*p && *p != ':') {
3797  char *entry = av_get_token(&p, ",:");
3798  if (!entry)
3799  break;
3801  "Adding '%s' to the entries to show in section '%s'\n",
3802  entry, section_name);
3803  av_dict_set(&entries, entry, "", AV_DICT_DONT_STRDUP_KEY);
3804  if (*p == ',')
3805  p++;
3806  }
3807  } else {
3808  show_all_entries = 1;
3809  }
3810 
3811  ret = match_section(section_name, show_all_entries, entries);
3812  if (ret == 0) {
3813  av_log(NULL, AV_LOG_ERROR, "No match for section '%s'\n", section_name);
3814  ret = AVERROR(EINVAL);
3815  }
3816  av_dict_free(&entries);
3817  av_free(section_name);
3818 
3819  if (ret <= 0)
3820  break;
3821  if (*p)
3822  p++;
3823  }
3824 
3825  return ret;
3826 }
3827 
3828 static int opt_input_file(void *optctx, const char *arg)
3829 {
3830  if (input_filename) {
3832  "Argument '%s' provided as input filename, but '%s' was already specified.\n",
3833  arg, input_filename);
3834  return AVERROR(EINVAL);
3835  }
3836  if (!strcmp(arg, "-"))
3837  arg = "fd:";
3839  if (!input_filename)
3840  return AVERROR(ENOMEM);
3841 
3842  return 0;
3843 }
3844 
3845 static int opt_input_file_i(void *optctx, const char *opt, const char *arg)
3846 {
3847  opt_input_file(optctx, arg);
3848  return 0;
3849 }
3850 
3851 static int opt_output_file_o(void *optctx, const char *opt, const char *arg)
3852 {
3853  if (output_filename) {
3855  "Argument '%s' provided as output filename, but '%s' was already specified.\n",
3856  arg, output_filename);
3857  return AVERROR(EINVAL);
3858  }
3859  if (!strcmp(arg, "-"))
3860  arg = "fd:";
3862  if (!output_filename)
3863  return AVERROR(ENOMEM);
3864 
3865  return 0;
3866 }
3867 
3868 static int opt_print_filename(void *optctx, const char *opt, const char *arg)
3869 {
3872  return print_input_filename ? 0 : AVERROR(ENOMEM);
3873 }
3874 
3875 void show_help_default(const char *opt, const char *arg)
3876 {
3878  show_usage();
3879  show_help_options(options, "Main options:", 0, 0);
3880  printf("\n");
3881 
3884 }
3885 
3886 /**
3887  * Parse interval specification, according to the format:
3888  * INTERVAL ::= [START|+START_OFFSET][%[END|+END_OFFSET]]
3889  * INTERVALS ::= INTERVAL[,INTERVALS]
3890 */
3891 static int parse_read_interval(const char *interval_spec,
3892  ReadInterval *interval)
3893 {
3894  int ret = 0;
3895  char *next, *p, *spec = av_strdup(interval_spec);
3896  if (!spec)
3897  return AVERROR(ENOMEM);
3898 
3899  if (!*spec) {
3900  av_log(NULL, AV_LOG_ERROR, "Invalid empty interval specification\n");
3901  ret = AVERROR(EINVAL);
3902  goto end;
3903  }
3904 
3905  p = spec;
3906  next = strchr(spec, '%');
3907  if (next)
3908  *next++ = 0;
3909 
3910  /* parse first part */
3911  if (*p) {
3912  interval->has_start = 1;
3913 
3914  if (*p == '+') {
3915  interval->start_is_offset = 1;
3916  p++;
3917  } else {
3918  interval->start_is_offset = 0;
3919  }
3920 
3921  ret = av_parse_time(&interval->start, p, 1);
3922  if (ret < 0) {
3923  av_log(NULL, AV_LOG_ERROR, "Invalid interval start specification '%s'\n", p);
3924  goto end;
3925  }
3926  } else {
3927  interval->has_start = 0;
3928  }
3929 
3930  /* parse second part */
3931  p = next;
3932  if (p && *p) {
3933  int64_t us;
3934  interval->has_end = 1;
3935 
3936  if (*p == '+') {
3937  interval->end_is_offset = 1;
3938  p++;
3939  } else {
3940  interval->end_is_offset = 0;
3941  }
3942 
3943  if (interval->end_is_offset && *p == '#') {
3944  long long int lli;
3945  char *tail;
3946  interval->duration_frames = 1;
3947  p++;
3948  lli = strtoll(p, &tail, 10);
3949  if (*tail || lli < 0) {
3951  "Invalid or negative value '%s' for duration number of frames\n", p);
3952  goto end;
3953  }
3954  interval->end = lli;
3955  } else {
3956  interval->duration_frames = 0;
3957  ret = av_parse_time(&us, p, 1);
3958  if (ret < 0) {
3959  av_log(NULL, AV_LOG_ERROR, "Invalid interval end/duration specification '%s'\n", p);
3960  goto end;
3961  }
3962  interval->end = us;
3963  }
3964  } else {
3965  interval->has_end = 0;
3966  }
3967 
3968 end:
3969  av_free(spec);
3970  return ret;
3971 }
3972 
3973 static int parse_read_intervals(const char *intervals_spec)
3974 {
3975  int ret, n, i;
3976  char *p, *spec = av_strdup(intervals_spec);
3977  if (!spec)
3978  return AVERROR(ENOMEM);
3979 
3980  /* preparse specification, get number of intervals */
3981  for (n = 0, p = spec; *p; p++)
3982  if (*p == ',')
3983  n++;
3984  n++;
3985 
3987  if (!read_intervals) {
3988  ret = AVERROR(ENOMEM);
3989  goto end;
3990  }
3991  read_intervals_nb = n;
3992 
3993  /* parse intervals */
3994  p = spec;
3995  for (i = 0; p; i++) {
3996  char *next;
3997 
3999  next = strchr(p, ',');
4000  if (next)
4001  *next++ = 0;
4002 
4003  read_intervals[i].id = i;
4005  if (ret < 0) {