avcpp 3.1.0
Wrapper for the FFmpeg that simplify usage from C++ projects.
Loading...
Searching...
No Matches
codeccontext.h
Go to the documentation of this file.
1#pragma once
2
9
10#include <cstring>
11
12#include "avcompat.h"
13
14#include "ffmpeg.h"
15#include "stream.h"
16#include "avutils.h"
17#include "averror.h"
18#include "pixelformat.h"
19#include "sampleformat.h"
20#include "avlog.h"
21#include "frame.h"
22#include "subtitle.h"
23#include "codec.h"
24#include "channellayout.h"
25#include "hwcontext.h"
26
27extern "C" {
28#include <libavcodec/avcodec.h>
29#include <libavutil/mem.h>
30}
31
32namespace av {
33
34namespace codec_context::audio {
35void set_channels(AVCodecContext *obj, int channels);
36void set_channel_layout_mask(AVCodecContext *obj, uint64_t mask);
37int get_channels(const AVCodecContext *obj);
38uint64_t get_channel_layout_mask(const AVCodecContext *obj);
39}
40
41namespace codec_context::internal {
42const int *get_supported_samplerates(const struct AVCodec *codec);
43}
44
63class CodecContext2 : public FFWrapperPtr<AVCodecContext>, public noncopyable
64{
65protected:
70 void swap(CodecContext2 &other);
71
72 //
73 // No directly created
74 //
75
80 using BaseWrapper::BaseWrapper;
81
82 CodecContext2();
83
84 // Stream decoding/encoding
85#if AVCPP_HAS_AVFORMAT
96 CodecContext2(const class Stream &st,
97 const class Codec& codec,
98 Direction direction,
99 AVMediaType type);
100#endif // if AVCPP_HAS_AVFORMAT
101
102 // Stream independ decoding/encoding
111 CodecContext2(const class Codec &codec, Direction direction, AVMediaType type);
112
113 ~CodecContext2();
114
125 void setCodec(const class Codec &codec, bool resetDefaults, Direction direction, AVMediaType type, OptionalErrorCode ec = throws());
126
135 AVMediaType codecType(AVMediaType contextType) const noexcept;
136
137public:
138
139 using BaseWrapper::_log;
140
141 //
142 // Common
143 //
144
155 void open(OptionalErrorCode ec = throws());
163 void open(const Codec &codec, OptionalErrorCode ec = throws());
171 void open(class Dictionary &options, OptionalErrorCode ec = throws());
178 void open(class Dictionary &&options, OptionalErrorCode ec = throws());
186 void open(class Dictionary &options, const Codec &codec, OptionalErrorCode ec = throws());
194 void open(class Dictionary &&options, const Codec &codec, OptionalErrorCode ec = throws());
195
206 [[deprecated("Start from FFmpeg 4.0 it is recommended to destroy and recreate codec context insted of close")]]
207 void close(OptionalErrorCode ec = throws());
208
214 bool isOpened() const noexcept;
220 bool isValid() const noexcept;
221
231 void copyContextFrom(const CodecContext2 &other, OptionalErrorCode ec = throws());
233
239 Rational timeBase() const noexcept;
245 void setTimeBase(const Rational &value) noexcept;
246
254 Rational frameRate() const noexcept;
261 void setFrameRate(const Rational &value) noexcept;
262
263#if AVCPP_NEW_CODEC_API
272 bool isEof() const noexcept { return m_eof; }
273
280 void flushBuffers() noexcept
281 {
282 if (m_raw)
283 avcodec_flush_buffers(m_raw);
284 m_eof = false;
285 }
286#endif
287
288#if AVCPP_HAS_AVFORMAT
295 const Stream& stream() const noexcept;
296#endif // if AVCPP_HAS_AVFORMAT
302 Codec codec() const noexcept;
303
312 void setOption(const std::string &key, const std::string &val, OptionalErrorCode ec = throws());
322 void setOption(const std::string &key, const std::string &val, int flags, OptionalErrorCode ec = throws());
323
329 int frameSize() const noexcept;
335 int64_t frameNumber() const noexcept;
336
337 // Note, set ref counted to enable for multithreaded processing
343 bool isRefCountedFrames() const noexcept;
351 void setRefCountedFrames(bool refcounted) const noexcept;
352
358 int strict() const noexcept;
365 void setStrict(int strict) noexcept;
366
372 int64_t bitRate() const noexcept;
378 std::pair<int64_t, int64_t> bitRateRange() const noexcept;
385 void setBitRate(int64_t bitRate) noexcept;
391 void setBitRateRange(const std::pair<int64_t, int64_t> &bitRateRange) noexcept;
392
393 // Flags
396
401 void setFlags(int flags) noexcept;
407 void addFlags(int flags) noexcept;
413 void clearFlags(int flags) noexcept;
419 int flags() noexcept;
427 bool isFlags(int flags) noexcept;
429
430 // Flags 2
433
438 void setFlags2(int flags) noexcept;
444 void addFlags2(int flags) noexcept;
450 void clearFlags2(int flags) noexcept;
456 int flags2() noexcept;
464 bool isFlags2(int flags) noexcept;
466
467
468protected:
469
478 bool isValidForEncode(Direction direction, AVMediaType type) const noexcept;
479
489 bool checkCodec(const Codec& codec, Direction direction, AVMediaType type, OptionalErrorCode ec);
490
499 void open(const Codec &codec, AVDictionary **options, OptionalErrorCode ec);
500
501 // Hardware codec state. The device and frames contexts are reference
502 // counted, copying the wrappers is cheap.
506 hw::DeviceContext m_hwDevice;
510 hw::FramesContext m_hwFrames;
518 bool m_hwAutoUpload = true;
522 hw::EncodingMode m_hwEncodingMode = hw::EncodingMode::Auto;
523
524 std::pair<int, const std::error_category*>
536 decodeCommon(AVFrame *outFrame, const class Packet &inPacket, size_t offset, int &frameFinished,
537 int (*decodeProc)(AVCodecContext*, AVFrame*,int *, const AVPacket *)) noexcept;
538
539 std::pair<int, const std::error_category*>
550 encodeCommon(class Packet &outPacket, const AVFrame *inFrame, int &gotPacket,
551 int (*encodeProc)(AVCodecContext*, AVPacket*,const AVFrame*, int*)) noexcept;
552
553#if AVCPP_NEW_CODEC_API
554 // Decode
562 std::error_code sendCommon(const class Packet& pkt);
570 std::error_code receiveCommon(AVFrame *frame);
578 template<typename T>
579 std::error_code receiveCommon(T &frame);
580
581 // Encode
589 std::error_code sendCommon(const AVFrame* frame);
597 std::error_code receiveCommon(class Packet& pkt);
605 template<typename T>
606 std::error_code sendCommon(const T& frame);
607#endif
608
609public:
610 template<typename T>
611 std::pair<int, const std::error_category*>
623 decodeCommon(T &outFrame,
624 const class Packet &inPacket,
625 size_t offset,
626 int &frameFinished,
627 int (*decodeProc)(AVCodecContext *, AVFrame *, int *, const AVPacket *));
628
629 template<typename T>
630 std::pair<int, const std::error_category*>
641 encodeCommon(class Packet &outPacket,
642 const T &inFrame,
643 int &gotPacket,
644 int (*encodeProc)(AVCodecContext *, AVPacket *, const AVFrame *, int *));
645
646#if AVCPP_NEW_CODEC_API
647 // Decode
657 bool send(const Packet &packet, OptionalErrorCode ec = throws());
658
668#endif
669
670private:
671#if AVCPP_HAS_AVFORMAT
672 Stream m_stream;
673#endif // if AVCPP_HAS_AVFORMAT
674 Direction m_direction{Direction::Invalid};
675#if AVCPP_NEW_CODEC_API
676 bool m_eof{false};
677#endif
678};
679
680
688class GenericCodecContext : public CodecContext2
689{
690protected:
692
693public:
698
699#if AVCPP_HAS_AVFORMAT
709#endif // if AVCPP_HAS_AVFORMAT
710
717
726
732 AVMediaType codecType() const noexcept;
733};
734
735
742template<typename Clazz, Direction _direction, AVMediaType _type>
743class CodecContextBase : public CodecContext2
744{
745protected:
753 Clazz& moveOperator(Clazz &&rhs)
754 {
755 if (this == &rhs)
756 return static_cast<Clazz&>(*this);
757 Clazz(std::forward<Clazz>(rhs)).swap(static_cast<Clazz&>(*this));
758 return static_cast<Clazz&>(*this);
759 }
760
762
763public:
764
766
771 : CodecContext2()
772 {
773 }
774
775 // Stream decoding/encoding
776#if AVCPP_HAS_AVFORMAT
783 explicit CodecContextBase(const class Stream &st, const class Codec& codec = Codec())
784 : CodecContext2(st, codec, _direction, _type)
785 {
786 }
787#endif // if AVCPP_HAS_AVFORMAT
788
789 // Stream independ decoding/encoding
795 explicit CodecContextBase(const Codec &codec)
796 : CodecContext2(codec, _direction, _type)
797 {
798 }
799
800 //
801 // Disable copy/Activate move
802 //
810 {
811 swap(other);
812 }
813 //
814
815
822 void setCodec(const Codec &codec, OptionalErrorCode ec = throws())
823 {
824 setCodec(codec, false, _direction, _type, ec);
825 }
826
835 void setCodec(const Codec &codec, bool resetDefaults, OptionalErrorCode ec = throws())
836 {
837 setCodec(codec, resetDefaults, _direction, _type, ec);
838 }
839
845 AVMediaType codecType() const noexcept
846 {
847 return CodecContext2::codecType(_type);
848 }
849
850#if AVCPP_NEW_CODEC_API
851
863 bool flush(OptionalErrorCode ec = throws())
864 {
865 clear_if(ec);
866
867 if constexpr (_type == AVMEDIA_TYPE_SUBTITLE) {
868 throws_if(ec, Errors::CodecUnsupportedOperation);
869 return false;
870 }
871
872 if (!isValid()) {
873 throws_if(ec, make_error_code(Errors::CodecInvalid));
874 return false;
875 }
876
877 if (!isOpened()) {
878 throws_if(ec, make_error_code(Errors::CodecNotOpened));
879 return false;
880 }
881
882 int ret = 0;
883 if constexpr (_direction == Direction::Decoding) {
884 ret = avcodec_send_packet(m_raw, nullptr);
885 } else {
886 ret = avcodec_send_frame(m_raw, nullptr);
887 }
888
889 if (ret == AVERROR(EAGAIN)) {
890 // Output queue is full: drain it first, then call flush() again
891 return false;
892 }
893 if (ret == AVERROR_EOF) {
894 // Already drained, flush is idempotent
895 return true;
896 }
897 if (ret) {
898 throws_if(ec, ret, ffmpeg_category());
899 return false;
900 }
901 return true;
902 }
903
904#endif
905};
906
907
915template<typename Clazz, Direction _direction>
916class VideoCodecContext : public CodecContextBase<Clazz, _direction, AVMEDIA_TYPE_VIDEO>
917{
918public:
921 using Parent::Parent;
922 using Parent::isValid;
923 using Parent::isOpened;
924
930 int width() const
931 {
932 return RAW_GET2(isValid(), width, 0);
933 }
934
940 int height() const
941 {
942 return RAW_GET2(isValid(), height, 0);
943 }
944
950 int codedWidth() const
951 {
952 return RAW_GET2(isValid(), coded_width, 0);
953 }
954
960 int codedHeight() const
961 {
962 return RAW_GET2(isValid(), coded_height, 0);
963 }
964
971 {
972 return RAW_GET2(isValid(), pix_fmt, AV_PIX_FMT_NONE);
973 }
974
980 int32_t globalQuality() const
981 {
982 return RAW_GET2(isValid(), global_quality, FF_LAMBDA_MAX);
983 }
984
990 int32_t gopSize() const
991 {
992 return RAW_GET2(isValid(), gop_size, 0);
993 }
994
1001 {
1002 return RAW_GET2(isValid(), bit_rate_tolerance, 0);
1003 }
1004
1010 int maxBFrames() const
1011 {
1012 return RAW_GET2(isValid(), max_b_frames, 0);
1013 }
1014
1021 {
1022 return RAW_GET(sample_aspect_ratio, AVRational());
1023 }
1024
1033 void setWidth(int w) // Note, it also sets coded_width
1034 {
1035 if (isValid() && !isOpened())
1036 {
1037 m_raw->width = w;
1038 m_raw->coded_width = w;
1039 }
1040 }
1041
1049 void setHeight(int h) // Note, it also sets coded_height
1050 {
1051 if (isValid() && !isOpened())
1052 {
1053 m_raw->height = h;
1054 m_raw->coded_height = h;
1055 }
1056 }
1057
1065 void setCodedWidth(int w)
1066 {
1067 RAW_SET2(isValid() && !isOpened(), coded_width, w);
1068 }
1069
1077 void setCodedHeight(int h)
1078 {
1079 RAW_SET2(isValid() && !isOpened(), coded_height, h);
1080 }
1081
1089 {
1090 RAW_SET2(isValid(), pix_fmt, pixelFormat);
1091 }
1092
1099 void setGlobalQuality(int32_t quality)
1100 {
1101 if (quality < 0 || quality > FF_LAMBDA_MAX)
1102 quality = FF_LAMBDA_MAX;
1103
1104 RAW_SET2(isValid(), global_quality, quality);
1105 }
1106
1112 void setGopSize(int32_t size)
1113 {
1114 RAW_SET2(isValid(), gop_size, size);
1115 }
1116
1123 {
1124 RAW_SET2(isValid(), bit_rate_tolerance, bitRateTolerance);
1125 }
1126
1133 {
1134 RAW_SET2(isValid(), max_b_frames, maxBFrames);
1135 }
1136
1143 {
1144 RAW_SET(sample_aspect_ratio, sampleAspectRatio);
1145 }
1146
1147protected:
1148 using Parent::moveOperator;
1149 using Parent::m_raw;
1150};
1151
1152
1160class VideoDecoderContext : public VideoCodecContext<VideoDecoderContext, Direction::Decoding>
1161{
1162public:
1167 using Parent::Parent;
1168
1179
1188
1200 VideoFrame decode(const Packet &packet,
1201 OptionalErrorCode ec = throws(),
1202 bool autoAllocateFrame = true);
1203
1217 VideoFrame decode(const Packet &packet,
1218 size_t offset,
1219 size_t &decodedBytes,
1220 OptionalErrorCode ec = throws(),
1221 bool autoAllocateFrame = true);
1222
1223
1224#if AVCPP_NEW_CODEC_API
1233 bool send(const Packet &packet, OptionalErrorCode ec = throws());
1234
1251 VideoFrame receive(OptionalErrorCode ec = throws(), bool autoAllocateFrame = true);
1252#endif
1253
1268 OptionalErrorCode ec = throws());
1269
1273 void clearHwDeviceContext() noexcept;
1274
1284 hw::DeviceContext hwDeviceContext() const noexcept;
1285
1303 hw::FramesContext hwFramesContext() const noexcept;
1304
1312 void setHwTransferToSystem(bool enabled) noexcept;
1318 bool isHwTransferToSystem() const noexcept;
1319
1320private:
1321 VideoFrame decodeVideo(OptionalErrorCode ec,
1322 const Packet &packet,
1323 size_t offset,
1324 size_t *decodedBytes,
1325 bool autoAllocateFrame);
1326
1327};
1328
1329
1338{
1339public:
1344 using Parent::Parent;
1345
1356
1365
1376
1388 Packet encode(const VideoFrame &inFrame, OptionalErrorCode ec = throws());
1389
1390
1391#if AVCPP_NEW_CODEC_API
1392
1402 bool send(const VideoFrame& frame, OptionalErrorCode ec = throws());
1403
1415
1416#endif
1417
1424 OptionalErrorCode ec = throws());
1425
1429 void clearHwDeviceContext() noexcept;
1430
1439 void setHwFramesContext(const hw::FramesContext& frames,
1440 OptionalErrorCode ec = throws());
1441
1445 void clearHwFramesContext() noexcept;
1446
1453 hw::DeviceContext hwDeviceContext() const noexcept;
1454
1461 hw::FramesContext hwFramesContext() const noexcept;
1462
1478 void configureHwEncoding(const hw::DeviceContext& device,
1479 hw::EncodingMode mode = hw::EncodingMode::Auto,
1480 PixelFormat swFormat = AV_PIX_FMT_NONE,
1481 OptionalErrorCode ec = throws());
1482
1491 void configureHwEncoding(const hw::FramesContext& frames,
1492 OptionalErrorCode ec = throws());
1493
1499 hw::EncodingMode hwEncodingMode() const noexcept;
1505 bool isHwEncoding() const noexcept;
1506
1514 void setHwAutoUpload(bool enabled) noexcept;
1520 bool isHwAutoUpload() const noexcept;
1521
1522};
1523
1524
1531template<typename Clazz, Direction _direction>
1532class AudioCodecContext : public CodecContextBase<Clazz, _direction, AVMEDIA_TYPE_AUDIO>
1533{
1534public:
1537 using Parent::Parent;
1538 using Parent::isValid;
1539 using Parent::isOpened;
1540 using Parent::_log;
1541
1547 int sampleRate() const noexcept
1548 {
1549 return RAW_GET2(isValid(), sample_rate, 0);
1550 }
1551
1557 int channels() const noexcept
1558 {
1559 if (!isValid())
1560 return 0;
1561 return codec_context::audio::get_channels(m_raw);
1562 }
1563
1570 {
1571 return RAW_GET2(isValid(), sample_fmt, AV_SAMPLE_FMT_NONE);
1572 }
1573
1579 uint64_t channelLayout() const noexcept
1580 {
1581 if (!isValid())
1582 return 0;
1583 return codec_context::audio::get_channel_layout_mask(m_raw);
1584 }
1585
1586#if AVCPP_API_NEW_CHANNEL_LAYOUT
1595 {
1596 if (!isValid())
1597 return ChannelLayoutView{};
1598 return ChannelLayoutView{m_raw->ch_layout};
1599 }
1600#endif
1601
1610 void setSampleRate(int sampleRate) noexcept
1611 {
1612 if (!isValid())
1613 return;
1614#if AVCPP_CXX_STANDARD >= 20
1615 int sr = guessValue(sampleRate, make_array_view_until<const int>(codec_context::internal::get_supported_samplerates(m_raw->codec), 0));
1616#else
1617 int sr = guessValue(sampleRate, codec_context::internal::get_supported_samplerates(m_raw->codec), EqualComparator<int>(0));
1618#endif
1619 if (sr != sampleRate)
1620 {
1621 fflog(AV_LOG_INFO, "Guess sample rate %d instead unsupported %d\n", sr, sampleRate);
1622 }
1623 if (sr > 0)
1624 m_raw->sample_rate = sr;
1625 }
1626
1632 void setChannels(int channels) noexcept
1633 {
1634 if (!isValid() || channels <= 0)
1635 return;
1636 codec_context::audio::set_channels(m_raw, channels);
1637 }
1638
1646 {
1647 RAW_SET2(isValid(), sample_fmt, sampleFormat);
1648 }
1649
1655 void setChannelLayout(uint64_t layout) noexcept
1656 {
1657 if (!isValid() || layout == 0)
1658 return;
1659 codec_context::audio::set_channel_layout_mask(m_raw, layout);
1660 }
1661
1662#if AVCPP_API_NEW_CHANNEL_LAYOUT
1670 void setChannelLayout(ChannelLayout layout) noexcept
1671 {
1672 if (!isValid() || !layout.isValid())
1673 return;
1674 m_raw->ch_layout = *layout.raw();
1675 layout.release(); // is controlled by the CodecContext
1676 }
1677#endif
1678
1679protected:
1680 using Parent::moveOperator;
1681 using Parent::m_raw;
1682};
1683
1684
1691class AudioDecoderContext : public AudioCodecContext<AudioDecoderContext, Direction::Decoding>
1692{
1693public:
1698 using Parent::Parent;
1699
1710
1719
1729 AudioSamples decode(const Packet &inPacket, OptionalErrorCode ec = throws());
1739 AudioSamples decode(const Packet &inPacket, size_t offset, OptionalErrorCode ec = throws());
1740
1741#if AVCPP_NEW_CODEC_API
1742
1758 bool send(const Packet& packet, OptionalErrorCode ec = throws());
1759
1769
1770#endif
1771};
1772
1773
1781class AudioEncoderContext : public AudioCodecContext<AudioEncoderContext, Direction::Encoding>
1782{
1783public:
1788 using Parent::Parent;
1789
1800
1809
1822
1832 Packet encode(const AudioSamples &inSamples, OptionalErrorCode ec = throws());
1833
1834
1835#if AVCPP_NEW_CODEC_API
1836
1845 bool send(const AudioSamples &samples, OptionalErrorCode ec = throws());
1846
1858
1859#endif
1860};
1861
1862
1876template<typename Clazz, Direction _direction>
1877class SubtitleCodecContext : public CodecContextBase<Clazz, _direction, AVMEDIA_TYPE_SUBTITLE>
1878{
1879public:
1884 using Parent::Parent;
1885
1891 std::string_view subtitleHeader() const noexcept
1892 {
1893 if (!this->m_raw || !this->m_raw->subtitle_header || this->m_raw->subtitle_header_size <= 0)
1894 return {};
1895
1896 return { reinterpret_cast<const char*>(this->m_raw->subtitle_header),
1897 static_cast<std::size_t>(this->m_raw->subtitle_header_size) };
1898 }
1899
1906 void setSubtitleHeader(std::string_view header, OptionalErrorCode ec = throws())
1907 {
1908 clear_if(ec);
1909
1910 if (!this->isValid()) {
1911 throws_if(ec, Errors::CodecInvalid);
1912 return;
1913 }
1914
1915 if (this->isOpened()) {
1916 throws_if(ec, Errors::CodecAlreadyOpened);
1917 return;
1918 }
1919
1920 std::unique_ptr<uint8_t, void(*)(void*)> copy(nullptr, av_free);
1921 if (!header.empty()) {
1922 copy = av::mallocz<uint8_t>(header.size() + 1);
1923 if (!copy) {
1924 throws_if(ec, Errors::Unallocated);
1925 return;
1926 }
1927 std::memcpy(copy.get(), header.data(), header.size());
1928 }
1929
1930 av::freep(this->m_raw->subtitle_header);
1931 this->m_raw->subtitle_header = copy.release();
1932 this->m_raw->subtitle_header_size = static_cast<int>(header.size());
1933 }
1934
1944
1948 void clearSubtitleHeader() noexcept
1949 {
1950 if (!this->m_raw || this->isOpened())
1951 return;
1952
1953 av::freep(this->m_raw->subtitle_header);
1954 this->m_raw->subtitle_header_size = 0;
1955 }
1956
1962 Rational pktTimeBase() const noexcept
1963 {
1964 return this->m_raw ? Rational(this->m_raw->pkt_timebase) : Rational();
1965 }
1966
1973 void setPktTimeBase(const Rational &value) noexcept
1974 {
1975 if (this->m_raw)
1976 this->m_raw->pkt_timebase = value;
1977 }
1978
1985 bool flush(OptionalErrorCode ec = throws()) = delete;
1986};
1987
1988
1996class SubtitleDecoderContext : public SubtitleCodecContext<SubtitleDecoderContext, Direction::Decoding>
1997{
1998public:
2003 using Parent::Parent;
2004
2023
2040 SubtitleFrame decode(const Packet &packet, OptionalErrorCode ec = throws());
2041
2053 SubtitleFrame decode(const Packet &packet, size_t offset, size_t &decodedBytes,
2054 OptionalErrorCode ec = throws());
2055
2056#if AVCPP_NEW_CODEC_API
2057 bool send(const Packet &packet, OptionalErrorCode ec = throws()) = delete;
2058 Packet receive(OptionalErrorCode ec = throws()) = delete;
2059#endif
2060};
2061
2062
2069class SubtitleEncoderContext : public SubtitleCodecContext<SubtitleEncoderContext, Direction::Encoding>
2070{
2071public:
2076 using Parent::Parent;
2077
2096
2109 Packet encode(const SubtitleFrame &frame, OptionalErrorCode ec = throws());
2110
2111#if AVCPP_NEW_CODEC_API
2112 bool send(const SubtitleFrame &frame, OptionalErrorCode ec = throws()) = delete;
2113 Packet receive(OptionalErrorCode ec = throws()) = delete;
2114#endif
2115};
2116
2117
2118} // namespace av
FFmpeg version and API compatibility switches.
Error codes, error categories and the OptionalErrorCode convention.
Bridge to the FFmpeg logging system.
#define fflog(level, format,...)
Default in-class logger.
Definition avlog.h:41
Common helpers: comparisons, value lookup, non-copyable base, string utilities.
Audio channel layouts.
Audio-specific parameters shared by audio encoders and decoders.
Definition codeccontext.h:1533
void setChannelLayout(ChannelLayout layout) noexcept
Set the channel layout from a structured value.
Definition codeccontext.h:1670
void setChannels(int channels) noexcept
Set the channel count.
Definition codeccontext.h:1632
uint64_t channelLayout() const noexcept
Channel layout as a bit mask.
Definition codeccontext.h:1579
CodecContextBase< Clazz, _direction, AVMEDIA_TYPE_AUDIO > Parent
The base class this context derives from.
Definition codeccontext.h:1536
SampleFormat sampleFormat() const noexcept
Sample format of the context.
Definition codeccontext.h:1569
void setChannelLayout(uint64_t layout) noexcept
Set the channel layout as a bit mask.
Definition codeccontext.h:1655
int channels() const noexcept
Number of audio channels.
Definition codeccontext.h:1557
void setSampleRate(int sampleRate) noexcept
Set the sample rate.
Definition codeccontext.h:1610
void setSampleFormat(SampleFormat sampleFormat) noexcept
Set the sample format.
Definition codeccontext.h:1645
int sampleRate() const noexcept
Sample rate of the context.
Definition codeccontext.h:1547
ChannelLayoutView channelLayout2() const noexcept
Channel layout as a structured view.
Definition codeccontext.h:1594
AudioDecoderContext(AudioDecoderContext &&other)
Move the decoder.
AudioCodecContext< AudioDecoderContext, Direction::Decoding > Parent
/// The base class this context derives from.
Definition codeccontext.h:1697
bool send(const Packet &packet, OptionalErrorCode ec=throws())
Sends a packet to the decoder.
AudioSamples decode(const Packet &inPacket, OptionalErrorCode ec=throws())
Decode one audio packet.
AudioSamples receive(OptionalErrorCode ec=throws())
Receives one decoded audio buffer.
AudioDecoderContext & operator=(AudioDecoderContext &&other)
Move assignment.
AudioDecoderContext()=default
Create an empty decoder; set a codec and open() it later.
AudioSamples decode(const Packet &inPacket, size_t offset, OptionalErrorCode ec=throws())
Decode one audio packet starting at a byte offset.
Packet encode(OptionalErrorCode ec=throws())
Drain the encoder.
AudioCodecContext< AudioEncoderContext, Direction::Encoding > Parent
/// The base class this context derives from.
Definition codeccontext.h:1787
bool send(const AudioSamples &samples, OptionalErrorCode ec=throws())
Sends audio samples to the encoder.
AudioEncoderContext & operator=(AudioEncoderContext &&other)
Move assignment.
AudioEncoderContext()=default
Create an empty encoder; set a codec and open() it later.
Packet receive(OptionalErrorCode ec=throws())
Receives one encoded packet.
Packet encode(const AudioSamples &inSamples, OptionalErrorCode ec=throws())
Encode one buffer of samples.
AudioEncoderContext(AudioEncoderContext &&other)
Move the encoder.
One buffer of decoded audio samples.
Definition frame.h:892
Non-owning view of an AVChannelLayout.
Definition channellayout.h:68
Owning channel layout.
Definition channellayout.h:240
std::pair< int, const std::error_category * > encodeCommon(class Packet &outPacket, const T &inFrame, int &gotPacket, int(*encodeProc)(AVCodecContext *, AVPacket *, const AVFrame *, int *))
Encode one typed frame into a packet.
bool isValidForEncode(Direction direction, AVMediaType type) const noexcept
Whether the configured codec can encode the given media type.
Codec codec() const noexcept
The codec in use.
hw::DeviceContext m_hwDevice
Device attached by setHwDeviceContext() or configureHwEncoding().
Definition codeccontext.h:506
CodecContext2(const class Stream &st, const class Codec &codec, Direction direction, AVMediaType type)
Create a context attached to a stream.
bool isValid() const noexcept
Whether the context owns an FFmpeg codec context.
int64_t bitRate() const noexcept
Target bit rate.
std::error_code sendCommon(const AVFrame *frame)
Submit a frame to an encoder.
void _log(int level, const char *fmt) const
Log through the FFmpeg log system, using this wrapper as the context.
Definition ffmpeg.h:85
void clearFlags(int flags) noexcept
Remove AV_CODEC_FLAG_* flags.
std::error_code receiveCommon(AVFrame *frame)
Read one frame from a decode context.
AVMediaType codecType(AVMediaType contextType) const noexcept
Map a context media type to the effective media type.
void open(class Dictionary &&options, const Codec &codec, OptionalErrorCode ec=throws())
Open an explicitly chosen codec with options, moving the dictionary.
void open(class Dictionary &options, const Codec &codec, OptionalErrorCode ec=throws())
Open an explicitly chosen codec with options.
std::pair< int, const std::error_category * > encodeCommon(class Packet &outPacket, const AVFrame *inFrame, int &gotPacket, int(*encodeProc)(AVCodecContext *, AVPacket *, const AVFrame *, int *)) noexcept
Encode one typed frame into a packet.
void addFlags2(int flags) noexcept
Add AV_CODEC_FLAG2_* flags.
void setFrameRate(const Rational &value) noexcept
Set the frame rate.
std::error_code sendCommon(const class Packet &pkt)
Submit a packet to a decoder.
Rational frameRate() const noexcept
Frame rate advertised by the codec.
bool send(const Packet &packet, OptionalErrorCode ec=throws())
Submit a packet to a decoder.
void setOption(const std::string &key, const std::string &val, OptionalErrorCode ec=throws())
Set a private codec option.
hw::EncodingMode m_hwEncodingMode
How the encoder receives hardware frames.
Definition codeccontext.h:522
hw::FramesContext m_hwFrames
Pool attached by setHwFramesContext() or configureHwEncoding().
Definition codeccontext.h:510
bool checkCodec(const Codec &codec, Direction direction, AVMediaType type, OptionalErrorCode ec)
Validate a codec against a direction and media type, reporting the reason.
Rational timeBase() const noexcept
Time base of the codec.
void open(class Dictionary &options, OptionalErrorCode ec=throws())
Open the codec with options.
void setBitRate(int64_t bitRate) noexcept
Set the target bit rate.
CodecContext2(const class Codec &codec, Direction direction, AVMediaType type)
Create a context for a codec without a stream.
int64_t frameNumber() const noexcept
Counter of frames passed through the context.
std::error_code receiveCommon(class Packet &pkt)
Read one packet from an encode context.
void swap(CodecContext2 &other)
Exchange the state of two contexts.
FFWrapperPtr< AVCodecContext > BaseWrapper
/// The reference-counting wrapper this context builds on.
Definition codeccontext.h:79
bool isOpened() const noexcept
Whether the codec has been opened.
void flushBuffers() noexcept
Resets the codec internal state and the end-of-stream flag.
Definition codeccontext.h:280
int flags() noexcept
Current AV_CODEC_FLAG_* mask.
void setBitRateRange(const std::pair< int64_t, int64_t > &bitRateRange) noexcept
Set the allowed bit rate range.
void copyContextFrom(const CodecContext2 &other, OptionalErrorCode ec=throws())
Copy codec context from codec context associated with given stream or other codec context.
std::error_code sendCommon(const T &frame)
Submit a typed frame to an encoder.
std::error_code receiveCommon(T &frame)
Read one typed output object from a decode context.
bool isFlags2(int flags) noexcept
Whether all given flags are set.
const Stream & stream() const noexcept
The stream this context is attached to.
void open(OptionalErrorCode ec=throws())
Open the codec with the parameters set so far.
bool isRefCountedFrames() const noexcept
Whether the codec hands out reference-counted frames.
std::pair< int64_t, int64_t > bitRateRange() const noexcept
Allowed bit rate range.
bool isEof() const noexcept
Returns true if the codec has been flushed and all output is drained.
Definition codeccontext.h:272
int strict() const noexcept
Current strictness level of the codec.
bool isFlags(int flags) noexcept
Whether all given flags are set.
bool m_hwTransferToSystem
Whether decoded hardware frames are copied to system memory automatically.
Definition codeccontext.h:514
void setFlags2(int flags) noexcept
Access to CODEC_FLAG2_* flags.
bool m_hwAutoUpload
Whether software frames are uploaded into the pool before encoding.
Definition codeccontext.h:518
void setStrict(int strict) noexcept
Set the strictness level.
void open(const Codec &codec, OptionalErrorCode ec=throws())
Open the codec, choosing it explicitly.
void setRefCountedFrames(bool refcounted) const noexcept
Ask the codec for reference-counted frames.
std::pair< int, const std::error_category * > decodeCommon(AVFrame *outFrame, const class Packet &inPacket, size_t offset, int &frameFinished, int(*decodeProc)(AVCodecContext *, AVFrame *, int *, const AVPacket *)) noexcept
Decode one packet into an FFmpeg frame.
void addFlags(int flags) noexcept
Add AV_CODEC_FLAG_* flags.
void setTimeBase(const Rational &value) noexcept
Set the time base.
int frameSize() const noexcept
Number of samples per frame the codec works with.
void clearFlags2(int flags) noexcept
Remove AV_CODEC_FLAG2_* flags.
void open(class Dictionary &&options, OptionalErrorCode ec=throws())
Open the codec with options, taking ownership of the dictionary.
void close(OptionalErrorCode ec=throws())
Close the codec context.
void setFlags(int flags) noexcept
Access to CODEC_FLAG_* flags.
int flags2() noexcept
Current AV_CODEC_FLAG2_* mask.
std::pair< int, const std::error_category * > decodeCommon(T &outFrame, const class Packet &inPacket, size_t offset, int &frameFinished, int(*decodeProc)(AVCodecContext *, AVFrame *, int *, const AVPacket *))
Decode one packet into a typed frame.
void setCodec(const class Codec &codec, bool resetDefaults, Direction direction, AVMediaType type, OptionalErrorCode ec=throws())
Attach a codec and validate it against the direction and media type.
Packet receive(OptionalErrorCode ec=throws())
Read one decoded packet from an encoder.
CodecContextBase(const class Stream &st, const class Codec &codec=Codec())
Create a context attached to a stream.
Definition codeccontext.h:783
CodecContextBase()
Create an empty context of this direction and media type.
Definition codeccontext.h:770
void setCodec(const Codec &codec, OptionalErrorCode ec=throws())
Choose the codec without resetting its defaults.
Definition codeccontext.h:822
bool flush(OptionalErrorCode ec=throws())
Puts the codec into draining mode.
Definition codeccontext.h:863
void setCodec(const Codec &codec, bool resetDefaults, OptionalErrorCode ec=throws())
Choose the codec.
Definition codeccontext.h:835
CodecContextBase(CodecContextBase &&other)
Move the context.
Definition codeccontext.h:808
CodecContextBase(const Codec &codec)
Create a context for a codec, without a stream.
Definition codeccontext.h:795
Clazz & moveOperator(Clazz &&rhs)
Move-assign the derived object and return it.
Definition codeccontext.h:753
AVMediaType codecType() const noexcept
The media type of this context.
Definition codeccontext.h:845
Codec descriptor.
Definition codec.h:32
Implements interface to access to the AVDictionary entity.
Definition dictionary.h:38
AVMediaType codecType() const noexcept
The media type of the attached stream or codec.
GenericCodecContext & operator=(GenericCodecContext &&rhs)
Move assignment.
GenericCodecContext(Stream st)
Attach the context to a stream without a direction.
GenericCodecContext(GenericCodecContext &&other)
Move the context.
GenericCodecContext()=default
Create an empty context; no codec and no stream.
Carries the caller's choice between exceptions and error codes.
Definition averror.h:96
Compressed data and its metadata.
Definition packet.h:110
The PixelFormat class is a simple wrapper for AVPixelFormat that allow to acces it it properties.
Definition pixelformat.h:41
Rational number: a numerator and a denominator.
Definition rational.h:49
The SampleFormat class is a simple proxy class for AVSampleFormat.
Definition sampleformat.h:35
One stream inside a container.
Definition stream.h:34
Base class for subtitle codec contexts.
Definition codeccontext.h:1878
void setPktTimeBase(const Rational &value) noexcept
Set the time base used to fill AVSubtitle::pts.
Definition codeccontext.h:1973
void setSubtitleHeader(std::string_view header, OptionalErrorCode ec=throws())
Sets the subtitle header.
Definition codeccontext.h:1906
void setDefaultSubtitleHeader(OptionalErrorCode ec=throws())
Sets the built-in ASS header accepted by every text subtitle encoder provided by FFmpeg.
Definition codeccontext.h:1940
bool flush(OptionalErrorCode ec=throws())=delete
Removing the flush is deliberate: subtitle codecs do not support the send/receive API,...
std::string_view subtitleHeader() const noexcept
Subtitle header in ASS/SSA format, or an empty view when no header has been set.
Definition codeccontext.h:1891
Rational pktTimeBase() const noexcept
Time base used by the decoder to fill AVSubtitle::pts.
Definition codeccontext.h:1962
CodecContextBase< Clazz, _direction, AVMEDIA_TYPE_SUBTITLE > Parent
/// The base class this context derives from.
Definition codeccontext.h:1883
void clearSubtitleHeader() noexcept
Releases the subtitle header.
Definition codeccontext.h:1948
SubtitleCodecContext< SubtitleDecoderContext, Direction::Decoding > Parent
/// The base class this context derives from.
Definition codeccontext.h:2002
SubtitleDecoderContext(SubtitleDecoderContext &&other)
Move the decoder.
SubtitleDecoderContext()=default
Create an empty decoder; set a codec and open() it later.
SubtitleFrame decode(const Packet &packet, OptionalErrorCode ec=throws())
Decodes one subtitle packet.
SubtitleFrame decode(const Packet &packet, size_t offset, size_t &decodedBytes, OptionalErrorCode ec=throws())
Decodes one subtitle packet starting at the given offset.
SubtitleDecoderContext & operator=(SubtitleDecoderContext &&other)
Move assignment.
SubtitleEncoderContext()=default
Create an empty encoder; set a codec and open() it later.
SubtitleEncoderContext(SubtitleEncoderContext &&other)
Move the encoder.
Packet encode(const SubtitleFrame &frame, OptionalErrorCode ec=throws())
Encodes one subtitle frame.
SubtitleEncoderContext & operator=(SubtitleEncoderContext &&other)
Move assignment.
SubtitleCodecContext< SubtitleEncoderContext, Direction::Encoding > Parent
/// The base class this context derives from.
Definition codeccontext.h:2075
Owning, move-only subtitle frame.
Definition subtitle.h:274
Video-specific parameters shared by video encoders and decoders.
Definition codeccontext.h:917
int bitRateTolerance() const
How far the encoder may deviate from the target bit rate.
Definition codeccontext.h:1000
void setGopSize(int32_t size)
Set the distance between key frames.
Definition codeccontext.h:1112
void setCodedHeight(int h)
Set the coded height independently of the display height.
Definition codeccontext.h:1077
int height() const
Frame height stored in the context.
Definition codeccontext.h:940
void setGlobalQuality(int32_t quality)
Set the global quality for constant-quality encoders.
Definition codeccontext.h:1099
void setPixelFormat(PixelFormat pixelFormat)
Set the pixel format.
Definition codeccontext.h:1088
PixelFormat pixelFormat() const
Pixel format the codec works with.
Definition codeccontext.h:970
int codedHeight() const
Height as coded by the bitstream, before any cropping.
Definition codeccontext.h:960
void setCodedWidth(int w)
Set the coded width independently of the display width.
Definition codeccontext.h:1065
int codedWidth() const
Width as coded by the bitstream, before any cropping.
Definition codeccontext.h:950
void setSampleAspectRatio(const Rational &sampleAspectRatio)
Set the pixel aspect ratio.
Definition codeccontext.h:1142
CodecContextBase< Clazz, _direction, AVMEDIA_TYPE_VIDEO > Parent
The base class this context derives from.
Definition codeccontext.h:920
void setWidth(int w)
Set the frame width.
Definition codeccontext.h:1033
void setBitRateTolerance(int bitRateTolerance)
Set how far the encoder may deviate from the target bit rate.
Definition codeccontext.h:1122
void setMaxBFrames(int maxBFrames)
Limit the number of B-frames.
Definition codeccontext.h:1132
int maxBFrames() const
Maximum number of B-frames the encoder may use.
Definition codeccontext.h:1010
void setHeight(int h)
Set the frame height.
Definition codeccontext.h:1049
int32_t globalQuality() const
Global quality value used by constant-quality encoders.
Definition codeccontext.h:980
Rational sampleAspectRatio() const
Pixel aspect ratio of the frames.
Definition codeccontext.h:1020
int32_t gopSize() const
Distance between key frames.
Definition codeccontext.h:990
int width() const
Frame width stored in the context.
Definition codeccontext.h:930
bool isHwTransferToSystem() const noexcept
Whether decoded hardware frames are transferred to system memory.
VideoFrame decode(const Packet &packet, size_t offset, size_t &decodedBytes, OptionalErrorCode ec=throws(), bool autoAllocateFrame=true)
decodeVideo - decode video packet with additional parameters
VideoDecoderContext()=default
Create an empty decoder; set a codec and open() it later.
void clearHwDeviceContext() noexcept
Removes the hardware device and restores the default get_format().
VideoCodecContext< VideoDecoderContext, Direction::Decoding > Parent
/// The base class this context derives from.
Definition codeccontext.h:1166
hw::DeviceContext hwDeviceContext() const noexcept
Device context set with setHwDeviceContext().
bool send(const Packet &packet, OptionalErrorCode ec=throws())
Sends a packet to the decoder.
VideoFrame receive(OptionalErrorCode ec=throws(), bool autoAllocateFrame=true)
Receives one decoded frame.
VideoDecoderContext(VideoDecoderContext &&other)
Move the decoder.
void setHwDeviceContext(const hw::DeviceContext &device, OptionalErrorCode ec=throws())
Configures a hardware device for decoding.
hw::FramesContext hwFramesContext() const noexcept
Frames context of decoded hardware frames.
VideoFrame decode(const Packet &packet, OptionalErrorCode ec=throws(), bool autoAllocateFrame=true)
decodeVideo - decode video packet
void setHwTransferToSystem(bool enabled) noexcept
Transfer decoded hardware frames to system memory automatically.
VideoDecoderContext & operator=(VideoDecoderContext &&other)
Move assignment.
hw::DeviceContext hwDeviceContext() const noexcept
Device configured for this encoder.
VideoCodecContext< VideoEncoderContext, Direction::Encoding > Parent
/// The base class this context derives from.
Definition codeccontext.h:1343
Packet encode(const VideoFrame &inFrame, OptionalErrorCode ec=throws())
encodeVideo - encode video frame
VideoEncoderContext(VideoEncoderContext &&other)
Move the encoder.
void setHwDeviceContext(const hw::DeviceContext &device, OptionalErrorCode ec=throws())
Sets AVCodecContext::hw_device_ctx before open().
VideoEncoderContext & operator=(VideoEncoderContext &&other)
Move assignment.
Packet encode(OptionalErrorCode ec=throws())
encodeVideo - Flush encoder
void configureHwEncoding(const hw::DeviceContext &device, hw::EncodingMode mode=hw::EncodingMode::Auto, PixelFormat swFormat=AV_PIX_FMT_NONE, OptionalErrorCode ec=throws())
Configures hardware encoding for the given device.
bool isHwEncoding() const noexcept
Whether hardware encoding is configured.
void setHwAutoUpload(bool enabled) noexcept
Upload software frames automatically before encoding.
void clearHwDeviceContext() noexcept
Removes the hardware device context.
hw::FramesContext hwFramesContext() const noexcept
Frames context configured for this encoder.
VideoEncoderContext()=default
Create an empty encoder; set a codec and open() it later.
void clearHwFramesContext() noexcept
Removes the hardware frames context.
Packet receive(OptionalErrorCode ec=throws())
Receives one encoded packet.
bool send(const VideoFrame &frame, OptionalErrorCode ec=throws())
Sends a frame to the encoder.
hw::EncodingMode hwEncodingMode() const noexcept
How the encoder receives hardware frames.
void setHwFramesContext(const hw::FramesContext &frames, OptionalErrorCode ec=throws())
Sets AVCodecContext::hw_frames_ctx before open().
bool isHwAutoUpload() const noexcept
Whether software frames are uploaded automatically.
One video frame.
Definition frame.h:578
Owner of an AVHWDeviceContext.
Definition hwcontext.h:126
Codec descriptors and lookup by name or id.
FFmpeg types re-exported for the public API and small value wrappers.
#define RAW_GET(field, def)
Read an AVCodecContext-style field through a possibly empty raw pointer.
Definition ffmpeg.h:114
#define RAW_SET(field, val)
Write an AVCodecContext-style field when the raw pointer is set.
Definition ffmpeg.h:121
#define RAW_GET2(cond, field, def)
Read a field when the pointer is set and a condition holds.
Definition ffmpeg.h:130
#define RAW_SET2(cond, field, val)
Write a field when the pointer is set and a condition holds.
Definition ffmpeg.h:138
Video frames, audio samples and their common frame interface.
Hardware devices, hardware frames and hardware codec configuration.
Root namespace of the library.
Definition audioresampler.h:19
void clear_if(OptionalErrorCode ec)
clear_if - clear error code if it is not av::throws()
Definition averror.h:368
OptionalErrorCode throws()
Helper to construct null OptionalErrorCode object.
Definition averror.h:310
Direction
Direction a codec or a stream is used in.
Definition codecparameters.h:29
@ Invalid
Not a direction; the default state of a context that has none.
Definition codecparameters.h:31
@ Decoding
Decompressing packets into frames.
Definition codecparameters.h:35
std::error_code make_error_code(av::Errors errc) noexcept
Build an error code from an avcpp error.
Definition averror.h:223
std::unique_ptr< T, void(*)(void *)> mallocz(size_t size)
Allocate zeroed memory with the FFmpeg allocator.
Definition avutils.h:326
void freep(T *&ptr) noexcept
Frees a buffer allocated by the FFmpeg allocator and resets the pointer.
Definition avutils.h:367
FfmpegCategory & ffmpeg_category()
Error category that wraps FFmpeg return codes.
Definition averror.h:196
auto make_array_view_until(auto *ptr, auto value)
Helper to create array view with end marker.
Definition avutils.h:927
void throws_if(OptionalErrorCode ec, int errcode, const Category &cat)
Throw or store an error, depending on what the caller passed.
Definition averror.h:323
T guessValue(const T &value, L list)
Select more approptiate value from given value list.
Definition avutils.h:951
STL namespace.
Pixel formats.
Audio sample formats.
Streams inside a container: parameters, time base and disposition.
void _log(int level, const char *fmt) const
Definition ffmpeg.h:85
AVCodecContext * m_raw
Definition ffmpeg.h:105
Predicate that compares an element with a stored value.
Definition avutils.h:979
Subtitle frames: text and ASS payloads, bitmap rectangles.
std::string_view defaultAssHeader() noexcept
Returns a built-in ASS/SSA script header accepted by the FFmpeg text subtitle encoders (subrip,...