FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/internal.h
Date: 2022-11-26 13:19:19
Exec Total Coverage
Lines: 6 6 100.0%
Branches: 0 0 -%

Line Branch Exec Source
1 /*
2 * copyright (c) 2001 Fabrice Bellard
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 #ifndef AVFORMAT_INTERNAL_H
22 #define AVFORMAT_INTERNAL_H
23
24 #include <stdint.h>
25
26 #include "libavcodec/packet_internal.h"
27
28 #include "avformat.h"
29 #include "os_support.h"
30
31 #define MAX_URL_SIZE 4096
32
33 /** size of probe buffer, for guessing file type from file contents */
34 #define PROBE_BUF_MIN 2048
35 #define PROBE_BUF_MAX (1 << 20)
36
37 #ifdef DEBUG
38 # define hex_dump_debug(class, buf, size) av_hex_dump_log(class, AV_LOG_DEBUG, buf, size)
39 #else
40 # define hex_dump_debug(class, buf, size) do { if (0) av_hex_dump_log(class, AV_LOG_DEBUG, buf, size); } while(0)
41 #endif
42
43 /**
44 * For an AVInputFormat with this flag set read_close() needs to be called
45 * by the caller upon read_header() failure.
46 */
47 #define FF_FMT_INIT_CLEANUP (1 << 0)
48
49 typedef struct AVCodecTag {
50 enum AVCodecID id;
51 unsigned int tag;
52 } AVCodecTag;
53
54 typedef struct CodecMime{
55 char str[32];
56 enum AVCodecID id;
57 } CodecMime;
58
59 /*************************************************/
60 /* fractional numbers for exact pts handling */
61
62 /**
63 * The exact value of the fractional number is: 'val + num / den'.
64 * num is assumed to be 0 <= num < den.
65 */
66 typedef struct FFFrac {
67 int64_t val, num, den;
68 } FFFrac;
69
70
71 typedef struct FFFormatContext {
72 /**
73 * The public context.
74 */
75 AVFormatContext pub;
76
77 /**
78 * Number of streams relevant for interleaving.
79 * Muxing only.
80 */
81 int nb_interleaved_streams;
82
83 /**
84 * Whether the timestamp shift offset has already been determined.
85 * -1: disabled, 0: not yet determined, 1: determined.
86 */
87 enum {
88 AVOID_NEGATIVE_TS_DISABLED = -1,
89 AVOID_NEGATIVE_TS_UNKNOWN = 0,
90 AVOID_NEGATIVE_TS_KNOWN = 1,
91 } avoid_negative_ts_status;
92 #define AVOID_NEGATIVE_TS_ENABLED(status) ((status) >= 0)
93
94 /**
95 * The interleavement function in use. Always set for muxers.
96 */
97 int (*interleave_packet)(struct AVFormatContext *s, AVPacket *pkt,
98 int flush, int has_packet);
99
100 /**
101 * This buffer is only needed when packets were already buffered but
102 * not decoded, for example to get the codec parameters in MPEG
103 * streams.
104 */
105 PacketList packet_buffer;
106
107 /* av_seek_frame() support */
108 int64_t data_offset; /**< offset of the first packet */
109
110 /**
111 * Raw packets from the demuxer, prior to parsing and decoding.
112 * This buffer is used for buffering packets until the codec can
113 * be identified, as parsing cannot be done without knowing the
114 * codec.
115 */
116 PacketList raw_packet_buffer;
117 /**
118 * Packets split by the parser get queued here.
119 */
120 PacketList parse_queue;
121 /**
122 * The generic code uses this as a temporary packet
123 * to parse packets or for muxing, especially flushing.
124 * For demuxers, it may also be used for other means
125 * for short periods that are guaranteed not to overlap
126 * with calls to av_read_frame() (or ff_read_packet())
127 * or with each other.
128 * It may be used by demuxers as a replacement for
129 * stack packets (unless they call one of the aforementioned
130 * functions with their own AVFormatContext).
131 * Every user has to ensure that this packet is blank
132 * after using it.
133 */
134 AVPacket *parse_pkt;
135
136 /**
137 * Used to hold temporary packets for the generic demuxing code.
138 * When muxing, it may be used by muxers to hold packets (even
139 * permanent ones).
140 */
141 AVPacket *pkt;
142 /**
143 * Sum of the size of packets in raw_packet_buffer, in bytes.
144 */
145 int raw_packet_buffer_size;
146
147 #if FF_API_COMPUTE_PKT_FIELDS2
148 int missing_ts_warning;
149 #endif
150
151 int inject_global_side_data;
152
153 int avoid_negative_ts_use_pts;
154
155 /**
156 * Timestamp of the end of the shortest stream.
157 */
158 int64_t shortest_end;
159
160 /**
161 * Whether or not avformat_init_output has already been called
162 */
163 int initialized;
164
165 /**
166 * Whether or not avformat_init_output fully initialized streams
167 */
168 int streams_initialized;
169
170 /**
171 * ID3v2 tag useful for MP3 demuxing
172 */
173 AVDictionary *id3v2_meta;
174
175 /*
176 * Prefer the codec framerate for avg_frame_rate computation.
177 */
178 int prefer_codec_framerate;
179
180 /**
181 * Set if chapter ids are strictly monotonic.
182 */
183 int chapter_ids_monotonic;
184
185 /**
186 * Contexts and child contexts do not contain a metadata option
187 */
188 int metafree;
189 } FFFormatContext;
190
191 5832897 static av_always_inline FFFormatContext *ffformatcontext(AVFormatContext *s)
192 {
193 5832897 return (FFFormatContext*)s;
194 }
195
196 typedef struct FFStream {
197 /**
198 * The public context.
199 */
200 AVStream pub;
201
202 /**
203 * Set to 1 if the codec allows reordering, so pts can be different
204 * from dts.
205 */
206 int reorder;
207
208 /**
209 * bitstream filter to run on stream
210 * - encoding: Set by muxer using ff_stream_add_bitstream_filter
211 * - decoding: unused
212 */
213 struct AVBSFContext *bsfc;
214
215 /**
216 * Whether or not check_bitstream should still be run on each packet
217 */
218 int bitstream_checked;
219
220 /**
221 * The codec context used by avformat_find_stream_info, the parser, etc.
222 */
223 struct AVCodecContext *avctx;
224 /**
225 * 1 if avctx has been initialized with the values from the codec parameters
226 */
227 int avctx_inited;
228
229 /* the context for extracting extradata in find_stream_info()
230 * inited=1/bsf=NULL signals that extracting is not possible (codec not
231 * supported) */
232 struct {
233 struct AVBSFContext *bsf;
234 int inited;
235 } extract_extradata;
236
237 /**
238 * Whether the internal avctx needs to be updated from codecpar (after a late change to codecpar)
239 */
240 int need_context_update;
241
242 int is_intra_only;
243
244 FFFrac *priv_pts;
245
246 /**
247 * Stream information used internally by avformat_find_stream_info()
248 */
249 struct FFStreamInfo *info;
250
251 AVIndexEntry *index_entries; /**< Only used if the format does not
252 support seeking natively. */
253 int nb_index_entries;
254 unsigned int index_entries_allocated_size;
255
256 int64_t interleaver_chunk_size;
257 int64_t interleaver_chunk_duration;
258
259 /**
260 * stream probing state
261 * -1 -> probing finished
262 * 0 -> no probing requested
263 * rest -> perform probing with request_probe being the minimum score to accept.
264 */
265 int request_probe;
266 /**
267 * Indicates that everything up to the next keyframe
268 * should be discarded.
269 */
270 int skip_to_keyframe;
271
272 /**
273 * Number of samples to skip at the start of the frame decoded from the next packet.
274 */
275 int skip_samples;
276
277 /**
278 * If not 0, the number of samples that should be skipped from the start of
279 * the stream (the samples are removed from packets with pts==0, which also
280 * assumes negative timestamps do not happen).
281 * Intended for use with formats such as mp3 with ad-hoc gapless audio
282 * support.
283 */
284 int64_t start_skip_samples;
285
286 /**
287 * If not 0, the first audio sample that should be discarded from the stream.
288 * This is broken by design (needs global sample count), but can't be
289 * avoided for broken by design formats such as mp3 with ad-hoc gapless
290 * audio support.
291 */
292 int64_t first_discard_sample;
293
294 /**
295 * The sample after last sample that is intended to be discarded after
296 * first_discard_sample. Works on frame boundaries only. Used to prevent
297 * early EOF if the gapless info is broken (considered concatenated mp3s).
298 */
299 int64_t last_discard_sample;
300
301 /**
302 * Number of internally decoded frames, used internally in libavformat, do not access
303 * its lifetime differs from info which is why it is not in that structure.
304 */
305 int nb_decoded_frames;
306
307 /**
308 * Timestamp offset added to timestamps before muxing
309 */
310 int64_t mux_ts_offset;
311
312 /**
313 * This is the lowest ts allowed in this track; it may be set by the muxer
314 * during init or write_header and influences the automatic timestamp
315 * shifting code.
316 */
317 int64_t lowest_ts_allowed;
318
319 /**
320 * Internal data to check for wrapping of the time stamp
321 */
322 int64_t pts_wrap_reference;
323
324 /**
325 * Options for behavior, when a wrap is detected.
326 *
327 * Defined by AV_PTS_WRAP_ values.
328 *
329 * If correction is enabled, there are two possibilities:
330 * If the first time stamp is near the wrap point, the wrap offset
331 * will be subtracted, which will create negative time stamps.
332 * Otherwise the offset will be added.
333 */
334 int pts_wrap_behavior;
335
336 /**
337 * Internal data to prevent doing update_initial_durations() twice
338 */
339 int update_initial_durations_done;
340
341 #define MAX_REORDER_DELAY 16
342
343 /**
344 * Internal data to generate dts from pts
345 */
346 int64_t pts_reorder_error[MAX_REORDER_DELAY+1];
347 uint8_t pts_reorder_error_count[MAX_REORDER_DELAY+1];
348
349 int64_t pts_buffer[MAX_REORDER_DELAY+1];
350
351 /**
352 * Internal data to analyze DTS and detect faulty mpeg streams
353 */
354 int64_t last_dts_for_order_check;
355 uint8_t dts_ordered;
356 uint8_t dts_misordered;
357
358 /**
359 * Internal data to inject global side data
360 */
361 int inject_global_side_data;
362
363 /**
364 * display aspect ratio (0 if unknown)
365 * - encoding: unused
366 * - decoding: Set by libavformat to calculate sample_aspect_ratio internally
367 */
368 AVRational display_aspect_ratio;
369
370 AVProbeData probe_data;
371
372 /**
373 * last packet in packet_buffer for this stream when muxing.
374 */
375 PacketListEntry *last_in_packet_buffer;
376
377 int64_t last_IP_pts;
378 int last_IP_duration;
379
380 /**
381 * Number of packets to buffer for codec probing
382 */
383 int probe_packets;
384
385 /* av_read_frame() support */
386 enum AVStreamParseType need_parsing;
387 struct AVCodecParserContext *parser;
388
389 /**
390 * Number of frames that have been demuxed during avformat_find_stream_info()
391 */
392 int codec_info_nb_frames;
393
394 /**
395 * Stream Identifier
396 * This is the MPEG-TS stream identifier +1
397 * 0 means unknown
398 */
399 int stream_identifier;
400
401 // Timestamp generation support:
402 /**
403 * Timestamp corresponding to the last dts sync point.
404 *
405 * Initialized when AVCodecParserContext.dts_sync_point >= 0 and
406 * a DTS is received from the underlying container. Otherwise set to
407 * AV_NOPTS_VALUE by default.
408 */
409 int64_t first_dts;
410 int64_t cur_dts;
411 } FFStream;
412
413 11886647 static av_always_inline FFStream *ffstream(AVStream *st)
414 {
415 11886647 return (FFStream*)st;
416 }
417
418 3238774 static av_always_inline const FFStream *cffstream(const AVStream *st)
419 {
420 3238774 return (FFStream*)st;
421 }
422
423 #ifdef __GNUC__
424 #define dynarray_add(tab, nb_ptr, elem)\
425 do {\
426 __typeof__(tab) _tab = (tab);\
427 __typeof__(elem) _elem = (elem);\
428 (void)sizeof(**_tab == _elem); /* check that types are compatible */\
429 av_dynarray_add(_tab, nb_ptr, _elem);\
430 } while(0)
431 #else
432 #define dynarray_add(tab, nb_ptr, elem)\
433 do {\
434 av_dynarray_add((tab), nb_ptr, (elem));\
435 } while(0)
436 #endif
437
438
439 void ff_flush_packet_queue(AVFormatContext *s);
440
441 /**
442 * Automatically create sub-directories
443 *
444 * @param path will create sub-directories by path
445 * @return 0, or < 0 on error
446 */
447 int ff_mkdir_p(const char *path);
448
449 /**
450 * Write hexadecimal string corresponding to given binary data. The string
451 * is zero-terminated.
452 *
453 * @param buf the output string is written here;
454 * needs to be at least 2 * size + 1 bytes long.
455 * @param src the input data to be transformed.
456 * @param size the size (in byte) of src.
457 * @param lowercase determines whether to use the range [0-9a-f] or [0-9A-F].
458 * @return buf.
459 */
460 char *ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase);
461
462 /**
463 * Parse a string of hexadecimal strings. Any space between the hexadecimal
464 * digits is ignored.
465 *
466 * @param data if non-null, the parsed data is written to this pointer
467 * @param p the string to parse
468 * @return the number of bytes written (or to be written, if data is null)
469 */
470 int ff_hex_to_data(uint8_t *data, const char *p);
471
472 #define NTP_OFFSET 2208988800ULL
473 #define NTP_OFFSET_US (NTP_OFFSET * 1000000ULL)
474
475 /** Get the current time since NTP epoch in microseconds. */
476 uint64_t ff_ntp_time(void);
477
478 /**
479 * Get the NTP time stamp formatted as per the RFC-5905.
480 *
481 * @param ntp_time NTP time in micro seconds (since NTP epoch)
482 * @return the formatted NTP time stamp
483 */
484 uint64_t ff_get_formatted_ntp_time(uint64_t ntp_time_us);
485
486 /**
487 * Parse the NTP time in micro seconds (since NTP epoch).
488 *
489 * @param ntp_ts NTP time stamp formatted as per the RFC-5905.
490 * @return the time in micro seconds (since NTP epoch)
491 */
492 uint64_t ff_parse_ntp_time(uint64_t ntp_ts);
493
494 /**
495 * Append the media-specific SDP fragment for the media stream c
496 * to the buffer buff.
497 *
498 * Note, the buffer needs to be initialized, since it is appended to
499 * existing content.
500 *
501 * @param buff the buffer to append the SDP fragment to
502 * @param size the size of the buff buffer
503 * @param st the AVStream of the media to describe
504 * @param idx the global stream index
505 * @param dest_addr the destination address of the media stream, may be NULL
506 * @param dest_type the destination address type, may be NULL
507 * @param port the destination port of the media stream, 0 if unknown
508 * @param ttl the time to live of the stream, 0 if not multicast
509 * @param fmt the AVFormatContext, which might contain options modifying
510 * the generated SDP
511 * @return 0 on success, a negative error code on failure
512 */
513 int ff_sdp_write_media(char *buff, int size, const AVStream *st, int idx,
514 const char *dest_addr, const char *dest_type,
515 int port, int ttl, AVFormatContext *fmt);
516
517 /**
518 * Read a whole line of text from AVIOContext. Stop reading after reaching
519 * either a \\n, a \\0 or EOF. The returned string is always \\0-terminated,
520 * and may be truncated if the buffer is too small.
521 *
522 * @param s the read-only AVIOContext
523 * @param buf buffer to store the read line
524 * @param maxlen size of the buffer
525 * @return the length of the string written in the buffer, not including the
526 * final \\0
527 */
528 int ff_get_line(AVIOContext *s, char *buf, int maxlen);
529
530 /**
531 * Same as ff_get_line but strip the white-space characters in the text tail
532 *
533 * @param s the read-only AVIOContext
534 * @param buf buffer to store the read line
535 * @param maxlen size of the buffer
536 * @return the length of the string written in the buffer
537 */
538 int ff_get_chomp_line(AVIOContext *s, char *buf, int maxlen);
539
540 #define SPACE_CHARS " \t\r\n"
541
542 /**
543 * Callback function type for ff_parse_key_value.
544 *
545 * @param key a pointer to the key
546 * @param key_len the number of bytes that belong to the key, including the '='
547 * char
548 * @param dest return the destination pointer for the value in *dest, may
549 * be null to ignore the value
550 * @param dest_len the length of the *dest buffer
551 */
552 typedef void (*ff_parse_key_val_cb)(void *context, const char *key,
553 int key_len, char **dest, int *dest_len);
554 /**
555 * Parse a string with comma-separated key=value pairs. The value strings
556 * may be quoted and may contain escaped characters within quoted strings.
557 *
558 * @param str the string to parse
559 * @param callback_get_buf function that returns where to store the
560 * unescaped value string.
561 * @param context the opaque context pointer to pass to callback_get_buf
562 */
563 void ff_parse_key_value(const char *str, ff_parse_key_val_cb callback_get_buf,
564 void *context);
565
566 enum AVCodecID ff_guess_image2_codec(const char *filename);
567
568 const AVCodec *ff_find_decoder(AVFormatContext *s, const AVStream *st,
569 enum AVCodecID codec_id);
570
571 /**
572 * Set the time base and wrapping info for a given stream. This will be used
573 * to interpret the stream's timestamps. If the new time base is invalid
574 * (numerator or denominator are non-positive), it leaves the stream
575 * unchanged.
576 *
577 * @param st stream
578 * @param pts_wrap_bits number of bits effectively used by the pts
579 * (used for wrap control)
580 * @param pts_num time base numerator
581 * @param pts_den time base denominator
582 */
583 void avpriv_set_pts_info(AVStream *st, int pts_wrap_bits,
584 unsigned int pts_num, unsigned int pts_den);
585
586 /**
587 * Set the timebase for each stream from the corresponding codec timebase and
588 * print it.
589 */
590 int ff_framehash_write_header(AVFormatContext *s);
591
592 /**
593 * Frees a stream without modifying the corresponding AVFormatContext.
594 * Must only be called if the latter doesn't matter or if the stream
595 * is not yet attached to an AVFormatContext.
596 */
597 void ff_free_stream(AVStream **st);
598 /**
599 * Remove a stream from its AVFormatContext and free it.
600 * The stream must be the last stream of the AVFormatContext.
601 */
602 void ff_remove_stream(AVFormatContext *s, AVStream *st);
603
604 unsigned int ff_codec_get_tag(const AVCodecTag *tags, enum AVCodecID id);
605
606 enum AVCodecID ff_codec_get_id(const AVCodecTag *tags, unsigned int tag);
607
608 int ff_is_intra_only(enum AVCodecID id);
609
610 /**
611 * Select a PCM codec based on the given parameters.
612 *
613 * @param bps bits-per-sample
614 * @param flt floating-point
615 * @param be big-endian
616 * @param sflags signed flags. each bit corresponds to one byte of bit depth.
617 * e.g. the 1st bit indicates if 8-bit should be signed or
618 * unsigned, the 2nd bit indicates if 16-bit should be signed or
619 * unsigned, etc... This is useful for formats such as WAVE where
620 * only 8-bit is unsigned and all other bit depths are signed.
621 * @return a PCM codec id or AV_CODEC_ID_NONE
622 */
623 enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags);
624
625 /**
626 * Copy side data from source to destination stream
627 *
628 * @param dst pointer to destination AVStream
629 * @param src pointer to source AVStream
630 * @return >=0 on success, AVERROR code on error
631 */
632 int ff_stream_side_data_copy(AVStream *dst, const AVStream *src);
633
634 /**
635 * Create a new stream and copy to it all parameters from a source stream, with
636 * the exception of the index field, which is set when the new stream is
637 * created.
638 *
639 * @param dst_ctx pointer to the context in which the new stream is created
640 * @param src pointer to source AVStream
641 * @return pointer to the new stream or NULL on error
642 */
643 AVStream *ff_stream_clone(AVFormatContext *dst_ctx, const AVStream *src);
644
645 /**
646 * Wrap ffurl_move() and log if error happens.
647 *
648 * @param url_src source path
649 * @param url_dst destination path
650 * @return 0 or AVERROR on failure
651 */
652 int ff_rename(const char *url_src, const char *url_dst, void *logctx);
653
654 /**
655 * Allocate extradata with additional AV_INPUT_BUFFER_PADDING_SIZE at end
656 * which is always set to 0.
657 *
658 * Previously allocated extradata in par will be freed.
659 *
660 * @param size size of extradata
661 * @return 0 if OK, AVERROR_xxx on error
662 */
663 int ff_alloc_extradata(AVCodecParameters *par, int size);
664
665 /**
666 * Copies the whilelists from one context to the other
667 */
668 int ff_copy_whiteblacklists(AVFormatContext *dst, const AVFormatContext *src);
669
670 /*
671 * A wrapper around AVFormatContext.io_close that should be used
672 * instead of calling the pointer directly.
673 *
674 * @param s AVFormatContext
675 * @param *pb the AVIOContext to be closed and freed. Can be NULL.
676 * @return >=0 on success, negative AVERROR in case of failure
677 */
678 int ff_format_io_close(AVFormatContext *s, AVIOContext **pb);
679
680 /* Default io_close callback, not to be used directly, use ff_format_io_close
681 * instead. */
682 void ff_format_io_close_default(AVFormatContext *s, AVIOContext *pb);
683
684 /**
685 * Utility function to check if the file uses http or https protocol
686 *
687 * @param s AVFormatContext
688 * @param filename URL or file name to open for writing
689 */
690 int ff_is_http_proto(const char *filename);
691
692 struct AVBPrint;
693 /**
694 * Finalize buf into extradata and set its size appropriately.
695 */
696 int ff_bprint_to_codecpar_extradata(AVCodecParameters *par, struct AVBPrint *buf);
697
698 int ff_lock_avformat(void);
699 int ff_unlock_avformat(void);
700
701 /**
702 * Set AVFormatContext url field to the provided pointer. The pointer must
703 * point to a valid string. The existing url field is freed if necessary. Also
704 * set the legacy filename field to the same string which was provided in url.
705 */
706 void ff_format_set_url(AVFormatContext *s, char *url);
707
708 void avpriv_register_devices(const AVOutputFormat * const o[], const AVInputFormat * const i[]);
709
710 #endif /* AVFORMAT_INTERNAL_H */
711