You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3644 lines
131KB

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