avcpp 3.1.0
Wrapper for the FFmpeg that simplify usage from C++ projects.
Loading...
Searching...
No Matches
formatcontext.h
Go to the documentation of this file.
1#pragma once
2
9
10#include <memory>
11#include <chrono>
12#include <functional>
13#include <vector>
14
15#include "ffmpeg.h"
16#include "format.h"
17#include "avutils.h"
18#include "stream.h"
19#include "packet.h"
20#include "codec.h"
21#include "dictionary.h"
22#include "averror.h"
23
24#if AVCPP_HAS_AVFORMAT
25
26extern "C" {
27#include <libavformat/avformat.h>
28}
29
30namespace av {
31
39using AvioInterruptCb = std::function<int()>;
40
57{
58 virtual ~CustomIO() {}
59
74 virtual int write(const uint8_t *data, size_t size)
75 {
76 static_cast<void>(data);
77 static_cast<void>(size);
78 return -1;
79 }
80
96 virtual int read(uint8_t *data, size_t size)
97 {
98 static_cast<void>(data);
99 static_cast<void>(size);
100 return -1;
101 }
102
117 virtual int64_t seek(int64_t offset, int whence)
118 {
119 static_cast<void>(offset);
120 static_cast<void>(whence);
121 return -1;
122 }
123
131 virtual int seekable() const { return 0; }
132
138 virtual const char* name() const { return ""; }
139};
140
152class FormatContext : public FFWrapperPtr<AVFormatContext>, public noncopyable
153{
154#if AVCPP_CXX_STANDARD >= 20
155 struct _StreamTransform {
156 const FormatContext *_parent{};
157 Stream operator()(AVStream *st) const {
158 assert(_parent);
159 return Stream{_parent->m_monitor, st, _parent->isOutput() ? Direction::Encoding : Direction::Decoding};
160 }
161 };
162 using StreamsView = std::ranges::transform_view<std::span<AVStream*>, _StreamTransform>;
163#endif
164
165public:
166 FormatContext();
167 ~FormatContext();
168
175 void setSocketTimeout(int64_t timeout);
182
188 void setFormat(const InputFormat& format);
194 void setFormat(const OutputFormat& format);
195
208
214 bool isOutput() const;
220 bool isOpened() const;
221
228 void flush();
235 void close();
241 void dump() const;
242
243 //
244 // Streams
245 //
251 size_t streamsCount() const;
259 Stream stream(size_t idx);
281 [[deprecated("Codec is not used by the FFmpeg API. Use addStream() without codec and point configured codec context after")]]
282 Stream addStream(const Codec &codec, OptionalErrorCode ec = throws());
302 Stream addStream(const class VideoEncoderContext& encCtx, OptionalErrorCode ec = throws());
311 Stream addStream(const class AudioEncoderContext& encCtx, OptionalErrorCode ec = throws());
312
313#if AVCPP_CXX_STANDARD >= 20
321 StreamsView streams(OptionalErrorCode ec = throws()) const;
322#endif
323
324 //
325 // Seeking
326 //
332 bool seekable() const noexcept;
339 void seek(const Timestamp& timestamp, OptionalErrorCode ec = throws());
347 void seek(const Timestamp& timestamp, size_t streamIndex, OptionalErrorCode ec = throws());
356 void seek(const Timestamp& timestamp, bool anyFrame, OptionalErrorCode ec = throws());
365 void seek(const Timestamp& timestamp, size_t streamIndex, bool anyFrame, OptionalErrorCode ec = throws());
366
376 void seek(int64_t position, int streamIndex, int flags, OptionalErrorCode ec = throws());
377
378 //
379 // Other tools
380 //
386 Timestamp startTime() const noexcept;
392 Timestamp duration() const noexcept;
398 void substractStartTime(bool enable);
399
411 int eventFlags() const noexcept;
419 bool eventFlags(int flags) const noexcept;
425 void eventFlagsClear(int flags) noexcept;
426
427 //
428 // Input
429 //
439 void openInput(const std::string& uri, OptionalErrorCode ec = throws());
447 void openInput(const std::string& uri, Dictionary &formatOptions, OptionalErrorCode ec = throws());
455 void openInput(const std::string& uri, Dictionary &&formatOptions, OptionalErrorCode ec = throws());
456
464 void openInput(const std::string& uri, InputFormat format, OptionalErrorCode ec = throws());
473 void openInput(const std::string& uri, Dictionary &formatOptions, InputFormat format, OptionalErrorCode ec = throws());
482 void openInput(const std::string& uri, Dictionary &&formatOptions, InputFormat format, OptionalErrorCode ec = throws());
483
485 static constexpr size_t CUSTOM_IO_DEFAULT_BUFFER_SIZE = 200000;
486
496 size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE)
497 {
498 return openInput(io, InputFormat(), ec, internalBufferSize);
499 }
500
509 Dictionary &formatOptions,
510 OptionalErrorCode ec = throws(),
511 size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE)
512 {
513 return openInput(io, formatOptions, InputFormat(), ec, internalBufferSize);
514 }
515
524 Dictionary &&formatOptions,
525 OptionalErrorCode ec = throws(),
526 size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE)
527 {
528 return openInput(io, std::move(formatOptions), InputFormat(), ec, internalBufferSize);
529 }
530
540 InputFormat format,
541 OptionalErrorCode ec = throws(),
542 size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
553 Dictionary &formatOptions,
554 InputFormat format,
555 OptionalErrorCode ec = throws(),
556 size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
568 Dictionary &&formatOptions,
569 InputFormat format,
570 OptionalErrorCode ec = throws(),
571 size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
572
588 void findStreamInfo(DictionaryArray &streamsOptions, OptionalErrorCode ec = throws());
595 void findStreamInfo(DictionaryArray &&streamsOptions, OptionalErrorCode ec = throws());
596
606
607 //
608 // Output
609 //
618 void openOutput(const std::string& uri, OptionalErrorCode ec = throws());
626 void openOutput(const std::string& uri, Dictionary &options, OptionalErrorCode ec = throws());
634 void openOutput(const std::string& uri, Dictionary &&options, OptionalErrorCode ec = throws());
635
643 void openOutput(const std::string& uri, OutputFormat format, OptionalErrorCode ec = throws());
652 void openOutput(const std::string& uri, Dictionary &options, OutputFormat format, OptionalErrorCode ec = throws());
661 void openOutput(const std::string& uri, Dictionary &&options, OutputFormat format, OptionalErrorCode ec = throws());
662
664
675 void openOutput(CustomIO *io, OptionalErrorCode ec = throws(), size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
676
694 bool openOutput(CustomIO *io, Dictionary &formatOptions, OptionalErrorCode ec = throws(), size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
706 bool openOutput(CustomIO *io, Dictionary &&formatOptions, OptionalErrorCode ec = throws(), size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
707
716 void openOutput(CustomIO *io, OutputFormat format, OptionalErrorCode ec = throws(), size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
717
733 bool openOutput(CustomIO *io, Dictionary &formatOptions, OutputFormat format, OptionalErrorCode ec = throws(), size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
747 bool openOutput(CustomIO *io, Dictionary &&formatOptions, OutputFormat format, OptionalErrorCode ec = throws(), size_t internalBufferSize = CUSTOM_IO_DEFAULT_BUFFER_SIZE);
749
751
764 bool initOutput(OptionalErrorCode ec = throws());
774 bool initOutput(Dictionary &options, OptionalErrorCode ec = throws());
784 bool initOutput(Dictionary &&options, OptionalErrorCode ec = throws());
786
795 void writeHeader(OptionalErrorCode ec = throws());
802 void writeHeader(Dictionary &options, OptionalErrorCode ec = throws());
809 void writeHeader(Dictionary &&options, OptionalErrorCode ec = throws());
810
819 void writePacket(OptionalErrorCode ec = throws());
829 void writePacket(const Packet &pkt, OptionalErrorCode ec = throws());
845 void writePacketDirect(const Packet &pkt, OptionalErrorCode ec = throws());
846
858 bool checkUncodedFrameWriting(size_t streamIndex, std::error_code &ec) noexcept;
866 bool checkUncodedFrameWriting(size_t streamIndex) noexcept;
867
878 void writeUncodedFrame(class VideoFrame &frame, size_t streamIndex, OptionalErrorCode ec = throws());
886 void writeUncodedFrameDirect(class VideoFrame &frame, size_t streamIndex, OptionalErrorCode ec = throws());
894 void writeUncodedFrame(class AudioSamples &frame, size_t streamIndex, OptionalErrorCode ec = throws());
902 void writeUncodedFrameDirect(class AudioSamples &frame, size_t streamIndex, OptionalErrorCode ec = throws());
903
912 void writeTrailer(OptionalErrorCode ec = throws());
913
914private:
915 void openInput(const std::string& uri, InputFormat format, AVDictionary **options, OptionalErrorCode ec);
916 void openOutput(const std::string& uri, OutputFormat format, AVDictionary **options, OptionalErrorCode ec);
917 bool initOutput(Dictionary &options, bool closeOnError, OptionalErrorCode ec);
918 bool initOutput(AVDictionary **options, OptionalErrorCode ec);
919 void writeHeader(AVDictionary **options, OptionalErrorCode ec);
920 void writePacket(const Packet &pkt, OptionalErrorCode ec, int(*write_proc)(AVFormatContext *, AVPacket *));
921 void writeFrame(AVFrame *frame, int streamIndex, OptionalErrorCode ec, int(*write_proc)(AVFormatContext*,int,AVFrame*));
922
923 Stream addStream(const class CodecContext2 &ctx, OptionalErrorCode ec);
924
925 static int avioInterruptCb(void *opaque);
926 int avioInterruptCb();
927 void setupInterruptHandling();
928 void resetSocketAccess();
929 void findStreamInfo(AVDictionary **options, size_t optionsCount, OptionalErrorCode ec);
930 void closeCodecContexts();
931 int checkPbError(int stat);
932
933 void openCustomIO(CustomIO *io, size_t internalBufferSize, bool isWritable, OptionalErrorCode ec);
934 void openCustomIOInput(CustomIO *io, size_t internalBufferSize, OptionalErrorCode ec);
935 void openCustomIOOutput(CustomIO *io, size_t internalBufferSize, OptionalErrorCode ec);
936
937private:
938 std::shared_ptr<char> m_monitor {new char};
939 std::chrono::time_point<std::chrono::system_clock> m_lastSocketAccess;
940 int64_t m_socketTimeout = -1;
941 AvioInterruptCb m_interruptCb;
942
943 bool m_isOpened = false;
944 bool m_customIO = false;
945 bool m_streamsInfoFound = false;
946 bool m_headerWriten = false;
947 bool m_substractStartTime = false;
948};
949
950} // namespace av
951
952#endif // if AVCPP_HAS_AVFORMAT
Error codes, error categories and the OptionalErrorCode convention.
Common helpers: comparisons, value lookup, non-copyable base, string utilities.
Encodes audio samples into packets.
Definition codeccontext.h:1782
One buffer of decoded audio samples.
Definition frame.h:892
Base class for audio and video codec contexts.
Definition codeccontext.h:64
Codec descriptor.
Definition codec.h:32
Array of Dictinaries wrapper.
Definition dictionary.h:808
Implements interface to access to the AVDictionary entity.
Definition dictionary.h:38
void openInput(CustomIO *io, Dictionary &&formatOptions, InputFormat format, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open an input on a custom IO object with an explicit demuxer and options, moving the dictionary.
void setInterruptCallback(const AvioInterruptCb &cb)
Install a callback that can cancel blocking IO.
void setFormat(const OutputFormat &format)
Force the muxer used by openOutput().
void writeHeader(Dictionary &&options, OptionalErrorCode ec=throws())
Write the container header with muxer options, moving the dictionary.
void close()
Close the container and release its resources.
StreamsView streams(OptionalErrorCode ec=throws()) const
All streams as a range, for range-based for and std algorithms.
void writeUncodedFrameDirect(class VideoFrame &frame, size_t streamIndex, OptionalErrorCode ec=throws())
Write an uncompressed video frame without intercepting FFmpeg errors.
void writeUncodedFrameDirect(class AudioSamples &frame, size_t streamIndex, OptionalErrorCode ec=throws())
Write uncompressed audio samples without intercepting FFmpeg errors.
void writeUncodedFrame(class AudioSamples &frame, size_t streamIndex, OptionalErrorCode ec=throws())
Write uncompressed audio samples through the muxer.
void openInput(CustomIO *io, Dictionary &formatOptions, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open an input on a custom IO object with demuxer options.
Definition formatcontext.h:508
OutputFormat outputFormat() const
The muxer in use.
void setSocketTimeout(int64_t timeout)
Abort network operations that block for too long.
Stream addStream(const class VideoEncoderContext &encCtx, OptionalErrorCode ec=throws())
Add a video stream configured from an encoder context.
void openInput(const std::string &uri, OptionalErrorCode ec=throws())
Open an input and probe its container.
void openOutput(const std::string &uri, OutputFormat format, OptionalErrorCode ec=throws())
Open an output with an explicit muxer.
Stream addStream(const Codec &codec, OptionalErrorCode ec=throws())
Add a stream for the given codec.
void openInput(CustomIO *io, Dictionary &&formatOptions, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open an input on a custom IO object with demuxer options, moving the dictionary.
Definition formatcontext.h:523
void openInput(CustomIO *io, Dictionary &formatOptions, InputFormat format, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open an input on a custom IO object with an explicit demuxer and options.
void writeUncodedFrame(class VideoFrame &frame, size_t streamIndex, OptionalErrorCode ec=throws())
Write an uncompressed video frame through the muxer.
Stream stream(size_t idx, OptionalErrorCode ec)
Stream by index, reporting an out-of-range index as an error.
InputFormat inputFormat() const
The demuxer in use.
bool initOutput(Dictionary &&options, OptionalErrorCode ec=throws())
Init the output with muxer options, moving the dictionary.
void writePacket(const Packet &pkt, OptionalErrorCode ec=throws())
Write one packet.
void findStreamInfo(DictionaryArray &streamsOptions, OptionalErrorCode ec=throws())
Read the stream parameters with per-stream options.
void openInput(CustomIO *io, InputFormat format, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open an input on a custom IO object with an explicit demuxer.
bool openOutput(CustomIO *io, Dictionary &&formatOptions, OutputFormat format, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open output on a custom IO object with an explicit format and options, moving the dictionary.
void writeTrailer(OptionalErrorCode ec=throws())
Write the container trailer and close the output.
bool initOutput(Dictionary &options, OptionalErrorCode ec=throws())
Init the output with muxer options instead of writing the header.
bool openOutput(CustomIO *io, Dictionary &&formatOptions, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open output on a custom IO object with muxer options, moving the dictionary.
void writeHeader(OptionalErrorCode ec=throws())
Write the container header.
void openOutput(const std::string &uri, OptionalErrorCode ec=throws())
Open an output.
Timestamp duration() const noexcept
Duration of the container.
Timestamp startTime() const noexcept
Start time of the container.
bool isOpened() const
Whether the container is open.
static constexpr size_t CUSTOM_IO_DEFAULT_BUFFER_SIZE
Default size of the buffer avcpp allocates around a custom IO object.
Definition formatcontext.h:485
bool openOutput(CustomIO *io, Dictionary &formatOptions, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open output on a custom IO object with explicit muxer options.
void openOutput(const std::string &uri, Dictionary &&options, OutputFormat format, OptionalErrorCode ec=throws())
Open an output with an explicit muxer and options, moving the dictionary.
void openOutput(const std::string &uri, Dictionary &options, OutputFormat format, OptionalErrorCode ec=throws())
Open an output with an explicit muxer and options.
void eventFlagsClear(int flags) noexcept
Acknowledge events.
void substractStartTime(bool enable)
Shift timestamps so the file starts at zero.
void findStreamInfo(DictionaryArray &&streamsOptions, OptionalErrorCode ec=throws())
Read the stream parameters with per-stream options, moving them in.
bool initOutput(OptionalErrorCode ec=throws())
Init output without writing the header.
int eventFlags() const noexcept
Flags to the user to detect events happening on the file.
Stream addStream(const class AudioEncoderContext &encCtx, OptionalErrorCode ec=throws())
Add an audio stream configured from an encoder context.
bool checkUncodedFrameWriting(size_t streamIndex, std::error_code &ec) noexcept
Whether an uncompressed frame can be written to a stream.
void writePacket(OptionalErrorCode ec=throws())
Flush the muxer queue.
bool isOutput() const
Whether this context writes instead of reads.
Stream addStream(OptionalErrorCode ec=throws())
Add a stream to an output container.
void openOutput(const std::string &uri, Dictionary &&options, OptionalErrorCode ec=throws())
Open an output with muxer options, moving the dictionary.
void dump() const
Print the container layout through the FFmpeg log system.
void flush()
Discard buffered packets and internal state.
void setFormat(const InputFormat &format)
Force the demuxer used by openInput().
bool checkUncodedFrameWriting(size_t streamIndex) noexcept
Whether an uncompressed frame can be written to a stream.
void findStreamInfo(OptionalErrorCode ec=throws())
Read the stream parameters of an opened input.
void openOutput(CustomIO *io, OutputFormat format, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open output on a custom IO object with an explicit output format.
void writePacketDirect(OptionalErrorCode ec=throws())
Flush the muxer queue without intercepting FFmpeg errors.
bool seekable() const noexcept
Whether the container supports seeking.
void writePacketDirect(const Packet &pkt, OptionalErrorCode ec=throws())
Write one packet without intercepting FFmpeg errors.
void seek(const Timestamp &timestamp, OptionalErrorCode ec=throws())
Seek to a timestamp in any stream.
bool openOutput(CustomIO *io, Dictionary &formatOptions, OutputFormat format, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open output on a custom IO object with an explicit output format and muxer options.
size_t streamsCount() const
Number of streams in the container.
Stream stream(size_t idx)
Stream by index.
Packet readPacket(OptionalErrorCode ec=throws())
Read the next packet from any stream.
void writeHeader(Dictionary &options, OptionalErrorCode ec=throws())
Write the container header with muxer options.
void openOutput(CustomIO *io, OptionalErrorCode ec=throws(), size_t internalBufferSize=CUSTOM_IO_DEFAULT_BUFFER_SIZE)
Open output on a custom IO object.
void openOutput(const std::string &uri, Dictionary &options, OptionalErrorCode ec=throws())
Open an output with muxer options.
Demuxer descriptor.
Definition format.h:168
Carries the caller's choice between exceptions and error codes.
Definition averror.h:96
Muxer descriptor.
Definition format.h:202
Compressed data and its metadata.
Definition packet.h:110
One stream inside a container.
Definition stream.h:34
The Timestamp class represents timestamp value and it timebase.
Definition timestamp.h:25
Encodes video frames into packets.
Definition codeccontext.h:1338
One video frame.
Definition frame.h:578
Codec descriptors and lookup by name or id.
AVDictionary wrappers: Dictionary and DictionaryArray.
FFmpeg types re-exported for the public API and small value wrappers.
Input and output format descriptors.
Root namespace of the library.
Definition audioresampler.h:19
OptionalErrorCode throws()
Helper to construct null OptionalErrorCode object.
Definition averror.h:310
@ Encoding
Compressing frames into packets.
Definition codecparameters.h:33
@ Decoding
Decompressing packets into frames.
Definition codecparameters.h:35
std::function< int()> AvioInterruptCb
Callback that can abort a blocking IO operation.
Definition formatcontext.h:39
STL namespace.
Compressed packets and their side data.
Streams inside a container: parameters, time base and disposition.
Interface class to customize IO operations with FormatContext.
Definition formatcontext.h:57
virtual int write(const uint8_t *data, size_t size)
Write part of data to the destination.
Definition formatcontext.h:74
virtual const char * name() const
Name of the I/O.
Definition formatcontext.h:138
virtual int seekable() const
Defines supported types of buffer seeking.
Definition formatcontext.h:131
virtual int read(uint8_t *data, size_t size)
Read part of data from the data source.
Definition formatcontext.h:96
virtual int64_t seek(int64_t offset, int whence)
Seek in stream.
Definition formatcontext.h:117