Repository: Nevcairiel/LAVFilters Branch: master Commit: 8c4ee4e52c78 Files: 695 Total size: 6.2 MB Directory structure: gitextract_htgb5fag/ ├── .clang-format ├── .editorconfig ├── .github/ │ └── FUNDING.yml ├── .gitignore ├── .gitmodules ├── CHANGELOG.txt ├── COPYING ├── LAVFilters.iss ├── LAVFilters.sln ├── README.md ├── build.bat ├── build_ffmpeg.sh ├── build_ffmpeg_msvc.sh ├── common/ │ ├── DSUtilLite/ │ │ ├── BaseDSPropPage.cpp │ │ ├── BaseDSPropPage.h │ │ ├── BaseTrayIcon.cpp │ │ ├── BaseTrayIcon.h │ │ ├── ByteParser.cpp │ │ ├── ByteParser.h │ │ ├── CueSheet.cpp │ │ ├── CueSheet.h │ │ ├── DSMResourceBag.cpp │ │ ├── DSMResourceBag.h │ │ ├── DSUtilLite.vcxproj │ │ ├── DSUtilLite.vcxproj.filters │ │ ├── DShowUtil.cpp │ │ ├── DShowUtil.h │ │ ├── DeCSS/ │ │ │ ├── CSSauth.cpp │ │ │ ├── CSSauth.h │ │ │ ├── CSSscramble.cpp │ │ │ ├── CSSscramble.h │ │ │ ├── DeCSSInputPin.cpp │ │ │ └── DeCSSInputPin.h │ │ ├── FloatingAverage.h │ │ ├── FontInstaller.cpp │ │ ├── FontInstaller.h │ │ ├── H264Nalu.cpp │ │ ├── H264Nalu.h │ │ ├── MediaSampleSideData.cpp │ │ ├── MediaSampleSideData.h │ │ ├── PopupMenu.cpp │ │ ├── PopupMenu.h │ │ ├── SynchronizedQueue.h │ │ ├── filterreg.cpp │ │ ├── gpu_memcpy_sse4.h │ │ ├── growarray.h │ │ ├── lavf_log.h │ │ ├── locale.cpp │ │ ├── rand_sse.h │ │ ├── registry.cpp │ │ ├── registry.h │ │ ├── stdafx.cpp │ │ ├── stdafx.h │ │ └── timer.h │ ├── baseclasses/ │ │ ├── amextra.cpp │ │ ├── amextra.h │ │ ├── amfilter.cpp │ │ ├── amfilter.h │ │ ├── amvideo.cpp │ │ ├── arithutil.cpp │ │ ├── baseclasses.vcxproj │ │ ├── baseclasses.vcxproj.filters │ │ ├── cache.h │ │ ├── checkbmi.h │ │ ├── combase.cpp │ │ ├── combase.h │ │ ├── cprop.cpp │ │ ├── cprop.h │ │ ├── ctlutil.cpp │ │ ├── ctlutil.h │ │ ├── ddmm.cpp │ │ ├── ddmm.h │ │ ├── dllentry.cpp │ │ ├── dllsetup.cpp │ │ ├── dllsetup.h │ │ ├── dxmperf.h │ │ ├── fourcc.h │ │ ├── measure.h │ │ ├── msgthrd.h │ │ ├── mtype.cpp │ │ ├── mtype.h │ │ ├── outputq.cpp │ │ ├── outputq.h │ │ ├── perflog.cpp │ │ ├── perflog.h │ │ ├── perfstruct.h │ │ ├── pstream.cpp │ │ ├── pstream.h │ │ ├── pullpin.cpp │ │ ├── pullpin.h │ │ ├── refclock.cpp │ │ ├── refclock.h │ │ ├── reftime.h │ │ ├── renbase.cpp │ │ ├── renbase.h │ │ ├── schedule.cpp │ │ ├── schedule.h │ │ ├── seekpt.cpp │ │ ├── seekpt.h │ │ ├── source.cpp │ │ ├── source.h │ │ ├── streams.h │ │ ├── strmctl.cpp │ │ ├── strmctl.h │ │ ├── sysclock.cpp │ │ ├── sysclock.h │ │ ├── transfrm.cpp │ │ ├── transfrm.h │ │ ├── transip.cpp │ │ ├── transip.h │ │ ├── videoctl.cpp │ │ ├── videoctl.h │ │ ├── vtrans.cpp │ │ ├── vtrans.h │ │ ├── winctrl.cpp │ │ ├── winctrl.h │ │ ├── winutil.cpp │ │ ├── winutil.h │ │ ├── wxdebug.cpp │ │ ├── wxdebug.h │ │ ├── wxlist.cpp │ │ ├── wxlist.h │ │ ├── wxutil.cpp │ │ └── wxutil.h │ ├── common.props │ ├── genversion.bat │ ├── includes/ │ │ ├── ILAVPinInfo.h │ │ ├── IMediaSideDataFFmpeg.h │ │ ├── LAVSplitterSettingsInternal.h │ │ ├── SubRenderIntf.h │ │ ├── common_defines.h │ │ ├── moreuuids.h │ │ └── version.h │ └── platform.props ├── decoder/ │ ├── LAVAudio/ │ │ ├── AudioSettingsProp.cpp │ │ ├── AudioSettingsProp.h │ │ ├── Bitstream.cpp │ │ ├── BitstreamMAT.cpp │ │ ├── BitstreamParser.cpp │ │ ├── BitstreamParser.h │ │ ├── LAVAudio.cpp │ │ ├── LAVAudio.def │ │ ├── LAVAudio.h │ │ ├── LAVAudio.manifest │ │ ├── LAVAudio.rc │ │ ├── LAVAudio.rc2 │ │ ├── LAVAudio.vcxproj │ │ ├── LAVAudio.vcxproj.filters │ │ ├── Media.cpp │ │ ├── Media.h │ │ ├── PostProcessor.cpp │ │ ├── PostProcessor.h │ │ ├── dllmain.cpp │ │ ├── parser/ │ │ │ ├── dts.cpp │ │ │ ├── dts.h │ │ │ └── parser.h │ │ ├── resource.h │ │ ├── stdafx.cpp │ │ └── stdafx.h │ └── LAVVideo/ │ ├── CCOutputPin.cpp │ ├── CCOutputPin.h │ ├── DecodeManager.cpp │ ├── DecodeManager.h │ ├── Filtering.cpp │ ├── LAVPixFmtConverter.cpp │ ├── LAVPixFmtConverter.h │ ├── LAVVideo.cpp │ ├── LAVVideo.def │ ├── LAVVideo.h │ ├── LAVVideo.manifest │ ├── LAVVideo.rc │ ├── LAVVideo.rc2 │ ├── LAVVideo.vcxproj │ ├── LAVVideo.vcxproj.filters │ ├── Media.cpp │ ├── Media.h │ ├── VideoInputPin.cpp │ ├── VideoInputPin.h │ ├── VideoOutputPin.cpp │ ├── VideoOutputPin.h │ ├── VideoSettingsProp.cpp │ ├── VideoSettingsProp.h │ ├── decoders/ │ │ ├── DecBase.h │ │ ├── ILAVDecoder.h │ │ ├── avcodec.cpp │ │ ├── avcodec.h │ │ ├── cuvid/ │ │ │ ├── dynlink_cuda.h │ │ │ ├── dynlink_cuda_cuda.h │ │ │ ├── dynlink_cuda_d3d.h │ │ │ ├── dynlink_cuviddec.h │ │ │ └── dynlink_nvcuvid.h │ │ ├── cuvid.cpp │ │ ├── cuvid.h │ │ ├── d3d11/ │ │ │ ├── D3D11SurfaceAllocator.cpp │ │ │ └── D3D11SurfaceAllocator.h │ │ ├── d3d11va.cpp │ │ ├── d3d11va.h │ │ ├── dxva2/ │ │ │ ├── DXVA2SurfaceAllocator.cpp │ │ │ ├── DXVA2SurfaceAllocator.h │ │ │ ├── dxva_common.cpp │ │ │ └── dxva_common.h │ │ ├── dxva2dec.cpp │ │ ├── dxva2dec.h │ │ ├── msdk_mvc.cpp │ │ ├── msdk_mvc.h │ │ ├── mvc/ │ │ │ ├── include/ │ │ │ │ ├── mfxcommon.h │ │ │ │ ├── mfxdefs.h │ │ │ │ ├── mfxmvc.h │ │ │ │ ├── mfxsession.h │ │ │ │ ├── mfxstructures.h │ │ │ │ ├── mfxvideo.h │ │ │ │ └── mfxvstructures.h │ │ │ ├── lib32/ │ │ │ │ └── libmfx.lib │ │ │ └── lib64/ │ │ │ └── libmfx.lib │ │ ├── pixfmt.cpp │ │ ├── quicksync.cpp │ │ ├── quicksync.h │ │ ├── wmv9mft.cpp │ │ └── wmv9mft.h │ ├── dllmain.cpp │ ├── parsers/ │ │ ├── AnnexBConverter.cpp │ │ ├── AnnexBConverter.h │ │ ├── H264SequenceParser.cpp │ │ ├── H264SequenceParser.h │ │ ├── HEVCSequenceParser.cpp │ │ ├── HEVCSequenceParser.h │ │ ├── MPEG2HeaderParser.cpp │ │ ├── MPEG2HeaderParser.h │ │ ├── VC1HeaderParser.cpp │ │ └── VC1HeaderParser.h │ ├── pixconv/ │ │ ├── convert_direct.cpp │ │ ├── convert_generic.cpp │ │ ├── interleave.cpp │ │ ├── pixconv.cpp │ │ ├── pixconv_internal.h │ │ ├── pixconv_sse2_templates.h │ │ ├── rgb2rgb_unscaled.cpp │ │ ├── yuv2rgb.cpp │ │ ├── yuv2yuv_unscaled.cpp │ │ ├── yuv420_yuy2.cpp │ │ └── yuv444_ayuv.cpp │ ├── resource.h │ ├── stdafx.cpp │ ├── stdafx.h │ └── subtitles/ │ ├── LAVSubtitleConsumer.cpp │ ├── LAVSubtitleConsumer.h │ ├── LAVSubtitleFrame.cpp │ ├── LAVSubtitleFrame.h │ ├── LAVSubtitleProvider.cpp │ ├── LAVSubtitleProvider.h │ ├── LAVVideoSubtitleInputPin.cpp │ ├── LAVVideoSubtitleInputPin.h │ ├── SubRenderOptionsImpl.cpp │ ├── SubRenderOptionsImpl.h │ └── blend/ │ └── blend_generic.cpp ├── demuxer/ │ ├── Demuxers/ │ │ ├── BDDemuxer.cpp │ │ ├── BDDemuxer.h │ │ ├── BaseDemuxer.cpp │ │ ├── BaseDemuxer.h │ │ ├── Demuxers.vcxproj │ │ ├── Demuxers.vcxproj.filters │ │ ├── ExtradataParser.cpp │ │ ├── ExtradataParser.h │ │ ├── LAVFAudioHelper.cpp │ │ ├── LAVFAudioHelper.h │ │ ├── LAVFDemuxer.cpp │ │ ├── LAVFDemuxer.h │ │ ├── LAVFInputFormats.cpp │ │ ├── LAVFStreamInfo.cpp │ │ ├── LAVFStreamInfo.h │ │ ├── LAVFUtils.cpp │ │ ├── LAVFUtils.h │ │ ├── LAVFVideoHelper.cpp │ │ ├── LAVFVideoHelper.h │ │ ├── Packet.cpp │ │ ├── Packet.h │ │ ├── StreamInfo.cpp │ │ ├── StreamInfo.h │ │ ├── stdafx.cpp │ │ └── stdafx.h │ └── LAVSplitter/ │ ├── InputPin.cpp │ ├── InputPin.h │ ├── LAVSplitter.cpp │ ├── LAVSplitter.def │ ├── LAVSplitter.h │ ├── LAVSplitter.manifest │ ├── LAVSplitter.rc │ ├── LAVSplitter.rc2 │ ├── LAVSplitter.vcxproj │ ├── LAVSplitter.vcxproj.filters │ ├── LAVSplitterTrayIcon.cpp │ ├── LAVSplitterTrayIcon.h │ ├── OutputPin.cpp │ ├── OutputPin.h │ ├── PacketAllocator.cpp │ ├── PacketAllocator.h │ ├── PacketQueue.cpp │ ├── PacketQueue.h │ ├── SettingsProp.cpp │ ├── SettingsProp.h │ ├── StreamParser.cpp │ ├── StreamParser.h │ ├── dllmain.cpp │ ├── resource.h │ ├── stdafx.cpp │ └── stdafx.h ├── include/ │ ├── IBitRateInfo.h │ ├── IBufferInfo.h │ ├── ID3DVideoMemoryConfiguration.h │ ├── IDSMResourceBag.h │ ├── IGraphRebuildDelegate.h │ ├── IKeyFrameInfo.h │ ├── ILAVDynamicAllocator.h │ ├── IMediaSample3D.h │ ├── IMediaSideData.h │ ├── IPinSegmentEx.h │ ├── ISpecifyPropertyPages2.h │ ├── IStreamSourceControl.h │ ├── ITrackInfo.h │ ├── IURLSourceFilterLAV.h │ ├── LAVAudioSettings.h │ ├── LAVSplitterSettings.h │ ├── LAVVideoSettings.h │ └── README.txt ├── resources/ │ └── LAVFilters.Dependencies.manifest └── thirdparty/ ├── 32/ │ ├── include/ │ │ ├── avisynth/ │ │ │ ├── avisynth.h │ │ │ ├── avisynth_c.h │ │ │ └── avs/ │ │ │ ├── alignment.h │ │ │ ├── arch.h │ │ │ ├── capi.h │ │ │ ├── config.h │ │ │ ├── cpuid.h │ │ │ ├── filesystem.h │ │ │ ├── minmax.h │ │ │ ├── posix.h │ │ │ ├── types.h │ │ │ ├── version.h │ │ │ └── win.h │ │ ├── dav1d/ │ │ │ ├── common.h │ │ │ ├── data.h │ │ │ ├── dav1d.h │ │ │ ├── headers.h │ │ │ ├── picture.h │ │ │ └── version.h │ │ ├── gmp.h │ │ ├── gnutls/ │ │ │ ├── abstract.h │ │ │ ├── compat.h │ │ │ ├── crypto.h │ │ │ ├── dtls.h │ │ │ ├── gnutls.h │ │ │ ├── ocsp.h │ │ │ ├── openpgp.h │ │ │ ├── pkcs11.h │ │ │ ├── pkcs12.h │ │ │ ├── pkcs7.h │ │ │ ├── self-test.h │ │ │ ├── socket.h │ │ │ ├── system-keys.h │ │ │ ├── tpm.h │ │ │ ├── urls.h │ │ │ ├── x509-ext.h │ │ │ └── x509.h │ │ ├── libxml2/ │ │ │ └── libxml/ │ │ │ ├── HTMLparser.h │ │ │ ├── HTMLtree.h │ │ │ ├── SAX.h │ │ │ ├── SAX2.h │ │ │ ├── c14n.h │ │ │ ├── catalog.h │ │ │ ├── chvalid.h │ │ │ ├── debugXML.h │ │ │ ├── dict.h │ │ │ ├── encoding.h │ │ │ ├── entities.h │ │ │ ├── globals.h │ │ │ ├── hash.h │ │ │ ├── list.h │ │ │ ├── nanoftp.h │ │ │ ├── nanohttp.h │ │ │ ├── parser.h │ │ │ ├── parserInternals.h │ │ │ ├── pattern.h │ │ │ ├── relaxng.h │ │ │ ├── schemasInternals.h │ │ │ ├── schematron.h │ │ │ ├── threads.h │ │ │ ├── tree.h │ │ │ ├── uri.h │ │ │ ├── valid.h │ │ │ ├── xinclude.h │ │ │ ├── xlink.h │ │ │ ├── xmlIO.h │ │ │ ├── xmlautomata.h │ │ │ ├── xmlerror.h │ │ │ ├── xmlexports.h │ │ │ ├── xmlmemory.h │ │ │ ├── xmlmodule.h │ │ │ ├── xmlreader.h │ │ │ ├── xmlregexp.h │ │ │ ├── xmlsave.h │ │ │ ├── xmlschemas.h │ │ │ ├── xmlschemastypes.h │ │ │ ├── xmlstring.h │ │ │ ├── xmlunicode.h │ │ │ ├── xmlversion.h │ │ │ ├── xmlwriter.h │ │ │ ├── xpath.h │ │ │ ├── xpathInternals.h │ │ │ └── xpointer.h │ │ ├── nettle/ │ │ │ ├── aes.h │ │ │ ├── arcfour.h │ │ │ ├── arctwo.h │ │ │ ├── asn1.h │ │ │ ├── balloon.h │ │ │ ├── base16.h │ │ │ ├── base64.h │ │ │ ├── bignum.h │ │ │ ├── blowfish.h │ │ │ ├── buffer.h │ │ │ ├── camellia.h │ │ │ ├── cast128.h │ │ │ ├── cbc.h │ │ │ ├── ccm.h │ │ │ ├── cfb.h │ │ │ ├── chacha-poly1305.h │ │ │ ├── chacha.h │ │ │ ├── cmac.h │ │ │ ├── ctr.h │ │ │ ├── curve25519.h │ │ │ ├── curve448.h │ │ │ ├── des.h │ │ │ ├── dsa-compat.h │ │ │ ├── dsa.h │ │ │ ├── eax.h │ │ │ ├── ecc-curve.h │ │ │ ├── ecc.h │ │ │ ├── ecdsa.h │ │ │ ├── eddsa.h │ │ │ ├── gcm.h │ │ │ ├── gostdsa.h │ │ │ ├── gosthash94.h │ │ │ ├── hkdf.h │ │ │ ├── hmac.h │ │ │ ├── knuth-lfib.h │ │ │ ├── macros.h │ │ │ ├── md2.h │ │ │ ├── md4.h │ │ │ ├── md5-compat.h │ │ │ ├── md5.h │ │ │ ├── memops.h │ │ │ ├── memxor.h │ │ │ ├── nettle-meta.h │ │ │ ├── nettle-types.h │ │ │ ├── nist-keywrap.h │ │ │ ├── ocb.h │ │ │ ├── pbkdf2.h │ │ │ ├── pgp.h │ │ │ ├── pkcs1.h │ │ │ ├── poly1305.h │ │ │ ├── pss-mgf1.h │ │ │ ├── pss.h │ │ │ ├── realloc.h │ │ │ ├── ripemd160.h │ │ │ ├── rsa.h │ │ │ ├── salsa20.h │ │ │ ├── serpent.h │ │ │ ├── sexp.h │ │ │ ├── sha.h │ │ │ ├── sha1.h │ │ │ ├── sha2.h │ │ │ ├── sha3.h │ │ │ ├── siv-cmac.h │ │ │ ├── siv-gcm.h │ │ │ ├── sm3.h │ │ │ ├── sm4.h │ │ │ ├── streebog.h │ │ │ ├── twofish.h │ │ │ ├── umac.h │ │ │ ├── version.h │ │ │ ├── xts.h │ │ │ └── yarrow.h │ │ ├── opencore-amrnb/ │ │ │ ├── interf_dec.h │ │ │ └── interf_enc.h │ │ ├── opencore-amrwb/ │ │ │ ├── dec_if.h │ │ │ └── if_rom.h │ │ └── speex/ │ │ ├── speex.h │ │ ├── speex_bits.h │ │ ├── speex_callbacks.h │ │ ├── speex_config_types.h │ │ ├── speex_header.h │ │ ├── speex_stereo.h │ │ └── speex_types.h │ └── lib/ │ ├── libdav1d.a │ ├── libgmp.a │ ├── libgnutls.a │ ├── libhogweed.a │ ├── libnettle.a │ ├── libopencore-amrnb.a │ ├── libopencore-amrwb.a │ ├── libspeex.a │ ├── libxml2.a │ └── pkgconfig/ │ ├── dav1d.pc │ ├── gmp.pc │ ├── gnutls.pc │ ├── hogweed.pc │ ├── libxml-2.0.pc │ ├── nettle.pc │ ├── opencore-amrnb.pc │ ├── opencore-amrwb.pc │ └── speex.pc ├── 64/ │ ├── include/ │ │ ├── avisynth/ │ │ │ ├── avisynth.h │ │ │ ├── avisynth_c.h │ │ │ └── avs/ │ │ │ ├── alignment.h │ │ │ ├── arch.h │ │ │ ├── capi.h │ │ │ ├── config.h │ │ │ ├── cpuid.h │ │ │ ├── filesystem.h │ │ │ ├── minmax.h │ │ │ ├── posix.h │ │ │ ├── types.h │ │ │ ├── version.h │ │ │ └── win.h │ │ ├── dav1d/ │ │ │ ├── common.h │ │ │ ├── data.h │ │ │ ├── dav1d.h │ │ │ ├── headers.h │ │ │ ├── picture.h │ │ │ └── version.h │ │ ├── gmp.h │ │ ├── gnutls/ │ │ │ ├── abstract.h │ │ │ ├── compat.h │ │ │ ├── crypto.h │ │ │ ├── dtls.h │ │ │ ├── gnutls.h │ │ │ ├── ocsp.h │ │ │ ├── openpgp.h │ │ │ ├── pkcs11.h │ │ │ ├── pkcs12.h │ │ │ ├── pkcs7.h │ │ │ ├── self-test.h │ │ │ ├── socket.h │ │ │ ├── system-keys.h │ │ │ ├── tpm.h │ │ │ ├── urls.h │ │ │ ├── x509-ext.h │ │ │ └── x509.h │ │ ├── libxml2/ │ │ │ └── libxml/ │ │ │ ├── HTMLparser.h │ │ │ ├── HTMLtree.h │ │ │ ├── SAX.h │ │ │ ├── SAX2.h │ │ │ ├── c14n.h │ │ │ ├── catalog.h │ │ │ ├── chvalid.h │ │ │ ├── debugXML.h │ │ │ ├── dict.h │ │ │ ├── encoding.h │ │ │ ├── entities.h │ │ │ ├── globals.h │ │ │ ├── hash.h │ │ │ ├── list.h │ │ │ ├── nanoftp.h │ │ │ ├── nanohttp.h │ │ │ ├── parser.h │ │ │ ├── parserInternals.h │ │ │ ├── pattern.h │ │ │ ├── relaxng.h │ │ │ ├── schemasInternals.h │ │ │ ├── schematron.h │ │ │ ├── threads.h │ │ │ ├── tree.h │ │ │ ├── uri.h │ │ │ ├── valid.h │ │ │ ├── xinclude.h │ │ │ ├── xlink.h │ │ │ ├── xmlIO.h │ │ │ ├── xmlautomata.h │ │ │ ├── xmlerror.h │ │ │ ├── xmlexports.h │ │ │ ├── xmlmemory.h │ │ │ ├── xmlmodule.h │ │ │ ├── xmlreader.h │ │ │ ├── xmlregexp.h │ │ │ ├── xmlsave.h │ │ │ ├── xmlschemas.h │ │ │ ├── xmlschemastypes.h │ │ │ ├── xmlstring.h │ │ │ ├── xmlunicode.h │ │ │ ├── xmlversion.h │ │ │ ├── xmlwriter.h │ │ │ ├── xpath.h │ │ │ ├── xpathInternals.h │ │ │ └── xpointer.h │ │ ├── nettle/ │ │ │ ├── aes.h │ │ │ ├── arcfour.h │ │ │ ├── arctwo.h │ │ │ ├── asn1.h │ │ │ ├── balloon.h │ │ │ ├── base16.h │ │ │ ├── base64.h │ │ │ ├── bignum.h │ │ │ ├── blowfish.h │ │ │ ├── buffer.h │ │ │ ├── camellia.h │ │ │ ├── cast128.h │ │ │ ├── cbc.h │ │ │ ├── ccm.h │ │ │ ├── cfb.h │ │ │ ├── chacha-poly1305.h │ │ │ ├── chacha.h │ │ │ ├── cmac.h │ │ │ ├── ctr.h │ │ │ ├── curve25519.h │ │ │ ├── curve448.h │ │ │ ├── des.h │ │ │ ├── dsa-compat.h │ │ │ ├── dsa.h │ │ │ ├── eax.h │ │ │ ├── ecc-curve.h │ │ │ ├── ecc.h │ │ │ ├── ecdsa.h │ │ │ ├── eddsa.h │ │ │ ├── gcm.h │ │ │ ├── gostdsa.h │ │ │ ├── gosthash94.h │ │ │ ├── hkdf.h │ │ │ ├── hmac.h │ │ │ ├── knuth-lfib.h │ │ │ ├── macros.h │ │ │ ├── md2.h │ │ │ ├── md4.h │ │ │ ├── md5-compat.h │ │ │ ├── md5.h │ │ │ ├── memops.h │ │ │ ├── memxor.h │ │ │ ├── nettle-meta.h │ │ │ ├── nettle-types.h │ │ │ ├── nist-keywrap.h │ │ │ ├── ocb.h │ │ │ ├── pbkdf2.h │ │ │ ├── pgp.h │ │ │ ├── pkcs1.h │ │ │ ├── poly1305.h │ │ │ ├── pss-mgf1.h │ │ │ ├── pss.h │ │ │ ├── realloc.h │ │ │ ├── ripemd160.h │ │ │ ├── rsa.h │ │ │ ├── salsa20.h │ │ │ ├── serpent.h │ │ │ ├── sexp.h │ │ │ ├── sha.h │ │ │ ├── sha1.h │ │ │ ├── sha2.h │ │ │ ├── sha3.h │ │ │ ├── siv-cmac.h │ │ │ ├── siv-gcm.h │ │ │ ├── sm3.h │ │ │ ├── sm4.h │ │ │ ├── streebog.h │ │ │ ├── twofish.h │ │ │ ├── umac.h │ │ │ ├── version.h │ │ │ ├── xts.h │ │ │ └── yarrow.h │ │ ├── opencore-amrnb/ │ │ │ ├── interf_dec.h │ │ │ └── interf_enc.h │ │ ├── opencore-amrwb/ │ │ │ ├── dec_if.h │ │ │ └── if_rom.h │ │ └── speex/ │ │ ├── speex.h │ │ ├── speex_bits.h │ │ ├── speex_callbacks.h │ │ ├── speex_config_types.h │ │ ├── speex_header.h │ │ ├── speex_stereo.h │ │ └── speex_types.h │ └── lib/ │ ├── libdav1d.a │ ├── libgmp.a │ ├── libgnutls.a │ ├── libhogweed.a │ ├── libnettle.a │ ├── libopencore-amrnb.a │ ├── libopencore-amrwb.a │ ├── libspeex.a │ ├── libxml2.a │ └── pkgconfig/ │ ├── dav1d.pc │ ├── gmp.pc │ ├── gnutls.pc │ ├── hogweed.pc │ ├── libxml-2.0.pc │ ├── nettle.pc │ ├── opencore-amrnb.pc │ ├── opencore-amrwb.pc │ └── speex.pc ├── build instructions.txt └── versions.txt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clang-format ================================================ BasedOnStyle: Microsoft IndentWidth: 4 UseTab: Never Language: Cpp Standard: Cpp11 SortIncludes: false AlignAfterOpenBracket: Align AlignEscapedNewlines: Left AlignOperands: true AlignTrailingComments: true # AllowShortBlocksOnASingleLine: Empty AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: InlineOnly AllowShortIfStatementsOnASingleLine: Never AllowShortLambdasOnASingleLine: All AlwaysBreakAfterReturnType: None BreakConstructorInitializers: BeforeComma BreakInheritanceList: BeforeComma Cpp11BracedListStyle: true PointerAlignment: Right SpaceBeforeAssignmentOperators: true SpaceBeforeCtorInitializerColon: true SpaceBeforeInheritanceColon: true SpaceBeforeParens: ControlStatements SpaceBeforeRangeBasedForLoopColon: true # SpaceBeforeSquareBrackets: false # SpaceInEmptyBlock: false SpaceInEmptyParentheses: false SpacesInAngles: false SpacesInCStyleCastParentheses: false # SpacesInConditionalStatement: false SpacesInParentheses: false SpacesInSquareBrackets: false ================================================ FILE: .editorconfig ================================================ root = true [*] end_of_line = CRLF indent_style = space indent_size = 4 insert_final_newline = true trim_trailing_whitespace = true [ffmpeg/**] end_of_line = LF indent_style = space indent_size = 4 [libbluray/**] end_of_line = LF indent_style = space indent_size = 4 ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: Nevcairiel # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .gitignore ================================================ *.user *.suo *.sdf *.opensdf *.aps *.db *.opendb /ipch /bin_* /common/includes/version_rev.h /.vs ================================================ FILE: .gitmodules ================================================ [submodule "ffmpeg"] path = ffmpeg url = https://gitea.1f0.de/LAV/FFmpeg.git [submodule "libbluray"] path = libbluray url = https://gitea.1f0.de/LAV/libbluray.git [submodule "qsdecoder"] path = qsdecoder url = https://gitea.1f0.de/LAV/qsdecoder.git ================================================ FILE: CHANGELOG.txt ================================================ LAV DirectShow Filters Changelog =================================== 0.81.0 - 2026/01/12 LAV Splitter - NEW: Support for APV (Advanced Professional Video) video streams - Fixed: VVC in MP4 without CTTS did not play properly - Fixed: AV1 streams with invalid metadata did not get handled correctly LAV Video - NEW: Support for decoding APV (Advanced Professional Video) - Changed: Re-designed pixel format mapping to be based on a heuristic rather then hard-coded, improving support for rarely-used formats - Fixed: Deinterlacing of 4:2:2 videos was broken in 0.80 LAV Audio - Fixed: Bitstreaming TrueHD from Blu-rays with seamless branching could result in out-of-sync audio, or a noticeable gap 0.80.0 - 2025/06/20 LAV Splitter - NEW: Introduced the IURLSourceFilterLAV interface to allow opening URLs with custom user agent and referrer - NEW: Added support for WebP images - Changed: Increased the length of the advanced subtitle selection field, so its no longer cut off after 255 characters - Changed: Improved buffering behavior on badly interleaved video files - Fixed: Audio streams with an unknown/unsupported codec are no longer selected for playback, as long as others are present - Fixed: Improved accuracy of reported FPS from AviSynth scripts LAV Video - NEW: D3D11 support for HEVC 4:2:2 and 4:4:4 hardware decoding - NEW: Dolby Vision extension metadata is exported for renderers to use - Changed: Added additional media types to support more video streams - Changed: Updated dav1d for significant AV1 decoding improvements - Fixed: Improved handling of H.264 4:4:4 files encoded by certain versions of x264 - Fixed: VP9 DXVA2/D3D11 decoding could result in artifacts on some clips - Fixed: Decoding ProRes reports more accurate color details LAV Audio - Changed: Added support for additional ADPCM audio codecs 0.79.2 - 2024/04/08 LAV Splitter - Fixed: Buffering media from a high latency source was slower then expected (since 0.79) LAV Audio - Fixed: Bitstream AC3 audio could fallback to PCM on streams that start with a corrupt audio frame (since 0.78) - Fixed: Resolved a memory leak when bitstreaming AC3 0.79.1 - 2024/03/28 LAV Video - Fixed: Resolved a glitch when playing HEVC video 0.79.0 - 2024/03/25 LAV Splitter - NEW: Support for demuxing VVC video - Changed: Updated language lists to support all relevant language codes - Changed: Improved resilience of streaming HLS - Changed: Tweaked frame rate detection logic LAV Video: - NEW: Support for decoding VVC video 0.78.0 - 2023/10/25 LAV Splitter - NEW: Added identification of DTS:X in DTS HD-HRA streams - NEW: Support for various stream flags in Matroska containers (Hearing Impaired, and more) - Changed: Text-based subtitle selection now uses case-insensitive matches (ASCII characters only) - Fixed: Many stream titles in MP4 files weren't being read properly LAV Video - NEW: Support for decoding SMC video - Fixed: HLG video streams could have their HLG flag overriden in some circumstances LAV Audio - Fixed: TrueHD bitstreaming of Atmos tracks could cause output timestamps to be off, confusing some audio renderers 0.77.2 - 2023/03/08 LAV Splitter - NEW: Added identification for spatial/immersive audio extensions (Atmos, DTS:X) - Changed: More reasonable rounding for odd aspect ratios, avoiding issues with some video pipelines - Fixed: Improved compatibility with some FTP servers LAV Audio - Fixed: Restored the default channel layouts for 5.1 and 7.1 to the correct layout (accidentally changed in 0.77, causing some playback issues) - Fixed: Some TrueHD files would not decode correctly - Fixed: Clipping protection did not engage when using Integer output 0.77.1 - 2022/11/15 LAV Splitter - Fixed: More MP4 keyframe information fixes 0.77.0 - 2022/11/10 LAV Splitter - Fixed: Improved handling of multichannel PCM channel assignments - Fixed: MP4 Keyframe information could be wrong LAV Audio - NEW: Support for audio with more then 8 channel, including automatic downmixing if required 0.76.1 - 2022/02/28 LAV Splitter - Changed: When requesting a HTTP URL, the URL itself is send as a referrer to increase compatibility - Fixed: The priority of "Default" subtitle tracks in MKV files was wrong when a forced track was present LAV Video - Changed: Improved color reporting for DVD menus/subtitles - Fixed: D3D11 surface clearing did not work properly on Intel GPUs 0.76.0 - 2022/01/22 LAV Splitter - NEW: Added an option to re-evaluate subtitle stream selection when the audio language changes - NEW: Improved advanced subtitle selection syntax with negated flags (positive and negative flags can now be combined for more flexible selection) - Changed: Improved variant/stream selection in DASH and HLS streams - Changed: Video streams with the highest bitrate are preferred (if equal resolution) LAV Video - NEW: Support for passing DoVi metadata to video renderers - NEW: BobWeaver (BWDIF) software deinterlacer (a blend of YADIF and Weston, focusing on their individual strengths) - NEW: Support for FIC screen capture video - Changed: D3D11 video surfaces are flushed to black before decoding, avoiding green artifacts - Changed: D3D11 devices are created up to feature level 12.1 LAV Audio - Fixed: TrueHD bitstreaming could result in A/V sync issues or drop-outs - Removed: Support for the external DTS decoder (dtsdecoderdll.dll) has been removed 0.75.1 - 2021/06/21 LAV Splitter - Changed: AV1 files with no extradata will now generate a format header with stream information for decoders to use - Fixed: Improved stream selection when multiple "default" video tracks are present LAV Video - Changed: Updated dav1d for significant improvements in AV1 10-bit decoding performance - Changed: AV1 hardware decoding will more reliably engage when provided with additional stream information from the demuxer LAV Audio - Fixed: Opus decoding had audible artifacts in some files in 0.75 0.75.0 - 2021/03/30 LAV Splitter - NEW: Support for DASH streaming - NEW: WebVTT support in Matroska/WebM - Changed: Improved Font support from Matroska files - Fixed: Large queue size limits could result in the wrong limit being applied - Fixed: Resolved a memory leak in Matroska demuxing - Fixed: Avoid selecting a stream with only a single video frame in MP4 files, which is often a cover art - Fixed: Seeking in Matroska files with only audio cue points did not function - Fixed: Seeking to the beginning of certain HLS streams did not work properly - Fixed: Duration information in Matroska files is more reliable LAV Video - NEW: AV1 DXVA2/D3D11 hardware decoding support - NEW: ProRes 4444 XQ support - Faster: Updated dav1d decoder and improved thread configuration for significantly improved AV1 decoding speed - Fixed: Added a workaround for VP9 hardware decoding on AMD video cards - Fixed: H.264 streams exceeding the Level 5.1 DPB limit will no longer be hardware decoded - Fixed: Improved handling of missing reference frames in H.264 streams with hardware decoding - Fixed: HEVC streams encoding 8-bit video in a Main10 profile can be properly hardware decoded - Deprecated: NVIDIA CUVID and Intel QuickSync have been deprecated for future removal/replacement LAV Audio - Fixed: Resolved an issue with glitching TrueHD bitstreaming on seamless-branching titles - Fixed: Resolved a compatibility issue with some playback applications - Deprecated: Support for the binary DTS decoder (dtsdecoderdll.dll) has been deprecated for future removal 0.74.1 - 2019/03/19 LAV Video - Fixed: VP9 video could produce wrong timestamps, resulting in a black screen or other playback disruptions - Fixed: Decoding VP9 from a non-keyframe (ie. after a seek, or badly cut file) would not always recover properly once a keyframe was encountered 0.74.0 - 2019/03/16 LAV Splitter - Changed: Using GnuTLS for HTTPS and other TLS protocols, improving performance and compatibility with a lot of web streaming services (ie. YouTube Live Streams through youtube-dl, and more) - Fixed: Keyframes in MP4 files were being reported with a slightly offset timestamp, resulting in slow keyframe seeking - Fixed: Subtitles that stretch over chapter boundaries could be lost in Ordered Chapter MKV files - Fixed: Fonts embedded in MKVs without a proper mimetype were not being imported (now it checks the file extensions for .ttf/.otf as well) LAV Video - NEW: Initial support for parsing HDR10+ (SMPTE ST 2094-40) metadata, and passing it to the video renderer - NEW: Using the dav1d AV1 decoder for significantly improved AV1 decoding performance - Changed: Re-enabled experimental hardware acceleration for H.264 MVC 3D decoding on Intel GPUs, disabled by default - Changed: Updated Intel MediaSDK dispatchers to the latest Media SDK, fixing compatibility with newer runtimes in the Intel DCH drivers - Changed: Improved support for additional UtVideo subtypes LAV Audio - Changed: Added an option to disable the PCM fallback when bitstreaming is requested - Fixed: Further improvements to TrueHD Bitstreaming, resolving glitching on more new titles (particularly seamless branching titles) - Fixed: Automatic fallback from bitstreaming to PCM could crash in some situations 0.73.1 - 2018/10/11 LAV Video - Fixed: Container-provided color information will only overwrite video bitstream color information if its set and valid LAV Audio - Fixed: Certain multi-channel AAC streams did not decode in 0.73 0.73.0 - 2018/10/05 LAV Splitter - Changed: Export the description of cover art and attachments for use by players - Fixed: Properly marked the packet allocator as providing read-only packets, to avoid crashes with in-place transform filters LAV Video - NEW: Support for AV1 decoding using libaom - Changed: Enabled VP9 hardware acceleration by default - Fixed: The aspect ratio of certain WMV/VC-1 files was not being properly respected in the WMV9 MFT decoder 0.72.0 - 2018/06/19 LAV Video - Changed: Enabled CineformHD decoding by default, since the decoder has much improved - Fixed: Decoding Matroska files with Linked Segments which used old x264 4:4:4 encodes could result in corruption LAV Audio - NEW: Blu-ray Dolby Digital Plus 7.1 decoding and bitstreaming support - NEW: LAV Audio will fallback to audio decoding if bitstreaming is not supported by the audio renderer/hardware - Fixed: DTS-HD HRA bitstreaming did not work properly with many A/V receivers - Fixed: TrueHD bitstreaming could result in drop-outs on high bitrate TrueHD+Atmos streams 0.71.0 - 2018/02/15 General - LAV Filters now requires Windows Vista or newer, Windows XP is no longer supported LAV Splitter - NEW: Preliminary support for UHD Blu-ray parsing LAV Video - NEW: D3D11 hardware accelerated decoding (native mode with madVR, Copy-Back otherwise) - Fixed: HDR metadata was not properly communicated to madVR in DXVA2-Native mode - Fixed: Anamorphic WMV9/VC-1 videos were not being played back with the correct aspect ratio in all cases - Fixed: Changing certain settings while playback was paused could result in a deadlock - Fixed: Playing severely corrupted HEVC streams with hardware decoding could result in playback failing entirely, instead of skipping over the corruption LAV Audio - NEW: Basic support for AAC 960 streams (common in DVB radio streams) 0.70.2 - 2017/07/06 LAV Video - Fixed: DXVA2 decoding could fail in 0.70 after a dynamic media type change 0.70.1 - 2017/07/01 LAV Video - NEW: DXVA2-CopyBack uses D3D9Ex to allow headless operation - Changed: Increased the maximum number of decode threads to 32 - Changed: Rebalanced the "Auto" thread strategy to use the exact number of available CPU cores, instead of 1.5x the cores - Fixed: Certain H264 streams could crash in 0.70 due to lack of buffer padding 0.70.0 - 2017/06/15 General - Official LAV Filters builds require a SSE2 capable CPU LAV Splitter - Fixed: Certain MP4/MOV files didn't play or seek correctly in recent versions of LAV Splitter - Fixed: HEVC in MP4 without PTS timestamp is being signaled appropriately - Fixed: Closing RTSP streams did not properly call the TEARDOWN function LAV Video - NEW: CUVID support for VP9 8/10-bit and HEVC 10/12-bit decoding - NEW: DXVA2 support for VP9 10-bit decoding - Changed: Simplified the internal dataflow to reduce overhead and improve performance - Changed: Enabled P010 output to EVR on Windows 10 Creators Update - Fixed: Y416 output was incorrect (required by madVR 0.91.8 and newer) - Fixed: Parsing H.264 MVC SEI NALs could fail in some cases - Fixed: CUVID decoding could deinterlace progressive streams under certain circumstances, degrading the quality LAV Audio - Fixed: LATM AAC streams with Program Config Elements (PCE) (common in DVB-T2 broadcast) played with audible distortions - Fixed: Very short PCM audio streams didn't play properly 0.69.0 - 2016/12/11 LAV Splitter - NEW: Support for extracting HDR metadata from YouTube HDR VP9 streams - Fixed: Reading MKV files could crash when encountering tags for unknown or disabled streams LAV Video - NEW: Support for 10-bit UtVideo - NEW: MagicYUV decoding support - NEW: Experimental support for CineformHD decoding - Fixed: Converting 12-bit 4:4:4 YCbCr to RGB32 would result in a garbled image - Fixed: Decoding certain H.264 streams could drop a few frames at the start of playback LAV Audio - NEW: DTS Express (LBR) decoding support 0.68.1 - 2016/05/05 LAV Splitter - NEW: Support for reading metadata tags from MKV files (including the "3d-plane" MVC 3D tag from MakeMKV 1.9.10 and newer) - Fixed: Improved handling of QuickTime codecs in MKV files - Fixed: S302M audio streams with non-pcm content did not work anymore (requires an external decoder) LAV Video - Changed: Flags for BT.2020 are exported in DXVA2_ExtendedFormat (previously only reported to madVR, since the Windows SDK did not specify them) - Changed: Prevent connections to the "AVI Decompressor" filter which could result in a broken image or crashes otherwise - Fixed: Some progressive files could report the wrong FPS when software deinterlacing was turned on - Fixed: MPEG-2 streams using "intra refresh" did not decode properly LAV Audio - Fixed: Decoding MPEG Audio streams from the Microsoft MPEG-1 Splitter could result in playback starting with an audible glitch 0.68.0 - 2016/03/08 LAV Splitter - NEW: H.264 MVC 3D demuxing from MKV 3D, Blu-ray discs and Blu-ray SSIF files - Fixed: The bitdepth of DTS-HD MA streams is reported properly in the stream information LAV Video - NEW: H.264 MVC 3D decoding (requires madVR 0.90 or newer) - NEW: HEVC HDR streams export the HDR metadata to the video renderer (requires madVR 0.89.18 or newer) - NEW: VP9 DXVA2 Hardware Acceleration - NEW: Weston Three Field Deinterlacing filter (w3fdif) - NEW: Ability to choose which GPU is used for DXVA2-CopyBack decoding - Changed: Removed the CUVID HQ processing option, it is now automatically used when appropriate - Fixed: CUVID would crash when playing certain HEVC files - Fixed: Some pixel format conversions were much slower than expected - Fixed: Pixel Format changes mid-stream were not re-negotiated with the renderer in all cases - Fixed: Changes in the framerate due to software deinterlacing are properly reflected in the media type LAV Audio - Fixed: Increased PCM buffering to avoid stuttering with TrueHD on some audio devices 0.67.0 - 2015/11/15 LAV Splitter - NEW: Support for HTTPS URLs - NEW: Automatic selection of the highest quality variant in HLS streams - Changed: Reverted back to the old ASF demuxer - Changed: Backported ASF seeking improvements to the old ASF demuxer - Fixed: ASS in AVI did not work in recent versions - Fixed: RTP/RTSP did not work properly in 0.66 LAV Video - NEW: Improved DVD subtitle and menu drawing with madVR (support for madVRs subtitle repositioning and lower latency) - Changed: HEVC and 4K HWAccel is enabled by default - Changed: Enabled DXVA2-CB Direct Mode with YV12 output on 8-bit sources - Fixed: DVD menus could show a black screen instead of the menu in some situations LAV Audio - Fixed: Improved clipping behavior in badly mastered DTS-HD tracks 0.66.0 - 2015/09/22 LAV Splitter - NEW: Added options to increase the queue size for increased buffering - Changed: Switched ASF/WMV demuxing to a new demuxer from Libav - Fixed: Improved seeking with MPEG-TS files which contain teletext streams LAV Video - NEW: Support for DXVA2-Native decoding of HEVC 10-bit with EVR on supported GPUs - Changed: 4K Video Decoding on AMD graphics card is now enabled (needs recent drivers to work properly) - Changed: DXVA2-CB decoding uses less memory on NVIDIA graphics cards - Fixed: H264 DXVA2 decoding failed when no SPS/PPS was available in the media type - Fixed: Conversion of RGB48 to RGB32/24 did not properly use dithering - Fixed: Improved handling of a few DVD menu quirks - Fixed: Decoding 10-bit video with EVR could result in a black screen LAV Audio - Changed: 5.1 audio favors the "Side" 5.1 layout, which conforms to modern surround standards 0.65.0 - 2015/04/21 LAV Splitter - NEW: Support for MKV subtitle Cues to show subtitles immediately after a seek - NEW: Attachments and embedded cover art images are exported through the IDSMResourceBag interface - Fixed: Improved demuxing of HEVC in MPEG-TS and increased the reliability of the SPS/PPS/VPS extraction - Fixed: Demuxing Blu-rays/MPEG-TS where the first stream was not a video stream could result in broken timestamps - Fixed: Seeking in MKVs which are currently being written is more reliable LAV Video - Fixed: Improved HEVC DXVA2 decoding on a few samples - Fixed: Playback of VFR MPEG-4 in AVI had wrong timestamps in 0.64 - Fixed: Improved handling of DVD subtitles without timestamps LAV Audio: - NEW: Native DTS-HD decoding using libdcadec - Changed: 5.1 audio prefers the speaker mask with side channels, to match recent specifications 0.64.0 - 2015/02/13 General - NEW: Individual LAV Filters can now be blacklisted through the registry by creating a key with the executable name in HKCU\Software\LAV\\Blacklist LAV Splitter - NEW: Support for RTMP using rtmpdump-style parameter syntax - NEW: Support for Opus-in-TS - Fixed: The language reported for audio/subtitle streams on some Blu-rays could be wrong LAV Video - NEW: HEVC Main10 decoding in DXVA2 Copy-Back mode - Faster: DXVA2 Copy-Back in direct output mode uses up to 50% less CPU and performance is improved accordingly - Fixed: H.264 streams with only DTS timestamps would play out of sync with DXVA2 - Fixed: DXVA2 could crash on some MPEG-2 streams - Fixed: Improved compatibility with a few HEVC streams when using DXVA2 0.63.0 - 2014/10/03 LAV Splitter - NEW: Support for playing AES encrypted HLS streams - NEW: Advanced Subtitle selection allows selecting subtitles by a string match on the stream title - NEW: Support for rtspu, rtspm, rtspt and rtsph URLs to force the RTSP transport protocol - NEW: Animated GIF image support - Fixed: Improved timestamp handling of badly muxed/corrupted H.264 streams - Fixed: 4K ProRes streams in MKV didn't play reliably - Fixed: Some HEVC streams in MKV/MP4 didn't play properly - Fixed: VobSubs in MP4 didn't properly export their color palette - Fixed: Streaming MP3s through the Microsoft URL filter could result in the last audio frame to be partially repeated - Fixed: The duration of MP3 files would be wrong if it contained long IDv3 tags - Fixed: TrueHD streams with an Dolby Atmos sub-stream were not demuxed properly LAV Video - NEW: Experimental support for CUVID and DXVA2 HEVC acceleration - Faster: HEVC decoding is up to 100% faster - Fixed: DVD subtitle rendering could crash in 64-bit builds LAV Audio - Fixed: TrueHD streams with an Dolby Atmos sub-stream did not decode 0.62.0 - 2014/06/12 LAV Splitter - Fixed: The filtered Forced Subtitles stream did not properly send all related subtitle data in some cases LAV Video - NEW: Implemented a WMV9 MFT decoder to replace the old DMO decoder for VC-1/WMV3 on Windows 7 and above - NEW: Support for VP7 video - Fixed: Multi-threaded video decoding could result in a handle leak on some systems - Fixed: Video processing was slow on Windows XP due to inefficient memcpy use - Fixed: DVD subtitles could overlap on some discs LAV Audio - Fixed: Dynamic format switching to an audio stream with a different sample rate did not work in some cases 0.61.2 - 2014/04/08 General - Installer: The installer does now backup DirectShow registry settings before overwriting them, allowing uninstall to restore them LAV Splitter - NEW: Support for ProRes in MKV - Fixed: Opening AviSynth scripts with LAV Splitter which used DirectShowSource to load LAV Splitter again caused a deadlock - Fixed: Audio-only AviSynth scripts did not show a duration. - Fixed: Cue Sheets with directives with empty parameters could cause a crash LAV Video - Fixed: AVC1 video streams without SPS/PPS in the configuration record did not decode properly - Fixed: Decoding H.264 streams with a resolution change using the DXVA2 Copy-Back decoder could crash - Fixed: YUV->RGB conversion produced the wrong output for the last line of odd-height 4:2:2 or 4:4:4 files LAV Audio - Changed: LAV Audio offers more alternate output configurations to the audio renderer if the audio renderer refuses our preferred format. - Fixed: Decoding AC3 audio with corrupted audio frames could cause unnecessary format changes to occur and disrupt playback - Fixed: Decoding DTS audio on a CPU without SSE2 support could crash on some streams 0.61.1 - 2014/03/07 LAV Splitter - NEW: Support for opening "icyx://" stream URLs - Fixed: Opening of some Blu-ray discs would take several minutes and could hang the player. LAV Video - Fixed: Aggressive Deinterlacing is no longer applied to soft-telecined content, which caused severe playback issues. 0.61.0 - 2014/03/04 LAV Splitter - NEW: Support for "demuxing" AviSynth scripts (requires AviSynth, 2.6 recommended) - NEW: Support for reading ICY stream metadata from ShoutCast streams - Fixed: The duration of DVB MPEG-TS files is being detected more reliably - Fixed: The ITrackInfo interface was not available in the last few versions - Fixed: The duration of certain Ogg Vorbis streams was wrong - Changed: DTS-HD audio tracks are now exposed using the official DTS-HD media type, in addition to the old DTS type - Workaround: Block WMP/WMC from always overwriting the initial track selection LAV Video - NEW: Support for Duck TrueMotion 1/2 - NEW: Support for BT.2020 in YCbCr -> RGB conversions - Fixed: Format conversion could cause out of memory errors when converting high-resolution videos - Fixed: The decoder could crash if DXVA2 decoding failed and the software decoder is unavailable - Fixed: Reduced binary bloat caused by the YCbCr -> RGB converter, reducing binary size to nearly half - Fixed: Playback of RV30/RV40 was not smooth in 0.60 - Fixed: Video corruption when using DXVA2 on Intel GPUs when decoding certain VC-1 or MPEG-2 clips - Fixed: Decoding WMV3 Complex profile automatically falls back to software, since hardware decoding is unsupported. - Faster: DXVA2 Copy-Back decoding on Intel GPUs is significantly faster - Changed: If the wmv9dmo decoder is unavailable, the FFmpeg decoder is automatically used instead - Changed: Updated QuickSync decoder to the latest version, fixes a few timestamp issues. - Changed: Relaxed the resolution checks for H.264 decoding on AMD GPUs, allowing files with 2K resolutions to be decoded (ie. 2048x1280, etc.) LAV Audio - NEW: Support for ATRAC3+ - Fixed: Decoding AC3 audio could produce glitches in playback due to too aggressive error checking. 0.60.1 - 2014/01/14 LAV Splitter - Fixed a crash when opening MPEG-2 files with Stereo3D Metadata - Improved the format of the chapter names created from embedded cue sheets - Fixed an incompatibility in the IPropertyBag metadata interface with a few players 0.60.0 - 2014/01/12 LAV Splitter - Improved playback of a few Blu-ray discs, avoids a hiccup at clip change - Support for reading embedded Cue Sheets from audio files as chapters - Added support for reporting the stream bitrate through IBitrateInfo (for MPC-HC et al.) - Additional metadata from the source file is exported through IPropertyBag (including "ROTATION" for video orientation information) - Fixed demuxing of MKV files with huge SSA/ASS format blocks (> 1MB) - Fixed playback of certain MPEG4 ASP streams in MKV to be smooth LAV Video - Added support for VC-1/WMV3 DXVA2 decoding on recent Intel GPUs (Ivy Bridge/Haswell, needs recent drivers) - Fixed a crash when stopping playback or seeking on AMD when using DXVA2 Native - Fixed playback of WMVA videos in software mode - Fixed a few issues with output of odd-height videos when converting to various pixel formats - Fixed a few corner cases when reporting the video range to madVR - Fixed a crash when playing raw video files with unaligned width (non mod16) LAV Audio - The version of the DTS DLL decoder is now checked, and versions before 1.1.0.0 are blocked (since they do not work) - Fixed an issue with DTS parsing which could result in occasional audio stutter - Improved support for Opus audio pre-skip 0.59.1 - 2013/11/04 LAV Splitter - Fixed a regression when demuxing AAC audio from MP4/MOV files 0.59.0 - 2013/11/03 LAV Splitter - Support for demuxing H.265/HEVC and VP9 - Improvements for H.264 in AVI or as raw video streams - Improved stream detection in files which start with a few seconds audio before the video - Improved timestamp handling when demuxing seamless branching Blu-rays, fixes a few hicups/freezes mid-stream LAV Video - Support for decoding H.265/HEVC and VP9 - Accept H.264 from the MainConcept demuxer - Added support for DV Video from Canopus cameras LAV Audio - Fixed playback issues on a few DTS and DTS-HD tracks 0.58.2 - 2013/07/26 LAV Splitter - Fixed demuxing of WavPack from MKV LAV Video - Fixed a crash when YADIF was being used on a single- or dual-core CPU LAV Audio - Fixed decoding of DTS streams with a frame size change mid-stream 0.58.1 - 2013/07/09 LAV Splitter - Improved UDP network streaming - Added a new option to configure the stream analysis duration of network streams - Reduced subtitle delay on certain Blu-ray titles - Improved detection of DTS-in-WAV - Improved I/O behaviour for sequential reading from optical media LAV Video - Fixed dynamic reconnection on parameter changes (Aspect Ratio, etc) with VMR-9 - Support for Apple Intermediate Codec (ICOD) - dxva2: added a check for AMD UVD/UVD+ GPUs to ensure the H.264 Level 4.1 DPB restrictions are met LAV Audio - Fixed a regression decoding certain Ogg Vorbis streams 0.58.0 - 2013/06/23 General - LAV Filters now includes a manifest file to control DLL loading - Fixed the shortcuts to the configuration dialogs created by the installer in the start menu LAV Splitter - Handle the "Default" flag in MKV files with multiple video streams - Fixed a regression in VC-1 demuxing which caused some streams to fail decoding with the WMV9 DMO decoder - Improved transition between ordered chapters in certain (badly formed) MKV files - Improved handling of AVC1 in AVI files - Improved accuracy of IAMStreamSelect::get_CurrentMarker - Several potential crash fixes and stability improvements LAV Video - YADIF deinterlacing is now multi-threaded, significant performance improvement on multi-core CPUs - Improved detection of progressive streams to ensure deinterlacing is disabled, especially when "Aggressive Deinterlacing" is used - Restored Fraps constant frame rate output by proper handling of repeated frames - Support for the new UtVideo sub-types, and fixed a regression in UtVideo decoding - cuvid: fix double-rate deinterlacing on certain streams without timing information - Updated the Intel QuickSync Decoder to 0.44 0.57.0 - 2013/05/20 LAV Splitter - Added a Popup Menu to the Tray Icon which allows Stream, Edition and Chapter switching - Improved stream selection in files with multiple video streams - Improved performance when opening MKVs with linked segments - Fixed playback of MKVs with Segment Linking and Vorbis Audio LAV Video - Enabled Hardware/GPU Deinterlacing when using the QuickSync decoder - Support for JPEG2000 DCinema streams - Support for RGB48 output, and high-quality dithering of RGB48 to RGB32 - Fixed a crash with DXVA2 Native on AMD GPUs in certain situations - Improved detection of H.264 RGB streams, improves support with EVR - Adjusted performance tuning for consistent performance in both playback and transcoding (in 0.56, transcoding could be slow) LAV Audio - Use the FLAC channel mask from metadata, fixes playback of FLAC files with non-standard channel layouts 0.56.2 - 2013/04/19 LAV Splitter - Emit the EC_LENGTH_CHANGED event when the edition is changed, to help players update their playback duration LAV Video - dxva2: fixed corruption/dropped frames after seeking in interlaced MPEG-2/VC-1 streams - dxva2: fixed corruption after seeking in interlaced H.264 on AMD GPUs - dxva2: fixed decoding of H.264 on AMD UVD/UVD+ GPUs (HD 2xxx/3xxx Series) - dxva2: disabled wmv3 decoding on AMD UVD/UVD+ GPUs (until it can be fixed) - Fixed colorspace used for YUV Fraps to always be BT.709 - Added support for MPEG-4 Video with the BLZ0 FourCC (used in older Blizzard games) 0.56.1 - 2013/04/13 LAV Splitter - Fixed various crashes with ordered chapter MKVs - Fixed a crash when playing an MKV with a disabled subtitle track - Fixed switching between video streams with different codecs (ie. H264 -> MPEG2) LAV Video - Fixed a crash on close with DXVA2 Native - Re-tuned YADIF for smooth playback instead of benchmarking 0.56.0 - 2013/04/10 General - Major ffmpeg update, the DLLs have had their version number increased LAV Splitter - Support for Matroska Ordered Chaptes / Segment Linking - Improved support for parsing language tags from OGM files - Small performance improvements by avoiding copying the stream data in memory needlessly - Improved duration calculation for MP3 files LAV Video - Performance improvements for single-threaded decoders and YADIF (up to 20% in some situations) 0.55.3 - 2013/02/10 LAV Splitter - Improved handling of Annex B H.264 in many containers - Improved support for external source filters without seeking ability (live sources) - Fixed duration in some MP4/MOV files - Fixed stream program assignment for some MPEG-TS files (resulted in some streams not visible) LAV Video - Added support for TSCC2 - Fixed a crash when playing certain H.264 files with QuickSync or CUVID 0.55.2 - 2013/01/25 LAV Splitter - Improved support for MP4-style H.264 in AVI - Further improvements for AAC in MPEG-TS - Small improvements to handling Blu-rays with odd stream configurations - Improved handling of Ogg Vorbis streams LAV Video - Basic support for playing DVDs in different playback rates - Fixed DXVA2 resource cleanup which may have caused a crash in some situations with DXVA2-Native - Fixed A/V Sync when using the WMV9 DMO decoder (especially noticeable after seeking) LAV Audio - Improved AC3 decoding quality (thanks to madshi for the patch in ffmpeg) 0.55.1 - 2013/01/11 General - Clicking the Tray Icon with a Property Page already active brings it back to the front LAV Splitter - Added an option to disable quality-based audio stream selection (selects the first stream matching the language preferences) - Removed Bitrate from audio quality criteria, because its too unreliable at this point. LAV Video - Fixed YADIF deinterlacing (broken after a ffmpeg update on 0.55) LAV Audio - Switched to Triangular Dithering for 16-bit Integer conversions 0.55.0 - 2013/01/09 General - All Filters now have an optional tray icon which can open the property sheet when clicked (disabled by default) LAV Splitter - Improved FPS detection for interlaced H.264 streams in Matroska - Fixed H.264 in Ogg and PMP - Fixed seeking in RMVB files with AAC audio - Improved support for AAC in MPEG-TS (especially in ISDB-T) - Fixed Key-Frame seeking for AVI and added support for MP4 LAV Video - Improved handling of raw RGB video with LAV Splitter (Video was upside-down in some cases) - Improved support for the Overlay Mixer renderer - Fixed decoding of non-mod16 video with CUVID - Fixed DXVA2 decoding of H.264 MBAFF content with >= 16px cropping - Support for fade in/out animations in DVD subtitles - Fixed DVD menu overlays showing too early on some discs - Fixed forced DVD subtitles being stuck on the screen until the next subtitle line - Improved playback of MPEG-1 in MKV with Haali Splitter LAV Audio - Fixed 6.1 to 7.1 upmixing when the standard channel layout option is turned off - Dithering when converting audio to 16-bit Integer - Fallback to DTS "Core" bitstreaming if DTS-HD fails 0.54.1 - 2012/11/27 LAV Splitter - Improved seeking in MP4 files created by Windows Live Movie Maker LAV Video - Improved H.264 DXVA on recent Intel GPUs (Sandy/Ivy Bridge and newer Atoms) - Fixed corruption with high number of reference frames ( > 11 ) - Fixed corruption in MBAFF interlaced content - Fixed an issue that caused DVD menus/subtitles to stop working in DXVA2 Native mode in some situations 0.54.0 - 2012/11/24 LAV Splitter - Subtitle selection in "Default" mode now properly takes the "Default Track" flag into account - Fixed an issue that could cause graph flush events to be send out of sync LAV Video - The DXVA2 Native decoder can now properly detect hardware support for video resolutions - Allows 4K DXVA2 decoding on NVIDIA - New options to control which resolutions are being handled by the hardware decoder (SD, HD and 4K/UHD) - Added support for DVD menu overlays and DVD subtitles with DXVA2 Native - Improved DXVA2 Native support with madVR - Fixed a freeze when playing corrupted H.264 streams in DXVA2 Native - Fixed a few rare DVD menu issues when using the QuickSync decoder 0.53.2 - 2012/11/11 LAV Video - Fixed DVD menu still frames with DXVA2 Copy Back - Fixed Live TV playback with QuickSync 0.53.1 - 2012/11/10 LAV Video - Fixed initial media type when YADIF is active - Fixed an image corruption issue with DVD playback - Improved handling of DVD menus on some discs - Reduced decode latency with CUVID/DXVA2-CB on DVDs for smoother playback in some situations - Added an option to toggle HW decoding for DVDs 0.53.0 - 2012/11/05 LAV Splitter - Added support for reading image files (tiff, png, jpeg, tga, bmp) - Support for MPEG-4 ASP in MPEG-TS - Support for reading metadata using the IAMMediaContent interface - Fixed Aspect Ratio on some wmv/asf files LAV Video - Fixed a crash in the WMV9 DMO decoder on Windows 8 - DVD improvements - Subtitles are properly cleared from the screen, and won't be shown forever on some discs - Improved subtitle/menu positioning on some PAL discs - Improved handling of still frame DVD menus - Fixed a deadlock that caused the player to freeze in some DVD menus - Improved quality of blending subtitles/menus - QuickSync improvements - Support using QuickSync in Fullscreen Exclusive mode (ie. in WMC) - Improved fallback to software decoding if QuickSync is not available - Support for DVD decoding - Added support for Avid DV - Properly indicate progressive video when YADIF deinterlacing is activated LAV Audio - Added proper DirectShow types and config options for AMR-NB, Nellymoser and various (AD)PCM variants 0.52.0 - 2012/10/20 LAV Splitter - Improved IO performance on network sources - Added an option to configure the maximum memory usage of the frame queues - Support ALAC in MKV - Support SRT subtitles in AVI - Improved raw video support in combination with LAV Video LAV Video - Support for DVD Video decoding - Slight GPU memory usage reduction with DXVA2 Native - Fixed video corruption after seeks with VP3/Theora - Fixed decoding of "old" H.264 4:4:4 lossless files - More strict handling of output pixel formats, only enabled formats are allowed for output - QuickSync: Improved compatibility with new driver series - Improved support for VC-1 with the SageTV MpegDemux LAV Audio - Fixed a few issues with audio mixing - Some channels would occasionally be mixed twice, causing incorrect audio levels - Downmixing 8ch to stereo could crash on some systems - Increased maximum LFE coefficient to 3.0 and fixed scale to be consistent with surround/center coefficients - Added downmixing to Mono - Clipping protection is no longer reset on seeks - Added support for Opus - Fixed excessive memory allocations when decoding MPEG4-ALS 0.51.3 - 2012/07/19 LAV Splitter - Further improved H264 media type creation LAV Audio - Fixed an issue with the initial media types causing graph building failures in some situations - Fixed a bug with DVBViewer which caused a delay on channel changes 0.51.2 - 2012/07/15 LAV Splitter - Improved H264 media type creation with some files - Fixed reading of QuickTime/AppleText chapters in MOV/MP4 LAV Video - Reduced latency of H264 software decoding (improves Live TV playback) - Fixed chroma handling of the YCgCo to RGB conversion - Fixed timestamp handling of MPEG2 (regression introduced in 0.51) LAV Audio - Re-Mix audio as a fallback when the audio chain refuses a new channel configuration - Fixed an error that caused 16-bit FLAC to show as 24-bit on the status panel 0.51.1 - 2012/07/10 LAV Video - Improved compatibility between DXVA and certain DVB players 0.51.0 - 2012/07/09 LAV Splitter - Increased IO responsiveness on high-latency network connections - Improved timestamp handling for MPEG-PS (.mpg/.vob/.evo) - Improved support for H264 streams in SSIF MPEG-TS files - Added an option to control the priority of audio streams for the hearing/visually impaired - Added new flags to the advanced subtitle selection - "h" for hearing impaired - "n" for normal streams (no flags) - "!" NOT operator for inverting the meaning of the flags LAV Video - Improved DXVA2 Native to software fallback in some situations - Support for YCgCo to RGB conversion - Added a new smart Stream Aspect Ratio mode - Will only use Stream AR when the container does not provide a realiable AR LAV Audio - Improved decoding performance of MP4 ALS and a few other formats - Fixed playback of COOK with the MPC-HC RM Splitter - Auto A/V Sync is now automatically disabled on pure-audio files to avoid potential conflicts - Audio Down-Mixing support 0.50.5 - 2012/05/12 LAV Video - Fixed a crash in DXVA2-Native decoding (introduced in 0.50.4) 0.50.4 - 2012/05/12 LAV Video - Fixed seeking with QuickSync running in madVR Exclusive Mode 0.50.3 - 2012/05/11 LAV Splitter - Fixed playback of raw PCM in AVI streams - Fixed a rare misdetection of MPEG-2 as VC-1 LAV Video - QuickSync: Fixed playback of some H.264 streams that would run out of sync on newer drivers - Fixed a memory leak when playing H.264 RGB (and some other formats) - Improved behaviour for H.264 and MPEG-2 on Live TV channel changes LAV Audio - Added support for Speex (via libspeex) - Improved support for AMR-NB/WB (using OpenCore decoder) 0.50.2 - 2012/04/26 LAV Splitter - Improved support for Playback Rates other then 1.0x - Improved demuxing performance by implementing a custom Sample Allocator to avoid one extra memory copy LAV Video - Fixed a rare crash when using YV12 output on non-mod16 video - Fixed excessive memory consumption with Haali Splitter and DXVA2-CB - Fixed a deadlock on dynamic format changes with DXVA2 Native - Added support for YV24 output LAV Audio - Improved support for Playback Rates other then 1.0x - Support for ALAC and ALS with the MPC-HC MP4 splitter - Improved A/V Sync on dynamic format changes - Improved Auto A/V Sync Correction algorithm (lower threshold, faster reaction) - Fixed audio pitch when bitstreaming 44.1KHz AC3/DTS 0.50.1 - 2012/03/29 LAV Splitter - Fixed Stream Detection on some Blu-rays with short Logo clips before the main movie - Fixed a crash when processing invalid/broken PGS subtitles LAV Video - Fixed a crash on dynamic format changes (stream change, Blu-ray clip change) 0.50 - 2012/03/27 LAV Splitter - Improved support for H264 Elementary Streams - Fixed a regression with seeking in MPEG-TS files recorded by some HD-PVR devices LAV Video - New Worker Thread design for Decoding/Deinterlacing - WMV9+YADIF is up to 40% faster - Improved DXVA2 for MPEG-2 interlaced - Improved H264 DXVA2 on AMD with certain streams - Improved CUVID support for 4K streams on supported hardware (GT520, GTX680, other VP5 hardware) LAV Audio - Added support for RealAudio Lossless (RALF) 0.49 - 2012/03/10 LAV Splitter - Improved MKV demuxing performance from slow sources (network streaming, etc) - Improved stream detection on Blu-rays - Improved support for RealAudio (COOK, SIPR, etc) in MKV - Support for streaming from HTTP URLs LAV Audio - Improved support for DTS files with Little-Endian or 14B encodings LAV Video - New VC1/WMV3 decoder based on the Microsoft DMO Decoder (new default) - Updated Intel QuickSync decoder (0.29, r44) - Fixed decoding of some MBAFF H264 streams with DXVA2 - Improved Stream Aspect Ratio logic in the CUVID decoder for H264 streams - Fixed Deinterlacing when DXVA2 Native is active in certain situations 0.48 - 2012/02/24 LAV Splitter - Improved Video/Audio stream detection in some MPEG-TS files LAV Video - Fixed a potential crash with native DXVA2 when the software fallback was used 0.47 - 2012/02/20 LAV Audio - Fixed seeking in COOK audio with the MPC-HC RealMedia splitter LAV Video - New DXVA2 "native" decoder (see release notes) - Updated Intel QuickSync decoder and tweaked configuration (0.28, r41) - Overall performance improvements - Multi-threaded decoding for Fraps - Fixed a regression that resulted in only single-threaded playback on certain H264 files - Fixed a crash in the CUVID decoder introduced in 0.46 under certain circumstances 0.46 - 2012/02/12 LAV Splitter - Experimental support for streaming protocols (RTSP, RTP, MMS) - Support for IBufferInfo (Buffer Status in MPC-HC "Statistics" pane) - Added a memory limit to avoid too high memory use from the frame queues - Fixed playback of files with Subtitles in WMP/WMC in some cases LAV Audio - Improved playback of files with bad audio frame interleaving - Improved support of COOK, ATRAC and SIPR (RealAudio codecs) LAV Video - Updated and improved Intel QuickSync decoder (0.26, r38) - Fixed DXVA2 software fallback on some lossless H264 clips - Improved Fraps decoding with EVR - Improved playback of MPEG4 in MP4 - Multi-threaded decoding for Lagarith - Fixed playback of Theora with the MPC-HC Ogg Splitter - Dithering Enhancements: - New "Random Dithering" option (new default) - Improved "Ordered Dithering" in the RGB converter - Support for decoding v210/v410 raw formats - Support for Snow and FFV1 0.45 - 2012/01/28 LAV Splitter - Improved playback of concatenated H.264 MOV/MP4 files - Adjusted FLAC MediaType to avoid ReClock stealing the connection - Improved playback of MPEG-TS with timestamp discontinuities LAV Audio - Fixed playback of very short PCM samples - Improved COOK decoding without LAV Splitter LAV Video - New DXVA2 "copy back" decoder (see release notes) - Updated Intel QuickSync decoder (r29) - Multi-threaded decoding for RV30/40, UtVideo and DNxHD - Support for the "FCC" color matrix - Improved Dirac support - CUVID support for MPEG-4 ASP (experimental) - Support for Intel Indeo 4, MS Video 1, 8BPS, LOCO, ZMBV, VCR1, AASC 0.44 - 2012/01/07 LAV Splitter - Fixed a seeking regression in the mkv demuxer introduced in 0.43 - Fixed a bug that caused stream descriptions to vanish after the file finished playing - Improved playback of WMVA video with commercial decoders - Added support for the new OpenType MIME type produced by mkvtoolnix > 5.2.0 LAV Audio - Fixed LATM AAC playback with some source filters LAV Video - Added Intel QuickSync hardware decoder - Added support for YADIF with hardware decoding - Added support for Dirac decoding - Added support for DNxHD decoding - Added support for v210/v410 output - Improved dynamic reconnection with post-processing filters - Fixed a seeking related corruption issue with MPEG4-ASP 0.43 - 2011/12/21 LAV Splitter - Improved MKV seeking and demuxing performance - Improved buffering for smoother playback (especially at start/after seeks) - Fixed a few audio media type issues - Fixed a minor resource handle leak LAV Audio - Updated to new ffmpeg audio decoding API - Disabled Float Audio output on Windows XP by default LAV Video - Fixed handling of soft-telecined MPEG2/H264 broadcasts in CUVID mode - Improved support for 4:2:2 10-bit streams - Fixed a crash related to unaligned memory buffers on Windows XP - Added support for decoding AMV streams 0.42 - 2011/11/30 LAV Splitter - Fixed a timestamping bug in the new MKV demuxer - Further enhancements to explorer thumbnail generation 0.41 - 2011/11/29 LAV Splitter - New MKV Demuxer (see release notes for details) - Fixed a bug with the Vorbis Media Type - Disabled Subtitles when generating Thumbnails in Explorer LAV Video - Fixed a overflow in 10 -> 8 bit dithering and NV12 output 0.40 - 2011/11/21 LAV Splitter - Improved demuxing of raw PCM streams - Fixed VC-1 in MP4 with the MS WMVideo Decoder - Improved playback of files with TrueHD audio streams - Added support for a requested stop time from the player - Improved playback of Blu-ray rips created by EasyBD - Added support for RGB24 raw video in AVI LAV Audio - Improved decoding of formats with extremely large audio frames LAV Video - Added YADIF software deinterlacing - Rewritten Interlaced options - Added new "Aggressive" deinterlacing mode - Moved many interlaced related options to global level - Fixed an issue with stream compatibility detection in the CUVID decoder, causing a software fallback when not required 0.39 - 2011/11/07 LAV Splitter - Fixed a bug that caused MPEG-2 and VC-1 parsers to produce wrong timestamps after a seek - Fixed playback of raw .h264 files LAV Video - NV12 is now the preferred YUV 4:2:0 output format - Fixed handling of the "As Input" RGB output setting - Improved VP6 cropping - Don't report completely progressive movies as interlaced to the renderer - Fixed playback of some broken MPEG-2 MKV muxes - RGB will now by default be offered as Bottom-Up instead of Top-Down for improved compatibility 0.38 - 2011/11/01 LAV Splitter - New subtitle selection options (see release notes or readme) - Improved handling of languages with more then one ISO 639-2 code (f.ex. German, French, etc) - Improved seeking to the start of the file - Added support for VobSubs in MP4 - Added support for MKV nested chapters - Improved playback of RV40 in MKV - Improved support of H264 in WTV LAV Audio - Fixed a crash with raw audio and SPDIF processing - Improved support for COOK - Improved DTS-in-WAV detection LAV Video - Fixed a issue that caused MPC-HCs EVR-CP to produce wrong colors when using CUVID decoding - Support Multi-Threading and CUVID decoding for MPEG-1 - Improve decoder flushing - Fixed a potential freeze on load and dynamic type changes - Fixed a freeze on seeking with certain VP8 files - Added support for UtVideo - Added support for H264 4:2:2 0.37 - 2011/10/06 LAV Splitter - Improved handling of failures on the output pins - Improved VC-1 in EVO timestamps LAV Audio - Added support for dynamic channel count changes in AAC - Implemented support for sample format conversions - Implemented Audio Delay options - Disabled the WMA codecs by default - Improved Bitstreaming data flow LAV Video - Fixed cropping of VP6 video - New SSE2 YUV420 -> YUV422 converter - Performance enhancements in the CUVID decoder on some systems - Fixed playback with the XP Overlay Mixer - Fixed a crash when decoding RGB video (Fraps, etc) 0.36 - 2011/09/29 LAV Splitter - Improved support for ADTS AAC - Fixed MPEG-2 timestamps in VOB - Fixed MPEG-2 frame rate reporting for telecined/interlaced LAV Video - Integrated NVIDIA CUVID Hardware decoder - Performance enhancements in 10bit decoding - Support for Flash Screen Video (FSV1) - Support for Apple ProRes - Improved MPEG-2 playback - Improved A/V sync with VC-1 and MPEG4-ASP 0.35 - 2011/09/07 LAV Splitter - Fixed a crash in IAMStreamSelect::Info handling with certain applications - Improve duration calculation for MPEG files LAV Audio - Fix playback of DTS streams which change the channel mid-playback LAV Video - Fixed a crash with 10-bit decoding and benchmarking tools - Fixed a H264 NALU parsing issue with certain streams 0.34 - 2011/09/04 LAV Splitter - Improve playback of VC-1 in EVO - Support for SSA subtitles in AVI - Support for H264 in VFW mode in MKV LAV Video - New optimized pixel format converters (faster and more accurate) - New YUV->RGB converter - Support for PNG video 0.33 - 2011/08/22 LAV Splitter - Improved compatibility with the MS WMVideo decoder - Fixed the mediatype for raw PCM streams LAV Audio - Added support for Vorbis streams demuxed by Haali and MPC-HC Splitters LAV Video - VC-1 decoding is now disabled by default - Fixed behaviour of the Stream AR option - The maximum number of decoding threads is now 16 - Free decoding buffers when the input pin disconnects to avoid big memory leaks 0.32 - 2011/08/19 General - The installer will now add shortcuts to the start menu to open the filter configurations - The ffmpeg DLLs have been renamed to carry a "lav" suffix to avoid collisions with other components LAV Splitter - Improved detection of AAC LATM tracks (previously mis-detected as mp1/mp2) - Fixed playback of badly interleaved AVI files - Smarter default stream selection for RealMedia files - Improved stream language handling for Blu-rays - Fixed a crash issue with the Forced Subtitle pin on Blu-rays LAV Audio - DTS decoding failures are now handled more gracefully - Fixed Media Types for Stereo 44.1kHz Audio LAV Video - First official version - refer to release notes for details 0.31 - 2011/07/28 LAV Splitter - Improved audio codec selection priorities - Improved VC-1 playback when using the madVR internal decoder - Improved playback of MPEG-TS files with a timestamp wrap right at the beginning of a file - Reduced amount of data required for file probing, resulting in faster startup time - Fixed demuxing/timestamping of RealMedia files LAV Audio - Fixed a bug in the DTS parser which caused occasional hiccups on DTS-HD content - Added the ability to detect DTS-in-WAV 0.30 - 2011/07/15 LAV Splitter - Improved VC-1 playback with ffdshow DXVA - Added support for outputting MPEG-4 Timed Text subtitles (only pure text supported) - Better support for MLP audio - I/O performance enhancements - Added an option to toggle how LAV Splitter handles audio stream switching - Added a hard-limit on queue sizes to avoid excessive memory usage when transcoding - Added an experimental interface for the Player to control graph rebuilding LAV Audio - Further improvements to the DTS-HD parsing - Better support for MLP audio - Added more E-AC3 subtypes 0.29 - 2011/06/09 LAV Splitter - The language code is now always shown in the stream changer (as a hint to easily know what to put into the preferred languages fields) - Enabled ITrackInfo - Improved H264 in MPEG-TS playback (including an option to try to fix broken HD-PVR recordings) - Added a programmatic configuration interface for players to configure LAV Splitter LAV Audio - Added support for decoding encrypted DVD audio - Fix decoding of some DTS-HD streams with the ArcSoft decoder - Added a programmatic configuration interface for players to configure LAV Audio 0.28 - 2011/05/27 LAV Splitter - Improved PGS filtering, forced subtitles should be cleared off the screen properly more often. - Improved playback of H264 in MPEG-TS with certain files (mostly from camcorders, but some Blu-rays as well) - Fixed 16-bit LPCM on DVDs - Fixed the Media Types for uncompressed video LAV Audio - Added the ability to decode DTS Express when using the ArcSoft DTS Decoder - Fixed missing audio after seeks with Ogg Vorbis 0.27 - 2011/05/24 General - Added debug versions which generate log files on your desktop LAV Splitter - Fixed a memory leak when switching streams - Increased probe buffer size (which results in files to be properly detected in more cases) - Fixed playback of MPEG-TS files with a odd program configuration LAV Audio - Improvements to the DTS decoder interface - Support for 1.1.0.0 - Try to reverse any channel upmixing done by the decoder, outputting the audio as close to the original source as possible. - New Channel Mapping functionality - Output only "standard" channel layouts (Mono, Stereo, 5.1, 6.1, 7.1), filling non-existent channels with silence. Required by some HDMI receivers with "odd" source layouts. (default) - Convert Mono to Stereo (simply double the audio channel) - Convert 6.1 to 7.1 (Back Center gets doubled into both back channels) 0.26 - 2011/05/15 General - The VC2010 runtime is no longer required to be installed LAV Splitter - Further VC-1 in MKV improvements - Added a separate "mpegvideo" (m2v files) option to the Format section - Added a flag for secondary audio streams - Changed the default DTS media type (better compatibility) LAV Audio - Added the ability to use the ArcSoft DTS decoder directly through LAV Audio - Added an automatic algorithm to keep A/V sync stable - Improved Bitstreaming with splitters other then LAV Splitter - Improved timestamp generation when bitstreaming - Fixed LPCM 24-bit Media Types 0.25 - 2011/05/06 LAV Splitter - Added the ability to filter Blu-ray PGS subtitles, so only frames flagged as "forced" are delivered - Either through a new "Forced Subtitles" stream (default) - Or, filtering for every PGS stream (configurable) - Improved support for H264 in AVI - Improved timings for TrueHD in MKV - m2ts files directly openend inside a Blu-ray structure should now properly display stream languages - Alot of fixes and enhancements for format compatibility (especially MPEG-TS) - Support using the ArcSoft HD Audio Decoder for E-AC3 LAV Audio - Audio bitstreaming (pass-through) for HDMI and S/PDIF - Support for AC3, E-AC3, TrueHD, DTS and DTS-HD - Use the float decoders for mp1/mp2 - Added official support for WMAv1, WMAv2 and WMA Pro - Fixed an issue that caused sync issues with FLAC audio, and FLAC is once again enabled by default 0.24 - 2011/04/25 General - Big ffmpeg update! Libraries have been renamed (version increase) LAV Splitter - Obviously wrong frame rates will no longer be reported to the decoder - Improved mpeg2 playback - Improved dynamic media type changes - Fix the first few frames of ASS/SSA subtitles in Matroska - Fix an issue with the display of some codec names - Add proper subtypes for little-endian PCM - Fix subtypes for QT PCM LAV Audio - Support processing of 64-bit double output from the decoders - PCM data will be buffered before its send to the renderer/post processor 0.23 - 2011/04/21 General - There is now an installer available in addition to the trusted old .zip files! LAV Splitter - Added support for using the "File Source (Async)" (and others) together with LAV Splitter - This is the new default mode for improved compatibility! - Check release notes for additional informations. - Added configuration which input formats will be demuxed - Improved VC-1 in MKV playback LAV Audio - Fixed playback of lossless formats with huge sample sizes - Improved A/V sync with TrueHD (and possibly others) - FLAC decoding is now disabled by default, because the decoder is not 100% working 0.22 - 2011/04/11 LAV Splitter - Added support for MKV embedded fonts - Improved VC-1 and H264 parsing - Fixed choppy XVID playback in MKV - Fixed a seeking issues that caused incompatibilitys with certain decoders (eg. a crash in ffdshow libmpeg2) - No longer report incomplete lists of keyframes via IKeyFrameInfo, as it would break seeking in certain players. - Allow opening all .mpls files if the user directly specifys to open one, even if it contains loops or duplicate titles. - Improved playback of MPEG-TS with multiple programs - Added new debugging option (Generate missing timestamps) 0.21 - 2011/04/07 LAV Splitter - Improve MPEG-TS program handling in some special circumstances - Filter out misdetected audio streams (unsupported DTS Express on BluRays) - Increase the priority of DTS-HD over normal DTS - Use the official AVI MEDIASUBTYPE instead of a custom one - Added options to completly disable stream parsing - Added a new VC-1 parser which will take over when VC-1 timestamp adjustments are turned off 0.20 - 2011/04/05 LAV Splitter - Added first BluRay support (see Release Notes or README for more details) LAV Audio - Removed static jitter check which caused corruptions in some audio streams - Improved error resilience - broken streams should now play in many more cases 0.19 - 2011/03/19 General - Version Information has been added to the filter .ax files, as well as shown on the property pages. LAV Splitter - Redesigned stream name generations - Codec profiles are now shown (if known - supported are H264, VC1, MPEG2 and DTS) - Audio bit-depth is no longer shown for lossy codecs, as it doesn't apply there - Improved logic that parses the stream flags - Names for the subtitle codecs have been added - If the language is "Undetermined", it'll no longer be shown - Size of the packet queue has been increased (solves subtitle issues, as well as improves playback stability) - Redesigned the way the splitter registers for formats in the registry for better compatibility - Changed the stream change handling for better compatibility with certain players (Media Portal, and others) - Improved handling of unknown streams (no codec information present) - Added a new option that controls if substreams should be exposed in the stream selector (Only AC3 in TrueHD supported) LAV Audio - Added a new configuration panel which allows to configure which formats the decoder should handle 0.18 - 2011/03/09 LAV Splitter - Improved compatibility when decoding VC-1 with the ArcSoft and Cyberlink Decoders - Increased the splitters merit - Fixed an issue that caused the splitter to deadlock when changing streams with madVR LAV Audio Decoder - Fixed a bug that caused sample durations to be calculated wrong, causing playback glitches 0.17 - 2011/02/27 LAV Splitter - Fixed seeking before starting playback 0.16 - 2011/02/27 LAV Audio Decoder - Fixed missing audio after seeks 0.15 - 2011/02/27 LAV Splitter - Fixed automatic selection of forced subtitle stream if the "Only Forced Subs" mode is active. - Fixed a bug in file handling that caused file sizes above 4GB to overflow, causing invalid durations to be reported in some files. - Improved performance on file opening LAV Audio Decoder - Enabled the ffmpeg codec parsers, which should improve compatibility with other DirectShow splitters. - Added a audio channel activity display to the status property page (for debugging channel assignments) 0.14 - 2011/02/10 General - The project and filters have been renamed slightly for consistency LAV Splitter - The settings have been moved to a different place in the Registry. You will need to re-apply them. - Improved MPEG-TS duration calculations. - The settings will now always be properly saved and loaded. - Disabled the limit of 20 Streams per file. - Fixed two separate issues that caused files to not start playing. LAV Audio Decoder - Property Page for Configuration and Status has been added - Dynamic Range Compression is now off by default, but configurable. - Media Type creation has been improved, fixes filter connection issues. - Processing of UINT8 Samples has been fixed. - Fixed a crash with some Audio codecs. - Fixed Channel Order for 7.1 Streams - Increased the decoders Merit - Added support for decoding QT PCM 0.13 - 2011/01/29 LAVFSplitter - Added support for demuxing BluRay LPCM tracks into the MPC-HC format - Added a new LAVFSplitter specific media type to all audio streams LAVCAudio - First version of LAVCAudio implemented 0.12 - 2011/01/21 - Fixed a crash issue with certain configurations and files with subtitles - Revisited file duration logic, now tries to prefer the duration of the video stream. This fixes MPEG-TS duration issues. - Updated ffmpeg (a lot of issues resolved) 0.11 - 2010/11/06 - Smart stream pre-selection based on language, flags and quality - Properties page for configuration (languages, stream selection logic) - Added support for AAC LATM (single stream) - Changed the "No Subtitles" pin to a more "friendly" Media Type - Fixed a crash with certain AAC tracks 0.10 - 2010/10/26 - Added more MOV/MP4 byte markers - Added support for multichannel PCM tracks - Added support for DVD LPCM tracks - Added support for usign the ArcSoft HD decoder for DTS and TrueHD tracks - Send the proper media type for TrueHD instead of trying to connect with AC-3 - Improved H264 frame rate detection - Improved FLAC support - Fix loading of files with unicode characters in their names - Fixed timestamping issues that caused certain videos to play too fast - Fixed M-JPEG media type - Fixed corruption with MPEG-4 ASP (DivX/Xvid) when using the Xvid decoder 0.9 - 2010/09/12 - Added support for distinguishing hearing impaired subtitles in mpeg-ts streams - Added BluRay LPCM support - MP1/MP2 audio media type fixes - Honor the original FourCC of the file in media type generation - Added support for using the Cyberlink VC-1 decoder - Fixed an issue with some H264/AVC1 files that caused video to not play at all - Fixed unicode in chapter names - Fixed getting the current chapter 0.8 - 2010/08/30 - Alot of internal changes to enhance performance and maintainability - Fixed a potential deadlock on seeking - Fixed playing files without a video stream - Fixed an issue that caused some players to hang on playback start - Improved language detection 0.7 - 2010/08/23 - Further improvements to aspect ratio detection - Restore old FPS detection - Adjusted flushing to fix subtitle delays - Reverted a timing change that broke TrueHD 0.6 - 2010/08/22 - Added support for E-AC3 - Fixed MPEG2 Media Types - Added support for RealVideo in MKV - Set proper aspect ratio in media type - Fixed memory leaks in packet handling code - Unicode support for stream names - Threading changes for more fluid playback at startup - Changed Flushing behaviour that solves a conflict with the MS DTV-DVD Decoder - Better support for Vorbis audio - Registers for the OGG Container Format 0.5 - 2010/08/18 - Fixed duration of MPEG-TS files - Added support for DVB subtitles - Fixed switching of Audio and Subtitle Streams - Added a "No Subtitles" Stream 0.4 - 2010/08/16 - Improved SSA Subtitle support - Fixed freeze-on-stop issue 0.3 - 2010/08/15 - Added Chapter support - Improved stream descriptions - 64-bit support 0.2 - 2010/08/14 - Fixed overflow in timestamp calculation causing AVIs to play too fast 0.1 - 2010/08/14 - Initial Release ================================================ FILE: COPYING ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: LAVFilters.iss ================================================ ; LAV Filters Inno Setup script #include ; Include version info #define ISPP_INCLUDED #include "common\includes\version.h" #if LAV_VERSION_BUILD > 0 #define LAV_VERSION_STRING str(LAV_VERSION_MAJOR) + "." + str(LAV_VERSION_MINOR) + "." + str(LAV_VERSION_REVISION) + "-" + str(LAV_VERSION_BUILD) #else #if LAV_VERSION_REVISION > 0 #define LAV_VERSION_STRING str(LAV_VERSION_MAJOR) + "." + str(LAV_VERSION_MINOR) + "." + str(LAV_VERSION_REVISION) #else #define LAV_VERSION_STRING str(LAV_VERSION_MAJOR) + "." + str(LAV_VERSION_MINOR) #endif #endif [Setup] AllowCancelDuringInstall = no AllowNoIcons = yes AllowUNCPath = no AppId = lavfilters AppName = LAV Filters AppPublisher = Hendrik Leppkes AppPublisherURL = https://1f0.de/ AppVerName = LAV Filters {#=LAV_VERSION_STRING} AppVersion = {#=LAV_VERSION_STRING} VersionInfoVersion = {#=LAV_VERSION_MAJOR}.{#=LAV_VERSION_MINOR}.{#=LAV_VERSION_REVISION}.{#=LAV_VERSION_BUILD} VersionInfoCompany = 1f0.de VersionInfoCopyright = GPLv2 OutputBaseFilename = LAVFilters-{#=LAV_VERSION_STRING} OutputDir = . Compression = lzma2/ultra64 SolidCompression = yes MinVersion = 0,6.0 PrivilegesRequired = admin CreateAppDir = yes DefaultDirName = {pf}\LAV Filters DefaultGroupName = LAV Filters DisableStartupPrompt = yes Uninstallable = yes DisableDirPage = auto DisableProgramGroupPage = auto UsePreviousTasks = yes #ifexist "..\LAVSignInfo.txt" SignTool = LAVSignTool SignedUninstaller = yes #endif [Messages] WelcomeLabel1=[name/ver] WelcomeLabel2=This will install [name] on your computer.%n%nIt is recommended that you close all other applications before continuing. WinVersionTooLowError=This software only works on Windows XP SP3 and newer. [Types] Name: default; Description: Default Name: full; Description: Full Name: custom; Description: Custom; Flags: iscustom [Components] Name: lavsplitter32; Description: LAV Splitter (x86); Types: default full custom; Name: lavsplitter64; Description: LAV Splitter (x64); Types: default full custom; Check: IsWin64; Name: lavaudio32; Description: LAV Audio (x86); Types: default full custom; Name: lavaudio64; Description: LAV Audio (x64); Types: default full custom; Check: IsWin64; Name: lavvideo32; Description: LAV Video (x86); Types: default full custom; Name: lavvideo64; Description: LAV Video (x64); Types: default full custom; Check: IsWin64; Name: mvc3d; Description: H.264 MVC 3D Decoder (extra download); Types: full; ExtraDiskSpaceRequired: 41242624; [Tasks] Name: icons; Description: "Create Start Menu Shortcuts"; Name: reset_settings; Description: "Reset Settings"; Flags: checkedonce unchecked; Check: SettingsExistCheck() [Files] Source: bin_Win32\avcodec-lav-62.dll; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter32 lavaudio32 lavvideo32 Source: bin_Win32\avfilter-lav-11.dll; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavvideo32 Source: bin_Win32\avformat-lav-62.dll; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter32 lavaudio32 Source: bin_Win32\avutil-lav-60.dll; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter32 lavaudio32 lavvideo32 Source: bin_Win32\swresample-lav-6.dll;DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter32 lavaudio32 lavvideo32 Source: bin_Win32\swscale-lav-9.dll; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavvideo32 Source: bin_Win32\libbluray.dll; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter32 Source: bin_Win32\LAVAudio.ax; DestDir: {app}\x86; Flags: 32bit regserver ignoreversion restartreplace uninsrestartdelete; Components: lavaudio32 Source: bin_Win32\LAVSplitter.ax; DestDir: {app}\x86; Flags: 32bit regserver ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter32 Source: bin_Win32\LAVVideo.ax; DestDir: {app}\x86; Flags: 32bit regserver ignoreversion restartreplace uninsrestartdelete; Components: lavvideo32 Source: bin_Win32\LAVFilters.Dependencies.manifest; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter32 lavaudio32 lavvideo32 Source: bin_Win32\IntelQuickSyncDecoder.dll; DestDir: {app}\x86; Flags: 32bit ignoreversion restartreplace uninsrestartdelete; Components: lavvideo32 Source: bin_x64\avcodec-lav-62.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter64 lavaudio64 lavvideo64 Source: bin_x64\avfilter-lav-11.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavvideo64 Source: bin_x64\avformat-lav-62.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter64 lavaudio64 Source: bin_x64\avutil-lav-60.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter64 lavaudio64 lavvideo64 Source: bin_x64\swresample-lav-6.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter64 lavaudio64 lavvideo64 Source: bin_x64\swscale-lav-9.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavvideo64 Source: bin_x64\libbluray.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter64 Source: bin_x64\LAVAudio.ax; DestDir: {app}\x64; Flags: 64bit regserver ignoreversion restartreplace uninsrestartdelete; Components: lavaudio64 Source: bin_x64\LAVSplitter.ax; DestDir: {app}\x64; Flags: 64bit regserver ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter64 Source: bin_x64\LAVVideo.ax; DestDir: {app}\x64; Flags: 64bit regserver ignoreversion restartreplace uninsrestartdelete; Components: lavvideo64 Source: bin_x64\LAVFilters.Dependencies.manifest; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavsplitter64 lavaudio64 lavvideo64 Source: bin_x64\IntelQuickSyncDecoder.dll; DestDir: {app}\x64; Flags: 64bit ignoreversion restartreplace uninsrestartdelete; Components: lavvideo64 Source: COPYING; DestDir: {app}; Flags: ignoreversion restartreplace uninsrestartdelete Source: README.md; DestDir: {app}; Flags: ignoreversion restartreplace uninsrestartdelete Source: CHANGELOG.txt; DestDir: {app}; Flags: ignoreversion restartreplace uninsrestartdelete Source: thirdparty\contrib\7za.exe; DestDir: {tmp}; Flags: dontcopy [UninstallDelete] Type: files; Name: {app}\x86\libmfxsw32.dll Type: files; Name: {app}\x64\libmfxsw64.dll [Icons] Name: {group}\LAV Splitter Configuration; Filename: rundll32.exe; Parameters: """{app}\x86\LAVSplitter.ax"",OpenConfiguration"; WorkingDir: {app}\x86; IconFilename: {app}\x86\LAVSplitter.ax; IconIndex: 0; Tasks: icons; Components: lavsplitter32 Name: {group}\LAV Splitter Configuration; Filename: rundll32.exe; Parameters: """{app}\x64\LAVSplitter.ax"",OpenConfiguration"; WorkingDir: {app}\x64; IconFilename: {app}\x64\LAVSplitter.ax; IconIndex: 0; Tasks: icons; Components: lavsplitter64 AND NOT lavsplitter32 Name: {group}\LAV Audio Configuration; Filename: rundll32.exe; Parameters: """{app}\x86\LAVAudio.ax"",OpenConfiguration"; WorkingDir: {app}\x86; IconFilename: {app}\x86\LAVAudio.ax; IconIndex: 0; Tasks: icons; Components: lavaudio32 Name: {group}\LAV Audio Configuration; Filename: rundll32.exe; Parameters: """{app}\x64\LAVAudio.ax"",OpenConfiguration"; WorkingDir: {app}\x64; IconFilename: {app}\x64\LAVAudio.ax; IconIndex: 0; Tasks: icons; Components: lavaudio64 AND NOT lavaudio32 Name: {group}\LAV Video Configuration; Filename: rundll32.exe; Parameters: """{app}\x86\LAVVideo.ax"",OpenConfiguration"; WorkingDir: {app}\x86; IconFilename: {app}\x86\LAVVideo.ax; IconIndex: 0; Tasks: icons; Components: lavvideo32 Name: {group}\LAV Video Configuration; Filename: rundll32.exe; Parameters: """{app}\x64\LAVVideo.ax"",OpenConfiguration"; WorkingDir: {app}\x64; IconFilename: {app}\x64\LAVVideo.ax; IconIndex: 0; Tasks: icons; Components: lavvideo64 AND NOT lavvideo32 Name: {group}\Visit LAV Filters Home Page; Filename: "https://1f0.de/"; Tasks: icons Name: {group}\Visit LAV Filters on Doom9; Filename: "https://forum.doom9.org/showthread.php?t=156191"; Tasks: icons Name: {group}\Uninstall LAV Filters; Filename: {uninstallexe}; Tasks: icons [Registry] Root: HKCU; Subkey: Software\LAV; Flags: uninsdeletekeyifempty Root: HKCU; Subkey: Software\LAV\Audio; Flags: uninsdeletekey; Components: lavaudio32 lavaudio64 Root: HKCU; Subkey: Software\LAV\Splitter; Flags: uninsdeletekey; Components: lavsplitter32 lavsplitter64 Root: HKCU; Subkey: Software\LAV\Splitter\Formats; Flags: uninsdeletekey; Components: lavsplitter32 lavsplitter64 Root: HKCU; Subkey: Software\LAV\Video; Flags: uninsdeletekey; Components: lavvideo32 lavvideo64 Root: HKCU; Subkey: Software\LAV\Video\Formats; Flags: uninsdeletekey; Components: lavvideo32 lavvideo64 Root: HKCU; Subkey: Software\LAV\Video\Output; Flags: uninsdeletekey; Components: lavvideo32 lavvideo64 [Run] Description: "Open LAV Splitter Configuration"; Filename: rundll32.exe; Parameters: """{app}\x86\LAVSplitter.ax"",OpenConfiguration"; WorkingDir: {app}\x86; Components: lavsplitter32; Flags: postinstall nowait unchecked Description: "Open LAV Splitter Configuration"; Filename: rundll32.exe; Parameters: """{app}\x64\LAVSplitter.ax"",OpenConfiguration"; WorkingDir: {app}\x64; Components: lavsplitter64 AND NOT lavsplitter32; Flags: postinstall nowait unchecked Description: "Open LAV Audio Configuration"; Filename: rundll32.exe; Parameters: """{app}\x86\LAVAudio.ax"",OpenConfiguration"; WorkingDir: {app}\x86; Components: lavaudio32; Flags: postinstall nowait unchecked Description: "Open LAV Audio Configuration"; Filename: rundll32.exe; Parameters: """{app}\x64\LAVAudio.ax"",OpenConfiguration"; WorkingDir: {app}\x64; Components: lavaudio64 AND NOT lavaudio32; Flags: postinstall nowait unchecked Description: "Open LAV Video Configuration"; Filename: rundll32.exe; Parameters: """{app}\x86\LAVVideo.ax"",OpenConfiguration"; WorkingDir: {app}\x86; Components: lavvideo32; Flags: postinstall nowait unchecked Description: "Open LAV Video Configuration"; Filename: rundll32.exe; Parameters: """{app}\x64\LAVVideo.ax"",OpenConfiguration"; WorkingDir: {app}\x64; Components: lavvideo64 AND NOT lavvideo32; Flags: postinstall nowait unchecked [Code] type Format = record id: String; name: String; default: Boolean; subtype: String; asyncSource: Boolean; protocol: Boolean; extensions: Array of String; chkbytes: Array of String; end; const NumFormatsMinusOne = 22; LavGUID = '{B98D13E7-55DB-4385-A33D-09FD1BA26338}'; StreamGUID = '{E436EB83-524F-11CE-9F53-0020AF0BA770}'; LavSplitterFormatsReg = 'Software\LAV\Splitter\Formats'; var SplitterPage: TInputOptionWizardPage; SplitterFormats: Array [0..NumFormatsMinusOne] of Format; function IsProcessorFeaturePresent(Feature: Integer): Boolean; external 'IsProcessorFeaturePresent@kernel32.dll stdcall'; function Is_SSE2_Supported(): Boolean; begin // PF_XMMI64_INSTRUCTIONS_AVAILABLE Result := IsProcessorFeaturePresent(10); end; function SettingsExistCheck(): Boolean; begin if RegKeyExists(HKCU, 'Software\LAV') then Result := True else Result := False; end; function IsUpdate(): Boolean; var sPrevPath: String; begin sPrevPath := WizardForm.PrevAppDir; Result := (sPrevPath <> ''); end; procedure FR(var f: Format; const id, desc: String; const default: Boolean; const extensions: Array of String); begin f.id := id; f.name := desc; f.default := default; f.extensions := extensions; f.subtype := ''; f.chkbytes := ['']; f.protocol := False; end; procedure FP(var f: Format; const id, desc: String; const default: Boolean; const extensions: Array of String); begin FR(f, id, desc, default, extensions); f.protocol := True; end; procedure FS(var f: Format; const subtype: String; const chkbytes : Array of String; UseAsync: Boolean); begin f.subtype := subtype; f.chkbytes := chkbytes; f.asyncSource := UseAsync; end; procedure InitFormats(); begin FR(SplitterFormats[0], 'matroska', 'Matroska/WebM', True, ['mkv','mka', 'mks', 'mk3d', 'webm', '']); FS(SplitterFormats[0], '{1AC0BEBD-4D2B-45ad-BCEB-F2C41C5E3788}', ['0,4,,1A45DFA3', ''], True); FR(SplitterFormats[1], 'avi', 'AVI', True, ['avi','divx', 'vp6', 'amv', '']); FS(SplitterFormats[1], '{e436eb88-524f-11ce-9f53-0020af0ba770}', ['0,4,,52494646,8,4,,41564920', '0,4,,52494646,8,4,,41564958', '0,4,,52494646,8,4,,414D5620', ''], True); FR(SplitterFormats[2], 'mp4', 'MP4/MOV', True, ['mp4', 'mov', '3gp', '3ga', 'm4v', 'qt', '']); FS(SplitterFormats[2], '{08E22ADA-B715-45ed-9D20-7B87750301D4}', ['4,4,,66747970', '4,4,,6d6f6f76', '4,4,,6d646174', '4,4,,736b6970', '4,4,,75647461', '4,12,ffffffff00000000ffffffff,77696465000000006d646174', '4,12,ffffffff00000000ffffffff,776964650000000066726565', '4,12,ffffffff00000000ffffffff,6672656500000000636D6F76', '4,12,ffffffff00000000ffffffff,66726565000000006D766864', '4,14,ffffffff000000000000ffffffff,706E6F7400000000000050494354', ''], True); FR(SplitterFormats[3], 'mpegts', 'MPEG-TS', True, ['ts', 'm2ts', 'mts', 'tp', 'ssif', '']); FS(SplitterFormats[3], '{e06d8023-db46-11cf-b4d1-00805f6cbbea}', ['0,1,,47,188,1,,47,376,1,,47', '4,1,,47,196,1,,47,388,1,,47', '0,4,,54467263,1660,1,,47', ''], True); FR(SplitterFormats[4], 'mpeg', 'MPEG-PS/VOB/EVO', True, ['mpg', 'mpeg', 'vob', 'evo', '']); FS(SplitterFormats[4], '{e06d8022-db46-11cf-b4d1-00805f6cbbea}', ['0,5,FFFFFFFFC0,000001BA40', ''], True); FR(SplitterFormats[5], 'bluray', 'Blu-ray', True, ['bdmv', 'mpls', '']); FS(SplitterFormats[5], '{20884BC2-629F-45EA-B1C5-FA4FFA438250}', ['0,4,,494E4458', '0,4,,4D4F424A', '0,4,,4D504C53', ''], False); FR(SplitterFormats[6], 'flv', 'FLV', True, ['flv', '']); FS(SplitterFormats[6], '{F2FAC0F1-3852-4670-AAC0-9051D400AC54}', ['0,4,,464C5601', ''], True); FR(SplitterFormats[7], 'ogg', 'Ogg/OGM', True, ['ogg', 'ogv', 'ogm', '']); FS(SplitterFormats[7], '{D2855FA9-61A7-4db0-B979-71F297C17A04}', ['0,4,,4F676753', ''], True); FR(SplitterFormats[8], 'rm', 'RealMedia (rm/rmvb)', True, ['rm', 'rmvb', '']); FR(SplitterFormats[9], 'wtv', 'Windows Television (wtv)', False, ['wtv', '']); FR(SplitterFormats[10], 'asf', 'WMV / ASF / DVR-MS', True, ['wmv', 'asf', 'dvr-ms', '']); FR(SplitterFormats[11], 'mxf', 'MXF (Material Exchange Format)', True, ['mxf', '']); FR(SplitterFormats[12], 'bink', 'Bink', True, ['bik', '']); FR(SplitterFormats[13], 'avisynth', 'AviSynth scripts', True, ['avs', '']); FP(SplitterFormats[14], 'rtmp', 'RTMP Streaming Protocol', False, ['rtmp', 'rtmpt', '']); FP(SplitterFormats[15], 'rtsp', 'RTSP Streaming Protocol', True, ['rtsp', 'rtspu', 'rtspm', 'rtspt', 'rtsph', '']); FP(SplitterFormats[16], 'rtp', 'RTP Streaming Protocol', True, ['rtp', '']); FP(SplitterFormats[17], 'mms', 'MMS Streaming Protocol', True, ['mms', 'mmsh', 'mmst', '']); FR(SplitterFormats[18], 'dts', 'DTS Audio', True, ['dts', 'dtshd', '']); FR(SplitterFormats[19], 'ac3', 'AC3 Audio', True, ['ac3', 'eac3', '']); FR(SplitterFormats[20], 'aac', 'AAC Audio', True, ['aac', '']); FR(SplitterFormats[21], 'mp3', 'MP3 Audio', True, ['mp3', '']); FR(SplitterFormats[22], 'flac', 'FLAC Audio', True, ['flac', '']); end; procedure RegWriteStringWithBackup(const RootKey: Integer; const SubKeyName, ValueName, Data: String); var OldValue: String; begin if RegQueryStringValue(RootKey, SubKeyName, ValueName, OldValue) then begin if CompareText(OldValue, Data) <> 0 then begin RegWriteStringValue(RootKey, SubKeyName, ValueName + '.LAV', OldValue); end end; RegWriteStringValue(RootKey, SubKeyName, ValueName, Data); end; function RegRestoreBackup(const RootKey: Integer; const SubKeyName, ValueName, CheckValue: String; const DeleteMode: Integer) : Boolean; var CurrentValue: String; BackupValue: String; begin Result := False; if RegQueryStringValue(RootKey, SubKeyName, ValueName, CurrentValue) then begin if CompareText(CurrentValue, CheckValue) = 0 then begin if RegQueryStringValue(RootKey, SubKeyName, ValueName + '.LAV', BackupValue) then begin RegWriteStringValue(RootKey, SubKeyName, ValueName, BackupValue); Result := True; end else begin if DeleteMode = 1 then begin RegDeleteValue(RootKey, SubKeyName, ValueName); RegDeleteKeyIfEmpty(RootKey, SubKeyName); end else if DeleteMode = 2 then RegDeleteKeyIncludingSubkeys(RootKey, SubKeyName); end end end; RegDeleteValue(RootKey, SubKeyName, ValueName + '.LAV'); end; procedure RegisterSourceFormatGUIDs(f: Format); var i: Integer; source: String; begin i := 0; if Length(f.subtype) > 0 then begin if f.asyncSource then source := '{e436ebb5-524f-11ce-9f53-0020af0ba770}' else source := LavGUID; if IsComponentSelected('lavsplitter32') then RegWriteStringWithBackup(HKCR32, 'Media Type\' + StreamGUID + '\' + f.subtype, 'Source Filter', source); if IsComponentSelected('lavsplitter64') then RegWriteStringWithBackup(HKCR64, 'Media Type\' + StreamGUID + '\' + f.subtype, 'Source Filter', source); end; while Length(f.chkbytes[i]) > 0 do begin if IsComponentSelected('lavsplitter32') then RegWriteStringValue(HKCR32, 'Media Type\' + StreamGUID + '\' + f.subtype, IntToStr(i), f.chkbytes[i]); if IsComponentSelected('lavsplitter64') then RegWriteStringValue(HKCR64, 'Media Type\' + StreamGUID + '\' + f.subtype, IntToStr(i), f.chkbytes[i]); i := i+1; end; end; procedure UnregisterSourceFormatGUIDs(f: Format); var SourceGuid: String; DelMode: Integer; begin if Length(f.subtype) > 0 then begin if f.asyncSource then begin SourceGuid := '{e436ebb5-524f-11ce-9f53-0020af0ba770}'; DelMode := 0; end else begin SourceGuid := LavGUID; DelMode := 2; end; RegRestoreBackup(HKCR32, 'Media Type\' + StreamGUID + '\' + f.subtype, 'Source Filter', SourceGuid, DelMode); if IsWin64 then RegRestoreBackup(HKCR64, 'Media Type\' + StreamGUID + '\' + f.subtype, 'Source Filter', SourceGuid, DelMode); end; end; procedure RegisterSourceFormatExtensions(f: Format); var i: Integer; begin i := 0; while Length(f.extensions[i]) > 0 do begin if f.protocol then begin RegWriteStringWithBackup(HKCR, f.extensions[i], 'Source Filter', LavGUID); end else begin if IsComponentSelected('lavsplitter32') then begin RegWriteStringWithBackup(HKCR32, 'Media Type\Extensions\.' + f.extensions[i], 'Source Filter', LavGUID); RegWriteStringWithBackup(HKCR32, 'Media Type\Extensions\.' + f.extensions[i], 'Media Type', StreamGUID); if Length(f.subtype) > 0 then RegWriteStringWithBackup(HKCR32, 'Media Type\Extensions\.' + f.extensions[i], 'SubType', f.subtype); end; if IsComponentSelected('lavsplitter64') then begin RegWriteStringWithBackup(HKCR64, 'Media Type\Extensions\.' + f.extensions[i], 'Source Filter', LavGUID); RegWriteStringWithBackup(HKCR64, 'Media Type\Extensions\.' + f.extensions[i], 'Media Type', StreamGUID); if Length(f.subtype) > 0 then RegWriteStringWithBackup(HKCR64, 'Media Type\Extensions\.' + f.extensions[i], 'SubType', f.subtype); end end; i := i+1; end; end; procedure UnregisterSourceFormatExtensions(f: Format); var source: String; i: Integer; begin i := 0; while Length(f.extensions[i]) > 0 do begin if f.protocol then RegRestoreBackup(HKCR, f.extensions[i], 'Source Filter', LavGUID, 1) else begin RegRestoreBackup(HKCR32, 'Media Type\Extensions\.' + f.extensions[i], 'Source Filter', LavGUID, 2); RegRestoreBackup(HKCR32, 'Media Type\Extensions\.' + f.extensions[i], 'Media Type', StreamGUID, 0); if Length(f.subtype) > 0 then RegRestoreBackup(HKCR32, 'Media Type\Extensions\.' + f.extensions[i], 'SubType', f.subtype, 0); if IsWin64 then begin RegRestoreBackup(HKCR64, 'Media Type\Extensions\.' + f.extensions[i], 'Source Filter', LavGUID, 2); RegRestoreBackup(HKCR64, 'Media Type\Extensions\.' + f.extensions[i], 'Media Type', StreamGUID, 0); if Length(f.subtype) > 0 then RegRestoreBackup(HKCR64, 'Media Type\Extensions\.' + f.extensions[i], 'SubType', f.subtype, 0) end end; i := i+1; end; end; function GetDefaultFormatSetting(f: Format): Boolean; var value: Cardinal; begin if RegQueryDWordValue(HKCU, LavSplitterFormatsReg, f.id, value) then begin Result := value > 0; end else begin Result := f.default; end end; procedure ResetSettings(); begin RegDeleteKeyIncludingSubkeys(HKCU, 'Software\LAV'); end; procedure DoUnzip(source: String; targetdir: String); var unzipTool: String; ReturnCode: Integer; begin // source contains tmp constant, so resolve it to path name source := ExpandConstant(source); unzipTool := ExpandConstant('{tmp}\7za.exe'); if not FileExists(unzipTool) then MsgBox('UnzipTool not found: ' + unzipTool, mbError, MB_OK) else if not FileExists(source) then MsgBox('File was not found while trying to unzip: ' + source, mbError, MB_OK) else begin if Exec(unzipTool, ' x "' + source + '" -o"' + targetdir + '" -y', '', SW_HIDE, ewWaitUntilTerminated, ReturnCode) = false then begin MsgBox('Unzip failed:' + source, mbError, MB_OK) end; end; end; procedure CurStepChanged(CurStep: TSetupStep); var i: Integer; targetPath : String; begin if (CurStep = ssPostInstall) then begin if IsTaskSelected('reset_settings') then ResetSettings(); if IsComponentSelected('lavsplitter32') or IsComponentSelected('lavsplitter64') then begin for i := 0 to NumFormatsMinusOne do begin if SplitterPage.Values[i] then begin RegisterSourceFormatGUIDs(SplitterFormats[i]); RegisterSourceFormatExtensions(SplitterFormats[i]); end else begin UnregisterSourceFormatGUIDs(SplitterFormats[i]); UnregisterSourceFormatExtensions(SplitterFormats[i]); end; RegWriteDWordValue(HKCU, LavSplitterFormatsReg, SplitterFormats[i].id, Ord(SplitterPage.Values[i])); end; end; if IsComponentSelected('mvc3d') then begin ExtractTemporaryFile('7za.exe'); targetPath := ExpandConstant('{tmp}\'); if IsComponentSelected('lavvideo32') then DoUnzip(targetPath + 'libmfxsw32-v3.7z', ExpandConstant('{app}\x86')); if IsComponentSelected('lavvideo64') then DoUnzip(targetPath + 'libmfxsw64-v3.7z', ExpandConstant('{app}\x64')); end; end; end; procedure CurPageChanged(CurPageID: Integer); begin if CurPageID = wpReady then begin // User can navigate to 'Ready to install' page several times, so we // need to clear file list to ensure that only needed files are added. idpClearFiles; if IsComponentSelected('mvc3d') then begin if IsComponentSelected('lavvideo32') then idpAddFile('https://files.1f0.de/lavf/plugins/libmfxsw32-v3.7z', ExpandConstant('{tmp}\libmfxsw32-v3.7z')); if IsComponentSelected('lavvideo64') then idpAddFile('https://files.1f0.de/lavf/plugins/libmfxsw64-v3.7z', ExpandConstant('{tmp}\libmfxsw64-v3.7z')); end; end; end; procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); var i: Integer; begin if (CurUninstallStep = usUninstall) then begin for i := 0 to NumFormatsMinusOne do begin UnregisterSourceFormatGUIDs(SplitterFormats[i]); UnregisterSourceFormatExtensions(SplitterFormats[i]); end; end; end; function ShouldSkipPage(PageID: Integer): Boolean; begin Result := False; if PageID = SplitterPage.ID then begin if not (IsComponentSelected('lavsplitter32') or IsComponentSelected('lavsplitter64')) then Result := True; end; end; function InitializeSetup(): Boolean; begin InitFormats; Result := True; if not Is_SSE2_Supported() then begin SuppressibleMsgBox('LAV Filters requires a CPU with SSE2 instruction support.'#10'Your CPU does not have these capabilities.', mbCriticalError, MB_OK, MB_OK); Result := False; end; end; function InitializeUninstall(): Boolean; begin InitFormats; Result := True; end; procedure InitializeWizard(); var i: Integer; begin SplitterPage := CreateInputOptionPage(wpSelectTasks, 'LAV Splitter Formats', 'Select which formats LAV Splitter should be setup to handle', 'Select for which formats LAV Splitter should be setup to be the Source Filter.'#10'Note: These are only the file formats for LAV Splitter, audio and video codecs are configured separately.', False, False); for i := 0 to NumFormatsMinusOne do begin SplitterPage.Add(SplitterFormats[i].name); SplitterPage.Values[i] := GetDefaultFormatSetting(SplitterFormats[i]); end; // Adjust tasks page WizardForm.SelectTasksLabel.Hide; WizardForm.TasksList.Top := 0; WizardForm.TasksList.Height := PageFromID(wpSelectTasks).SurfaceHeight; idpDownloadAfter(wpReady); end; ================================================ FILE: LAVFilters.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32630.192 MinimumVisualStudioVersion = 16.0.30011.22 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LAVSplitter", "demuxer\LAVSplitter\LAVSplitter.vcxproj", "{F475F86F-3F7F-4B1D-82A6-078339F599FD}" ProjectSection(ProjectDependencies) = postProject {0A058024-41F4-4509-97D2-803A1806CE86} = {0A058024-41F4-4509-97D2-803A1806CE86} {E2012DB5-33CB-44A7-B521-04287F6D0D80} = {E2012DB5-33CB-44A7-B521-04287F6D0D80} {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} = {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "baseclasses", "common\baseclasses\baseclasses.vcxproj", "{E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DSUtilLite", "common\DSUtilLite\DSUtilLite.vcxproj", "{0A058024-41F4-4509-97D2-803A1806CE86}" ProjectSection(ProjectDependencies) = postProject {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} = {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Demuxers", "demuxer\Demuxers\Demuxers.vcxproj", "{E2012DB5-33CB-44A7-B521-04287F6D0D80}" ProjectSection(ProjectDependencies) = postProject {0A058024-41F4-4509-97D2-803A1806CE86} = {0A058024-41F4-4509-97D2-803A1806CE86} {E1DA1B95-71F1-4C21-A271-121176925062} = {E1DA1B95-71F1-4C21-A271-121176925062} {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} = {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LAVAudio", "decoder\LAVAudio\LAVAudio.vcxproj", "{12154C64-9136-4C21-92FA-665008C6FD27}" ProjectSection(ProjectDependencies) = postProject {0A058024-41F4-4509-97D2-803A1806CE86} = {0A058024-41F4-4509-97D2-803A1806CE86} {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} = {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libbluray", "libbluray\libbluray.vcxproj", "{E1DA1B95-71F1-4C21-A271-121176925062}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LAVVideo", "decoder\LAVVideo\LAVVideo.vcxproj", "{D29ADED3-086B-46A8-9455-97EFF6B14775}" ProjectSection(ProjectDependencies) = postProject {0A058024-41F4-4509-97D2-803A1806CE86} = {0A058024-41F4-4509-97D2-803A1806CE86} {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} = {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "IntelQuickSyncDecoder", "qsdecoder\IntelQuickSyncDecoder.vcxproj", "{83F0170E-6AB3-467B-98D5-E061BD2BF00D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Debug|Win32.ActiveCfg = Debug|Win32 {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Debug|Win32.Build.0 = Debug|Win32 {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Debug|x64.ActiveCfg = Debug|x64 {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Debug|x64.Build.0 = Debug|x64 {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Release|Win32.ActiveCfg = Release|Win32 {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Release|Win32.Build.0 = Release|Win32 {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Release|x64.ActiveCfg = Release|x64 {F475F86F-3F7F-4B1D-82A6-078339F599FD}.Release|x64.Build.0 = Release|x64 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Debug|Win32.ActiveCfg = Debug|Win32 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Debug|Win32.Build.0 = Debug|Win32 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Debug|x64.ActiveCfg = Debug|x64 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Debug|x64.Build.0 = Debug|x64 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Release|Win32.ActiveCfg = Release|Win32 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Release|Win32.Build.0 = Release|Win32 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Release|x64.ActiveCfg = Release|x64 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA}.Release|x64.Build.0 = Release|x64 {0A058024-41F4-4509-97D2-803A1806CE86}.Debug|Win32.ActiveCfg = Debug|Win32 {0A058024-41F4-4509-97D2-803A1806CE86}.Debug|Win32.Build.0 = Debug|Win32 {0A058024-41F4-4509-97D2-803A1806CE86}.Debug|x64.ActiveCfg = Debug|x64 {0A058024-41F4-4509-97D2-803A1806CE86}.Debug|x64.Build.0 = Debug|x64 {0A058024-41F4-4509-97D2-803A1806CE86}.Release|Win32.ActiveCfg = Release|Win32 {0A058024-41F4-4509-97D2-803A1806CE86}.Release|Win32.Build.0 = Release|Win32 {0A058024-41F4-4509-97D2-803A1806CE86}.Release|x64.ActiveCfg = Release|x64 {0A058024-41F4-4509-97D2-803A1806CE86}.Release|x64.Build.0 = Release|x64 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Debug|Win32.ActiveCfg = Debug|Win32 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Debug|Win32.Build.0 = Debug|Win32 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Debug|x64.ActiveCfg = Debug|x64 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Debug|x64.Build.0 = Debug|x64 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Release|Win32.ActiveCfg = Release|Win32 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Release|Win32.Build.0 = Release|Win32 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Release|x64.ActiveCfg = Release|x64 {E2012DB5-33CB-44A7-B521-04287F6D0D80}.Release|x64.Build.0 = Release|x64 {12154C64-9136-4C21-92FA-665008C6FD27}.Debug|Win32.ActiveCfg = Debug|Win32 {12154C64-9136-4C21-92FA-665008C6FD27}.Debug|Win32.Build.0 = Debug|Win32 {12154C64-9136-4C21-92FA-665008C6FD27}.Debug|x64.ActiveCfg = Debug|x64 {12154C64-9136-4C21-92FA-665008C6FD27}.Debug|x64.Build.0 = Debug|x64 {12154C64-9136-4C21-92FA-665008C6FD27}.Release|Win32.ActiveCfg = Release|Win32 {12154C64-9136-4C21-92FA-665008C6FD27}.Release|Win32.Build.0 = Release|Win32 {12154C64-9136-4C21-92FA-665008C6FD27}.Release|x64.ActiveCfg = Release|x64 {12154C64-9136-4C21-92FA-665008C6FD27}.Release|x64.Build.0 = Release|x64 {E1DA1B95-71F1-4C21-A271-121176925062}.Debug|Win32.ActiveCfg = Debug|Win32 {E1DA1B95-71F1-4C21-A271-121176925062}.Debug|Win32.Build.0 = Debug|Win32 {E1DA1B95-71F1-4C21-A271-121176925062}.Debug|x64.ActiveCfg = Debug|x64 {E1DA1B95-71F1-4C21-A271-121176925062}.Debug|x64.Build.0 = Debug|x64 {E1DA1B95-71F1-4C21-A271-121176925062}.Release|Win32.ActiveCfg = Release|Win32 {E1DA1B95-71F1-4C21-A271-121176925062}.Release|Win32.Build.0 = Release|Win32 {E1DA1B95-71F1-4C21-A271-121176925062}.Release|x64.ActiveCfg = Release|x64 {E1DA1B95-71F1-4C21-A271-121176925062}.Release|x64.Build.0 = Release|x64 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Debug|Win32.ActiveCfg = Debug|Win32 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Debug|Win32.Build.0 = Debug|Win32 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Debug|x64.ActiveCfg = Debug|x64 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Debug|x64.Build.0 = Debug|x64 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Release|Win32.ActiveCfg = Release|Win32 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Release|Win32.Build.0 = Release|Win32 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Release|x64.ActiveCfg = Release|x64 {D29ADED3-086B-46A8-9455-97EFF6B14775}.Release|x64.Build.0 = Release|x64 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Debug|Win32.ActiveCfg = Debug|Win32 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Debug|Win32.Build.0 = Debug|Win32 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Debug|x64.ActiveCfg = Debug|x64 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Debug|x64.Build.0 = Debug|x64 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Release|Win32.ActiveCfg = Release|Win32 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Release|Win32.Build.0 = Release|Win32 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Release|x64.ActiveCfg = Release|x64 {83F0170E-6AB3-467B-98D5-E061BD2BF00D}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {F5B92918-449E-4214-B227-464B757DB420} EndGlobalSection EndGlobal ================================================ FILE: README.md ================================================ LAV Filters - ffmpeg based DirectShow Splitter and Decoders ============================= LAV Filters are a set of DirectShow filters based on the libavformat and libavcodec libraries from the ffmpeg project, which will allow you to play virtually any format in a DirectShow player. The filters are still under development, so not every feature is finished, or every format supported. Install ----------------------------- - Unpack - Register (install_*.bat files) Registering requires administrative rights, and an elevated shell ("Run as Administrator") Using it ----------------------------- By default, the splitter will register for all media formats that have been tested and found working at least partially. This currently includes (but is not limited to) MKV/WebM, AVI, MP4/MOV, TS/M2TS/MPG, FLV, OGG, BluRay (.bdmv and .mpls) However, some other splitters register in a "bad" way and force all players to use them. The Haali Media Splitter is one of those, and to give priority to the LAVFSplitter you have to either uninstall Haali or rename its .ax file at least temporarily. The Audio and Video Decoder will register with relatively high merit, which should make it the preferred decoder by default. Most players offer a way to choose the preferred decoder however. Automatic Stream Selection ----------------------------- LAV Splitter offers different ways to pre-select streams when opening a file. The selection of video streams is not configurable, and LAV Splitter will quite simply pick the one with the best quality. Audio stream selection offers some flexibility, specifically you can configure your preferred languages. The language configuration is straightforward. Just enter a list of 3-letter language codes (ISO 639-2), separated by comma or space. For example: `eng ger fre`. This would try to select a stream matching one of these languages, in the order you specified them. First, check if an English track is present, and only if not, go to German, and after that, go to French. If multiple audio tracks match one language, the choice is based on the quality. The primary attribute here is the number of channels, and after that is the codec used. PCM and lossless codecs have a higher priority than lossy codecs. Subtitle selection offers the most flexibility. There are 4 distinct modes of subtitle selection. #### No Subtitles This mode is simple, by default subtitles will be off. #### Only Forced Subtitles This mode will only pre-select subtitles flagged with the "forced" flag. It'll also obey the language preferences, of course. #### Default The default mode will select subtitles matching your language preference. If there is no match, or you didn't configure languages, no subtitles will be activated. In addition, subtitles flagged "default" or "forced" will always be used. #### Advanced The advanced mode lets you write your own combinations of rules with a special syntax. It also allows selecting subtitles based on the audio language of the file. The base syntax is simple, it always requires a pair of audio and subtitle language, separated by a colon, for example: `eng:ger` In this example, LAV Splitter would select German subtitles if English audio was found. Instead of language codes, the advanced mode supports two special cases: `*` and `off`. When you specify `*` for a language code, it'll match everything. For example `*:eng` will activate English subtitles, independent of the audio language. The reverse is also possible: `eng:*` will activate any subtitles when the audio is English. The "off" flag is only valid for the subtitle language, and it instructs LAV Splitter to turn the subtitles off. So "eng:off" means that when the audio is English, the subtitles will be deactivated. Additionally to the syntax above, the following flags can be appended to the subtitle token separated by a pipe symbol (`|`): - `d` for default subtitles - `f` for forced subtitles - `h` for hearing impaired - `n` for normal streams (not default, forced, or impaired). In addition, you can also check for the absence of flags by preceding the flags with a `!`. The advanced rules can be combined into a complete logic for subtitle selection by just appending them, separated with a comma or a space. The rules will always be parsed from left to right, the first match taking precedence. Finally, the rules can match the name of a stream, with some limitations. Only single words can be matched, as spaces are a separator for the next token. A text match can be added to the end of the token with a `@` sign. Example: (basic flag usage) - `*:*|f` - On any audio language, load any subtitles that are flagged forced. Example: (basic ruleset) - `eng:eng|f eng:ger|f eng:off *:eng *:ger` - If the audio is English, load an English or a German forced subtitle track, otherwise, turn subtitles off. - If the audio is not English, load English or German subtitles. Example: (flag usage with negation) - `jpn:ger|d!f` - In the Japanese language, load German subtitles that have the default-flag but not together with forced-flag. - This is useful when you have files where the default and forced flags are set together. Example: (advanced ruleset for files with multiple audio and subtitle-tracks) - `jpn:ger|d!f jpn:ger|!f jpn:ger ger:ger|f ger:eng|f ger:*|f` - On Japanese audio, try to load German full subs (default but not forced), then unforced, and at last any german subs if there are no unforced subs. - On German audio load only forced subs in the following order: German, English, any. Example: (text match) - `*:eng@Forced` - On any audio, select english subtitle streams with "Forced" in the stream title. Blu-ray Support ----------------------------- To play a BluRay, simply open the index.bdmv file in the BDMV folder on the BluRay disc. LAV Splitter will then automatically detect the longest track on the disc (usually the main movie), and start playing. Alternatively, you can also open a playlist file (*.mpls, located in BDMV/PLAYLIST), and LAV Splitter will then play that specific title. In future versions, you'll be able to choose the title from within the player, as well. Compiling ----------------------------- Compiling is pretty straightforward using VS2022 (included project files). Older versions of Visual Studio are not officially supported, but may still work. It does, however, require that you build your own FFmpeg. FFmpeg is included as part of the repository in a submodule, pointing to a custom fork of FFmpeg with various patches for improved compatibility with LAV and DirectShow. A script is provided to compile FFmpeg using MSYS2 with MINGW/GCC or MSVC. The custom fork of FFmpeg can be found here: https://gitea.1f0.de/LAV/FFmpeg libbluray is compiled with the MSVC project files, however, as with FFmpeg a custom version is used, which is also linked as a Git submodule. You can get find the custom version of libbluray here: https://gitea.1f0.de/LAV/libbluray Feedback ----------------------------- GitHub Project: https://github.com/Nevcairiel/LAVFilters Doom9: https://forum.doom9.org/showthread.php?t=156191 ================================================ FILE: build.bat ================================================ @ECHO OFF for /f "usebackq tokens=*" %%i in (`call "%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -version "[16.0,18.0)" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do ( set VSInstallDir=%%i ) set "VSCMD_START_DIR=%CD%" call "%VSInstallDir%\Common7\Tools\VsDevCmd.bat" -no_logo -arch=x86 > NUL sh build_ffmpeg.sh x86 || EXIT /B 1 MSBuild.exe LAVFilters.sln /nologo /m /t:Rebuild /property:Configuration=Release;Platform=Win32 IF ERRORLEVEL 1 EXIT /B 1 sh build_ffmpeg.sh x64 || EXIT /B 1 MSBuild.exe LAVFilters.sln /nologo /m /t:Rebuild /property:Configuration=Release;Platform=x64 IF ERRORLEVEL 1 EXIT /B 1 PAUSE ================================================ FILE: build_ffmpeg.sh ================================================ #!/bin/sh arch=x86 archdir=Win32 clean_build=true cross_prefix= CV2PDB=../thirdparty/contrib/cv2pdb.exe for opt in "$@" do case "$opt" in x86) ;; x64 | amd64) arch=x86_64 archdir=x64 cross_prefix=x86_64-w64-mingw32- ;; quick) clean_build=false ;; *) echo "Unknown Option $opt" exit 1 esac done make_dirs() ( mkdir -p bin_${archdir}/lib mkdir -p bin_${archdir}d/lib ) copy_libs() ( # copy and process .dll/.pdb for file in lib*/*-lav-*.dll; do file_basename=$(basename $file) file_pdb=$(basename $file .dll).pdb ${CV2PDB} -p${file_pdb} ${file} ../bin_${archdir}d/${file_basename} cp ../bin_${archdir}d/${file_basename} ../bin_${archdir}/ cp ../bin_${archdir}d/${file_pdb} ../bin_${archdir}/ done # copy lib files cp -u lib*/*.lib ../bin_${archdir}/lib cp -u lib*/*.lib ../bin_${archdir}d/lib ) clean() ( make distclean > /dev/null 2>&1 ) configure() ( OPTIONS=" --enable-shared \ --disable-static \ --enable-gpl \ --enable-version3 \ --disable-autodetect \ --enable-w32threads \ --disable-demuxer=matroska \ --disable-filters \ --enable-filter=scale,yadif,w3fdif,bwdif \ --disable-protocol=async,cache,concat,httpproxy,icecast,md5,subfile \ --disable-muxers \ --enable-muxer=spdif \ --disable-bsfs \ --enable-bsf=extract_extradata \ --disable-avdevice \ --disable-encoders \ --disable-devices \ --disable-programs \ --disable-debug \ --disable-doc \ --enable-avisynth \ --enable-bzlib \ --enable-d3d11va \ --enable-dxva2 \ --enable-gnutls \ --enable-gmp \ --enable-libdav1d \ --enable-libspeex \ --enable-libopencore-amrnb \ --enable-libopencore-amrwb \ --enable-libxml2 \ --enable-zlib \ --build-suffix=-lav \ --disable-stripping \ --arch=${arch}" EXTRA_CFLAGS="-fno-tree-vectorize -D_WIN32_WINNT=0x0600 -DWINVER=0x0600 -gdwarf-5" EXTRA_LDFLAGS="" PKG_CONFIG_PREFIX_DIR="" if [ "${arch}" == "x86_64" ]; then export PKG_CONFIG_PATH="$PKG_CONFIG_PATH:../thirdparty/64/lib/pkgconfig/" OPTIONS="${OPTIONS} --enable-cross-compile --cross-prefix=${cross_prefix} --target-os=mingw32 --pkg-config=pkg-config" EXTRA_CFLAGS="${EXTRA_CFLAGS} -I../thirdparty/64/include -fno-omit-frame-pointer" EXTRA_LDFLAGS="${EXTRA_LDFLAGS} -L../thirdparty/64/lib" PKG_CONFIG_PREFIX_DIR="--define-variable=prefix=../thirdparty/64" else export PKG_CONFIG_PATH="$PKG_CONFIG_PATH:../thirdparty/32/lib/pkgconfig/" OPTIONS="${OPTIONS} --cpu=i686" EXTRA_CFLAGS="${EXTRA_CFLAGS} -I../thirdparty/32/include -mmmx -msse -msse2 -mfpmath=sse -mstackrealign" EXTRA_LDFLAGS="${EXTRA_LDFLAGS} -L../thirdparty/32/lib" PKG_CONFIG_PREFIX_DIR="--define-variable=prefix=../thirdparty/32" fi sh configure --extra-ldflags="${EXTRA_LDFLAGS}" --extra-cflags="${EXTRA_CFLAGS}" --pkg-config-flags="--static ${PKG_CONFIG_PREFIX_DIR}" ${OPTIONS} ) build() ( make -j$NUMBER_OF_PROCESSORS ) make_dirs echo echo Building ffmpeg in GCC ${arch} Release config... echo cd ffmpeg if $clean_build ; then clean ## run configure, redirect to file because of a msys bug configure > ffbuild/config.out 2>&1 CONFIGRETVAL=$? ## show configure output cat ffbuild/config.out fi ## Only if configure succeeded, actually build if ! $clean_build || [ ${CONFIGRETVAL} -eq 0 ]; then build && copy_libs || exit 1 fi cd .. ================================================ FILE: build_ffmpeg_msvc.sh ================================================ #!/bin/sh arch=x86 archdir=Win32 archincdir=32 clean_build=true debug=true for opt in "$@" do case "$opt" in x86) ;; x64 | amd64) arch=x86_64 archdir=x64 archincdir=64 ;; quick) clean_build=false ;; release) debug=false ;; *) echo "Unknown Option $opt" exit 1 esac done make_dirs() ( mkdir -p bin_${archdir}d/lib mkdir -p bin_${archdir}/lib ) copy_libs() ( if $debug ; then cp -u lib*/*-lav-*.dll ../bin_${archdir}d cp -u lib*/*-lav-*.pdb ../bin_${archdir}d cp -u lib*/*.lib ../bin_${archdir}d/lib else cp -u lib*/*-lav-*.dll ../bin_${archdir} cp -u lib*/*-lav-*.pdb ../bin_${archdir} cp -u lib*/*.lib ../bin_${archdir}/lib fi ) clean() ( make distclean > /dev/null 2>&1 ) configure() ( OPTIONS=" --enable-shared \ --disable-static \ --enable-gpl \ --enable-version3 \ --disable-autodetect \ --enable-w32threads \ --disable-demuxer=matroska \ --disable-filters \ --enable-filter=scale,yadif,w3fdif,bwdif \ --disable-protocol=async,cache,concat,httpproxy,icecast,md5,subfile \ --disable-muxers \ --enable-muxer=spdif \ --disable-bsfs \ --enable-bsf=extract_extradata \ --disable-avdevice \ --disable-encoders \ --disable-devices \ --disable-programs \ --disable-doc \ --enable-avisynth \ --enable-d3d11va \ --enable-dxva2 \ --enable-schannel \ --enable-zlib \ --build-suffix=-lav \ --arch=${arch}" EXTRA_CFLAGS="-D_WIN32_WINNT=0x0600 -DWINVER=0x0600 -Zo -GS- -I../thirdparty/$archincdir/include/" EXTRA_LDFLAGS="" if $debug ; then OPTIONS="${OPTIONS} --enable-debug" EXTRA_CFLAGS="${EXTRA_CFLAGS} -MDd" EXTRA_LDFLAGS="${EXTRA_LDFLAGS} -NODEFAULTLIB:libcmt" else OPTIONS="${OPTIONS} --disable-debug" EXTRA_CFLAGS="${EXTRA_CFLAGS} -MD" EXTRA_LDFLAGS="${EXTRA_LDFLAGS} -NODEFAULTLIB:libcmt" fi sh configure --toolchain=msvc --extra-cflags="${EXTRA_CFLAGS}" --extra-ldflags="${EXTRA_LDFLAGS}" ${OPTIONS} ) build() ( make -j$NUMBER_OF_PROCESSORS ) echo Building ffmpeg in MSVC Debug config... make_dirs cd ffmpeg if $clean_build ; then clean ## run configure, redirect to file because of a msys bug configure > ffbuild/config.out 2>&1 CONFIGRETVAL=$? ## show configure output cat ffbuild/config.out fi ## Only if configure succeeded, actually build if ! $clean_build || [ ${CONFIGRETVAL} -eq 0 ]; then build && copy_libs fi cd .. ================================================ FILE: common/DSUtilLite/BaseDSPropPage.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "BaseDSPropPage.h" CBaseDSPropPage::CBaseDSPropPage(LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, int DialogId, int TitleId) : CBasePropertyPage(pName, pUnk, DialogId, TitleId) { } HWND CBaseDSPropPage::createHintWindow(HWND parent, int timePop, int timeInit, int timeReshow) { HWND hhint = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, nullptr, WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, parent, nullptr, nullptr, nullptr); SetWindowPos(hhint, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); SendMessage(hhint, TTM_SETDELAYTIME, TTDT_AUTOPOP, MAKELONG(timePop, 0)); SendMessage(hhint, TTM_SETDELAYTIME, TTDT_INITIAL, MAKELONG(timeInit, 0)); SendMessage(hhint, TTM_SETDELAYTIME, TTDT_RESHOW, MAKELONG(timeReshow, 0)); SendMessage(hhint, TTM_SETMAXTIPWIDTH, 0, 470); return hhint; } TOOLINFO CBaseDSPropPage::addHint(int id, const LPWSTR text) { if (!m_hHint) m_hHint = createHintWindow(m_Dlg, 15000); TOOLINFO ti; ti.cbSize = sizeof(TOOLINFO); ti.uFlags = TTF_SUBCLASS | TTF_IDISHWND; ti.hwnd = m_Dlg; ti.uId = (LPARAM)GetDlgItem(m_Dlg, id); ti.lpszText = text; SendMessage(m_hHint, TTM_ADDTOOL, 0, (LPARAM)&ti); return ti; } void CBaseDSPropPage::ListView_AddCol(HWND hlv, int &ncol, int w, const wchar_t *txt, bool right) { LVCOLUMN lvc; lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; lvc.iSubItem = ncol; lvc.pszText = (LPWSTR)txt; lvc.cx = w; lvc.fmt = right ? LVCFMT_RIGHT : LVCFMT_LEFT; ListView_InsertColumn(hlv, ncol, &lvc); ncol++; } HRESULT CBaseDSPropPage::ShowPropPageDialog(IBaseFilter *pFilter, HWND hwndOwner) { CheckPointer(pFilter, E_INVALIDARG); CoInitialize(nullptr); // Get PropertyPages interface ISpecifyPropertyPages *pProp = nullptr; HRESULT hr = pFilter->QueryInterface(&pProp); if (SUCCEEDED(hr) && pProp) { // Get the filter's name and IUnknown pointer. FILTER_INFO FilterInfo; hr = pFilter->QueryFilterInfo(&FilterInfo); // We don't need the graph, so don't sit on a ref to it if (FilterInfo.pGraph) FilterInfo.pGraph->Release(); IUnknown *pFilterUnk = nullptr; pFilter->QueryInterface(&pFilterUnk); // Show the page. CAUUID caGUID; pProp->GetPages(&caGUID); pProp->Release(); hr = OleCreatePropertyFrame(hwndOwner, // Parent window 0, 0, // Reserved FilterInfo.achName, // Caption for the dialog box 1, // Number of objects (just the filter) &pFilterUnk, // Array of object pointers. caGUID.cElems, // Number of property pages caGUID.pElems, // Array of property page CLSIDs 0, // Locale identifier 0, nullptr // Reserved ); // Clean up. pFilterUnk->Release(); CoTaskMemFree(caGUID.pElems); hr = S_OK; } CoUninitialize(); return hr; } ================================================ FILE: common/DSUtilLite/BaseDSPropPage.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class CBaseDSPropPage : public CBasePropertyPage { public: CBaseDSPropPage(LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, int DialogId, int TitleId); public: static HRESULT ShowPropPageDialog(IBaseFilter *pFilter, HWND hwndOwner = nullptr); protected: // Convenience function to add a new column to a list view control static void ListView_AddCol(HWND hlv, int &ncol, int w, const wchar_t *txt, bool right); TOOLINFO addHint(int id, const LPWSTR text); private: HWND createHintWindow(HWND parent, int timePop = 1700, int timeInit = 70, int timeReshow = 7); private: HWND m_hHint = 0; }; ================================================ FILE: common/DSUtilLite/BaseTrayIcon.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "DShowUtil.h" #include "BaseTrayIcon.h" #include "BaseDSPropPage.h" #include #include #include #define TRAYICON 0x1f0 #define MSG_TRAYICON WM_USER + 1 #define MSG_QUIT WM_USER + 2 // The assumed size of the propery page #define PROP_WIDTH_OFFSET 400 #define PROP_HEIGHT_OFFSET 250 static const WCHAR *noTrayProcesses[] = {L"dllhost.exe", L"explorer.exe", L"ReClockHelper.dll"}; BOOL CBaseTrayIcon::ProcessBlackList() { WCHAR fileName[1024]; GetModuleFileName(nullptr, fileName, 1024); WCHAR *processName = PathFindFileName(fileName); for (int i = 0; i < countof(noTrayProcesses); i++) { if (_wcsicmp(processName, noTrayProcesses[i]) == 0) return TRUE; } return FALSE; } CBaseTrayIcon::CBaseTrayIcon(IBaseFilter *pFilter, const WCHAR *wszName, int resIcon) : m_pFilter(pFilter) , m_wszName(wszName) , m_resIcon(resIcon) { memset(&m_NotifyIconData, 0, sizeof(m_NotifyIconData)); m_evSetupFinished.Reset(); StartMessageThread(); } CBaseTrayIcon::~CBaseTrayIcon(void) { m_pFilter = nullptr; if (m_hWnd) { SendMessage(m_hWnd, MSG_QUIT, 0, 0); WaitForSingleObject(m_hThread, INFINITE); } CloseHandle(m_hThread); } HRESULT CBaseTrayIcon::StartMessageThread() { m_hThread = (HANDLE)_beginthreadex(nullptr, /* Security */ 0, /* Stack Size */ InitialThreadProc, /* Thread process */ (LPVOID)this, /* Arguments */ 0, /* 0 = Start Immediately */ nullptr /* Thread Address */ ); m_evSetupFinished.Wait(); return S_OK; } unsigned int WINAPI CBaseTrayIcon::InitialThreadProc(LPVOID pv) { HRESULT hrCo = CoInitialize(nullptr); CBaseTrayIcon *pTrayIcon = (CBaseTrayIcon *)pv; unsigned int ret = pTrayIcon->TrayMessageThread(); if (SUCCEEDED(hrCo)) CoUninitialize(); return ret; } DWORD CBaseTrayIcon::TrayMessageThread() { HRESULT hr; MSG msg; // Create the Window Class if it doesn't exist yet hr = RegisterWindowClass(); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"CBaseTrayIcon::ThreadProc(): Failed to register window class")); } // And the Window we use for messages hr = CreateMessageWindow(); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"CBaseTrayIcon::ThreadProc(): Failed to create message window")); m_evSetupFinished.Set(); UnregisterClass(m_wszClassName, g_hInst); return 1; } ASSERT(m_hWnd); CreateTrayIconData(); Shell_NotifyIcon(NIM_ADD, &m_NotifyIconData); Shell_NotifyIcon(NIM_SETVERSION, &m_NotifyIconData); m_evSetupFinished.Set(); // Message loop while (GetMessage(&msg, nullptr, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } Shell_NotifyIcon(NIM_DELETE, &m_NotifyIconData); // Free icon resources if (m_NotifyIconData.hIcon) { DestroyIcon(m_NotifyIconData.hIcon); m_NotifyIconData.hIcon = nullptr; } // Unregister the window class we used UnregisterClass(m_wszClassName, g_hInst); return 0; } HRESULT CBaseTrayIcon::RegisterWindowClass() { swprintf_s(m_wszClassName, countof(m_wszClassName), L"LAVTrayIconClass%d", GetCurrentThreadId()); WNDCLASSEX wx = {}; wx.cbSize = sizeof(WNDCLASSEX); wx.lpfnWndProc = WindowProc; wx.hInstance = g_hInst; wx.lpszClassName = m_wszClassName; ATOM wndClass = RegisterClassEx(&wx); return !wndClass ? E_FAIL : S_OK; } HRESULT CBaseTrayIcon::CreateMessageWindow() { m_hWnd = CreateWindowEx(0, m_wszClassName, L"LAV Tray Message Window", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr); SetWindowLongPtr(m_hWnd, GWLP_USERDATA, LONG_PTR(this)); return m_hWnd == nullptr ? E_FAIL : S_OK; } HRESULT CBaseTrayIcon::CreateTrayIconData() { memset(&m_NotifyIconData, 0, sizeof(m_NotifyIconData)); m_NotifyIconData.cbSize = sizeof(m_NotifyIconData); m_NotifyIconData.hWnd = m_hWnd; m_NotifyIconData.uID = TRAYICON; m_NotifyIconData.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE; m_NotifyIconData.hIcon = (HICON)LoadImage(g_hInst, MAKEINTRESOURCE(m_resIcon), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); m_NotifyIconData.uCallbackMessage = MSG_TRAYICON; m_NotifyIconData.uVersion = NOTIFYICON_VERSION; wcscpy_s(m_NotifyIconData.szTip, m_wszName); return S_OK; } HRESULT CBaseTrayIcon::OpenPropPage() { CheckPointer(m_pFilter, E_UNEXPECTED); m_bPropPageOpen = TRUE; RECT desktopRect; GetWindowRect(GetDesktopWindow(), &desktopRect); SetWindowPos(m_hWnd, 0, (desktopRect.right / 2) - PROP_WIDTH_OFFSET, (desktopRect.bottom / 2) - PROP_HEIGHT_OFFSET, 0, 0, SWP_NOZORDER | SWP_NOSIZE); CBaseDSPropPage::ShowPropPageDialog(m_pFilter, m_hWnd); m_bPropPageOpen = FALSE; return S_OK; } static BOOL CALLBACK enumWindowCallback(HWND hwnd, LPARAM lparam) { HWND owner = (HWND)lparam; if (owner == GetWindow(hwnd, GW_OWNER)) { SetForegroundWindow(hwnd); return FALSE; } return TRUE; } LRESULT CALLBACK CBaseTrayIcon::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CBaseTrayIcon *icon = (CBaseTrayIcon *)GetWindowLongPtr(hwnd, GWLP_USERDATA); switch (uMsg) { case WM_DESTROY: Shell_NotifyIcon(NIM_DELETE, &icon->m_NotifyIconData); PostQuitMessage(0); break; case MSG_QUIT: DestroyWindow(hwnd); break; case MSG_TRAYICON: { UINT trayMsg = LOWORD(lParam); if (icon) { switch (trayMsg) { case WM_LBUTTONUP: if (!icon->m_bPropPageOpen) { icon->OpenPropPage(); } else { EnumThreadWindows(GetCurrentThreadId(), enumWindowCallback, (LPARAM)icon->m_hWnd); } break; case WM_RBUTTONUP: case WM_CONTEXTMENU: if (icon->m_bPropPageOpen) { break; } HMENU hMenu = icon->GetPopupMenu(); if (hMenu) { POINT p; GetCursorPos(&p); SetForegroundWindow(hwnd); int cmd = TrackPopupMenu(hMenu, TPM_RETURNCMD, p.x, p.y, 0, hwnd, nullptr); PostMessage(hwnd, WM_NULL, 0, 0); icon->ProcessMenuCommand(hMenu, cmd); DestroyMenu(hMenu); } break; } } } break; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } ================================================ FILE: common/DSUtilLite/BaseTrayIcon.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include class CBaseTrayIcon { public: CBaseTrayIcon(IBaseFilter *pFilter, const WCHAR *wszName, int resIcon); virtual ~CBaseTrayIcon(void); static BOOL ProcessBlackList(); protected: virtual HRESULT CreateTrayIconData(); virtual HMENU GetPopupMenu() { return nullptr; } virtual HRESULT ProcessMenuCommand(HMENU hMenu, int cmd) { return E_NOTIMPL; } HRESULT OpenPropPage(); private: HRESULT StartMessageThread(); HRESULT RegisterWindowClass(); HRESULT CreateMessageWindow(); DWORD TrayMessageThread(); static unsigned int WINAPI InitialThreadProc(LPVOID pv); static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); protected: IBaseFilter *m_pFilter; private: CAMEvent m_evSetupFinished{TRUE}; HANDLE m_hThread = 0; HWND m_hWnd = 0; BOOL m_bPropPageOpen = FALSE; WCHAR m_wszClassName[64]; const WCHAR *m_wszName = nullptr; int m_resIcon = 0; NOTIFYICONDATA m_NotifyIconData; }; ================================================ FILE: common/DSUtilLite/ByteParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #include "stdafx.h" #include "ByteParser.h" #pragma warning(push) #pragma warning(disable : 4101) #pragma warning(disable : 4244) #pragma warning(disable : 5033) extern "C" { #define AVCODEC_X86_MATHOPS_H #include "libavcodec/get_bits.h" }; #pragma warning(pop) CByteParser::CByteParser(const BYTE *pData, size_t length) : m_pData(pData) , m_pEnd(pData + length) { m_gbCtx = (GetBitContext *)av_mallocz(sizeof(GetBitContext)); init_get_bits8(m_gbCtx, pData, (int)length); } CByteParser::~CByteParser() { av_freep(&m_gbCtx); } unsigned int CByteParser::BitRead(unsigned int numBits, bool peek) { if (numBits == 0) return 0; if (peek) return show_bits_long(m_gbCtx, numBits); else return get_bits_long(m_gbCtx, numBits); } void CByteParser::BitSkip(unsigned int numBits) { if (numBits == 0) return; skip_bits_long(m_gbCtx, numBits); } size_t CByteParser::RemainingBits() const { int bits = get_bits_left(m_gbCtx); if (bits < 0) return 0; return (size_t)bits; } size_t CByteParser::Pos() const { return (size_t)(m_pEnd - m_pData - Remaining()); } // Exponential Golomb Coding (with k = 0) // As used in H.264/MPEG-4 AVC // http://en.wikipedia.org/wiki/Exponential-Golomb_coding unsigned CByteParser::UExpGolombRead() { int n = -1; for (BYTE b = 0; !b && RemainingBits(); n++) { b = get_bits1(m_gbCtx); } if (!RemainingBits()) return 0; return ((1 << n) | BitRead(n)) - 1; } int CByteParser::SExpGolombRead() { int k = UExpGolombRead() + 1; // Negative numbers are interleaved in the series // unsigned: 0, 1, 2, 3, 4, 5, 6, ... // signed: 0, 1, -1, 2, -2, 3, -3, .... // So all even numbers are negative (last bit = 0) // Note that we added 1 to the unsigned value already, so the check is inverted if (k & 1) return -(k >> 1); else return (k >> 1); } void CByteParser::BitByteAlign() { align_get_bits(m_gbCtx); } ================================================ FILE: common/DSUtilLite/ByteParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #pragma once struct GetBitContext; /** * Byte Parser Utility Class */ class CByteParser { public: /** Construct a Byte Parser to parse the given BYTE array with the given length */ CByteParser(const BYTE *pData, size_t length); virtual ~CByteParser(); /** Read 1 to 32 Bits from the Byte Array. If peek is set, the data will just be returned, and the buffer not * advanced. */ unsigned int BitRead(unsigned int numBits, bool peek = false); /** Skip any number of bits from the byte array */ void BitSkip(unsigned int numBits); /** Read a unsigned number in Exponential Golomb encoding (with k = 0) */ unsigned int UExpGolombRead(); /** Read a signed number in Exponential Golomb encoding (with k = 0) */ int SExpGolombRead(); /** Pointer to the start of the byte array */ const BYTE *Start() const { return m_pData; } /** Pointer to the end of the byte array */ const BYTE *End() const { return m_pEnd; } /** Overall length (in bytes) of the byte array */ size_t Length() const; size_t Pos() const; /** Number of bytes remaining in the array */ size_t Remaining() const { return RemainingBits() >> 3; } /** Number of bits remaining */ size_t RemainingBits() const; void BitByteAlign(); private: GetBitContext *m_gbCtx = nullptr; const BYTE *m_pData = nullptr; const BYTE *m_pEnd = nullptr; }; ================================================ FILE: common/DSUtilLite/CueSheet.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "CueSheet.h" #include #include #include using namespace std; enum class ParserState { GLOBAL, FILE, TRACK }; typedef string::value_type char_t; static char_t up_char(char_t ch) { return use_facet>(locale()).toupper(ch); } static string toupper(const string &src) { string result; transform(src.begin(), src.end(), back_inserter(result), up_char); return result; } static void str_replace(string &s, const string &search, const string &replace) { for (string::size_type pos = 0;; pos += replace.length()) { pos = s.find(search, pos); if (pos == string::npos) break; s.erase(pos, search.length()); s.insert(pos, replace); } } static string GetCueParam(string line, bool firstWord = false) { const string delims(" \t\n\r\"'"); string::size_type idx; // Find beginning of the command word idx = line.find_first_not_of(delims); // Find end of the command word idx = line.find_first_of(delims, idx); // Find beginning of param idx = line.find_first_not_of(delims, idx); if (idx == string::npos) return string(); string param = line.substr(idx); // trim spaces off the end param = param.substr(0, param.find_last_not_of(delims) + 1); // replace escaped quotes str_replace(param, "\\\"", "\""); if (firstWord) { idx = param.find_first_of(delims); if (idx != string::npos) param = param.substr(0, idx); } return param; } static REFERENCE_TIME ParseCueIndex(string line) { int index, m, s, f, ret; ret = sscanf_s(line.c_str(), " INDEX %d %d:%d:%d", &index, &m, &s, &f); if (ret == 4) return (m * 60i64 + s) * 10000000i64 + (f * 10000000i64 / 75); else return 0; } CCueSheet::CCueSheet() { } CCueSheet::~CCueSheet() { } HRESULT CCueSheet::Parse(string cueSheet) { DbgLog((LOG_TRACE, 10, L"CCueSheet::Parse(): Parsing Cue Sheet")); int trackCount = 0; ParserState state(ParserState::GLOBAL); stringstream cueSheetStream(cueSheet); string line; while (getline(cueSheetStream, line)) { string word; (stringstream(line)) >> word; word = toupper(word); switch (state) { case ParserState::GLOBAL: if (word == "PERFORMER") { m_Performer = GetCueParam(line); } else if (word == "TITLE") { m_Title = GetCueParam(line); } else if (word == "FILE") { state = ParserState::FILE; } break; case ParserState::FILE: case ParserState::TRACK: if (word == "FILE") { DbgLog((LOG_TRACE, 10, L"CCueSheet::Parse(): Multiple FILE segments not supported.")); return E_FAIL; } if (word == "TRACK") { state = ParserState::TRACK; trackCount++; string id = GetCueParam(line, true); Track track{trackCount - 1, id, "Title " + id, 0, ""}; m_Tracks.push_back(track); } else if (state == ParserState::TRACK) { if (word == "TITLE") { m_Tracks.back().Title = GetCueParam(line); } else if (word == "INDEX") { m_Tracks.back().Time = ParseCueIndex(line); } else if (word == "PERFORMER") { m_Tracks.back().Performer = GetCueParam(line); } } break; } } return S_OK; } std::string CCueSheet::FormatTrack(Track &track) { string trackFormat = track.Id + ". "; if (!track.Performer.empty()) trackFormat += track.Performer + " - "; trackFormat += track.Title; return trackFormat; } ================================================ FILE: common/DSUtilLite/CueSheet.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #include class CCueSheet { public: CCueSheet(); ~CCueSheet(); HRESULT Parse(std::string cueSheet); public: struct Track { int index; std::string Id; std::string Title; REFERENCE_TIME Time; std::string Performer; }; std::string m_Performer; std::string m_Title; std::list m_Tracks; std::string FormatTrack(Track &track); }; ================================================ FILE: common/DSUtilLite/DSMResourceBag.cpp ================================================ #include "stdafx.h" #include "DSMResourceBag.h" #include CDSMResource::CDSMResource() : mime(L"application/octet-stream") { } CDSMResource::CDSMResource(LPCWSTR name, LPCWSTR desc, LPCWSTR mime, BYTE *pData, int len, DWORD_PTR tag) { this->name = name; this->desc = desc; this->mime = mime; data.resize(len); memcpy(data.data(), pData, data.size()); this->tag = tag; } CDSMResource &CDSMResource::operator=(const CDSMResource &r) { if (this != &r) { name = r.name; desc = r.desc; mime = r.mime; data = r.data; tag = r.tag; } return *this; } CDSMResourceBag::CDSMResourceBag() { } CDSMResourceBag::~CDSMResourceBag() { m_resources.clear(); } STDMETHODIMP_(DWORD) CDSMResourceBag::ResGetCount() { CAutoLock lock(&m_csResources); return (DWORD)m_resources.size(); } STDMETHODIMP CDSMResourceBag::ResGet(DWORD iIndex, BSTR *ppName, BSTR *ppDesc, BSTR *ppMime, BYTE **ppData, DWORD *pDataLen, DWORD_PTR *pTag) { CAutoLock lock(&m_csResources); if (ppData && !pDataLen) return E_INVALIDARG; if (iIndex >= m_resources.size()) return E_INVALIDARG; CDSMResource &r = m_resources[iIndex]; if (ppName) { *ppName = SysAllocString(r.name.data()); if (*ppName == NULL) return E_OUTOFMEMORY; } if (ppDesc) { *ppDesc = SysAllocString(r.desc.data()); if (*ppDesc == NULL) return E_OUTOFMEMORY; } if (ppMime) { *ppMime = SysAllocString(r.mime.data()); if (*ppMime == NULL) return E_OUTOFMEMORY; } if (ppData) { *pDataLen = (DWORD)r.data.size(); memcpy(*ppData = (BYTE *)CoTaskMemAlloc(*pDataLen), r.data.data(), *pDataLen); } if (pTag) { *pTag = r.tag; } return S_OK; } STDMETHODIMP CDSMResourceBag::ResSet(DWORD iIndex, LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, const BYTE *pData, DWORD len, DWORD_PTR tag) { CAutoLock lock(&m_csResources); if (iIndex >= m_resources.size()) return E_INVALIDARG; CDSMResource &r = m_resources[iIndex]; if (pName) r.name = pName; if (pDesc) r.desc = pDesc; if (pMime) r.mime = pMime; if (pData || len == 0) { r.data.resize(len); if (pData) { memcpy(r.data.data(), pData, r.data.size()); } } r.tag = tag; return S_OK; } STDMETHODIMP CDSMResourceBag::ResAppend(LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, BYTE *pData, DWORD len, DWORD_PTR tag) { CAutoLock lock(&m_csResources); m_resources.push_back(CDSMResource()); return ResSet((DWORD)m_resources.size() - 1, pName, pDesc, pMime, pData, len, tag); } STDMETHODIMP CDSMResourceBag::ResRemoveAt(DWORD iIndex) { CAutoLock lock(&m_csResources); if (iIndex >= m_resources.size()) return E_INVALIDARG; m_resources.erase(m_resources.cbegin() + iIndex); return S_OK; } STDMETHODIMP CDSMResourceBag::ResRemoveAll(DWORD_PTR tag) { CAutoLock lock(&m_csResources); if (tag) { m_resources.erase( std::remove_if(m_resources.begin(), m_resources.end(), [&](const CDSMResource &r) { return r.tag == tag; }), m_resources.end()); } else { m_resources.clear(); } return S_OK; } ================================================ FILE: common/DSUtilLite/DSMResourceBag.h ================================================ #pragma once #include "IDSMResourceBag.h" #include #include #include class CDSMResource { public: CDSMResource(); CDSMResource(LPCWSTR name, LPCWSTR desc, LPCWSTR mime, BYTE *pData, int len, DWORD_PTR tag = 0); CDSMResource &operator=(const CDSMResource &r); public: DWORD_PTR tag; std::wstring name, desc, mime; std::vector data; }; class CDSMResourceBag : public IDSMResourceBag { public: CDSMResourceBag(); virtual ~CDSMResourceBag(); // IDSMResourceBag STDMETHODIMP_(DWORD) ResGetCount(); STDMETHODIMP ResGet(DWORD iIndex, BSTR *ppName, BSTR *ppDesc, BSTR *ppMime, BYTE **ppData, DWORD *pDataLen, DWORD_PTR *pTag = nullptr); STDMETHODIMP ResSet(DWORD iIndex, LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, const BYTE *pData, DWORD len, DWORD_PTR tag = 0); STDMETHODIMP ResAppend(LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, BYTE *pData, DWORD len, DWORD_PTR tag = 0); STDMETHODIMP ResRemoveAt(DWORD iIndex); STDMETHODIMP ResRemoveAll(DWORD_PTR tag = 0); private: CCritSec m_csResources; std::vector m_resources; }; ================================================ FILE: common/DSUtilLite/DSUtilLite.vcxproj ================================================  Debug Win32 Debug x64 Release Win32 Release x64 {0A058024-41F4-4509-97D2-803A1806CE86} Win32Proj DSUtilLite StaticLibrary true Unicode StaticLibrary false true Unicode dsutild dsutil WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) "$(SolutionDir)common\genversion.bat" WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) "$(SolutionDir)common\genversion.bat" Create {e8a3f6fa-ae1c-4c8e-a0b6-9c8480324eaa} ================================================ FILE: common/DSUtilLite/DSUtilLite.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {a130de5c-2e03-4582-92a8-2675b370e46f} {b645319e-a7a0-4188-b5cb-516008bf32c5} Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files\DeCSS Header Files\DeCSS Header Files\DeCSS Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files\DeCSS Source Files\DeCSS Source Files\DeCSS Source Files Source Files Source Files Source Files Source Files Source Files ================================================ FILE: common/DSUtilLite/DShowUtil.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "DShowUtil.h" #include #include #include "moreuuids.h" #include "registry.h" #include "IMediaSideDataFFmpeg.h" // // Usage: SetThreadName (-1, "MainThread"); // typedef struct tagTHREADNAME_INFO { DWORD dwType; // must be 0x1000 LPCSTR szName; // pointer to name (in user addr space) DWORD dwThreadID; // thread ID (-1=caller thread) DWORD dwFlags; // reserved for future use, must be zero } THREADNAME_INFO; const DWORD MS_VC_EXCEPTION = 0x406D1388; void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = szThreadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info); } __except (EXCEPTION_EXECUTE_HANDLER) { } } #ifdef DEBUG #include #include extern HANDLE m_hOutput; volatile LONG hOutputCounter = 0; extern HRESULT DbgUniqueProcessName(LPCTSTR inName, LPTSTR outName); void DbgSetLogFile(LPCTSTR szFile) { HANDLE hOutput = CreateFile(szFile, GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (INVALID_HANDLE_VALUE == hOutput && GetLastError() == ERROR_SHARING_VIOLATION) { TCHAR uniqueName[MAX_PATH] = {0}; if (SUCCEEDED(DbgUniqueProcessName(szFile, uniqueName))) { hOutput = CreateFile(uniqueName, GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); } } if (hOutput != INVALID_HANDLE_VALUE) { if (InterlockedCompareExchangePointer(&m_hOutput, hOutput, INVALID_HANDLE_VALUE) != INVALID_HANDLE_VALUE) CloseHandle(hOutput); } InterlockedIncrement(&hOutputCounter); } void DbgSetLogFileDesktop(LPCTSTR szFile) { TCHAR szLogPath[512]; SHGetFolderPath(nullptr, CSIDL_DESKTOPDIRECTORY, nullptr, 0, szLogPath); PathAppend(szLogPath, szFile); DbgSetLogFile(szLogPath); } void DbgCloseLogFile() { LONG count = InterlockedDecrement(&hOutputCounter); if (count == 0 && m_hOutput != INVALID_HANDLE_VALUE) { FlushFileBuffers(m_hOutput); CloseHandle(m_hOutput); m_hOutput = INVALID_HANDLE_VALUE; } } #endif void split(const std::string &text, const std::string &separators, std::list &words) { size_t n = text.length(); size_t start, stop; start = text.find_first_not_of(separators); while ((start >= 0) && (start < n)) { stop = text.find_first_of(separators, start); if ((stop < 0) || (stop > n)) stop = n; words.push_back(text.substr(start, stop - start)); start = text.find_first_not_of(separators, stop + 1); } } IBaseFilter *FindFilter(const GUID &clsid, IFilterGraph *pFG) { IBaseFilter *pFilter = nullptr; IEnumFilters *pEnumFilters = nullptr; if (pFG && SUCCEEDED(pFG->EnumFilters(&pEnumFilters))) { for (IBaseFilter *pBF = nullptr; S_OK == pEnumFilters->Next(1, &pBF, 0);) { GUID clsid2; if (SUCCEEDED(pBF->GetClassID(&clsid2)) && clsid == clsid2) { pFilter = pBF; break; } SafeRelease(&pBF); } SafeRelease(&pEnumFilters); } return pFilter; } BOOL FilterInGraph(const GUID &clsid, IFilterGraph *pFG) { BOOL bFound = FALSE; IBaseFilter *pFilter = nullptr; pFilter = FindFilter(clsid, pFG); bFound = (pFilter != nullptr); SafeRelease(&pFilter); return bFound; } BOOL FilterInGraphWithInputSubtype(const GUID &clsid, IFilterGraph *pFG, const GUID &clsidSubtype) { BOOL bFound = FALSE; IBaseFilter *pFilter = nullptr; pFilter = FindFilter(clsid, pFG); if (pFilter) { IEnumPins *pPinEnum = nullptr; pFilter->EnumPins(&pPinEnum); IPin *pPin = nullptr; while ((S_OK == pPinEnum->Next(1, &pPin, nullptr)) && pPin) { PIN_DIRECTION dir; pPin->QueryDirection(&dir); if (dir == PINDIR_INPUT) { AM_MEDIA_TYPE mt; pPin->ConnectionMediaType(&mt); if (mt.subtype == clsidSubtype) { bFound = TRUE; } FreeMediaType(mt); } SafeRelease(&pPin); if (bFound) break; } SafeRelease(&pPinEnum); SafeRelease(&pFilter); } return bFound; } std::wstring WStringFromGUID(const GUID &guid) { WCHAR null[128] = {0}, buff[128]; StringFromGUID2(GUID_NULL, null, 127); return std::wstring(StringFromGUID2(guid, buff, 127) > 0 ? buff : null); } int SafeMultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar) { int len = MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, lpWideCharStr, cchWideChar); if (cchWideChar) { if (len == cchWideChar || (len == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { lpWideCharStr[cchWideChar - 1] = 0; } else if (len == 0) { DWORD dwErr = GetLastError(); if (dwErr == ERROR_NO_UNICODE_TRANSLATION && CodePage == CP_UTF8) { return SafeMultiByteToWideChar(CP_ACP, dwFlags, lpMultiByteStr, cbMultiByte, lpWideCharStr, cchWideChar); } else if (dwErr == ERROR_NO_UNICODE_TRANSLATION && (dwFlags & MB_ERR_INVALID_CHARS)) { return SafeMultiByteToWideChar(CP_UTF8, (dwFlags & ~MB_ERR_INVALID_CHARS), lpMultiByteStr, cbMultiByte, lpWideCharStr, cchWideChar); } lpWideCharStr[0] = 0; } } return len; } int SafeWideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, LPBOOL lpUsedDefaultChar) { int len = WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar); if (cbMultiByte) { if (len == cbMultiByte || (len == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER)) { lpMultiByteStr[cbMultiByte - 1] = 0; } else if (len == 0) { lpMultiByteStr[0] = 0; } } return len; } LPWSTR CoTaskGetWideCharFromMultiByte(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte) { int len = MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, nullptr, 0); if (len) { LPWSTR pszWideString = (LPWSTR)CoTaskMemAlloc(len * sizeof(WCHAR)); MultiByteToWideChar(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, pszWideString, len); return pszWideString; } else { DWORD dwErr = GetLastError(); if (dwErr == ERROR_NO_UNICODE_TRANSLATION && CodePage == CP_UTF8) { return CoTaskGetWideCharFromMultiByte(CP_ACP, dwFlags, lpMultiByteStr, cbMultiByte); } else if (dwErr == ERROR_NO_UNICODE_TRANSLATION && (dwFlags & MB_ERR_INVALID_CHARS)) { return CoTaskGetWideCharFromMultiByte(CP_UTF8, (dwFlags & ~MB_ERR_INVALID_CHARS), lpMultiByteStr, cbMultiByte); } } return NULL; } LPSTR CoTaskGetMultiByteFromWideChar(UINT CodePage, DWORD dwFlags, LPCWSTR lpMultiByteStr, int cbMultiByte) { int len = WideCharToMultiByte(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, nullptr, 0, nullptr, nullptr); if (len) { LPSTR pszMBString = (LPSTR)CoTaskMemAlloc(len * sizeof(char)); WideCharToMultiByte(CodePage, dwFlags, lpMultiByteStr, cbMultiByte, pszMBString, len, nullptr, nullptr); return pszMBString; } return NULL; } BSTR ConvertCharToBSTR(const char *sz) { bool acp = false; if (!sz || strlen(sz) == 0) return nullptr; WCHAR *wide = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, sz, -1); if (!wide) return nullptr; BSTR bstr = SysAllocString(wide); CoTaskMemFree(wide); return bstr; } IBaseFilter *GetFilterFromPin(IPin *pPin) { CheckPointer(pPin, nullptr); PIN_INFO pi; if (pPin && SUCCEEDED(pPin->QueryPinInfo(&pi))) { return pi.pFilter; } return nullptr; } HRESULT NukeDownstream(IFilterGraph *pGraph, IPin *pPin) { PIN_DIRECTION dir; if (pPin) { IPin *pPinTo = nullptr; if (FAILED(pPin->QueryDirection(&dir))) return E_FAIL; if (dir == PINDIR_OUTPUT) { if (SUCCEEDED(pPin->ConnectedTo(&pPinTo)) && pPinTo) { if (IBaseFilter *pFilter = GetFilterFromPin(pPinTo)) { NukeDownstream(pGraph, pFilter); pGraph->Disconnect(pPinTo); pGraph->Disconnect(pPin); pGraph->RemoveFilter(pFilter); SafeRelease(&pFilter); } SafeRelease(&pPinTo); } } } return S_OK; } HRESULT NukeDownstream(IFilterGraph *pGraph, IBaseFilter *pFilter) { IEnumPins *pEnumPins = nullptr; if (pFilter && SUCCEEDED(pFilter->EnumPins(&pEnumPins))) { for (IPin *pPin = nullptr; S_OK == pEnumPins->Next(1, &pPin, 0); pPin = nullptr) { NukeDownstream(pGraph, pPin); SafeRelease(&pPin); } SafeRelease(&pEnumPins); } return S_OK; } // pPin - pin of our filter to start searching // refiid - guid of the interface to find // pUnknown - variable that'll receive the interface HRESULT FindIntefaceInGraph(IPin *pPin, REFIID refiid, void **pUnknown) { PIN_DIRECTION dir; pPin->QueryDirection(&dir); IPin *pOtherPin = nullptr; if (SUCCEEDED(pPin->ConnectedTo(&pOtherPin)) && pOtherPin) { IBaseFilter *pFilter = GetFilterFromPin(pOtherPin); SafeRelease(&pOtherPin); HRESULT hrFilter = pFilter->QueryInterface(refiid, pUnknown); if (FAILED(hrFilter)) { IEnumPins *pPinEnum = nullptr; pFilter->EnumPins(&pPinEnum); HRESULT hrPin = E_FAIL; for (IPin *pOtherPin2 = nullptr; pPinEnum->Next(1, &pOtherPin2, 0) == S_OK; pOtherPin2 = nullptr) { PIN_DIRECTION pinDir; pOtherPin2->QueryDirection(&pinDir); if (dir == pinDir) { hrPin = FindIntefaceInGraph(pOtherPin2, refiid, pUnknown); } SafeRelease(&pOtherPin2); if (SUCCEEDED(hrPin)) break; } hrFilter = hrPin; SafeRelease(&pPinEnum); } SafeRelease(&pFilter); if (SUCCEEDED(hrFilter)) { return S_OK; } } return E_NOINTERFACE; } // pPin - pin of our filter to start searching // refiid - guid of the interface to find // pUnknown - variable that'll receive the interface HRESULT FindPinIntefaceInGraph(IPin *pPin, REFIID refiid, void **pUnknown) { PIN_DIRECTION dir; pPin->QueryDirection(&dir); IPin *pOtherPin = nullptr; if (SUCCEEDED(pPin->ConnectedTo(&pOtherPin)) && pOtherPin) { IBaseFilter *pFilter = nullptr; HRESULT hrFilter = pOtherPin->QueryInterface(refiid, pUnknown); if (FAILED(hrFilter)) { pFilter = GetFilterFromPin(pOtherPin); IEnumPins *pPinEnum = nullptr; pFilter->EnumPins(&pPinEnum); HRESULT hrPin = E_FAIL; for (IPin *pOtherPin2 = nullptr; pPinEnum->Next(1, &pOtherPin2, 0) == S_OK; pOtherPin2 = nullptr) { PIN_DIRECTION pinDir; pOtherPin2->QueryDirection(&pinDir); if (dir == pinDir) { hrPin = FindPinIntefaceInGraph(pOtherPin2, refiid, pUnknown); } SafeRelease(&pOtherPin2); if (SUCCEEDED(hrPin)) break; } hrFilter = hrPin; SafeRelease(&pPinEnum); } SafeRelease(&pFilter); SafeRelease(&pOtherPin); if (SUCCEEDED(hrFilter)) { return S_OK; } } return E_NOINTERFACE; } // pPin - pin of our filter to start searching // guid - guid of the filter to find // ppFilter - variable that'll receive a AddRef'd reference to the filter HRESULT FindFilterSafe(IPin *pPin, const GUID &guid, IBaseFilter **ppFilter, BOOL bReverse) { CheckPointer(ppFilter, E_POINTER); CheckPointer(pPin, E_POINTER); HRESULT hr = S_OK; PIN_DIRECTION dir; pPin->QueryDirection(&dir); IPin *pOtherPin = nullptr; if (bReverse) { dir = (dir == PINDIR_INPUT) ? PINDIR_OUTPUT : PINDIR_INPUT; pOtherPin = pPin; pPin->AddRef(); hr = S_OK; } else { hr = pPin->ConnectedTo(&pOtherPin); } if (SUCCEEDED(hr) && pOtherPin) { IBaseFilter *pFilter = GetFilterFromPin(pOtherPin); SafeRelease(&pOtherPin); HRESULT hrFilter = E_NOINTERFACE; CLSID filterGUID; if (SUCCEEDED(pFilter->GetClassID(&filterGUID))) { if (filterGUID == guid) { *ppFilter = pFilter; hrFilter = S_OK; } else { IEnumPins *pPinEnum = nullptr; pFilter->EnumPins(&pPinEnum); HRESULT hrPin = E_FAIL; for (IPin *pOtherPin2 = nullptr; pPinEnum->Next(1, &pOtherPin2, 0) == S_OK; pOtherPin2 = nullptr) { PIN_DIRECTION pinDir; pOtherPin2->QueryDirection(&pinDir); if (dir == pinDir) { hrPin = FindFilterSafe(pOtherPin2, guid, ppFilter); } SafeRelease(&pOtherPin2); if (SUCCEEDED(hrPin)) break; } hrFilter = hrPin; SafeRelease(&pPinEnum); SafeRelease(&pFilter); } } if (SUCCEEDED(hrFilter)) { return S_OK; } } return E_NOINTERFACE; } // pPin - pin of our filter to start searching // guid - guid of the filter to find // ppFilter - variable that'll receive a AddRef'd reference to the filter BOOL HasSourceWithType(IPin *pPin, const GUID &mediaType) { CheckPointer(pPin, false); BOOL bFound = FALSE; PIN_DIRECTION dir; pPin->QueryDirection(&dir); IPin *pOtherPin = nullptr; if (SUCCEEDED(pPin->ConnectedTo(&pOtherPin)) && pOtherPin) { IBaseFilter *pFilter = GetFilterFromPin(pOtherPin); HRESULT hrFilter = E_NOINTERFACE; IEnumPins *pPinEnum = nullptr; pFilter->EnumPins(&pPinEnum); HRESULT hrPin = E_FAIL; for (IPin *pOtherPin2 = nullptr; !bFound && pPinEnum->Next(1, &pOtherPin2, 0) == S_OK; pOtherPin2 = nullptr) { if (pOtherPin2 != pOtherPin) { PIN_DIRECTION pinDir; pOtherPin2->QueryDirection(&pinDir); if (dir != pinDir) { IEnumMediaTypes *pMediaTypeEnum = nullptr; if (SUCCEEDED(pOtherPin2->EnumMediaTypes(&pMediaTypeEnum))) { for (AM_MEDIA_TYPE *mt = nullptr; pMediaTypeEnum->Next(1, &mt, 0) == S_OK; mt = nullptr) { if (mt->majortype == mediaType) { bFound = TRUE; } DeleteMediaType(mt); } SafeRelease(&pMediaTypeEnum); } } else { bFound = HasSourceWithType(pOtherPin2, mediaType); } } SafeRelease(&pOtherPin2); } SafeRelease(&pPinEnum); SafeRelease(&pFilter); SafeRelease(&pOtherPin); } return bFound; } // Similar to HasSourceWithType but also checks forward pins for future backwards joins BOOL HasSourceWithTypeAdvanced(IPin *pPinInput, IPin *pPinOutput, const GUID &mediaType) { // check the input pin backwards first if (pPinInput && HasSourceWithType(pPinInput, mediaType)) return true; if (pPinOutput == NULL) return false; // and check the tree forwards BOOL bFound = FALSE; IPin *pOtherPin = nullptr; if (SUCCEEDED(pPinOutput->ConnectedTo(&pOtherPin)) && pOtherPin) { IBaseFilter *pFilter = GetFilterFromPin(pOtherPin); HRESULT hrFilter = E_NOINTERFACE; IEnumPins *pPinEnum = nullptr; pFilter->EnumPins(&pPinEnum); // Iterate over pins of the filter.. HRESULT hrPin = E_FAIL; for (IPin *pOtherPin2 = nullptr; !bFound && pPinEnum->Next(1, &pOtherPin2, 0) == S_OK; pOtherPin2 = nullptr) { // ignore the pint we're connected to if (pOtherPin2 != pOtherPin) { PIN_DIRECTION pinDir; pOtherPin2->QueryDirection(&pinDir); // if its another input, go backwards there if (pinDir == PINDIR_INPUT) { bFound = HasSourceWithType(pOtherPin2, mediaType); } // if its an output, go forwards else if (pinDir == PINDIR_OUTPUT) { bFound = HasSourceWithTypeAdvanced(NULL, pOtherPin2, mediaType); } } SafeRelease(&pOtherPin2); } SafeRelease(&pPinEnum); SafeRelease(&pFilter); SafeRelease(&pOtherPin); } return bFound; } BOOL FilterInGraphSafe(IPin *pPin, const GUID &guid, BOOL bReverse) { IBaseFilter *pFilter = nullptr; HRESULT hr = FindFilterSafe(pPin, guid, &pFilter, bReverse); if (SUCCEEDED(hr) && pFilter) { SafeRelease(&pFilter); return TRUE; } return FALSE; } unsigned int lav_xiphlacing(unsigned char *s, unsigned int v) { unsigned int n = 0; while (v >= 0xff) { *s++ = 0xff; v -= 0xff; n++; } *s = v; n++; return n; } void videoFormatTypeHandler(const AM_MEDIA_TYPE &mt, BITMAPINFOHEADER **pBMI, REFERENCE_TIME *prtAvgTime, DWORD *pDwAspectX, DWORD *pDwAspectY) { videoFormatTypeHandler(mt.pbFormat, &mt.formattype, pBMI, prtAvgTime, pDwAspectX, pDwAspectY); } void videoFormatTypeHandler(const BYTE *format, const GUID *formattype, BITMAPINFOHEADER **pBMI, REFERENCE_TIME *prtAvgTime, DWORD *pDwAspectX, DWORD *pDwAspectY) { REFERENCE_TIME rtAvg = 0; BITMAPINFOHEADER *bmi = nullptr; DWORD dwAspectX = 0, dwAspectY = 0; if (!format) goto done; if (*formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER *vih = (VIDEOINFOHEADER *)format; rtAvg = vih->AvgTimePerFrame; bmi = &vih->bmiHeader; } else if (*formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)format; rtAvg = vih2->AvgTimePerFrame; bmi = &vih2->bmiHeader; dwAspectX = vih2->dwPictAspectRatioX; dwAspectY = vih2->dwPictAspectRatioY; } else if (*formattype == FORMAT_MPEGVideo) { MPEG1VIDEOINFO *mp1vi = (MPEG1VIDEOINFO *)format; rtAvg = mp1vi->hdr.AvgTimePerFrame; bmi = &mp1vi->hdr.bmiHeader; } else if (*formattype == FORMAT_MPEG2Video) { MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)format; rtAvg = mp2vi->hdr.AvgTimePerFrame; bmi = &mp2vi->hdr.bmiHeader; dwAspectX = mp2vi->hdr.dwPictAspectRatioX; dwAspectY = mp2vi->hdr.dwPictAspectRatioY; } else { ASSERT(FALSE); } done: if (pBMI) { *pBMI = bmi; } if (prtAvgTime) { *prtAvgTime = rtAvg; } if (pDwAspectX && pDwAspectY) { *pDwAspectX = dwAspectX; *pDwAspectY = dwAspectY; } } void audioFormatTypeHandler(const BYTE *format, const GUID *formattype, DWORD *pnSamples, WORD *pnChannels, WORD *pnBitsPerSample, WORD *pnBlockAlign, DWORD *pnBytesPerSec, DWORD *pnChannelMask) { DWORD nSamples = 0; WORD nChannels = 0; WORD nBitsPerSample = 0; WORD nBlockAlign = 0; DWORD nBytesPerSec = 0; DWORD nChannelMask = 0; if (!format) goto done; if (*formattype == FORMAT_WaveFormatEx) { WAVEFORMATEX *wfex = (WAVEFORMATEX *)format; nSamples = wfex->nSamplesPerSec; nChannels = wfex->nChannels; nBitsPerSample = wfex->wBitsPerSample; nBlockAlign = wfex->nBlockAlign; nBytesPerSec = wfex->nAvgBytesPerSec; if (wfex->wFormatTag == WAVE_FORMAT_EXTENSIBLE && wfex->cbSize >= 22) { WAVEFORMATEXTENSIBLE *wfexs = (WAVEFORMATEXTENSIBLE *)wfex; nChannelMask = wfexs->dwChannelMask; } } else if (*formattype == FORMAT_VorbisFormat2) { VORBISFORMAT2 *vf2 = (VORBISFORMAT2 *)format; nSamples = vf2->SamplesPerSec; nChannels = (WORD)vf2->Channels; nBitsPerSample = (WORD)vf2->BitsPerSample; } done: if (pnSamples) *pnSamples = nSamples; if (pnChannels) *pnChannels = nChannels; if (pnBitsPerSample) *pnBitsPerSample = nBitsPerSample; if (pnBlockAlign) *pnBlockAlign = nBlockAlign; if (pnBytesPerSec) *pnBytesPerSec = nBytesPerSec; if (pnChannelMask) *pnChannelMask = nChannelMask; } void getExtraData(const AM_MEDIA_TYPE &mt, BYTE *extra, size_t *extralen) { return getExtraData(mt.pbFormat, &mt.formattype, mt.cbFormat, extra, extralen); } void getExtraData(const BYTE *format, const GUID *formattype, const size_t formatlen, BYTE *extra, size_t *extralen) { const BYTE *extraposition = nullptr; size_t extralength = 0; if (*formattype == FORMAT_WaveFormatEx) { WAVEFORMATEX *wfex = (WAVEFORMATEX *)format; extraposition = format + sizeof(WAVEFORMATEX); // Protected against over-reads extralength = formatlen - sizeof(WAVEFORMATEX); } else if (*formattype == FORMAT_VorbisFormat2) { VORBISFORMAT2 *vf2 = (VORBISFORMAT2 *)format; BYTE *start = nullptr, *end = nullptr; unsigned offset = 1; if (extra) { *extra = 2; offset += lav_xiphlacing(extra + offset, vf2->HeaderSize[0]); offset += lav_xiphlacing(extra + offset, vf2->HeaderSize[1]); extra += offset; } else { BYTE dummy[100]; offset += lav_xiphlacing(dummy, vf2->HeaderSize[0]); offset += lav_xiphlacing(dummy, vf2->HeaderSize[1]); } extralength = vf2->HeaderSize[0] + vf2->HeaderSize[1] + vf2->HeaderSize[2]; extralength = min(extralength, formatlen - sizeof(VORBISFORMAT2)); if (extra && extralength) memcpy(extra, format + sizeof(VORBISFORMAT2), extralength); if (extralen) *extralen = extralength + offset; return; } else if (*formattype == FORMAT_VideoInfo) { extraposition = format + sizeof(VIDEOINFOHEADER); extralength = formatlen - sizeof(VIDEOINFOHEADER); } else if (*formattype == FORMAT_VideoInfo2) { extraposition = format + sizeof(VIDEOINFOHEADER2); extralength = formatlen - sizeof(VIDEOINFOHEADER2); } else if (*formattype == FORMAT_MPEGVideo) { MPEG1VIDEOINFO *mp1vi = (MPEG1VIDEOINFO *)format; extraposition = (BYTE *)mp1vi->bSequenceHeader; extralength = min(mp1vi->cbSequenceHeader, formatlen - FIELD_OFFSET(MPEG1VIDEOINFO, bSequenceHeader[0])); } else if (*formattype == FORMAT_MPEG2Video) { MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)format; extraposition = (BYTE *)mp2vi->dwSequenceHeader; extralength = min(mp2vi->cbSequenceHeader, formatlen - FIELD_OFFSET(MPEG2VIDEOINFO, dwSequenceHeader[0])); } else if (*formattype == FORMAT_SubtitleInfo) { SUBTITLEINFO *sub = (SUBTITLEINFO *)format; extraposition = format + sub->dwOffset; extralength = formatlen - sub->dwOffset; } if (extra && extralength) memcpy(extra, extraposition, extralength); if (extralen) *extralen = extralength; } void CopyMediaSideDataFF(AVPacket *dst, const MediaSideDataFFMpeg **sd) { if (!dst) return; if (!sd || !*sd) { dst->side_data = nullptr; dst->side_data_elems = 0; return; } // add sidedata to the packet for (int i = 0; i < (*sd)->side_data_elems; i++) { uint8_t *ptr = av_packet_new_side_data(dst, (*sd)->side_data[i].type, (*sd)->side_data[i].size); memcpy(ptr, (*sd)->side_data[i].data, (*sd)->side_data[i].size); } *sd = nullptr; } BOOL IsWindows7OrNewer() { return (g_osInfo.dwMajorVersion == 6 && g_osInfo.dwMinorVersion >= 1) || (g_osInfo.dwMajorVersion > 6); } BOOL IsWindows8OrNewer() { return (g_osInfo.dwMajorVersion == 6 && g_osInfo.dwMinorVersion >= 2) || (g_osInfo.dwMajorVersion > 6); } BOOL IsWindows10OrNewer() { return (g_osInfo.dwMajorVersion >= 10); } BOOL IsWindows10BuildOrNewer(DWORD dwBuild) { return (g_osInfo.dwMajorVersion > 10 || (g_osInfo.dwMajorVersion == 10 && g_osInfo.dwBuildNumber >= dwBuild)); } void __cdecl debugprintf(LPCWSTR format, ...) { WCHAR buf[4096], *p = buf; va_list args; int n; va_start(args, format); n = _vsnwprintf_s(p, 4096, 4096 - 3, format, args); // buf-3 is room for CR/LF/NUL va_end(args); p += (n < 0) ? (4096 - 3) : n; while (p > buf && isspace(p[-1])) *--p = L'\0'; *p++ = L'\r'; *p++ = L'\n'; *p = L'\0'; OutputDebugString(buf); } BOOL CheckApplicationBlackList(LPCTSTR subkey) { HRESULT hr; DWORD dwVal; WCHAR fileName[1024]; GetModuleFileName(NULL, fileName, 1024); WCHAR *processName = PathFindFileName(fileName); // Check local machine path CRegistry regLM = CRegistry(HKEY_LOCAL_MACHINE, subkey, hr, TRUE); if (SUCCEEDED(hr)) { dwVal = regLM.ReadDWORD(processName, hr); return SUCCEEDED(hr) && dwVal; } // Check current user path CRegistry regCU = CRegistry(HKEY_CURRENT_USER, subkey, hr, TRUE); if (SUCCEEDED(hr)) { dwVal = regCU.ReadDWORD(processName, hr); return SUCCEEDED(hr) && dwVal; } return FALSE; } ================================================ FILE: common/DSUtilLite/DShowUtil.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #pragma once #include #include #include #define LCID_NOSUBTITLES -1 // SafeRelease Template, for type safety template void SafeRelease(T **ppT) { if (*ppT) { (*ppT)->Release(); *ppT = nullptr; } } #ifdef _DEBUG #define DBG_TIMING(x, l, y) \ { \ DWORD start = timeGetTime(); \ y; \ DWORD end = timeGetTime(); \ if (end - start > l) \ DbgLog((LOG_CUSTOM5, 10, L"TIMING: %S took %u ms", x, end - start)); \ } extern void DbgSetLogFile(LPCTSTR szLogFile); extern void DbgSetLogFileDesktop(LPCTSTR szLogFile); extern void DbgCloseLogFile(); #else #define DBG_TIMING(x, l, y) y; #define DbgSetLogFile(sz) #define DbgSetLogFileDesktop(sz) #define DbgCloseLogFile() #endif // SAFE_ARRAY_DELETE macro. // Deletes an array allocated with new []. #ifndef SAFE_ARRAY_DELETE #define SAFE_ARRAY_DELETE(x) \ if (x) \ { \ delete[] x; \ x = nullptr; \ } #endif // some common macros #define SAFE_DELETE(pPtr) \ { \ delete pPtr; \ pPtr = nullptr; \ } #define SAFE_CO_FREE(pPtr) \ { \ CoTaskMemFree(pPtr); \ pPtr = nullptr; \ } #define CHECK_HR(hr) \ if (FAILED(hr)) \ { \ goto done; \ } #define QI(i) (riid == __uuidof(i)) ? GetInterface((i *)this, ppv): #define QI2(i) (riid == IID_##i) ? GetInterface((i *)this, ppv): #define countof(array) (sizeof(array) / sizeof(array[0])) // Gennenric IUnknown creation function template static CUnknown *WINAPI CreateInstance(LPUNKNOWN lpunk, HRESULT *phr) { *phr = S_OK; CUnknown *punk = new T(lpunk, phr); if (punk == nullptr) { *phr = E_OUTOFMEMORY; } return punk; } extern void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName); void split(const std::string &text, const std::string &separators, std::list &words); // Filter Registration extern void RegisterSourceFilter(const CLSID &clsid, const GUID &subtype2, LPCWSTR chkbytes, ...); extern void RegisterSourceFilter(const CLSID &clsid, const GUID &subtype2, std::list chkbytes, ...); extern void UnRegisterSourceFilter(const GUID &subtype); extern void RegisterProtocolSourceFilter(const CLSID &clsid, LPCWSTR protocol); extern void UnRegisterProtocolSourceFilter(LPCWSTR protocol); extern BOOL CheckApplicationBlackList(LPCTSTR subkey); // Locale extern std::string ISO6391ToLanguage(LPCSTR code); extern std::string ISO6392ToLanguage(LPCSTR code); extern std::string ProbeLangForLanguage(LPCSTR code); extern LCID ISO6391ToLcid(LPCSTR code); extern LCID ISO6392ToLcid(LPCSTR code); extern LCID ProbeLangForLCID(LPCSTR code); extern std::string ISO6391To6392(LPCSTR code); extern std::string ISO6392To6391(LPCSTR code); extern std::string ProbeForISO6392(LPCSTR lang); // FilterGraphUtils extern IBaseFilter *FindFilter(const GUID &clsid, IFilterGraph *pFG); extern BOOL FilterInGraph(const GUID &clsid, IFilterGraph *pFG); extern BOOL FilterInGraphWithInputSubtype(const GUID &clsid, IFilterGraph *pFG, const GUID &clsidSubtype); extern IBaseFilter *GetFilterFromPin(IPin *pPin); extern HRESULT NukeDownstream(IFilterGraph *pGraph, IPin *pPin); extern HRESULT NukeDownstream(IFilterGraph *pGraph, IBaseFilter *pFilter); extern HRESULT FindIntefaceInGraph(IPin *pPin, REFIID refiid, void **pUnknown); extern HRESULT FindPinIntefaceInGraph(IPin *pPin, REFIID refiid, void **pUnknown); extern HRESULT FindFilterSafe(IPin *pPin, const GUID &guid, IBaseFilter **ppFilter, BOOL bReverse = FALSE); extern BOOL FilterInGraphSafe(IPin *pPin, const GUID &guid, BOOL bReverse = FALSE); extern BOOL HasSourceWithType(IPin *pPin, const GUID &mediaType); extern BOOL HasSourceWithTypeAdvanced(IPin *pPinInput, IPin *pPinOutput, const GUID &mediaType); std::wstring WStringFromGUID(const GUID &guid); BSTR ConvertCharToBSTR(const char *sz); int SafeMultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar); int SafeWideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCSTR lpDefaultChar, LPBOOL lpUsedDefaultChar); LPWSTR CoTaskGetWideCharFromMultiByte(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte); LPSTR CoTaskGetMultiByteFromWideChar(UINT CodePage, DWORD dwFlags, LPCWSTR lpMultiByteStr, int cbMultiByte); unsigned int lav_xiphlacing(unsigned char *s, unsigned int v); void videoFormatTypeHandler(const AM_MEDIA_TYPE &mt, BITMAPINFOHEADER **pBMI = nullptr, REFERENCE_TIME *prtAvgTime = nullptr, DWORD *pDwAspectX = nullptr, DWORD *pDwAspectY = nullptr); void videoFormatTypeHandler(const BYTE *format, const GUID *formattype, BITMAPINFOHEADER **pBMI = nullptr, REFERENCE_TIME *prtAvgTime = nullptr, DWORD *pDwAspectX = nullptr, DWORD *pDwAspectY = nullptr); void audioFormatTypeHandler(const BYTE *format, const GUID *formattype, DWORD *pnSamples, WORD *pnChannels, WORD *pnBitsPerSample, WORD *pnBlockAlign, DWORD *pnBytesPerSec, DWORD *pnChannelMask); void getExtraData(const AM_MEDIA_TYPE &mt, BYTE *extra, size_t *extralen); void getExtraData(const BYTE *format, const GUID *formattype, const size_t formatlen, BYTE *extra, size_t *extralen); struct AVPacket; struct MediaSideDataFFMpeg; void CopyMediaSideDataFF(AVPacket *dst, const MediaSideDataFFMpeg **sd); BOOL IsWindows7OrNewer(); BOOL IsWindows8OrNewer(); BOOL IsWindows10OrNewer(); BOOL IsWindows10BuildOrNewer(DWORD dwBuild); void __cdecl debugprintf(LPCWSTR format, ...); ================================================ FILE: common/DSUtilLite/DeCSS/CSSauth.cpp ================================================ #include "stdafx.h" static void CSSengine(int varient, unsigned char const *input, unsigned char *output); void CSSkey1(int varient, unsigned char const *challenge, unsigned char *key) { static unsigned char perm_challenge[] = {1, 3, 0, 7, 5, 2, 9, 6, 4, 8}; unsigned char scratch[10]; int i; for (i = 9; i >= 0; --i) { scratch[i] = challenge[perm_challenge[i]]; } CSSengine(varient, scratch, key); } void CSSkey2(int varient, unsigned char const *challenge, unsigned char *key) { static unsigned char perm_challenge[] = {6, 1, 9, 3, 8, 5, 7, 4, 0, 2}; static unsigned char perm_varient[] = {0x0a, 0x08, 0x0e, 0x0c, 0x0b, 0x09, 0x0f, 0x0d, 0x1a, 0x18, 0x1e, 0x1c, 0x1b, 0x19, 0x1f, 0x1d, 0x02, 0x00, 0x06, 0x04, 0x03, 0x01, 0x07, 0x05, 0x12, 0x10, 0x16, 0x14, 0x13, 0x11, 0x17, 0x15}; unsigned char scratch[10]; int i; for (i = 9; i >= 0; --i) { scratch[i] = challenge[perm_challenge[i]]; } CSSengine(perm_varient[varient], scratch, key); } void CSSbuskey(int varient, unsigned char const *challenge, unsigned char *key) { static unsigned char perm_challenge[] = {4, 0, 3, 5, 7, 2, 8, 6, 1, 9}; static unsigned char perm_varient[] = {0x12, 0x1a, 0x16, 0x1e, 0x02, 0x0a, 0x06, 0x0e, 0x10, 0x18, 0x14, 0x1c, 0x00, 0x08, 0x04, 0x0c, 0x13, 0x1b, 0x17, 0x1f, 0x03, 0x0b, 0x07, 0x0f, 0x11, 0x19, 0x15, 0x1d, 0x01, 0x09, 0x05, 0x0d}; unsigned char scratch[10]; int i; for (i = 9; i >= 0; --i) { scratch[i] = challenge[perm_challenge[i]]; } CSSengine(perm_varient[varient], scratch, key); } static void CSSgenbits(unsigned char *output, int len, unsigned char const *s) { unsigned long lfsr0, lfsr1; unsigned char b1_combined; /* Save the old value of bit 1 for feedback */ /* In order to ensure that the LFSR works we need to ensure that the * initial values are non-zero. Thus when we initialise them from * the seed, we ensure that a bit is set. */ lfsr0 = (s[0] << 17) | (s[1] << 9) | ((s[2] & ~7) << 1) | 8 | (s[2] & 7); lfsr1 = (s[3] << 9) | 0x100 | s[4]; ++output; b1_combined = 0; do { int bit; unsigned char val; for (bit = 0, val = 0; bit < 8; ++bit) { unsigned char o_lfsr0, o_lfsr1; /* Actually only 1 bit each */ unsigned char combined; o_lfsr0 = ((lfsr0 >> 24) ^ (lfsr0 >> 21) ^ (lfsr0 >> 20) ^ (lfsr0 >> 12)) & 1; lfsr0 = (lfsr0 << 1) | o_lfsr0; o_lfsr1 = ((lfsr1 >> 16) ^ (lfsr1 >> 2)) & 1; lfsr1 = (lfsr1 << 1) | o_lfsr1; #define BIT0(x) ((x)&1) #define BIT1(x) (((x) >> 1) & 1) combined = !o_lfsr1 + b1_combined + !o_lfsr0; b1_combined = BIT1(combined); val |= BIT0(combined) << bit; } *--output = val; } while (--len > 0); } unsigned char CSSsecret[]; unsigned char CSSvarients[]; unsigned char CSStable0[]; unsigned char CSStable1[]; unsigned char CSStable2[]; unsigned char CSStable3[]; static void CSSengine(int varient, unsigned char const *input, unsigned char *output) { unsigned char cse, term, index; unsigned char temp1[5]; unsigned char temp2[5]; unsigned char bits[30]; int i; /* Feed the CSSsecret into the input values such that * we alter the seed to the LFSR's used above, then * generate the bits to play with. */ for (i = 5; --i >= 0;) { temp1[i] = input[5 + i] ^ CSSsecret[i] ^ CSStable2[i]; } CSSgenbits(&bits[29], sizeof bits, temp1); /* This term is used throughout the following to * select one of 32 different variations on the * algorithm. */ cse = CSSvarients[varient] ^ CSStable2[varient]; /* Now the actual blocks doing the encryption. Each * of these works on 40 bits at a time and are quite * similar. */ for (i = 5, term = 0; --i >= 0; term = input[i]) { index = bits[25 + i] ^ input[i]; index = CSStable1[index] ^ ~CSStable2[index] ^ cse; temp1[i] = CSStable2[index] ^ CSStable3[index] ^ term; } temp1[4] ^= temp1[0]; for (i = 5, term = 0; --i >= 0; term = temp1[i]) { index = bits[20 + i] ^ temp1[i]; index = CSStable1[index] ^ ~CSStable2[index] ^ cse; temp2[i] = CSStable2[index] ^ CSStable3[index] ^ term; } temp2[4] ^= temp2[0]; for (i = 5, term = 0; --i >= 0; term = temp2[i]) { index = bits[15 + i] ^ temp2[i]; index = CSStable1[index] ^ ~CSStable2[index] ^ cse; index = CSStable2[index] ^ CSStable3[index] ^ term; temp1[i] = CSStable0[index] ^ CSStable2[index]; } temp1[4] ^= temp1[0]; for (i = 5, term = 0; --i >= 0; term = temp1[i]) { index = bits[10 + i] ^ temp1[i]; index = CSStable1[index] ^ ~CSStable2[index] ^ cse; index = CSStable2[index] ^ CSStable3[index] ^ term; temp2[i] = CSStable0[index] ^ CSStable2[index]; } temp2[4] ^= temp2[0]; for (i = 5, term = 0; --i >= 0; term = temp2[i]) { index = bits[5 + i] ^ temp2[i]; index = CSStable1[index] ^ ~CSStable2[index] ^ cse; temp1[i] = CSStable2[index] ^ CSStable3[index] ^ term; } temp1[4] ^= temp1[0]; for (i = 5, term = 0; --i >= 0; term = temp1[i]) { index = bits[i] ^ temp1[i]; index = CSStable1[index] ^ ~CSStable2[index] ^ cse; output[i] = CSStable2[index] ^ CSStable3[index] ^ term; } } static unsigned char CSSvarients[] = {0xB7, 0x74, 0x85, 0xD0, 0xCC, 0xDB, 0xCA, 0x73, 0x03, 0xFE, 0x31, 0x03, 0x52, 0xE0, 0xB7, 0x42, 0x63, 0x16, 0xF2, 0x2A, 0x79, 0x52, 0xFF, 0x1B, 0x7A, 0x11, 0xCA, 0x1A, 0x9B, 0x40, 0xAD, 0x01}; static unsigned char CSSsecret[] = {0x55, 0xD6, 0xC4, 0xC5, 0x28}; static unsigned char CSStable0[] = { 0xB7, 0xF4, 0x82, 0x57, 0xDA, 0x4D, 0xDB, 0xE2, 0x2F, 0x52, 0x1A, 0xA8, 0x68, 0x5A, 0x8A, 0xFF, 0xFB, 0x0E, 0x6D, 0x35, 0xF7, 0x5C, 0x76, 0x12, 0xCE, 0x25, 0x79, 0x29, 0x39, 0x62, 0x08, 0x24, 0xA5, 0x85, 0x7B, 0x56, 0x01, 0x23, 0x68, 0xCF, 0x0A, 0xE2, 0x5A, 0xED, 0x3D, 0x59, 0xB0, 0xA9, 0xB0, 0x2C, 0xF2, 0xB8, 0xEF, 0x32, 0xA9, 0x40, 0x80, 0x71, 0xAF, 0x1E, 0xDE, 0x8F, 0x58, 0x88, 0xB8, 0x3A, 0xD0, 0xFC, 0xC4, 0x1E, 0xB5, 0xA0, 0xBB, 0x3B, 0x0F, 0x01, 0x7E, 0x1F, 0x9F, 0xD9, 0xAA, 0xB8, 0x3D, 0x9D, 0x74, 0x1E, 0x25, 0xDB, 0x37, 0x56, 0x8F, 0x16, 0xBA, 0x49, 0x2B, 0xAC, 0xD0, 0xBD, 0x95, 0x20, 0xBE, 0x7A, 0x28, 0xD0, 0x51, 0x64, 0x63, 0x1C, 0x7F, 0x66, 0x10, 0xBB, 0xC4, 0x56, 0x1A, 0x04, 0x6E, 0x0A, 0xEC, 0x9C, 0xD6, 0xE8, 0x9A, 0x7A, 0xCF, 0x8C, 0xDB, 0xB1, 0xEF, 0x71, 0xDE, 0x31, 0xFF, 0x54, 0x3E, 0x5E, 0x07, 0x69, 0x96, 0xB0, 0xCF, 0xDD, 0x9E, 0x47, 0xC7, 0x96, 0x8F, 0xE4, 0x2B, 0x59, 0xC6, 0xEE, 0xB9, 0x86, 0x9A, 0x64, 0x84, 0x72, 0xE2, 0x5B, 0xA2, 0x96, 0x58, 0x99, 0x50, 0x03, 0xF5, 0x38, 0x4D, 0x02, 0x7D, 0xE7, 0x7D, 0x75, 0xA7, 0xB8, 0x67, 0x87, 0x84, 0x3F, 0x1D, 0x11, 0xE5, 0xFC, 0x1E, 0xD3, 0x83, 0x16, 0xA5, 0x29, 0xF6, 0xC7, 0x15, 0x61, 0x29, 0x1A, 0x43, 0x4F, 0x9B, 0xAF, 0xC5, 0x87, 0x34, 0x6C, 0x0F, 0x3B, 0xA8, 0x1D, 0x45, 0x58, 0x25, 0xDC, 0xA8, 0xA3, 0x3B, 0xD1, 0x79, 0x1B, 0x48, 0xF2, 0xE9, 0x93, 0x1F, 0xFC, 0xDB, 0x2A, 0x90, 0xA9, 0x8A, 0x3D, 0x39, 0x18, 0xA3, 0x8E, 0x58, 0x6C, 0xE0, 0x12, 0xBB, 0x25, 0xCD, 0x71, 0x22, 0xA2, 0x64, 0xC6, 0xE7, 0xFB, 0xAD, 0x94, 0x77, 0x04, 0x9A, 0x39, 0xCF, 0x7C}; static unsigned char CSStable1[] = { 0x8C, 0x47, 0xB0, 0xE1, 0xEB, 0xFC, 0xEB, 0x56, 0x10, 0xE5, 0x2C, 0x1A, 0x5D, 0xEF, 0xBE, 0x4F, 0x08, 0x75, 0x97, 0x4B, 0x0E, 0x25, 0x8E, 0x6E, 0x39, 0x5A, 0x87, 0x53, 0xC4, 0x1F, 0xF4, 0x5C, 0x4E, 0xE6, 0x99, 0x30, 0xE0, 0x42, 0x88, 0xAB, 0xE5, 0x85, 0xBC, 0x8F, 0xD8, 0x3C, 0x54, 0xC9, 0x53, 0x47, 0x18, 0xD6, 0x06, 0x5B, 0x41, 0x2C, 0x67, 0x1E, 0x41, 0x74, 0x33, 0xE2, 0xB4, 0xE0, 0x23, 0x29, 0x42, 0xEA, 0x55, 0x0F, 0x25, 0xB4, 0x24, 0x2C, 0x99, 0x13, 0xEB, 0x0A, 0x0B, 0xC9, 0xF9, 0x63, 0x67, 0x43, 0x2D, 0xC7, 0x7D, 0x07, 0x60, 0x89, 0xD1, 0xCC, 0xE7, 0x94, 0x77, 0x74, 0x9B, 0x7E, 0xD7, 0xE6, 0xFF, 0xBB, 0x68, 0x14, 0x1E, 0xA3, 0x25, 0xDE, 0x3A, 0xA3, 0x54, 0x7B, 0x87, 0x9D, 0x50, 0xCA, 0x27, 0xC3, 0xA4, 0x50, 0x91, 0x27, 0xD4, 0xB0, 0x82, 0x41, 0x97, 0x79, 0x94, 0x82, 0xAC, 0xC7, 0x8E, 0xA5, 0x4E, 0xAA, 0x78, 0x9E, 0xE0, 0x42, 0xBA, 0x28, 0xEA, 0xB7, 0x74, 0xAD, 0x35, 0xDA, 0x92, 0x60, 0x7E, 0xD2, 0x0E, 0xB9, 0x24, 0x5E, 0x39, 0x4F, 0x5E, 0x63, 0x09, 0xB5, 0xFA, 0xBF, 0xF1, 0x22, 0x55, 0x1C, 0xE2, 0x25, 0xDB, 0xC5, 0xD8, 0x50, 0x03, 0x98, 0xC4, 0xAC, 0x2E, 0x11, 0xB4, 0x38, 0x4D, 0xD0, 0xB9, 0xFC, 0x2D, 0x3C, 0x08, 0x04, 0x5A, 0xEF, 0xCE, 0x32, 0xFB, 0x4C, 0x92, 0x1E, 0x4B, 0xFB, 0x1A, 0xD0, 0xE2, 0x3E, 0xDA, 0x6E, 0x7C, 0x4D, 0x56, 0xC3, 0x3F, 0x42, 0xB1, 0x3A, 0x23, 0x4D, 0x6E, 0x84, 0x56, 0x68, 0xF4, 0x0E, 0x03, 0x64, 0xD0, 0xA9, 0x92, 0x2F, 0x8B, 0xBC, 0x39, 0x9C, 0xAC, 0x09, 0x5E, 0xEE, 0xE5, 0x97, 0xBF, 0xA5, 0xCE, 0xFA, 0x28, 0x2C, 0x6D, 0x4F, 0xEF, 0x77, 0xAA, 0x1B, 0x79, 0x8E, 0x97, 0xB4, 0xC3, 0xF4}; static unsigned char CSStable2[] = { 0xB7, 0x75, 0x81, 0xD5, 0xDC, 0xCA, 0xDE, 0x66, 0x23, 0xDF, 0x15, 0x26, 0x62, 0xD1, 0x83, 0x77, 0xE3, 0x97, 0x76, 0xAF, 0xE9, 0xC3, 0x6B, 0x8E, 0xDA, 0xB0, 0x6E, 0xBF, 0x2B, 0xF1, 0x19, 0xB4, 0x95, 0x34, 0x48, 0xE4, 0x37, 0x94, 0x5D, 0x7B, 0x36, 0x5F, 0x65, 0x53, 0x07, 0xE2, 0x89, 0x11, 0x98, 0x85, 0xD9, 0x12, 0xC1, 0x9D, 0x84, 0xEC, 0xA4, 0xD4, 0x88, 0xB8, 0xFC, 0x2C, 0x79, 0x28, 0xD8, 0xDB, 0xB3, 0x1E, 0xA2, 0xF9, 0xD0, 0x44, 0xD7, 0xD6, 0x60, 0xEF, 0x14, 0xF4, 0xF6, 0x31, 0xD2, 0x41, 0x46, 0x67, 0x0A, 0xE1, 0x58, 0x27, 0x43, 0xA3, 0xF8, 0xE0, 0xC8, 0xBA, 0x5A, 0x5C, 0x80, 0x6C, 0xC6, 0xF2, 0xE8, 0xAD, 0x7D, 0x04, 0x0D, 0xB9, 0x3C, 0xC2, 0x25, 0xBD, 0x49, 0x63, 0x8C, 0x9F, 0x51, 0xCE, 0x20, 0xC5, 0xA1, 0x50, 0x92, 0x2D, 0xDD, 0xBC, 0x8D, 0x4F, 0x9A, 0x71, 0x2F, 0x30, 0x1D, 0x73, 0x39, 0x13, 0xFB, 0x1A, 0xCB, 0x24, 0x59, 0xFE, 0x05, 0x96, 0x57, 0x0F, 0x1F, 0xCF, 0x54, 0xBE, 0xF5, 0x06, 0x1B, 0xB2, 0x6D, 0xD3, 0x4D, 0x32, 0x56, 0x21, 0x33, 0x0B, 0x52, 0xE7, 0xAB, 0xEB, 0xA6, 0x74, 0x00, 0x4C, 0xB1, 0x7F, 0x82, 0x99, 0x87, 0x0E, 0x5E, 0xC0, 0x8F, 0xEE, 0x6F, 0x55, 0xF3, 0x7E, 0x08, 0x90, 0xFA, 0xB6, 0x64, 0x70, 0x47, 0x4A, 0x17, 0xA7, 0xB5, 0x40, 0x8A, 0x38, 0xE5, 0x68, 0x3E, 0x8B, 0x69, 0xAA, 0x9B, 0x42, 0xA5, 0x10, 0x01, 0x35, 0xFD, 0x61, 0x9E, 0xE6, 0x16, 0x9C, 0x86, 0xED, 0xCD, 0x2E, 0xFF, 0xC4, 0x5B, 0xA0, 0xAE, 0xCC, 0x4B, 0x3B, 0x03, 0xBB, 0x1C, 0x2A, 0xAC, 0x0C, 0x3F, 0x93, 0xC7, 0x72, 0x7A, 0x09, 0x22, 0x3D, 0x45, 0x78, 0xA9, 0xA8, 0xEA, 0xC9, 0x6A, 0xF7, 0x29, 0x91, 0xF0, 0x02, 0x18, 0x3A, 0x4E, 0x7C}; static unsigned char CSStable3[] = { 0x73, 0x51, 0x95, 0xE1, 0x12, 0xE4, 0xC0, 0x58, 0xEE, 0xF2, 0x08, 0x1B, 0xA9, 0xFA, 0x98, 0x4C, 0xA7, 0x33, 0xE2, 0x1B, 0xA7, 0x6D, 0xF5, 0x30, 0x97, 0x1D, 0xF3, 0x02, 0x60, 0x5A, 0x82, 0x0F, 0x91, 0xD0, 0x9C, 0x10, 0x39, 0x7A, 0x83, 0x85, 0x3B, 0xB2, 0xB8, 0xAE, 0x0C, 0x09, 0x52, 0xEA, 0x1C, 0xE1, 0x8D, 0x66, 0x4F, 0xF3, 0xDA, 0x92, 0x29, 0xB9, 0xD5, 0xC5, 0x77, 0x47, 0x22, 0x53, 0x14, 0xF7, 0xAF, 0x22, 0x64, 0xDF, 0xC6, 0x72, 0x12, 0xF3, 0x75, 0xDA, 0xD7, 0xD7, 0xE5, 0x02, 0x9E, 0xED, 0xDA, 0xDB, 0x4C, 0x47, 0xCE, 0x91, 0x06, 0x06, 0x6D, 0x55, 0x8B, 0x19, 0xC9, 0xEF, 0x8C, 0x80, 0x1A, 0x0E, 0xEE, 0x4B, 0xAB, 0xF2, 0x08, 0x5C, 0xE9, 0x37, 0x26, 0x5E, 0x9A, 0x90, 0x00, 0xF3, 0x0D, 0xB2, 0xA6, 0xA3, 0xF7, 0x26, 0x17, 0x48, 0x88, 0xC9, 0x0E, 0x2C, 0xC9, 0x02, 0xE7, 0x18, 0x05, 0x4B, 0xF3, 0x39, 0xE1, 0x20, 0x02, 0x0D, 0x40, 0xC7, 0xCA, 0xB9, 0x48, 0x30, 0x57, 0x67, 0xCC, 0x06, 0xBF, 0xAC, 0x81, 0x08, 0x24, 0x7A, 0xD4, 0x8B, 0x19, 0x8E, 0xAC, 0xB4, 0x5A, 0x0F, 0x73, 0x13, 0xAC, 0x9E, 0xDA, 0xB6, 0xB8, 0x96, 0x5B, 0x60, 0x88, 0xE1, 0x81, 0x3F, 0x07, 0x86, 0x37, 0x2D, 0x79, 0x14, 0x52, 0xEA, 0x73, 0xDF, 0x3D, 0x09, 0xC8, 0x25, 0x48, 0xD8, 0x75, 0x60, 0x9A, 0x08, 0x27, 0x4A, 0x2C, 0xB9, 0xA8, 0x8B, 0x8A, 0x73, 0x62, 0x37, 0x16, 0x02, 0xBD, 0xC1, 0x0E, 0x56, 0x54, 0x3E, 0x14, 0x5F, 0x8C, 0x8F, 0x6E, 0x75, 0x1C, 0x07, 0x39, 0x7B, 0x4B, 0xDB, 0xD3, 0x4B, 0x1E, 0xC8, 0x7E, 0xFE, 0x3E, 0x72, 0x16, 0x83, 0x7D, 0xEE, 0xF5, 0xCA, 0xC5, 0x18, 0xF9, 0xD8, 0x68, 0xAB, 0x38, 0x85, 0xA8, 0xF0, 0xA1, 0x73, 0x9F, 0x5D, 0x19, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x72, 0x39, 0x25, 0x67, 0x26, 0x6D, 0x71, 0x36, 0x77, 0x3C, 0x20, 0x62, 0x23, 0x68, 0x74, 0xC3, 0x82, 0xC9, 0x15, 0x57, 0x16, 0x5D, 0x81}; ================================================ FILE: common/DSUtilLite/DeCSS/CSSauth.h ================================================ #pragma once extern void CSSkey1(int varient, byte const *challenge, byte *key); extern void CSSkey2(int varient, byte const *challenge, byte *key); extern void CSSbuskey(int varient, byte const *challenge, byte *key); ================================================ FILE: common/DSUtilLite/DeCSS/CSSscramble.cpp ================================================ #include "stdafx.h" #ifndef countof #define countof(array) (sizeof(array) / sizeof(array[0])) #endif unsigned int CSStab0[11] = {5, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4}; unsigned char CSStab1[256] = { 0x33, 0x73, 0x3b, 0x26, 0x63, 0x23, 0x6b, 0x76, 0x3e, 0x7e, 0x36, 0x2b, 0x6e, 0x2e, 0x66, 0x7b, 0xd3, 0x93, 0xdb, 0x06, 0x43, 0x03, 0x4b, 0x96, 0xde, 0x9e, 0xd6, 0x0b, 0x4e, 0x0e, 0x46, 0x9b, 0x57, 0x17, 0x5f, 0x82, 0xc7, 0x87, 0xcf, 0x12, 0x5a, 0x1a, 0x52, 0x8f, 0xca, 0x8a, 0xc2, 0x1f, 0xd9, 0x99, 0xd1, 0x00, 0x49, 0x09, 0x41, 0x90, 0xd8, 0x98, 0xd0, 0x01, 0x48, 0x08, 0x40, 0x91, 0x3d, 0x7d, 0x35, 0x24, 0x6d, 0x2d, 0x65, 0x74, 0x3c, 0x7c, 0x34, 0x25, 0x6c, 0x2c, 0x64, 0x75, 0xdd, 0x9d, 0xd5, 0x04, 0x4d, 0x0d, 0x45, 0x94, 0xdc, 0x9c, 0xd4, 0x05, 0x4c, 0x0c, 0x44, 0x95, 0x59, 0x19, 0x51, 0x80, 0xc9, 0x89, 0xc1, 0x10, 0x58, 0x18, 0x50, 0x81, 0xc8, 0x88, 0xc0, 0x11, 0xd7, 0x97, 0xdf, 0x02, 0x47, 0x07, 0x4f, 0x92, 0xda, 0x9a, 0xd2, 0x0f, 0x4a, 0x0a, 0x42, 0x9f, 0x53, 0x13, 0x5b, 0x86, 0xc3, 0x83, 0xcb, 0x16, 0x5e, 0x1e, 0x56, 0x8b, 0xce, 0x8e, 0xc6, 0x1b, 0xb3, 0xf3, 0xbb, 0xa6, 0xe3, 0xa3, 0xeb, 0xf6, 0xbe, 0xfe, 0xb6, 0xab, 0xee, 0xae, 0xe6, 0xfb, 0x37, 0x77, 0x3f, 0x22, 0x67, 0x27, 0x6f, 0x72, 0x3a, 0x7a, 0x32, 0x2f, 0x6a, 0x2a, 0x62, 0x7f, 0xb9, 0xf9, 0xb1, 0xa0, 0xe9, 0xa9, 0xe1, 0xf0, 0xb8, 0xf8, 0xb0, 0xa1, 0xe8, 0xa8, 0xe0, 0xf1, 0x5d, 0x1d, 0x55, 0x84, 0xcd, 0x8d, 0xc5, 0x14, 0x5c, 0x1c, 0x54, 0x85, 0xcc, 0x8c, 0xc4, 0x15, 0xbd, 0xfd, 0xb5, 0xa4, 0xed, 0xad, 0xe5, 0xf4, 0xbc, 0xfc, 0xb4, 0xa5, 0xec, 0xac, 0xe4, 0xf5, 0x39, 0x79, 0x31, 0x20, 0x69, 0x29, 0x61, 0x70, 0x38, 0x78, 0x30, 0x21, 0x68, 0x28, 0x60, 0x71, 0xb7, 0xf7, 0xbf, 0xa2, 0xe7, 0xa7, 0xef, 0xf2, 0xba, 0xfa, 0xb2, 0xaf, 0xea, 0xaa, 0xe2, 0xff}; unsigned char CSStab2[256] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c, 0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23, 0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a, 0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x49, 0x48, 0x4b, 0x4a, 0x4d, 0x4c, 0x4f, 0x4e, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x5b, 0x5a, 0x59, 0x58, 0x5f, 0x5e, 0x5d, 0x5c, 0x52, 0x53, 0x50, 0x51, 0x56, 0x57, 0x54, 0x55, 0x6d, 0x6c, 0x6f, 0x6e, 0x69, 0x68, 0x6b, 0x6a, 0x64, 0x65, 0x66, 0x67, 0x60, 0x61, 0x62, 0x63, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x79, 0x78, 0x76, 0x77, 0x74, 0x75, 0x72, 0x73, 0x70, 0x71, 0x92, 0x93, 0x90, 0x91, 0x96, 0x97, 0x94, 0x95, 0x9b, 0x9a, 0x99, 0x98, 0x9f, 0x9e, 0x9d, 0x9c, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x89, 0x88, 0x8b, 0x8a, 0x8d, 0x8c, 0x8f, 0x8e, 0xb6, 0xb7, 0xb4, 0xb5, 0xb2, 0xb3, 0xb0, 0xb1, 0xbf, 0xbe, 0xbd, 0xbc, 0xbb, 0xba, 0xb9, 0xb8, 0xa4, 0xa5, 0xa6, 0xa7, 0xa0, 0xa1, 0xa2, 0xa3, 0xad, 0xac, 0xaf, 0xae, 0xa9, 0xa8, 0xab, 0xaa, 0xdb, 0xda, 0xd9, 0xd8, 0xdf, 0xde, 0xdd, 0xdc, 0xd2, 0xd3, 0xd0, 0xd1, 0xd6, 0xd7, 0xd4, 0xd5, 0xc9, 0xc8, 0xcb, 0xca, 0xcd, 0xcc, 0xcf, 0xce, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf6, 0xf7, 0xf4, 0xf5, 0xf2, 0xf3, 0xf0, 0xf1, 0xed, 0xec, 0xef, 0xee, 0xe9, 0xe8, 0xeb, 0xea, 0xe4, 0xe5, 0xe6, 0xe7, 0xe0, 0xe1, 0xe2, 0xe3}; unsigned char CSStab3[512] = { 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff, 0x00, 0x24, 0x49, 0x6d, 0x92, 0xb6, 0xdb, 0xff}; unsigned char CSStab4[256] = { 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff}; unsigned char CSStab5[256] = { 0xff, 0x7f, 0xbf, 0x3f, 0xdf, 0x5f, 0x9f, 0x1f, 0xef, 0x6f, 0xaf, 0x2f, 0xcf, 0x4f, 0x8f, 0x0f, 0xf7, 0x77, 0xb7, 0x37, 0xd7, 0x57, 0x97, 0x17, 0xe7, 0x67, 0xa7, 0x27, 0xc7, 0x47, 0x87, 0x07, 0xfb, 0x7b, 0xbb, 0x3b, 0xdb, 0x5b, 0x9b, 0x1b, 0xeb, 0x6b, 0xab, 0x2b, 0xcb, 0x4b, 0x8b, 0x0b, 0xf3, 0x73, 0xb3, 0x33, 0xd3, 0x53, 0x93, 0x13, 0xe3, 0x63, 0xa3, 0x23, 0xc3, 0x43, 0x83, 0x03, 0xfd, 0x7d, 0xbd, 0x3d, 0xdd, 0x5d, 0x9d, 0x1d, 0xed, 0x6d, 0xad, 0x2d, 0xcd, 0x4d, 0x8d, 0x0d, 0xf5, 0x75, 0xb5, 0x35, 0xd5, 0x55, 0x95, 0x15, 0xe5, 0x65, 0xa5, 0x25, 0xc5, 0x45, 0x85, 0x05, 0xf9, 0x79, 0xb9, 0x39, 0xd9, 0x59, 0x99, 0x19, 0xe9, 0x69, 0xa9, 0x29, 0xc9, 0x49, 0x89, 0x09, 0xf1, 0x71, 0xb1, 0x31, 0xd1, 0x51, 0x91, 0x11, 0xe1, 0x61, 0xa1, 0x21, 0xc1, 0x41, 0x81, 0x01, 0xfe, 0x7e, 0xbe, 0x3e, 0xde, 0x5e, 0x9e, 0x1e, 0xee, 0x6e, 0xae, 0x2e, 0xce, 0x4e, 0x8e, 0x0e, 0xf6, 0x76, 0xb6, 0x36, 0xd6, 0x56, 0x96, 0x16, 0xe6, 0x66, 0xa6, 0x26, 0xc6, 0x46, 0x86, 0x06, 0xfa, 0x7a, 0xba, 0x3a, 0xda, 0x5a, 0x9a, 0x1a, 0xea, 0x6a, 0xaa, 0x2a, 0xca, 0x4a, 0x8a, 0x0a, 0xf2, 0x72, 0xb2, 0x32, 0xd2, 0x52, 0x92, 0x12, 0xe2, 0x62, 0xa2, 0x22, 0xc2, 0x42, 0x82, 0x02, 0xfc, 0x7c, 0xbc, 0x3c, 0xdc, 0x5c, 0x9c, 0x1c, 0xec, 0x6c, 0xac, 0x2c, 0xcc, 0x4c, 0x8c, 0x0c, 0xf4, 0x74, 0xb4, 0x34, 0xd4, 0x54, 0x94, 0x14, 0xe4, 0x64, 0xa4, 0x24, 0xc4, 0x44, 0x84, 0x04, 0xf8, 0x78, 0xb8, 0x38, 0xd8, 0x58, 0x98, 0x18, 0xe8, 0x68, 0xa8, 0x28, 0xc8, 0x48, 0x88, 0x08, 0xf0, 0x70, 0xb0, 0x30, 0xd0, 0x50, 0x90, 0x10, 0xe0, 0x60, 0xa0, 0x20, 0xc0, 0x40, 0x80, 0x00}; void CSSdescramble(unsigned char *sec, unsigned char *tkey) { unsigned int t1, t2, t3, t4, t5, t6; unsigned char *end = sec + 0x800; t1 = tkey[0] ^ sec[0x54] | 0x100; t2 = tkey[1] ^ sec[0x55]; t3 = (*((unsigned int *)(tkey + 2))) ^ (*((unsigned int *)(sec + 0x56))); t4 = t3 & 7; t3 = t3 * 2 + 8 - t4; sec += 0x80; t5 = 0; while (sec != end) { t4 = CSStab2[t2] ^ CSStab3[t1]; t2 = t1 >> 1; t1 = ((t1 & 1) << 8) ^ t4; t4 = CSStab5[t4]; t6 = (((((((t3 >> 3) ^ t3) >> 1) ^ t3) >> 8) ^ t3) >> 5) & 0xff; t3 = (t3 << 8) | t6; t6 = CSStab4[t6]; t5 += t6 + t4; *sec++ = CSStab1[*sec] ^ (t5 & 0xff); t5 >>= 8; } } void CSSdisckey(unsigned char *dkey, unsigned char *pkey) { unsigned int t1, t2, t3, t4, t5, t6; unsigned char k[5]; int i; t1 = pkey[0] | 0x100; t2 = pkey[1]; t3 = *((unsigned int *)(pkey + 2)); t4 = t3 & 7; t3 = t3 * 2 + 8 - t4; t5 = 0; for (i = 0; i < 5; i++) { t4 = CSStab2[t2] ^ CSStab3[t1]; t2 = t1 >> 1; t1 = ((t1 & 1) << 8) ^ t4; t4 = CSStab4[t4]; t6 = (((((((t3 >> 3) ^ t3) >> 1) ^ t3) >> 8) ^ t3) >> 5) & 0xff; t3 = (t3 << 8) | t6; t6 = CSStab4[t6]; t5 += t6 + t4; k[i] = t5 & 0xff; t5 >>= 8; } for (i = 9; i >= 0; i--) { dkey[CSStab0[i + 1]] = k[CSStab0[i + 1]] ^ CSStab1[dkey[CSStab0[i + 1]]] ^ dkey[CSStab0[i]]; } } void CSStitlekey(unsigned char *tkey, unsigned char *dkey) { unsigned int t1, t2, t3, t4, t5, t6; unsigned char k[5]; int i; t1 = dkey[0] | 0x100; t2 = dkey[1]; t3 = *((unsigned int *)(dkey + 2)); t4 = t3 & 7; t3 = t3 * 2 + 8 - t4; t5 = 0; for (i = 0; i < 5; i++) { t4 = CSStab2[t2] ^ CSStab3[t1]; t2 = t1 >> 1; t1 = ((t1 & 1) << 8) ^ t4; t4 = CSStab4[t4]; t6 = (((((((t3 >> 3) ^ t3) >> 1) ^ t3) >> 8) ^ t3) >> 5) & 0xff; t3 = (t3 << 8) | t6; t6 = CSStab5[t6]; t5 += t6 + t4; k[i] = t5 & 0xff; t5 >>= 8; } for (i = 9; i >= 0; i--) { tkey[CSStab0[i + 1]] = k[CSStab0[i + 1]] ^ CSStab1[tkey[CSStab0[i + 1]]] ^ tkey[CSStab0[i]]; } } unsigned char g_PlayerKeys[][6] = { // from mplayer: {0x01, 0xaf, 0xe3, 0x12, 0x80}, {0x12, 0x11, 0xca, 0x04, 0x3b}, {0x14, 0x0c, 0x9e, 0xd0, 0x09}, {0x14, 0x71, 0x35, 0xba, 0xe2}, {0x1a, 0xa4, 0x33, 0x21, 0xa6}, {0x26, 0xec, 0xc4, 0xa7, 0x4e}, {0x2c, 0xb2, 0xc1, 0x09, 0xee}, {0x2f, 0x25, 0x9e, 0x96, 0xdd}, {0x33, 0x2f, 0x49, 0x6c, 0xe0}, {0x35, 0x5b, 0xc1, 0x31, 0x0f}, {0x36, 0x67, 0xb2, 0xe3, 0x85}, {0x39, 0x3d, 0xf1, 0xf1, 0xbd}, {0x3b, 0x31, 0x34, 0x0d, 0x91}, {0x45, 0xed, 0x28, 0xeb, 0xd3}, {0x48, 0xb7, 0x6c, 0xce, 0x69}, {0x4b, 0x65, 0x0d, 0xc1, 0xee}, {0x4c, 0xbb, 0xf5, 0x5b, 0x23}, {0x51, 0x67, 0x67, 0xc5, 0xe0}, {0x53, 0x94, 0xe1, 0x75, 0xbf}, {0x57, 0x2c, 0x8b, 0x31, 0xae}, {0x63, 0xdb, 0x4c, 0x5b, 0x4a}, {0x7b, 0x1e, 0x5e, 0x2b, 0x57}, {0x85, 0xf3, 0x85, 0xa0, 0xe0}, {0xab, 0x1e, 0xe7, 0x7b, 0x72}, {0xab, 0x36, 0xe3, 0xeb, 0x76}, {0xb1, 0xb8, 0xf9, 0x38, 0x03}, {0xb8, 0x5d, 0xd8, 0x53, 0xbd}, {0xbf, 0x92, 0xc3, 0xb0, 0xe2}, {0xcf, 0x1a, 0xb2, 0xf8, 0x0a}, {0xec, 0xa0, 0xcf, 0xb3, 0xff}, {0xfc, 0x95, 0xa9, 0x87, 0x35} // TODO: find more player keys }; int g_nPlayerKeys = countof(g_PlayerKeys); ================================================ FILE: common/DSUtilLite/DeCSS/CSSscramble.h ================================================ #pragma once extern void CSSdisckey(unsigned char *dkey, unsigned char *pkey); extern void CSStitlekey(unsigned char *tkey, unsigned char *dkey); extern void CSSdescramble(unsigned char *sector, unsigned char *tkey); extern unsigned char g_PlayerKeys[][6]; extern int g_nPlayerKeys; ================================================ FILE: common/DSUtilLite/DeCSS/DeCSSInputPin.cpp ================================================ /* * Copyright (C) 2003-2006 Gabest * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include #include #include "DeCSSInputPin.h" #include "CSSauth.h" #include "CSSscramble.h" #include "../DShowUtil.h" // // CDeCSSPinHelper // CDeCSSPinHelper::CDeCSSPinHelper() { m_varient = -1; memset(m_Challenge, 0, sizeof(m_Challenge)); memset(m_KeyCheck, 0, sizeof(m_KeyCheck)); memset(m_DiscKey, 0, sizeof(m_DiscKey)); memset(m_TitleKey, 0, sizeof(m_TitleKey)); } void CDeCSSPinHelper::Decrypt(IMediaSample *pSample) { long len = pSample->GetActualDataLength(); BYTE *p = nullptr; if (SUCCEEDED(pSample->GetPointer(&p)) && len > 0) { if (m_mt.majortype == MEDIATYPE_DVD_ENCRYPTED_PACK && len == 2048 && (p[0x14] & 0x30)) { CSSdescramble(p, m_TitleKey); p[0x14] &= ~0x30; IMediaSample2 *pMS2 = nullptr; if (SUCCEEDED(pSample->QueryInterface(&pMS2)) && pMS2) { AM_SAMPLE2_PROPERTIES props; memset(&props, 0, sizeof(props)); if (SUCCEEDED(pMS2->GetProperties(sizeof(props), (BYTE *)&props)) && (props.dwTypeSpecificFlags & AM_UseNewCSSKey)) { props.dwTypeSpecificFlags &= ~AM_UseNewCSSKey; pMS2->SetProperties(sizeof(props), (BYTE *)&props); } pMS2->Release(); } } } } void CDeCSSPinHelper::StripPacket(BYTE *&p, long &len) { GUID majortype = m_mt.majortype; GUID subtype = m_mt.subtype; if (majortype == MEDIATYPE_MPEG2_PACK || majortype == MEDIATYPE_DVD_ENCRYPTED_PACK) { if (len > 0 && *(DWORD *)p == 0xba010000) { // MEDIATYPE_*_PACK len -= 14; p += 14; if (int stuffing = (p[-1] & 7)) { len -= stuffing; p += stuffing; } majortype = MEDIATYPE_MPEG2_PES; } } if (majortype == MEDIATYPE_MPEG2_PES) { if (len > 0 && *(DWORD *)p == 0xbb010000) { len -= 4; p += 4; int hdrlen = ((p[0] << 8) | p[1]) + 2; len -= hdrlen; p += hdrlen; } if (len > 4 && ((*(DWORD *)p & 0xf0ffffff) == 0xe0010000 || (*(DWORD *)p & 0xe0ffffff) == 0xc0010000 || (*(DWORD *)p & 0xbdffffff) == 0xbd010000)) { // PES bool ps1 = (*(DWORD *)p & 0xbdffffff) == 0xbd010000; len -= 4; p += 4; size_t expected = ((p[0] << 8) | p[1]); len -= 2; p += 2; BYTE *p0 = p; for (int i = 0; i < 16 && *p == 0xff; i++, len--, p++) { ; } if ((*p & 0xc0) == 0x80) { // mpeg2 len -= 2; p += 2; len -= *p + 1; p += *p + 1; } else { // mpeg1 if ((*p & 0xc0) == 0x40) { len -= 2; p += 2; } if ((*p & 0x30) == 0x30 || (*p & 0x30) == 0x20) { bool pts = !!(*p & 0x20), dts = !!(*p & 0x10); if (pts) { len -= 5; } p += 5; if (dts) { ASSERT((*p & 0xf0) == 0x10); len -= 5; p += 5; } } else { len--; p++; } } if (ps1) { len--; p++; if (subtype == MEDIASUBTYPE_DVD_LPCM_AUDIO) { len -= 6; p += 6; } else if (subtype == MEDIASUBTYPE_DOLBY_AC3 || subtype == FOURCCMap(0x2000) || subtype == MEDIASUBTYPE_DTS || subtype == FOURCCMap(0x2001)) { len -= 3; p += 3; } } if (expected > 0) { expected -= (p - p0); len = min((long)expected, len); } } if (len < 0) { ASSERT(0); len = 0; } } } // IKsPropertySet STDMETHODIMP CDeCSSPinHelper::Set(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength) { if (PropSet != AM_KSPROPSETID_CopyProt) { return E_NOTIMPL; } switch (Id) { case AM_PROPERTY_COPY_MACROVISION: break; case AM_PROPERTY_DVDCOPY_CHLG_KEY: { // 3. auth: receive drive nonce word, also store and encrypt the buskey made up // of the two nonce words AM_DVDCOPY_CHLGKEY *pChlgKey = (AM_DVDCOPY_CHLGKEY *)pPropertyData; for (int i = 0; i < 10; i++) { m_Challenge[i] = pChlgKey->ChlgKey[9 - i]; } CSSkey2(m_varient, m_Challenge, &m_Key[5]); CSSbuskey(m_varient, m_Key, m_KeyCheck); } break; case AM_PROPERTY_DVDCOPY_DISC_KEY: { // 5. receive the disckey AM_DVDCOPY_DISCKEY *pDiscKey = (AM_DVDCOPY_DISCKEY *)pPropertyData; // pDiscKey->DiscKey holds the disckey encrypted with itself and the // 408 disckeys encrypted with the playerkeys bool fSuccess = false; for (int j = 0; j < g_nPlayerKeys; j++) { for (int k = 1; k < 409; k++) { BYTE DiscKey[6]; for (int i = 0; i < 5; i++) { DiscKey[i] = pDiscKey->DiscKey[k * 5 + i] ^ m_KeyCheck[4 - i]; } DiscKey[5] = 0; CSSdisckey(DiscKey, g_PlayerKeys[j]); BYTE Hash[6]; for (int i = 0; i < 5; i++) { Hash[i] = pDiscKey->DiscKey[i] ^ m_KeyCheck[4 - i]; } Hash[5] = 0; CSSdisckey(Hash, DiscKey); if (!memcmp(Hash, DiscKey, 6)) { memcpy(m_DiscKey, DiscKey, 6); j = g_nPlayerKeys; fSuccess = true; break; } } } if (!fSuccess) { return E_FAIL; } } break; case AM_PROPERTY_DVDCOPY_DVD_KEY1: { // 2. auth: receive our drive-encrypted nonce word and decrypt it for // verification AM_DVDCOPY_BUSKEY *pKey1 = (AM_DVDCOPY_BUSKEY *)pPropertyData; for (int i = 0; i < 5; i++) { m_Key[i] = pKey1->BusKey[4 - i]; } m_varient = -1; for (int i = 31; i >= 0; i--) { CSSkey1(i, m_Challenge, m_KeyCheck); if (memcmp(m_KeyCheck, &m_Key[0], 5) == 0) { m_varient = i; } } } break; case AM_PROPERTY_DVDCOPY_REGION: break; case AM_PROPERTY_DVDCOPY_SET_COPY_STATE: break; case AM_PROPERTY_DVDCOPY_TITLE_KEY: { // 6. receive the title key and decrypt it with the disc key AM_DVDCOPY_TITLEKEY *pTitleKey = (AM_DVDCOPY_TITLEKEY *)pPropertyData; for (int i = 0; i < 5; i++) { m_TitleKey[i] = pTitleKey->TitleKey[i] ^ m_KeyCheck[4 - i]; } m_TitleKey[5] = 0; CSStitlekey(m_TitleKey, m_DiscKey); } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CDeCSSPinHelper::Get(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength, ULONG *pBytesReturned) { if (PropSet != AM_KSPROPSETID_CopyProt) { return E_NOTIMPL; } switch (Id) { case AM_PROPERTY_DVDCOPY_CHLG_KEY: { // 1. auth: send our nonce word AM_DVDCOPY_CHLGKEY *pChlgKey = (AM_DVDCOPY_CHLGKEY *)pPropertyData; for (int i = 0; i < 10; i++) { pChlgKey->ChlgKey[i] = 9 - (m_Challenge[i] = i); } *pBytesReturned = sizeof(AM_DVDCOPY_CHLGKEY); } break; case AM_PROPERTY_DVDCOPY_DEC_KEY2: { // 4. auth: send back the encrypted drive nonce word to finish the // authentication AM_DVDCOPY_BUSKEY *pKey2 = (AM_DVDCOPY_BUSKEY *)pPropertyData; for (int i = 0; i < 5; i++) { pKey2->BusKey[4 - i] = m_Key[5 + i]; } *pBytesReturned = sizeof(AM_DVDCOPY_BUSKEY); } break; case AM_PROPERTY_DVDCOPY_REGION: { DVD_REGION *pRegion = (DVD_REGION *)pPropertyData; pRegion->RegionData = 0; pRegion->SystemRegion = 0; *pBytesReturned = sizeof(DVD_REGION); } break; case AM_PROPERTY_DVDCOPY_SET_COPY_STATE: { AM_DVDCOPY_SET_COPY_STATE *pState = (AM_DVDCOPY_SET_COPY_STATE *)pPropertyData; pState->DVDCopyState = AM_DVDCOPYSTATE_AUTHENTICATION_REQUIRED; *pBytesReturned = sizeof(AM_DVDCOPY_SET_COPY_STATE); } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CDeCSSPinHelper::QuerySupported(REFGUID PropSet, ULONG Id, ULONG *pTypeSupport) { if (PropSet != AM_KSPROPSETID_CopyProt) { return E_NOTIMPL; } switch (Id) { case AM_PROPERTY_COPY_MACROVISION: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDCOPY_CHLG_KEY: *pTypeSupport = KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDCOPY_DEC_KEY2: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_PROPERTY_DVDCOPY_DISC_KEY: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDCOPY_DVD_KEY1: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDCOPY_REGION: *pTypeSupport = KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDCOPY_SET_COPY_STATE: *pTypeSupport = KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDCOPY_TITLE_KEY: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } // // CDeCSSTransformInputPin // CDeCSSTransformInputPin::CDeCSSTransformInputPin(TCHAR *pObjectName, CTransformFilter *pFilter, HRESULT *phr, LPWSTR pName) : CTransformInputPin(pObjectName, pFilter, phr, pName) , CDeCSSPinHelper() { } STDMETHODIMP CDeCSSTransformInputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); return QI(IKsPropertySet) __super::NonDelegatingQueryInterface(riid, ppv); } STDMETHODIMP CDeCSSTransformInputPin::Receive(IMediaSample *pSample) { Decrypt(pSample); return __super::Receive(pSample); } HRESULT CDeCSSTransformInputPin::SetMediaType(const CMediaType *pmt) { SetCSSMediaType(pmt); return __super::SetMediaType(pmt); } ================================================ FILE: common/DSUtilLite/DeCSS/DeCSSInputPin.h ================================================ /* * Copyright (C) 2003-2006 Gabest * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #pragma once class CDeCSSPinHelper : public IKsPropertySet { int m_varient; BYTE m_Challenge[10], m_KeyCheck[5], m_Key[10]; BYTE m_DiscKey[6], m_TitleKey[6]; CMediaType m_mt; public: CDeCSSPinHelper(); void Decrypt(IMediaSample *pSample); void StripPacket(BYTE *&p, long &len); void SetCSSMediaType(const CMediaType *pmt) { m_mt = *pmt; } // IKsPropertySet STDMETHODIMP Set(REFGUID PropSet, ULONG Id, LPVOID InstanceData, ULONG InstanceLength, LPVOID PropertyData, ULONG DataLength); STDMETHODIMP Get(REFGUID PropSet, ULONG Id, LPVOID InstanceData, ULONG InstanceLength, LPVOID PropertyData, ULONG DataLength, ULONG *pBytesReturned); STDMETHODIMP QuerySupported(REFGUID PropSet, ULONG Id, ULONG *pTypeSupport); }; class CDeCSSTransformInputPin : public CTransformInputPin , public CDeCSSPinHelper { public: CDeCSSTransformInputPin(TCHAR *pObjectName, CTransformFilter *pFilter, HRESULT *phr, LPWSTR pName); DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // IMemInputPin STDMETHODIMP Receive(IMediaSample *pSample); HRESULT SetMediaType(const CMediaType *pmt); }; ================================================ FILE: common/DSUtilLite/FloatingAverage.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #include "DShowUtil.h" template class FloatingAverage { public: FloatingAverage(unsigned int iNumSamples = 10) { SetNumSamples(iNumSamples); } ~FloatingAverage() { free(m_Samples); } void SetNumSamples(unsigned int iNumSamples) { if (iNumSamples > m_NumSamplesAlloc) { m_Samples = (T *)realloc(m_Samples, iNumSamples * sizeof(T)); m_NumSamplesAlloc = iNumSamples; } if (iNumSamples > m_NumSamples) memset(m_Samples + m_NumSamples, 0, sizeof(T) * (iNumSamples - m_NumSamples)); m_NumSamples = iNumSamples; } void Sample(T fSample) { m_Samples[m_CurrentSample] = fSample; if (++m_CurrentSample >= m_NumSamples) { m_CurrentSample = 0; } } T Average() const { T fAverage = 0; for (unsigned int i = 0; i < m_NumSamples; ++i) { fAverage += m_Samples[i] / m_NumSamples; } return fAverage; } T Minimum() const { T min = m_Samples[0]; for (unsigned int i = 1; i < m_NumSamples; ++i) { if (m_Samples[i] < min) min = m_Samples[i]; } return min; } T AbsMinimum() const { T min = m_Samples[0]; for (unsigned int i = 1; i < m_NumSamples; ++i) { if (abs(m_Samples[i]) < abs(min)) min = m_Samples[i]; } return min; } T Maximum() const { T max = m_Samples[0]; for (unsigned int i = 1; i < m_NumSamples; ++i) { if (m_Samples[i] > max) max = m_Samples[i]; } return max; } T AbsMaximum() const { T max = m_Samples[0]; for (unsigned int i = 1; i < m_NumSamples; ++i) { if (abs(m_Samples[i]) > abs(max)) max = m_Samples[i]; } return max; } void OffsetValues(T value) const { for (unsigned int i = 0; i < m_NumSamples; ++i) { m_Samples[i] += value; } } unsigned int CurrentSample() const { return m_CurrentSample; } private: T *m_Samples = nullptr; unsigned int m_NumSamples = 0; unsigned int m_NumSamplesAlloc = 0; unsigned int m_CurrentSample = 0; }; ================================================ FILE: common/DSUtilLite/FontInstaller.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #include "stdafx.h" #include "FontInstaller.h" CFontInstaller::CFontInstaller() : pAddFontMemResourceEx(nullptr) , pRemoveFontMemResourceEx(nullptr) { if (HMODULE hGdi = GetModuleHandle(_T("gdi32.dll"))) { pAddFontMemResourceEx = (HANDLE(WINAPI *)(PVOID, DWORD, PVOID, DWORD *))GetProcAddress(hGdi, "AddFontMemResourceEx"); pRemoveFontMemResourceEx = (BOOL(WINAPI *)(HANDLE))GetProcAddress(hGdi, "RemoveFontMemResourceEx"); } } CFontInstaller::~CFontInstaller() { UninstallFonts(); } bool CFontInstaller::InstallFont(const void *pData, UINT len) { return InstallFontMemory(pData, len); } void CFontInstaller::UninstallFonts() { if (pRemoveFontMemResourceEx) { std::vector::iterator it; for (it = m_fonts.begin(); it != m_fonts.end(); ++it) { pRemoveFontMemResourceEx(*it); } m_fonts.clear(); } } bool CFontInstaller::InstallFontMemory(const void *pData, UINT len) { if (!pAddFontMemResourceEx) { return false; } DWORD nFonts = 0; HANDLE hFont = pAddFontMemResourceEx((PVOID)pData, len, nullptr, &nFonts); if (hFont && nFonts > 0) { m_fonts.push_back(hFont); } return hFont && nFonts > 0; } ================================================ FILE: common/DSUtilLite/FontInstaller.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #pragma once #include class CFontInstaller { HANDLE(WINAPI *pAddFontMemResourceEx)(PVOID, DWORD, PVOID, DWORD *) = nullptr; BOOL(WINAPI *pRemoveFontMemResourceEx)(HANDLE) = nullptr; std::vector m_fonts; bool InstallFontMemory(const void *pData, UINT len); public: CFontInstaller(); virtual ~CFontInstaller(); bool InstallFont(const void *pData, UINT len); void UninstallFonts(); }; ================================================ FILE: common/DSUtilLite/H264Nalu.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #include "stdafx.h" #include "H264Nalu.h" void CH264Nalu::SetBuffer(const BYTE *pBuffer, size_t nSize, int nNALSize) { m_pBuffer = pBuffer; m_nSize = nSize; m_nNALSize = nNALSize; m_nCurPos = 0; m_nNextRTP = 0; m_nNALStartPos = 0; m_nNALDataPos = 0; // In AnnexB, the buffer is not guaranteed to start on a NAL boundary if (nNALSize == 0 && nSize > 0) MoveToNextAnnexBStartcode(); } bool CH264Nalu::MoveToNextAnnexBStartcode() { if (m_nSize < 4) goto notfound; size_t nBuffEnd = m_nSize - 4; for (size_t i = m_nCurPos; i <= nBuffEnd; i++) { if ((*((DWORD *)(m_pBuffer + i)) & 0x00FFFFFF) == 0x00010000) { // Found next AnnexB NAL m_nCurPos = i; return true; } } notfound: m_nCurPos = m_nSize; return false; } bool CH264Nalu::MoveToNextRTPStartcode() { if (m_nNextRTP < m_nSize) { m_nCurPos = m_nNextRTP; return true; } m_nCurPos = m_nSize; return false; } bool CH264Nalu::ReadNext() { if (m_nCurPos >= m_nSize) return false; if ((m_nNALSize != 0) && (m_nCurPos == m_nNextRTP)) { if (m_nCurPos + m_nNALSize >= m_nSize) return false; // RTP Nalu type : (XX XX) XX XX NAL..., with XX XX XX XX or XX XX equal to NAL size m_nNALStartPos = m_nCurPos; m_nNALDataPos = m_nCurPos + m_nNALSize; // Read Length code from the buffer unsigned nTemp = 0; for (int i = 0; i < m_nNALSize; i++) nTemp = (nTemp << 8) + m_pBuffer[m_nCurPos++]; m_nNextRTP += nTemp + m_nNALSize; MoveToNextRTPStartcode(); } else { // Remove trailing bits while (m_pBuffer[m_nCurPos] == 0x00 && ((*((DWORD *)(m_pBuffer + m_nCurPos)) & 0x00FFFFFF) != 0x00010000)) m_nCurPos++; // AnnexB Nalu : 00 00 01 NAL... m_nNALStartPos = m_nCurPos; m_nCurPos += 3; m_nNALDataPos = m_nCurPos; MoveToNextAnnexBStartcode(); } forbidden_bit = (m_pBuffer[m_nNALDataPos] >> 7) & 1; nal_reference_idc = (m_pBuffer[m_nNALDataPos] >> 5) & 3; nal_unit_type = (NALU_TYPE)(m_pBuffer[m_nNALDataPos] & 0x1f); return true; } bool CH265Nalu::ReadNext() { if (CH264Nalu::ReadNext()) { nal_unit_type = (NALU_TYPE)((m_pBuffer[m_nNALDataPos] >> 1) & 0x3F); return true; } return false; } CH264NALUnescape::CH264NALUnescape(const BYTE *src, size_t nSize) { m_pBuffer = (BYTE *)_aligned_malloc(nSize + 16, 16); memset(m_pBuffer, 0, nSize + 16); unsigned si = 0, di = 0; BYTE *dst = m_pBuffer; while (si + 2 < nSize) { // detect and remove escapes if (src[si + 2] > 3) { dst[di++] = src[si++]; dst[di++] = src[si++]; } else if (src[si] == 0 && src[si + 1] == 0 && src[si + 2] != 0) { if (src[si + 2] == 3) { // escape dst[di++] = 0; dst[di++] = 0; si += 3; continue; } } dst[di++] = src[si++]; } while (si < nSize) dst[di++] = src[si++]; m_nSize = di; } CH264NALUnescape::~CH264NALUnescape() { _aligned_free(m_pBuffer); } ================================================ FILE: common/DSUtilLite/H264Nalu.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #pragma once typedef enum { NALU_TYPE_UNKNOWN = 0, NALU_TYPE_SLICE = 1, NALU_TYPE_DPA = 2, NALU_TYPE_DPB = 3, NALU_TYPE_DPC = 4, NALU_TYPE_IDR = 5, NALU_TYPE_SEI = 6, NALU_TYPE_SPS = 7, NALU_TYPE_PPS = 8, NALU_TYPE_AUD = 9, NALU_TYPE_EOSEQ = 10, NALU_TYPE_EOSTREAM = 11, NALU_TYPE_FILL = 12, NALU_TYPE_SPS_SUB = 15, } NALU_TYPE; class CH264Nalu { protected: int forbidden_bit = 0; //! should be always FALSE int nal_reference_idc = 0; //! NALU_PRIORITY_xxxx NALU_TYPE nal_unit_type = NALU_TYPE_UNKNOWN; //! NALU_TYPE_xxxx size_t m_nNALStartPos = 0; //! NALU start (including startcode / size) size_t m_nNALDataPos = 0; //! Useful part const BYTE *m_pBuffer = nullptr; size_t m_nCurPos = 0; size_t m_nNextRTP = 0; size_t m_nSize = 0; int m_nNALSize = 0; bool MoveToNextAnnexBStartcode(); bool MoveToNextRTPStartcode(); public: CH264Nalu() { SetBuffer(nullptr, 0, 0); } NALU_TYPE GetType() const { return nal_unit_type; } bool IsRefFrame() const { return (nal_reference_idc != 0); } size_t GetDataLength() const { return m_nCurPos - m_nNALDataPos; } const BYTE *GetDataBuffer() { return m_pBuffer + m_nNALDataPos; } size_t GetRoundedDataLength() const { size_t nSize = m_nCurPos - m_nNALDataPos; return nSize + 128 - (nSize % 128); } size_t GetLength() const { return m_nCurPos - m_nNALStartPos; } const BYTE *GetNALBuffer() { return m_pBuffer + m_nNALStartPos; } size_t GetNALPos() { return m_nNALStartPos; } bool IsEOF() const { return m_nCurPos >= m_nSize; } void SetBuffer(const BYTE *pBuffer, size_t nSize, int nNALSize); bool ReadNext(); }; class CH265Nalu : public CH264Nalu { public: CH265Nalu() : CH264Nalu(){}; bool ReadNext(); }; class CH264NALUnescape { public: CH264NALUnescape(const BYTE *pBuffer, size_t nSize); ~CH264NALUnescape(); const BYTE *GetBuffer() const { return m_pBuffer; } size_t GetSize() const { return m_nSize; } private: BYTE *m_pBuffer = nullptr; size_t m_nSize = 0; }; ================================================ FILE: common/DSUtilLite/MediaSampleSideData.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "MediaSampleSideData.h" CMediaSampleSideData::CMediaSampleSideData(LPCTSTR pName, CBaseAllocator *pAllocator, HRESULT *phr, LPBYTE pBuffer, LONG length) : CMediaSample(pName, pAllocator, phr, pBuffer, length) { } CMediaSampleSideData::~CMediaSampleSideData() { ReleaseSideData(); } STDMETHODIMP CMediaSampleSideData::QueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == __uuidof(IMediaSideData)) { return GetInterface((IMediaSideData *)this, ppv); } else { return __super::QueryInterface(riid, ppv); } } STDMETHODIMP_(ULONG) CMediaSampleSideData::Release() { /* Decrement our own private reference count */ LONG lRef; if (m_cRef == 1) { lRef = 0; m_cRef = 0; } else { lRef = InterlockedDecrement(&m_cRef); } ASSERT(lRef >= 0); /* Did we release our final reference count */ if (lRef == 0) { /* Free all resources */ if (m_dwFlags & Sample_TypeChanged) { SetMediaType(NULL); } ASSERT(m_pMediaType == NULL); m_dwFlags = 0; m_dwTypeSpecificFlags = 0; m_dwStreamId = AM_STREAM_MEDIA; ReleaseSideData(); /* This may cause us to be deleted */ // Our refcount is reliably 0 thus no-one will mess with us m_pAllocator->ReleaseBuffer(this); } return (ULONG)lRef; } void CMediaSampleSideData::ReleaseSideData() { CAutoLock Lock(&m_csSideData); for (auto it = m_SideData.begin(); it != m_SideData.end(); it++) { SideDataEntry *sd = &(it->second); _aligned_free(sd->pData); } m_SideData.clear(); } // IMediaSideData STDMETHODIMP CMediaSampleSideData::SetSideData(GUID guidType, const BYTE *pData, size_t size) { if (!pData || !size) return E_POINTER; CAutoLock Lock(&m_csSideData); auto it = m_SideData.find(guidType); if (it != m_SideData.end()) { SideDataEntry *sd = &(it->second); BYTE *newData = (BYTE *)_aligned_realloc(sd->pData, size, 16); if (newData) { sd->size = size; sd->pData = newData; memcpy(newData, pData, size); } else { return E_OUTOFMEMORY; } } else { SideDataEntry sd; sd.pData = (BYTE *)_aligned_malloc(size, 16); if (sd.pData) { sd.size = size; memcpy(sd.pData, pData, size); } else { return E_OUTOFMEMORY; } m_SideData[guidType] = sd; } return S_OK; } STDMETHODIMP CMediaSampleSideData::GetSideData(GUID guidType, const BYTE **pData, size_t *pSize) { if (!pData || !pSize) return E_POINTER; CAutoLock Lock(&m_csSideData); auto it = m_SideData.find(guidType); if (it != m_SideData.end()) { *pData = it->second.pData; *pSize = it->second.size; return S_OK; } return E_FAIL; } ================================================ FILE: common/DSUtilLite/MediaSampleSideData.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #include "amfilter.h" #include "IMediaSideData.h" struct SideDataGUIDComparer { bool operator()(const GUID &Left, const GUID &Right) const { // comparison logic goes here return memcmp(&Left, &Right, sizeof(Right)) < 0; } }; class CMediaSampleSideData : public CMediaSample , public IMediaSideData { public: CMediaSampleSideData(LPCTSTR pName, CBaseAllocator *pAllocator, HRESULT *phr, LPBYTE pBuffer, LONG length); virtual ~CMediaSampleSideData(); STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) Release(); // IMediaSideData STDMETHODIMP SetSideData(GUID guidType, const BYTE *pData, size_t size); STDMETHODIMP GetSideData(GUID guidType, const BYTE **pData, size_t *pSize); private: void ReleaseSideData(); struct SideDataEntry { BYTE *pData; size_t size; }; CCritSec m_csSideData; std::map m_SideData; }; ================================================ FILE: common/DSUtilLite/PopupMenu.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "PopupMenu.h" CPopupMenu::CPopupMenu(void) { m_hMenu = CreatePopupMenu(); } CPopupMenu::~CPopupMenu(void) { if (m_hMenu) DestroyMenu(m_hMenu); } HRESULT CPopupMenu::AddItem(UINT id, LPWSTR caption, BOOL checked, BOOL enabled) { if (!m_hMenu) return E_UNEXPECTED; MENUITEMINFO mii; mii.cbSize = sizeof(mii); mii.fMask = MIIM_ID | MIIM_STATE | MIIM_FTYPE | MIIM_STRING; mii.fType = MFT_STRING | MFT_RADIOCHECK; mii.wID = id; mii.fState = (checked ? MFS_CHECKED : 0) | (!enabled ? MFS_DISABLED : 0); mii.dwTypeData = caption; mii.cch = (UINT)wcslen(mii.dwTypeData); InsertMenuItem(m_hMenu, order++, TRUE, &mii); return S_OK; } HRESULT CPopupMenu::AddSeparator() { if (!m_hMenu) return E_UNEXPECTED; MENUITEMINFO mii; mii.cbSize = sizeof(mii); mii.fMask = MIIM_TYPE; mii.fType = MFT_SEPARATOR; InsertMenuItem(m_hMenu, order++, TRUE, &mii); return S_OK; } HRESULT CPopupMenu::AddSubmenu(HMENU hSubMenu, LPWSTR caption) { if (!m_hMenu) return E_UNEXPECTED; MENUITEMINFO mii; mii.cbSize = sizeof(mii); mii.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_SUBMENU; mii.fType = MFT_STRING; mii.hSubMenu = hSubMenu; mii.dwTypeData = caption; mii.cch = (UINT)wcslen(mii.dwTypeData); InsertMenuItem(m_hMenu, order++, TRUE, &mii); return S_OK; } HMENU CPopupMenu::Finish() { HMENU hMenu = m_hMenu; m_hMenu = nullptr; return hMenu; } ================================================ FILE: common/DSUtilLite/PopupMenu.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class CPopupMenu { public: CPopupMenu(void); virtual ~CPopupMenu(void); HRESULT AddItem(UINT id, LPWSTR caption, BOOL checked = FALSE, BOOL enabled = TRUE); HRESULT AddSeparator(); HRESULT AddSubmenu(HMENU hSubMenu, LPWSTR caption); HMENU Finish(); private: HMENU m_hMenu = 0; int order = 0; }; ================================================ FILE: common/DSUtilLite/SynchronizedQueue.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include template class CSynchronizedQueue : public CCritSec { public: CSynchronizedQueue(){}; void Push(T item) { CAutoLock lock(this); m_queue.push_back(item); } T Pop(void) { CAutoLock lock(this); if (m_queue.empty()) return nullptr; T item = m_queue.front(); m_queue.pop_front(); return item; } bool Empty() { CAutoLock lock(this); return m_queue.empty(); } size_t Size() { CAutoLock lock(this); return m_queue.size(); } private: std::deque m_queue; }; ================================================ FILE: common/DSUtilLite/filterreg.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #include "stdafx.h" #include "DShowUtil.h" std::wstring CStringFromGUID(const GUID &guid) { WCHAR null[128] = {0}, buff[128]; StringFromGUID2(GUID_NULL, null, 127); return std::wstring(StringFromGUID2(guid, buff, 127) > 0 ? buff : null); } // filter registration helpers bool DeleteRegKey(std::wstring szKey, std::wstring szSubkey) { bool bOK = false; HKEY hKey; LONG ec = ::RegOpenKeyEx(HKEY_CLASSES_ROOT, szKey.c_str(), 0, KEY_ALL_ACCESS, &hKey); if (ec == ERROR_SUCCESS) { if (szSubkey.length() > 0) ec = ::RegDeleteKey(hKey, szSubkey.c_str()); bOK = (ec == ERROR_SUCCESS); ::RegCloseKey(hKey); } return bOK; } bool SetRegKeyValue(std::wstring szKey, std::wstring szSubkey, std::wstring szValueName, std::wstring szValue) { bool bOK = false; if (szSubkey.length() > 0) szKey += _T("\\") + szSubkey; HKEY hKey; LONG ec = ::RegCreateKeyEx(HKEY_CLASSES_ROOT, szKey.c_str(), 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hKey, 0); if (ec == ERROR_SUCCESS) { if (szValue.length() > 0) { ec = ::RegSetValueEx(hKey, szValueName.c_str(), 0, REG_SZ, reinterpret_cast(const_cast(szValue.c_str())), (DWORD)(_tcslen(szValue.c_str()) + 1) * sizeof(TCHAR)); } bOK = (ec == ERROR_SUCCESS); ::RegCloseKey(hKey); } return bOK; } bool SetRegKeyValue(std::wstring szKey, std::wstring szSubkey, std::wstring szValue) { return SetRegKeyValue(szKey, szSubkey, _T(""), szValue); } void RegisterSourceFilter(const CLSID &clsid, const GUID &subtype2, LPCWSTR chkbytes, ...) { std::wstring null = CStringFromGUID(GUID_NULL); std::wstring majortype = CStringFromGUID(MEDIATYPE_Stream); std::wstring subtype = CStringFromGUID(subtype2); SetRegKeyValue(_T("Media Type\\") + majortype, subtype, _T("0"), chkbytes); SetRegKeyValue(_T("Media Type\\") + majortype, subtype, _T("Source Filter"), CStringFromGUID(clsid)); DeleteRegKey(_T("Media Type\\") + null, subtype); va_list extensions; va_start(extensions, chkbytes); LPCWSTR ext = nullptr; while (ext = va_arg(extensions, LPCWSTR)) { DeleteRegKey(_T("Media Type\\Extensions"), ext); } va_end(extensions); } void RegisterProtocolSourceFilter(const CLSID &clsid, LPCWSTR protocol) { SetRegKeyValue(protocol, _T(""), _T("Source Filter"), CStringFromGUID(clsid)); } void UnRegisterProtocolSourceFilter(LPCWSTR protocol) { DeleteRegKey(protocol, _T("")); } void RegisterSourceFilter(const CLSID &clsid, const GUID &subtype2, std::list chkbytes, ...) { std::wstring null = CStringFromGUID(GUID_NULL); std::wstring majortype = CStringFromGUID(MEDIATYPE_Stream); std::wstring subtype = CStringFromGUID(subtype2); int i = 0; std::list::iterator it; for (it = chkbytes.begin(); it != chkbytes.end(); ++it) { WCHAR idx[10] = {0}; swprintf_s(idx, _T("%d"), i); SetRegKeyValue(_T("Media Type\\") + majortype, subtype, idx, *it); i++; } SetRegKeyValue(_T("Media Type\\") + majortype, subtype, _T("Source Filter"), CStringFromGUID(clsid)); DeleteRegKey(_T("Media Type\\") + null, subtype); va_list extensions; va_start(extensions, chkbytes); LPCWSTR ext = nullptr; while (ext = va_arg(extensions, LPCWSTR)) { DeleteRegKey(_T("Media Type\\Extensions"), ext); } va_end(extensions); } void UnRegisterSourceFilter(const GUID &subtype) { DeleteRegKey(_T("Media Type\\") + CStringFromGUID(MEDIATYPE_Stream), CStringFromGUID(subtype)); } ================================================ FILE: common/DSUtilLite/gpu_memcpy_sse4.h ================================================ /* * Copyright (C) 2011-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Taken from the QuickSync decoder by Eric Gur */ #include #include // gpu_memcpy is a memcpy style function that copied data very fast from a // GPU tiled memory (write back) // Performance tip: page offset (12 lsb) of both addresses should be different // optimally use a 2K offset between them. inline void *gpu_memcpy(void *d, const void *s, size_t size) { static const size_t regsInLoop = sizeof(size_t) * 2; // 8 or 16 if (d == nullptr || s == nullptr) return nullptr; // If memory is not aligned, use memcpy bool isAligned = (((size_t)(s) | (size_t)(d)) & 0xF) == 0; if (!isAligned) { return memcpy(d, s, size); } __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; #ifdef _M_X64 __m128i xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15; #endif size_t remainder = size & (regsInLoop * sizeof(xmm0) - 1); // Copy 128 or 256 bytes every loop size_t end = 0; __m128i *pTrg = (__m128i *)d; __m128i *pTrgEnd = pTrg + ((size - remainder) >> 4); __m128i *pSrc = (__m128i *)s; // Make sure source is synced - doesn't hurt if not needed. _mm_sfence(); while (pTrg < pTrgEnd) { // _mm_stream_load_si128 emits the Streaming SIMD Extensions 4 (SSE4.1) instruction MOVNTDQA // Fastest method for copying GPU RAM. Available since Penryn (45nm Core 2 Duo/Quad) xmm0 = _mm_stream_load_si128(pSrc); xmm1 = _mm_stream_load_si128(pSrc + 1); xmm2 = _mm_stream_load_si128(pSrc + 2); xmm3 = _mm_stream_load_si128(pSrc + 3); xmm4 = _mm_stream_load_si128(pSrc + 4); xmm5 = _mm_stream_load_si128(pSrc + 5); xmm6 = _mm_stream_load_si128(pSrc + 6); xmm7 = _mm_stream_load_si128(pSrc + 7); #ifdef _M_X64 // Use all 16 xmm registers xmm8 = _mm_stream_load_si128(pSrc + 8); xmm9 = _mm_stream_load_si128(pSrc + 9); xmm10 = _mm_stream_load_si128(pSrc + 10); xmm11 = _mm_stream_load_si128(pSrc + 11); xmm12 = _mm_stream_load_si128(pSrc + 12); xmm13 = _mm_stream_load_si128(pSrc + 13); xmm14 = _mm_stream_load_si128(pSrc + 14); xmm15 = _mm_stream_load_si128(pSrc + 15); #endif _ReadWriteBarrier(); // _mm_store_si128 emit the SSE2 intruction MOVDQA (aligned store) _mm_store_si128(pTrg, xmm0); _mm_store_si128(pTrg + 1, xmm1); _mm_store_si128(pTrg + 2, xmm2); _mm_store_si128(pTrg + 3, xmm3); _mm_store_si128(pTrg + 4, xmm4); _mm_store_si128(pTrg + 5, xmm5); _mm_store_si128(pTrg + 6, xmm6); _mm_store_si128(pTrg + 7, xmm7); #ifdef _M_X64 // Use all 16 xmm registers _mm_store_si128(pTrg + 8, xmm8); _mm_store_si128(pTrg + 9, xmm9); _mm_store_si128(pTrg + 10, xmm10); _mm_store_si128(pTrg + 11, xmm11); _mm_store_si128(pTrg + 12, xmm12); _mm_store_si128(pTrg + 13, xmm13); _mm_store_si128(pTrg + 14, xmm14); _mm_store_si128(pTrg + 15, xmm15); #endif pSrc += regsInLoop; pTrg += regsInLoop; } // Copy in 16 byte steps if (remainder >= 16) { size = remainder; remainder = size & 15; end = size >> 4; for (size_t i = 0; i < end; ++i) { pTrg[i] = _mm_stream_load_si128(pSrc + i); } } // Copy last bytes - shouldn't happen as strides are modulu 16 if (remainder) { __m128i temp = _mm_stream_load_si128(pSrc + end); char *ps = (char *)(&temp); char *pt = (char *)(pTrg + end); for (size_t i = 0; i < remainder; ++i) { pt[i] = ps[i]; } } return d; } ================================================ FILE: common/DSUtilLite/growarray.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Class template: Re-sizable array. // To grow or shrink the array, call SetSize(). // To pre-allocate the array, call Allocate(). // Notes: // Copy constructor and assignment operator are private, to avoid throwing exceptions. (One could easily modify this.) // It is the caller's responsibility to release the objects in the array. The array's destuctor does not release them. // The array does not actually shrink when SetSize is called with a smaller size. Only the reported size changes. #pragma once #include #include "DShowUtil.h" template class GrowableArray { public: GrowableArray() {} virtual ~GrowableArray() { free(m_pArray); } // Allocate: Reserves memory for the array, but does not increase the count. HRESULT Allocate(DWORD alloc) { HRESULT hr = S_OK; if (alloc > m_allocated || !m_pArray) { T *pNew = (T *)realloc(m_pArray, sizeof(T) * alloc); if (!pNew) { free(m_pArray); m_pArray = nullptr; m_allocated = 0; return E_OUTOFMEMORY; } m_pArray = pNew; ZeroMemory(m_pArray + m_allocated, (alloc - m_allocated) * sizeof(T)); m_allocated = alloc; } return hr; } HRESULT Clear() { free(m_pArray); m_pArray = nullptr; m_count = m_allocated = 0; return S_OK; } // SetSize: Changes the count, and grows the array if needed. HRESULT SetSize(DWORD count) { HRESULT hr = S_OK; if (count > m_allocated) { hr = Allocate(count); } if (SUCCEEDED(hr)) { m_count = count; } return hr; } HRESULT Append(GrowableArray *other) { return Append(other->Ptr(), other->GetCount()); } HRESULT Append(const T *other, DWORD dwSize) { HRESULT hr = S_OK; DWORD old = GetCount(); hr = SetSize(old + dwSize); if (SUCCEEDED(hr)) memcpy(m_pArray + old, other, dwSize); return S_OK; } HRESULT AppendZero(DWORD dwSize) { HRESULT hr = S_OK; DWORD old = GetCount(); hr = SetSize(old + dwSize); if (SUCCEEDED(hr)) memset(m_pArray + old, 0, dwSize); return S_OK; } void Consume(DWORD dwSize) { ASSERT(dwSize <= m_count); if (dwSize == m_count) Clear(); else { memmove(m_pArray, m_pArray + dwSize, m_count - dwSize); m_count -= dwSize; } } DWORD GetCount() const { return m_count; } DWORD GetAllocated() const { return m_allocated; } // Accessor. T &operator[](DWORD index) { assert(index < m_count); return m_pArray[index]; } // Const accessor. const T &operator[](DWORD index) const { assert(index < m_count); return m_pArray[index]; } // Return the underlying array. T *Ptr() { return m_pArray; } protected: GrowableArray &operator=(const GrowableArray &r); GrowableArray(const GrowableArray &r); T *m_pArray = nullptr; DWORD m_count = 0; // Nominal count. DWORD m_allocated = 0; // Actual allocation size. }; ================================================ FILE: common/DSUtilLite/lavf_log.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #define LOG_BUF_LEN 2048 inline void lavf_log_callback(void *ptr, int level, const char *fmt, va_list vl) { static int print_prefix = 1; static int count; static char line[LOG_BUF_LEN] = {0}, prev[LOG_BUF_LEN] = {0}; if (level > AV_LOG_VERBOSE) return; av_log_format_line(ptr, level, fmt, vl, line, sizeof(line), &print_prefix); if (print_prefix && !strcmp(line, prev)) { count++; return; } if (count > 0) { DbgLog((LOG_CUSTOM1, level, L" Last message repeated %d times", count)); count = 0; } size_t len = strnlen_s(line, LOG_BUF_LEN); if (len > 0 && line[len - 1] == '\n') { line[len - 1] = 0; } DbgLog((LOG_CUSTOM1, level, L"%S", line)); strncpy_s(prev, line, _TRUNCATE); } ================================================ FILE: common/DSUtilLite/locale.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #include "stdafx.h" #include "DShowUtil.h" #include #include #include static struct { LPCSTR name, iso6392, iso6391, iso6392_2; LCID lcid; } s_isolangs[] = // TODO : fill LCID !!! { // Based on ISO-639-2, sorted by primary language code. Some manual additions of deprecated tags. {"Afar", "aar", "aa"}, {"Abkhazian", "abk", "ab"}, {"Achinese", "ace", nullptr}, {"Acoli", "ach", nullptr}, {"Adangme", "ada", nullptr}, {"Adyghe", "ady", nullptr}, {"Afro-Asiatic (Other)", "afa", nullptr}, {"Afrihili", "afh", nullptr}, {"Afrikaans", "afr", "af", nullptr, MAKELCID(MAKELANGID(LANG_AFRIKAANS, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Ainu", "ain", nullptr}, {"Akan", "aka", "ak"}, {"Akkadian", "akk", nullptr}, {"Albanian", "sqi", "sq", "alb", MAKELCID(MAKELANGID(LANG_ALBANIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Aleut", "ale", nullptr}, {"Algonquian languages", "alg", nullptr}, {"Southern Altai", "alt", nullptr}, {"Amharic", "amh", "am"}, {"English, Old (ca.450-1100)", "ang", nullptr}, {"Angika", "anp", nullptr}, {"Apache languages", "apa", nullptr}, {"Arabic", "ara", "ar", nullptr, MAKELCID(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Aramaic", "arc", nullptr}, {"Aragonese", "arg", "an"}, {"Armenian", "arm", "hy", "hye", MAKELCID(MAKELANGID(LANG_ARMENIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Mapudungun", "arn", nullptr}, {"Arapaho", "arp", nullptr}, {"Artificial (Other)", "art", nullptr}, {"Arawak", "arw", nullptr}, {"Assamese", "asm", "as", nullptr, MAKELCID(MAKELANGID(LANG_ASSAMESE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Asturian; Bable", "ast", nullptr}, {"Athapascan languages", "ath", nullptr}, {"Australian languages", "aus", nullptr}, {"Avaric", "ava", "av"}, {"Avestan", "ave", "ae"}, {"Awadhi", "awa", nullptr}, {"Aymara", "aym", "ay"}, {"Azerbaijani", "aze", "az", nullptr, MAKELCID(MAKELANGID(LANG_AZERI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Banda", "bad", nullptr}, {"Bamileke languages", "bai", nullptr}, {"Bashkir", "bak", "ba", nullptr, MAKELCID(MAKELANGID(LANG_BASHKIR, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Baluchi", "bal", nullptr}, {"Bambara", "bam", "bm"}, {"Balinese", "ban", nullptr}, {"Basque", "baq", "eu", "eus", MAKELCID(MAKELANGID(LANG_BASQUE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Basa", "bas", nullptr}, {"Baltic (Other)", "bat", nullptr}, {"Beja", "bej", nullptr}, {"Belarusian", "bel", "be", nullptr, MAKELCID(MAKELANGID(LANG_BELARUSIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Bemba", "bem", nullptr}, {"Bengali", "ben", "bn", nullptr, MAKELCID(MAKELANGID(LANG_BENGALI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Berber (Other)", "ber", nullptr}, {"Bhojpuri", "bho", nullptr}, {"Bihari", "bih", "bh"}, {"Bikol", "bik", nullptr}, {"Bini", "bin", nullptr}, {"Bislama", "bis", "bi"}, {"Siksika", "bla", nullptr}, {"Bantu (Other)", "bnt", nullptr}, {"Bosnian", "bos", "bs"}, {"Braj", "bra", nullptr}, {"Breton", "bre", "br", nullptr, MAKELCID(MAKELANGID(LANG_BRETON, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Batak (Indonesia)", "btk", nullptr}, {"Buriat", "bua", nullptr}, {"Buginese", "bug", nullptr}, {"Bulgarian", "bul", "bg", nullptr, MAKELCID(MAKELANGID(LANG_BULGARIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Burmese", "bur", "my", "mya"}, {"Blin", "byn", nullptr}, {"Caddo", "cad", nullptr}, {"Central American Indian (Other)", "cai", nullptr}, {"Carib", "car", nullptr}, {"Catalan", "cat", "ca", nullptr, MAKELCID(MAKELANGID(LANG_CATALAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Caucasian (Other)", "cau", nullptr}, {"Cebuano", "ceb", nullptr}, {"Celtic (Other)", "cel", nullptr}, {"Chamorro", "cha", "ch"}, {"Chibcha", "chb", nullptr}, {"Chechen", "che", "ce"}, {"Chagatai", "chg", nullptr}, {"Chinese", "chi", "zh", "zho", MAKELCID(MAKELANGID(LANG_CHINESE, SUBLANG_NEUTRAL), SORT_DEFAULT)}, {"Chuukese", "chk", nullptr}, {"Mari", "chm", nullptr}, {"Chinook jargon", "chn", nullptr}, {"Choctaw", "cho", nullptr}, {"Chipewyan", "chp", nullptr}, {"Cherokee", "chr", nullptr}, {"Church Slavic", "chu", "cu"}, {"Chuvash", "chv", "cv"}, {"Cheyenne", "chy", nullptr}, {"Chamic languages", "cmc", nullptr}, {"Montenegrin", "cnr", nullptr}, {"Coptic", "cop", nullptr}, {"Cornish", "cor", "kw"}, {"Corsican", "cos", "co", nullptr, MAKELCID(MAKELANGID(LANG_CORSICAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Creoles and pidgins, English-based", "cpe", nullptr}, {"Creoles and pidgins, French-based", "cpf", nullptr}, {"Creoles and pidgins, Portuguese-based", "cpp", nullptr}, {"Cree", "cre", "cr"}, {"Crimean Turkish", "crh", nullptr}, {"Creoles and pidgins (Other)", "crp", nullptr}, {"Kashubian", "csb", nullptr}, {"Cushitic (Other)", "cus", nullptr}, {"Czech", "cze", "cs", "ces", MAKELCID(MAKELANGID(LANG_CZECH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Dakota", "dak", nullptr}, {"Danish", "dan", "da", nullptr, MAKELCID(MAKELANGID(LANG_DANISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Dargwa", "dar", nullptr}, {"Dayak", "day", nullptr}, {"Delaware", "del", nullptr}, {"Slave (Athapascan)", "den", nullptr}, {"Dogrib", "dgr", nullptr}, {"Dinka", "din", nullptr}, {"Divehi", "div", "dv", nullptr, MAKELCID(MAKELANGID(LANG_DIVEHI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Dogri", "doi", nullptr}, {"Dravidian (Other)", "dra", nullptr}, {"Lower Sorbian", "dsb", nullptr}, {"Duala", "dua", nullptr}, {"Dutch, Middle (ca. 1050-1350)", "dum", nullptr}, {"Dutch", "dut", "nl", "nld", MAKELCID(MAKELANGID(LANG_DUTCH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Dyula", "dyu", nullptr}, {"Dzongkha", "dzo", "dz"}, {"Efik", "efi", nullptr}, {"Egyptian (Ancient)", "egy", nullptr}, {"Ekajuk", "eka", nullptr}, {"Elamite", "elx", nullptr}, {"English", "eng", "en", nullptr, MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"English, Middle (1100-1500)", "enm", nullptr}, {"Esperanto", "epo", "eo"}, {"Estonian", "est", "et", nullptr, MAKELCID(MAKELANGID(LANG_ESTONIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Ewe", "ewe", "ee"}, {"Ewondo", "ewo", nullptr}, {"Fang", "fan", nullptr}, {"Faroese", "fao", "fo", nullptr, MAKELCID(MAKELANGID(LANG_FAEROESE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Fanti", "fat", nullptr}, {"Fijian", "fij", "fj"}, {"Filipino", "fil", nullptr}, {"Finnish", "fin", "fi", nullptr, MAKELCID(MAKELANGID(LANG_FINNISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Finno-Ugrian (Other)", "fiu", nullptr}, {"Fon", "fon", nullptr}, {"French", "fre", "fr", "fra", MAKELCID(MAKELANGID(LANG_FRENCH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"French, Middle (ca.1400-1600)", "frm", nullptr}, {"French, Old (842-ca.1400)", "fro", nullptr}, {"Northern Frisian", "frr", nullptr}, {"Eastern Frisian", "frs", nullptr}, {"Frisian", "fry", "fy", nullptr, MAKELCID(MAKELANGID(LANG_FRISIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Fulah", "ful", "ff"}, {"Friulian", "fur", nullptr}, {"Ga", "gaa", nullptr}, {"Gayo", "gay", nullptr}, {"Gbaya", "gba", nullptr}, {"Germanic (Other)", "gem", nullptr}, {"Georgian", "geo", "ka", "kat", MAKELCID(MAKELANGID(LANG_GEORGIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"German", "ger", "de", "deu", MAKELCID(MAKELANGID(LANG_GERMAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Geez", "gez", nullptr}, {"Gilbertese", "gil", nullptr}, {"Gaelic; Scottish Gaelic", "gla", "gd"}, {"Irish", "gle", "ga", nullptr, MAKELCID(MAKELANGID(LANG_IRISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Galician", "glg", "gl", nullptr, MAKELCID(MAKELANGID(LANG_GALICIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Manx", "glv", "gv"}, {"German, Middle High (ca.1050-1500)", "gmh", nullptr}, {"German, Old High (ca.750-1050)", "goh", nullptr}, {"Gondi", "gon", nullptr}, {"Gorontalo", "gor", nullptr}, {"Gothic", "got", nullptr}, {"Grebo", "grb", nullptr}, {"Ancient Greek", "grc", nullptr}, {"Greek", "gre", "el", "ell", MAKELCID(MAKELANGID(LANG_GREEK, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Guarani", "grn", "gn"}, {"Swiss German", "gsw", nullptr}, {"Gujarati", "guj", "gu", nullptr, MAKELCID(MAKELANGID(LANG_GUJARATI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Gwichin", "gwi", nullptr}, {"Haida", "hai", nullptr}, {"Haitian", "hat", "ht"}, {"Hausa", "hau", "ha", nullptr, MAKELCID(MAKELANGID(LANG_HAUSA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Hawaiian", "haw", nullptr}, {"Hebrew", "heb", "he", nullptr, MAKELCID(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Herero", "her", "hz"}, {"Hiligaynon", "hil", nullptr}, {"Himachali", "him", nullptr}, {"Hindi", "hin", "hi", nullptr, MAKELCID(MAKELANGID(LANG_HINDI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Hittite", "hit", nullptr}, {"Hmong", "hmn", nullptr}, {"Hiri Motu", "hmo", "ho"}, {"Croatian", "hrv", "hr", "scr", MAKELCID(MAKELANGID(LANG_CROATIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Upper Sorbian", "hsb", nullptr}, {"Hungarian", "hun", "hu", nullptr, MAKELCID(MAKELANGID(LANG_HUNGARIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Hupa", "hup", nullptr}, {"Iban", "iba", nullptr}, {"Igbo", "ibo", "ig", nullptr, MAKELCID(MAKELANGID(LANG_IGBO, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Icelandic", "ice", "is", "isl", MAKELCID(MAKELANGID(LANG_ICELANDIC, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Ido", "ido", "io"}, {"Sichuan Yi", "iii", "ii"}, {"Ijo", "ijo", nullptr}, {"Inuktitut", "iku", "iu", nullptr, MAKELCID(MAKELANGID(LANG_INUKTITUT, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Interlingue", "ile", "ie"}, {"Iloko", "ilo", nullptr}, {"Interlingua", "ina", "ia"}, {"Indic (Other)", "inc", nullptr}, {"Indonesian", "ind", "id", nullptr, MAKELCID(MAKELANGID(LANG_INDONESIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Indo-European (Other)", "ine", nullptr}, {"Ingush", "inh", nullptr}, {"Inupiaq", "ipk", "ik"}, {"Iranian (Other)", "ira", nullptr}, {"Iroquoian languages", "iro", nullptr}, {"Italian", "ita", "it", nullptr, MAKELCID(MAKELANGID(LANG_ITALIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Javanese", "jav", "jv"}, {"Lojban", "jbo", nullptr}, {"Japanese", "jpn", "ja", nullptr, MAKELCID(MAKELANGID(LANG_JAPANESE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Judeo-Persian", "jpr", nullptr}, {"Judeo-Arabic", "jrb", nullptr}, {"Kara-Kalpak", "kaa", nullptr}, {"Kabyle", "kab", nullptr}, {"Kachin", "kac", nullptr}, {"Greenlandic; Kalaallisut", "kal", "kl", nullptr, MAKELCID(MAKELANGID(LANG_GREENLANDIC, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Kamba", "kam", nullptr}, {"Kannada", "kan", "kn", nullptr, MAKELCID(MAKELANGID(LANG_KANNADA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Karen", "kar", nullptr}, {"Kashmiri", "kas", "ks", nullptr, MAKELCID(MAKELANGID(LANG_KASHMIRI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Kanuri", "kau", "kr"}, {"Kawi", "kaw", nullptr}, {"Kazakh", "kaz", "kk", nullptr, MAKELCID(MAKELANGID(LANG_KAZAK, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Kabardian", "kbd", nullptr}, {"Khasi", "kha", nullptr}, {"Khoisan (Other)", "khi", nullptr}, {"Khmer", "khm", "km", nullptr, MAKELCID(MAKELANGID(LANG_KHMER, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Khotanese", "kho", nullptr}, {"Kikuyu; Gikuyu", "kik", "ki"}, {"Kinyarwanda", "kin", "rw", nullptr, MAKELCID(MAKELANGID(LANG_KINYARWANDA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Kirghiz", "kir", "ky"}, {"Kimbundu", "kmb", nullptr}, {"Konkani", "kok", nullptr, nullptr, MAKELCID(MAKELANGID(LANG_KONKANI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Komi", "kom", "kv"}, {"Kongo", "kon", "kg"}, {"Korean", "kor", "ko", nullptr, MAKELCID(MAKELANGID(LANG_KOREAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Kosraean", "kos", nullptr}, {"Kpelle", "kpe", nullptr}, {"Karachay-Balkar", "krc", nullptr}, {"Karelian", "krl", nullptr}, {"Kru", "kro", nullptr}, {"Kurukh", "kru", nullptr}, {"Kwanyama, Kuanyama", "kua", "kj"}, {"Kumyk", "kum", nullptr}, {"Kurdish", "kur", "ku"}, {"Kutenai", "kut", nullptr}, {"Ladino", "lad", nullptr}, {"Lahnda", "lah", nullptr}, {"Lamba", "lam", nullptr}, {"Lao", "lao", "lo", nullptr, MAKELCID(MAKELANGID(LANG_LAO, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Latin", "lat", "la"}, {"Latvian", "lav", "lv", nullptr, MAKELCID(MAKELANGID(LANG_LATVIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Lezghian", "lez", nullptr}, {"Limburgan; Limburger; Limburgish", "lim", "li"}, {"Lingala", "lin", "ln"}, {"Lithuanian", "lit", "lt", nullptr, MAKELCID(MAKELANGID(LANG_LITHUANIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Mongo", "lol", nullptr}, {"Lozi", "loz", nullptr}, {"Luxembourgish; Letzeburgesch", "ltz", "lb", nullptr, MAKELCID(MAKELANGID(LANG_LUXEMBOURGISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Luba-Lulua", "lua", nullptr}, {"Luba-Katanga", "lub", "lu"}, {"Ganda", "lug", "lg"}, {"Luiseno", "lui", nullptr}, {"Lunda", "lun", nullptr}, {"Luo (Kenya and Tanzania)", "luo", nullptr}, {"Lushai", "lus", nullptr}, {"Macedonian", "mac", "mk", "mkd", MAKELCID(MAKELANGID(LANG_MACEDONIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Madurese", "mad", nullptr}, {"Magahi", "mag", nullptr}, {"Marshallese", "mah", "mh"}, {"Maithili", "mai", nullptr}, {"Makasar", "mak", nullptr}, {"Malayalam", "mal", "ml", nullptr, MAKELCID(MAKELANGID(LANG_MALAYALAM, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Mandingo", "man", nullptr}, {"Maori", "mao", "mi", "mri", MAKELCID(MAKELANGID(LANG_MAORI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Austronesian (Other)", "map", nullptr}, {"Marathi", "mar", "mr", nullptr, MAKELCID(MAKELANGID(LANG_MARATHI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Masai", "mas", nullptr}, {"Malay", "may", "ms", "msa", MAKELCID(MAKELANGID(LANG_MALAY, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Moksha", "mdf", nullptr}, {"Mandar", "mdr", nullptr}, {"Mende", "men", nullptr}, {"Irish, Middle (900-1200)", "mga", nullptr}, {"Micmac", "mic", nullptr}, {"Minangkabau", "min", nullptr}, {"Miscellaneous languages", "mis", nullptr}, {"Mon-Khmer (Other)", "mkh", nullptr}, {"Malagasy", "mlg", "mg"}, {"Maltese", "mlt", "mt", nullptr, MAKELCID(MAKELANGID(LANG_MALTESE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Manchu", "mnc", nullptr}, {"Manipuri", "mni", nullptr, nullptr, MAKELCID(MAKELANGID(LANG_MANIPURI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Manobo languages", "mno", nullptr}, {"Mohawk", "moh", nullptr, nullptr, MAKELCID(MAKELANGID(LANG_MOHAWK, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Moldavian", "mol", "mo"}, // deprecated {"Mongolian", "mon", "mn", nullptr, MAKELCID(MAKELANGID(LANG_MONGOLIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Mossi", "mos", nullptr}, {"Multiple languages", "mul", nullptr}, {"Munda languages", "mun", nullptr}, {"Creek", "mus", nullptr}, {"Mirandese", "mwl", nullptr}, {"Marwari", "mwr", nullptr}, {"Mayan languages", "myn", nullptr}, {"Erzya", "myv", nullptr}, {"Nahuatl", "nah", nullptr}, {"North American Indian (Other)", "nai", nullptr}, {"Neapolitan", "nap", nullptr}, {"Nauru", "nau", "na"}, {"Navaho, Navajo", "nav", "nv"}, {"Ndebele, South", "nbl", "nr"}, {"Ndebele, North", "nde", "nd"}, {"Ndonga", "ndo", "ng"}, {"Low German; Low Saxon", "nds", nullptr}, {"Nepali", "nep", "ne", nullptr, MAKELCID(MAKELANGID(LANG_NEPALI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Newari", "new", nullptr}, {"Nias", "nia", nullptr}, {"Niger-Kordofanian (Other)", "nic", nullptr}, {"Niuean", "niu", nullptr}, {"Norwegian Nynorsk", "nno", "nn"}, {"Norwegian Bokml", "nob", "nb"}, {"Nogai", "nog", nullptr}, {"Norse, Old", "non", nullptr}, {"Norwegian", "nor", "no", nullptr, MAKELCID(MAKELANGID(LANG_NORWEGIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"N'Ko", "nqo", nullptr}, {"Pedi; Sepedi; Northern Sotho", "nso", nullptr, nullptr, MAKELCID(MAKELANGID(LANG_SOTHO, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Nubian languages", "nub", nullptr}, {"Classical Newari", "nwc", nullptr}, {"Nyanja; Chichewa; Chewa", "nya", "ny"}, {"Nyamwezi", "nym", nullptr}, {"Nyankole", "nyn", nullptr}, {"Nyoro", "nyo", nullptr}, {"Nzima", "nzi", nullptr}, {"Occitan (post 1500}", "oci", "oc", nullptr, MAKELCID(MAKELANGID(LANG_OCCITAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Ojibwa", "oji", "oj"}, {"Oriya", "ori", "or"}, {"Oromo", "orm", "om"}, {"Osage", "osa", nullptr}, {"Ossetian; Ossetic", "oss", "os"}, {"Turkish, Ottoman (1500-1928)", "ota", nullptr}, {"Otomian languages", "oto", nullptr}, {"Papuan (Other)", "paa", nullptr}, {"Pangasinan", "pag", nullptr}, {"Pahlavi", "pal", nullptr}, {"Pampanga", "pam", nullptr}, {"Panjabi", "pan", "pa"}, {"Papiamento", "pap", nullptr}, {"Palauan", "pau", nullptr}, {"Persian, Old (ca.600-400 B.C.)", "peo", nullptr}, {"Persian", "per", "fa", "fas", MAKELCID(MAKELANGID(LANG_PERSIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Philippine (Other)", "phi", nullptr}, {"Phoenician", "phn", nullptr}, {"Pali", "pli", "pi"}, {"Portuguese (Brazil)", "pob", "pb"}, // deprecated/unofficial {"Polish", "pol", "pl", nullptr, MAKELCID(MAKELANGID(LANG_POLISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Pohnpeian", "pon", nullptr}, {"Portuguese", "por", "pt", nullptr, MAKELCID(MAKELANGID(LANG_PORTUGUESE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Prakrit languages", "pra", nullptr}, {"Provenal, Old (to 1500)", "pro", nullptr}, {"Pushto", "pus", "ps"}, {"Quechua", "que", "qu", nullptr, MAKELCID(MAKELANGID(LANG_QUECHUA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Rajasthani", "raj", nullptr}, {"Rapanui", "rap", nullptr}, {"Rarotongan", "rar", nullptr}, {"Romance (Other)", "roa", nullptr}, {"Romansh", "roh", "rm"}, {"Romany", "rom", nullptr}, {"Romanian", "rum", "ro", "ron", MAKELCID(MAKELANGID(LANG_ROMANIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Rundi", "run", "rn"}, {"Aromanian", "rup", nullptr}, {"Russian", "rus", "ru", nullptr, MAKELCID(MAKELANGID(LANG_RUSSIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Sandawe", "sad", nullptr}, {"Sango", "sag", "sg"}, {"Yakut", "sah", nullptr, nullptr, MAKELCID(MAKELANGID(LANG_YAKUT, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"South American Indian (Other)", "sai", nullptr}, {"Salishan languages", "sal", nullptr}, {"Samaritan Aramaic", "sam", nullptr}, {"Sanskrit", "san", "sa", nullptr, MAKELCID(MAKELANGID(LANG_SANSKRIT, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Sasak", "sas", nullptr}, {"Santali", "sat", nullptr}, {"Sicilian", "scn", nullptr}, {"Scots", "sco", nullptr}, {"Selkup", "sel", nullptr}, {"Semitic (Other)", "sem", nullptr}, {"Irish, Old (to 900)", "sga", nullptr}, {"Sign languages", "sgn", nullptr}, {"Shan", "shn", nullptr}, {"Sidamo", "sid", nullptr}, {"Sinhalese", "sin", "si", nullptr, MAKELCID(MAKELANGID(LANG_SINHALESE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Siouan languages", "sio", nullptr}, {"Sino-Tibetan (Other)", "sit", nullptr}, {"Slavic (Other)", "sla", nullptr}, {"Slovak", "slo", "sk", "slk", MAKELCID(MAKELANGID(LANG_SLOVAK, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Slovenian", "slv", "sl", nullptr, MAKELCID(MAKELANGID(LANG_SLOVENIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Southern Sami", "sma", nullptr}, {"Northern Sami", "sme", "se"}, {"Sami languages (Other)", "smi", nullptr}, {"Lule Sami", "smj", nullptr}, {"Inari Sami", "smn", nullptr}, {"Samoan", "smo", "sm"}, {"Skolt Sami", "sms", nullptr}, {"Shona", "sna", "sn"}, {"Sindhi", "snd", "sd", nullptr, MAKELCID(MAKELANGID(LANG_SINDHI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Soninke", "snk", nullptr}, {"Sogdian", "sog", nullptr}, {"Somali", "som", "so"}, {"Songhai", "son", nullptr}, {"Sotho, Southern", "sot", "st", nullptr, MAKELCID(MAKELANGID(LANG_SOTHO, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Spanish", "spa", "es", "esp", MAKELCID(MAKELANGID(LANG_SPANISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Sardinian", "srd", "sc"}, {"Sranan Tongo", "srn", nullptr}, {"Serbian", "srp", "sr", "scc", MAKELCID(MAKELANGID(LANG_SERBIAN_NEUTRAL, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Serer", "srr", nullptr}, {"Nilo-Saharan (Other)", "ssa", nullptr}, {"Swati", "ssw", "ss"}, {"Sukuma", "suk", nullptr}, {"Sundanese", "sun", "su"}, {"Susu", "sus", nullptr}, {"Sumerian", "sux", nullptr}, {"Swahili", "swa", "sw", nullptr, MAKELCID(MAKELANGID(LANG_SWAHILI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Swedish", "swe", "sv", nullptr, MAKELCID(MAKELANGID(LANG_SWEDISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Classical Syriac", "syc", nullptr}, {"Syriac", "syr", nullptr, nullptr, MAKELCID(MAKELANGID(LANG_SYRIAC, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tahitian", "tah", "ty"}, {"Tai (Other)", "tai", nullptr}, {"Tamil", "tam", "ta", nullptr, MAKELCID(MAKELANGID(LANG_TAMIL, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tatar", "tat", "tt", nullptr, MAKELCID(MAKELANGID(LANG_TATAR, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Telugu", "tel", "te", nullptr, MAKELCID(MAKELANGID(LANG_TELUGU, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Timne", "tem", nullptr}, {"Tereno", "ter", nullptr}, {"Tetum", "tet", nullptr}, {"Tajik", "tgk", "tg", nullptr, MAKELCID(MAKELANGID(LANG_TAJIK, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tagalog", "tgl", "tl"}, {"Thai", "tha", "th", nullptr, MAKELCID(MAKELANGID(LANG_THAI, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tibetan", "tib", "bo", "bod", MAKELCID(MAKELANGID(LANG_TIBETAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tigre", "tig", nullptr}, {"Tigrinya", "tir", "ti", nullptr, MAKELCID(MAKELANGID(LANG_TIGRIGNA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tiv", "tiv", nullptr}, {"Tokelau", "tkl", nullptr}, {"Klingon", "tlh", nullptr}, {"Tlingit", "tli", nullptr}, {"Tamashek", "tmh", nullptr}, {"Tonga (Nyasa)", "tog", nullptr}, {"Tonga (Tonga Islands)", "ton", "to"}, {"Tok Pisin", "tpi", nullptr}, {"Tsimshian", "tsi", nullptr}, {"Tswana", "tsn", "tn", nullptr, MAKELCID(MAKELANGID(LANG_TSWANA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tsonga", "tso", "ts"}, {"Turkmen", "tuk", "tk", nullptr, MAKELCID(MAKELANGID(LANG_TURKMEN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Tumbuka", "tum", nullptr}, {"Tupi languages", "tup", nullptr}, {"Turkish", "tur", "tr", nullptr, MAKELCID(MAKELANGID(LANG_TURKISH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Altaic (Other)", "tut", nullptr}, {"Tuvalu", "tvl", nullptr}, {"Twi", "twi", "tw"}, {"Tuvinian", "tyv", nullptr}, {"Udmurt", "udm", nullptr}, {"Ugaritic", "uga", nullptr}, {"Uighur", "uig", "ug", nullptr, MAKELCID(MAKELANGID(LANG_UIGHUR, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Ukrainian", "ukr", "uk", nullptr, MAKELCID(MAKELANGID(LANG_UKRAINIAN, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Umbundu", "umb", nullptr}, {"Undetermined", "und", nullptr}, {"Urdu", "urd", "ur", nullptr, MAKELCID(MAKELANGID(LANG_URDU, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Uzbek", "uzb", "uz", nullptr, MAKELCID(MAKELANGID(LANG_UZBEK, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Vai", "vai", nullptr}, {"Venda", "ven", "ve"}, {"Vietnamese", "vie", "vi", nullptr, MAKELCID(MAKELANGID(LANG_VIETNAMESE, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Volapk", "vol", "vo"}, {"Votic", "vot", nullptr}, {"Wakashan languages", "wak", nullptr}, {"Walamo", "wal", nullptr}, {"Waray", "war", nullptr}, {"Washo", "was", nullptr}, {"Welsh", "wel", "cy", "cym", MAKELCID(MAKELANGID(LANG_WELSH, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Sorbian languages", "wen", nullptr}, {"Walloon", "wln", "wa"}, {"Wolof", "wol", "wo", nullptr, MAKELCID(MAKELANGID(LANG_WOLOF, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Kalmyk", "xal", nullptr}, {"Xhosa", "xho", "xh", nullptr, MAKELCID(MAKELANGID(LANG_XHOSA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Yao", "yao", nullptr}, {"Yapese", "yap", nullptr}, {"Yiddish", "yid", "yi"}, {"Yoruba", "yor", "yo", nullptr, MAKELCID(MAKELANGID(LANG_YORUBA, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Yupik languages", "ypk", nullptr}, {"Zapotec", "zap", nullptr}, {"Blissymbols", "zbl", nullptr}, {"Zenaga", "zen", nullptr}, {"Standard Moroccan Tamazight", "zgh", nullptr}, {"Zhuang; Chuang", "zha", "za"}, {"Zande", "znd", nullptr}, {"Zulu", "zul", "zu", nullptr, MAKELCID(MAKELANGID(LANG_ZULU, SUBLANG_DEFAULT), SORT_DEFAULT)}, {"Zuni", "zun", nullptr}, {"Zaza", "zza", nullptr}, {nullptr, nullptr, nullptr}, {"No subtitles", "---", nullptr, nullptr, (LCID)LCID_NOSUBTITLES}, }; std::string ISO6391ToLanguage(LPCSTR code) { CHAR tmp[2 + 1]; strncpy_s(tmp, code, 2); tmp[2] = 0; _strlwr_s(tmp); for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if (s_isolangs[i].iso6391 && !strcmp(s_isolangs[i].iso6391, tmp)) { std::string ret = std::string(s_isolangs[i].name); size_t i = ret.find(';'); if (i != std::string::npos) { ret = ret.substr(0, i); } return ret; } } return std::string(); } std::string ISO6392ToLanguage(LPCSTR code) { CHAR tmp[3 + 1]; strncpy_s(tmp, code, 3); tmp[3] = 0; _strlwr_s(tmp); for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if ((s_isolangs[i].iso6392 && !strcmp(s_isolangs[i].iso6392, tmp)) || (s_isolangs[i].iso6392_2 && !strcmp(s_isolangs[i].iso6392_2, tmp))) { std::string ret = std::string(s_isolangs[i].name); size_t i = ret.find(';'); if (i != std::string::npos) { ret = ret.substr(0, i); } return ret; } } return std::string(); } std::string ProbeLangForLanguage(LPCSTR code) { if (strlen(code) == 3) { return ISO6392ToLanguage(code); } else if (strlen(code) >= 2) { return ISO6391ToLanguage(code); } return std::string(); } static std::string ISO6392Check(LPCSTR lang) { CHAR tmp[3 + 1]; strncpy_s(tmp, lang, 3); tmp[3] = 0; _strlwr_s(tmp); for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if ((s_isolangs[i].iso6392 && !strcmp(s_isolangs[i].iso6392, tmp)) || (s_isolangs[i].iso6392_2 && !strcmp(s_isolangs[i].iso6392_2, tmp))) { return std::string(s_isolangs[i].iso6392); } } return std::string(tmp); } static std::string LanguageToISO6392(LPCSTR code) { for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if ((s_isolangs[i].name && !_stricmp(s_isolangs[i].name, code))) { return std::string(s_isolangs[i].iso6392); } } return std::string(); } std::string ProbeForISO6392(LPCSTR lang) { std::string isoLang; if (strlen(lang) == 2) { isoLang = ISO6391To6392(lang); } else if (strlen(lang) == 3) { isoLang = ISO6392Check(lang); } else if (strlen(lang) > 3) { isoLang = LanguageToISO6392(lang); if (isoLang.empty()) { std::regex ogmRegex("\\[([[:alpha:]]{3})\\]"); std::cmatch res; bool found = std::regex_search(lang, res, ogmRegex); if (found && !res[1].str().empty()) { isoLang = ISO6392Check(res[1].str().c_str()); } } } if (isoLang.empty()) isoLang = std::string(lang); return isoLang; } LCID ISO6391ToLcid(LPCSTR code) { CHAR tmp[2 + 1]; strncpy_s(tmp, code, 2); tmp[2] = 0; _strlwr_s(tmp); for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if (s_isolangs[i].iso6391 && !strcmp(s_isolangs[i].iso6391, tmp)) { return s_isolangs[i].lcid; } } return 0; } LCID ISO6392ToLcid(LPCSTR code) { CHAR tmp[3 + 1]; strncpy_s(tmp, code, 3); tmp[3] = 0; _strlwr_s(tmp); for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if ((s_isolangs[i].iso6392 && !strcmp(s_isolangs[i].iso6392, tmp)) || (s_isolangs[i].iso6392_2 && !strcmp(s_isolangs[i].iso6392_2, tmp))) { return s_isolangs[i].lcid; } } return 0; } std::string ISO6391To6392(LPCSTR code) { CHAR tmp[2 + 1]; strncpy_s(tmp, code, 2); tmp[2] = 0; _strlwr_s(tmp); for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if (s_isolangs[i].iso6391 && !strcmp(s_isolangs[i].iso6391, tmp)) { return s_isolangs[i].iso6392; } } return std::string(code); } std::string ISO6392To6391(LPCSTR code) { CHAR tmp[3 + 1]; strncpy_s(tmp, code, 3); tmp[3] = 0; _strlwr_s(tmp); for (size_t i = 0, j = countof(s_isolangs); i < j; i++) { if ((s_isolangs[i].iso6392 && !strcmp(s_isolangs[i].iso6392, tmp)) || (s_isolangs[i].iso6392_2 && !strcmp(s_isolangs[i].iso6392_2, tmp))) { return s_isolangs[i].iso6391; } } return std::string(); } LCID ProbeLangForLCID(LPCSTR code) { if (strlen(code) == 3) { return ISO6392ToLcid(code); } else if (strlen(code) >= 2) { return ISO6391ToLcid(code); } return 0; } ================================================ FILE: common/DSUtilLite/rand_sse.h ================================================ // Based on rand_sse at // http://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor/ #include __declspec(align(16)) static __m128i cur_seed; void srand_sse(unsigned int seed) { cur_seed = _mm_set_epi32(seed, seed + 1, seed, seed + 1); } inline void rand_sse(int *result) { __declspec(align(16)) __m128i cur_seed_split; __declspec(align(16)) __m128i multiplier; __declspec(align(16)) __m128i adder; __declspec(align(16)) __m128i mod_mask; __declspec(align(16)) __m128i sra_mask; __declspec(align(16)) __m128i sseresult; __declspec(align(16)) static const unsigned int mult[4] = {214013, 17405, 214013, 69069}; __declspec(align(16)) static const unsigned int gadd[4] = {2531011, 10395331, 13737667, 1}; __declspec(align(16)) static const unsigned int mask[4] = {0xFFFFFFFF, 0, 0xFFFFFFFF, 0}; __declspec(align(16)) static const unsigned int masklo[4] = {0x00007FFF, 0x00007FFF, 0x00007FFF, 0x00007FFF}; adder = _mm_load_si128((__m128i *)gadd); multiplier = _mm_load_si128((__m128i *)mult); mod_mask = _mm_load_si128((__m128i *)mask); sra_mask = _mm_load_si128((__m128i *)masklo); cur_seed_split = _mm_shuffle_epi32(cur_seed, _MM_SHUFFLE(2, 3, 0, 1)); cur_seed = _mm_mul_epu32(cur_seed, multiplier); multiplier = _mm_shuffle_epi32(multiplier, _MM_SHUFFLE(2, 3, 0, 1)); cur_seed_split = _mm_mul_epu32(cur_seed_split, multiplier); cur_seed = _mm_and_si128(cur_seed, mod_mask); cur_seed_split = _mm_and_si128(cur_seed_split, mod_mask); cur_seed_split = _mm_shuffle_epi32(cur_seed_split, _MM_SHUFFLE(2, 3, 0, 1)); cur_seed = _mm_or_si128(cur_seed, cur_seed_split); cur_seed = _mm_add_epi32(cur_seed, adder); sseresult = _mm_srai_epi32(cur_seed, 16); sseresult = _mm_and_si128(sseresult, sra_mask); _mm_storeu_si128((__m128i *)result, sseresult); return; } ================================================ FILE: common/DSUtilLite/registry.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "registry.h" bool CreateRegistryKey(HKEY hKeyRoot, LPCTSTR pszSubKey) { HKEY hKey; LONG lRet; lRet = RegCreateKeyEx(hKeyRoot, pszSubKey, 0, nullptr, REG_OPTION_NON_VOLATILE, KEY_WRITE, nullptr, &hKey, nullptr); if (lRet == ERROR_SUCCESS) { RegCloseKey(hKey); hKey = (HKEY) nullptr; return true; } SetLastError((DWORD)lRet); return false; } CRegistry::CRegistry() { } CRegistry::CRegistry(HKEY hkeyRoot, LPCTSTR pszSubKey, HRESULT &hr, BOOL bReadOnly, BOOL b64Bit) { hr = Open(hkeyRoot, pszSubKey, bReadOnly, b64Bit); } CRegistry::~CRegistry() { if (m_key) RegCloseKey(*m_key); delete m_key; } HRESULT CRegistry::Open(HKEY hkeyRoot, LPCTSTR pszSubKey, BOOL bReadOnly, BOOL b64Bit) { LONG lRet; if (m_key != nullptr) { return E_UNEXPECTED; } m_key = new HKEY(); REGSAM sam = bReadOnly ? KEY_READ : KEY_READ | KEY_WRITE; if (b64Bit) sam |= KEY_WOW64_64KEY; lRet = RegOpenKeyEx(hkeyRoot, pszSubKey, 0, sam, m_key); if (lRet != ERROR_SUCCESS) { delete m_key; m_key = nullptr; return E_FAIL; } return S_OK; } std::wstring CRegistry::ReadString(LPCTSTR pszKey, HRESULT &hr) { LONG lRet; DWORD dwSize; std::wstring result; hr = S_OK; if (m_key == nullptr) { hr = E_UNEXPECTED; return result; } lRet = RegQueryValueEx(*m_key, pszKey, nullptr, nullptr, nullptr, &dwSize); if (lRet == ERROR_SUCCESS) { // Alloc Buffer to fit the data WCHAR *buffer = (WCHAR *)CoTaskMemAlloc(dwSize); if (!buffer) { hr = E_OUTOFMEMORY; return result; } memset(buffer, 0, dwSize); lRet = RegQueryValueEx(*m_key, pszKey, nullptr, nullptr, (LPBYTE)buffer, &dwSize); result = std::wstring(buffer); CoTaskMemFree(buffer); } if (lRet != ERROR_SUCCESS) { hr = E_FAIL; } return result; } HRESULT CRegistry::WriteString(LPCTSTR pszKey, const LPCTSTR pszValue) { LONG lRet; HRESULT hr; hr = S_OK; if (m_key == nullptr) { return E_UNEXPECTED; } lRet = RegSetValueEx(*m_key, pszKey, 0, REG_SZ, (const BYTE *)pszValue, (DWORD)((wcslen(pszValue) + 1) * sizeof(WCHAR))); if (lRet != ERROR_SUCCESS) { return E_FAIL; } return S_OK; } DWORD CRegistry::ReadDWORD(LPCTSTR pszKey, HRESULT &hr) { LONG lRet; DWORD dwSize = sizeof(DWORD); DWORD dwVal = 0; hr = S_OK; if (m_key == nullptr) { hr = E_UNEXPECTED; return 0; } lRet = RegQueryValueEx(*m_key, pszKey, 0, nullptr, (LPBYTE)&dwVal, &dwSize); if (lRet != ERROR_SUCCESS) { hr = E_FAIL; } return dwVal; } HRESULT CRegistry::WriteDWORD(LPCTSTR pszKey, DWORD dwValue) { LONG lRet; HRESULT hr; hr = S_OK; if (m_key == nullptr) { return E_UNEXPECTED; } lRet = RegSetValueEx(*m_key, pszKey, 0, REG_DWORD, (const BYTE *)&dwValue, sizeof(dwValue)); if (lRet != ERROR_SUCCESS) { return E_FAIL; } return S_OK; } BOOL CRegistry::ReadBOOL(LPCTSTR pszKey, HRESULT &hr) { DWORD dwVal = ReadDWORD(pszKey, hr); return dwVal ? TRUE : FALSE; } HRESULT CRegistry::WriteBOOL(LPCTSTR pszKey, BOOL bValue) { return WriteDWORD(pszKey, bValue); } BYTE *CRegistry::ReadBinary(LPCTSTR pszKey, DWORD &dwSize, HRESULT &hr) { LONG lRet; BYTE *result = nullptr; hr = S_OK; if (m_key == nullptr) { hr = E_UNEXPECTED; return result; } lRet = RegQueryValueEx(*m_key, pszKey, nullptr, nullptr, nullptr, &dwSize); if (lRet == ERROR_SUCCESS) { // Alloc Buffer to fit the data result = (BYTE *)CoTaskMemAlloc(dwSize); if (!result) { hr = E_OUTOFMEMORY; return result; } memset(result, 0, dwSize); lRet = RegQueryValueEx(*m_key, pszKey, nullptr, nullptr, (LPBYTE)result, &dwSize); } if (lRet != ERROR_SUCCESS) { hr = E_FAIL; CoTaskMemFree(result); result = nullptr; } return result; } HRESULT CRegistry::WriteBinary(LPCTSTR pszKey, const BYTE *pbValue, int iLen) { LONG lRet; HRESULT hr; hr = S_OK; if (m_key == nullptr) { return E_UNEXPECTED; } lRet = RegSetValueEx(*m_key, pszKey, 0, REG_BINARY, (const BYTE *)pbValue, iLen); if (lRet != ERROR_SUCCESS) { return E_FAIL; } return S_OK; } HRESULT CRegistry::DeleteKey(LPCTSTR pszKey) { LONG lRet; if (m_key == nullptr) { return E_UNEXPECTED; } lRet = RegDeleteValue(*m_key, pszKey); if (lRet != ERROR_SUCCESS) { return E_FAIL; } return S_OK; } ================================================ FILE: common/DSUtilLite/registry.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include bool CreateRegistryKey(HKEY hKeyRoot, LPCTSTR pszSubKey); class CRegistry { public: CRegistry(); CRegistry(HKEY hkeyRoot, LPCTSTR pszSubKey, HRESULT &hr, BOOL bReadOnly = FALSE, BOOL b64Bit = TRUE); ~CRegistry(); HRESULT Open(HKEY hkeyRoot, LPCTSTR pszSubKey, BOOL bReadOnly = FALSE, BOOL b64Bit = TRUE); std::wstring ReadString(LPCTSTR pszKey, HRESULT &hr); HRESULT WriteString(LPCTSTR pszKey, LPCTSTR pszValue); DWORD ReadDWORD(LPCTSTR pszKey, HRESULT &hr); HRESULT WriteDWORD(LPCTSTR pszKey, DWORD dwValue); BOOL ReadBOOL(LPCTSTR pszKey, HRESULT &hr); HRESULT WriteBOOL(LPCTSTR pszKey, BOOL bValue); BYTE *ReadBinary(LPCTSTR pszKey, DWORD &dwSize, HRESULT &hr); HRESULT WriteBinary(LPCTSTR pszKey, const BYTE *pbValue, int iLen); HRESULT DeleteKey(LPCTSTR pszKey); private: HKEY *m_key = nullptr; }; ================================================ FILE: common/DSUtilLite/stdafx.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #include "stdafx.h" ================================================ FILE: common/DSUtilLite/stdafx.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "common_defines.h" #include #include #include #include #include #include "streams.h" // TODO: reference additional headers your program requires here ================================================ FILE: common/DSUtilLite/timer.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include #define START_TIMER \ uint64_t tend; \ uint64_t tstart = __rdtsc(); #define STOP_TIMER(id) \ tend = __rdtsc(); \ { \ static uint64_t tsum = 0; \ static int tcount = 0; \ static int tskip_count = 0; \ if (tcount < 2 || tend - tstart < 8 * tsum / tcount || tend - tstart < 2000) \ { \ tsum += tend - tstart; \ tcount++; \ } \ else \ tskip_count++; \ if (((tcount + tskip_count) & (tcount + tskip_count - 1)) == 0) \ { \ debugprintf(L"%I64u decicycles in %S, %d runs, %d skips", tsum * 10 / tcount, id, tcount, tskip_count); \ } \ } ================================================ FILE: common/baseclasses/amextra.cpp ================================================ //------------------------------------------------------------------------------ // File: AMExtra.cpp // // Desc: DirectShow base classes - implements CRenderedInputPin class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include // DirectShow base class definitions #include // Needed for definition of timeGetTime #include // Standard data type limit definitions #include // Used for time critical log functions #include "amextra.h" #pragma warning(disable : 4355) // Implements CRenderedInputPin class CRenderedInputPin::CRenderedInputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBaseInputPin(pObjectName, pFilter, pLock, phr, pName) , m_bAtEndOfStream(FALSE) , m_bCompleteNotified(FALSE) { } #ifdef UNICODE CRenderedInputPin::CRenderedInputPin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBaseInputPin(pObjectName, pFilter, pLock, phr, pName) , m_bAtEndOfStream(FALSE) , m_bCompleteNotified(FALSE) { } #endif // Flush end of stream condition - caller should do any // necessary stream level locking before calling this STDMETHODIMP CRenderedInputPin::EndOfStream() { HRESULT hr = CheckStreaming(); // Do EC_COMPLETE handling for rendered pins if (S_OK == hr && !m_bAtEndOfStream) { m_bAtEndOfStream = TRUE; FILTER_STATE fs; EXECUTE_ASSERT(SUCCEEDED(m_pFilter->GetState(0, &fs))); if (fs == State_Running) { DoCompleteHandling(); } } return hr; } // Called to complete the flush STDMETHODIMP CRenderedInputPin::EndFlush() { CAutoLock lck(m_pLock); // Clean up renderer state m_bAtEndOfStream = FALSE; m_bCompleteNotified = FALSE; return CBaseInputPin::EndFlush(); } // Notify of Run() from filter HRESULT CRenderedInputPin::Run(REFERENCE_TIME tStart) { UNREFERENCED_PARAMETER(tStart); m_bCompleteNotified = FALSE; if (m_bAtEndOfStream) { DoCompleteHandling(); } return S_OK; } // Clear status on going into paused state HRESULT CRenderedInputPin::Active() { m_bAtEndOfStream = FALSE; m_bCompleteNotified = FALSE; return CBaseInputPin::Active(); } // Do stuff to deliver end of stream void CRenderedInputPin::DoCompleteHandling() { ASSERT(m_bAtEndOfStream); if (!m_bCompleteNotified) { m_bCompleteNotified = TRUE; m_pFilter->NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)(IBaseFilter *)m_pFilter); } } ================================================ FILE: common/baseclasses/amextra.h ================================================ //------------------------------------------------------------------------------ // File: AMExtra.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __AMEXTRA__ #define __AMEXTRA__ // Simple rendered input pin // // NOTE if your filter queues stuff before rendering then it may not be // appropriate to use this class // // In that case queue the end of stream condition until the last sample // is actually rendered and flush the condition appropriately class CRenderedInputPin : public CBaseInputPin { public: CRenderedInputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); #ifdef UNICODE CRenderedInputPin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); #endif // Override methods to track end of stream state STDMETHODIMP EndOfStream(); STDMETHODIMP EndFlush(); HRESULT Active(); HRESULT Run(REFERENCE_TIME tStart); protected: // Member variables to track state BOOL m_bAtEndOfStream; // Set by EndOfStream BOOL m_bCompleteNotified; // Set when we notify for EC_COMPLETE private: void DoCompleteHandling(); }; #endif // __AMEXTRA__ ================================================ FILE: common/baseclasses/amfilter.cpp ================================================ //------------------------------------------------------------------------------ // File: AMFilter.cpp // // Desc: DirectShow base classes - implements class hierarchy for streams // architecture. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ //===================================================================== //===================================================================== // The following classes are declared in this header: // // // CBaseMediaFilter Basic IMediaFilter support (abstract class) // CBaseFilter Support for IBaseFilter (incl. IMediaFilter) // CEnumPins Enumerate input and output pins // CEnumMediaTypes Enumerate the preferred pin formats // CBasePin Abstract base class for IPin interface // CBaseOutputPin Adds data provider member functions // CBaseInputPin Implements IMemInputPin interface // CMediaSample Basic transport unit for IMemInputPin // CBaseAllocator General list guff for most allocators // CMemAllocator Implements memory buffer allocation // //===================================================================== //===================================================================== #include #include #ifdef DXMPERF #include "dxmperf.h" #endif // DXMPERF //===================================================================== // Helpers //===================================================================== STDAPI CreateMemoryAllocator(__deref_out IMemAllocator **ppAllocator) { return CoCreateInstance(CLSID_MemoryAllocator, 0, CLSCTX_INPROC_SERVER, IID_IMemAllocator, (void **)ppAllocator); } // Put this one here rather than in ctlutil.cpp to avoid linking // anything brought in by ctlutil.cpp STDAPI CreatePosPassThru(__in_opt LPUNKNOWN pAgg, BOOL bRenderer, IPin *pPin, __deref_out IUnknown **ppPassThru) { *ppPassThru = NULL; IUnknown *pUnkSeek; HRESULT hr = CoCreateInstance(CLSID_SeekingPassThru, pAgg, CLSCTX_INPROC_SERVER, IID_IUnknown, (void **)&pUnkSeek); if (FAILED(hr)) { return hr; } ISeekingPassThru *pPassThru; hr = pUnkSeek->QueryInterface(IID_ISeekingPassThru, (void **)&pPassThru); if (FAILED(hr)) { pUnkSeek->Release(); return hr; } hr = pPassThru->Init(bRenderer, pPin); pPassThru->Release(); if (FAILED(hr)) { pUnkSeek->Release(); return hr; } *ppPassThru = pUnkSeek; return S_OK; } #define CONNECT_TRACE_LEVEL 3 //===================================================================== //===================================================================== // Implements CBaseMediaFilter //===================================================================== //===================================================================== /* Constructor */ CBaseMediaFilter::CBaseMediaFilter(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __in CCritSec *pLock, REFCLSID clsid) : CUnknown(pName, pUnk) , m_pLock(pLock) , m_clsid(clsid) , m_State(State_Stopped) , m_pClock(NULL) { } /* Destructor */ CBaseMediaFilter::~CBaseMediaFilter() { // must be stopped, but can't call Stop here since // our critsec has been destroyed. /* Release any clock we were using */ if (m_pClock) { m_pClock->Release(); m_pClock = NULL; } } /* Override this to say what interfaces we support and where */ STDMETHODIMP CBaseMediaFilter::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_IMediaFilter) { return GetInterface((IMediaFilter *)this, ppv); } else if (riid == IID_IPersist) { return GetInterface((IPersist *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } /* Return the filter's clsid */ STDMETHODIMP CBaseMediaFilter::GetClassID(__out CLSID *pClsID) { CheckPointer(pClsID, E_POINTER); ValidateReadWritePtr(pClsID, sizeof(CLSID)); *pClsID = m_clsid; return NOERROR; } /* Override this if your state changes are not done synchronously */ STDMETHODIMP CBaseMediaFilter::GetState(DWORD dwMSecs, __out FILTER_STATE *State) { UNREFERENCED_PARAMETER(dwMSecs); CheckPointer(State, E_POINTER); ValidateReadWritePtr(State, sizeof(FILTER_STATE)); *State = m_State; return S_OK; } /* Set the clock we will use for synchronisation */ STDMETHODIMP CBaseMediaFilter::SetSyncSource(__inout_opt IReferenceClock *pClock) { CAutoLock cObjectLock(m_pLock); // Ensure the new one does not go away - even if the same as the old if (pClock) { pClock->AddRef(); } // if we have a clock, release it if (m_pClock) { m_pClock->Release(); } // Set the new reference clock (might be NULL) // Should we query it to ensure it is a clock? Consider for a debug build. m_pClock = pClock; return NOERROR; } /* Return the clock we are using for synchronisation */ STDMETHODIMP CBaseMediaFilter::GetSyncSource(__deref_out_opt IReferenceClock **pClock) { CheckPointer(pClock, E_POINTER); ValidateReadWritePtr(pClock, sizeof(IReferenceClock *)); CAutoLock cObjectLock(m_pLock); if (m_pClock) { // returning an interface... addref it... m_pClock->AddRef(); } *pClock = (IReferenceClock *)m_pClock; return NOERROR; } /* Put the filter into a stopped state */ STDMETHODIMP CBaseMediaFilter::Stop() { CAutoLock cObjectLock(m_pLock); m_State = State_Stopped; return S_OK; } /* Put the filter into a paused state */ STDMETHODIMP CBaseMediaFilter::Pause() { CAutoLock cObjectLock(m_pLock); m_State = State_Paused; return S_OK; } // Put the filter into a running state. // The time parameter is the offset to be added to the samples' // stream time to get the reference time at which they should be presented. // // you can either add these two and compare it against the reference clock, // or you can call CBaseMediaFilter::StreamTime and compare that against // the sample timestamp. STDMETHODIMP CBaseMediaFilter::Run(REFERENCE_TIME tStart) { CAutoLock cObjectLock(m_pLock); // remember the stream time offset m_tStart = tStart; if (m_State == State_Stopped) { HRESULT hr = Pause(); if (FAILED(hr)) { return hr; } } m_State = State_Running; return S_OK; } // // return the current stream time - samples with start timestamps of this // time or before should be rendered by now HRESULT CBaseMediaFilter::StreamTime(CRefTime &rtStream) { // Caller must lock for synchronization // We can't grab the filter lock because we want to be able to call // this from worker threads without deadlocking if (m_pClock == NULL) { return VFW_E_NO_CLOCK; } // get the current reference time HRESULT hr = m_pClock->GetTime((REFERENCE_TIME *)&rtStream); if (FAILED(hr)) { return hr; } // subtract the stream offset to get stream time rtStream -= m_tStart; return S_OK; } //===================================================================== //===================================================================== // Implements CBaseFilter //===================================================================== //===================================================================== /* Override this to say what interfaces we support and where */ STDMETHODIMP CBaseFilter::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { /* Do we have this interface */ if (riid == IID_IBaseFilter) { return GetInterface((IBaseFilter *)this, ppv); } else if (riid == IID_IMediaFilter) { return GetInterface((IMediaFilter *)this, ppv); } else if (riid == IID_IPersist) { return GetInterface((IPersist *)this, ppv); } else if (riid == IID_IAMovieSetup) { return GetInterface((IAMovieSetup *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } #ifdef DEBUG STDMETHODIMP_(ULONG) CBaseFilter::NonDelegatingRelease() { if (m_cRef == 1) { KASSERT(m_pGraph == NULL); } return CUnknown::NonDelegatingRelease(); } #endif /* Constructor */ CBaseFilter::CBaseFilter(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __in CCritSec *pLock, REFCLSID clsid) : CUnknown(pName, pUnk) , m_pLock(pLock) , m_clsid(clsid) , m_State(State_Stopped) , m_pClock(NULL) , m_pGraph(NULL) , m_pSink(NULL) , m_pName(NULL) , m_PinVersion(1) { #ifdef DXMPERF PERFLOG_CTOR(pName ? pName : L"CBaseFilter", (IBaseFilter *)this); #endif // DXMPERF ASSERT(pLock != NULL); } /* Passes in a redundant HRESULT argument */ CBaseFilter::CBaseFilter(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk, __in CCritSec *pLock, REFCLSID clsid, __inout HRESULT *phr) : CUnknown(pName, pUnk) , m_pLock(pLock) , m_clsid(clsid) , m_State(State_Stopped) , m_pClock(NULL) , m_pGraph(NULL) , m_pSink(NULL) , m_pName(NULL) , m_PinVersion(1) { #ifdef DXMPERF PERFLOG_CTOR(pName ? pName : L"CBaseFilter", (IBaseFilter *)this); #endif // DXMPERF ASSERT(pLock != NULL); UNREFERENCED_PARAMETER(phr); } #ifdef UNICODE CBaseFilter::CBaseFilter(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk, __in CCritSec *pLock, REFCLSID clsid) : CUnknown(pName, pUnk) , m_pLock(pLock) , m_clsid(clsid) , m_State(State_Stopped) , m_pClock(NULL) , m_pGraph(NULL) , m_pSink(NULL) , m_pName(NULL) , m_PinVersion(1) { #ifdef DXMPERF PERFLOG_CTOR(L"CBaseFilter", (IBaseFilter *)this); #endif // DXMPERF ASSERT(pLock != NULL); } CBaseFilter::CBaseFilter(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk, __in CCritSec *pLock, REFCLSID clsid, __inout HRESULT *phr) : CUnknown(pName, pUnk) , m_pLock(pLock) , m_clsid(clsid) , m_State(State_Stopped) , m_pClock(NULL) , m_pGraph(NULL) , m_pSink(NULL) , m_pName(NULL) , m_PinVersion(1) { #ifdef DXMPERF PERFLOG_CTOR(L"CBaseFilter", (IBaseFilter *)this); #endif // DXMPERF ASSERT(pLock != NULL); UNREFERENCED_PARAMETER(phr); } #endif /* Destructor */ CBaseFilter::~CBaseFilter() { #ifdef DXMPERF PERFLOG_DTOR(L"CBaseFilter", (IBaseFilter *)this); #endif // DXMPERF // NOTE we do NOT hold references on the filtergraph for m_pGraph or m_pSink // When we did we had the circular reference problem. Nothing would go away. delete[] m_pName; // must be stopped, but can't call Stop here since // our critsec has been destroyed. /* Release any clock we were using */ if (m_pClock) { m_pClock->Release(); m_pClock = NULL; } } /* Return the filter's clsid */ STDMETHODIMP CBaseFilter::GetClassID(__out CLSID *pClsID) { CheckPointer(pClsID, E_POINTER); ValidateReadWritePtr(pClsID, sizeof(CLSID)); *pClsID = m_clsid; return NOERROR; } /* Override this if your state changes are not done synchronously */ STDMETHODIMP CBaseFilter::GetState(DWORD dwMSecs, __out FILTER_STATE *State) { UNREFERENCED_PARAMETER(dwMSecs); CheckPointer(State, E_POINTER); ValidateReadWritePtr(State, sizeof(FILTER_STATE)); *State = m_State; return S_OK; } /* Set the clock we will use for synchronisation */ STDMETHODIMP CBaseFilter::SetSyncSource(__in_opt IReferenceClock *pClock) { CAutoLock cObjectLock(m_pLock); // Ensure the new one does not go away - even if the same as the old if (pClock) { pClock->AddRef(); } // if we have a clock, release it if (m_pClock) { m_pClock->Release(); } // Set the new reference clock (might be NULL) // Should we query it to ensure it is a clock? Consider for a debug build. m_pClock = pClock; return NOERROR; } /* Return the clock we are using for synchronisation */ STDMETHODIMP CBaseFilter::GetSyncSource(__deref_out_opt IReferenceClock **pClock) { CheckPointer(pClock, E_POINTER); ValidateReadWritePtr(pClock, sizeof(IReferenceClock *)); CAutoLock cObjectLock(m_pLock); if (m_pClock) { // returning an interface... addref it... m_pClock->AddRef(); } *pClock = (IReferenceClock *)m_pClock; return NOERROR; } // override CBaseMediaFilter Stop method, to deactivate any pins this // filter has. STDMETHODIMP CBaseFilter::Stop() { CAutoLock cObjectLock(m_pLock); HRESULT hr = NOERROR; // notify all pins of the state change if (m_State != State_Stopped) { int cPins = GetPinCount(); for (int c = 0; c < cPins; c++) { CBasePin *pPin = GetPin(c); if (NULL == pPin) { break; } // Disconnected pins are not activated - this saves pins worrying // about this state themselves. We ignore the return code to make // sure everyone is inactivated regardless. The base input pin // class can return an error if it has no allocator but Stop can // be used to resync the graph state after something has gone bad if (pPin->IsConnected()) { HRESULT hrTmp = pPin->Inactive(); if (FAILED(hrTmp) && SUCCEEDED(hr)) { hr = hrTmp; } } } } #ifdef DXMPERF PERFLOG_STOP(m_pName ? m_pName : L"CBaseFilter", (IBaseFilter *)this, m_State); #endif // DXMPERF m_State = State_Stopped; return hr; } // override CBaseMediaFilter Pause method to activate any pins // this filter has (also called from Run) STDMETHODIMP CBaseFilter::Pause() { CAutoLock cObjectLock(m_pLock); // notify all pins of the change to active state if (m_State == State_Stopped) { int cPins = GetPinCount(); for (int c = 0; c < cPins; c++) { CBasePin *pPin = GetPin(c); if (NULL == pPin) { break; } // Disconnected pins are not activated - this saves pins // worrying about this state themselves if (pPin->IsConnected()) { HRESULT hr = pPin->Active(); if (FAILED(hr)) { return hr; } } } } #ifdef DXMPERF PERFLOG_PAUSE(m_pName ? m_pName : L"CBaseFilter", (IBaseFilter *)this, m_State); #endif // DXMPERF m_State = State_Paused; return S_OK; } // Put the filter into a running state. // The time parameter is the offset to be added to the samples' // stream time to get the reference time at which they should be presented. // // you can either add these two and compare it against the reference clock, // or you can call CBaseFilter::StreamTime and compare that against // the sample timestamp. STDMETHODIMP CBaseFilter::Run(REFERENCE_TIME tStart) { CAutoLock cObjectLock(m_pLock); // remember the stream time offset m_tStart = tStart; if (m_State == State_Stopped) { HRESULT hr = Pause(); if (FAILED(hr)) { return hr; } } // notify all pins of the change to active state if (m_State != State_Running) { int cPins = GetPinCount(); for (int c = 0; c < cPins; c++) { CBasePin *pPin = GetPin(c); if (NULL == pPin) { break; } // Disconnected pins are not activated - this saves pins // worrying about this state themselves if (pPin->IsConnected()) { HRESULT hr = pPin->Run(tStart); if (FAILED(hr)) { return hr; } } } } #ifdef DXMPERF PERFLOG_RUN(m_pName ? m_pName : L"CBaseFilter", (IBaseFilter *)this, tStart, m_State); #endif // DXMPERF m_State = State_Running; return S_OK; } // // return the current stream time - samples with start timestamps of this // time or before should be rendered by now HRESULT CBaseFilter::StreamTime(CRefTime &rtStream) { // Caller must lock for synchronization // We can't grab the filter lock because we want to be able to call // this from worker threads without deadlocking if (m_pClock == NULL) { return VFW_E_NO_CLOCK; } // get the current reference time HRESULT hr = m_pClock->GetTime((REFERENCE_TIME *)&rtStream); if (FAILED(hr)) { return hr; } // subtract the stream offset to get stream time rtStream -= m_tStart; return S_OK; } /* Create an enumerator for the pins attached to this filter */ STDMETHODIMP CBaseFilter::EnumPins(__deref_out IEnumPins **ppEnum) { CheckPointer(ppEnum, E_POINTER); ValidateReadWritePtr(ppEnum, sizeof(IEnumPins *)); /* Create a new ref counted enumerator */ *ppEnum = new CEnumPins(this, NULL); return *ppEnum == NULL ? E_OUTOFMEMORY : NOERROR; } // default behaviour of FindPin is to assume pins are named // by their pin names STDMETHODIMP CBaseFilter::FindPin(LPCWSTR Id, __deref_out IPin **ppPin) { CheckPointer(ppPin, E_POINTER); ValidateReadWritePtr(ppPin, sizeof(IPin *)); // We're going to search the pin list so maintain integrity CAutoLock lck(m_pLock); int iCount = GetPinCount(); for (int i = 0; i < iCount; i++) { CBasePin *pPin = GetPin(i); if (NULL == pPin) { break; } if (0 == lstrcmpW(pPin->Name(), Id)) { // Found one that matches // // AddRef() and return it *ppPin = pPin; pPin->AddRef(); return S_OK; } } *ppPin = NULL; return VFW_E_NOT_FOUND; } /* Return information about this filter */ STDMETHODIMP CBaseFilter::QueryFilterInfo(__out FILTER_INFO *pInfo) { CheckPointer(pInfo, E_POINTER); ValidateReadWritePtr(pInfo, sizeof(FILTER_INFO)); if (m_pName) { (void)StringCchCopyW(pInfo->achName, NUMELMS(pInfo->achName), m_pName); } else { pInfo->achName[0] = L'\0'; } pInfo->pGraph = m_pGraph; if (m_pGraph) m_pGraph->AddRef(); return NOERROR; } /* Provide the filter with a filter graph */ STDMETHODIMP CBaseFilter::JoinFilterGraph(__inout_opt IFilterGraph *pGraph, __in_opt LPCWSTR pName) { CAutoLock cObjectLock(m_pLock); // NOTE: we no longer hold references on the graph (m_pGraph, m_pSink) m_pGraph = pGraph; if (m_pGraph) { HRESULT hr = m_pGraph->QueryInterface(IID_IMediaEventSink, (void **)&m_pSink); if (FAILED(hr)) { ASSERT(m_pSink == NULL); } else m_pSink->Release(); // we do NOT keep a reference on it. } else { // if graph pointer is null, then we should // also release the IMediaEventSink on the same object - we don't // refcount it, so just set it to null m_pSink = NULL; } if (m_pName) { delete[] m_pName; m_pName = NULL; } if (pName) { size_t namelen; HRESULT hr = StringCchLengthW(pName, STRSAFE_MAX_CCH, &namelen); if (FAILED(hr)) { return hr; } m_pName = new WCHAR[namelen + 1]; if (m_pName) { (void)StringCchCopyW(m_pName, namelen + 1, pName); } else { return E_OUTOFMEMORY; } } #ifdef DXMPERF PERFLOG_JOINGRAPH(m_pName ? m_pName : L"CBaseFilter", (IBaseFilter *)this, pGraph); #endif // DXMPERF return NOERROR; } // return a Vendor information string. Optional - may return E_NOTIMPL. // memory returned should be freed using CoTaskMemFree // default implementation returns E_NOTIMPL STDMETHODIMP CBaseFilter::QueryVendorInfo(__deref_out LPWSTR *pVendorInfo) { UNREFERENCED_PARAMETER(pVendorInfo); return E_NOTIMPL; } // send an event notification to the filter graph if we know about it. // returns S_OK if delivered, S_FALSE if the filter graph does not sink // events, or an error otherwise. HRESULT CBaseFilter::NotifyEvent(long EventCode, LONG_PTR EventParam1, LONG_PTR EventParam2) { // Snapshot so we don't have to lock up IMediaEventSink *pSink = m_pSink; if (pSink) { if (EC_COMPLETE == EventCode) { EventParam2 = (LONG_PTR)(IBaseFilter *)this; } return pSink->Notify(EventCode, EventParam1, EventParam2); } else { return E_NOTIMPL; } } // Request reconnect // pPin is the pin to reconnect // pmt is the type to reconnect with - can be NULL // Calls ReconnectEx on the filter graph HRESULT CBaseFilter::ReconnectPin(IPin *pPin, __in_opt AM_MEDIA_TYPE const *pmt) { IFilterGraph2 *pGraph2; if (m_pGraph != NULL) { HRESULT hr = m_pGraph->QueryInterface(IID_IFilterGraph2, (void **)&pGraph2); if (SUCCEEDED(hr)) { hr = pGraph2->ReconnectEx(pPin, pmt); pGraph2->Release(); return hr; } else { return m_pGraph->Reconnect(pPin); } } else { return E_NOINTERFACE; } } /* This is the same idea as the media type version does for type enumeration on pins but for the list of pins available. So if the list of pins you provide changes dynamically then either override this virtual function to provide the version number, or more simply call IncrementPinVersion */ LONG CBaseFilter::GetPinVersion() { return m_PinVersion; } /* Increment the current pin version cookie */ void CBaseFilter::IncrementPinVersion() { InterlockedIncrement(&m_PinVersion); } /* register filter */ STDMETHODIMP CBaseFilter::Register() { // get setup data, if it exists // LPAMOVIESETUP_FILTER psetupdata = GetSetupData(); // check we've got data // if (NULL == psetupdata) return S_FALSE; // init is ref counted so call just in case // we're being called cold. // HRESULT hr = CoInitialize((LPVOID)NULL); ASSERT(SUCCEEDED(hr)); // get hold of IFilterMapper // IFilterMapper *pIFM; hr = CoCreateInstance(CLSID_FilterMapper, NULL, CLSCTX_INPROC_SERVER, IID_IFilterMapper, (void **)&pIFM); if (SUCCEEDED(hr)) { hr = AMovieSetupRegisterFilter(psetupdata, pIFM, TRUE); pIFM->Release(); } // and clear up // CoFreeUnusedLibraries(); CoUninitialize(); return NOERROR; } /* unregister filter */ STDMETHODIMP CBaseFilter::Unregister() { // get setup data, if it exists // LPAMOVIESETUP_FILTER psetupdata = GetSetupData(); // check we've got data // if (NULL == psetupdata) return S_FALSE; // OLE init is ref counted so call // just in case we're being called cold. // HRESULT hr = CoInitialize((LPVOID)NULL); ASSERT(SUCCEEDED(hr)); // get hold of IFilterMapper // IFilterMapper *pIFM; hr = CoCreateInstance(CLSID_FilterMapper, NULL, CLSCTX_INPROC_SERVER, IID_IFilterMapper, (void **)&pIFM); if (SUCCEEDED(hr)) { hr = AMovieSetupRegisterFilter(psetupdata, pIFM, FALSE); // release interface // pIFM->Release(); } // clear up // CoFreeUnusedLibraries(); CoUninitialize(); // handle one acceptable "error" - that // of filter not being registered! // (couldn't find a suitable #define'd // name for the error!) // if (0x80070002 == hr) return NOERROR; else return hr; } //===================================================================== //===================================================================== // Implements CEnumPins //===================================================================== //===================================================================== CEnumPins::CEnumPins(__in CBaseFilter *pFilter, __in_opt CEnumPins *pEnumPins) : m_Position(0) , m_PinCount(0) , m_pFilter(pFilter) , m_cRef(1) , // Already ref counted m_PinCache(NAME("Pin Cache")) { #ifdef DEBUG m_dwCookie = DbgRegisterObjectCreation("CEnumPins", 0); #endif /* We must be owned by a filter derived from CBaseFilter */ ASSERT(pFilter != NULL); /* Hold a reference count on our filter */ m_pFilter->AddRef(); /* Are we creating a new enumerator */ if (pEnumPins == NULL) { m_Version = m_pFilter->GetPinVersion(); m_PinCount = m_pFilter->GetPinCount(); } else { ASSERT(m_Position <= m_PinCount); m_Position = pEnumPins->m_Position; m_PinCount = pEnumPins->m_PinCount; m_Version = pEnumPins->m_Version; m_PinCache.AddTail(&(pEnumPins->m_PinCache)); } } /* Destructor releases the reference count on our filter NOTE since we hold a reference count on the filter who created us we know it is safe to release it, no access can be made to it afterwards though as we have just caused the last reference count to go and the object to be deleted */ CEnumPins::~CEnumPins() { m_pFilter->Release(); #ifdef DEBUG DbgRegisterObjectDestruction(m_dwCookie); #endif } /* Override this to say what interfaces we support where */ STDMETHODIMP CEnumPins::QueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); /* Do we have this interface */ if (riid == IID_IEnumPins || riid == IID_IUnknown) { return GetInterface((IEnumPins *)this, ppv); } else { *ppv = NULL; return E_NOINTERFACE; } } STDMETHODIMP_(ULONG) CEnumPins::AddRef() { return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) CEnumPins::Release() { ULONG cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } /* One of an enumerator's basic member functions allows us to create a cloned interface that initially has the same state. Since we are taking a snapshot of an object (current position and all) we must lock access at the start */ STDMETHODIMP CEnumPins::Clone(__deref_out IEnumPins **ppEnum) { CheckPointer(ppEnum, E_POINTER); ValidateReadWritePtr(ppEnum, sizeof(IEnumPins *)); HRESULT hr = NOERROR; /* Check we are still in sync with the filter */ if (AreWeOutOfSync() == TRUE) { *ppEnum = NULL; hr = VFW_E_ENUM_OUT_OF_SYNC; } else { *ppEnum = new CEnumPins(m_pFilter, this); if (*ppEnum == NULL) { hr = E_OUTOFMEMORY; } } return hr; } /* Return the next pin after the current position */ STDMETHODIMP CEnumPins::Next(ULONG cPins, // place this many pins... __out_ecount(cPins) IPin **ppPins, // ...in this array __out_opt ULONG *pcFetched) // actual count passed returned here { CheckPointer(ppPins, E_POINTER); ValidateReadWritePtr(ppPins, cPins * sizeof(IPin *)); ASSERT(ppPins); if (pcFetched != NULL) { ValidateWritePtr(pcFetched, sizeof(ULONG)); *pcFetched = 0; // default unless we succeed } // now check that the parameter is valid else if (cPins > 1) { // pcFetched == NULL return E_INVALIDARG; } ULONG cFetched = 0; // increment as we get each one. /* Check we are still in sync with the filter */ if (AreWeOutOfSync() == TRUE) { // If we are out of sync, we should refresh the enumerator. // This will reset the position and update the other members, but // will not clear cache of pins we have already returned. Refresh(); } /* Return each pin interface NOTE GetPin returns CBasePin * not addrefed so we must QI for the IPin (which increments its reference count) If while we are retrieving a pin from the filter an error occurs we assume that our internal state is stale with respect to the filter (for example someone has deleted a pin) so we return VFW_E_ENUM_OUT_OF_SYNC */ while (cFetched < cPins && m_PinCount > m_Position) { /* Get the next pin object from the filter */ CBasePin *pPin = m_pFilter->GetPin(m_Position++); if (pPin == NULL) { // If this happend, and it's not the first time through, then we've got a problem, // since we should really go back and release the iPins, which we have previously // AddRef'ed. ASSERT(cFetched == 0); return VFW_E_ENUM_OUT_OF_SYNC; } /* We only want to return this pin, if it is not in our cache */ if (0 == m_PinCache.Find(pPin)) { /* From the object get an IPin interface */ *ppPins = pPin; pPin->AddRef(); cFetched++; ppPins++; m_PinCache.AddTail(pPin); } } if (pcFetched != NULL) { *pcFetched = cFetched; } return (cPins == cFetched ? NOERROR : S_FALSE); } /* Skip over one or more entries in the enumerator */ STDMETHODIMP CEnumPins::Skip(ULONG cPins) { /* Check we are still in sync with the filter */ if (AreWeOutOfSync() == TRUE) { return VFW_E_ENUM_OUT_OF_SYNC; } /* Work out how many pins are left to skip over */ /* We could position at the end if we are asked to skip too many... */ /* ..which would match the base implementation for CEnumMediaTypes::Skip */ ULONG PinsLeft = m_PinCount - m_Position; if (cPins > PinsLeft) { return S_FALSE; } m_Position += cPins; return NOERROR; } /* Set the current position back to the start */ /* Reset has 4 simple steps: * * Set position to head of list * Sync enumerator with object being enumerated * Clear the cache of pins already returned * return S_OK */ STDMETHODIMP CEnumPins::Reset() { m_Version = m_pFilter->GetPinVersion(); m_PinCount = m_pFilter->GetPinCount(); m_Position = 0; // Clear the cache m_PinCache.RemoveAll(); return S_OK; } /* Set the current position back to the start */ /* Refresh has 3 simple steps: * * Set position to head of list * Sync enumerator with object being enumerated * return S_OK */ STDMETHODIMP CEnumPins::Refresh() { m_Version = m_pFilter->GetPinVersion(); m_PinCount = m_pFilter->GetPinCount(); m_Position = 0; return S_OK; } //===================================================================== //===================================================================== // Implements CEnumMediaTypes //===================================================================== //===================================================================== CEnumMediaTypes::CEnumMediaTypes(__in CBasePin *pPin, __in_opt CEnumMediaTypes *pEnumMediaTypes) : m_Position(0) , m_pPin(pPin) , m_cRef(1) { #ifdef DEBUG m_dwCookie = DbgRegisterObjectCreation("CEnumMediaTypes", 0); #endif /* We must be owned by a pin derived from CBasePin */ ASSERT(pPin != NULL); /* Hold a reference count on our pin */ m_pPin->AddRef(); /* Are we creating a new enumerator */ if (pEnumMediaTypes == NULL) { m_Version = m_pPin->GetMediaTypeVersion(); return; } m_Position = pEnumMediaTypes->m_Position; m_Version = pEnumMediaTypes->m_Version; } /* Destructor releases the reference count on our base pin. NOTE since we hold a reference count on the pin who created us we know it is safe to release it, no access can be made to it afterwards though as we might have just caused the last reference count to go and the object to be deleted */ CEnumMediaTypes::~CEnumMediaTypes() { #ifdef DEBUG DbgRegisterObjectDestruction(m_dwCookie); #endif m_pPin->Release(); } /* Override this to say what interfaces we support where */ STDMETHODIMP CEnumMediaTypes::QueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); /* Do we have this interface */ if (riid == IID_IEnumMediaTypes || riid == IID_IUnknown) { return GetInterface((IEnumMediaTypes *)this, ppv); } else { *ppv = NULL; return E_NOINTERFACE; } } STDMETHODIMP_(ULONG) CEnumMediaTypes::AddRef() { return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) CEnumMediaTypes::Release() { ULONG cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } /* One of an enumerator's basic member functions allows us to create a cloned interface that initially has the same state. Since we are taking a snapshot of an object (current position and all) we must lock access at the start */ STDMETHODIMP CEnumMediaTypes::Clone(__deref_out IEnumMediaTypes **ppEnum) { CheckPointer(ppEnum, E_POINTER); ValidateReadWritePtr(ppEnum, sizeof(IEnumMediaTypes *)); HRESULT hr = NOERROR; /* Check we are still in sync with the pin */ if (AreWeOutOfSync() == TRUE) { *ppEnum = NULL; hr = VFW_E_ENUM_OUT_OF_SYNC; } else { *ppEnum = new CEnumMediaTypes(m_pPin, this); if (*ppEnum == NULL) { hr = E_OUTOFMEMORY; } } return hr; } /* Enumerate the next pin(s) after the current position. The client using this interface passes in a pointer to an array of pointers each of which will be filled in with a pointer to a fully initialised media type format Return NOERROR if it all works, S_FALSE if fewer than cMediaTypes were enumerated. VFW_E_ENUM_OUT_OF_SYNC if the enumerator has been broken by state changes in the filter The actual count always correctly reflects the number of types in the array. */ STDMETHODIMP CEnumMediaTypes::Next(ULONG cMediaTypes, // place this many types... __out_ecount(cMediaTypes) AM_MEDIA_TYPE **ppMediaTypes, // ...in this array __out ULONG *pcFetched) // actual count passed { CheckPointer(ppMediaTypes, E_POINTER); ValidateReadWritePtr(ppMediaTypes, cMediaTypes * sizeof(AM_MEDIA_TYPE *)); /* Check we are still in sync with the pin */ if (AreWeOutOfSync() == TRUE) { return VFW_E_ENUM_OUT_OF_SYNC; } if (pcFetched != NULL) { ValidateWritePtr(pcFetched, sizeof(ULONG)); *pcFetched = 0; // default unless we succeed } // now check that the parameter is valid else if (cMediaTypes > 1) { // pcFetched == NULL return E_INVALIDARG; } ULONG cFetched = 0; // increment as we get each one. /* Return each media type by asking the filter for them in turn - If we have an error code retured to us while we are retrieving a media type we assume that our internal state is stale with respect to the filter (for example the window size changing) so we return VFW_E_ENUM_OUT_OF_SYNC */ while (cMediaTypes) { CMediaType cmt; HRESULT hr = m_pPin->GetMediaType(m_Position++, &cmt); if (S_OK != hr) { break; } /* We now have a CMediaType object that contains the next media type but when we assign it to the array position we CANNOT just assign the AM_MEDIA_TYPE structure because as soon as the object goes out of scope it will delete the memory we have just copied. The function we use is CreateMediaType which allocates a task memory block */ /* Transfer across the format block manually to save an allocate and free on the format block and generally go faster */ *ppMediaTypes = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)); if (*ppMediaTypes == NULL) { break; } /* Do a regular copy */ **ppMediaTypes = cmt; /* Make sure the destructor doesn't free these */ cmt.pbFormat = NULL; cmt.cbFormat = NULL; cmt.pUnk = NULL; ppMediaTypes++; cFetched++; cMediaTypes--; } if (pcFetched != NULL) { *pcFetched = cFetched; } return (cMediaTypes == 0 ? NOERROR : S_FALSE); } /* Skip over one or more entries in the enumerator */ STDMETHODIMP CEnumMediaTypes::Skip(ULONG cMediaTypes) { // If we're skipping 0 elements we're guaranteed to skip the // correct number of elements if (cMediaTypes == 0) { return S_OK; } /* Check we are still in sync with the pin */ if (AreWeOutOfSync() == TRUE) { return VFW_E_ENUM_OUT_OF_SYNC; } m_Position += cMediaTypes; /* See if we're over the end */ CMediaType cmt; return S_OK == m_pPin->GetMediaType(m_Position - 1, &cmt) ? S_OK : S_FALSE; } /* Set the current position back to the start */ /* Reset has 3 simple steps: * * set position to head of list * sync enumerator with object being enumerated * return S_OK */ STDMETHODIMP CEnumMediaTypes::Reset() { m_Position = 0; // Bring the enumerator back into step with the current state. This // may be a noop but ensures that the enumerator will be valid on the // next call. m_Version = m_pPin->GetMediaTypeVersion(); return NOERROR; } //===================================================================== //===================================================================== // Implements CBasePin //===================================================================== //===================================================================== /* NOTE The implementation of this class calls the CUnknown constructor with a NULL outer unknown pointer. This has the effect of making us a self contained class, ie any QueryInterface, AddRef or Release calls will be routed to the class's NonDelegatingUnknown methods. You will typically find that the classes that do this then override one or more of these virtual functions to provide more specialised behaviour. A good example of this is where a class wants to keep the QueryInterface internal but still wants its lifetime controlled by the external object */ /* Constructor */ CBasePin::CBasePin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName, PIN_DIRECTION dir) : CUnknown(pObjectName, NULL) , m_pFilter(pFilter) , m_pLock(pLock) , m_pName(NULL) , m_Connected(NULL) , m_dir(dir) , m_bRunTimeError(FALSE) , m_pQSink(NULL) , m_TypeVersion(1) , m_tStart() , m_tStop(MAX_TIME) , m_bCanReconnectWhenActive(false) , m_bTryMyTypesFirst(false) , m_dRate(1.0) { /* WARNING - pFilter is often not a properly constituted object at this state (in particular QueryInterface may not work) - this is because its owner is often its containing object and we have been called from the containing object's constructor so the filter's owner has not yet had its CUnknown constructor called */ #ifdef DXMPERF PERFLOG_CTOR(pName ? pName : L"CBasePin", (IPin *)this); #endif // DXMPERF ASSERT(pFilter != NULL); ASSERT(pLock != NULL); if (pName) { size_t cchName; HRESULT hr = StringCchLengthW(pName, STRSAFE_MAX_CCH, &cchName); if (SUCCEEDED(hr)) { m_pName = new WCHAR[cchName + 1]; if (m_pName) { (void)StringCchCopyW(m_pName, cchName + 1, pName); } } } #ifdef DEBUG m_cRef = 0; #endif } #ifdef UNICODE CBasePin::CBasePin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName, PIN_DIRECTION dir) : CUnknown(pObjectName, NULL) , m_pFilter(pFilter) , m_pLock(pLock) , m_pName(NULL) , m_Connected(NULL) , m_dir(dir) , m_bRunTimeError(FALSE) , m_pQSink(NULL) , m_TypeVersion(1) , m_tStart() , m_tStop(MAX_TIME) , m_bCanReconnectWhenActive(false) , m_bTryMyTypesFirst(false) , m_dRate(1.0) { /* WARNING - pFilter is often not a properly constituted object at this state (in particular QueryInterface may not work) - this is because its owner is often its containing object and we have been called from the containing object's constructor so the filter's owner has not yet had its CUnknown constructor called */ #ifdef DXMPERF PERFLOG_CTOR(pName ? pName : L"CBasePin", (IPin *)this); #endif // DXMPERF ASSERT(pFilter != NULL); ASSERT(pLock != NULL); if (pName) { size_t cchName; HRESULT hr = StringCchLengthW(pName, STRSAFE_MAX_CCH, &cchName); if (SUCCEEDED(hr)) { m_pName = new WCHAR[cchName + 1]; if (m_pName) { (void)StringCchCopyW(m_pName, cchName + 1, pName); } } } #ifdef DEBUG m_cRef = 0; #endif } #endif /* Destructor since a connected pin holds a reference count on us there is no way that we can be deleted unless we are not currently connected */ CBasePin::~CBasePin() { #ifdef DXMPERF PERFLOG_DTOR(m_pName ? m_pName : L"CBasePin", (IPin *)this); #endif // DXMPERF // We don't call disconnect because if the filter is going away // all the pins must have a reference count of zero so they must // have been disconnected anyway - (but check the assumption) ASSERT(m_Connected == FALSE); delete[] m_pName; // check the internal reference count is consistent ASSERT(m_cRef == 0); } /* Override this to say what interfaces we support and where */ STDMETHODIMP CBasePin::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { /* Do we have this interface */ if (riid == IID_IPin) { return GetInterface((IPin *)this, ppv); } else if (riid == IID_IQualityControl) { return GetInterface((IQualityControl *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } /* Override to increment the owning filter's reference count */ STDMETHODIMP_(ULONG) CBasePin::NonDelegatingAddRef() { ASSERT(InterlockedIncrement(&m_cRef) > 0); return m_pFilter->AddRef(); } /* Override to decrement the owning filter's reference count */ STDMETHODIMP_(ULONG) CBasePin::NonDelegatingRelease() { ASSERT(InterlockedDecrement(&m_cRef) >= 0); return m_pFilter->Release(); } /* Displays pin connection information */ #ifdef DEBUG void CBasePin::DisplayPinInfo(IPin *pReceivePin) { if (DbgCheckModuleLevel(LOG_TRACE, CONNECT_TRACE_LEVEL)) { PIN_INFO ConnectPinInfo; PIN_INFO ReceivePinInfo; if (FAILED(QueryPinInfo(&ConnectPinInfo))) { StringCchCopyW(ConnectPinInfo.achName, sizeof(ConnectPinInfo.achName) / sizeof(WCHAR), L"Bad Pin"); } else { QueryPinInfoReleaseFilter(ConnectPinInfo); } if (FAILED(pReceivePin->QueryPinInfo(&ReceivePinInfo))) { StringCchCopyW(ReceivePinInfo.achName, sizeof(ReceivePinInfo.achName) / sizeof(WCHAR), L"Bad Pin"); } else { QueryPinInfoReleaseFilter(ReceivePinInfo); } DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Trying to connect Pins :"))); DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" <%ls>"), ConnectPinInfo.achName)); DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" <%ls>"), ReceivePinInfo.achName)); } } #endif /* Displays general information on the pin media type */ #ifdef DEBUG void CBasePin::DisplayTypeInfo(IPin *pPin, const CMediaType *pmt) { UNREFERENCED_PARAMETER(pPin); if (DbgCheckModuleLevel(LOG_TRACE, CONNECT_TRACE_LEVEL)) { DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Trying media type:"))); DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" major type: %hs"), GuidNames[*pmt->Type()])); DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT(" sub type : %hs"), GuidNames[*pmt->Subtype()])); } } #endif /* Asked to connect to a pin. A pin is always attached to an owning filter object so we always delegate our locking to that object. We first of all retrieve a media type enumerator for the input pin and see if we accept any of the formats that it would ideally like, failing that we retrieve our enumerator and see if it will accept any of our preferred types */ STDMETHODIMP CBasePin::Connect(IPin *pReceivePin, __in_opt const AM_MEDIA_TYPE *pmt // optional media type ) { CheckPointer(pReceivePin, E_POINTER); ValidateReadPtr(pReceivePin, sizeof(IPin)); CAutoLock cObjectLock(m_pLock); DisplayPinInfo(pReceivePin); /* See if we are already connected */ if (m_Connected) { DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Already connected"))); return VFW_E_ALREADY_CONNECTED; } /* See if the filter is active */ if (!IsStopped() && !m_bCanReconnectWhenActive) { return VFW_E_NOT_STOPPED; } // Find a mutually agreeable media type - // Pass in the template media type. If this is partially specified, // each of the enumerated media types will need to be checked against // it. If it is non-null and fully specified, we will just try to connect // with this. const CMediaType *ptype = (CMediaType *)pmt; HRESULT hr = AgreeMediaType(pReceivePin, ptype); if (FAILED(hr)) { DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Failed to agree type"))); // Since the procedure is already returning an error code, there // is nothing else this function can do to report the error. EXECUTE_ASSERT(SUCCEEDED(BreakConnect())); #ifdef DXMPERF PERFLOG_CONNECT((IPin *)this, pReceivePin, hr, pmt); #endif // DXMPERF return hr; } DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Connection succeeded"))); #ifdef DXMPERF PERFLOG_CONNECT((IPin *)this, pReceivePin, NOERROR, pmt); #endif // DXMPERF return NOERROR; } // given a specific media type, attempt a connection (includes // checking that the type is acceptable to this pin) HRESULT CBasePin::AttemptConnection(IPin *pReceivePin, // connect to this pin const CMediaType *pmt // using this type ) { // The caller should hold the filter lock becasue this function // uses m_Connected. The caller should also hold the filter lock // because this function calls SetMediaType(), IsStopped() and // CompleteConnect(). ASSERT(CritCheckIn(m_pLock)); // Check that the connection is valid -- need to do this for every // connect attempt since BreakConnect will undo it. HRESULT hr = CheckConnect(pReceivePin); if (FAILED(hr)) { DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("CheckConnect failed"))); // Since the procedure is already returning an error code, there // is nothing else this function can do to report the error. EXECUTE_ASSERT(SUCCEEDED(BreakConnect())); return hr; } DisplayTypeInfo(pReceivePin, pmt); /* Check we will accept this media type */ hr = CheckMediaType(pmt); if (hr == NOERROR) { /* Make ourselves look connected otherwise ReceiveConnection may not be able to complete the connection */ m_Connected = pReceivePin; m_Connected->AddRef(); hr = SetMediaType(pmt); if (SUCCEEDED(hr)) { /* See if the other pin will accept this type */ hr = pReceivePin->ReceiveConnection((IPin *)this, pmt); if (SUCCEEDED(hr)) { /* Complete the connection */ hr = CompleteConnect(pReceivePin); if (SUCCEEDED(hr)) { return hr; } else { DbgLog((LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Failed to complete connection"))); pReceivePin->Disconnect(); } } } } else { // we cannot use this media type // return a specific media type error if there is one // or map a general failure code to something more helpful // (in particular S_FALSE gets changed to an error code) if (SUCCEEDED(hr) || (hr == E_FAIL) || (hr == E_INVALIDARG)) { hr = VFW_E_TYPE_NOT_ACCEPTED; } } // BreakConnect and release any connection here in case CheckMediaType // failed, or if we set anything up during a call back during // ReceiveConnection. // Since the procedure is already returning an error code, there // is nothing else this function can do to report the error. EXECUTE_ASSERT(SUCCEEDED(BreakConnect())); /* If failed then undo our state */ if (m_Connected) { m_Connected->Release(); m_Connected = NULL; } return hr; } /* Given an enumerator we cycle through all the media types it proposes and firstly suggest them to our derived pin class and if that succeeds try them with the pin in a ReceiveConnection call. This means that if our pin proposes a media type we still check in here that we can support it. This is deliberate so that in simple cases the enumerator can hold all of the media types even if some of them are not really currently available */ HRESULT CBasePin::TryMediaTypes(IPin *pReceivePin, __in_opt const CMediaType *pmt, IEnumMediaTypes *pEnum) { /* Reset the current enumerator position */ HRESULT hr = pEnum->Reset(); if (FAILED(hr)) { return hr; } CMediaType *pMediaType = NULL; ULONG ulMediaCount = 0; // attempt to remember a specific error code if there is one HRESULT hrFailure = S_OK; for (;;) { /* Retrieve the next media type NOTE each time round the loop the enumerator interface will allocate another AM_MEDIA_TYPE structure If we are successful then we copy it into our output object, if not then we must delete the memory allocated before returning */ hr = pEnum->Next(1, (AM_MEDIA_TYPE **)&pMediaType, &ulMediaCount); if (hr != S_OK) { if (S_OK == hrFailure) { hrFailure = VFW_E_NO_ACCEPTABLE_TYPES; } return hrFailure; } ASSERT(ulMediaCount == 1); ASSERT(pMediaType); // check that this matches the partial type (if any) if (pMediaType && ((pmt == NULL) || pMediaType->MatchesPartial(pmt))) { hr = AttemptConnection(pReceivePin, pMediaType); // attempt to remember a specific error code if (FAILED(hr) && SUCCEEDED(hrFailure) && (hr != E_FAIL) && (hr != E_INVALIDARG) && (hr != VFW_E_TYPE_NOT_ACCEPTED)) { hrFailure = hr; } } else { hr = VFW_E_NO_ACCEPTABLE_TYPES; } if (pMediaType) { DeleteMediaType(pMediaType); pMediaType = NULL; } if (S_OK == hr) { return hr; } } } /* This is called to make the connection, including the taask of finding a media type for the pin connection. pmt is the proposed media type from the Connect call: if this is fully specified, we will try that. Otherwise we enumerate and try all the input pin's types first and if that fails we then enumerate and try all our preferred media types. For each media type we check it against pmt (if non-null and partially specified) as well as checking that both pins will accept it. */ HRESULT CBasePin::AgreeMediaType(IPin *pReceivePin, const CMediaType *pmt) { ASSERT(pReceivePin); IEnumMediaTypes *pEnumMediaTypes = NULL; // if the media type is fully specified then use that if ((pmt != NULL) && (!pmt->IsPartiallySpecified())) { // if this media type fails, then we must fail the connection // since if pmt is nonnull we are only allowed to connect // using a type that matches it. return AttemptConnection(pReceivePin, pmt); } /* Try the other pin's enumerator */ HRESULT hrFailure = VFW_E_NO_ACCEPTABLE_TYPES; for (int i = 0; i < 2; i++) { HRESULT hr; if (i == (int)m_bTryMyTypesFirst) { hr = pReceivePin->EnumMediaTypes(&pEnumMediaTypes); } else { hr = EnumMediaTypes(&pEnumMediaTypes); } if (SUCCEEDED(hr)) { ASSERT(pEnumMediaTypes); hr = TryMediaTypes(pReceivePin, pmt, pEnumMediaTypes); pEnumMediaTypes->Release(); if (SUCCEEDED(hr)) { return NOERROR; } else { // try to remember specific error codes if there are any if ((hr != E_FAIL) && (hr != E_INVALIDARG) && (hr != VFW_E_TYPE_NOT_ACCEPTED)) { hrFailure = hr; } } } } return hrFailure; } /* Called when we want to complete a connection to another filter. Failing this will also fail the connection and disconnect the other pin as well */ HRESULT CBasePin::CompleteConnect(IPin *pReceivePin) { UNREFERENCED_PARAMETER(pReceivePin); return NOERROR; } /* This is called to set the format for a pin connection - CheckMediaType will have been called to check the connection format and if it didn't return an error code then this (virtual) function will be invoked */ HRESULT CBasePin::SetMediaType(const CMediaType *pmt) { HRESULT hr = m_mt.Set(*pmt); if (FAILED(hr)) { return hr; } return NOERROR; } /* This is called during Connect() to provide a virtual method that can do any specific check needed for connection such as QueryInterface. This base class method just checks that the pin directions don't match */ HRESULT CBasePin::CheckConnect(IPin *pPin) { /* Check that pin directions DONT match */ PIN_DIRECTION pd; pPin->QueryDirection(&pd); ASSERT((pd == PINDIR_OUTPUT) || (pd == PINDIR_INPUT)); ASSERT((m_dir == PINDIR_OUTPUT) || (m_dir == PINDIR_INPUT)); // we should allow for non-input and non-output connections? if (pd == m_dir) { return VFW_E_INVALID_DIRECTION; } return NOERROR; } /* This is called when we realise we can't make a connection to the pin and must undo anything we did in CheckConnect - override to release QIs done */ HRESULT CBasePin::BreakConnect() { return NOERROR; } /* Called normally by an output pin on an input pin to try and establish a connection. */ STDMETHODIMP CBasePin::ReceiveConnection(IPin *pConnector, // this is the pin who we will connect to const AM_MEDIA_TYPE *pmt // this is the media type we will exchange ) { CheckPointer(pConnector, E_POINTER); CheckPointer(pmt, E_POINTER); ValidateReadPtr(pConnector, sizeof(IPin)); ValidateReadPtr(pmt, sizeof(AM_MEDIA_TYPE)); CAutoLock cObjectLock(m_pLock); /* Are we already connected */ if (m_Connected) { return VFW_E_ALREADY_CONNECTED; } /* See if the filter is active */ if (!IsStopped() && !m_bCanReconnectWhenActive) { return VFW_E_NOT_STOPPED; } HRESULT hr = CheckConnect(pConnector); if (FAILED(hr)) { // Since the procedure is already returning an error code, there // is nothing else this function can do to report the error. EXECUTE_ASSERT(SUCCEEDED(BreakConnect())); #ifdef DXMPERF PERFLOG_RXCONNECT(pConnector, (IPin *)this, hr, pmt); #endif // DXMPERF return hr; } /* Ask derived class if this media type is ok */ CMediaType *pcmt = (CMediaType *)pmt; hr = CheckMediaType(pcmt); if (hr != NOERROR) { // no -we don't support this media type // Since the procedure is already returning an error code, there // is nothing else this function can do to report the error. EXECUTE_ASSERT(SUCCEEDED(BreakConnect())); // return a specific media type error if there is one // or map a general failure code to something more helpful // (in particular S_FALSE gets changed to an error code) if (SUCCEEDED(hr) || (hr == E_FAIL) || (hr == E_INVALIDARG)) { hr = VFW_E_TYPE_NOT_ACCEPTED; } #ifdef DXMPERF PERFLOG_RXCONNECT(pConnector, (IPin *)this, hr, pmt); #endif // DXMPERF return hr; } /* Complete the connection */ m_Connected = pConnector; m_Connected->AddRef(); hr = SetMediaType(pcmt); if (SUCCEEDED(hr)) { hr = CompleteConnect(pConnector); if (SUCCEEDED(hr)) { #ifdef DXMPERF PERFLOG_RXCONNECT(pConnector, (IPin *)this, NOERROR, pmt); #endif // DXMPERF return NOERROR; } } DbgLog( (LOG_TRACE, CONNECT_TRACE_LEVEL, TEXT("Failed to set the media type or failed to complete the connection."))); m_Connected->Release(); m_Connected = NULL; // Since the procedure is already returning an error code, there // is nothing else this function can do to report the error. EXECUTE_ASSERT(SUCCEEDED(BreakConnect())); #ifdef DXMPERF PERFLOG_RXCONNECT(pConnector, (IPin *)this, hr, pmt); #endif // DXMPERF return hr; } /* Called when we want to terminate a pin connection */ STDMETHODIMP CBasePin::Disconnect() { CAutoLock cObjectLock(m_pLock); /* See if the filter is active */ if (!IsStopped()) { return VFW_E_NOT_STOPPED; } return DisconnectInternal(); } STDMETHODIMP CBasePin::DisconnectInternal() { ASSERT(CritCheckIn(m_pLock)); if (m_Connected) { HRESULT hr = BreakConnect(); if (FAILED(hr)) { #ifdef DXMPERF PERFLOG_DISCONNECT((IPin *)this, m_Connected, hr); #endif // DXMPERF // There is usually a bug in the program if BreakConnect() fails. DbgBreak("WARNING: BreakConnect() failed in CBasePin::Disconnect()."); return hr; } m_Connected->Release(); m_Connected = NULL; #ifdef DXMPERF PERFLOG_DISCONNECT((IPin *)this, m_Connected, S_OK); #endif // DXMPERF return S_OK; } else { // no connection - not an error #ifdef DXMPERF PERFLOG_DISCONNECT((IPin *)this, m_Connected, S_FALSE); #endif // DXMPERF return S_FALSE; } } /* Return an AddRef()'d pointer to the connected pin if there is one */ STDMETHODIMP CBasePin::ConnectedTo(__deref_out IPin **ppPin) { CheckPointer(ppPin, E_POINTER); ValidateReadWritePtr(ppPin, sizeof(IPin *)); // // It's pointless to lock here. // The caller should ensure integrity. // IPin *pPin = m_Connected; *ppPin = pPin; if (pPin != NULL) { pPin->AddRef(); return S_OK; } else { ASSERT(*ppPin == NULL); return VFW_E_NOT_CONNECTED; } } /* Return the media type of the connection */ STDMETHODIMP CBasePin::ConnectionMediaType(__out AM_MEDIA_TYPE *pmt) { CheckPointer(pmt, E_POINTER); ValidateReadWritePtr(pmt, sizeof(AM_MEDIA_TYPE)); CAutoLock cObjectLock(m_pLock); /* Copy constructor of m_mt allocates the memory */ if (IsConnected()) { CopyMediaType(pmt, &m_mt); return S_OK; } else { ((CMediaType *)pmt)->InitMediaType(); return VFW_E_NOT_CONNECTED; } } /* Return information about the filter we are connect to */ STDMETHODIMP CBasePin::QueryPinInfo(__out PIN_INFO *pInfo) { CheckPointer(pInfo, E_POINTER); ValidateReadWritePtr(pInfo, sizeof(PIN_INFO)); pInfo->pFilter = m_pFilter; if (m_pFilter) { m_pFilter->AddRef(); } if (m_pName) { (void)StringCchCopyW(pInfo->achName, NUMELMS(pInfo->achName), m_pName); } else { pInfo->achName[0] = L'\0'; } pInfo->dir = m_dir; return NOERROR; } STDMETHODIMP CBasePin::QueryDirection(__out PIN_DIRECTION *pPinDir) { CheckPointer(pPinDir, E_POINTER); ValidateReadWritePtr(pPinDir, sizeof(PIN_DIRECTION)); *pPinDir = m_dir; return NOERROR; } // Default QueryId to return the pin's name STDMETHODIMP CBasePin::QueryId(__deref_out LPWSTR *Id) { // We're not going away because someone's got a pointer to us // so there's no need to lock return AMGetWideString(Name(), Id); } /* Does this pin support this media type WARNING this interface function does not lock the main object as it is meant to be asynchronous by nature - if the media types you support depend on some internal state that is updated dynamically then you will need to implement locking in a derived class */ STDMETHODIMP CBasePin::QueryAccept(const AM_MEDIA_TYPE *pmt) { CheckPointer(pmt, E_POINTER); ValidateReadPtr(pmt, sizeof(AM_MEDIA_TYPE)); /* The CheckMediaType method is valid to return error codes if the media type is horrible, an example might be E_INVALIDARG. What we do here is map all the error codes into either S_OK or S_FALSE regardless */ HRESULT hr = CheckMediaType((CMediaType *)pmt); if (FAILED(hr)) { return S_FALSE; } // note that the only defined success codes should be S_OK and S_FALSE... return hr; } /* This can be called to return an enumerator for the pin's list of preferred media types. An input pin is not obliged to have any preferred formats although it can do. For example, the window renderer has a preferred type which describes a video image that matches the current window size. All output pins should expose at least one preferred format otherwise it is possible that neither pin has any types and so no connection is possible */ STDMETHODIMP CBasePin::EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum) { CheckPointer(ppEnum, E_POINTER); ValidateReadWritePtr(ppEnum, sizeof(IEnumMediaTypes *)); /* Create a new ref counted enumerator */ *ppEnum = new CEnumMediaTypes(this, NULL); if (*ppEnum == NULL) { return E_OUTOFMEMORY; } return NOERROR; } /* This is a virtual function that returns a media type corresponding with place iPosition in the list. This base class simply returns an error as we support no media types by default but derived classes should override */ HRESULT CBasePin::GetMediaType(int iPosition, __inout CMediaType *pMediaType) { UNREFERENCED_PARAMETER(iPosition); UNREFERENCED_PARAMETER(pMediaType); return E_UNEXPECTED; } /* This is a virtual function that returns the current media type version. The base class initialises the media type enumerators with the value 1 By default we always returns that same value. A Derived class may change the list of media types available and after doing so it should increment the version either in a method derived from this, or more simply by just incrementing the m_TypeVersion base pin variable. The type enumerators call this when they want to see if their enumerations are out of date */ LONG CBasePin::GetMediaTypeVersion() { return m_TypeVersion; } /* Increment the cookie representing the current media type version */ void CBasePin::IncrementTypeVersion() { InterlockedIncrement(&m_TypeVersion); } /* Called by IMediaFilter implementation when the state changes from Stopped to either paused or running and in derived classes could do things like commit memory and grab hardware resource (the default is to do nothing) */ HRESULT CBasePin::Active(void) { return NOERROR; } /* Called by IMediaFilter implementation when the state changes from to either paused to running and in derived classes could do things like commit memory and grab hardware resource (the default is to do nothing) */ HRESULT CBasePin::Run(REFERENCE_TIME tStart) { UNREFERENCED_PARAMETER(tStart); return NOERROR; } /* Also called by the IMediaFilter implementation when the state changes to Stopped at which point you should decommit allocators and free hardware resources you grabbed in the Active call (default is also to do nothing) */ HRESULT CBasePin::Inactive(void) { m_bRunTimeError = FALSE; return NOERROR; } // Called when no more data will arrive STDMETHODIMP CBasePin::EndOfStream(void) { return S_OK; } STDMETHODIMP CBasePin::SetSink(IQualityControl *piqc) { CAutoLock cObjectLock(m_pLock); if (piqc) ValidateReadPtr(piqc, sizeof(IQualityControl)); m_pQSink = piqc; return NOERROR; } // SetSink STDMETHODIMP CBasePin::Notify(IBaseFilter *pSender, Quality q) { UNREFERENCED_PARAMETER(q); UNREFERENCED_PARAMETER(pSender); DbgBreak("IQualityControl::Notify not over-ridden from CBasePin. (IGNORE is OK)"); return E_NOTIMPL; } // Notify // NewSegment notifies of the start/stop/rate applying to the data // about to be received. Default implementation records data and // returns S_OK. // Override this to pass downstream. STDMETHODIMP CBasePin::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { m_tStart = tStart; m_tStop = tStop; m_dRate = dRate; return S_OK; } //===================================================================== //===================================================================== // Implements CBaseOutputPin //===================================================================== //===================================================================== CBaseOutputPin::CBaseOutputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBasePin(pObjectName, pFilter, pLock, phr, pName, PINDIR_OUTPUT) , m_pAllocator(NULL) , m_pInputPin(NULL) { ASSERT(pFilter); } #ifdef UNICODE CBaseOutputPin::CBaseOutputPin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBasePin(pObjectName, pFilter, pLock, phr, pName, PINDIR_OUTPUT) , m_pAllocator(NULL) , m_pInputPin(NULL) { ASSERT(pFilter); } #endif /* This is called after a media type has been proposed Try to complete the connection by agreeing the allocator */ HRESULT CBaseOutputPin::CompleteConnect(IPin *pReceivePin) { UNREFERENCED_PARAMETER(pReceivePin); return DecideAllocator(m_pInputPin, &m_pAllocator); } /* This method is called when the output pin is about to try and connect to an input pin. It is at this point that you should try and grab any extra interfaces that you need, in this case IMemInputPin. Because this is only called if we are not currently connected we do NOT need to call BreakConnect. This also makes it easier to derive classes from us as BreakConnect is only called when we actually have to break a connection (or a partly made connection) and not when we are checking a connection */ /* Overriden from CBasePin */ HRESULT CBaseOutputPin::CheckConnect(IPin *pPin) { HRESULT hr = CBasePin::CheckConnect(pPin); if (FAILED(hr)) { return hr; } // get an input pin and an allocator interface hr = pPin->QueryInterface(IID_IMemInputPin, (void **)&m_pInputPin); if (FAILED(hr)) { return hr; } return NOERROR; } /* Overriden from CBasePin */ HRESULT CBaseOutputPin::BreakConnect() { /* Release any allocator we hold */ if (m_pAllocator) { // Always decommit the allocator because a downstream filter may or // may not decommit the connection's allocator. A memory leak could // occur if the allocator is not decommited when a connection is broken. HRESULT hr = m_pAllocator->Decommit(); if (FAILED(hr)) { return hr; } m_pAllocator->Release(); m_pAllocator = NULL; } /* Release any input pin interface we hold */ if (m_pInputPin) { m_pInputPin->Release(); m_pInputPin = NULL; } return NOERROR; } /* This is called when the input pin didn't give us a valid allocator */ HRESULT CBaseOutputPin::InitAllocator(__deref_out IMemAllocator **ppAlloc) { return CreateMemoryAllocator(ppAlloc); } /* Decide on an allocator, override this if you want to use your own allocator Override DecideBufferSize to call SetProperties. If the input pin fails the GetAllocator call then this will construct a CMemAllocator and call DecideBufferSize on that, and if that fails then we are completely hosed. If the you succeed the DecideBufferSize call, we will notify the input pin of the selected allocator. NOTE this is called during Connect() which therefore looks after grabbing and locking the object's critical section */ // We query the input pin for its requested properties and pass this to // DecideBufferSize to allow it to fulfill requests that it is happy // with (eg most people don't care about alignment and are thus happy to // use the downstream pin's alignment request). HRESULT CBaseOutputPin::DecideAllocator(IMemInputPin *pPin, __deref_out IMemAllocator **ppAlloc) { HRESULT hr = NOERROR; *ppAlloc = NULL; // get downstream prop request // the derived class may modify this in DecideBufferSize, but // we assume that he will consistently modify it the same way, // so we only get it once ALLOCATOR_PROPERTIES prop; ZeroMemory(&prop, sizeof(prop)); // whatever he returns, we assume prop is either all zeros // or he has filled it out. pPin->GetAllocatorRequirements(&prop); // if he doesn't care about alignment, then set it to 1 if (prop.cbAlign == 0) { prop.cbAlign = 1; } /* Try the allocator provided by the input pin */ hr = pPin->GetAllocator(ppAlloc); if (SUCCEEDED(hr)) { hr = DecideBufferSize(*ppAlloc, &prop); if (SUCCEEDED(hr)) { hr = pPin->NotifyAllocator(*ppAlloc, FALSE); if (SUCCEEDED(hr)) { return NOERROR; } } } /* If the GetAllocator failed we may not have an interface */ if (*ppAlloc) { (*ppAlloc)->Release(); *ppAlloc = NULL; } /* Try the output pin's allocator by the same method */ hr = InitAllocator(ppAlloc); if (SUCCEEDED(hr)) { // note - the properties passed here are in the same // structure as above and may have been modified by // the previous call to DecideBufferSize hr = DecideBufferSize(*ppAlloc, &prop); if (SUCCEEDED(hr)) { hr = pPin->NotifyAllocator(*ppAlloc, FALSE); if (SUCCEEDED(hr)) { return NOERROR; } } } /* Likewise we may not have an interface to release */ if (*ppAlloc) { (*ppAlloc)->Release(); *ppAlloc = NULL; } return hr; } /* This returns an empty sample buffer from the allocator WARNING the same dangers and restrictions apply here as described below for Deliver() */ HRESULT CBaseOutputPin::GetDeliveryBuffer(__deref_out IMediaSample **ppSample, __in_opt REFERENCE_TIME *pStartTime, __in_opt REFERENCE_TIME *pEndTime, DWORD dwFlags) { if (m_pAllocator != NULL) { return m_pAllocator->GetBuffer(ppSample, pStartTime, pEndTime, dwFlags); } else { return E_NOINTERFACE; } } /* Deliver a filled-in sample to the connected input pin. NOTE the object must have locked itself before calling us otherwise we may get halfway through executing this method only to find the filter graph has got in and disconnected us from the input pin. If the filter has no worker threads then the lock is best applied on Receive(), otherwise it should be done when the worker thread is ready to deliver. There is a wee snag to worker threads that this shows up. The worker thread must lock the object when it is ready to deliver a sample, but it may have to wait until a state change has completed, but that may never complete because the state change is waiting for the worker thread to complete. The way to handle this is for the state change code to grab the critical section, then set an abort event for the worker thread, then release the critical section and wait for the worker thread to see the event we set and then signal that it has finished (with another event). At which point the state change code can complete */ // note (if you've still got any breath left after reading that) that you // need to release the sample yourself after this call. if the connected // input pin needs to hold onto the sample beyond the call, it will addref // the sample itself. // of course you must release this one and call GetDeliveryBuffer for the // next. You cannot reuse it directly. HRESULT CBaseOutputPin::Deliver(IMediaSample *pSample) { if (m_pInputPin == NULL) { return VFW_E_NOT_CONNECTED; } #ifdef DXMPERF PERFLOG_DELIVER(m_pName ? m_pName : L"CBaseOutputPin", (IPin *)this, (IPin *)m_pInputPin, pSample, &m_mt); #endif // DXMPERF return m_pInputPin->Receive(pSample); } // called from elsewhere in our filter to pass EOS downstream to // our connected input pin HRESULT CBaseOutputPin::DeliverEndOfStream(void) { // remember this is on IPin not IMemInputPin if (m_Connected == NULL) { return VFW_E_NOT_CONNECTED; } return m_Connected->EndOfStream(); } /* Commit the allocator's memory, this is called through IMediaFilter which is responsible for locking the object before calling us */ HRESULT CBaseOutputPin::Active(void) { if (m_pAllocator == NULL) { return VFW_E_NO_ALLOCATOR; } return m_pAllocator->Commit(); } /* Free up or unprepare allocator's memory, this is called through IMediaFilter which is responsible for locking the object first */ HRESULT CBaseOutputPin::Inactive(void) { m_bRunTimeError = FALSE; if (m_pAllocator == NULL) { return VFW_E_NO_ALLOCATOR; } return m_pAllocator->Decommit(); } // we have a default handling of EndOfStream which is to return // an error, since this should be called on input pins only STDMETHODIMP CBaseOutputPin::EndOfStream(void) { return E_UNEXPECTED; } // BeginFlush should be called on input pins only STDMETHODIMP CBaseOutputPin::BeginFlush(void) { return E_UNEXPECTED; } // EndFlush should be called on input pins only STDMETHODIMP CBaseOutputPin::EndFlush(void) { return E_UNEXPECTED; } // call BeginFlush on the connected input pin HRESULT CBaseOutputPin::DeliverBeginFlush(void) { // remember this is on IPin not IMemInputPin if (m_Connected == NULL) { return VFW_E_NOT_CONNECTED; } return m_Connected->BeginFlush(); } // call EndFlush on the connected input pin HRESULT CBaseOutputPin::DeliverEndFlush(void) { // remember this is on IPin not IMemInputPin if (m_Connected == NULL) { return VFW_E_NOT_CONNECTED; } return m_Connected->EndFlush(); } // deliver NewSegment to connected pin HRESULT CBaseOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { if (m_Connected == NULL) { return VFW_E_NOT_CONNECTED; } return m_Connected->NewSegment(tStart, tStop, dRate); } //===================================================================== //===================================================================== // Implements CBaseInputPin //===================================================================== //===================================================================== /* Constructor creates a default allocator object */ CBaseInputPin::CBaseInputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pPinName) : CBasePin(pObjectName, pFilter, pLock, phr, pPinName, PINDIR_INPUT) , m_pAllocator(NULL) , m_bReadOnly(FALSE) , m_bFlushing(FALSE) { ZeroMemory(&m_SampleProps, sizeof(m_SampleProps)); } #ifdef UNICODE CBaseInputPin::CBaseInputPin(__in LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pPinName) : CBasePin(pObjectName, pFilter, pLock, phr, pPinName, PINDIR_INPUT) , m_pAllocator(NULL) , m_bReadOnly(FALSE) , m_bFlushing(FALSE) { ZeroMemory(&m_SampleProps, sizeof(m_SampleProps)); } #endif /* Destructor releases it's reference count on the default allocator */ CBaseInputPin::~CBaseInputPin() { if (m_pAllocator != NULL) { m_pAllocator->Release(); m_pAllocator = NULL; } } // override this to publicise our interfaces STDMETHODIMP CBaseInputPin::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { /* Do we know about this interface */ if (riid == IID_IMemInputPin) { return GetInterface((IMemInputPin *)this, ppv); } else { return CBasePin::NonDelegatingQueryInterface(riid, ppv); } } /* Return the allocator interface that this input pin would like the output pin to use. NOTE subsequent calls to GetAllocator should all return an interface onto the SAME object so we create one object at the start Note: The allocator is Release()'d on disconnect and replaced on NotifyAllocator(). Override this to provide your own allocator. */ STDMETHODIMP CBaseInputPin::GetAllocator(__deref_out IMemAllocator **ppAllocator) { CheckPointer(ppAllocator, E_POINTER); ValidateReadWritePtr(ppAllocator, sizeof(IMemAllocator *)); CAutoLock cObjectLock(m_pLock); if (m_pAllocator == NULL) { HRESULT hr = CreateMemoryAllocator(&m_pAllocator); if (FAILED(hr)) { return hr; } } ASSERT(m_pAllocator != NULL); *ppAllocator = m_pAllocator; m_pAllocator->AddRef(); return NOERROR; } /* Tell the input pin which allocator the output pin is actually going to use Override this if you care - NOTE the locking we do both here and also in GetAllocator is unnecessary but derived classes that do something useful will undoubtedly have to lock the object so this might help remind people */ STDMETHODIMP CBaseInputPin::NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly) { CheckPointer(pAllocator, E_POINTER); ValidateReadPtr(pAllocator, sizeof(IMemAllocator)); CAutoLock cObjectLock(m_pLock); IMemAllocator *pOldAllocator = m_pAllocator; pAllocator->AddRef(); m_pAllocator = pAllocator; if (pOldAllocator != NULL) { pOldAllocator->Release(); } // the readonly flag indicates whether samples from this allocator should // be regarded as readonly - if true, then inplace transforms will not be // allowed. m_bReadOnly = (BYTE)bReadOnly; return NOERROR; } HRESULT CBaseInputPin::BreakConnect() { /* We don't need our allocator any more */ if (m_pAllocator) { // Always decommit the allocator because a downstream filter may or // may not decommit the connection's allocator. A memory leak could // occur if the allocator is not decommited when a pin is disconnected. HRESULT hr = m_pAllocator->Decommit(); if (FAILED(hr)) { return hr; } m_pAllocator->Release(); m_pAllocator = NULL; } return S_OK; } /* Do something with this media sample - this base class checks to see if the format has changed with this media sample and if so checks that the filter will accept it, generating a run time error if not. Once we have raised a run time error we set a flag so that no more samples will be accepted It is important that any filter should override this method and implement synchronization so that samples are not processed when the pin is disconnected etc */ STDMETHODIMP CBaseInputPin::Receive(IMediaSample *pSample) { CheckPointer(pSample, E_POINTER); ValidateReadPtr(pSample, sizeof(IMediaSample)); ASSERT(pSample); HRESULT hr = CheckStreaming(); if (S_OK != hr) { return hr; } #ifdef DXMPERF PERFLOG_RECEIVE(m_pName ? m_pName : L"CBaseInputPin", (IPin *)m_Connected, (IPin *)this, pSample, &m_mt); #endif // DXMPERF /* Check for IMediaSample2 */ IMediaSample2 *pSample2; if (SUCCEEDED(pSample->QueryInterface(IID_IMediaSample2, (void **)&pSample2))) { hr = pSample2->GetProperties(sizeof(m_SampleProps), (PBYTE)&m_SampleProps); pSample2->Release(); if (FAILED(hr)) { return hr; } } else { /* Get the properties the hard way */ m_SampleProps.cbData = sizeof(m_SampleProps); m_SampleProps.dwTypeSpecificFlags = 0; m_SampleProps.dwStreamId = AM_STREAM_MEDIA; m_SampleProps.dwSampleFlags = 0; if (S_OK == pSample->IsDiscontinuity()) { m_SampleProps.dwSampleFlags |= AM_SAMPLE_DATADISCONTINUITY; } if (S_OK == pSample->IsPreroll()) { m_SampleProps.dwSampleFlags |= AM_SAMPLE_PREROLL; } if (S_OK == pSample->IsSyncPoint()) { m_SampleProps.dwSampleFlags |= AM_SAMPLE_SPLICEPOINT; } if (SUCCEEDED(pSample->GetTime(&m_SampleProps.tStart, &m_SampleProps.tStop))) { m_SampleProps.dwSampleFlags |= AM_SAMPLE_TIMEVALID | AM_SAMPLE_STOPVALID; } if (S_OK == pSample->GetMediaType(&m_SampleProps.pMediaType)) { m_SampleProps.dwSampleFlags |= AM_SAMPLE_TYPECHANGED; } pSample->GetPointer(&m_SampleProps.pbBuffer); m_SampleProps.lActual = pSample->GetActualDataLength(); m_SampleProps.cbBuffer = pSample->GetSize(); } /* Has the format changed in this sample */ if (!(m_SampleProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED)) { return NOERROR; } /* Check the derived class accepts this format */ /* This shouldn't fail as the source must call QueryAccept first */ hr = CheckMediaType((CMediaType *)m_SampleProps.pMediaType); if (hr == NOERROR) { return NOERROR; } /* Raise a runtime error if we fail the media type */ m_bRunTimeError = TRUE; EndOfStream(); m_pFilter->NotifyEvent(EC_ERRORABORT, VFW_E_TYPE_NOT_ACCEPTED, 0); return VFW_E_INVALIDMEDIATYPE; } /* Receive multiple samples */ STDMETHODIMP CBaseInputPin::ReceiveMultiple(__in_ecount(nSamples) IMediaSample **pSamples, long nSamples, __out long *nSamplesProcessed) { CheckPointer(pSamples, E_POINTER); ValidateReadPtr(pSamples, nSamples * sizeof(IMediaSample *)); HRESULT hr = S_OK; *nSamplesProcessed = 0; while (nSamples-- > 0) { hr = Receive(pSamples[*nSamplesProcessed]); /* S_FALSE means don't send any more */ if (hr != S_OK) { break; } (*nSamplesProcessed)++; } return hr; } /* See if Receive() might block */ STDMETHODIMP CBaseInputPin::ReceiveCanBlock() { /* Ask all the output pins if they block If there are no output pin assume we do block */ int cPins = m_pFilter->GetPinCount(); int cOutputPins = 0; for (int c = 0; c < cPins; c++) { CBasePin *pPin = m_pFilter->GetPin(c); if (NULL == pPin) { break; } PIN_DIRECTION pd; HRESULT hr = pPin->QueryDirection(&pd); if (FAILED(hr)) { return hr; } if (pd == PINDIR_OUTPUT) { IPin *pConnected; hr = pPin->ConnectedTo(&pConnected); if (SUCCEEDED(hr)) { ASSERT(pConnected != NULL); cOutputPins++; IMemInputPin *pInputPin; hr = pConnected->QueryInterface(IID_IMemInputPin, (void **)&pInputPin); pConnected->Release(); if (SUCCEEDED(hr)) { hr = pInputPin->ReceiveCanBlock(); pInputPin->Release(); if (hr != S_FALSE) { return S_OK; } } else { /* There's a transport we don't understand here */ return S_OK; } } } } return cOutputPins == 0 ? S_OK : S_FALSE; } // Default handling for BeginFlush - call at the beginning // of your implementation (makes sure that all Receive calls // fail). After calling this, you need to free any queued data // and then call downstream. STDMETHODIMP CBaseInputPin::BeginFlush(void) { // BeginFlush is NOT synchronized with streaming but is part of // a control action - hence we synchronize with the filter CAutoLock lck(m_pLock); // if we are already in mid-flush, this is probably a mistake // though not harmful - try to pick it up for now so I can think about it ASSERT(!m_bFlushing); // first thing to do is ensure that no further Receive calls succeed m_bFlushing = TRUE; // now discard any data and call downstream - must do that // in derived classes return S_OK; } // default handling for EndFlush - call at end of your implementation // - before calling this, ensure that there is no queued data and no thread // pushing any more without a further receive, then call downstream, // then call this method to clear the m_bFlushing flag and re-enable // receives STDMETHODIMP CBaseInputPin::EndFlush(void) { // Endlush is NOT synchronized with streaming but is part of // a control action - hence we synchronize with the filter CAutoLock lck(m_pLock); // almost certainly a mistake if we are not in mid-flush ASSERT(m_bFlushing); // before calling, sync with pushing thread and ensure // no more data is going downstream, then call EndFlush on // downstream pins. // now re-enable Receives m_bFlushing = FALSE; // No more errors m_bRunTimeError = FALSE; return S_OK; } STDMETHODIMP CBaseInputPin::Notify(IBaseFilter *pSender, Quality q) { UNREFERENCED_PARAMETER(q); CheckPointer(pSender, E_POINTER); ValidateReadPtr(pSender, sizeof(IBaseFilter)); DbgBreak("IQuality::Notify called on an input pin"); return NOERROR; } // Notify /* Free up or unprepare allocator's memory, this is called through IMediaFilter which is responsible for locking the object first */ HRESULT CBaseInputPin::Inactive(void) { m_bRunTimeError = FALSE; if (m_pAllocator == NULL) { return VFW_E_NO_ALLOCATOR; } m_bFlushing = FALSE; return m_pAllocator->Decommit(); } // what requirements do we have of the allocator - override if you want // to support other people's allocators but need a specific alignment // or prefix. STDMETHODIMP CBaseInputPin::GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES *pProps) { UNREFERENCED_PARAMETER(pProps); return E_NOTIMPL; } // Check if it's OK to process data // HRESULT CBaseInputPin::CheckStreaming() { // Shouldn't be able to get any data if we're not connected! ASSERT(IsConnected()); // Don't process stuff in Stopped state if (IsStopped()) { return VFW_E_WRONG_STATE; } if (m_bFlushing) { return S_FALSE; } if (m_bRunTimeError) { return VFW_E_RUNTIME_ERROR; } return S_OK; } // Pass on the Quality notification q to // a. Our QualityControl sink (if we have one) or else // b. to our upstream filter // and if that doesn't work, throw it away with a bad return code HRESULT CBaseInputPin::PassNotify(Quality &q) { // We pass the message on, which means that we find the quality sink // for our input pin and send it there // DbgLog((LOG_TRACE,3,TEXT("Passing Quality notification through transform"))); if (m_pQSink != NULL) { return m_pQSink->Notify(m_pFilter, q); } else { // no sink set, so pass it upstream HRESULT hr; IQualityControl *pIQC; hr = VFW_E_NOT_FOUND; // default if (m_Connected) { m_Connected->QueryInterface(IID_IQualityControl, (void **)&pIQC); if (pIQC != NULL) { hr = pIQC->Notify(m_pFilter, q); pIQC->Release(); } } return hr; } } // PassNotify //===================================================================== //===================================================================== // Memory allocation class, implements CMediaSample //===================================================================== //===================================================================== /* NOTE The implementation of this class calls the CUnknown constructor with a NULL outer unknown pointer. This has the effect of making us a self contained class, ie any QueryInterface, AddRef or Release calls will be routed to the class's NonDelegatingUnknown methods. You will typically find that the classes that do this then override one or more of these virtual functions to provide more specialised behaviour. A good example of this is where a class wants to keep the QueryInterface internal but still wants it's lifetime controlled by the external object */ /* The last two parameters have default values of NULL and zero */ CMediaSample::CMediaSample(__in_opt LPCTSTR pName, __in_opt CBaseAllocator *pAllocator, __inout_opt HRESULT *phr, __in_bcount_opt(length) LPBYTE pBuffer, LONG length) : m_pBuffer(pBuffer) , // Initialise the buffer m_cbBuffer(length) , // And it's length m_lActual(length) , // By default, actual = length m_pMediaType(NULL) , // No media type change m_dwFlags(0) , // Nothing set m_cRef(0) , // 0 ref count m_dwTypeSpecificFlags(0) , // Type specific flags m_dwStreamId(AM_STREAM_MEDIA) , // Stream id m_pAllocator(pAllocator) // Allocator { #ifdef DXMPERF PERFLOG_CTOR(pName ? pName : L"CMediaSample", (IMediaSample *)this); #endif // DXMPERF /* We must have an owner and it must also be derived from class CBaseAllocator BUT we do not hold a reference count on it */ ASSERT(pAllocator); if (length < 0) { *phr = VFW_E_BUFFER_OVERFLOW; m_cbBuffer = 0; } } #ifdef UNICODE CMediaSample::CMediaSample(__in_opt LPCSTR pName, __in_opt CBaseAllocator *pAllocator, __inout_opt HRESULT *phr, __in_bcount_opt(length) LPBYTE pBuffer, LONG length) : m_pBuffer(pBuffer) , // Initialise the buffer m_cbBuffer(length) , // And it's length m_lActual(length) , // By default, actual = length m_pMediaType(NULL) , // No media type change m_dwFlags(0) , // Nothing set m_cRef(0) , // 0 ref count m_dwTypeSpecificFlags(0) , // Type specific flags m_dwStreamId(AM_STREAM_MEDIA) , // Stream id m_pAllocator(pAllocator) // Allocator { #ifdef DXMPERF PERFLOG_CTOR(L"CMediaSample", (IMediaSample *)this); #endif // DXMPERF /* We must have an owner and it must also be derived from class CBaseAllocator BUT we do not hold a reference count on it */ ASSERT(pAllocator); } #endif /* Destructor deletes the media type memory */ CMediaSample::~CMediaSample() { #ifdef DXMPERF PERFLOG_DTOR(L"CMediaSample", (IMediaSample *)this); #endif // DXMPERF if (m_pMediaType) { DeleteMediaType(m_pMediaType); } } /* Override this to publicise our interfaces */ STDMETHODIMP CMediaSample::QueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_IMediaSample || riid == IID_IMediaSample2 || riid == IID_IUnknown) { return GetInterface((IMediaSample *)this, ppv); } else { *ppv = NULL; return E_NOINTERFACE; } } STDMETHODIMP_(ULONG) CMediaSample::AddRef() { return InterlockedIncrement(&m_cRef); } // -- CMediaSample lifetimes -- // // On final release of this sample buffer it is not deleted but // returned to the freelist of the owning memory allocator // // The allocator may be waiting for the last buffer to be placed on the free // list in order to decommit all the memory, so the ReleaseBuffer() call may // result in this sample being deleted. We also need to hold a refcount on // the allocator to stop that going away until we have finished with this. // However, we cannot release the allocator before the ReleaseBuffer, as the // release may cause us to be deleted. Similarly we can't do it afterwards. // // Thus we must leave it to the allocator to hold an addref on our behalf. // When he issues us in GetBuffer, he addref's himself. When ReleaseBuffer // is called, he releases himself, possibly causing us and him to be deleted. STDMETHODIMP_(ULONG) CMediaSample::Release() { /* Decrement our own private reference count */ LONG lRef; if (m_cRef == 1) { lRef = 0; m_cRef = 0; } else { lRef = InterlockedDecrement(&m_cRef); } ASSERT(lRef >= 0); DbgLog((LOG_MEMORY, 3, TEXT(" Unknown %X ref-- = %d"), this, m_cRef)); /* Did we release our final reference count */ if (lRef == 0) { /* Free all resources */ if (m_dwFlags & Sample_TypeChanged) { SetMediaType(NULL); } ASSERT(m_pMediaType == NULL); m_dwFlags = 0; m_dwTypeSpecificFlags = 0; m_dwStreamId = AM_STREAM_MEDIA; /* This may cause us to be deleted */ // Our refcount is reliably 0 thus no-one will mess with us m_pAllocator->ReleaseBuffer(this); } return (ULONG)lRef; } // set the buffer pointer and length. Used by allocators that // want variable sized pointers or pointers into already-read data. // This is only available through a CMediaSample* not an IMediaSample* // and so cannot be changed by clients. HRESULT CMediaSample::SetPointer(__in_bcount(cBytes) BYTE *ptr, LONG cBytes) { if (cBytes < 0) { return VFW_E_BUFFER_OVERFLOW; } m_pBuffer = ptr; // new buffer area (could be null) m_cbBuffer = cBytes; // length of buffer m_lActual = cBytes; // length of data in buffer (assume full) return S_OK; } // get me a read/write pointer to this buffer's memory. I will actually // want to use sizeUsed bytes. STDMETHODIMP CMediaSample::GetPointer(__deref_out BYTE **ppBuffer) { ValidateReadWritePtr(ppBuffer, sizeof(BYTE *)); // creator must have set pointer either during // constructor or by SetPointer ASSERT(m_pBuffer); *ppBuffer = m_pBuffer; return NOERROR; } // return the size in bytes of this buffer STDMETHODIMP_(LONG) CMediaSample::GetSize(void) { return m_cbBuffer; } // get the stream time at which this sample should start and finish. STDMETHODIMP CMediaSample::GetTime(__out REFERENCE_TIME *pTimeStart, // put time here __out REFERENCE_TIME *pTimeEnd) { ValidateReadWritePtr(pTimeStart, sizeof(REFERENCE_TIME)); ValidateReadWritePtr(pTimeEnd, sizeof(REFERENCE_TIME)); if (!(m_dwFlags & Sample_StopValid)) { if (!(m_dwFlags & Sample_TimeValid)) { return VFW_E_SAMPLE_TIME_NOT_SET; } else { *pTimeStart = m_Start; // Make sure old stuff works *pTimeEnd = m_Start + 1; return VFW_S_NO_STOP_TIME; } } *pTimeStart = m_Start; *pTimeEnd = m_End; return NOERROR; } // Set the stream time at which this sample should start and finish. // NULL pointers means the time is reset STDMETHODIMP CMediaSample::SetTime(__in_opt REFERENCE_TIME *pTimeStart, __in_opt REFERENCE_TIME *pTimeEnd) { if (pTimeStart == NULL) { ASSERT(pTimeEnd == NULL); m_dwFlags &= ~(Sample_TimeValid | Sample_StopValid); } else { if (pTimeEnd == NULL) { m_Start = *pTimeStart; m_dwFlags |= Sample_TimeValid; m_dwFlags &= ~Sample_StopValid; } else { ValidateReadPtr(pTimeStart, sizeof(REFERENCE_TIME)); ValidateReadPtr(pTimeEnd, sizeof(REFERENCE_TIME)); ASSERT(*pTimeEnd >= *pTimeStart); m_Start = *pTimeStart; m_End = *pTimeEnd; m_dwFlags |= Sample_TimeValid | Sample_StopValid; } } return NOERROR; } // get the media times (eg bytes) for this sample STDMETHODIMP CMediaSample::GetMediaTime(__out LONGLONG *pTimeStart, __out LONGLONG *pTimeEnd) { ValidateReadWritePtr(pTimeStart, sizeof(LONGLONG)); ValidateReadWritePtr(pTimeEnd, sizeof(LONGLONG)); if (!(m_dwFlags & Sample_MediaTimeValid)) { return VFW_E_MEDIA_TIME_NOT_SET; } *pTimeStart = m_MediaStart; *pTimeEnd = (m_MediaStart + m_MediaEnd); return NOERROR; } // Set the media times for this sample STDMETHODIMP CMediaSample::SetMediaTime(__in_opt LONGLONG *pTimeStart, __in_opt LONGLONG *pTimeEnd) { if (pTimeStart == NULL) { ASSERT(pTimeEnd == NULL); m_dwFlags &= ~Sample_MediaTimeValid; } else { if (NULL == pTimeEnd) { return E_POINTER; } ValidateReadPtr(pTimeStart, sizeof(LONGLONG)); ValidateReadPtr(pTimeEnd, sizeof(LONGLONG)); ASSERT(*pTimeEnd >= *pTimeStart); m_MediaStart = *pTimeStart; m_MediaEnd = (LONG)(*pTimeEnd - *pTimeStart); m_dwFlags |= Sample_MediaTimeValid; } return NOERROR; } STDMETHODIMP CMediaSample::IsSyncPoint(void) { if (m_dwFlags & Sample_SyncPoint) { return S_OK; } else { return S_FALSE; } } STDMETHODIMP CMediaSample::SetSyncPoint(BOOL bIsSyncPoint) { if (bIsSyncPoint) { m_dwFlags |= Sample_SyncPoint; } else { m_dwFlags &= ~Sample_SyncPoint; } return NOERROR; } // returns S_OK if there is a discontinuity in the data (this same is // not a continuation of the previous stream of data // - there has been a seek). STDMETHODIMP CMediaSample::IsDiscontinuity(void) { if (m_dwFlags & Sample_Discontinuity) { return S_OK; } else { return S_FALSE; } } // set the discontinuity property - TRUE if this sample is not a // continuation, but a new sample after a seek. STDMETHODIMP CMediaSample::SetDiscontinuity(BOOL bDiscont) { // should be TRUE or FALSE if (bDiscont) { m_dwFlags |= Sample_Discontinuity; } else { m_dwFlags &= ~Sample_Discontinuity; } return S_OK; } STDMETHODIMP CMediaSample::IsPreroll(void) { if (m_dwFlags & Sample_Preroll) { return S_OK; } else { return S_FALSE; } } STDMETHODIMP CMediaSample::SetPreroll(BOOL bIsPreroll) { if (bIsPreroll) { m_dwFlags |= Sample_Preroll; } else { m_dwFlags &= ~Sample_Preroll; } return NOERROR; } STDMETHODIMP_(LONG) CMediaSample::GetActualDataLength(void) { return m_lActual; } STDMETHODIMP CMediaSample::SetActualDataLength(LONG lActual) { if (lActual > m_cbBuffer || lActual < 0) { ASSERT(lActual <= GetSize()); return VFW_E_BUFFER_OVERFLOW; } m_lActual = lActual; return NOERROR; } /* These allow for limited format changes in band */ STDMETHODIMP CMediaSample::GetMediaType(__deref_out AM_MEDIA_TYPE **ppMediaType) { ValidateReadWritePtr(ppMediaType, sizeof(AM_MEDIA_TYPE *)); ASSERT(ppMediaType); /* Do we have a new media type for them */ if (!(m_dwFlags & Sample_TypeChanged)) { ASSERT(m_pMediaType == NULL); *ppMediaType = NULL; return S_FALSE; } ASSERT(m_pMediaType); /* Create a copy of our media type */ *ppMediaType = CreateMediaType(m_pMediaType); if (*ppMediaType == NULL) { return E_OUTOFMEMORY; } return NOERROR; } /* Mark this sample as having a different format type */ STDMETHODIMP CMediaSample::SetMediaType(__in_opt AM_MEDIA_TYPE *pMediaType) { /* Delete the current media type */ if (m_pMediaType) { DeleteMediaType(m_pMediaType); m_pMediaType = NULL; } /* Mechanism for resetting the format type */ if (pMediaType == NULL) { m_dwFlags &= ~Sample_TypeChanged; return NOERROR; } ASSERT(pMediaType); ValidateReadPtr(pMediaType, sizeof(AM_MEDIA_TYPE)); /* Take a copy of the media type */ m_pMediaType = CreateMediaType(pMediaType); if (m_pMediaType == NULL) { m_dwFlags &= ~Sample_TypeChanged; return E_OUTOFMEMORY; } m_dwFlags |= Sample_TypeChanged; return NOERROR; } // Set and get properties (IMediaSample2) STDMETHODIMP CMediaSample::GetProperties(DWORD cbProperties, __out_bcount(cbProperties) BYTE *pbProperties) { if (0 != cbProperties) { CheckPointer(pbProperties, E_POINTER); // Return generic stuff up to the length AM_SAMPLE2_PROPERTIES Props; Props.cbData = min(cbProperties, sizeof(Props)); Props.dwSampleFlags = m_dwFlags & ~Sample_MediaTimeValid; Props.dwTypeSpecificFlags = m_dwTypeSpecificFlags; Props.pbBuffer = m_pBuffer; Props.cbBuffer = m_cbBuffer; Props.lActual = m_lActual; Props.tStart = m_Start; Props.tStop = m_End; Props.dwStreamId = m_dwStreamId; if (m_dwFlags & AM_SAMPLE_TYPECHANGED) { Props.pMediaType = m_pMediaType; } else { Props.pMediaType = NULL; } CopyMemory(pbProperties, &Props, Props.cbData); } return S_OK; } #define CONTAINS_FIELD(type, field, offset) ((FIELD_OFFSET(type, field) + sizeof(((type *)0)->field)) <= offset) HRESULT CMediaSample::SetProperties(DWORD cbProperties, __in_bcount(cbProperties) const BYTE *pbProperties) { /* Generic properties */ AM_MEDIA_TYPE *pMediaType = NULL; if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbData, cbProperties)) { CheckPointer(pbProperties, E_POINTER); AM_SAMPLE2_PROPERTIES *pProps = (AM_SAMPLE2_PROPERTIES *)pbProperties; /* Don't use more data than is actually there */ if (pProps->cbData < cbProperties) { cbProperties = pProps->cbData; } /* We only handle IMediaSample2 */ if (cbProperties > sizeof(*pProps) || pProps->cbData > sizeof(*pProps)) { return E_INVALIDARG; } /* Do checks first, the assignments (for backout) */ if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwSampleFlags, cbProperties)) { /* Check the flags */ if (pProps->dwSampleFlags & (~Sample_ValidFlags | Sample_MediaTimeValid)) { return E_INVALIDARG; } /* Check a flag isn't being set for a property not being provided */ if ((pProps->dwSampleFlags & AM_SAMPLE_TIMEVALID) && !(m_dwFlags & AM_SAMPLE_TIMEVALID) && !CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStop, cbProperties)) { return E_INVALIDARG; } } /* NB - can't SET the pointer or size */ if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pbBuffer, cbProperties)) { /* Check pbBuffer */ if (pProps->pbBuffer != 0 && pProps->pbBuffer != m_pBuffer) { return E_INVALIDARG; } } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbBuffer, cbProperties)) { /* Check cbBuffer */ if (pProps->cbBuffer != 0 && pProps->cbBuffer != m_cbBuffer) { return E_INVALIDARG; } } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, cbBuffer, cbProperties) && CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, lActual, cbProperties)) { /* Check lActual */ if (pProps->cbBuffer < pProps->lActual) { return E_INVALIDARG; } } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pMediaType, cbProperties)) { /* Check pMediaType */ if (pProps->dwSampleFlags & AM_SAMPLE_TYPECHANGED) { CheckPointer(pProps->pMediaType, E_POINTER); pMediaType = CreateMediaType(pProps->pMediaType); if (pMediaType == NULL) { return E_OUTOFMEMORY; } } } /* Now do the assignments */ if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwStreamId, cbProperties)) { m_dwStreamId = pProps->dwStreamId; } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwSampleFlags, cbProperties)) { /* Set the flags */ m_dwFlags = pProps->dwSampleFlags | (m_dwFlags & Sample_MediaTimeValid); m_dwTypeSpecificFlags = pProps->dwTypeSpecificFlags; } else { if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, dwTypeSpecificFlags, cbProperties)) { m_dwTypeSpecificFlags = pProps->dwTypeSpecificFlags; } } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, lActual, cbProperties)) { /* Set lActual */ m_lActual = pProps->lActual; } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStop, cbProperties)) { /* Set the times */ m_End = pProps->tStop; } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, tStart, cbProperties)) { /* Set the times */ m_Start = pProps->tStart; } if (CONTAINS_FIELD(AM_SAMPLE2_PROPERTIES, pMediaType, cbProperties)) { /* Set pMediaType */ if (pProps->dwSampleFlags & AM_SAMPLE_TYPECHANGED) { if (m_pMediaType != NULL) { DeleteMediaType(m_pMediaType); } m_pMediaType = pMediaType; } } /* Fix up the type changed flag to correctly reflect the current state If, for instance the input contained no type change but the output does then if we don't do this we'd lose the output media type. */ if (m_pMediaType) { m_dwFlags |= Sample_TypeChanged; } else { m_dwFlags &= ~Sample_TypeChanged; } } return S_OK; } // // The streaming thread calls IPin::NewSegment(), IPin::EndOfStream(), // IMemInputPin::Receive() and IMemInputPin::ReceiveMultiple() on the // connected input pin. The application thread calls Block(). The // following class members can only be called by the streaming thread. // // Deliver() // DeliverNewSegment() // StartUsingOutputPin() // StopUsingOutputPin() // ChangeOutputFormat() // ChangeMediaType() // DynamicReconnect() // // The following class members can only be called by the application thread. // // Block() // SynchronousBlockOutputPin() // AsynchronousBlockOutputPin() // CDynamicOutputPin::CDynamicOutputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBaseOutputPin(pObjectName, pFilter, pLock, phr, pName) , m_hStopEvent(NULL) , m_pGraphConfig(NULL) , m_bPinUsesReadOnlyAllocator(FALSE) , m_BlockState(NOT_BLOCKED) , m_hUnblockOutputPinEvent(NULL) , m_hNotifyCallerPinBlockedEvent(NULL) , m_dwBlockCallerThreadID(0) , m_dwNumOutstandingOutputPinUsers(0) { HRESULT hr = Initialize(); if (FAILED(hr)) { *phr = hr; return; } } #ifdef UNICODE CDynamicOutputPin::CDynamicOutputPin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBaseOutputPin(pObjectName, pFilter, pLock, phr, pName) , m_hStopEvent(NULL) , m_pGraphConfig(NULL) , m_bPinUsesReadOnlyAllocator(FALSE) , m_BlockState(NOT_BLOCKED) , m_hUnblockOutputPinEvent(NULL) , m_hNotifyCallerPinBlockedEvent(NULL) , m_dwBlockCallerThreadID(0) , m_dwNumOutstandingOutputPinUsers(0) { HRESULT hr = Initialize(); if (FAILED(hr)) { *phr = hr; return; } } #endif CDynamicOutputPin::~CDynamicOutputPin() { if (NULL != m_hUnblockOutputPinEvent) { // This call should not fail because we have access to m_hUnblockOutputPinEvent // and m_hUnblockOutputPinEvent is a valid event. EXECUTE_ASSERT(::CloseHandle(m_hUnblockOutputPinEvent)); } if (NULL != m_hNotifyCallerPinBlockedEvent) { // This call should not fail because we have access to m_hNotifyCallerPinBlockedEvent // and m_hNotifyCallerPinBlockedEvent is a valid event. EXECUTE_ASSERT(::CloseHandle(m_hNotifyCallerPinBlockedEvent)); } } HRESULT CDynamicOutputPin::Initialize(void) { m_hUnblockOutputPinEvent = ::CreateEvent(NULL, // The event will have the default security descriptor. TRUE, // This is a manual reset event. TRUE, // The event is initially signaled. NULL); // The event is not named. // CreateEvent() returns NULL if an error occurs. if (NULL == m_hUnblockOutputPinEvent) { return AmGetLastErrorToHResult(); } // Set flag to say we can reconnect while streaming. SetReconnectWhenActive(true); return S_OK; } STDMETHODIMP CDynamicOutputPin::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_IPinFlowControl) { return GetInterface(static_cast(this), ppv); } else { return CBaseOutputPin::NonDelegatingQueryInterface(riid, ppv); } } STDMETHODIMP CDynamicOutputPin::Disconnect(void) { CAutoLock cObjectLock(m_pLock); return DisconnectInternal(); } STDMETHODIMP CDynamicOutputPin::Block(DWORD dwBlockFlags, HANDLE hEvent) { const DWORD VALID_FLAGS = AM_PIN_FLOW_CONTROL_BLOCK; // Check for illegal flags. if (dwBlockFlags & ~VALID_FLAGS) { return E_INVALIDARG; } // Make sure the event is unsignaled. if ((dwBlockFlags & AM_PIN_FLOW_CONTROL_BLOCK) && (NULL != hEvent)) { if (!::ResetEvent(hEvent)) { return AmGetLastErrorToHResult(); } } // No flags are set if we are unblocking the output pin. if (0 == dwBlockFlags) { // This parameter should be NULL because unblock operations are always synchronous. // There is no need to notify the caller when the event is done. if (NULL != hEvent) { return E_INVALIDARG; } } #ifdef DEBUG AssertValid(); #endif // DEBUG HRESULT hr; if (dwBlockFlags & AM_PIN_FLOW_CONTROL_BLOCK) { // IPinFlowControl::Block()'s hEvent parameter is NULL if the block is synchronous. // If hEvent is not NULL, the block is asynchronous. if (NULL == hEvent) { hr = SynchronousBlockOutputPin(); } else { hr = AsynchronousBlockOutputPin(hEvent); } } else { hr = UnblockOutputPin(); } #ifdef DEBUG AssertValid(); #endif // DEBUG if (FAILED(hr)) { return hr; } return S_OK; } HRESULT CDynamicOutputPin::SynchronousBlockOutputPin(void) { HANDLE hNotifyCallerPinBlockedEvent = ::CreateEvent(NULL, // The event will have the default security attributes. FALSE, // This is an automatic reset event. FALSE, // The event is initially unsignaled. NULL); // The event is not named. // CreateEvent() returns NULL if an error occurs. if (NULL == hNotifyCallerPinBlockedEvent) { return AmGetLastErrorToHResult(); } HRESULT hr = AsynchronousBlockOutputPin(hNotifyCallerPinBlockedEvent); if (FAILED(hr)) { // This call should not fail because we have access to hNotifyCallerPinBlockedEvent // and hNotifyCallerPinBlockedEvent is a valid event. EXECUTE_ASSERT(::CloseHandle(hNotifyCallerPinBlockedEvent)); return hr; } hr = WaitEvent(hNotifyCallerPinBlockedEvent); // This call should not fail because we have access to hNotifyCallerPinBlockedEvent // and hNotifyCallerPinBlockedEvent is a valid event. EXECUTE_ASSERT(::CloseHandle(hNotifyCallerPinBlockedEvent)); if (FAILED(hr)) { return hr; } return S_OK; } HRESULT CDynamicOutputPin::AsynchronousBlockOutputPin(HANDLE hNotifyCallerPinBlockedEvent) { // This function holds the m_BlockStateLock because it uses // m_dwBlockCallerThreadID, m_BlockState and // m_hNotifyCallerPinBlockedEvent. CAutoLock alBlockStateLock(&m_BlockStateLock); if (NOT_BLOCKED != m_BlockState) { if (m_dwBlockCallerThreadID == ::GetCurrentThreadId()) { return VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD; } else { return VFW_E_PIN_ALREADY_BLOCKED; } } BOOL fSuccess = ::DuplicateHandle(::GetCurrentProcess(), hNotifyCallerPinBlockedEvent, ::GetCurrentProcess(), &m_hNotifyCallerPinBlockedEvent, EVENT_MODIFY_STATE, FALSE, 0); if (!fSuccess) { return AmGetLastErrorToHResult(); } m_BlockState = PENDING; m_dwBlockCallerThreadID = ::GetCurrentThreadId(); // The output pin cannot be blocked if the streaming thread is // calling IPin::NewSegment(), IPin::EndOfStream(), IMemInputPin::Receive() // or IMemInputPin::ReceiveMultiple() on the connected input pin. Also, it // cannot be blocked if the streaming thread is calling DynamicReconnect(), // ChangeMediaType() or ChangeOutputFormat(). if (!StreamingThreadUsingOutputPin()) { // The output pin can be immediately blocked. BlockOutputPin(); } return S_OK; } void CDynamicOutputPin::BlockOutputPin(void) { // The caller should always hold the m_BlockStateLock because this function // uses m_BlockState and m_hNotifyCallerPinBlockedEvent. ASSERT(CritCheckIn(&m_BlockStateLock)); // This function should not be called if the streaming thread is modifying // the connection state or it's passing data downstream. ASSERT(!StreamingThreadUsingOutputPin()); // This should not fail because we successfully created the event // and we have the security permissions to change it's state. EXECUTE_ASSERT(::ResetEvent(m_hUnblockOutputPinEvent)); // This event should not fail because AsynchronousBlockOutputPin() successfully // duplicated this handle and we have the appropriate security permissions. EXECUTE_ASSERT(::SetEvent(m_hNotifyCallerPinBlockedEvent)); EXECUTE_ASSERT(::CloseHandle(m_hNotifyCallerPinBlockedEvent)); m_BlockState = BLOCKED; m_hNotifyCallerPinBlockedEvent = NULL; } HRESULT CDynamicOutputPin::UnblockOutputPin(void) { // UnblockOutputPin() holds the m_BlockStateLock because it // uses m_BlockState, m_dwBlockCallerThreadID and // m_hNotifyCallerPinBlockedEvent. CAutoLock alBlockStateLock(&m_BlockStateLock); if (NOT_BLOCKED == m_BlockState) { return S_FALSE; } // This should not fail because we successfully created the event // and we have the security permissions to change it's state. EXECUTE_ASSERT(::SetEvent(m_hUnblockOutputPinEvent)); // Cancel the block operation if it's still pending. if (NULL != m_hNotifyCallerPinBlockedEvent) { // This event should not fail because AsynchronousBlockOutputPin() successfully // duplicated this handle and we have the appropriate security permissions. EXECUTE_ASSERT(::SetEvent(m_hNotifyCallerPinBlockedEvent)); EXECUTE_ASSERT(::CloseHandle(m_hNotifyCallerPinBlockedEvent)); } m_BlockState = NOT_BLOCKED; m_dwBlockCallerThreadID = 0; m_hNotifyCallerPinBlockedEvent = NULL; return S_OK; } HRESULT CDynamicOutputPin::StartUsingOutputPin(void) { // The caller should not hold m_BlockStateLock. If the caller does, // a deadlock could occur. ASSERT(CritCheckOut(&m_BlockStateLock)); CAutoLock alBlockStateLock(&m_BlockStateLock); #ifdef DEBUG AssertValid(); #endif // DEBUG // Are we in the middle of a block operation? while (BLOCKED == m_BlockState) { m_BlockStateLock.Unlock(); // If this ASSERT fires, a deadlock could occur. The caller should make sure // that this thread never acquires the Block State lock more than once. ASSERT(CritCheckOut(&m_BlockStateLock)); // WaitForMultipleObjects() returns WAIT_OBJECT_0 if the unblock event // is fired. It returns WAIT_OBJECT_0 + 1 if the stop event if fired. // See the Windows SDK documentation for more information on // WaitForMultipleObjects(). const DWORD UNBLOCK = WAIT_OBJECT_0; const DWORD STOP = WAIT_OBJECT_0 + 1; HANDLE ahWaitEvents[] = {m_hUnblockOutputPinEvent, m_hStopEvent}; DWORD dwNumWaitEvents = sizeof(ahWaitEvents) / sizeof(HANDLE); DWORD dwReturnValue = ::WaitForMultipleObjects(dwNumWaitEvents, ahWaitEvents, FALSE, INFINITE); m_BlockStateLock.Lock(); #ifdef DEBUG AssertValid(); #endif // DEBUG switch (dwReturnValue) { case UNBLOCK: break; case STOP: return VFW_E_STATE_CHANGED; case WAIT_FAILED: return AmGetLastErrorToHResult(); default: DbgBreak("An Unexpected case occured in CDynamicOutputPin::StartUsingOutputPin()."); return E_UNEXPECTED; } } m_dwNumOutstandingOutputPinUsers++; #ifdef DEBUG AssertValid(); #endif // DEBUG return S_OK; } void CDynamicOutputPin::StopUsingOutputPin(void) { CAutoLock alBlockStateLock(&m_BlockStateLock); #ifdef DEBUG AssertValid(); #endif // DEBUG m_dwNumOutstandingOutputPinUsers--; if ((m_dwNumOutstandingOutputPinUsers == 0) && (NOT_BLOCKED != m_BlockState)) { BlockOutputPin(); } #ifdef DEBUG AssertValid(); #endif // DEBUG } bool CDynamicOutputPin::StreamingThreadUsingOutputPin(void) { CAutoLock alBlockStateLock(&m_BlockStateLock); return (m_dwNumOutstandingOutputPinUsers > 0); } void CDynamicOutputPin::SetConfigInfo(IGraphConfig *pGraphConfig, HANDLE hStopEvent) { // This pointer is not addrefed because filters are not allowed to // hold references to the filter graph manager. See the documentation for // IBaseFilter::JoinFilterGraph() in the Direct Show SDK for more information. m_pGraphConfig = pGraphConfig; m_hStopEvent = hStopEvent; } HRESULT CDynamicOutputPin::Active(void) { // Make sure the user initialized the object by calling SetConfigInfo(). if ((NULL == m_hStopEvent) || (NULL == m_pGraphConfig)) { DbgBreak(ERROR : CDynamicOutputPin::Active() failed because m_pGraphConfig and m_hStopEvent were not initialized.Call SetConfigInfo() to initialize them.); return E_FAIL; } // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). // The ASSERT can also fire if the event if destroyed and then Active() is called. An event // handle is invalid if 1) the event does not exist or the user does not have the security // permissions to use the event. EXECUTE_ASSERT(ResetEvent(m_hStopEvent)); return CBaseOutputPin::Active(); } HRESULT CDynamicOutputPin::Inactive(void) { // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). // The ASSERT can also fire if the event if destroyed and then Active() is called. An event // handle is invalid if 1) the event does not exist or the user does not have the security // permissions to use the event. EXECUTE_ASSERT(SetEvent(m_hStopEvent)); return CBaseOutputPin::Inactive(); } HRESULT CDynamicOutputPin::DeliverBeginFlush(void) { // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). // The ASSERT can also fire if the event if destroyed and then DeliverBeginFlush() is called. // An event handle is invalid if 1) the event does not exist or the user does not have the security // permissions to use the event. EXECUTE_ASSERT(SetEvent(m_hStopEvent)); return CBaseOutputPin::DeliverBeginFlush(); } HRESULT CDynamicOutputPin::DeliverEndFlush(void) { // If this ASSERT fires, the user may have passed an invalid event handle to SetConfigInfo(). // The ASSERT can also fire if the event if destroyed and then DeliverBeginFlush() is called. // An event handle is invalid if 1) the event does not exist or the user does not have the security // permissions to use the event. EXECUTE_ASSERT(ResetEvent(m_hStopEvent)); return CBaseOutputPin::DeliverEndFlush(); } // ChangeOutputFormat() either dynamicly changes the connection's format type or it dynamicly // reconnects the output pin. HRESULT CDynamicOutputPin::ChangeOutputFormat(const AM_MEDIA_TYPE *pmt, REFERENCE_TIME tSegmentStart, REFERENCE_TIME tSegmentStop, double dSegmentRate) { // The caller should call StartUsingOutputPin() before calling this // method. ASSERT(StreamingThreadUsingOutputPin()); // Callers should always pass a valid media type to ChangeOutputFormat() . ASSERT(NULL != pmt); CMediaType cmt(*pmt); HRESULT hr = ChangeMediaType(&cmt); if (FAILED(hr)) { return hr; } hr = DeliverNewSegment(tSegmentStart, tSegmentStop, dSegmentRate); if (FAILED(hr)) { return hr; } return S_OK; } HRESULT CDynamicOutputPin::ChangeMediaType(const CMediaType *pmt) { // The caller should call StartUsingOutputPin() before calling this // method. ASSERT(StreamingThreadUsingOutputPin()); // This function assumes the filter graph is running. ASSERT(!IsStopped()); if (!IsConnected()) { return VFW_E_NOT_CONNECTED; } /* First check if the downstream pin will accept a dynamic format change */ QzCComPtr pConnection; m_Connected->QueryInterface(IID_IPinConnection, (void **)&pConnection); if (pConnection != NULL) { if (S_OK == pConnection->DynamicQueryAccept(pmt)) { HRESULT hr = ChangeMediaTypeHelper(pmt); if (FAILED(hr)) { return hr; } return S_OK; } } /* Can't do the dynamic connection */ return DynamicReconnect(pmt); } HRESULT CDynamicOutputPin::ChangeMediaTypeHelper(const CMediaType *pmt) { // The caller should call StartUsingOutputPin() before calling this // method. ASSERT(StreamingThreadUsingOutputPin()); HRESULT hr = m_Connected->ReceiveConnection(this, pmt); if (FAILED(hr)) { return hr; } hr = SetMediaType(pmt); if (FAILED(hr)) { return hr; } // Does this pin use the local memory transport? if (NULL != m_pInputPin) { // This function assumes that m_pInputPin and m_Connected are // two different interfaces to the same object. ASSERT(::IsEqualObject(m_Connected, m_pInputPin)); ALLOCATOR_PROPERTIES apInputPinRequirements; apInputPinRequirements.cbAlign = 0; apInputPinRequirements.cbBuffer = 0; apInputPinRequirements.cbPrefix = 0; apInputPinRequirements.cBuffers = 0; m_pInputPin->GetAllocatorRequirements(&apInputPinRequirements); // A zero allignment does not make any sense. if (0 == apInputPinRequirements.cbAlign) { apInputPinRequirements.cbAlign = 1; } hr = m_pAllocator->Decommit(); if (FAILED(hr)) { return hr; } hr = DecideBufferSize(m_pAllocator, &apInputPinRequirements); if (FAILED(hr)) { return hr; } hr = m_pAllocator->Commit(); if (FAILED(hr)) { return hr; } hr = m_pInputPin->NotifyAllocator(m_pAllocator, m_bPinUsesReadOnlyAllocator); if (FAILED(hr)) { return hr; } } return S_OK; } // this method has to be called from the thread that is pushing data, // and it's the caller's responsibility to make sure that the thread // has no outstand samples because they cannot be delivered after a // reconnect // HRESULT CDynamicOutputPin::DynamicReconnect(const CMediaType *pmt) { // The caller should call StartUsingOutputPin() before calling this // method. ASSERT(StreamingThreadUsingOutputPin()); if ((m_pGraphConfig == NULL) || (NULL == m_hStopEvent)) { return E_FAIL; } HRESULT hr = m_pGraphConfig->Reconnect(this, NULL, pmt, NULL, m_hStopEvent, AM_GRAPH_CONFIG_RECONNECT_CACHE_REMOVED_FILTERS); return hr; } HRESULT CDynamicOutputPin::CompleteConnect(IPin *pReceivePin) { HRESULT hr = CBaseOutputPin::CompleteConnect(pReceivePin); if (SUCCEEDED(hr)) { if (!IsStopped() && m_pAllocator) { hr = m_pAllocator->Commit(); ASSERT(hr != VFW_E_ALREADY_COMMITTED); } } return hr; } #ifdef DEBUG void CDynamicOutputPin::AssertValid(void) { // Make sure the object was correctly initialized. // This ASSERT only fires if the object failed to initialize // and the user ignored the constructor's return code (phr). ASSERT(NULL != m_hUnblockOutputPinEvent); // If either of these ASSERTs fire, the user did not correctly call // SetConfigInfo(). ASSERT(NULL != m_hStopEvent); ASSERT(NULL != m_pGraphConfig); // Make sure the block state is consistent. CAutoLock alBlockStateLock(&m_BlockStateLock); // BLOCK_STATE variables only have three legal values: PENDING, BLOCKED and NOT_BLOCKED. ASSERT((NOT_BLOCKED == m_BlockState) || (PENDING == m_BlockState) || (BLOCKED == m_BlockState)); // m_hNotifyCallerPinBlockedEvent is only needed when a block operation cannot complete // immediately. ASSERT(((NULL == m_hNotifyCallerPinBlockedEvent) && (PENDING != m_BlockState)) || ((NULL != m_hNotifyCallerPinBlockedEvent) && (PENDING == m_BlockState))); // m_dwBlockCallerThreadID should always be 0 if the pin is not blocked and // the user is not trying to block the pin. ASSERT((0 == m_dwBlockCallerThreadID) || (NOT_BLOCKED != m_BlockState)); // If this ASSERT fires, the streaming thread is using the output pin and the // output pin is blocked. ASSERT(((0 != m_dwNumOutstandingOutputPinUsers) && (BLOCKED != m_BlockState)) || ((0 == m_dwNumOutstandingOutputPinUsers) && (NOT_BLOCKED != m_BlockState)) || ((0 == m_dwNumOutstandingOutputPinUsers) && (NOT_BLOCKED == m_BlockState))); } #endif // DEBUG HRESULT CDynamicOutputPin::WaitEvent(HANDLE hEvent) { const DWORD EVENT_SIGNALED = WAIT_OBJECT_0; DWORD dwReturnValue = ::WaitForSingleObject(hEvent, INFINITE); switch (dwReturnValue) { case EVENT_SIGNALED: return S_OK; case WAIT_FAILED: return AmGetLastErrorToHResult(); default: DbgBreak("An Unexpected case occured in CDynamicOutputPin::WaitEvent()."); return E_UNEXPECTED; } } //===================================================================== //===================================================================== // Implements CBaseAllocator //===================================================================== //===================================================================== /* Constructor overrides the default settings for the free list to request that it be alertable (ie the list can be cast to a handle which can be passed to WaitForSingleObject). Both of the allocator lists also ask for object locking, the all list matches the object default settings but I have included them here just so it is obvious what kind of list it is */ CBaseAllocator::CBaseAllocator(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr, BOOL bEvent, BOOL fEnableReleaseCallback) : CUnknown(pName, pUnk) , m_lAllocated(0) , m_bChanged(FALSE) , m_bCommitted(FALSE) , m_bDecommitInProgress(FALSE) , m_lSize(0) , m_lCount(0) , m_lAlignment(0) , m_lPrefix(0) , m_hSem(NULL) , m_lWaiting(0) , m_fEnableReleaseCallback(fEnableReleaseCallback) , m_pNotify(NULL) { #ifdef DXMPERF PERFLOG_CTOR(pName ? pName : L"CBaseAllocator", (IMemAllocator *)this); #endif // DXMPERF if (bEvent) { m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL); if (m_hSem == NULL) { *phr = E_OUTOFMEMORY; return; } } } #ifdef UNICODE CBaseAllocator::CBaseAllocator(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr, BOOL bEvent, BOOL fEnableReleaseCallback) : CUnknown(pName, pUnk) , m_lAllocated(0) , m_bChanged(FALSE) , m_bCommitted(FALSE) , m_bDecommitInProgress(FALSE) , m_lSize(0) , m_lCount(0) , m_lAlignment(0) , m_lPrefix(0) , m_hSem(NULL) , m_lWaiting(0) , m_fEnableReleaseCallback(fEnableReleaseCallback) , m_pNotify(NULL) { #ifdef DXMPERF PERFLOG_CTOR(L"CBaseAllocator", (IMemAllocator *)this); #endif // DXMPERF if (bEvent) { m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL); if (m_hSem == NULL) { *phr = E_OUTOFMEMORY; return; } } } #endif /* Destructor */ CBaseAllocator::~CBaseAllocator() { // we can't call Decommit here since that would mean a call to a // pure virtual in destructor. // We must assume that the derived class has gone into decommit state in // its destructor. #ifdef DXMPERF PERFLOG_DTOR(L"CBaseAllocator", (IMemAllocator *)this); #endif // DXMPERF ASSERT(!m_bCommitted); if (m_hSem != NULL) { EXECUTE_ASSERT(CloseHandle(m_hSem)); } if (m_pNotify) { m_pNotify->Release(); } } /* Override this to publicise our interfaces */ STDMETHODIMP CBaseAllocator::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { /* Do we know about this interface */ if (riid == IID_IMemAllocator || riid == IID_IMemAllocatorCallbackTemp && m_fEnableReleaseCallback) { return GetInterface((IMemAllocatorCallbackTemp *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } /* This sets the size and count of the required samples. The memory isn't actually allocated until Commit() is called, if memory has already been allocated then assuming no samples are outstanding the user may call us to change the buffering, the memory will be released in Commit() */ STDMETHODIMP CBaseAllocator::SetProperties(__in ALLOCATOR_PROPERTIES *pRequest, __out ALLOCATOR_PROPERTIES *pActual) { CheckPointer(pRequest, E_POINTER); CheckPointer(pActual, E_POINTER); ValidateReadWritePtr(pActual, sizeof(ALLOCATOR_PROPERTIES)); CAutoLock cObjectLock(this); ZeroMemory(pActual, sizeof(ALLOCATOR_PROPERTIES)); ASSERT(pRequest->cbBuffer > 0); /* Check the alignment requested */ if (pRequest->cbAlign != 1) { DbgLog((LOG_ERROR, 2, TEXT("Alignment requested was 0x%x, not 1"), pRequest->cbAlign)); return VFW_E_BADALIGN; } /* Can't do this if already committed, there is an argument that says we should not reject the SetProperties call if there are buffers still active. However this is called by the source filter, which is the same person who is holding the samples. Therefore it is not unreasonable for them to free all their samples before changing the requirements */ if (m_bCommitted) { return VFW_E_ALREADY_COMMITTED; } /* Must be no outstanding buffers */ if (m_lAllocated != m_lFree.GetCount()) { return VFW_E_BUFFERS_OUTSTANDING; } /* There isn't any real need to check the parameters as they will just be rejected when the user finally calls Commit */ pActual->cbBuffer = m_lSize = pRequest->cbBuffer; pActual->cBuffers = m_lCount = pRequest->cBuffers; pActual->cbAlign = m_lAlignment = pRequest->cbAlign; pActual->cbPrefix = m_lPrefix = pRequest->cbPrefix; m_bChanged = TRUE; return NOERROR; } STDMETHODIMP CBaseAllocator::GetProperties(__out ALLOCATOR_PROPERTIES *pActual) { CheckPointer(pActual, E_POINTER); ValidateReadWritePtr(pActual, sizeof(ALLOCATOR_PROPERTIES)); CAutoLock cObjectLock(this); pActual->cbBuffer = m_lSize; pActual->cBuffers = m_lCount; pActual->cbAlign = m_lAlignment; pActual->cbPrefix = m_lPrefix; return NOERROR; } // get container for a sample. Blocking, synchronous call to get the // next free buffer (as represented by an IMediaSample interface). // on return, the time etc properties will be invalid, but the buffer // pointer and size will be correct. HRESULT CBaseAllocator::GetBuffer(__deref_out IMediaSample **ppBuffer, __in_opt REFERENCE_TIME *pStartTime, __in_opt REFERENCE_TIME *pEndTime, DWORD dwFlags) { UNREFERENCED_PARAMETER(pStartTime); UNREFERENCED_PARAMETER(pEndTime); UNREFERENCED_PARAMETER(dwFlags); CMediaSample *pSample; *ppBuffer = NULL; for (;;) { { // scope for lock CAutoLock cObjectLock(this); /* Check we are committed */ if (!m_bCommitted) { return VFW_E_NOT_COMMITTED; } pSample = (CMediaSample *)m_lFree.RemoveHead(); if (pSample == NULL) { SetWaiting(); } } /* If we didn't get a sample then wait for the list to signal */ if (pSample) { break; } if (dwFlags & AM_GBF_NOWAIT) { return VFW_E_TIMEOUT; } ASSERT(m_hSem != NULL); WaitForSingleObject(m_hSem, INFINITE); } /* Addref the buffer up to one. On release back to zero instead of being deleted, it will requeue itself by calling the ReleaseBuffer member function. NOTE the owner of a media sample must always be derived from CBaseAllocator */ ASSERT(pSample->m_cRef == 0); pSample->m_cRef = 1; *ppBuffer = pSample; #ifdef DXMPERF PERFLOG_GETBUFFER((IMemAllocator *)this, pSample); #endif // DXMPERF return NOERROR; } /* Final release of a CMediaSample will call this */ STDMETHODIMP CBaseAllocator::ReleaseBuffer(IMediaSample *pSample) { CheckPointer(pSample, E_POINTER); ValidateReadPtr(pSample, sizeof(IMediaSample)); #ifdef DXMPERF PERFLOG_RELBUFFER((IMemAllocator *)this, pSample); #endif // DXMPERF BOOL bRelease = FALSE; { CAutoLock cal(this); /* Put back on the free list */ m_lFree.Add((CMediaSample *)pSample); if (m_lWaiting != 0) { NotifySample(); } // if there is a pending Decommit, then we need to complete it by // calling Free() when the last buffer is placed on the free list LONG l1 = m_lFree.GetCount(); if (m_bDecommitInProgress && (l1 == m_lAllocated)) { Free(); m_bDecommitInProgress = FALSE; bRelease = TRUE; } } if (m_pNotify) { ASSERT(m_fEnableReleaseCallback); // // Note that this is not synchronized with setting up a notification // method. // m_pNotify->NotifyRelease(); } /* For each buffer there is one AddRef, made in GetBuffer and released here. This may cause the allocator and all samples to be deleted */ if (bRelease) { Release(); } return NOERROR; } STDMETHODIMP CBaseAllocator::SetNotify(IMemAllocatorNotifyCallbackTemp *pNotify) { ASSERT(m_fEnableReleaseCallback); CAutoLock lck(this); if (pNotify) { pNotify->AddRef(); } if (m_pNotify) { m_pNotify->Release(); } m_pNotify = pNotify; return S_OK; } STDMETHODIMP CBaseAllocator::GetFreeCount(__out LONG *plBuffersFree) { ASSERT(m_fEnableReleaseCallback); CAutoLock cObjectLock(this); *plBuffersFree = m_lCount - m_lAllocated + m_lFree.GetCount(); return NOERROR; } void CBaseAllocator::NotifySample() { if (m_lWaiting != 0) { ASSERT(m_hSem != NULL); ReleaseSemaphore(m_hSem, m_lWaiting, 0); m_lWaiting = 0; } } STDMETHODIMP CBaseAllocator::Commit() { /* Check we are not decommitted */ CAutoLock cObjectLock(this); // cannot need to alloc or re-alloc if we are committed if (m_bCommitted) { return NOERROR; } // is there a pending decommit ? if so, just cancel it if (m_bDecommitInProgress) { m_bDecommitInProgress = FALSE; m_bCommitted = TRUE; // don't call Alloc at this point. He cannot allow SetProperties // between Decommit and the last free, so the buffer size cannot have // changed. And because some of the buffers are not free yet, he // cannot re-alloc anyway. return NOERROR; } DbgLog((LOG_MEMORY, 1, TEXT("Allocating: %ldx%ld"), m_lCount, m_lSize)); // actually need to allocate the samples HRESULT hr = Alloc(); if (FAILED(hr)) { m_bCommitted = FALSE; return hr; } /* Allow GetBuffer calls */ m_bCommitted = TRUE; AddRef(); return NOERROR; } STDMETHODIMP CBaseAllocator::Decommit() { BOOL bRelease = FALSE; { /* Check we are not already decommitted */ CAutoLock cObjectLock(this); if (m_bCommitted == FALSE) { if (m_bDecommitInProgress == FALSE) { return NOERROR; } } /* No more GetBuffer calls will succeed */ m_bCommitted = FALSE; // are any buffers outstanding? if (m_lFree.GetCount() < m_lAllocated) { // please complete the decommit when last buffer is freed m_bDecommitInProgress = TRUE; } else { m_bDecommitInProgress = FALSE; // need to complete the decommit here as there are no // outstanding buffers Free(); bRelease = TRUE; } // Tell anyone waiting that they can go now so we can // reject their call #pragma warning(push) #ifndef _PREFAST_ #pragma warning(disable : 4068) #endif #pragma prefast( \ suppress \ : __WARNING_DEREF_NULL_PTR, \ "Suppress warning related to Free() invalidating 'this' which is no applicable to CBaseAllocator::Free()") NotifySample(); #pragma warning(pop) } if (bRelease) { Release(); } return NOERROR; } /* Base definition of allocation which checks we are ok to go ahead and do the full allocation. We return S_FALSE if the requirements are the same */ HRESULT CBaseAllocator::Alloc(void) { /* Error if he hasn't set the size yet */ if (m_lCount <= 0 || m_lSize <= 0 || m_lAlignment <= 0) { return VFW_E_SIZENOTSET; } /* should never get here while buffers outstanding */ ASSERT(m_lFree.GetCount() == m_lAllocated); /* If the requirements haven't changed then don't reallocate */ if (m_bChanged == FALSE) { return S_FALSE; } return NOERROR; } /* Implement CBaseAllocator::CSampleList::Remove(pSample) Removes pSample from the list */ void CBaseAllocator::CSampleList::Remove(__inout CMediaSample *pSample) { CMediaSample **pSearch; for (pSearch = &m_List; *pSearch != NULL; pSearch = &(CBaseAllocator::NextSample(*pSearch))) { if (*pSearch == pSample) { *pSearch = CBaseAllocator::NextSample(pSample); CBaseAllocator::NextSample(pSample) = NULL; m_nOnList--; return; } } DbgBreak("Couldn't find sample in list"); } //===================================================================== //===================================================================== // Implements CMemAllocator //===================================================================== //===================================================================== /* This goes in the factory template table to create new instances */ CUnknown *CMemAllocator::CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) { CUnknown *pUnkRet = new CMemAllocator(NAME("CMemAllocator"), pUnk, phr); return pUnkRet; } CMemAllocator::CMemAllocator(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) : CBaseAllocator(pName, pUnk, phr, TRUE, TRUE) , m_pBuffer(NULL) { } #ifdef UNICODE CMemAllocator::CMemAllocator(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) : CBaseAllocator(pName, pUnk, phr, TRUE, TRUE) , m_pBuffer(NULL) { } #endif /* This sets the size and count of the required samples. The memory isn't actually allocated until Commit() is called, if memory has already been allocated then assuming no samples are outstanding the user may call us to change the buffering, the memory will be released in Commit() */ STDMETHODIMP CMemAllocator::SetProperties(__in ALLOCATOR_PROPERTIES *pRequest, __out ALLOCATOR_PROPERTIES *pActual) { CheckPointer(pActual, E_POINTER); ValidateReadWritePtr(pActual, sizeof(ALLOCATOR_PROPERTIES)); CAutoLock cObjectLock(this); ZeroMemory(pActual, sizeof(ALLOCATOR_PROPERTIES)); ASSERT(pRequest->cbBuffer > 0); SYSTEM_INFO SysInfo; GetSystemInfo(&SysInfo); /* Check the alignment request is a power of 2 */ if ((-pRequest->cbAlign & pRequest->cbAlign) != pRequest->cbAlign) { DbgLog((LOG_ERROR, 1, TEXT("Alignment requested 0x%x not a power of 2!"), pRequest->cbAlign)); } /* Check the alignment requested */ if (pRequest->cbAlign == 0 || (SysInfo.dwAllocationGranularity & (pRequest->cbAlign - 1)) != 0) { DbgLog((LOG_ERROR, 1, TEXT("Invalid alignment 0x%x requested - granularity = 0x%x"), pRequest->cbAlign, SysInfo.dwAllocationGranularity)); return VFW_E_BADALIGN; } /* Can't do this if already committed, there is an argument that says we should not reject the SetProperties call if there are buffers still active. However this is called by the source filter, which is the same person who is holding the samples. Therefore it is not unreasonable for them to free all their samples before changing the requirements */ if (m_bCommitted == TRUE) { return VFW_E_ALREADY_COMMITTED; } /* Must be no outstanding buffers */ if (m_lFree.GetCount() < m_lAllocated) { return VFW_E_BUFFERS_OUTSTANDING; } /* There isn't any real need to check the parameters as they will just be rejected when the user finally calls Commit */ // round length up to alignment - remember that prefix is included in // the alignment LONG lSize = pRequest->cbBuffer + pRequest->cbPrefix; LONG lRemainder = lSize % pRequest->cbAlign; if (lRemainder != 0) { lSize = lSize - lRemainder + pRequest->cbAlign; } pActual->cbBuffer = m_lSize = (lSize - pRequest->cbPrefix); pActual->cBuffers = m_lCount = pRequest->cBuffers; pActual->cbAlign = m_lAlignment = pRequest->cbAlign; pActual->cbPrefix = m_lPrefix = pRequest->cbPrefix; m_bChanged = TRUE; return NOERROR; } // override this to allocate our resources when Commit is called. // // note that our resources may be already allocated when this is called, // since we don't free them on Decommit. We will only be called when in // decommit state with all buffers free. // // object locked by caller HRESULT CMemAllocator::Alloc(void) { CAutoLock lck(this); /* Check he has called SetProperties */ HRESULT hr = CBaseAllocator::Alloc(); if (FAILED(hr)) { return hr; } /* If the requirements haven't changed then don't reallocate */ if (hr == S_FALSE) { ASSERT(m_pBuffer); return NOERROR; } ASSERT(hr == S_OK); // we use this fact in the loop below /* Free the old resources */ if (m_pBuffer) { ReallyFree(); } /* Make sure we've got reasonable values */ if (m_lSize < 0 || m_lPrefix < 0 || m_lCount < 0) { return E_OUTOFMEMORY; } /* Compute the aligned size */ LONG lAlignedSize = m_lSize + m_lPrefix; /* Check overflow */ if (lAlignedSize < m_lSize) { return E_OUTOFMEMORY; } if (m_lAlignment > 1) { LONG lRemainder = lAlignedSize % m_lAlignment; if (lRemainder != 0) { LONG lNewSize = lAlignedSize + m_lAlignment - lRemainder; if (lNewSize < lAlignedSize) { return E_OUTOFMEMORY; } lAlignedSize = lNewSize; } } /* Create the contiguous memory block for the samples making sure it's properly aligned (64K should be enough!) */ ASSERT(lAlignedSize % m_lAlignment == 0); LONGLONG lToAllocate = m_lCount * (LONGLONG)lAlignedSize; /* Check overflow */ if (lToAllocate > MAXLONG) { return E_OUTOFMEMORY; } m_pBuffer = (PBYTE)VirtualAlloc(NULL, (LONG)lToAllocate, MEM_COMMIT, PAGE_READWRITE); if (m_pBuffer == NULL) { return E_OUTOFMEMORY; } LPBYTE pNext = m_pBuffer; CMediaSample *pSample; ASSERT(m_lAllocated == 0); // Create the new samples - we have allocated m_lSize bytes for each sample // plus m_lPrefix bytes per sample as a prefix. We set the pointer to // the memory after the prefix - so that GetPointer() will return a pointer // to m_lSize bytes. for (; m_lAllocated < m_lCount; m_lAllocated++, pNext += lAlignedSize) { pSample = new CMediaSample(NAME("Default memory media sample"), this, &hr, pNext + m_lPrefix, // GetPointer() value m_lSize); // not including prefix ASSERT(SUCCEEDED(hr)); if (pSample == NULL) { return E_OUTOFMEMORY; } // This CANNOT fail m_lFree.Add(pSample); } m_bChanged = FALSE; return NOERROR; } // override this to free up any resources we have allocated. // called from the base class on Decommit when all buffers have been // returned to the free list. // // caller has already locked the object. // in our case, we keep the memory until we are deleted, so // we do nothing here. The memory is deleted in the destructor by // calling ReallyFree() void CMemAllocator::Free(void) { return; } // called from the destructor (and from Alloc if changing size/count) to // actually free up the memory void CMemAllocator::ReallyFree(void) { /* Should never be deleting this unless all buffers are freed */ ASSERT(m_lAllocated == m_lFree.GetCount()); /* Free up all the CMediaSamples */ CMediaSample *pSample; for (;;) { pSample = m_lFree.RemoveHead(); if (pSample != NULL) { delete pSample; } else { break; } } m_lAllocated = 0; // free the block of buffer memory if (m_pBuffer) { EXECUTE_ASSERT(VirtualFree(m_pBuffer, 0, MEM_RELEASE)); m_pBuffer = NULL; } } /* Destructor frees our memory resources */ CMemAllocator::~CMemAllocator() { Decommit(); ReallyFree(); } // ------------------------------------------------------------------------ // filter registration through IFilterMapper. used if IFilterMapper is // not found (Quartz 1.0 install) STDAPI AMovieSetupRegisterFilter(const AMOVIESETUP_FILTER *const psetupdata, IFilterMapper *pIFM, BOOL bRegister) { DbgLog((LOG_TRACE, 3, TEXT("= AMovieSetupRegisterFilter"))); // check we've got data // if (NULL == psetupdata) return S_FALSE; // unregister filter // (as pins are subkeys of filter's CLSID key // they do not need to be removed separately). // DbgLog((LOG_TRACE, 3, TEXT("= = unregister filter"))); HRESULT hr = pIFM->UnregisterFilter(*(psetupdata->clsID)); if (bRegister) { // register filter // DbgLog((LOG_TRACE, 3, TEXT("= = register filter"))); hr = pIFM->RegisterFilter(*(psetupdata->clsID), psetupdata->strName, psetupdata->dwMerit); if (SUCCEEDED(hr)) { // all its pins // DbgLog((LOG_TRACE, 3, TEXT("= = register filter pins"))); for (UINT m1 = 0; m1 < psetupdata->nPins; m1++) { hr = pIFM->RegisterPin( *(psetupdata->clsID), psetupdata->lpPin[m1].strName, psetupdata->lpPin[m1].bRendered, psetupdata->lpPin[m1].bOutput, psetupdata->lpPin[m1].bZero, psetupdata->lpPin[m1].bMany, *(psetupdata->lpPin[m1].clsConnectsToFilter), psetupdata->lpPin[m1].strConnectsToPin); if (SUCCEEDED(hr)) { // and each pin's media types // DbgLog((LOG_TRACE, 3, TEXT("= = register filter pin types"))); for (UINT m2 = 0; m2 < psetupdata->lpPin[m1].nMediaTypes; m2++) { hr = pIFM->RegisterPinType(*(psetupdata->clsID), psetupdata->lpPin[m1].strName, *(psetupdata->lpPin[m1].lpMediaType[m2].clsMajorType), *(psetupdata->lpPin[m1].lpMediaType[m2].clsMinorType)); if (FAILED(hr)) break; } if (FAILED(hr)) break; } if (FAILED(hr)) break; } } } // handle one acceptable "error" - that // of filter not being registered! // (couldn't find a suitable #define'd // name for the error!) // if (0x80070002 == hr) return NOERROR; else return hr; } // Remove warnings about unreferenced inline functions #pragma warning(disable : 4514) ================================================ FILE: common/baseclasses/amfilter.h ================================================ //------------------------------------------------------------------------------ // File: AMFilter.h // // Desc: DirectShow base classes - efines class hierarchy for streams // architecture. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __FILTER__ #define __FILTER__ /* The following classes are declared in this header: */ class CBaseMediaFilter; // IMediaFilter support class CBaseFilter; // IBaseFilter,IMediaFilter support class CBasePin; // Abstract base class for IPin interface class CEnumPins; // Enumerate input and output pins class CEnumMediaTypes; // Enumerate the pin's preferred formats class CBaseOutputPin; // Adds data provider member functions class CBaseInputPin; // Implements IMemInputPin interface class CMediaSample; // Basic transport unit for IMemInputPin class CBaseAllocator; // General list guff for most allocators class CMemAllocator; // Implements memory buffer allocation //===================================================================== //===================================================================== // // QueryFilterInfo and QueryPinInfo AddRef the interface pointers // they return. You can use the macro below to release the interface. // //===================================================================== //===================================================================== #define QueryFilterInfoReleaseGraph(fi) \ if ((fi).pGraph) \ (fi).pGraph->Release(); #define QueryPinInfoReleaseFilter(pi) \ if ((pi).pFilter) \ (pi).pFilter->Release(); //===================================================================== //===================================================================== // Defines CBaseMediaFilter // // Abstract base class implementing IMediaFilter. // // Typically you will derive your filter from CBaseFilter rather than // this, unless you are implementing an object such as a plug-in // distributor that needs to support IMediaFilter but not IBaseFilter. // // Note that IMediaFilter is derived from IPersist to allow query of // class id. //===================================================================== //===================================================================== class AM_NOVTABLE CBaseMediaFilter : public CUnknown , public IMediaFilter { protected: FILTER_STATE m_State; // current state: running, paused IReferenceClock *m_pClock; // this filter's reference clock // note: all filters in a filter graph use the same clock // offset from stream time to reference time CRefTime m_tStart; CLSID m_clsid; // This filters clsid // used for serialization CCritSec *m_pLock; // Object we use for locking public: CBaseMediaFilter(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __in CCritSec *pLock, REFCLSID clsid); virtual ~CBaseMediaFilter(); DECLARE_IUNKNOWN // override this to say what interfaces we support where STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // // --- IPersist method --- // STDMETHODIMP GetClassID(__out CLSID *pClsID); // --- IMediaFilter methods --- STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); STDMETHODIMP SetSyncSource(__inout_opt IReferenceClock *pClock); STDMETHODIMP GetSyncSource(__deref_out_opt IReferenceClock **pClock); // default implementation of Stop and Pause just record the // state. Override to activate or de-activate your filter. // Note that Run when called from Stopped state will call Pause // to ensure activation, so if you are a source or transform // you will probably not need to override Run. STDMETHODIMP Stop(); STDMETHODIMP Pause(); // the start parameter is the difference to be added to the // sample's stream time to get the reference time for // its presentation STDMETHODIMP Run(REFERENCE_TIME tStart); // --- helper methods --- // return the current stream time - ie find out what // stream time should be appearing now virtual HRESULT StreamTime(CRefTime &rtStream); // Is the filter currently active? (running or paused) BOOL IsActive() { CAutoLock cObjectLock(m_pLock); return ((m_State == State_Paused) || (m_State == State_Running)); }; }; //===================================================================== //===================================================================== // Defines CBaseFilter // // An abstract class providing basic IBaseFilter support for pin // enumeration and filter information reading. // // We cannot derive from CBaseMediaFilter since methods in IMediaFilter // are also in IBaseFilter and would be ambiguous. Since much of the code // assumes that they derive from a class that has m_State and other state // directly available, we duplicate code from CBaseMediaFilter rather than // having a member variable. // // Derive your filter from this, or from a derived object such as // CTransformFilter. //===================================================================== //===================================================================== class AM_NOVTABLE CBaseFilter : public CUnknown , // Handles an IUnknown public IBaseFilter , // The Filter Interface public IAMovieSetup // For un/registration { friend class CBasePin; protected: FILTER_STATE m_State; // current state: running, paused IReferenceClock *m_pClock; // this graph's ref clock CRefTime m_tStart; // offset from stream time to reference time CLSID m_clsid; // This filters clsid // used for serialization CCritSec *m_pLock; // Object we use for locking WCHAR *m_pName; // Full filter name IFilterGraph *m_pGraph; // Graph we belong to IMediaEventSink *m_pSink; // Called with notify events LONG m_PinVersion; // Current pin version public: CBaseFilter(__in_opt LPCTSTR pName, // Object description __inout_opt LPUNKNOWN pUnk, // IUnknown of delegating object __in CCritSec *pLock, // Object who maintains lock REFCLSID clsid); // The clsid to be used to serialize this filter CBaseFilter(__in_opt LPCTSTR pName, // Object description __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object __in CCritSec *pLock, // Object who maintains lock REFCLSID clsid, // The clsid to be used to serialize this filter __inout HRESULT *phr); // General OLE return code #ifdef UNICODE CBaseFilter(__in_opt LPCSTR pName, // Object description __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object __in CCritSec *pLock, // Object who maintains lock REFCLSID clsid); // The clsid to be used to serialize this filter CBaseFilter(__in_opt LPCSTR pName, // Object description __in_opt LPUNKNOWN pUnk, // IUnknown of delegating object __in CCritSec *pLock, // Object who maintains lock REFCLSID clsid, // The clsid to be used to serialize this filter __inout HRESULT *phr); // General OLE return code #endif ~CBaseFilter(); DECLARE_IUNKNOWN // override this to say what interfaces we support where STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); #ifdef DEBUG STDMETHODIMP_(ULONG) NonDelegatingRelease(); #endif // // --- IPersist method --- // STDMETHODIMP GetClassID(__out CLSID *pClsID); // --- IMediaFilter methods --- STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); STDMETHODIMP SetSyncSource(__in_opt IReferenceClock *pClock); STDMETHODIMP GetSyncSource(__deref_out_opt IReferenceClock **pClock); // override Stop and Pause so we can activate the pins. // Note that Run will call Pause first if activation needed. // Override these if you want to activate your filter rather than // your pins. STDMETHODIMP Stop(); STDMETHODIMP Pause(); // the start parameter is the difference to be added to the // sample's stream time to get the reference time for // its presentation STDMETHODIMP Run(REFERENCE_TIME tStart); // --- helper methods --- // return the current stream time - ie find out what // stream time should be appearing now virtual HRESULT StreamTime(CRefTime &rtStream); // Is the filter currently active? BOOL IsActive() { CAutoLock cObjectLock(m_pLock); return ((m_State == State_Paused) || (m_State == State_Running)); }; // Is this filter stopped (without locking) BOOL IsStopped() { return (m_State == State_Stopped); }; // // --- IBaseFilter methods --- // // pin enumerator STDMETHODIMP EnumPins(__deref_out IEnumPins **ppEnum); // default behaviour of FindPin assumes pin ids are their names STDMETHODIMP FindPin(LPCWSTR Id, __deref_out IPin **ppPin); STDMETHODIMP QueryFilterInfo(__out FILTER_INFO *pInfo); STDMETHODIMP JoinFilterGraph(__inout_opt IFilterGraph *pGraph, __in_opt LPCWSTR pName); // return a Vendor information string. Optional - may return E_NOTIMPL. // memory returned should be freed using CoTaskMemFree // default implementation returns E_NOTIMPL STDMETHODIMP QueryVendorInfo(__deref_out LPWSTR *pVendorInfo); // --- helper methods --- // send an event notification to the filter graph if we know about it. // returns S_OK if delivered, S_FALSE if the filter graph does not sink // events, or an error otherwise. HRESULT NotifyEvent(long EventCode, LONG_PTR EventParam1, LONG_PTR EventParam2); // return the filter graph we belong to __out_opt IFilterGraph *GetFilterGraph() { return m_pGraph; } // Request reconnect // pPin is the pin to reconnect // pmt is the type to reconnect with - can be NULL // Calls ReconnectEx on the filter graph HRESULT ReconnectPin(IPin *pPin, __in_opt AM_MEDIA_TYPE const *pmt); // find out the current pin version (used by enumerators) virtual LONG GetPinVersion(); void IncrementPinVersion(); // you need to supply these to access the pins from the enumerator // and for default Stop and Pause/Run activation. virtual int GetPinCount() PURE; virtual CBasePin *GetPin(int n) PURE; // --- IAMovieSetup methods --- STDMETHODIMP Register(); // ask filter to register itself STDMETHODIMP Unregister(); // and unregister itself // --- setup helper methods --- // (override to return filters setup data) virtual __out_opt LPAMOVIESETUP_FILTER GetSetupData() { return NULL; } }; //===================================================================== //===================================================================== // Defines CBasePin // // Abstract class that supports the basics of IPin //===================================================================== //===================================================================== class AM_NOVTABLE CBasePin : public CUnknown , public IPin , public IQualityControl { protected: WCHAR *m_pName; // This pin's name IPin *m_Connected; // Pin we have connected to PIN_DIRECTION m_dir; // Direction of this pin CCritSec *m_pLock; // Object we use for locking bool m_bRunTimeError; // Run time error generated bool m_bCanReconnectWhenActive; // OK to reconnect when active bool m_bTryMyTypesFirst; // When connecting enumerate // this pin's types first CBaseFilter *m_pFilter; // Filter we were created by IQualityControl *m_pQSink; // Target for Quality messages LONG m_TypeVersion; // Holds current type version CMediaType m_mt; // Media type of connection CRefTime m_tStart; // time from NewSegment call CRefTime m_tStop; // time from NewSegment double m_dRate; // rate from NewSegment #ifdef DEBUG LONG m_cRef; // Ref count tracing #endif // displays pin connection information #ifdef DEBUG void DisplayPinInfo(IPin *pReceivePin); void DisplayTypeInfo(IPin *pPin, const CMediaType *pmt); #else void DisplayPinInfo(IPin *pReceivePin){}; void DisplayTypeInfo(IPin *pPin, const CMediaType *pmt){}; #endif // used to agree a media type for a pin connection // given a specific media type, attempt a connection (includes // checking that the type is acceptable to this pin) HRESULT AttemptConnection(IPin *pReceivePin, // connect to this pin const CMediaType *pmt // using this type ); // try all the media types in this enumerator - for each that // we accept, try to connect using ReceiveConnection. HRESULT TryMediaTypes(IPin *pReceivePin, // connect to this pin __in_opt const CMediaType *pmt, // proposed type from Connect IEnumMediaTypes *pEnum); // try this enumerator // establish a connection with a suitable mediatype. Needs to // propose a media type if the pmt pointer is null or partially // specified - use TryMediaTypes on both our and then the other pin's // enumerator until we find one that works. HRESULT AgreeMediaType(IPin *pReceivePin, // connect to this pin const CMediaType *pmt); // proposed type from Connect public: CBasePin(__in_opt LPCTSTR pObjectName, // Object description __in CBaseFilter *pFilter, // Owning filter who knows about pins __in CCritSec *pLock, // Object who implements the lock __inout HRESULT *phr, // General OLE return code __in_opt LPCWSTR pName, // Pin name for us PIN_DIRECTION dir); // Either PINDIR_INPUT or PINDIR_OUTPUT #ifdef UNICODE CBasePin(__in_opt LPCSTR pObjectName, // Object description __in CBaseFilter *pFilter, // Owning filter who knows about pins __in CCritSec *pLock, // Object who implements the lock __inout HRESULT *phr, // General OLE return code __in_opt LPCWSTR pName, // Pin name for us PIN_DIRECTION dir); // Either PINDIR_INPUT or PINDIR_OUTPUT #endif virtual ~CBasePin(); DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) NonDelegatingRelease(); STDMETHODIMP_(ULONG) NonDelegatingAddRef(); // --- IPin methods --- // take lead role in establishing a connection. Media type pointer // may be null, or may point to partially-specified mediatype // (subtype or format type may be GUID_NULL). STDMETHODIMP Connect(IPin *pReceivePin, __in_opt const AM_MEDIA_TYPE *pmt // optional media type ); // (passive) accept a connection from another pin STDMETHODIMP ReceiveConnection(IPin *pConnector, // this is the initiating connecting pin const AM_MEDIA_TYPE *pmt // this is the media type we will exchange ); STDMETHODIMP Disconnect(); STDMETHODIMP ConnectedTo(__deref_out IPin **pPin); STDMETHODIMP ConnectionMediaType(__out AM_MEDIA_TYPE *pmt); STDMETHODIMP QueryPinInfo(__out PIN_INFO *pInfo); STDMETHODIMP QueryDirection(__out PIN_DIRECTION *pPinDir); STDMETHODIMP QueryId(__deref_out LPWSTR *Id); // does the pin support this media type STDMETHODIMP QueryAccept(const AM_MEDIA_TYPE *pmt); // return an enumerator for this pins preferred media types STDMETHODIMP EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum); // return an array of IPin* - the pins that this pin internally connects to // All pins put in the array must be AddReffed (but no others) // Errors: "Can't say" - FAIL, not enough slots - return S_FALSE // Default: return E_NOTIMPL // The filter graph will interpret NOT_IMPL as any input pin connects to // all visible output pins and vice versa. // apPin can be NULL if nPin==0 (not otherwise). STDMETHODIMP QueryInternalConnections(__out_ecount_part(*nPin, *nPin) IPin **apPin, // array of IPin* __inout ULONG *nPin // on input, the number of slots // on output the number of pins ) { return E_NOTIMPL; } // Called when no more data will be sent STDMETHODIMP EndOfStream(void); // Begin/EndFlush still PURE // NewSegment notifies of the start/stop/rate applying to the data // about to be received. Default implementation records data and // returns S_OK. // Override this to pass downstream. STDMETHODIMP NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); //================================================================================ // IQualityControl methods //================================================================================ STDMETHODIMP Notify(IBaseFilter *pSender, Quality q); STDMETHODIMP SetSink(IQualityControl *piqc); // --- helper methods --- // Returns true if the pin is connected. false otherwise. BOOL IsConnected(void) { return (m_Connected != NULL); }; // Return the pin this is connected to (if any) IPin *GetConnected() { return m_Connected; }; // Check if our filter is currently stopped BOOL IsStopped() { return (m_pFilter->m_State == State_Stopped); }; // find out the current type version (used by enumerators) virtual LONG GetMediaTypeVersion(); void IncrementTypeVersion(); // switch the pin to active (paused or running) mode // not an error to call this if already active virtual HRESULT Active(void); // switch the pin to inactive state - may already be inactive virtual HRESULT Inactive(void); // Notify of Run() from filter virtual HRESULT Run(REFERENCE_TIME tStart); // check if the pin can support this specific proposed type and format virtual HRESULT CheckMediaType(const CMediaType *) PURE; // set the connection to use this format (previously agreed) virtual HRESULT SetMediaType(const CMediaType *); // check that the connection is ok before verifying it // can be overridden eg to check what interfaces will be supported. virtual HRESULT CheckConnect(IPin *); // Set and release resources required for a connection virtual HRESULT BreakConnect(); virtual HRESULT CompleteConnect(IPin *pReceivePin); // returns the preferred formats for a pin virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); // access to NewSegment values REFERENCE_TIME CurrentStopTime() { return m_tStop; } REFERENCE_TIME CurrentStartTime() { return m_tStart; } double CurrentRate() { return m_dRate; } // Access name LPWSTR Name() { return m_pName; }; // Can reconnectwhen active? void SetReconnectWhenActive(bool bCanReconnect) { m_bCanReconnectWhenActive = bCanReconnect; } bool CanReconnectWhenActive() { return m_bCanReconnectWhenActive; } protected: STDMETHODIMP DisconnectInternal(); }; //===================================================================== //===================================================================== // Defines CEnumPins // // Pin enumerator class that works by calling CBaseFilter. This interface // is provided by CBaseFilter::EnumPins and calls GetPinCount() and // GetPin() to enumerate existing pins. Needs to be a separate object so // that it can be cloned (creating an existing object at the same // position in the enumeration) // //===================================================================== //===================================================================== class CEnumPins : public IEnumPins // The interface we support { int m_Position; // Current ordinal position int m_PinCount; // Number of pins available CBaseFilter *m_pFilter; // The filter who owns us LONG m_Version; // Pin version information LONG m_cRef; typedef CGenericList CPinList; CPinList m_PinCache; // These pointers have not been AddRef'ed and // so they should not be dereferenced. They are // merely kept to ID which pins have been enumerated. #ifdef DEBUG DWORD m_dwCookie; #endif /* If while we are retrieving a pin for example from the filter an error occurs we assume that our internal state is stale with respect to the filter (someone may have deleted all the pins). We can check before starting whether or not the operation is likely to fail by asking the filter what it's current version number is. If the filter has not overriden the GetPinVersion method then this will always match */ BOOL AreWeOutOfSync() { return (m_pFilter->GetPinVersion() == m_Version ? FALSE : TRUE); }; /* This method performs the same operations as Reset, except is does not clear the cache of pins already enumerated. */ STDMETHODIMP Refresh(); public: CEnumPins(__in CBaseFilter *pFilter, __in_opt CEnumPins *pEnumPins); virtual ~CEnumPins(); // IUnknown STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IEnumPins STDMETHODIMP Next(ULONG cPins, // place this many pins... __out_ecount(cPins) IPin **ppPins, // ...in this array of IPin* __out_opt ULONG *pcFetched // actual count passed returned here ); STDMETHODIMP Skip(ULONG cPins); STDMETHODIMP Reset(); STDMETHODIMP Clone(__deref_out IEnumPins **ppEnum); }; //===================================================================== //===================================================================== // Defines CEnumMediaTypes // // Enumerates the preferred formats for input and output pins //===================================================================== //===================================================================== class CEnumMediaTypes : public IEnumMediaTypes // The interface we support { int m_Position; // Current ordinal position CBasePin *m_pPin; // The pin who owns us LONG m_Version; // Media type version value LONG m_cRef; #ifdef DEBUG DWORD m_dwCookie; #endif /* The media types a filter supports can be quite dynamic so we add to the general IEnumXXXX interface the ability to be signaled when they change via an event handle the connected filter supplies. Until the Reset method is called after the state changes all further calls to the enumerator (except Reset) will return E_UNEXPECTED error code */ BOOL AreWeOutOfSync() { return (m_pPin->GetMediaTypeVersion() == m_Version ? FALSE : TRUE); }; public: CEnumMediaTypes(__in CBasePin *pPin, __in_opt CEnumMediaTypes *pEnumMediaTypes); virtual ~CEnumMediaTypes(); // IUnknown STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IEnumMediaTypes STDMETHODIMP Next(ULONG cMediaTypes, // place this many pins... __out_ecount(cMediaTypes) AM_MEDIA_TYPE **ppMediaTypes, // ...in this array __out_opt ULONG *pcFetched // actual count passed ); STDMETHODIMP Skip(ULONG cMediaTypes); STDMETHODIMP Reset(); STDMETHODIMP Clone(__deref_out IEnumMediaTypes **ppEnum); }; //===================================================================== //===================================================================== // Defines CBaseOutputPin // // class derived from CBasePin that can pass buffers to a connected pin // that supports IMemInputPin. Supports IPin. // // Derive your output pin from this. // //===================================================================== //===================================================================== class AM_NOVTABLE CBaseOutputPin : public CBasePin { protected: IMemAllocator *m_pAllocator; IMemInputPin *m_pInputPin; // interface on the downstreaminput pin // set up in CheckConnect when we connect. public: CBaseOutputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); #ifdef UNICODE CBaseOutputPin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); #endif // override CompleteConnect() so we can negotiate an allocator virtual HRESULT CompleteConnect(IPin *pReceivePin); // negotiate the allocator and its buffer size/count and other properties // Calls DecideBufferSize to set properties virtual HRESULT DecideAllocator(IMemInputPin *pPin, __deref_out IMemAllocator **pAlloc); // override this to set the buffer size and count. Return an error // if the size/count is not to your liking. // The allocator properties passed in are those requested by the // input pin - use eg the alignment and prefix members if you have // no preference on these. virtual HRESULT DecideBufferSize(IMemAllocator *pAlloc, __inout ALLOCATOR_PROPERTIES *ppropInputRequest) PURE; // returns an empty sample buffer from the allocator virtual HRESULT GetDeliveryBuffer(__deref_out IMediaSample **ppSample, __in_opt REFERENCE_TIME *pStartTime, __in_opt REFERENCE_TIME *pEndTime, DWORD dwFlags); // deliver a filled-in sample to the connected input pin // note - you need to release it after calling this. The receiving // pin will addref the sample if it needs to hold it beyond the // call. virtual HRESULT Deliver(IMediaSample *); // override this to control the connection virtual HRESULT InitAllocator(__deref_out IMemAllocator **ppAlloc); HRESULT CheckConnect(IPin *pPin); HRESULT BreakConnect(); // override to call Commit and Decommit HRESULT Active(void); HRESULT Inactive(void); // we have a default handling of EndOfStream which is to return // an error, since this should be called on input pins only STDMETHODIMP EndOfStream(void); // called from elsewhere in our filter to pass EOS downstream to // our connected input pin virtual HRESULT DeliverEndOfStream(void); // same for Begin/EndFlush - we handle Begin/EndFlush since it // is an error on an output pin, and we have Deliver methods to // call the methods on the connected pin STDMETHODIMP BeginFlush(void); STDMETHODIMP EndFlush(void); virtual HRESULT DeliverBeginFlush(void); virtual HRESULT DeliverEndFlush(void); // deliver NewSegment to connected pin - you will need to // override this if you queue any data in your output pin. virtual HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); //================================================================================ // IQualityControl methods //================================================================================ // All inherited from CBasePin and not overridden here. // STDMETHODIMP Notify(IBaseFilter * pSender, Quality q); // STDMETHODIMP SetSink(IQualityControl * piqc); }; //===================================================================== //===================================================================== // Defines CBaseInputPin // // derive your standard input pin from this. // you need to supply GetMediaType and CheckConnect etc (see CBasePin), // and you need to supply Receive to do something more useful. // //===================================================================== //===================================================================== class AM_NOVTABLE CBaseInputPin : public CBasePin , public IMemInputPin { protected: IMemAllocator *m_pAllocator; // Default memory allocator // allocator is read-only, so received samples // cannot be modified (probably only relevant to in-place // transforms BYTE m_bReadOnly; // in flushing state (between BeginFlush and EndFlush) // if TRUE, all Receives are returned with S_FALSE BYTE m_bFlushing; // Sample properties - initalized in Receive AM_SAMPLE2_PROPERTIES m_SampleProps; public: CBaseInputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); #ifdef UNICODE CBaseInputPin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); #endif virtual ~CBaseInputPin(); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // return the allocator interface that this input pin // would like the output pin to use STDMETHODIMP GetAllocator(__deref_out IMemAllocator **ppAllocator); // tell the input pin which allocator the output pin is actually // going to use. STDMETHODIMP NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly); // do something with this media sample STDMETHODIMP Receive(IMediaSample *pSample); // do something with these media samples STDMETHODIMP ReceiveMultiple(__in_ecount(nSamples) IMediaSample **pSamples, long nSamples, __out long *nSamplesProcessed); // See if Receive() blocks STDMETHODIMP ReceiveCanBlock(); // Default handling for BeginFlush - call at the beginning // of your implementation (makes sure that all Receive calls // fail). After calling this, you need to free any queued data // and then call downstream. STDMETHODIMP BeginFlush(void); // default handling for EndFlush - call at end of your implementation // - before calling this, ensure that there is no queued data and no thread // pushing any more without a further receive, then call downstream, // then call this method to clear the m_bFlushing flag and re-enable // receives STDMETHODIMP EndFlush(void); // this method is optional (can return E_NOTIMPL). // default implementation returns E_NOTIMPL. Override if you have // specific alignment or prefix needs, but could use an upstream // allocator STDMETHODIMP GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES *pProps); // Release the pin's allocator. HRESULT BreakConnect(); // helper method to check the read-only flag BOOL IsReadOnly() { return m_bReadOnly; }; // helper method to see if we are flushing BOOL IsFlushing() { return m_bFlushing; }; // Override this for checking whether it's OK to process samples // Also call this from EndOfStream. virtual HRESULT CheckStreaming(); // Pass a Quality notification on to the appropriate sink HRESULT PassNotify(Quality &q); //================================================================================ // IQualityControl methods (from CBasePin) //================================================================================ STDMETHODIMP Notify(IBaseFilter *pSender, Quality q); // no need to override: // STDMETHODIMP SetSink(IQualityControl * piqc); // switch the pin to inactive state - may already be inactive virtual HRESULT Inactive(void); // Return sample properties pointer AM_SAMPLE2_PROPERTIES *SampleProps() { ASSERT(m_SampleProps.cbData != 0); return &m_SampleProps; } }; /////////////////////////////////////////////////////////////////////////// // CDynamicOutputPin // class CDynamicOutputPin : public CBaseOutputPin , public IPinFlowControl { public: #ifdef UNICODE CDynamicOutputPin(__in_opt LPCSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); #endif CDynamicOutputPin(__in_opt LPCTSTR pObjectName, __in CBaseFilter *pFilter, __in CCritSec *pLock, __inout HRESULT *phr, __in_opt LPCWSTR pName); ~CDynamicOutputPin(); // IUnknown Methods DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // IPin Methods STDMETHODIMP Disconnect(void); // IPinFlowControl Methods STDMETHODIMP Block(DWORD dwBlockFlags, HANDLE hEvent); // Set graph config info void SetConfigInfo(IGraphConfig *pGraphConfig, HANDLE hStopEvent); #ifdef DEBUG virtual HRESULT Deliver(IMediaSample *pSample); virtual HRESULT DeliverEndOfStream(void); virtual HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); #endif // DEBUG HRESULT DeliverBeginFlush(void); HRESULT DeliverEndFlush(void); HRESULT Inactive(void); HRESULT Active(void); virtual HRESULT CompleteConnect(IPin *pReceivePin); virtual HRESULT StartUsingOutputPin(void); virtual void StopUsingOutputPin(void); virtual bool StreamingThreadUsingOutputPin(void); HRESULT ChangeOutputFormat(const AM_MEDIA_TYPE *pmt, REFERENCE_TIME tSegmentStart, REFERENCE_TIME tSegmentStop, double dSegmentRate); HRESULT ChangeMediaType(const CMediaType *pmt); HRESULT DynamicReconnect(const CMediaType *pmt); protected: HRESULT SynchronousBlockOutputPin(void); HRESULT AsynchronousBlockOutputPin(HANDLE hNotifyCallerPinBlockedEvent); HRESULT UnblockOutputPin(void); void BlockOutputPin(void); void ResetBlockState(void); static HRESULT WaitEvent(HANDLE hEvent); enum BLOCK_STATE { NOT_BLOCKED, PENDING, BLOCKED }; // This lock should be held when the following class members are // being used: m_hNotifyCallerPinBlockedEvent, m_BlockState, // m_dwBlockCallerThreadID and m_dwNumOutstandingOutputPinUsers. CCritSec m_BlockStateLock; // This event should be signaled when the output pin is // not blocked. This is a manual reset event. For more // information on events, see the documentation for // CreateEvent() in the Windows SDK. HANDLE m_hUnblockOutputPinEvent; // This event will be signaled when block operation succeedes or // when the user cancels the block operation. The block operation // can be canceled by calling IPinFlowControl2::Block( 0, NULL ) // while the block operation is pending. HANDLE m_hNotifyCallerPinBlockedEvent; // The state of the current block operation. BLOCK_STATE m_BlockState; // The ID of the thread which last called IPinFlowControl::Block(). // For more information on thread IDs, see the documentation for // GetCurrentThreadID() in the Windows SDK. DWORD m_dwBlockCallerThreadID; // The number of times StartUsingOutputPin() has been sucessfully // called and a corresponding call to StopUsingOutputPin() has not // been made. When this variable is greater than 0, the streaming // thread is calling IPin::NewSegment(), IPin::EndOfStream(), // IMemInputPin::Receive() or IMemInputPin::ReceiveMultiple(). The // streaming thread could also be calling: DynamicReconnect(), // ChangeMediaType() or ChangeOutputFormat(). The output pin cannot // be blocked while the output pin is being used. DWORD m_dwNumOutstandingOutputPinUsers; // This event should be set when the IMediaFilter::Stop() is called. // This is a manual reset event. It is also set when the output pin // delivers a flush to the connected input pin. HANDLE m_hStopEvent; IGraphConfig *m_pGraphConfig; // TRUE if the output pin's allocator's samples are read only. // Otherwise FALSE. For more information, see the documentation // for IMemInputPin::NotifyAllocator(). BOOL m_bPinUsesReadOnlyAllocator; private: HRESULT Initialize(void); HRESULT ChangeMediaTypeHelper(const CMediaType *pmt); #ifdef DEBUG void AssertValid(void); #endif // DEBUG }; class CAutoUsingOutputPin { public: CAutoUsingOutputPin(__in CDynamicOutputPin *pOutputPin, __inout HRESULT *phr); ~CAutoUsingOutputPin(); private: CDynamicOutputPin *m_pOutputPin; }; inline CAutoUsingOutputPin::CAutoUsingOutputPin(__in CDynamicOutputPin *pOutputPin, __inout HRESULT *phr) : m_pOutputPin(NULL) { // The caller should always pass in valid pointers. ASSERT(NULL != pOutputPin); ASSERT(NULL != phr); // Make sure the user initialized phr. ASSERT(S_OK == *phr); HRESULT hr = pOutputPin->StartUsingOutputPin(); if (FAILED(hr)) { *phr = hr; return; } m_pOutputPin = pOutputPin; } inline CAutoUsingOutputPin::~CAutoUsingOutputPin() { if (NULL != m_pOutputPin) { m_pOutputPin->StopUsingOutputPin(); } } #ifdef DEBUG inline HRESULT CDynamicOutputPin::Deliver(IMediaSample *pSample) { // The caller should call StartUsingOutputPin() before calling this // method. ASSERT(StreamingThreadUsingOutputPin()); return CBaseOutputPin::Deliver(pSample); } inline HRESULT CDynamicOutputPin::DeliverEndOfStream(void) { // The caller should call StartUsingOutputPin() before calling this // method. ASSERT(StreamingThreadUsingOutputPin()); return CBaseOutputPin::DeliverEndOfStream(); } inline HRESULT CDynamicOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { // The caller should call StartUsingOutputPin() before calling this // method. ASSERT(StreamingThreadUsingOutputPin()); return CBaseOutputPin::DeliverNewSegment(tStart, tStop, dRate); } #endif // DEBUG //===================================================================== //===================================================================== // Memory allocators // // the shared memory transport between pins requires the input pin // to provide a memory allocator that can provide sample objects. A // sample object supports the IMediaSample interface. // // CBaseAllocator handles the management of free and busy samples. It // allocates CMediaSample objects. CBaseAllocator is an abstract class: // in particular it has no method of initializing the list of free // samples. CMemAllocator is derived from CBaseAllocator and initializes // the list of samples using memory from the standard IMalloc interface. // // If you want your buffers to live in some special area of memory, // derive your allocator object from CBaseAllocator. If you derive your // IMemInputPin interface object from CBaseMemInputPin, you will get // CMemAllocator-based allocation etc for free and will just need to // supply the Receive handling, and media type / format negotiation. //===================================================================== //===================================================================== //===================================================================== //===================================================================== // Defines CMediaSample // // an object of this class supports IMediaSample and represents a buffer // for media data with some associated properties. Releasing it returns // it to a freelist managed by a CBaseAllocator derived object. //===================================================================== //===================================================================== class CMediaSample : public IMediaSample2 // The interface we support { protected: friend class CBaseAllocator; /* Values for dwFlags - these are used for backward compatiblity only now - use AM_SAMPLE_xxx */ enum { Sample_SyncPoint = 0x01, /* Is this a sync point */ Sample_Preroll = 0x02, /* Is this a preroll sample */ Sample_Discontinuity = 0x04, /* Set if start of new segment */ Sample_TypeChanged = 0x08, /* Has the type changed */ Sample_TimeValid = 0x10, /* Set if time is valid */ Sample_MediaTimeValid = 0x20, /* Is the media time valid */ Sample_TimeDiscontinuity = 0x40, /* Time discontinuity */ Sample_StopValid = 0x100, /* Stop time valid */ Sample_ValidFlags = 0x1FF }; /* Properties, the media sample class can be a container for a format change in which case we take a copy of a type through the SetMediaType interface function and then return it when GetMediaType is called. As we do no internal processing on it we leave it as a pointer */ DWORD m_dwFlags; /* Flags for this sample */ /* Type specific flags are packed into the top word */ DWORD m_dwTypeSpecificFlags; /* Media type specific flags */ __field_ecount_opt(m_cbBuffer) LPBYTE m_pBuffer; /* Pointer to the complete buffer */ LONG m_lActual; /* Length of data in this sample */ LONG m_cbBuffer; /* Size of the buffer */ CBaseAllocator *m_pAllocator; /* The allocator who owns us */ CMediaSample *m_pNext; /* Chaining in free list */ REFERENCE_TIME m_Start; /* Start sample time */ REFERENCE_TIME m_End; /* End sample time */ LONGLONG m_MediaStart; /* Real media start position */ LONG m_MediaEnd; /* A difference to get the end */ AM_MEDIA_TYPE *m_pMediaType; /* Media type change data */ DWORD m_dwStreamId; /* Stream id */ public: LONG m_cRef; /* Reference count */ public: CMediaSample(__in_opt LPCTSTR pName, __in_opt CBaseAllocator *pAllocator, __inout_opt HRESULT *phr, __in_bcount_opt(length) LPBYTE pBuffer = NULL, LONG length = 0); #ifdef UNICODE CMediaSample(__in_opt LPCSTR pName, __in_opt CBaseAllocator *pAllocator, __inout_opt HRESULT *phr, __in_bcount_opt(length) LPBYTE pBuffer = NULL, LONG length = 0); #endif virtual ~CMediaSample(); /* Note the media sample does not delegate to its owner */ STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // set the buffer pointer and length. Used by allocators that // want variable sized pointers or pointers into already-read data. // This is only available through a CMediaSample* not an IMediaSample* // and so cannot be changed by clients. HRESULT SetPointer(__in_bcount(cBytes) BYTE *ptr, LONG cBytes); // Get me a read/write pointer to this buffer's memory. STDMETHODIMP GetPointer(__deref_out BYTE **ppBuffer); STDMETHODIMP_(LONG) GetSize(void); // get the stream time at which this sample should start and finish. STDMETHODIMP GetTime(__out REFERENCE_TIME *pTimeStart, // put time here __out REFERENCE_TIME *pTimeEnd); // Set the stream time at which this sample should start and finish. STDMETHODIMP SetTime(__in_opt REFERENCE_TIME *pTimeStart, // put time here __in_opt REFERENCE_TIME *pTimeEnd); STDMETHODIMP IsSyncPoint(void); STDMETHODIMP SetSyncPoint(BOOL bIsSyncPoint); STDMETHODIMP IsPreroll(void); STDMETHODIMP SetPreroll(BOOL bIsPreroll); STDMETHODIMP_(LONG) GetActualDataLength(void); STDMETHODIMP SetActualDataLength(LONG lActual); // these allow for limited format changes in band STDMETHODIMP GetMediaType(__deref_out AM_MEDIA_TYPE **ppMediaType); STDMETHODIMP SetMediaType(__in_opt AM_MEDIA_TYPE *pMediaType); // returns S_OK if there is a discontinuity in the data (this same is // not a continuation of the previous stream of data // - there has been a seek). STDMETHODIMP IsDiscontinuity(void); // set the discontinuity property - TRUE if this sample is not a // continuation, but a new sample after a seek. STDMETHODIMP SetDiscontinuity(BOOL bDiscontinuity); // get the media times for this sample STDMETHODIMP GetMediaTime(__out LONGLONG *pTimeStart, __out LONGLONG *pTimeEnd); // Set the media times for this sample STDMETHODIMP SetMediaTime(__in_opt LONGLONG *pTimeStart, __in_opt LONGLONG *pTimeEnd); // Set and get properties (IMediaSample2) STDMETHODIMP GetProperties(DWORD cbProperties, __out_bcount(cbProperties) BYTE *pbProperties); STDMETHODIMP SetProperties(DWORD cbProperties, __in_bcount(cbProperties) const BYTE *pbProperties); }; //===================================================================== //===================================================================== // Defines CBaseAllocator // // Abstract base class that manages a list of media samples // // This class provides support for getting buffers from the free list, // including handling of commit and (asynchronous) decommit. // // Derive from this class and override the Alloc and Free functions to // allocate your CMediaSample (or derived) objects and add them to the // free list, preparing them as necessary. //===================================================================== //===================================================================== class AM_NOVTABLE CBaseAllocator : public CUnknown , // A non delegating IUnknown public IMemAllocatorCallbackTemp , // The interface we support public CCritSec // Provides object locking { class CSampleList; friend class CSampleList; /* Trick to get at protected member in CMediaSample */ static CMediaSample *&NextSample(__in CMediaSample *pSample) { return pSample->m_pNext; }; /* Mini list class for the free list */ class CSampleList { public: CSampleList() : m_List(NULL) , m_nOnList(0){}; #ifdef DEBUG ~CSampleList() { ASSERT(m_nOnList == 0); }; #endif CMediaSample *Head() const { return m_List; }; CMediaSample *Next(__in CMediaSample *pSample) const { return CBaseAllocator::NextSample(pSample); }; int GetCount() const { return m_nOnList; }; void Add(__inout CMediaSample *pSample) { ASSERT(pSample != NULL); CBaseAllocator::NextSample(pSample) = m_List; m_List = pSample; m_nOnList++; }; CMediaSample *RemoveHead() { CMediaSample *pSample = m_List; if (pSample != NULL) { m_List = CBaseAllocator::NextSample(m_List); m_nOnList--; } return pSample; }; void Remove(__inout CMediaSample *pSample); public: CMediaSample *m_List; int m_nOnList; }; protected: CSampleList m_lFree; // Free list /* Note to overriders of CBaseAllocator. We use a lazy signalling mechanism for waiting for samples. This means we don't call the OS if no waits occur. In order to implement this: 1. When a new sample is added to m_lFree call NotifySample() which calls ReleaseSemaphore on m_hSem with a count of m_lWaiting and sets m_lWaiting to 0. This must all be done holding the allocator's critical section. 2. When waiting for a sample call SetWaiting() which increments m_lWaiting BEFORE leaving the allocator's critical section. 3. Actually wait by calling WaitForSingleObject(m_hSem, INFINITE) having left the allocator's critical section. The effect of this is to remove 1 from the semaphore's count. You MUST call this once having incremented m_lWaiting. The following are then true when the critical section is not held : (let nWaiting = number about to wait or waiting) (1) if (m_lFree.GetCount() != 0) then (m_lWaiting == 0) (2) m_lWaiting + Semaphore count == nWaiting We would deadlock if nWaiting != 0 && m_lFree.GetCount() != 0 && Semaphore count == 0 But from (1) if m_lFree.GetCount() != 0 then m_lWaiting == 0 so from (2) Semaphore count == nWaiting (which is non-0) so the deadlock can't happen. */ HANDLE m_hSem; // For signalling long m_lWaiting; // Waiting for a free element long m_lCount; // how many buffers we have agreed to provide long m_lAllocated; // how many buffers are currently allocated long m_lSize; // agreed size of each buffer long m_lAlignment; // agreed alignment long m_lPrefix; // agreed prefix (preceeds GetPointer() value) BOOL m_bChanged; // Have the buffer requirements changed // if true, we are decommitted and can't allocate memory BOOL m_bCommitted; // if true, the decommit has happened, but we haven't called Free yet // as there are still outstanding buffers BOOL m_bDecommitInProgress; // Notification interface IMemAllocatorNotifyCallbackTemp *m_pNotify; BOOL m_fEnableReleaseCallback; // called to decommit the memory when the last buffer is freed // pure virtual - need to override this virtual void Free(void) PURE; // override to allocate the memory when commit called virtual HRESULT Alloc(void); public: CBaseAllocator(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, __inout HRESULT *, BOOL bEvent = TRUE, BOOL fEnableReleaseCallback = FALSE); #ifdef UNICODE CBaseAllocator(__in_opt LPCSTR, __inout_opt LPUNKNOWN, __inout HRESULT *, BOOL bEvent = TRUE, BOOL fEnableReleaseCallback = FALSE); #endif virtual ~CBaseAllocator(); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP SetProperties(__in ALLOCATOR_PROPERTIES *pRequest, __out ALLOCATOR_PROPERTIES *pActual); // return the properties actually being used on this allocator STDMETHODIMP GetProperties(__out ALLOCATOR_PROPERTIES *pProps); // override Commit to allocate memory. We handle the GetBuffer // state changes STDMETHODIMP Commit(); // override this to handle the memory freeing. We handle any outstanding // GetBuffer calls STDMETHODIMP Decommit(); // get container for a sample. Blocking, synchronous call to get the // next free buffer (as represented by an IMediaSample interface). // on return, the time etc properties will be invalid, but the buffer // pointer and size will be correct. The two time parameters are // optional and either may be NULL, they may alternatively be set to // the start and end times the sample will have attached to it // bPrevFramesSkipped is not used (used only by the video renderer's // allocator where it affects quality management in direct draw). STDMETHODIMP GetBuffer(__deref_out IMediaSample **ppBuffer, __in_opt REFERENCE_TIME *pStartTime, __in_opt REFERENCE_TIME *pEndTime, DWORD dwFlags); // final release of a CMediaSample will call this STDMETHODIMP ReleaseBuffer(IMediaSample *pBuffer); // obsolete:: virtual void PutOnFreeList(CMediaSample * pSample); STDMETHODIMP SetNotify(IMemAllocatorNotifyCallbackTemp *pNotify); STDMETHODIMP GetFreeCount(__out LONG *plBuffersFree); // Notify that a sample is available void NotifySample(); // Notify that we're waiting for a sample void SetWaiting() { m_lWaiting++; }; }; //===================================================================== //===================================================================== // Defines CMemAllocator // // this is an allocator based on CBaseAllocator that allocates sample // buffers in main memory (from 'new'). You must call SetProperties // before calling Commit. // // we don't free the memory when going into Decommit state. The simplest // way to implement this without complicating CBaseAllocator is to // have a Free() function, called to go into decommit state, that does // nothing and a ReallyFree function called from our destructor that // actually frees the memory. //===================================================================== //===================================================================== // Make me one from quartz.dll STDAPI CreateMemoryAllocator(__deref_out IMemAllocator **ppAllocator); class CMemAllocator : public CBaseAllocator { protected: LPBYTE m_pBuffer; // combined memory for all buffers // override to free the memory when decommit completes // - we actually do nothing, and save the memory until deletion. void Free(void); // called from the destructor (and from Alloc if changing size/count) to // actually free up the memory void ReallyFree(void); // overriden to allocate the memory when commit called HRESULT Alloc(void); public: /* This goes in the factory template table to create new instances */ static CUnknown *CreateInstance(__inout_opt LPUNKNOWN, __inout HRESULT *); STDMETHODIMP SetProperties(__in ALLOCATOR_PROPERTIES *pRequest, __out ALLOCATOR_PROPERTIES *pActual); CMemAllocator(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, __inout HRESULT *); #ifdef UNICODE CMemAllocator(__in_opt LPCSTR, __inout_opt LPUNKNOWN, __inout HRESULT *); #endif ~CMemAllocator(); }; // helper used by IAMovieSetup implementation STDAPI AMovieSetupRegisterFilter(const AMOVIESETUP_FILTER *const psetupdata, IFilterMapper *pIFM, BOOL bRegister); /////////////////////////////////////////////////////////////////////////// // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /////////////////////////////////////////////////////////////////////////// #endif /* __FILTER__ */ ================================================ FILE: common/baseclasses/amvideo.cpp ================================================ //------------------------------------------------------------------------------ // File: AMVideo.cpp // // Desc: DirectShow base classes - implements helper functions for // bitmap formats. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include // These are bit field masks for true colour devices const DWORD bits555[] = {0x007C00, 0x0003E0, 0x00001F}; const DWORD bits565[] = {0x00F800, 0x0007E0, 0x00001F}; const DWORD bits888[] = {0xFF0000, 0x00FF00, 0x0000FF}; // This maps bitmap subtypes into a bits per pixel value and also a // name. unicode and ansi versions are stored because we have to // return a pointer to a static string. // clang-format off const struct { const GUID *pSubtype; WORD BitCount; CHAR *pName; WCHAR *wszName; } BitCountMap[] = { &MEDIASUBTYPE_RGB1, 1, "RGB Monochrome", L"RGB Monochrome", &MEDIASUBTYPE_RGB4, 4, "RGB VGA", L"RGB VGA", &MEDIASUBTYPE_RGB8, 8, "RGB 8", L"RGB 8", &MEDIASUBTYPE_RGB565, 16, "RGB 565 (16 bit)", L"RGB 565 (16 bit)", &MEDIASUBTYPE_RGB555, 16, "RGB 555 (16 bit)", L"RGB 555 (16 bit)", &MEDIASUBTYPE_RGB24, 24, "RGB 24", L"RGB 24", &MEDIASUBTYPE_RGB32, 32, "RGB 32", L"RGB 32", &MEDIASUBTYPE_ARGB32, 32, "ARGB 32", L"ARGB 32", &MEDIASUBTYPE_Overlay, 0, "Overlay", L"Overlay", &GUID_NULL, 0, "UNKNOWN", L"UNKNOWN" }; // clang-format on // Return the size of the bitmap as defined by this header STDAPI_(DWORD) GetBitmapSize(const BITMAPINFOHEADER *pHeader) { return DIBSIZE(*pHeader); } // This is called if the header has a 16 bit colour depth and needs to work // out the detailed type from the bit fields (either RGB 565 or RGB 555) STDAPI_(const GUID) GetTrueColorType(const BITMAPINFOHEADER *pbmiHeader) { BITMAPINFO *pbmInfo = (BITMAPINFO *)pbmiHeader; ASSERT(pbmiHeader->biBitCount == 16); // If its BI_RGB then it's RGB 555 by default if (pbmiHeader->biCompression == BI_RGB) { return MEDIASUBTYPE_RGB555; } // Compare the bit fields with RGB 555 DWORD *pMask = (DWORD *)pbmInfo->bmiColors; if (pMask[0] == bits555[0]) { if (pMask[1] == bits555[1]) { if (pMask[2] == bits555[2]) { return MEDIASUBTYPE_RGB555; } } } // Compare the bit fields with RGB 565 pMask = (DWORD *)pbmInfo->bmiColors; if (pMask[0] == bits565[0]) { if (pMask[1] == bits565[1]) { if (pMask[2] == bits565[2]) { return MEDIASUBTYPE_RGB565; } } } return GUID_NULL; } // Given a BITMAPINFOHEADER structure this returns the GUID sub type that is // used to describe it in format negotiations. For example a video codec fills // in the format block with a VIDEOINFO structure, it also fills in the major // type with MEDIATYPE_VIDEO and the subtype with a GUID that matches the bit // count, for example if it is an eight bit image then MEDIASUBTYPE_RGB8 STDAPI_(const GUID) GetBitmapSubtype(const BITMAPINFOHEADER *pbmiHeader) { ASSERT(pbmiHeader); // If it's not RGB then create a GUID from the compression type if (pbmiHeader->biCompression != BI_RGB) { if (pbmiHeader->biCompression != BI_BITFIELDS) { FOURCCMap FourCCMap(pbmiHeader->biCompression); return (const GUID)FourCCMap; } } // Map the RGB DIB bit depth to a image GUID switch (pbmiHeader->biBitCount) { case 1: return MEDIASUBTYPE_RGB1; case 4: return MEDIASUBTYPE_RGB4; case 8: return MEDIASUBTYPE_RGB8; case 16: return GetTrueColorType(pbmiHeader); case 24: return MEDIASUBTYPE_RGB24; case 32: return MEDIASUBTYPE_RGB32; } return GUID_NULL; } // Given a video bitmap subtype we return the number of bits per pixel it uses // We return a WORD bit count as thats what the BITMAPINFOHEADER uses. If the // GUID subtype is not found in the table we return an invalid USHRT_MAX STDAPI_(WORD) GetBitCount(const GUID *pSubtype) { ASSERT(pSubtype); const GUID *pMediaSubtype; INT iPosition = 0; // Scan the mapping list seeing if the source GUID matches any known // bitmap subtypes, the list is terminated by a GUID_NULL entry while (TRUE) { pMediaSubtype = BitCountMap[iPosition].pSubtype; if (IsEqualGUID(*pMediaSubtype, GUID_NULL)) { return USHRT_MAX; } if (IsEqualGUID(*pMediaSubtype, *pSubtype)) { return BitCountMap[iPosition].BitCount; } iPosition++; } } // Given a bitmap subtype we return a description name that can be used for // debug purposes. In a retail build this function still returns the names // If the subtype isn't found in the lookup table we return string UNKNOWN int LocateSubtype(const GUID *pSubtype) { ASSERT(pSubtype); const GUID *pMediaSubtype; INT iPosition = 0; // Scan the mapping list seeing if the source GUID matches any known // bitmap subtypes, the list is terminated by a GUID_NULL entry while (TRUE) { pMediaSubtype = BitCountMap[iPosition].pSubtype; if (IsEqualGUID(*pMediaSubtype, *pSubtype) || IsEqualGUID(*pMediaSubtype, GUID_NULL)) { break; } iPosition++; } return iPosition; } STDAPI_(WCHAR *) GetSubtypeNameW(const GUID *pSubtype) { return BitCountMap[LocateSubtype(pSubtype)].wszName; } STDAPI_(CHAR *) GetSubtypeNameA(const GUID *pSubtype) { return BitCountMap[LocateSubtype(pSubtype)].pName; } #ifndef GetSubtypeName #error wxutil.h should have defined GetSubtypeName #endif #undef GetSubtypeName // this is here for people that linked to it directly; most people // would use the header file that picks the A or W version. STDAPI_(CHAR *) GetSubtypeName(const GUID *pSubtype) { return GetSubtypeNameA(pSubtype); } // The mechanism for describing a bitmap format is with the BITMAPINFOHEADER // This is really messy to deal with because it invariably has fields that // follow it holding bit fields, palettes and the rest. This function gives // the number of bytes required to hold a VIDEOINFO that represents it. This // count includes the prefix information (like the rcSource rectangle) the // BITMAPINFOHEADER field, and any other colour information on the end. // // WARNING If you want to copy a BITMAPINFOHEADER into a VIDEOINFO always make // sure that you use the HEADER macro because the BITMAPINFOHEADER field isn't // right at the start of the VIDEOINFO (there are a number of other fields), // // CopyMemory(HEADER(pVideoInfo),pbmi,sizeof(BITMAPINFOHEADER)); // STDAPI_(LONG) GetBitmapFormatSize(const BITMAPINFOHEADER *pHeader) { // Everyone has this to start with this LONG Size = SIZE_PREHEADER + pHeader->biSize; ASSERT(pHeader->biSize >= sizeof(BITMAPINFOHEADER)); // Does this format use a palette, if the number of colours actually used // is zero then it is set to the maximum that are allowed for that colour // depth (an example is 256 for eight bits). Truecolour formats may also // pass a palette with them in which case the used count is non zero // This would scare me. ASSERT(pHeader->biBitCount <= iPALETTE || pHeader->biClrUsed == 0); if (pHeader->biBitCount <= iPALETTE || pHeader->biClrUsed) { LONG Entries = (DWORD)1 << pHeader->biBitCount; if (pHeader->biClrUsed) { Entries = pHeader->biClrUsed; } Size += Entries * sizeof(RGBQUAD); } // Truecolour formats may have a BI_BITFIELDS specifier for compression // type which means that room for three DWORDs should be allocated that // specify where in each pixel the RGB colour components may be found if (pHeader->biCompression == BI_BITFIELDS) { Size += SIZE_MASKS; } // A BITMAPINFO for a palettised image may also contain a palette map that // provides the information to map from a source palette to a destination // palette during a BitBlt for example, because this information is only // ever processed during drawing you don't normally store the palette map // nor have any way of knowing if it is present in the data structure return Size; } // Returns TRUE if the VIDEOINFO contains a palette STDAPI_(BOOL) ContainsPalette(const VIDEOINFOHEADER *pVideoInfo) { if (PALETTISED(pVideoInfo) == FALSE) { if (pVideoInfo->bmiHeader.biClrUsed == 0) { return FALSE; } } return TRUE; } // Return a pointer to the first entry in a palette STDAPI_(const RGBQUAD *) GetBitmapPalette(const VIDEOINFOHEADER *pVideoInfo) { if (pVideoInfo->bmiHeader.biCompression == BI_BITFIELDS) { return TRUECOLOR(pVideoInfo)->bmiColors; } return COLORS(pVideoInfo); } ================================================ FILE: common/baseclasses/arithutil.cpp ================================================ //------------------------------------------------------------------------------ // File: ArithUtil.cpp // // Desc: DirectShow base classes - implements helper classes for building // multimedia filters. // // Copyright (c) 1992-2004 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include // // Declare function from largeint.h we need so that PPC can build // // // Enlarged integer divide - 64-bits / 32-bits > 32-bits // #ifndef _X86_ #define LLtoU64(x) (*(unsigned __int64 *)(void *)(&(x))) __inline ULONG WINAPI EnlargedUnsignedDivide(IN ULARGE_INTEGER Dividend, IN ULONG Divisor, IN PULONG Remainder) { // return remainder if necessary if (Remainder != NULL) *Remainder = (ULONG)(LLtoU64(Dividend) % Divisor); return (ULONG)(LLtoU64(Dividend) / Divisor); } #else __inline ULONG WINAPI EnlargedUnsignedDivide(IN ULARGE_INTEGER Dividend, IN ULONG Divisor, IN PULONG Remainder) { ULONG ulResult; _asm { mov eax,Dividend.LowPart mov edx,Dividend.HighPart mov ecx,Remainder div Divisor or ecx,ecx jz short label mov [ecx],edx label: mov ulResult,eax } return ulResult; } #endif /* Arithmetic functions to help with time format conversions */ #ifdef _M_ALPHA // work around bug in version 12.00.8385 of the alpha compiler where // UInt32x32To64 sign-extends its arguments (?) #undef UInt32x32To64 #define UInt32x32To64(a, b) (((ULONGLONG)((ULONG)(a)) & 0xffffffff) * ((ULONGLONG)((ULONG)(b)) & 0xffffffff)) #endif /* Compute (a * b + d) / c */ LONGLONG WINAPI llMulDiv(LONGLONG a, LONGLONG b, LONGLONG c, LONGLONG d) { /* Compute the absolute values to avoid signed arithmetic problems */ ULARGE_INTEGER ua, ub; DWORDLONG uc; ua.QuadPart = (DWORDLONG)(a >= 0 ? a : -a); ub.QuadPart = (DWORDLONG)(b >= 0 ? b : -b); uc = (DWORDLONG)(c >= 0 ? c : -c); BOOL bSign = (a < 0) ^ (b < 0); /* Do long multiplication */ ULARGE_INTEGER p[2]; p[0].QuadPart = UInt32x32To64(ua.LowPart, ub.LowPart); /* This next computation cannot overflow into p[1].HighPart because the max number we can compute here is: (2 ** 32 - 1) * (2 ** 32 - 1) + // ua.LowPart * ub.LowPart (2 ** 32) * (2 ** 31) * (2 ** 32 - 1) * 2 // x.LowPart * y.HighPart * 2 == 2 ** 96 - 2 ** 64 + (2 ** 64 - 2 ** 33 + 1) == 2 ** 96 - 2 ** 33 + 1 < 2 ** 96 */ ULARGE_INTEGER x; x.QuadPart = UInt32x32To64(ua.LowPart, ub.HighPart) + UInt32x32To64(ua.HighPart, ub.LowPart) + p[0].HighPart; p[0].HighPart = x.LowPart; p[1].QuadPart = UInt32x32To64(ua.HighPart, ub.HighPart) + x.HighPart; if (d != 0) { ULARGE_INTEGER ud[2]; if (bSign) { ud[0].QuadPart = (DWORDLONG)(-d); if (d > 0) { /* -d < 0 */ ud[1].QuadPart = (DWORDLONG)(LONGLONG)-1; } else { ud[1].QuadPart = (DWORDLONG)0; } } else { ud[0].QuadPart = (DWORDLONG)d; if (d < 0) { ud[1].QuadPart = (DWORDLONG)(LONGLONG)-1; } else { ud[1].QuadPart = (DWORDLONG)0; } } /* Now do extended addition */ ULARGE_INTEGER uliTotal; /* Add ls DWORDs */ uliTotal.QuadPart = (DWORDLONG)ud[0].LowPart + p[0].LowPart; p[0].LowPart = uliTotal.LowPart; /* Propagate carry */ uliTotal.LowPart = uliTotal.HighPart; uliTotal.HighPart = 0; /* Add 2nd most ls DWORDs */ uliTotal.QuadPart += (DWORDLONG)ud[0].HighPart + p[0].HighPart; p[0].HighPart = uliTotal.LowPart; /* Propagate carry */ uliTotal.LowPart = uliTotal.HighPart; uliTotal.HighPart = 0; /* Add MS DWORDLONGs - no carry expected */ p[1].QuadPart += ud[1].QuadPart + uliTotal.QuadPart; /* Now see if we got a sign change from the addition */ if ((LONG)p[1].HighPart < 0) { bSign = !bSign; /* Negate the current value (ugh!) */ p[0].QuadPart = ~p[0].QuadPart; p[1].QuadPart = ~p[1].QuadPart; p[0].QuadPart += 1; p[1].QuadPart += (p[0].QuadPart == 0); } } /* Now for the division */ if (c < 0) { bSign = !bSign; } /* This will catch c == 0 and overflow */ if (uc <= p[1].QuadPart) { return bSign ? (LONGLONG)0x8000000000000000 : (LONGLONG)0x7FFFFFFFFFFFFFFF; } DWORDLONG ullResult; /* Do the division */ /* If the dividend is a DWORD_LONG use the compiler */ if (p[1].QuadPart == 0) { ullResult = p[0].QuadPart / uc; return bSign ? -(LONGLONG)ullResult : (LONGLONG)ullResult; } /* If the divisor is a DWORD then its simpler */ ULARGE_INTEGER ulic; ulic.QuadPart = uc; if (ulic.HighPart == 0) { ULARGE_INTEGER uliDividend; ULARGE_INTEGER uliResult; DWORD dwDivisor = (DWORD)uc; // ASSERT(p[1].HighPart == 0 && p[1].LowPart < dwDivisor); uliDividend.HighPart = p[1].LowPart; uliDividend.LowPart = p[0].HighPart; #ifndef USE_LARGEINT uliResult.HighPart = (DWORD)(uliDividend.QuadPart / dwDivisor); p[0].HighPart = (DWORD)(uliDividend.QuadPart % dwDivisor); uliResult.LowPart = 0; uliResult.QuadPart = p[0].QuadPart / dwDivisor + uliResult.QuadPart; #else /* NOTE - this routine will take exceptions if the result does not fit in a DWORD */ if (uliDividend.QuadPart >= (DWORDLONG)dwDivisor) { uliResult.HighPart = EnlargedUnsignedDivide(uliDividend, dwDivisor, &p[0].HighPart); } else { uliResult.HighPart = 0; } uliResult.LowPart = EnlargedUnsignedDivide(p[0], dwDivisor, NULL); #endif return bSign ? -(LONGLONG)uliResult.QuadPart : (LONGLONG)uliResult.QuadPart; } ullResult = 0; /* OK - do long division */ for (int i = 0; i < 64; i++) { ullResult <<= 1; /* Shift 128 bit p left 1 */ p[1].QuadPart <<= 1; if ((p[0].HighPart & 0x80000000) != 0) { p[1].LowPart++; } p[0].QuadPart <<= 1; /* Compare */ if (uc <= p[1].QuadPart) { p[1].QuadPart -= uc; ullResult += 1; } } return bSign ? -(LONGLONG)ullResult : (LONGLONG)ullResult; } LONGLONG WINAPI Int64x32Div32(LONGLONG a, LONG b, LONG c, LONG d) { ULARGE_INTEGER ua; DWORD ub; DWORD uc; /* Compute the absolute values to avoid signed arithmetic problems */ ua.QuadPart = (DWORDLONG)(a >= 0 ? a : -a); ub = (DWORD)(b >= 0 ? b : -b); uc = (DWORD)(c >= 0 ? c : -c); BOOL bSign = (a < 0) ^ (b < 0); /* Do long multiplication */ ULARGE_INTEGER p0; DWORD p1; p0.QuadPart = UInt32x32To64(ua.LowPart, ub); if (ua.HighPart != 0) { ULARGE_INTEGER x; x.QuadPart = UInt32x32To64(ua.HighPart, ub) + p0.HighPart; p0.HighPart = x.LowPart; p1 = x.HighPart; } else { p1 = 0; } if (d != 0) { ULARGE_INTEGER ud0; DWORD ud1; if (bSign) { // // Cast d to LONGLONG first otherwise -0x80000000 sign extends // incorrectly // ud0.QuadPart = (DWORDLONG)(-(LONGLONG)d); if (d > 0) { /* -d < 0 */ ud1 = (DWORD)-1; } else { ud1 = (DWORD)0; } } else { ud0.QuadPart = (DWORDLONG)d; if (d < 0) { ud1 = (DWORD)-1; } else { ud1 = (DWORD)0; } } /* Now do extended addition */ ULARGE_INTEGER uliTotal; /* Add ls DWORDs */ uliTotal.QuadPart = (DWORDLONG)ud0.LowPart + p0.LowPart; p0.LowPart = uliTotal.LowPart; /* Propagate carry */ uliTotal.LowPart = uliTotal.HighPart; uliTotal.HighPart = 0; /* Add 2nd most ls DWORDs */ uliTotal.QuadPart += (DWORDLONG)ud0.HighPart + p0.HighPart; p0.HighPart = uliTotal.LowPart; /* Add MS DWORDLONGs - no carry expected */ p1 += ud1 + uliTotal.HighPart; /* Now see if we got a sign change from the addition */ if ((LONG)p1 < 0) { bSign = !bSign; /* Negate the current value (ugh!) */ p0.QuadPart = ~p0.QuadPart; p1 = ~p1; p0.QuadPart += 1; p1 += (p0.QuadPart == 0); } } /* Now for the division */ if (c < 0) { bSign = !bSign; } /* This will catch c == 0 and overflow */ if (uc <= p1) { return bSign ? (LONGLONG)0x8000000000000000 : (LONGLONG)0x7FFFFFFFFFFFFFFF; } /* Do the division */ /* If the divisor is a DWORD then its simpler */ ULARGE_INTEGER uliDividend; ULARGE_INTEGER uliResult; DWORD dwDivisor = uc; uliDividend.HighPart = p1; uliDividend.LowPart = p0.HighPart; /* NOTE - this routine will take exceptions if the result does not fit in a DWORD */ if (uliDividend.QuadPart >= (DWORDLONG)dwDivisor) { uliResult.HighPart = EnlargedUnsignedDivide(uliDividend, dwDivisor, &p0.HighPart); } else { uliResult.HighPart = 0; } uliResult.LowPart = EnlargedUnsignedDivide(p0, dwDivisor, NULL); return bSign ? -(LONGLONG)uliResult.QuadPart : (LONGLONG)uliResult.QuadPart; } ================================================ FILE: common/baseclasses/baseclasses.vcxproj ================================================  Debug Win32 Debug x64 Release Win32 Release x64 {E8A3F6FA-AE1C-4C8E-A0B6-9C8480324EAA} BaseClasses Win32Proj StaticLibrary Unicode false true StaticLibrary Unicode true strmbasd strmbase NotUsing strmiids.lib;%(AdditionalDependencies) WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) ================================================ FILE: common/baseclasses/baseclasses.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files ================================================ FILE: common/baseclasses/cache.h ================================================ //------------------------------------------------------------------------------ // File: Cache.h // // Desc: DirectShow base classes - efines a non-MFC generic cache class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ /* This class implements a simple cache. A cache object is instantiated with the number of items it is to hold. An item is a pointer to an object derived from CBaseObject (helps reduce memory leaks). The cache can then have objects added to it and removed from it. The cache size is fixed at construction time and may therefore run out or be flooded. If it runs out it returns a NULL pointer, if it fills up it also returns a NULL pointer instead of a pointer to the object just inserted */ /* Making these classes inherit from CBaseObject does nothing for their functionality but it allows us to check there are no memory leaks */ /* WARNING Be very careful when using this class, what it lets you do is store and retrieve objects so that you can minimise object creation which in turns improves efficiency. However the object you store is exactly the same as the object you get back which means that it short circuits the constructor initialisation phase. This means any class variables the object has (eg pointers) are highly likely to be invalid. Therefore ensure you reinitialise the object before using it again */ #ifndef __CACHE__ #define __CACHE__ class CCache : CBaseObject { /* Make copy constructor and assignment operator inaccessible */ CCache(const CCache &refCache); CCache &operator=(const CCache &refCache); private: /* These are initialised in the constructor. The first variable points to an array of pointers, each of which points to a CBaseObject derived object. The m_iCacheSize is the static fixed size for the cache and the m_iUsed defines the number of places filled with objects at any time. We fill the array of pointers from the start (ie m_ppObjects[0] first) and then only add and remove objects from the end position, so in this respect the array of object pointers should be treated as a stack */ CBaseObject **m_ppObjects; const INT m_iCacheSize; INT m_iUsed; public: CCache(__in_opt LPCTSTR pName, INT iItems); virtual ~CCache(); /* Add an item to the cache */ CBaseObject *AddToCache(__in CBaseObject *pObject); /* Remove an item from the cache */ CBaseObject *RemoveFromCache(); /* Delete all the objects held in the cache */ void RemoveAll(void); /* Return the cache size which is set during construction */ INT GetCacheSize(void) const { return m_iCacheSize; }; }; #endif /* __CACHE__ */ ================================================ FILE: common/baseclasses/checkbmi.h ================================================ // Copyright (c) 1992 - 1997 Microsoft Corporation. All Rights Reserved. #ifndef _CHECKBMI_H_ #define _CHECKBMI_H_ #ifdef __cplusplus extern "C" { #endif // Helper __inline BOOL MultiplyCheckOverflow(DWORD a, DWORD b, __deref_out_range(==, a * b) DWORD *pab) { *pab = a * b; if ((a == 0) || (((*pab) / a) == b)) { return TRUE; } return FALSE; } // Checks if the fields in a BITMAPINFOHEADER won't generate // overlows and buffer overruns // This is not a complete check and does not guarantee code using this structure will be secure // from attack // Bugs this is guarding against: // 1. Total structure size calculation overflowing // 2. biClrUsed > 256 for 8-bit palettized content // 3. Total bitmap size in bytes overflowing // 4. biSize < size of the base structure leading to accessessing random memory // 5. Total structure size exceeding know size of data // __success(return != 0) __inline BOOL ValidateBitmapInfoHeader( const BITMAPINFOHEADER *pbmi, // pointer to structure to check __out_range(>=, sizeof(BITMAPINFOHEADER)) DWORD cbSize // size of memory block containing structure ) { DWORD dwWidthInBytes; DWORD dwBpp; DWORD dwWidthInBits; DWORD dwHeight; DWORD dwSizeImage; DWORD dwClrUsed; // Reject bad parameters - do the size check first to avoid reading bad memory if (cbSize < sizeof(BITMAPINFOHEADER) || pbmi->biSize < sizeof(BITMAPINFOHEADER) || pbmi->biSize > 4096) { return FALSE; } // Reject 0 size if (pbmi->biWidth == 0 || pbmi->biHeight == 0) { return FALSE; } // Use bpp of 200 for validating against further overflows if not set for compressed format dwBpp = 200; if (pbmi->biBitCount > dwBpp) { return FALSE; } // Strictly speaking abs can overflow so cast explicitly to DWORD dwHeight = (DWORD)abs(pbmi->biHeight); if (!MultiplyCheckOverflow(dwBpp, (DWORD)pbmi->biWidth, &dwWidthInBits)) { return FALSE; } // Compute correct width in bytes - rounding up to 4 bytes dwWidthInBytes = (dwWidthInBits / 8 + 3) & ~3; if (!MultiplyCheckOverflow(dwWidthInBytes, dwHeight, &dwSizeImage)) { return FALSE; } // Fail if total size is 0 - this catches indivual quantities being 0 // Also don't allow huge values > 1GB which might cause arithmetic // errors for users if (dwSizeImage > 0x40000000 || pbmi->biSizeImage > 0x40000000) { return FALSE; } // Fail if biClrUsed looks bad if (pbmi->biClrUsed > 256) { return FALSE; } if (pbmi->biClrUsed == 0 && pbmi->biBitCount <= 8 && pbmi->biBitCount > 0) { dwClrUsed = (1 << pbmi->biBitCount); } else { dwClrUsed = pbmi->biClrUsed; } // Check total size if (cbSize < pbmi->biSize + dwClrUsed * sizeof(RGBQUAD) + (pbmi->biCompression == BI_BITFIELDS ? 3 * sizeof(DWORD) : 0)) { return FALSE; } // If it is RGB validate biSizeImage - lots of code assumes the size is correct if (pbmi->biCompression == BI_RGB || pbmi->biCompression == BI_BITFIELDS) { if (pbmi->biSizeImage != 0) { DWORD dwBits = (DWORD)pbmi->biWidth * (DWORD)pbmi->biBitCount; DWORD dwWidthInBytes = ((DWORD)((dwBits+31) & (~31)) / 8); DWORD dwTotalSize = (DWORD)abs(pbmi->biHeight) * dwWidthInBytes; if (dwTotalSize > pbmi->biSizeImage) { return FALSE; } } } return TRUE; } #ifdef __cplusplus } #endif #endif // _CHECKBMI_H_ ================================================ FILE: common/baseclasses/combase.cpp ================================================ //------------------------------------------------------------------------------ // File: ComBase.cpp // // Desc: DirectShow base classes - implements class hierarchy for creating // COM objects. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #pragma warning(disable : 4514) // Disable warnings re unused inline functions /* Define the static member variable */ LONG CBaseObject::m_cObjects = 0; /* Constructor */ CBaseObject::CBaseObject(__in_opt LPCTSTR pName) { /* Increment the number of active objects */ InterlockedIncrement(&m_cObjects); #ifdef DEBUG #ifdef UNICODE m_dwCookie = DbgRegisterObjectCreation(0, pName); #else m_dwCookie = DbgRegisterObjectCreation(pName, 0); #endif #endif } #ifdef UNICODE CBaseObject::CBaseObject(const char *pName) { /* Increment the number of active objects */ InterlockedIncrement(&m_cObjects); #ifdef DEBUG m_dwCookie = DbgRegisterObjectCreation(pName, 0); #endif } #endif HINSTANCE hlibOLEAut32; /* Destructor */ CBaseObject::~CBaseObject() { /* Decrement the number of objects active */ if (InterlockedDecrement(&m_cObjects) == 0) { if (hlibOLEAut32) { FreeLibrary(hlibOLEAut32); hlibOLEAut32 = 0; } }; #ifdef DEBUG DbgRegisterObjectDestruction(m_dwCookie); #endif } static const TCHAR szOle32Aut[] = TEXT("OleAut32.dll"); HINSTANCE LoadOLEAut32() { if (hlibOLEAut32 == 0) { hlibOLEAut32 = LoadLibrary(szOle32Aut); } return hlibOLEAut32; } /* Constructor */ // We know we use "this" in the initialization list, we also know we don't modify *phr. #pragma warning(disable : 4355 4100) CUnknown::CUnknown(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk) : CBaseObject(pName) /* Start the object with a reference count of zero - when the */ /* object is queried for it's first interface this may be */ /* incremented depending on whether or not this object is */ /* currently being aggregated upon */ , m_cRef(0) /* Set our pointer to our IUnknown interface. */ /* If we have an outer, use its, otherwise use ours. */ /* This pointer effectivly points to the owner of */ /* this object and can be accessed by the GetOwner() method. */ , m_pUnknown(pUnk != 0 ? pUnk : reinterpret_cast(static_cast(this))) /* Why the double cast? Well, the inner cast is a type-safe cast */ /* to pointer to a type from which we inherit. The second is */ /* type-unsafe but works because INonDelegatingUnknown "behaves */ /* like" IUnknown. (Only the names on the methods change.) */ { // Everything we need to do has been done in the initializer list } // This does the same as above except it has a useless HRESULT argument // use the previous constructor, this is just left for compatibility... CUnknown::CUnknown(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr) : CBaseObject(pName) , m_cRef(0) , m_pUnknown(pUnk != 0 ? pUnk : reinterpret_cast(static_cast(this))) { } #ifdef UNICODE CUnknown::CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk) : CBaseObject(pName) , m_cRef(0) , m_pUnknown(pUnk != 0 ? pUnk : reinterpret_cast(static_cast(this))) { } CUnknown::CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr) : CBaseObject(pName) , m_cRef(0) , m_pUnknown(pUnk != 0 ? pUnk : reinterpret_cast(static_cast(this))) { } #endif #pragma warning(default : 4355 4100) /* QueryInterface */ STDMETHODIMP CUnknown::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); ValidateReadWritePtr(ppv, sizeof(PVOID)); /* We know only about IUnknown */ if (riid == IID_IUnknown) { GetInterface((LPUNKNOWN)(PNDUNKNOWN)this, ppv); return NOERROR; } else { *ppv = NULL; return E_NOINTERFACE; } } /* We have to ensure that we DON'T use a max macro, since these will typically */ /* lead to one of the parameters being evaluated twice. Since we are worried */ /* about concurrency, we can't afford to access the m_cRef twice since we can't */ /* afford to run the risk that its value having changed between accesses. */ template inline static T ourmax(const T &a, const T &b) { return a > b ? a : b; } /* AddRef */ STDMETHODIMP_(ULONG) CUnknown::NonDelegatingAddRef() { LONG lRef = InterlockedIncrement(&m_cRef); ASSERT(lRef > 0); DbgLog((LOG_MEMORY, 3, TEXT(" Obj %d ref++ = %d"), m_dwCookie, m_cRef)); return ourmax(ULONG(m_cRef), 1ul); } /* Release */ STDMETHODIMP_(ULONG) CUnknown::NonDelegatingRelease() { /* If the reference count drops to zero delete ourselves */ LONG lRef = InterlockedDecrement(&m_cRef); ASSERT(lRef >= 0); DbgLog((LOG_MEMORY, 3, TEXT(" Object %d ref-- = %d"), m_dwCookie, m_cRef)); if (lRef == 0) { // COM rules say we must protect against re-entrancy. // If we are an aggregator and we hold our own interfaces // on the aggregatee, the QI for these interfaces will // addref ourselves. So after doing the QI we must release // a ref count on ourselves. Then, before releasing the // private interface, we must addref ourselves. When we do // this from the destructor here it will result in the ref // count going to 1 and then back to 0 causing us to // re-enter the destructor. Hence we add an extra refcount here // once we know we will delete the object. // for an example aggregator see filgraph\distrib.cpp. m_cRef++; delete this; return ULONG(0); } else { // Don't touch m_cRef again even in this leg as the object // may have just been released on another thread too return ourmax(ULONG(lRef), 1ul); } } /* Return an interface pointer to a requesting client performing a thread safe AddRef as necessary */ STDAPI GetInterface(LPUNKNOWN pUnk, __out void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = pUnk; pUnk->AddRef(); return NOERROR; } /* Compares two interfaces and returns TRUE if they are on the same object */ BOOL WINAPI IsEqualObject(IUnknown *pFirst, IUnknown *pSecond) { /* Different objects can't have the same interface pointer for any interface */ if (pFirst == pSecond) { return TRUE; } /* OK - do it the hard way - check if they have the same IUnknown pointers - a single object can only have one of these */ LPUNKNOWN pUnknown1; // Retrieve the IUnknown interface LPUNKNOWN pUnknown2; // Retrieve the other IUnknown interface HRESULT hr; // General OLE return code ASSERT(pFirst); ASSERT(pSecond); /* See if the IUnknown pointers match */ hr = pFirst->QueryInterface(IID_IUnknown, (void **)&pUnknown1); if (FAILED(hr)) { return FALSE; } ASSERT(pUnknown1); /* Release the extra interface we hold */ pUnknown1->Release(); hr = pSecond->QueryInterface(IID_IUnknown, (void **)&pUnknown2); if (FAILED(hr)) { return FALSE; } ASSERT(pUnknown2); /* Release the extra interface we hold */ pUnknown2->Release(); return (pUnknown1 == pUnknown2); } ================================================ FILE: common/baseclasses/combase.h ================================================ //------------------------------------------------------------------------------ // File: ComBase.h // // Desc: DirectShow base classes - defines a class hierarchy for creating // COM objects. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ /* a. Derive your COM object from CUnknown b. Make a static CreateInstance function that takes an LPUNKNOWN, an HRESULT * and a TCHAR *. The LPUNKNOWN defines the object to delegate IUnknown calls to. The HRESULT * allows error codes to be passed around constructors and the TCHAR * is a descriptive name that can be printed on the debugger. It is important that constructors only change the HRESULT * if they have to set an ERROR code, if it was successful then leave it alone or you may overwrite an error code from an object previously created. When you call a constructor the descriptive name should be in static store as we do not copy the string. To stop large amounts of memory being used in retail builds by all these static strings use the NAME macro, CMyFilter = new CImplFilter(NAME("My filter"),pUnknown,phr); if (FAILED(hr)) { return hr; } In retail builds NAME(_x_) compiles to NULL, the base CBaseObject class knows not to do anything with objects that don't have a name. c. Have a constructor for your object that passes the LPUNKNOWN, HRESULT * and TCHAR * to the CUnknown constructor. You can set the HRESULT if you have an error, or just simply pass it through to the constructor. The object creation will fail in the class factory if the HRESULT indicates an error (ie FAILED(HRESULT) == TRUE) d. Create a FactoryTemplate with your object's class id and CreateInstance function. Then (for each interface) either Multiple inheritance 1. Also derive it from ISomeInterface 2. Include DECLARE_IUNKNOWN in your class definition to declare implementations of QueryInterface, AddRef and Release that call the outer unknown 3. Override NonDelegatingQueryInterface to expose ISomeInterface by code something like if (riid == IID_ISomeInterface) { return GetInterface((ISomeInterface *) this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } 4. Declare and implement the member functions of ISomeInterface. or: Nested interfaces 1. Declare a class derived from CUnknown 2. Include DECLARE_IUNKNOWN in your class definition 3. Override NonDelegatingQueryInterface to expose ISomeInterface by code something like if (riid == IID_ISomeInterface) { return GetInterface((ISomeInterface *) this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } 4. Implement the member functions of ISomeInterface. Use GetOwner() to access the COM object class. And in your COM object class: 5. Make the nested class a friend of the COM object class, and declare an instance of the nested class as a member of the COM object class. NOTE that because you must always pass the outer unknown and an hResult to the CUnknown constructor you cannot use a default constructor, in other words you will have to make the member variable a pointer to the class and make a NEW call in your constructor to actually create it. 6. override the NonDelegatingQueryInterface with code like this: if (riid == IID_ISomeInterface) { return m_pImplFilter-> NonDelegatingQueryInterface(IID_ISomeInterface, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } You can have mixed classes which support some interfaces via multiple inheritance and some via nested classes */ #ifndef __COMBASE__ #define __COMBASE__ // Filter Setup data structures no defined in axextend.idl typedef REGPINTYPES AMOVIESETUP_MEDIATYPE, *PAMOVIESETUP_MEDIATYPE, *FAR LPAMOVIESETUP_MEDIATYPE; typedef REGFILTERPINS AMOVIESETUP_PIN, *PAMOVIESETUP_PIN, *FAR LPAMOVIESETUP_PIN; typedef struct _AMOVIESETUP_FILTER { const CLSID *clsID; const WCHAR *strName; DWORD dwMerit; UINT nPins; const AMOVIESETUP_PIN *lpPin; const CLSID filterCategory; } AMOVIESETUP_FILTER, *PAMOVIESETUP_FILTER, *FAR LPAMOVIESETUP_FILTER; /* The DLLENTRY module initialises the module handle on loading */ extern HINSTANCE g_hInst; /* On DLL load remember which platform we are running on */ extern DWORD g_amPlatform; extern OSVERSIONINFO g_osInfo; // Filled in by GetVersionEx /* Version of IUnknown that is renamed to allow a class to support both non delegating and delegating IUnknowns in the same COM object */ #ifndef INONDELEGATINGUNKNOWN_DEFINED DECLARE_INTERFACE(INonDelegatingUnknown) { STDMETHOD(NonDelegatingQueryInterface)(THIS_ REFIID, LPVOID *) PURE; STDMETHOD_(ULONG, NonDelegatingAddRef)(THIS) PURE; STDMETHOD_(ULONG, NonDelegatingRelease)(THIS) PURE; }; #define INONDELEGATINGUNKNOWN_DEFINED #endif typedef INonDelegatingUnknown *PNDUNKNOWN; /* This is the base object class that supports active object counting. As part of the debug facilities we trace every time a C++ object is created or destroyed. The name of the object has to be passed up through the class derivation list during construction as you cannot call virtual functions in the constructor. The downside of all this is that every single object constructor has to take an object name parameter that describes it */ class CBaseObject { private: // Disable the copy constructor and assignment by default so you will get // compiler errors instead of unexpected behaviour if you pass objects // by value or assign objects. CBaseObject(const CBaseObject &objectSrc); // no implementation void operator=(const CBaseObject &objectSrc); // no implementation private: static LONG m_cObjects; /* Total number of objects active */ protected: #ifdef DEBUG DWORD m_dwCookie; /* Cookie identifying this object */ #endif public: /* These increment and decrement the number of active objects */ CBaseObject(__in_opt LPCTSTR pName); #ifdef UNICODE CBaseObject(__in_opt LPCSTR pName); #endif ~CBaseObject(); /* Call this to find if there are any CUnknown derived objects active */ static LONG ObjectsActive() { return m_cObjects; }; }; /* An object that supports one or more COM interfaces will be based on this class. It supports counting of total objects for DLLCanUnloadNow support, and an implementation of the core non delegating IUnknown */ class AM_NOVTABLE CUnknown : public INonDelegatingUnknown , public CBaseObject { private: const LPUNKNOWN m_pUnknown; /* Owner of this object */ protected: /* So we can override NonDelegatingRelease() */ volatile LONG m_cRef; /* Number of reference counts */ public: CUnknown(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk); virtual ~CUnknown(){}; // This is redundant, just use the other constructor // as we never touch the HRESULT in this anyway CUnknown(__in_opt LPCTSTR Name, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr); #ifdef UNICODE CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk); CUnknown(__in_opt LPCSTR pName, __in_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr); #endif /* Return the owner of this object */ LPUNKNOWN GetOwner() const { return m_pUnknown; }; /* Called from the class factory to create a new instance, it is pure virtual so it must be overriden in your derived class */ /* static CUnknown *CreateInstance(LPUNKNOWN, HRESULT *) */ /* Non delegating unknown implementation */ STDMETHODIMP NonDelegatingQueryInterface(REFIID, __deref_out void **); STDMETHODIMP_(ULONG) NonDelegatingAddRef(); STDMETHODIMP_(ULONG) NonDelegatingRelease(); }; /* Return an interface pointer to a requesting client performing a thread safe AddRef as necessary */ STDAPI GetInterface(LPUNKNOWN pUnk, __out void **ppv); /* A function that can create a new COM object */ typedef CUnknown *(CALLBACK *LPFNNewCOMObject)(__in_opt LPUNKNOWN pUnkOuter, __inout_opt HRESULT *phr); /* A function (can be NULL) which is called from the DLL entrypoint routine for each factory template: bLoading - TRUE on DLL load, FALSE on DLL unload rclsid - the m_ClsID of the entry */ typedef void(CALLBACK *LPFNInitRoutine)(BOOL bLoading, const CLSID *rclsid); /* Create one of these per object class in an array so that the default class factory code can create new instances */ class CFactoryTemplate { public: const WCHAR *m_Name; const CLSID *m_ClsID; LPFNNewCOMObject m_lpfnNew; LPFNInitRoutine m_lpfnInit; const AMOVIESETUP_FILTER *m_pAMovieSetup_Filter; BOOL IsClassID(REFCLSID rclsid) const { return (IsEqualCLSID(*m_ClsID, rclsid)); }; CUnknown *CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout_opt HRESULT *phr) const { CheckPointer(phr, NULL); return m_lpfnNew(pUnk, phr); }; }; /* You must override the (pure virtual) NonDelegatingQueryInterface to return interface pointers (using GetInterface) to the interfaces your derived class supports (the default implementation only supports IUnknown) */ #define DECLARE_IUNKNOWN \ STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv) \ { \ return GetOwner()->QueryInterface(riid, ppv); \ }; \ STDMETHODIMP_(ULONG) AddRef() { return GetOwner()->AddRef(); }; \ STDMETHODIMP_(ULONG) Release() { return GetOwner()->Release(); }; HINSTANCE LoadOLEAut32(); #endif /* __COMBASE__ */ ================================================ FILE: common/baseclasses/cprop.cpp ================================================ //------------------------------------------------------------------------------ // File: CProp.cpp // // Desc: DirectShow base classes - implements CBasePropertyPage class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include // Constructor for the base property page class. As described in the header // file we must be initialised with dialog and title resource identifiers. // The class supports IPropertyPage and overrides AddRef and Release calls // to keep track of the reference counts. When the last count is released // we call SetPageSite(NULL) and SetObjects(0,NULL) to release interfaces // previously obtained by the property page when it had SetObjects called CBasePropertyPage::CBasePropertyPage(__in_opt LPCTSTR pName, // Debug only name __inout_opt LPUNKNOWN pUnk, // COM Delegator int DialogId, // Resource ID int TitleId) : // To get tital CUnknown(pName, pUnk) , m_DialogId(DialogId) , m_TitleId(TitleId) , m_hwnd(NULL) , m_Dlg(NULL) , m_pPageSite(NULL) , m_bObjectSet(FALSE) , m_bDirty(FALSE) { } #ifdef UNICODE CBasePropertyPage::CBasePropertyPage(__in_opt LPCSTR pName, // Debug only name __inout_opt LPUNKNOWN pUnk, // COM Delegator int DialogId, // Resource ID int TitleId) : // To get tital CUnknown(pName, pUnk) , m_DialogId(DialogId) , m_TitleId(TitleId) , m_hwnd(NULL) , m_Dlg(NULL) , m_pPageSite(NULL) , m_bObjectSet(FALSE) , m_bDirty(FALSE) { } #endif // Increment our reference count STDMETHODIMP_(ULONG) CBasePropertyPage::NonDelegatingAddRef() { LONG lRef = InterlockedIncrement(&m_cRef); ASSERT(lRef > 0); return max(ULONG(m_cRef), 1ul); } // Release a reference count and protect against reentrancy STDMETHODIMP_(ULONG) CBasePropertyPage::NonDelegatingRelease() { // If the reference count drops to zero delete ourselves LONG lRef = InterlockedDecrement(&m_cRef); if (lRef == 0) { m_cRef++; SetPageSite(NULL); SetObjects(0, NULL); delete this; return ULONG(0); } else { // Don't touch m_cRef again here! return max(ULONG(lRef), 1ul); } } // Expose our IPropertyPage interface STDMETHODIMP CBasePropertyPage::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_IPropertyPage) { return GetInterface((IPropertyPage *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } // Get the page info so that the page site can size itself STDMETHODIMP CBasePropertyPage::GetPageInfo(__out LPPROPPAGEINFO pPageInfo) { CheckPointer(pPageInfo, E_POINTER); WCHAR wszTitle[STR_MAX_LENGTH]; WideStringFromResource(wszTitle, m_TitleId); // Allocate dynamic memory for the property page title LPOLESTR pszTitle; HRESULT hr = AMGetWideString(wszTitle, &pszTitle); if (FAILED(hr)) { NOTE("No caption memory"); return hr; } pPageInfo->cb = sizeof(PROPPAGEINFO); pPageInfo->pszTitle = pszTitle; pPageInfo->pszDocString = NULL; pPageInfo->pszHelpFile = NULL; pPageInfo->dwHelpContext = 0; // Set defaults in case GetDialogSize fails pPageInfo->size.cx = 340; pPageInfo->size.cy = 150; GetDialogSize(m_DialogId, DialogProc, 0L, &pPageInfo->size); return NOERROR; } // Handles the messages for our property window INT_PTR CALLBACK CBasePropertyPage::DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CBasePropertyPage *pPropertyPage; switch (uMsg) { case WM_INITDIALOG: _SetWindowLongPtr(hwnd, DWLP_USER, lParam); // This pointer may be NULL when calculating size pPropertyPage = (CBasePropertyPage *)lParam; if (pPropertyPage == NULL) { return (LRESULT)1; } pPropertyPage->m_Dlg = hwnd; } // This pointer may be NULL when calculating size pPropertyPage = _GetWindowLongPtr(hwnd, DWLP_USER); if (pPropertyPage == NULL) { return (LRESULT)1; } return pPropertyPage->OnReceiveMessage(hwnd, uMsg, wParam, lParam); } // Tells us the object that should be informed of the property changes STDMETHODIMP CBasePropertyPage::SetObjects(ULONG cObjects, __in_ecount_opt(cObjects) LPUNKNOWN *ppUnk) { if (cObjects == 1) { if ((ppUnk == NULL) || (*ppUnk == NULL)) { return E_POINTER; } // Set a flag to say that we have set the Object m_bObjectSet = TRUE; return OnConnect(*ppUnk); } else if (cObjects == 0) { // Set a flag to say that we have not set the Object for the page m_bObjectSet = FALSE; return OnDisconnect(); } DbgBreak("No support for more than one object"); return E_UNEXPECTED; } // Create the window we will use to edit properties STDMETHODIMP CBasePropertyPage::Activate(HWND hwndParent, LPCRECT pRect, BOOL fModal) { CheckPointer(pRect, E_POINTER); // Return failure if SetObject has not been called. if (m_bObjectSet == FALSE) { return E_UNEXPECTED; } if (m_hwnd) { return E_UNEXPECTED; } m_hwnd = CreateDialogParam(g_hInst, MAKEINTRESOURCE(m_DialogId), hwndParent, DialogProc, (LPARAM)this); if (m_hwnd == NULL) { return E_OUTOFMEMORY; } OnActivate(); Move(pRect); return Show(SW_SHOWNORMAL); } // Set the position of the property page STDMETHODIMP CBasePropertyPage::Move(LPCRECT pRect) { CheckPointer(pRect, E_POINTER); if (m_hwnd == NULL) { return E_UNEXPECTED; } MoveWindow(m_hwnd, // Property page handle pRect->left, // x coordinate pRect->top, // y coordinate WIDTH(pRect), // Overall window width HEIGHT(pRect), // And likewise height TRUE); // Should we repaint it return NOERROR; } // Display the property dialog STDMETHODIMP CBasePropertyPage::Show(UINT nCmdShow) { // Have we been activated yet if (m_hwnd == NULL) { return E_UNEXPECTED; } // Ignore wrong show flags if ((nCmdShow != SW_SHOW) && (nCmdShow != SW_SHOWNORMAL) && (nCmdShow != SW_HIDE)) { return E_INVALIDARG; } ShowWindow(m_hwnd, nCmdShow); InvalidateRect(m_hwnd, NULL, TRUE); return NOERROR; } // Destroy the property page dialog STDMETHODIMP CBasePropertyPage::Deactivate(void) { if (m_hwnd == NULL) { return E_UNEXPECTED; } // Remove WS_EX_CONTROLPARENT before DestroyWindow call DWORD dwStyle = GetWindowLong(m_hwnd, GWL_EXSTYLE); dwStyle = dwStyle & (~WS_EX_CONTROLPARENT); // Set m_hwnd to be NULL temporarily so the message handler // for WM_STYLECHANGING doesn't add the WS_EX_CONTROLPARENT // style back in HWND hwnd = m_hwnd; m_hwnd = NULL; SetWindowLong(hwnd, GWL_EXSTYLE, dwStyle); m_hwnd = hwnd; OnDeactivate(); // Destroy the dialog window DestroyWindow(m_hwnd); m_hwnd = NULL; return NOERROR; } // Tells the application property page site STDMETHODIMP CBasePropertyPage::SetPageSite(__in_opt LPPROPERTYPAGESITE pPageSite) { if (pPageSite) { if (m_pPageSite) { return E_UNEXPECTED; } m_pPageSite = pPageSite; m_pPageSite->AddRef(); } else { if (m_pPageSite == NULL) { return E_UNEXPECTED; } m_pPageSite->Release(); m_pPageSite = NULL; } return NOERROR; } // Apply any changes so far made STDMETHODIMP CBasePropertyPage::Apply() { // In ActiveMovie 1.0 we used to check whether we had been activated or // not. This is too constrictive. Apply should be allowed as long as // SetObject was called to set an object. So we will no longer check to // see if we have been activated (ie., m_hWnd != NULL), but instead // make sure that m_bObjectSet is TRUE (ie., SetObject has been called). if (m_bObjectSet == FALSE) { return E_UNEXPECTED; } // Must have had a site set if (m_pPageSite == NULL) { return E_UNEXPECTED; } // Has anything changed if (m_bDirty == FALSE) { return NOERROR; } // Commit derived class changes HRESULT hr = OnApplyChanges(); if (SUCCEEDED(hr)) { m_bDirty = FALSE; } return hr; } // Base class definition for message handling INT_PTR CBasePropertyPage::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // we would like the TAB key to move around the tab stops in our property // page, but for some reason OleCreatePropertyFrame clears the CONTROLPARENT // style behind our back, so we need to switch it back on now behind its // back. Otherwise the tab key will be useless in every page. // CBasePropertyPage *pPropertyPage; { pPropertyPage = _GetWindowLongPtr(hwnd, DWLP_USER); if (pPropertyPage->m_hwnd == NULL) { return 0; } switch (uMsg) { case WM_STYLECHANGING: if (wParam == GWL_EXSTYLE) { LPSTYLESTRUCT lpss = (LPSTYLESTRUCT)lParam; lpss->styleNew |= WS_EX_CONTROLPARENT; return 0; } } } return DefWindowProc(hwnd, uMsg, wParam, lParam); } ================================================ FILE: common/baseclasses/cprop.h ================================================ //------------------------------------------------------------------------------ // File: CProp.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __CPROP__ #define __CPROP__ // Base property page class. Filters typically expose custom properties by // implementing special control interfaces, examples are IDirectDrawVideo // and IQualProp on renderers. This allows property pages to be built that // use the given interface. Applications such as the ActiveMovie OCX query // filters for the property pages they support and expose them to the user // // This class provides all the framework for a property page. A property // page is a COM object that supports IPropertyPage. We should be created // with a resource ID for the dialog which we will load when required. We // should also be given in the constructor a resource ID for a title string // we will load from the DLLs STRINGTABLE. The property page titles must be // stored in resource files so that they can be easily internationalised // // We have a number of virtual methods (not PURE) that may be overriden in // derived classes to query for interfaces and so on. These functions have // simple implementations here that just return NOERROR. Derived classes // will almost definately have to override the message handler method called // OnReceiveMessage. We have a static dialog procedure that calls the method // so that derived classes don't have to fiddle around with the this pointer class AM_NOVTABLE CBasePropertyPage : public IPropertyPage , public CUnknown { protected: LPPROPERTYPAGESITE m_pPageSite; // Details for our property site HWND m_hwnd; // Window handle for the page HWND m_Dlg; // Actual dialog window handle BOOL m_bDirty; // Has anything been changed int m_TitleId; // Resource identifier for title int m_DialogId; // Dialog resource identifier static INT_PTR CALLBACK DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: BOOL m_bObjectSet; // SetObject has been called or not. public: CBasePropertyPage(__in_opt LPCTSTR pName, // Debug only name __inout_opt LPUNKNOWN pUnk, // COM Delegator int DialogId, // Resource ID int TitleId); // To get tital #ifdef UNICODE CBasePropertyPage(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN pUnk, int DialogId, int TitleId); #endif virtual ~CBasePropertyPage(){}; DECLARE_IUNKNOWN // Override these virtual methods virtual HRESULT OnConnect(IUnknown *pUnknown) { return NOERROR; }; virtual HRESULT OnDisconnect() { return NOERROR; }; virtual HRESULT OnActivate() { return NOERROR; }; virtual HRESULT OnDeactivate() { return NOERROR; }; virtual HRESULT OnApplyChanges() { return NOERROR; }; virtual INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); // These implement an IPropertyPage interface STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) NonDelegatingRelease(); STDMETHODIMP_(ULONG) NonDelegatingAddRef(); STDMETHODIMP SetPageSite(__in_opt LPPROPERTYPAGESITE pPageSite); STDMETHODIMP Activate(HWND hwndParent, LPCRECT prect, BOOL fModal); STDMETHODIMP Deactivate(void); STDMETHODIMP GetPageInfo(__out LPPROPPAGEINFO pPageInfo); STDMETHODIMP SetObjects(ULONG cObjects, __in_ecount_opt(cObjects) LPUNKNOWN *ppUnk); STDMETHODIMP Show(UINT nCmdShow); STDMETHODIMP Move(LPCRECT prect); STDMETHODIMP IsPageDirty(void) { return m_bDirty ? S_OK : S_FALSE; } STDMETHODIMP Apply(void); STDMETHODIMP Help(LPCWSTR lpszHelpDir) { return E_NOTIMPL; } STDMETHODIMP TranslateAccelerator(__inout LPMSG lpMsg) { return E_NOTIMPL; } }; #endif // __CPROP__ ================================================ FILE: common/baseclasses/ctlutil.cpp ================================================ //------------------------------------------------------------------------------ // File: CtlUtil.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Base classes implementing IDispatch parsing for the basic control dual // interfaces. Derive from these and implement just the custom method and // property methods. We also implement CPosPassThru that can be used by // renderers and transforms to pass by IMediaPosition and IMediaSeeking #include #include #include "seekpt.h" // 'bool' non standard reserved word #pragma warning(disable : 4237) // --- CBaseDispatch implementation ---------- CBaseDispatch::~CBaseDispatch() { if (m_pti) { m_pti->Release(); } } // return 1 if we support GetTypeInfo STDMETHODIMP CBaseDispatch::GetTypeInfoCount(__out UINT *pctinfo) { CheckPointer(pctinfo, E_POINTER); ValidateReadWritePtr(pctinfo, sizeof(UINT *)); *pctinfo = 1; return S_OK; } typedef HRESULT(STDAPICALLTYPE *LPLOADTYPELIB)(const OLECHAR FAR *szFile, __deref_out ITypeLib FAR *FAR *pptlib); typedef HRESULT(STDAPICALLTYPE *LPLOADREGTYPELIB)(REFGUID rguid, WORD wVerMajor, WORD wVerMinor, LCID lcid, __deref_out ITypeLib FAR *FAR *pptlib); // attempt to find our type library STDMETHODIMP CBaseDispatch::GetTypeInfo(REFIID riid, UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo) { CheckPointer(pptinfo, E_POINTER); ValidateReadWritePtr(pptinfo, sizeof(ITypeInfo *)); HRESULT hr; *pptinfo = NULL; // we only support one type element if (0 != itinfo) { return TYPE_E_ELEMENTNOTFOUND; } if (NULL == pptinfo) { return E_POINTER; } // always look for neutral if (NULL == m_pti) { LPLOADTYPELIB lpfnLoadTypeLib; LPLOADREGTYPELIB lpfnLoadRegTypeLib; ITypeLib *ptlib; HINSTANCE hInst; static const char szTypeLib[] = "LoadTypeLib"; static const char szRegTypeLib[] = "LoadRegTypeLib"; static const WCHAR szControl[] = L"control.tlb"; // // Try to get the Ole32Aut.dll module handle. // hInst = LoadOLEAut32(); if (hInst == NULL) { DWORD dwError = GetLastError(); return AmHresultFromWin32(dwError); } lpfnLoadRegTypeLib = (LPLOADREGTYPELIB)GetProcAddress(hInst, szRegTypeLib); if (lpfnLoadRegTypeLib == NULL) { DWORD dwError = GetLastError(); return AmHresultFromWin32(dwError); } hr = (*lpfnLoadRegTypeLib)(LIBID_QuartzTypeLib, 1, 0, // version 1.0 lcid, &ptlib); if (FAILED(hr)) { // attempt to load directly - this will fill the // registry in if it finds it lpfnLoadTypeLib = (LPLOADTYPELIB)GetProcAddress(hInst, szTypeLib); if (lpfnLoadTypeLib == NULL) { DWORD dwError = GetLastError(); return AmHresultFromWin32(dwError); } hr = (*lpfnLoadTypeLib)(szControl, &ptlib); if (FAILED(hr)) { return hr; } } hr = ptlib->GetTypeInfoOfGuid(riid, &m_pti); ptlib->Release(); if (FAILED(hr)) { return hr; } } *pptinfo = m_pti; m_pti->AddRef(); return S_OK; } STDMETHODIMP CBaseDispatch::GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid) { // although the IDispatch riid is dead, we use this to pass from // the interface implementation class to us the iid we are talking about. ITypeInfo *pti; HRESULT hr = GetTypeInfo(riid, 0, lcid, &pti); if (SUCCEEDED(hr)) { hr = pti->GetIDsOfNames(rgszNames, cNames, rgdispid); pti->Release(); } return hr; } // --- CMediaControl implementation --------- CMediaControl::CMediaControl(const TCHAR *name, LPUNKNOWN pUnk) : CUnknown(name, pUnk) { } // expose our interfaces IMediaControl and IUnknown STDMETHODIMP CMediaControl::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == IID_IMediaControl) { return GetInterface((IMediaControl *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } // return 1 if we support GetTypeInfo STDMETHODIMP CMediaControl::GetTypeInfoCount(__out UINT *pctinfo) { return m_basedisp.GetTypeInfoCount(pctinfo); } // attempt to find our type library STDMETHODIMP CMediaControl::GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo) { return m_basedisp.GetTypeInfo(IID_IMediaControl, itinfo, lcid, pptinfo); } STDMETHODIMP CMediaControl::GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid) { return m_basedisp.GetIDsOfNames(IID_IMediaControl, rgszNames, cNames, lcid, rgdispid); } STDMETHODIMP CMediaControl::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr) { // this parameter is a dead leftover from an earlier interface if (IID_NULL != riid) { return DISP_E_UNKNOWNINTERFACE; } ITypeInfo *pti; HRESULT hr = GetTypeInfo(0, lcid, &pti); if (FAILED(hr)) { return hr; } hr = pti->Invoke((IMediaControl *)this, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); pti->Release(); return hr; } // --- CMediaEvent implementation ---------- CMediaEvent::CMediaEvent(__in_opt LPCTSTR name, __in_opt LPUNKNOWN pUnk) : CUnknown(name, pUnk) { } // expose our interfaces IMediaEvent and IUnknown STDMETHODIMP CMediaEvent::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == IID_IMediaEvent || riid == IID_IMediaEventEx) { return GetInterface((IMediaEventEx *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } // return 1 if we support GetTypeInfo STDMETHODIMP CMediaEvent::GetTypeInfoCount(__out UINT *pctinfo) { return m_basedisp.GetTypeInfoCount(pctinfo); } // attempt to find our type library STDMETHODIMP CMediaEvent::GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo) { return m_basedisp.GetTypeInfo(IID_IMediaEvent, itinfo, lcid, pptinfo); } STDMETHODIMP CMediaEvent::GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid) { return m_basedisp.GetIDsOfNames(IID_IMediaEvent, rgszNames, cNames, lcid, rgdispid); } STDMETHODIMP CMediaEvent::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr) { // this parameter is a dead leftover from an earlier interface if (IID_NULL != riid) { return DISP_E_UNKNOWNINTERFACE; } ITypeInfo *pti; HRESULT hr = GetTypeInfo(0, lcid, &pti); if (FAILED(hr)) { return hr; } hr = pti->Invoke((IMediaEvent *)this, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); pti->Release(); return hr; } // --- CMediaPosition implementation ---------- CMediaPosition::CMediaPosition(__in_opt LPCTSTR name, __in_opt LPUNKNOWN pUnk) : CUnknown(name, pUnk) { } CMediaPosition::CMediaPosition(__in_opt LPCTSTR name, __in_opt LPUNKNOWN pUnk, __inout HRESULT *phr) : CUnknown(name, pUnk) { UNREFERENCED_PARAMETER(phr); } // expose our interfaces IMediaPosition and IUnknown STDMETHODIMP CMediaPosition::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == IID_IMediaPosition) { return GetInterface((IMediaPosition *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } // return 1 if we support GetTypeInfo STDMETHODIMP CMediaPosition::GetTypeInfoCount(__out UINT *pctinfo) { return m_basedisp.GetTypeInfoCount(pctinfo); } // attempt to find our type library STDMETHODIMP CMediaPosition::GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo) { return m_basedisp.GetTypeInfo(IID_IMediaPosition, itinfo, lcid, pptinfo); } STDMETHODIMP CMediaPosition::GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid) { return m_basedisp.GetIDsOfNames(IID_IMediaPosition, rgszNames, cNames, lcid, rgdispid); } STDMETHODIMP CMediaPosition::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr) { // this parameter is a dead leftover from an earlier interface if (IID_NULL != riid) { return DISP_E_UNKNOWNINTERFACE; } ITypeInfo *pti; HRESULT hr = GetTypeInfo(0, lcid, &pti); if (FAILED(hr)) { return hr; } hr = pti->Invoke((IMediaPosition *)this, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); pti->Release(); return hr; } // --- IMediaPosition and IMediaSeeking pass through class ---------- CPosPassThru::CPosPassThru(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk, __inout HRESULT *phr, IPin *pPin) : CMediaPosition(pName, pUnk) , m_pPin(pPin) { if (pPin == NULL) { *phr = E_POINTER; return; } } // Expose our IMediaSeeking and IMediaPosition interfaces STDMETHODIMP CPosPassThru::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = NULL; if (riid == IID_IMediaSeeking) { return GetInterface(static_cast(this), ppv); } return CMediaPosition::NonDelegatingQueryInterface(riid, ppv); } // Return the IMediaPosition interface from our peer HRESULT CPosPassThru::GetPeer(IMediaPosition **ppMP) { *ppMP = NULL; IPin *pConnected; HRESULT hr = m_pPin->ConnectedTo(&pConnected); if (FAILED(hr)) { return E_NOTIMPL; } IMediaPosition *pMP; hr = pConnected->QueryInterface(IID_IMediaPosition, (void **)&pMP); pConnected->Release(); if (FAILED(hr)) { return E_NOTIMPL; } *ppMP = pMP; return S_OK; } // Return the IMediaSeeking interface from our peer HRESULT CPosPassThru::GetPeerSeeking(__deref_out IMediaSeeking **ppMS) { *ppMS = NULL; IPin *pConnected; HRESULT hr = m_pPin->ConnectedTo(&pConnected); if (FAILED(hr)) { return E_NOTIMPL; } IMediaSeeking *pMS; hr = pConnected->QueryInterface(IID_IMediaSeeking, (void **)&pMS); pConnected->Release(); if (FAILED(hr)) { return E_NOTIMPL; } *ppMS = pMS; return S_OK; } // --- IMediaSeeking methods ---------- STDMETHODIMP CPosPassThru::GetCapabilities(__out DWORD *pCaps) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->GetCapabilities(pCaps); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::CheckCapabilities(__inout DWORD *pCaps) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->CheckCapabilities(pCaps); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::IsFormatSupported(const GUID *pFormat) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->IsFormatSupported(pFormat); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::QueryPreferredFormat(__out GUID *pFormat) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->QueryPreferredFormat(pFormat); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::SetTimeFormat(const GUID *pFormat) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->SetTimeFormat(pFormat); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::GetTimeFormat(__out GUID *pFormat) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->GetTimeFormat(pFormat); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::IsUsingTimeFormat(const GUID *pFormat) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->IsUsingTimeFormat(pFormat); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::ConvertTimeFormat(__out LONGLONG *pTarget, __in_opt const GUID *pTargetFormat, LONGLONG Source, __in_opt const GUID *pSourceFormat) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->ConvertTimeFormat(pTarget, pTargetFormat, Source, pSourceFormat); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::SetPositions(__inout_opt LONGLONG *pCurrent, DWORD CurrentFlags, __inout_opt LONGLONG *pStop, DWORD StopFlags) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->SetPositions(pCurrent, CurrentFlags, pStop, StopFlags); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::GetPositions(__out_opt LONGLONG *pCurrent, __out_opt LONGLONG *pStop) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->GetPositions(pCurrent, pStop); pMS->Release(); return hr; } HRESULT CPosPassThru::GetSeekingLongLong(HRESULT (__stdcall IMediaSeeking::*pMethod)(__out LONGLONG *), LONGLONG *pll) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (SUCCEEDED(hr)) { hr = (pMS->*pMethod)(pll); pMS->Release(); } return hr; } // If we don't have a current position then ask upstream STDMETHODIMP CPosPassThru::GetCurrentPosition(__out LONGLONG *pCurrent) { // Can we report the current position HRESULT hr = GetMediaTime(pCurrent, NULL); if (SUCCEEDED(hr)) hr = NOERROR; else hr = GetSeekingLongLong(&IMediaSeeking::GetCurrentPosition, pCurrent); return hr; } STDMETHODIMP CPosPassThru::GetStopPosition(__out LONGLONG *pStop) { return GetSeekingLongLong(&IMediaSeeking::GetStopPosition, pStop); ; } STDMETHODIMP CPosPassThru::GetDuration(__out LONGLONG *pDuration) { return GetSeekingLongLong(&IMediaSeeking::GetDuration, pDuration); ; } STDMETHODIMP CPosPassThru::GetPreroll(__out LONGLONG *pllPreroll) { return GetSeekingLongLong(&IMediaSeeking::GetPreroll, pllPreroll); ; } STDMETHODIMP CPosPassThru::GetAvailable(__out_opt LONGLONG *pEarliest, __out_opt LONGLONG *pLatest) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->GetAvailable(pEarliest, pLatest); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::GetRate(__out double *pdRate) { IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->GetRate(pdRate); pMS->Release(); return hr; } STDMETHODIMP CPosPassThru::SetRate(double dRate) { if (0.0 == dRate) { return E_INVALIDARG; } IMediaSeeking *pMS; HRESULT hr = GetPeerSeeking(&pMS); if (FAILED(hr)) { return hr; } hr = pMS->SetRate(dRate); pMS->Release(); return hr; } // --- IMediaPosition methods ---------- STDMETHODIMP CPosPassThru::get_Duration(__out REFTIME *plength) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->get_Duration(plength); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::get_CurrentPosition(__out REFTIME *pllTime) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->get_CurrentPosition(pllTime); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::put_CurrentPosition(REFTIME llTime) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->put_CurrentPosition(llTime); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::get_StopTime(__out REFTIME *pllTime) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->get_StopTime(pllTime); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::put_StopTime(REFTIME llTime) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->put_StopTime(llTime); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::get_PrerollTime(__out REFTIME *pllTime) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->get_PrerollTime(pllTime); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::put_PrerollTime(REFTIME llTime) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->put_PrerollTime(llTime); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::get_Rate(__out double *pdRate) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->get_Rate(pdRate); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::put_Rate(double dRate) { if (0.0 == dRate) { return E_INVALIDARG; } IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->put_Rate(dRate); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::CanSeekForward(__out LONG *pCanSeekForward) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->CanSeekForward(pCanSeekForward); pMP->Release(); return hr; } STDMETHODIMP CPosPassThru::CanSeekBackward(__out LONG *pCanSeekBackward) { IMediaPosition *pMP; HRESULT hr = GetPeer(&pMP); if (FAILED(hr)) { return hr; } hr = pMP->CanSeekBackward(pCanSeekBackward); pMP->Release(); return hr; } // --- Implements the CRendererPosPassThru class ---------- // Media times (eg current frame, field, sample etc) are passed through the // filtergraph in media samples. When a renderer gets a sample with media // times in it, it will call one of the RegisterMediaTime methods we expose // (one takes an IMediaSample, the other takes the media times direct). We // store the media times internally and return them in GetCurrentPosition. CRendererPosPassThru::CRendererPosPassThru(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk, __inout HRESULT *phr, IPin *pPin) : CPosPassThru(pName, pUnk, phr, pPin) , m_StartMedia(0) , m_EndMedia(0) , m_bReset(TRUE) { } // Sets the media times the object should report HRESULT CRendererPosPassThru::RegisterMediaTime(IMediaSample *pMediaSample) { ASSERT(pMediaSample); LONGLONG StartMedia; LONGLONG EndMedia; CAutoLock cAutoLock(&m_PositionLock); // Get the media times from the sample HRESULT hr = pMediaSample->GetTime(&StartMedia, &EndMedia); if (FAILED(hr)) { ASSERT(hr == VFW_E_SAMPLE_TIME_NOT_SET); return hr; } m_StartMedia = StartMedia; m_EndMedia = EndMedia; m_bReset = FALSE; return NOERROR; } // Sets the media times the object should report HRESULT CRendererPosPassThru::RegisterMediaTime(LONGLONG StartTime, LONGLONG EndTime) { CAutoLock cAutoLock(&m_PositionLock); m_StartMedia = StartTime; m_EndMedia = EndTime; m_bReset = FALSE; return NOERROR; } // Return the current media times registered in the object HRESULT CRendererPosPassThru::GetMediaTime(__out LONGLONG *pStartTime, __out_opt LONGLONG *pEndTime) { ASSERT(pStartTime); CAutoLock cAutoLock(&m_PositionLock); if (m_bReset == TRUE) { return E_FAIL; } // We don't have to return the end time HRESULT hr = ConvertTimeFormat(pStartTime, 0, m_StartMedia, &TIME_FORMAT_MEDIA_TIME); if (pEndTime && SUCCEEDED(hr)) { hr = ConvertTimeFormat(pEndTime, 0, m_EndMedia, &TIME_FORMAT_MEDIA_TIME); } return hr; } // Resets the media times we hold HRESULT CRendererPosPassThru::ResetMediaTime() { CAutoLock cAutoLock(&m_PositionLock); m_StartMedia = 0; m_EndMedia = 0; m_bReset = TRUE; return NOERROR; } // Intended to be called by the owing filter during EOS processing so // that the media times can be adjusted to the stop time. This ensures // that the GetCurrentPosition will actully get to the stop position. HRESULT CRendererPosPassThru::EOS() { HRESULT hr; if (m_bReset == TRUE) hr = E_FAIL; else { LONGLONG llStop; if SUCCEEDED(hr = GetStopPosition(&llStop)) { CAutoLock cAutoLock(&m_PositionLock); m_StartMedia = m_EndMedia = llStop; } } return hr; } // -- CSourceSeeking implementation ------------ CSourceSeeking::CSourceSeeking(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk, __inout HRESULT *phr, __in CCritSec *pLock) : CUnknown(pName, pUnk) , m_pLock(pLock) , m_rtStart((long)0) { m_rtStop = _I64_MAX / 2; m_rtDuration = m_rtStop; m_dRateSeeking = 1.0; m_dwSeekingCaps = AM_SEEKING_CanSeekForwards | AM_SEEKING_CanSeekBackwards | AM_SEEKING_CanSeekAbsolute | AM_SEEKING_CanGetStopPos | AM_SEEKING_CanGetDuration; } HRESULT CSourceSeeking::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_IMediaSeeking) { CheckPointer(ppv, E_POINTER); return GetInterface(static_cast(this), ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } HRESULT CSourceSeeking::IsFormatSupported(const GUID *pFormat) { CheckPointer(pFormat, E_POINTER); // only seeking in time (REFERENCE_TIME units) is supported return *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE; } HRESULT CSourceSeeking::QueryPreferredFormat(__out GUID *pFormat) { CheckPointer(pFormat, E_POINTER); *pFormat = TIME_FORMAT_MEDIA_TIME; return S_OK; } HRESULT CSourceSeeking::SetTimeFormat(const GUID *pFormat) { CheckPointer(pFormat, E_POINTER); // nothing to set; just check that it's TIME_FORMAT_TIME return *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : E_INVALIDARG; } HRESULT CSourceSeeking::IsUsingTimeFormat(const GUID *pFormat) { CheckPointer(pFormat, E_POINTER); return *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE; } HRESULT CSourceSeeking::GetTimeFormat(__out GUID *pFormat) { CheckPointer(pFormat, E_POINTER); *pFormat = TIME_FORMAT_MEDIA_TIME; return S_OK; } HRESULT CSourceSeeking::GetDuration(__out LONGLONG *pDuration) { CheckPointer(pDuration, E_POINTER); CAutoLock lock(m_pLock); *pDuration = m_rtDuration; return S_OK; } HRESULT CSourceSeeking::GetStopPosition(__out LONGLONG *pStop) { CheckPointer(pStop, E_POINTER); CAutoLock lock(m_pLock); *pStop = m_rtStop; return S_OK; } HRESULT CSourceSeeking::GetCurrentPosition(__out LONGLONG *pCurrent) { // GetCurrentPosition is typically supported only in renderers and // not in source filters. return E_NOTIMPL; } HRESULT CSourceSeeking::GetCapabilities(__out DWORD *pCapabilities) { CheckPointer(pCapabilities, E_POINTER); *pCapabilities = m_dwSeekingCaps; return S_OK; } HRESULT CSourceSeeking::CheckCapabilities(__inout DWORD *pCapabilities) { CheckPointer(pCapabilities, E_POINTER); // make sure all requested capabilities are in our mask return (~m_dwSeekingCaps & *pCapabilities) ? S_FALSE : S_OK; } HRESULT CSourceSeeking::ConvertTimeFormat(__out LONGLONG *pTarget, __in_opt const GUID *pTargetFormat, LONGLONG Source, __in_opt const GUID *pSourceFormat) { CheckPointer(pTarget, E_POINTER); // format guids can be null to indicate current format // since we only support TIME_FORMAT_MEDIA_TIME, we don't really // offer any conversions. if (pTargetFormat == 0 || *pTargetFormat == TIME_FORMAT_MEDIA_TIME) { if (pSourceFormat == 0 || *pSourceFormat == TIME_FORMAT_MEDIA_TIME) { *pTarget = Source; return S_OK; } } return E_INVALIDARG; } HRESULT CSourceSeeking::SetPositions(__inout_opt LONGLONG *pCurrent, DWORD CurrentFlags, __inout_opt LONGLONG *pStop, DWORD StopFlags) { DWORD StopPosBits = StopFlags & AM_SEEKING_PositioningBitsMask; DWORD StartPosBits = CurrentFlags & AM_SEEKING_PositioningBitsMask; if (StopFlags) { CheckPointer(pStop, E_POINTER); // accept only relative, incremental, or absolute positioning if (StopPosBits != StopFlags) { return E_INVALIDARG; } } if (CurrentFlags) { CheckPointer(pCurrent, E_POINTER); if (StartPosBits != AM_SEEKING_AbsolutePositioning && StartPosBits != AM_SEEKING_RelativePositioning) { return E_INVALIDARG; } } // scope for autolock { CAutoLock lock(m_pLock); // set start position if (StartPosBits == AM_SEEKING_AbsolutePositioning) { m_rtStart = *pCurrent; } else if (StartPosBits == AM_SEEKING_RelativePositioning) { m_rtStart += *pCurrent; } // set stop position if (StopPosBits == AM_SEEKING_AbsolutePositioning) { m_rtStop = *pStop; } else if (StopPosBits == AM_SEEKING_IncrementalPositioning) { m_rtStop = m_rtStart + *pStop; } else if (StopPosBits == AM_SEEKING_RelativePositioning) { m_rtStop = m_rtStop + *pStop; } } HRESULT hr = S_OK; if (SUCCEEDED(hr) && StopPosBits) { hr = ChangeStop(); } if (StartPosBits) { hr = ChangeStart(); } return hr; } HRESULT CSourceSeeking::GetPositions(__out_opt LONGLONG *pCurrent, __out_opt LONGLONG *pStop) { if (pCurrent) { *pCurrent = m_rtStart; } if (pStop) { *pStop = m_rtStop; } return S_OK; ; } HRESULT CSourceSeeking::GetAvailable(__out_opt LONGLONG *pEarliest, __out_opt LONGLONG *pLatest) { if (pEarliest) { *pEarliest = 0; } if (pLatest) { CAutoLock lock(m_pLock); *pLatest = m_rtDuration; } return S_OK; } HRESULT CSourceSeeking::SetRate(double dRate) { { CAutoLock lock(m_pLock); m_dRateSeeking = dRate; } return ChangeRate(); } HRESULT CSourceSeeking::GetRate(__out double *pdRate) { CheckPointer(pdRate, E_POINTER); CAutoLock lock(m_pLock); *pdRate = m_dRateSeeking; return S_OK; } HRESULT CSourceSeeking::GetPreroll(__out LONGLONG *pPreroll) { CheckPointer(pPreroll, E_POINTER); *pPreroll = 0; return S_OK; } // --- CSourcePosition implementation ---------- CSourcePosition::CSourcePosition(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN pUnk, __inout HRESULT *phr, __in CCritSec *pLock) : CMediaPosition(pName, pUnk) , m_pLock(pLock) , m_Start(CRefTime((LONGLONG)0)) { m_Stop = _I64_MAX; m_Rate = 1.0; } STDMETHODIMP CSourcePosition::get_Duration(__out REFTIME *plength) { CheckPointer(plength, E_POINTER); ValidateReadWritePtr(plength, sizeof(REFTIME)); CAutoLock lock(m_pLock); *plength = m_Duration; return S_OK; } STDMETHODIMP CSourcePosition::put_CurrentPosition(REFTIME llTime) { m_pLock->Lock(); m_Start = llTime; m_pLock->Unlock(); return ChangeStart(); } STDMETHODIMP CSourcePosition::get_StopTime(__out REFTIME *pllTime) { CheckPointer(pllTime, E_POINTER); ValidateReadWritePtr(pllTime, sizeof(REFTIME)); CAutoLock lock(m_pLock); *pllTime = m_Stop; return S_OK; } STDMETHODIMP CSourcePosition::put_StopTime(REFTIME llTime) { m_pLock->Lock(); m_Stop = llTime; m_pLock->Unlock(); return ChangeStop(); } STDMETHODIMP CSourcePosition::get_PrerollTime(__out REFTIME *pllTime) { CheckPointer(pllTime, E_POINTER); ValidateReadWritePtr(pllTime, sizeof(REFTIME)); return E_NOTIMPL; } STDMETHODIMP CSourcePosition::put_PrerollTime(REFTIME llTime) { return E_NOTIMPL; } STDMETHODIMP CSourcePosition::get_Rate(__out double *pdRate) { CheckPointer(pdRate, E_POINTER); ValidateReadWritePtr(pdRate, sizeof(double)); CAutoLock lock(m_pLock); *pdRate = m_Rate; return S_OK; } STDMETHODIMP CSourcePosition::put_Rate(double dRate) { m_pLock->Lock(); m_Rate = dRate; m_pLock->Unlock(); return ChangeRate(); } // By default we can seek forwards STDMETHODIMP CSourcePosition::CanSeekForward(__out LONG *pCanSeekForward) { CheckPointer(pCanSeekForward, E_POINTER); *pCanSeekForward = OATRUE; return S_OK; } // By default we can seek backwards STDMETHODIMP CSourcePosition::CanSeekBackward(__out LONG *pCanSeekBackward) { CheckPointer(pCanSeekBackward, E_POINTER); *pCanSeekBackward = OATRUE; return S_OK; } // --- Implementation of CBasicAudio class ---------- CBasicAudio::CBasicAudio(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN punk) : CUnknown(pName, punk) { } // overriden to publicise our interfaces STDMETHODIMP CBasicAudio::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == IID_IBasicAudio) { return GetInterface((IBasicAudio *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } STDMETHODIMP CBasicAudio::GetTypeInfoCount(__out UINT *pctinfo) { return m_basedisp.GetTypeInfoCount(pctinfo); } STDMETHODIMP CBasicAudio::GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo) { return m_basedisp.GetTypeInfo(IID_IBasicAudio, itinfo, lcid, pptinfo); } STDMETHODIMP CBasicAudio::GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid) { return m_basedisp.GetIDsOfNames(IID_IBasicAudio, rgszNames, cNames, lcid, rgdispid); } STDMETHODIMP CBasicAudio::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr) { // this parameter is a dead leftover from an earlier interface if (IID_NULL != riid) { return DISP_E_UNKNOWNINTERFACE; } ITypeInfo *pti; HRESULT hr = GetTypeInfo(0, lcid, &pti); if (FAILED(hr)) { return hr; } hr = pti->Invoke((IBasicAudio *)this, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); pti->Release(); return hr; } // --- IVideoWindow implementation ---------- CBaseVideoWindow::CBaseVideoWindow(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN punk) : CUnknown(pName, punk) { } // overriden to publicise our interfaces STDMETHODIMP CBaseVideoWindow::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == IID_IVideoWindow) { return GetInterface((IVideoWindow *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } STDMETHODIMP CBaseVideoWindow::GetTypeInfoCount(__out UINT *pctinfo) { return m_basedisp.GetTypeInfoCount(pctinfo); } STDMETHODIMP CBaseVideoWindow::GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo) { return m_basedisp.GetTypeInfo(IID_IVideoWindow, itinfo, lcid, pptinfo); } STDMETHODIMP CBaseVideoWindow::GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid) { return m_basedisp.GetIDsOfNames(IID_IVideoWindow, rgszNames, cNames, lcid, rgdispid); } STDMETHODIMP CBaseVideoWindow::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr) { // this parameter is a dead leftover from an earlier interface if (IID_NULL != riid) { return DISP_E_UNKNOWNINTERFACE; } ITypeInfo *pti; HRESULT hr = GetTypeInfo(0, lcid, &pti); if (FAILED(hr)) { return hr; } hr = pti->Invoke((IVideoWindow *)this, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); pti->Release(); return hr; } // --- IBasicVideo implementation ---------- CBaseBasicVideo::CBaseBasicVideo(__in_opt LPCTSTR pName, __in_opt LPUNKNOWN punk) : CUnknown(pName, punk) { } // overriden to publicise our interfaces STDMETHODIMP CBaseBasicVideo::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == IID_IBasicVideo || riid == IID_IBasicVideo2) { return GetInterface(static_cast(this), ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } STDMETHODIMP CBaseBasicVideo::GetTypeInfoCount(__out UINT *pctinfo) { return m_basedisp.GetTypeInfoCount(pctinfo); } STDMETHODIMP CBaseBasicVideo::GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo) { return m_basedisp.GetTypeInfo(IID_IBasicVideo, itinfo, lcid, pptinfo); } STDMETHODIMP CBaseBasicVideo::GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid) { return m_basedisp.GetIDsOfNames(IID_IBasicVideo, rgszNames, cNames, lcid, rgdispid); } STDMETHODIMP CBaseBasicVideo::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr) { // this parameter is a dead leftover from an earlier interface if (IID_NULL != riid) { return DISP_E_UNKNOWNINTERFACE; } ITypeInfo *pti; HRESULT hr = GetTypeInfo(0, lcid, &pti); if (FAILED(hr)) { return hr; } hr = pti->Invoke((IBasicVideo *)this, dispidMember, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); pti->Release(); return hr; } // --- Implementation of Deferred Commands ---------- CDispParams::CDispParams(UINT nArgs, __in_ecount(nArgs) VARIANT *pArgs, __inout_opt HRESULT *phr) { cNamedArgs = 0; rgdispidNamedArgs = NULL; cArgs = nArgs; if (cArgs) { rgvarg = new VARIANT[cArgs]; if (NULL == rgvarg) { cArgs = 0; if (phr) { *phr = E_OUTOFMEMORY; } return; } for (UINT i = 0; i < cArgs; i++) { // Why aren't we using VariantCopy? VARIANT *pDest = &rgvarg[i]; VARIANT *pSrc = &pArgs[i]; pDest->vt = pSrc->vt; switch (pDest->vt) { case VT_I4: pDest->lVal = pSrc->lVal; break; case VT_UI1: pDest->bVal = pSrc->bVal; break; case VT_I2: pDest->iVal = pSrc->iVal; break; case VT_R4: pDest->fltVal = pSrc->fltVal; break; case VT_R8: pDest->dblVal = pSrc->dblVal; break; case VT_BOOL: pDest->boolVal = pSrc->boolVal; break; case VT_ERROR: pDest->scode = pSrc->scode; break; case VT_CY: pDest->cyVal = pSrc->cyVal; break; case VT_DATE: pDest->date = pSrc->date; break; case VT_BSTR: if ((PVOID)pSrc->bstrVal == NULL) { pDest->bstrVal = NULL; } else { // a BSTR is a WORD followed by a UNICODE string. // the pointer points just after the WORD WORD len = *(WORD *)(pSrc->bstrVal - (sizeof(WORD) / sizeof(OLECHAR))); OLECHAR *pch = new OLECHAR[len + (sizeof(WORD) / sizeof(OLECHAR))]; if (pch) { WORD *pui = (WORD *)pch; *pui = len; pDest->bstrVal = pch + (sizeof(WORD) / sizeof(OLECHAR)); CopyMemory(pDest->bstrVal, pSrc->bstrVal, len * sizeof(OLECHAR)); } else { cArgs = i; if (phr) { *phr = E_OUTOFMEMORY; } } } break; case VT_UNKNOWN: pDest->punkVal = pSrc->punkVal; pDest->punkVal->AddRef(); break; case VT_DISPATCH: pDest->pdispVal = pSrc->pdispVal; pDest->pdispVal->AddRef(); break; default: // a type we haven't got round to adding yet! ASSERT(0); break; } } } else { rgvarg = NULL; } } CDispParams::~CDispParams() { for (UINT i = 0; i < cArgs; i++) { switch (rgvarg[i].vt) { case VT_BSTR: // Explicitly cast BSTR to PVOID to tell code scanning tools we really mean to test the pointer if ((PVOID)rgvarg[i].bstrVal != NULL) { OLECHAR *pch = rgvarg[i].bstrVal - (sizeof(WORD) / sizeof(OLECHAR)); delete pch; } break; case VT_UNKNOWN: rgvarg[i].punkVal->Release(); break; case VT_DISPATCH: rgvarg[i].pdispVal->Release(); break; } } delete[] rgvarg; } // lifetime is controlled by refcounts (see defer.h) CDeferredCommand::CDeferredCommand(__inout CCmdQueue *pQ, __in_opt LPUNKNOWN pUnk, __inout HRESULT *phr, __in LPUNKNOWN pUnkExecutor, REFTIME time, __in GUID *iid, long dispidMethod, short wFlags, long nArgs, __in_ecount(nArgs) VARIANT *pDispParams, __out VARIANT *pvarResult, __out short *puArgErr, BOOL bStream) : CUnknown(NAME("DeferredCommand"), pUnk) , m_pQueue(pQ) , m_pUnk(pUnkExecutor) , m_iid(iid) , m_dispidMethod(dispidMethod) , m_wFlags(wFlags) , m_DispParams(nArgs, pDispParams, phr) , m_pvarResult(pvarResult) , m_bStream(bStream) , m_hrResult(E_ABORT) { // convert REFTIME to REFERENCE_TIME COARefTime convertor(time); m_time = convertor; // no check of time validity - it's ok to queue a command that's // already late // check iid is supportable on pUnk by QueryInterface for it IUnknown *pInterface; HRESULT hr = m_pUnk->QueryInterface(GetIID(), (void **)&pInterface); if (FAILED(hr)) { *phr = hr; return; } pInterface->Release(); // !!! check dispidMethod and param/return types using typelib ITypeInfo *pti; hr = m_Dispatch.GetTypeInfo(*iid, 0, 0, &pti); if (FAILED(hr)) { *phr = hr; return; } // !!! some sort of ITypeInfo validity check here pti->Release(); // Fix up the dispid for put and get if (wFlags == DISPATCH_PROPERTYPUT) { m_DispParams.cNamedArgs = 1; m_DispId = DISPID_PROPERTYPUT; m_DispParams.rgdispidNamedArgs = &m_DispId; } // all checks ok - add to queue hr = pQ->Insert(this); if (FAILED(hr)) { *phr = hr; } } // refcounts are held by caller of InvokeAt... and by list. So if // we get here, we can't be on the list #if 0 CDeferredCommand::~CDeferredCommand() { // this assert is invalid since if the queue is deleted while we are // still on the queue, we will have been removed by the queue and this // m_pQueue will not have been modified. // ASSERT(m_pQueue == NULL); // we don't hold a ref count on pUnk, which is the object that should // execute the command. // This is because there would otherwise be a circular refcount problem // since pUnk probably owns the CmdQueue object that has a refcount // on us. // The lifetime of pUnk is guaranteed by it being part of, or lifetime // controlled by, our parent object. As long as we are on the list, pUnk // must be valid. Once we are off the list, we do not use pUnk. } #endif // overriden to publicise our interfaces STDMETHODIMP CDeferredCommand::NonDelegatingQueryInterface(REFIID riid, __out void **ppv) { ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == IID_IDeferredCommand) { return GetInterface((IDeferredCommand *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } // remove from q. this will reduce the refcount by one (since the q // holds a count) but can't make us go away since he must have a // refcount in order to call this method. STDMETHODIMP CDeferredCommand::Cancel() { if (m_pQueue == NULL) { return VFW_E_ALREADY_CANCELLED; } HRESULT hr = m_pQueue->Remove(this); if (FAILED(hr)) { return hr; } m_pQueue = NULL; return S_OK; } STDMETHODIMP CDeferredCommand::Confidence(__out LONG *pConfidence) { return E_NOTIMPL; } STDMETHODIMP CDeferredCommand::GetHResult(__out HRESULT *phrResult) { CheckPointer(phrResult, E_POINTER); ValidateReadWritePtr(phrResult, sizeof(HRESULT)); if (m_pQueue != NULL) { return E_ABORT; } *phrResult = m_hrResult; return S_OK; } // set the time to be a new time (checking that it is valid) and // then requeue STDMETHODIMP CDeferredCommand::Postpone(REFTIME newtime) { // check that this time is not past // convert REFTIME to REFERENCE_TIME COARefTime convertor(newtime); // check that the time has not passed if (m_pQueue->CheckTime(convertor, IsStreamTime())) { return VFW_E_TIME_ALREADY_PASSED; } // extract from list HRESULT hr = m_pQueue->Remove(this); if (FAILED(hr)) { return hr; } // change time m_time = convertor; // requeue hr = m_pQueue->Insert(this); return hr; } HRESULT CDeferredCommand::Invoke() { // check that we are still outstanding if (m_pQueue == NULL) { return VFW_E_ALREADY_CANCELLED; } // get the type info ITypeInfo *pti; HRESULT hr = m_Dispatch.GetTypeInfo(GetIID(), 0, 0, &pti); if (FAILED(hr)) { return hr; } // qi for the expected interface and then invoke it. Note that we have to // treat the returned interface as IUnknown since we don't know its type. IUnknown *pInterface; hr = m_pUnk->QueryInterface(GetIID(), (void **)&pInterface); if (FAILED(hr)) { pti->Release(); return hr; } EXCEPINFO expinfo; UINT uArgErr; m_hrResult = pti->Invoke(pInterface, GetMethod(), GetFlags(), GetParams(), GetResult(), &expinfo, &uArgErr); // release the interface we QI'd for pInterface->Release(); pti->Release(); // remove from list whether or not successful // or we loop indefinitely hr = m_pQueue->Remove(this); m_pQueue = NULL; return hr; } // --- CCmdQueue methods ---------- CCmdQueue::CCmdQueue(__inout_opt HRESULT *phr) : m_listPresentation(NAME("Presentation time command list")) , m_listStream(NAME("Stream time command list")) , m_evDue(TRUE, phr) , // manual reset m_dwAdvise(0) , m_pClock(NULL) , m_bRunning(FALSE) { } CCmdQueue::~CCmdQueue() { // empty all our lists // we hold a refcount on each, so traverse and Release each // entry then RemoveAll to empty the list POSITION pos = m_listPresentation.GetHeadPosition(); while (pos) { CDeferredCommand *pCmd = m_listPresentation.GetNext(pos); pCmd->Release(); } m_listPresentation.RemoveAll(); pos = m_listStream.GetHeadPosition(); while (pos) { CDeferredCommand *pCmd = m_listStream.GetNext(pos); pCmd->Release(); } m_listStream.RemoveAll(); if (m_pClock) { if (m_dwAdvise) { m_pClock->Unadvise(m_dwAdvise); m_dwAdvise = 0; } m_pClock->Release(); } } // returns a new CDeferredCommand object that will be initialised with // the parameters and will be added to the queue during construction. // returns S_OK if successfully created otherwise an error and // no object has been queued. HRESULT CCmdQueue::New(__out CDeferredCommand **ppCmd, __in LPUNKNOWN pUnk, // this object will execute command REFTIME time, __in GUID *iid, long dispidMethod, short wFlags, long cArgs, __in_ecount(cArgs) VARIANT *pDispParams, __out VARIANT *pvarResult, __out short *puArgErr, BOOL bStream) { CAutoLock lock(&m_Lock); HRESULT hr = S_OK; *ppCmd = NULL; CDeferredCommand *pCmd; pCmd = new CDeferredCommand(this, NULL, // not aggregated &hr, pUnk, // this guy will execute time, iid, dispidMethod, wFlags, cArgs, pDispParams, pvarResult, puArgErr, bStream); if (pCmd == NULL) { hr = E_OUTOFMEMORY; } else { *ppCmd = pCmd; } return hr; } HRESULT CCmdQueue::Insert(__in CDeferredCommand *pCmd) { CAutoLock lock(&m_Lock); // addref the item pCmd->AddRef(); CGenericList *pList; if (pCmd->IsStreamTime()) { pList = &m_listStream; } else { pList = &m_listPresentation; } POSITION pos = pList->GetHeadPosition(); // seek past all items that are before us while (pos && (pList->GetValid(pos)->GetTime() <= pCmd->GetTime())) { pList->GetNext(pos); } // now at end of list or in front of items that come later if (!pos) { pList->AddTail(pCmd); } else { pList->AddBefore(pos, pCmd); } SetTimeAdvise(); return S_OK; } HRESULT CCmdQueue::Remove(__in CDeferredCommand *pCmd) { CAutoLock lock(&m_Lock); HRESULT hr = S_OK; CGenericList *pList; if (pCmd->IsStreamTime()) { pList = &m_listStream; } else { pList = &m_listPresentation; } POSITION pos = pList->GetHeadPosition(); // traverse the list while (pos && (pList->GetValid(pos) != pCmd)) { pList->GetNext(pos); } // did we drop off the end? if (!pos) { hr = VFW_E_NOT_FOUND; } else { // found it - now take off list pList->Remove(pos); // Insert did an AddRef, so release it pCmd->Release(); // check that timer request is still for earliest time SetTimeAdvise(); } return hr; } // set the clock used for timing HRESULT CCmdQueue::SetSyncSource(__in_opt IReferenceClock *pClock) { CAutoLock lock(&m_Lock); // addref the new clock first in case they are the same if (pClock) { pClock->AddRef(); } // kill any advise on the old clock if (m_pClock) { if (m_dwAdvise) { m_pClock->Unadvise(m_dwAdvise); m_dwAdvise = 0; } m_pClock->Release(); } m_pClock = pClock; // set up a new advise SetTimeAdvise(); return S_OK; } // set up a timer event with the reference clock void CCmdQueue::SetTimeAdvise(void) { // make sure we have a clock to use if (!m_pClock) { return; } // reset the event whenever we are requesting a new signal m_evDue.Reset(); // time 0 is earliest CRefTime current; // find the earliest presentation time POSITION pos = m_listPresentation.GetHeadPosition(); if (pos != NULL) { current = m_listPresentation.GetValid(pos)->GetTime(); } // if we're running, check the stream times too if (m_bRunning) { CRefTime t; pos = m_listStream.GetHeadPosition(); if (NULL != pos) { t = m_listStream.GetValid(pos)->GetTime(); // add on stream time offset to get presentation time t += m_StreamTimeOffset; // is this earlier? if ((current == TimeZero) || (t < current)) { current = t; } } } // need to change? if ((current > TimeZero) && (current != m_tCurrentAdvise)) { if (m_dwAdvise) { m_pClock->Unadvise(m_dwAdvise); // reset the event whenever we are requesting a new signal m_evDue.Reset(); } // ask for time advice - the first two params are either // stream time offset and stream time or // presentation time and 0. we always use the latter HRESULT hr = m_pClock->AdviseTime((REFERENCE_TIME)current, TimeZero, (HEVENT)HANDLE(m_evDue), &m_dwAdvise); ASSERT(SUCCEEDED(hr)); m_tCurrentAdvise = current; } } // switch to run mode. Streamtime to Presentation time mapping known. HRESULT CCmdQueue::Run(REFERENCE_TIME tStreamTimeOffset) { CAutoLock lock(&m_Lock); m_StreamTimeOffset = tStreamTimeOffset; m_bRunning = TRUE; // ensure advise is accurate SetTimeAdvise(); return S_OK; } // switch to Stopped or Paused mode. Time mapping not known. HRESULT CCmdQueue::EndRun() { CAutoLock lock(&m_Lock); m_bRunning = FALSE; // check timer setting - stream times SetTimeAdvise(); return S_OK; } // return a pointer to the next due command. Blocks for msTimeout // milliseconds until there is a due command. // Stream-time commands will only become due between Run and Endrun calls. // The command remains queued until invoked or cancelled. // Returns E_ABORT if timeout occurs, otherwise S_OK (or other error). // // returns an AddRef'd object HRESULT CCmdQueue::GetDueCommand(__out CDeferredCommand **ppCmd, long msTimeout) { // loop until we timeout or find a due command for (;;) { { CAutoLock lock(&m_Lock); // find the earliest command CDeferredCommand *pCmd = NULL; // check the presentation time and the // stream time list to find the earliest POSITION pos = m_listPresentation.GetHeadPosition(); if (NULL != pos) { pCmd = m_listPresentation.GetValid(pos); } if (m_bRunning) { pos = m_listStream.GetHeadPosition(); if (NULL != pos) { CDeferredCommand *pStrm = m_listStream.GetValid(pos); CRefTime t = pStrm->GetTime() + m_StreamTimeOffset; if (!pCmd || (t < pCmd->GetTime())) { pCmd = pStrm; } } } // if we have found one, is it due? if (pCmd) { if (CheckTime(pCmd->GetTime(), pCmd->IsStreamTime())) { // yes it's due - addref it pCmd->AddRef(); *ppCmd = pCmd; return S_OK; } } } // block until the advise is signalled if (WaitForSingleObject(m_evDue, msTimeout) != WAIT_OBJECT_0) { return E_ABORT; } } } // return a pointer to a command that will be due for a given time. // Pass in a stream time here. The stream time offset will be passed // in via the Run method. // Commands remain queued until invoked or cancelled. // This method will not block. It will report E_ABORT if there are no // commands due yet. // // returns an AddRef'd object HRESULT CCmdQueue::GetCommandDueFor(REFERENCE_TIME rtStream, __out CDeferredCommand **ppCmd) { CAutoLock lock(&m_Lock); CRefTime tStream(rtStream); // find the earliest stream and presentation time commands CDeferredCommand *pStream = NULL; POSITION pos = m_listStream.GetHeadPosition(); if (NULL != pos) { pStream = m_listStream.GetValid(pos); } CDeferredCommand *pPresent = NULL; pos = m_listPresentation.GetHeadPosition(); if (NULL != pos) { pPresent = m_listPresentation.GetValid(pos); } // is there a presentation time that has passed already if (pPresent && CheckTime(pPresent->GetTime(), FALSE)) { pPresent->AddRef(); *ppCmd = pPresent; return S_OK; } // is there a stream time command due before this stream time if (pStream && (pStream->GetTime() <= tStream)) { pStream->AddRef(); *ppCmd = pStream; return S_OK; } // if we are running, we can map presentation times to // stream time. In this case, is there a presentation time command // that will be due before this stream time is presented? if (m_bRunning && pPresent) { // this stream time will appear at... tStream += m_StreamTimeOffset; // due before that? if (pPresent->GetTime() <= tStream) { *ppCmd = pPresent; return S_OK; } } // no commands due yet return VFW_E_NOT_FOUND; } ================================================ FILE: common/baseclasses/ctlutil.h ================================================ //------------------------------------------------------------------------------ // File: CtlUtil.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Base classes implementing IDispatch parsing for the basic control dual // interfaces. Derive from these and implement just the custom method and // property methods. We also implement CPosPassThru that can be used by // renderers and transforms to pass by IMediaPosition and IMediaSeeking #ifndef __CTLUTIL__ #define __CTLUTIL__ // OLE Automation has different ideas of TRUE and FALSE #define OATRUE (-1) #define OAFALSE (0) // It's possible that we could replace this class with CreateStdDispatch class CBaseDispatch { ITypeInfo *m_pti; public: CBaseDispatch() : m_pti(NULL) { } ~CBaseDispatch(); /* IDispatch methods */ STDMETHODIMP GetTypeInfoCount(__out UINT *pctinfo); STDMETHODIMP GetTypeInfo(REFIID riid, UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid); }; class AM_NOVTABLE CMediaControl : public IMediaControl , public CUnknown { CBaseDispatch m_basedisp; public: CMediaControl(const TCHAR *, LPUNKNOWN); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); /* IDispatch methods */ STDMETHODIMP GetTypeInfoCount(__out UINT *pctinfo); STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid); STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr); }; class AM_NOVTABLE CMediaEvent : public IMediaEventEx , public CUnknown { CBaseDispatch m_basedisp; public: CMediaEvent(__in_opt LPCTSTR, __in_opt LPUNKNOWN); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); /* IDispatch methods */ STDMETHODIMP GetTypeInfoCount(__out UINT *pctinfo); STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid); STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr); }; class AM_NOVTABLE CMediaPosition : public IMediaPosition , public CUnknown { CBaseDispatch m_basedisp; public: CMediaPosition(__in_opt LPCTSTR, __in_opt LPUNKNOWN); CMediaPosition(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT *phr); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); /* IDispatch methods */ STDMETHODIMP GetTypeInfoCount(__out UINT *pctinfo); STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid); STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr); }; // OA-compatibility means that we must use double as the RefTime value, // and REFERENCE_TIME (essentially a LONGLONG) within filters. // this class converts between the two class COARefTime : public CRefTime { public: COARefTime(){}; COARefTime(CRefTime t) : CRefTime(t){}; COARefTime(REFERENCE_TIME t) : CRefTime(t){}; COARefTime(double d) { m_time = (LONGLONG)(d * 10000000); }; operator double() { return double(m_time) / 10000000; }; operator REFERENCE_TIME() { return m_time; }; COARefTime &operator=(const double &rd) { m_time = (LONGLONG)(rd * 10000000); return *this; } COARefTime &operator=(const REFERENCE_TIME &rt) { m_time = rt; return *this; } inline BOOL operator==(const COARefTime &rt) { return m_time == rt.m_time; }; inline BOOL operator!=(const COARefTime &rt) { return m_time != rt.m_time; }; inline BOOL operator<(const COARefTime &rt) { return m_time < rt.m_time; }; inline BOOL operator>(const COARefTime &rt) { return m_time > rt.m_time; }; inline BOOL operator>=(const COARefTime &rt) { return m_time >= rt.m_time; }; inline BOOL operator<=(const COARefTime &rt) { return m_time <= rt.m_time; }; inline COARefTime operator+(const COARefTime &rt) { return COARefTime(m_time + rt.m_time); }; inline COARefTime operator-(const COARefTime &rt) { return COARefTime(m_time - rt.m_time); }; inline COARefTime operator*(LONG l) { return COARefTime(m_time * l); }; inline COARefTime operator/(LONG l) { return COARefTime(m_time / l); }; private: // Prevent bugs from constructing from LONG (which gets // converted to double and then multiplied by 10000000 COARefTime(LONG); LONG operator=(LONG); }; // A utility class that handles IMediaPosition and IMediaSeeking on behalf // of single-input pin renderers, or transform filters. // // Renderers will expose this from the filter; transform filters will // expose it from the output pin and not the renderer. // // Create one of these, giving it your IPin* for your input pin, and delegate // all IMediaPosition methods to it. It will query the input pin for // IMediaPosition and respond appropriately. // // Call ForceRefresh if the pin connection changes. // // This class no longer caches the upstream IMediaPosition or IMediaSeeking // it acquires it on each method call. This means ForceRefresh is not needed. // The method is kept for source compatibility and to minimise the changes // if we need to put it back later for performance reasons. class CPosPassThru : public IMediaSeeking , public CMediaPosition { IPin *m_pPin; HRESULT GetPeer(__deref_out IMediaPosition **ppMP); HRESULT GetPeerSeeking(__deref_out IMediaSeeking **ppMS); public: CPosPassThru(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT *, IPin *); DECLARE_IUNKNOWN HRESULT ForceRefresh() { return S_OK; }; // override to return an accurate current position virtual HRESULT GetMediaTime(__out LONGLONG *pStartTime, __out_opt LONGLONG *pEndTime) { return E_FAIL; } STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // IMediaSeeking methods STDMETHODIMP GetCapabilities(__out DWORD *pCapabilities); STDMETHODIMP CheckCapabilities(__inout DWORD *pCapabilities); STDMETHODIMP SetTimeFormat(const GUID *pFormat); STDMETHODIMP GetTimeFormat(__out GUID *pFormat); STDMETHODIMP IsUsingTimeFormat(const GUID *pFormat); STDMETHODIMP IsFormatSupported(const GUID *pFormat); STDMETHODIMP QueryPreferredFormat(__out GUID *pFormat); STDMETHODIMP ConvertTimeFormat(__out LONGLONG *pTarget, __in_opt const GUID *pTargetFormat, LONGLONG Source, __in_opt const GUID *pSourceFormat); STDMETHODIMP SetPositions(__inout_opt LONGLONG *pCurrent, DWORD CurrentFlags, __inout_opt LONGLONG *pStop, DWORD StopFlags); STDMETHODIMP GetPositions(__out_opt LONGLONG *pCurrent, __out_opt LONGLONG *pStop); STDMETHODIMP GetCurrentPosition(__out LONGLONG *pCurrent); STDMETHODIMP GetStopPosition(__out LONGLONG *pStop); STDMETHODIMP SetRate(double dRate); STDMETHODIMP GetRate(__out double *pdRate); STDMETHODIMP GetDuration(__out LONGLONG *pDuration); STDMETHODIMP GetAvailable(__out_opt LONGLONG *pEarliest, __out_opt LONGLONG *pLatest); STDMETHODIMP GetPreroll(__out LONGLONG *pllPreroll); // IMediaPosition properties STDMETHODIMP get_Duration(__out REFTIME *plength); STDMETHODIMP put_CurrentPosition(REFTIME llTime); STDMETHODIMP get_StopTime(__out REFTIME *pllTime); STDMETHODIMP put_StopTime(REFTIME llTime); STDMETHODIMP get_PrerollTime(__out REFTIME *pllTime); STDMETHODIMP put_PrerollTime(REFTIME llTime); STDMETHODIMP get_Rate(__out double *pdRate); STDMETHODIMP put_Rate(double dRate); STDMETHODIMP get_CurrentPosition(__out REFTIME *pllTime); STDMETHODIMP CanSeekForward(__out LONG *pCanSeekForward); STDMETHODIMP CanSeekBackward(__out LONG *pCanSeekBackward); private: HRESULT GetSeekingLongLong(HRESULT (__stdcall IMediaSeeking::*pMethod)(LONGLONG *), __out LONGLONG *pll); }; // Adds the ability to return a current position class CRendererPosPassThru : public CPosPassThru { CCritSec m_PositionLock; // Locks access to our position LONGLONG m_StartMedia; // Start media time last seen LONGLONG m_EndMedia; // And likewise the end media BOOL m_bReset; // Have media times been set public: // Used to help with passing media times through graph CRendererPosPassThru(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT *, IPin *); HRESULT RegisterMediaTime(IMediaSample *pMediaSample); HRESULT RegisterMediaTime(LONGLONG StartTime, LONGLONG EndTime); HRESULT GetMediaTime(__out LONGLONG *pStartTime, __out_opt LONGLONG *pEndTime); HRESULT ResetMediaTime(); HRESULT EOS(); }; STDAPI CreatePosPassThru(__in_opt LPUNKNOWN pAgg, BOOL bRenderer, IPin *pPin, __deref_out IUnknown **ppPassThru); // A class that handles the IDispatch part of IBasicAudio and leaves the // properties and methods themselves pure virtual. class AM_NOVTABLE CBasicAudio : public IBasicAudio , public CUnknown { CBaseDispatch m_basedisp; public: CBasicAudio(__in_opt LPCTSTR, __in_opt LPUNKNOWN); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); /* IDispatch methods */ STDMETHODIMP GetTypeInfoCount(__out UINT *pctinfo); STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid); STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr); }; // A class that handles the IDispatch part of IBasicVideo and leaves the // properties and methods themselves pure virtual. class AM_NOVTABLE CBaseBasicVideo : public IBasicVideo2 , public CUnknown { CBaseDispatch m_basedisp; public: CBaseBasicVideo(__in_opt LPCTSTR, __in_opt LPUNKNOWN); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); /* IDispatch methods */ STDMETHODIMP GetTypeInfoCount(__out UINT *pctinfo); STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid); STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr); STDMETHODIMP GetPreferredAspectRatio(__out long *plAspectX, __out long *plAspectY) { return E_NOTIMPL; } }; // A class that handles the IDispatch part of IVideoWindow and leaves the // properties and methods themselves pure virtual. class AM_NOVTABLE CBaseVideoWindow : public IVideoWindow , public CUnknown { CBaseDispatch m_basedisp; public: CBaseVideoWindow(__in_opt LPCTSTR, __in_opt LPUNKNOWN); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); /* IDispatch methods */ STDMETHODIMP GetTypeInfoCount(__out UINT *pctinfo); STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, __deref_out ITypeInfo **pptinfo); STDMETHODIMP GetIDsOfNames(REFIID riid, __in_ecount(cNames) LPOLESTR *rgszNames, UINT cNames, LCID lcid, __out_ecount(cNames) DISPID *rgdispid); STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, __in DISPPARAMS *pdispparams, __out_opt VARIANT *pvarResult, __out_opt EXCEPINFO *pexcepinfo, __out_opt UINT *puArgErr); }; // abstract class to help source filters with their implementation // of IMediaPosition. Derive from this and set the duration (and stop // position). Also override NotifyChange to do something when the properties // change. class AM_NOVTABLE CSourcePosition : public CMediaPosition { public: CSourcePosition(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT *, __in CCritSec *); // IMediaPosition methods STDMETHODIMP get_Duration(__out REFTIME *plength); STDMETHODIMP put_CurrentPosition(REFTIME llTime); STDMETHODIMP get_StopTime(__out REFTIME *pllTime); STDMETHODIMP put_StopTime(REFTIME llTime); STDMETHODIMP get_PrerollTime(__out REFTIME *pllTime); STDMETHODIMP put_PrerollTime(REFTIME llTime); STDMETHODIMP get_Rate(__out double *pdRate); STDMETHODIMP put_Rate(double dRate); STDMETHODIMP CanSeekForward(__out LONG *pCanSeekForward); STDMETHODIMP CanSeekBackward(__out LONG *pCanSeekBackward); // override if you can return the data you are actually working on STDMETHODIMP get_CurrentPosition(__out REFTIME *pllTime) { return E_NOTIMPL; }; protected: // we call this to notify changes. Override to handle them virtual HRESULT ChangeStart() PURE; virtual HRESULT ChangeStop() PURE; virtual HRESULT ChangeRate() PURE; COARefTime m_Duration; COARefTime m_Start; COARefTime m_Stop; double m_Rate; CCritSec *m_pLock; }; class AM_NOVTABLE CSourceSeeking : public IMediaSeeking , public CUnknown { public: DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // IMediaSeeking methods STDMETHODIMP IsFormatSupported(const GUID *pFormat); STDMETHODIMP QueryPreferredFormat(__out GUID *pFormat); STDMETHODIMP SetTimeFormat(const GUID *pFormat); STDMETHODIMP IsUsingTimeFormat(const GUID *pFormat); STDMETHODIMP GetTimeFormat(__out GUID *pFormat); STDMETHODIMP GetDuration(__out LONGLONG *pDuration); STDMETHODIMP GetStopPosition(__out LONGLONG *pStop); STDMETHODIMP GetCurrentPosition(__out LONGLONG *pCurrent); STDMETHODIMP GetCapabilities(__out DWORD *pCapabilities); STDMETHODIMP CheckCapabilities(__inout DWORD *pCapabilities); STDMETHODIMP ConvertTimeFormat(__out LONGLONG *pTarget, __in_opt const GUID *pTargetFormat, LONGLONG Source, __in_opt const GUID *pSourceFormat); STDMETHODIMP SetPositions(__inout_opt LONGLONG *pCurrent, DWORD CurrentFlags, __inout_opt LONGLONG *pStop, DWORD StopFlags); STDMETHODIMP GetPositions(__out_opt LONGLONG *pCurrent, __out_opt LONGLONG *pStop); STDMETHODIMP GetAvailable(__out_opt LONGLONG *pEarliest, __out_opt LONGLONG *pLatest); STDMETHODIMP SetRate(double dRate); STDMETHODIMP GetRate(__out double *pdRate); STDMETHODIMP GetPreroll(__out LONGLONG *pPreroll); protected: // ctor CSourceSeeking(__in_opt LPCTSTR, __in_opt LPUNKNOWN, __inout HRESULT *, __in CCritSec *); // we call this to notify changes. Override to handle them virtual HRESULT ChangeStart() PURE; virtual HRESULT ChangeStop() PURE; virtual HRESULT ChangeRate() PURE; CRefTime m_rtDuration; // length of stream CRefTime m_rtStart; // source will start here CRefTime m_rtStop; // source will stop here double m_dRateSeeking; // seeking capabilities DWORD m_dwSeekingCaps; CCritSec *m_pLock; }; // Base classes supporting Deferred commands. // Deferred commands are queued by calls to methods on the IQueueCommand // interface, exposed by the filtergraph and by some filters. A successful // call to one of these methods will return an IDeferredCommand interface // representing the queued command. // // A CDeferredCommand object represents a single deferred command, and exposes // the IDeferredCommand interface as well as other methods permitting time // checks and actual execution. It contains a reference to the CCommandQueue // object on which it is queued. // // CCommandQueue is a base class providing a queue of CDeferredCommand // objects, and methods to add, remove, check status and invoke the queued // commands. A CCommandQueue object would be part of an object that // implemented IQueueCommand. class CCmdQueue; // take a copy of the params and store them. Release any allocated // memory in destructor class CDispParams : public DISPPARAMS { public: CDispParams(UINT nArgs, __in_ecount(nArgs) VARIANT *pArgs, __inout_opt HRESULT *phr = NULL); ~CDispParams(); }; // CDeferredCommand lifetime is controlled by refcounts. Caller of // InvokeAt.. gets a refcounted interface pointer, and the CCmdQueue // object also holds a refcount on us. Calling Cancel or Invoke takes // us off the CCmdQueue and thus reduces the refcount by 1. Once taken // off the queue we cannot be put back on the queue. class CDeferredCommand : public CUnknown , public IDeferredCommand { public: CDeferredCommand(__inout CCmdQueue *pQ, __in_opt LPUNKNOWN pUnk, // aggregation outer unk __inout HRESULT *phr, __in LPUNKNOWN pUnkExecutor, // object that will execute this cmd REFTIME time, __in GUID *iid, long dispidMethod, short wFlags, long cArgs, __in_ecount(cArgs) VARIANT *pDispParams, __out VARIANT *pvarResult, __out short *puArgErr, BOOL bStream); DECLARE_IUNKNOWN // override this to publicise our interfaces STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __out void **ppv); // IDeferredCommand methods STDMETHODIMP Cancel(); STDMETHODIMP Confidence(__out LONG *pConfidence); STDMETHODIMP Postpone(REFTIME newtime); STDMETHODIMP GetHResult(__out HRESULT *phrResult); // other public methods HRESULT Invoke(); // access methods // returns TRUE if streamtime, FALSE if presentation time BOOL IsStreamTime() { return m_bStream; }; CRefTime GetTime() { return m_time; }; REFIID GetIID() { return *m_iid; }; long GetMethod() { return m_dispidMethod; }; short GetFlags() { return m_wFlags; }; DISPPARAMS *GetParams() { return &m_DispParams; }; VARIANT *GetResult() { return m_pvarResult; }; protected: CCmdQueue *m_pQueue; // pUnk for the interface that we will execute the command on LPUNKNOWN m_pUnk; // stored command data REFERENCE_TIME m_time; GUID *m_iid; long m_dispidMethod; short m_wFlags; VARIANT *m_pvarResult; BOOL m_bStream; CDispParams m_DispParams; DISPID m_DispId; // For get and put // we use this for ITypeInfo access CBaseDispatch m_Dispatch; // save retval here HRESULT m_hrResult; }; // a list of CDeferredCommand objects. this is a base class providing // the basics of access to the list. If you want to use CDeferredCommand // objects then your queue needs to be derived from this class. class AM_NOVTABLE CCmdQueue { public: CCmdQueue(__inout_opt HRESULT *phr = NULL); virtual ~CCmdQueue(); // returns a new CDeferredCommand object that will be initialised with // the parameters and will be added to the queue during construction. // returns S_OK if successfully created otherwise an error and // no object has been queued. virtual HRESULT New(__out CDeferredCommand **ppCmd, __in LPUNKNOWN pUnk, REFTIME time, __in GUID *iid, long dispidMethod, short wFlags, long cArgs, __in_ecount(cArgs) VARIANT *pDispParams, __out VARIANT *pvarResult, __out short *puArgErr, BOOL bStream); // called by the CDeferredCommand object to add and remove itself // from the queue virtual HRESULT Insert(__in CDeferredCommand *pCmd); virtual HRESULT Remove(__in CDeferredCommand *pCmd); // Command-Due Checking // // There are two schemes of synchronisation: coarse and accurate. In // coarse mode, you wait till the time arrives and then execute the cmd. // In accurate mode, you wait until you are processing the sample that // will appear at the time, and then execute the command. It's up to the // filter which one it will implement. The filtergraph will always // implement coarse mode for commands queued at the filtergraph. // // If you want coarse sync, you probably want to wait until there is a // command due, and then execute it. You can do this by calling // GetDueCommand. If you have several things to wait for, get the // event handle from GetDueHandle() and when this is signalled then call // GetDueCommand. Stream time will only advance between calls to Run and // EndRun. Note that to avoid an extra thread there is no guarantee that // if the handle is set there will be a command ready. Each time the // event is signalled, call GetDueCommand (probably with a 0 timeout); // This may return E_ABORT. // // If you want accurate sync, you must call GetCommandDueFor, passing // as a parameter the stream time of the samples you are about to process. // This will return: // -- a stream-time command due at or before that stream time // -- a presentation-time command due at or before the // time that stream time will be presented (only between Run // and EndRun calls, since outside of this, the mapping from // stream time to presentation time is not known. // -- any presentation-time command due now. // This means that if you want accurate synchronisation on samples that // might be processed during Paused mode, you need to use // stream-time commands. // // In all cases, commands remain queued until Invoked or Cancelled. The // setting and resetting of the event handle is managed entirely by this // queue object. // set the clock used for timing virtual HRESULT SetSyncSource(__in_opt IReferenceClock *); // switch to run mode. Streamtime to Presentation time mapping known. virtual HRESULT Run(REFERENCE_TIME tStreamTimeOffset); // switch to Stopped or Paused mode. Time mapping not known. virtual HRESULT EndRun(); // return a pointer to the next due command. Blocks for msTimeout // milliseconds until there is a due command. // Stream-time commands will only become due between Run and Endrun calls. // The command remains queued until invoked or cancelled. // Returns E_ABORT if timeout occurs, otherwise S_OK (or other error). // Returns an AddRef-ed object virtual HRESULT GetDueCommand(__out CDeferredCommand **ppCmd, long msTimeout); // return the event handle that will be signalled whenever // there are deferred commands due for execution (when GetDueCommand // will not block). HANDLE GetDueHandle() { return HANDLE(m_evDue); }; // return a pointer to a command that will be due for a given time. // Pass in a stream time here. The stream time offset will be passed // in via the Run method. // Commands remain queued until invoked or cancelled. // This method will not block. It will report VFW_E_NOT_FOUND if there // are no commands due yet. // Returns an AddRef-ed object virtual HRESULT GetCommandDueFor(REFERENCE_TIME tStream, __out CDeferredCommand **ppCmd); // check if a given time is due (TRUE if it is due yet) BOOL CheckTime(CRefTime time, BOOL bStream) { // if no clock, nothing is due! if (!m_pClock) { return FALSE; } // stream time if (bStream) { // not valid if not running if (!m_bRunning) { return FALSE; } // add on known stream time offset to get presentation time time += m_StreamTimeOffset; } CRefTime Now; m_pClock->GetTime((REFERENCE_TIME *)&Now); return (time <= Now); }; protected: // protect access to lists etc CCritSec m_Lock; // commands queued in presentation time are stored here CGenericList m_listPresentation; // commands queued in stream time are stored here CGenericList m_listStream; // set when any commands are due CAMEvent m_evDue; // creates an advise for the earliest time required, if any void SetTimeAdvise(void); // advise id from reference clock (0 if no outstanding advise) DWORD_PTR m_dwAdvise; // advise time is for this presentation time CRefTime m_tCurrentAdvise; // the reference clock we are using (addrefed) IReferenceClock *m_pClock; // true when running BOOL m_bRunning; // contains stream time offset when m_bRunning is true CRefTime m_StreamTimeOffset; }; #endif // __CTLUTIL__ ================================================ FILE: common/baseclasses/ddmm.cpp ================================================ //------------------------------------------------------------------------------ // File: DDMM.cpp // // Desc: DirectShow base classes - implements routines for using DirectDraw // on a multimonitor system. // // Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include #include "ddmm.h" /* * FindDeviceCallback */ typedef struct { LPSTR szDevice; GUID *lpGUID; GUID GUID; BOOL fFound; } FindDeviceData; BOOL CALLBACK FindDeviceCallback(__in_opt GUID *lpGUID, __in LPSTR szName, __in LPSTR szDevice, __in LPVOID lParam) { FindDeviceData *p = (FindDeviceData *)lParam; if (lstrcmpiA(p->szDevice, szDevice) == 0) { if (lpGUID) { p->GUID = *lpGUID; p->lpGUID = &p->GUID; } else { p->lpGUID = NULL; } p->fFound = TRUE; return FALSE; } return TRUE; } BOOL CALLBACK FindDeviceCallbackEx(__in_opt GUID *lpGUID, __in LPSTR szName, __in LPSTR szDevice, __in LPVOID lParam, HMONITOR hMonitor) { FindDeviceData *p = (FindDeviceData *)lParam; if (lstrcmpiA(p->szDevice, szDevice) == 0) { if (lpGUID) { p->GUID = *lpGUID; p->lpGUID = &p->GUID; } else { p->lpGUID = NULL; } p->fFound = TRUE; return FALSE; } return TRUE; } /* * DirectDrawCreateFromDevice * * create a DirectDraw object for a particular device */ IDirectDraw *DirectDrawCreateFromDevice(__in_opt LPSTR szDevice, PDRAWCREATE DirectDrawCreateP, PDRAWENUM DirectDrawEnumerateP) { IDirectDraw *pdd = NULL; FindDeviceData find; if (szDevice == NULL) { DirectDrawCreateP(NULL, &pdd, NULL); return pdd; } find.szDevice = szDevice; find.fFound = FALSE; DirectDrawEnumerateP(FindDeviceCallback, (LPVOID)&find); if (find.fFound) { // // In 4bpp mode the following DDraw call causes a message box to be popped // up by DDraw (!?!). It's DDraw's fault, but we don't like it. So we // make sure it doesn't happen. // UINT ErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS); DirectDrawCreateP(find.lpGUID, &pdd, NULL); SetErrorMode(ErrorMode); } return pdd; } /* * DirectDrawCreateFromDeviceEx * * create a DirectDraw object for a particular device */ IDirectDraw *DirectDrawCreateFromDeviceEx(__in_opt LPSTR szDevice, PDRAWCREATE DirectDrawCreateP, LPDIRECTDRAWENUMERATEEXA DirectDrawEnumerateExP) { IDirectDraw *pdd = NULL; FindDeviceData find; if (szDevice == NULL) { DirectDrawCreateP(NULL, &pdd, NULL); return pdd; } find.szDevice = szDevice; find.fFound = FALSE; DirectDrawEnumerateExP(FindDeviceCallbackEx, (LPVOID)&find, DDENUM_ATTACHEDSECONDARYDEVICES); if (find.fFound) { // // In 4bpp mode the following DDraw call causes a message box to be popped // up by DDraw (!?!). It's DDraw's fault, but we don't like it. So we // make sure it doesn't happen. // UINT ErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS); DirectDrawCreateP(find.lpGUID, &pdd, NULL); SetErrorMode(ErrorMode); } return pdd; } ================================================ FILE: common/baseclasses/ddmm.h ================================================ //------------------------------------------------------------------------------ // File: DDMM.h // // Desc: DirectShow base classes - efines routines for using DirectDraw // on a multimonitor system. // // Copyright (c) 1995-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifdef __cplusplus extern "C" { /* Assume C declarations for C++ */ #endif /* __cplusplus */ // DDRAW.H might not include these #ifndef DDENUM_ATTACHEDSECONDARYDEVICES #define DDENUM_ATTACHEDSECONDARYDEVICES 0x00000001L #endif typedef HRESULT (*PDRAWCREATE)(IID *, LPDIRECTDRAW *, LPUNKNOWN); typedef HRESULT (*PDRAWENUM)(LPDDENUMCALLBACKA, LPVOID); IDirectDraw *DirectDrawCreateFromDevice(__in_opt LPSTR, PDRAWCREATE, PDRAWENUM); IDirectDraw *DirectDrawCreateFromDeviceEx(__in_opt LPSTR, PDRAWCREATE, LPDIRECTDRAWENUMERATEEXA); #ifdef __cplusplus } #endif /* __cplusplus */ ================================================ FILE: common/baseclasses/dllentry.cpp ================================================ //------------------------------------------------------------------------------ // File: DlleEntry.cpp // // Desc: DirectShow base classes - implements classes used to support dll // entry points for COM objects. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include #ifdef DEBUG #ifdef UNICODE #ifndef _UNICODE #define _UNICODE #endif // _UNICODE #endif // UNICODE #include #endif // DEBUG #include extern CFactoryTemplate g_Templates[]; extern int g_cTemplates; HINSTANCE g_hInst; DWORD g_amPlatform; // VER_PLATFORM_WIN32_WINDOWS etc... (from GetVersionEx) OSVERSIONINFO g_osInfo; // // an instance of this is created by the DLLGetClassObject entrypoint // it uses the CFactoryTemplate object it is given to support the // IClassFactory interface class CClassFactory : public IClassFactory , public CBaseObject { private: const CFactoryTemplate *const m_pTemplate; ULONG m_cRef; static int m_cLocked; public: CClassFactory(const CFactoryTemplate *); // IUnknown STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IClassFactory STDMETHODIMP CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, __deref_out void **pv); STDMETHODIMP LockServer(BOOL fLock); // allow DLLGetClassObject to know about global server lock status static BOOL IsLocked() { return (m_cLocked > 0); }; }; // process-wide dll locked state int CClassFactory::m_cLocked = 0; CClassFactory::CClassFactory(const CFactoryTemplate *pTemplate) : CBaseObject(NAME("Class Factory")) , m_cRef(0) , m_pTemplate(pTemplate) { } STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER) ValidateReadWritePtr(ppv, sizeof(PVOID)); *ppv = NULL; // any interface on this object is the object pointer. if ((riid == IID_IUnknown) || (riid == IID_IClassFactory)) { *ppv = (LPVOID)this; // AddRef returned interface pointer ((LPUNKNOWN)*ppv)->AddRef(); return NOERROR; } return ResultFromScode(E_NOINTERFACE); } STDMETHODIMP_(ULONG) CClassFactory::AddRef() { return ++m_cRef; } STDMETHODIMP_(ULONG) CClassFactory::Release() { LONG lRef = InterlockedDecrement((volatile LONG *)&m_cRef); if (lRef == 0) { delete this; return 0; } else { return lRef; } } STDMETHODIMP CClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, __deref_out void **pv) { CheckPointer(pv, E_POINTER) ValidateReadWritePtr(pv, sizeof(void *)); *pv = NULL; /* Enforce the normal OLE rules regarding interfaces and delegation */ if (pUnkOuter != NULL) { if (IsEqualIID(riid, IID_IUnknown) == FALSE) { *pv = NULL; return ResultFromScode(E_NOINTERFACE); } } /* Create the new object through the derived class's create function */ HRESULT hr = NOERROR; CUnknown *pObj = m_pTemplate->CreateInstance(pUnkOuter, &hr); if (pObj == NULL) { *pv = NULL; if (SUCCEEDED(hr)) { hr = E_OUTOFMEMORY; } return hr; } /* Delete the object if we got a construction error */ if (FAILED(hr)) { delete pObj; *pv = NULL; return hr; } /* Get a reference counted interface on the object */ /* We wrap the non-delegating QI with NDAddRef & NDRelease. */ /* This protects any outer object from being prematurely */ /* released by an inner object that may have to be created */ /* in order to supply the requested interface. */ pObj->NonDelegatingAddRef(); hr = pObj->NonDelegatingQueryInterface(riid, pv); pObj->NonDelegatingRelease(); /* Note that if NonDelegatingQueryInterface fails, it will */ /* not increment the ref count, so the NonDelegatingRelease */ /* will drop the ref back to zero and the object will "self-*/ /* destruct". Hence we don't need additional tidy-up code */ /* to cope with NonDelegatingQueryInterface failing. */ if (SUCCEEDED(hr)) { ASSERT(*pv); } return hr; } STDMETHODIMP CClassFactory::LockServer(BOOL fLock) { if (fLock) { m_cLocked++; } else { m_cLocked--; } return NOERROR; } // --- COM entrypoints ----------------------------------------- // called by COM to get the class factory object for a given class __control_entrypoint(DllExport) STDAPI DllGetClassObject(__in REFCLSID rClsID, __in REFIID riid, __deref_out void **pv) { *pv = NULL; if (!(riid == IID_IUnknown) && !(riid == IID_IClassFactory)) { return E_NOINTERFACE; } // traverse the array of templates looking for one with this // class id for (int i = 0; i < g_cTemplates; i++) { const CFactoryTemplate *pT = &g_Templates[i]; if (pT->IsClassID(rClsID)) { // found a template - make a class factory based on this // template *pv = (LPVOID)(LPUNKNOWN) new CClassFactory(pT); if (*pv == NULL) { return E_OUTOFMEMORY; } ((LPUNKNOWN)*pv)->AddRef(); return NOERROR; } } return CLASS_E_CLASSNOTAVAILABLE; } // // Call any initialization routines // void DllInitClasses(BOOL bLoading) { int i; // traverse the array of templates calling the init routine // if they have one for (i = 0; i < g_cTemplates; i++) { const CFactoryTemplate *pT = &g_Templates[i]; if (pT->m_lpfnInit != NULL) { (*pT->m_lpfnInit)(bLoading, pT->m_ClsID); } } } // called by COM to determine if this dll can be unloaded // return ok unless there are outstanding objects or a lock requested // by IClassFactory::LockServer // // CClassFactory has a static function that can tell us about the locks, // and CCOMObject has a static function that can tell us about the active // object count STDAPI DllCanUnloadNow() { DbgLog((LOG_MEMORY, 2, TEXT("DLLCanUnloadNow called - IsLocked = %d, Active objects = %d"), CClassFactory::IsLocked(), CBaseObject::ObjectsActive())); if (CClassFactory::IsLocked() || CBaseObject::ObjectsActive()) { return S_FALSE; } else { return S_OK; } } // --- standard WIN32 entrypoints -------------------------------------- extern "C" void __cdecl __security_init_cookie(void); extern "C" BOOL WINAPI _DllEntryPoint(HINSTANCE, ULONG, __inout_opt LPVOID); #pragma comment(linker, "/merge:.CRT=.rdata") extern "C" DECLSPEC_NOINLINE BOOL WINAPI DllEntryPoint(HINSTANCE hInstance, ULONG ulReason, __inout_opt LPVOID pv) { if (ulReason == DLL_PROCESS_ATTACH) { // Must happen before any other code is executed. Thankfully - it's re-entrant __security_init_cookie(); } return _DllEntryPoint(hInstance, ulReason, pv); } DECLSPEC_NOINLINE BOOL WINAPI _DllEntryPoint(HINSTANCE hInstance, ULONG ulReason, __inout_opt LPVOID pv) { #ifdef DEBUG extern bool g_fDbgInDllEntryPoint; g_fDbgInDllEntryPoint = true; #endif switch (ulReason) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hInstance); DbgInitialise(hInstance); { // The platform identifier is used to work out whether // full unicode support is available or not. Hence the // default will be the lowest common denominator - i.e. N/A g_amPlatform = VER_PLATFORM_WIN32_WINDOWS; // win95 assumed in case GetVersionEx fails g_osInfo.dwOSVersionInfoSize = sizeof(g_osInfo); if (GetVersionEx(&g_osInfo)) { g_amPlatform = g_osInfo.dwPlatformId; } else { DbgLog((LOG_ERROR, 1, TEXT("Failed to get the OS platform, assuming Win95"))); } } g_hInst = hInstance; DllInitClasses(TRUE); break; case DLL_PROCESS_DETACH: DllInitClasses(FALSE); #ifdef DEBUG if (CBaseObject::ObjectsActive()) { DbgSetModuleLevel(LOG_MEMORY, 2); TCHAR szInfo[512]; extern TCHAR m_ModuleName[]; // Cut down module name TCHAR FullName[_MAX_PATH]; // Load the full path and module name TCHAR *pName; // Searches from the end for a backslash GetModuleFileName(NULL, FullName, _MAX_PATH); pName = _tcsrchr(FullName, '\\'); if (pName == NULL) { pName = FullName; } else { pName++; } (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("Executable: %s Pid %x Tid %x. "), pName, GetCurrentProcessId(), GetCurrentThreadId()); (void)StringCchPrintf(szInfo + lstrlen(szInfo), NUMELMS(szInfo) - lstrlen(szInfo), TEXT("Module %s, %d objects left active!"), m_ModuleName, CBaseObject::ObjectsActive()); DbgAssert(szInfo, TEXT(__FILE__), __LINE__); // If running remotely wait for the Assert to be acknowledged // before dumping out the object register DbgDumpObjectRegister(); } DbgTerminate(); #endif break; } #ifdef DEBUG g_fDbgInDllEntryPoint = false; #endif return TRUE; } ================================================ FILE: common/baseclasses/dllsetup.cpp ================================================ //------------------------------------------------------------------------------ // File: DllSetup.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include //--------------------------------------------------------------------------- // defines #define MAX_KEY_LEN 260 //--------------------------------------------------------------------------- // externally defined functions/variable extern int g_cTemplates; extern CFactoryTemplate g_Templates[]; //--------------------------------------------------------------------------- // // EliminateSubKey // // Try to enumerate all keys under this one. // if we find anything, delete it completely. // Otherwise just delete it. // // note - this was pinched/duplicated from // Filgraph\Mapper.cpp - so should it be in // a lib somewhere? // //--------------------------------------------------------------------------- STDAPI EliminateSubKey(HKEY hkey, LPCTSTR strSubKey) { HKEY hk; if (0 == lstrlen(strSubKey)) { // defensive approach return E_FAIL; } LONG lreturn = RegOpenKeyEx(hkey, strSubKey, 0, MAXIMUM_ALLOWED, &hk); ASSERT(lreturn == ERROR_SUCCESS || lreturn == ERROR_FILE_NOT_FOUND || lreturn == ERROR_INVALID_HANDLE); if (ERROR_SUCCESS == lreturn) { // Keep on enumerating the first (zero-th) // key and deleting that for (;;) { TCHAR Buffer[MAX_KEY_LEN]; DWORD dw = MAX_KEY_LEN; FILETIME ft; lreturn = RegEnumKeyEx(hk, 0, Buffer, &dw, NULL, NULL, NULL, &ft); ASSERT(lreturn == ERROR_SUCCESS || lreturn == ERROR_NO_MORE_ITEMS); if (ERROR_SUCCESS == lreturn) { EliminateSubKey(hk, Buffer); } else { break; } } RegCloseKey(hk); RegDeleteKey(hkey, strSubKey); } return NOERROR; } //--------------------------------------------------------------------------- // // AMovieSetupRegisterServer() // // registers specfied file "szFileName" as server for // CLSID "clsServer". A description is also required. // The ThreadingModel and ServerType are optional, as // they default to InprocServer32 (i.e. dll) and Both. // //--------------------------------------------------------------------------- STDAPI AMovieSetupRegisterServer(CLSID clsServer, LPCWSTR szDescription, LPCWSTR szFileName, LPCWSTR szThreadingModel = L"Both", LPCWSTR szServerType = L"InprocServer32") { // temp buffer // TCHAR achTemp[MAX_PATH]; // convert CLSID uuid to string and write // out subkey as string - CLSID\{} // OLECHAR szCLSID[CHARS_IN_GUID]; HRESULT hr = StringFromGUID2(clsServer, szCLSID, CHARS_IN_GUID); ASSERT(SUCCEEDED(hr)); // create key // HKEY hkey; (void)StringCchPrintf(achTemp, NUMELMS(achTemp), TEXT("CLSID\\%ls"), szCLSID); LONG lreturn = RegCreateKey(HKEY_CLASSES_ROOT, (LPCTSTR)achTemp, &hkey); if (ERROR_SUCCESS != lreturn) { return AmHresultFromWin32(lreturn); } // set description string // (void)StringCchPrintf(achTemp, NUMELMS(achTemp), TEXT("%ls"), szDescription); lreturn = RegSetValue(hkey, (LPCTSTR)NULL, REG_SZ, achTemp, sizeof(achTemp)); if (ERROR_SUCCESS != lreturn) { RegCloseKey(hkey); return AmHresultFromWin32(lreturn); } // create CLSID\\{"CLSID"}\\"ServerType" key, // using key to CLSID\\{"CLSID"} passed back by // last call to RegCreateKey(). // HKEY hsubkey; (void)StringCchPrintf(achTemp, NUMELMS(achTemp), TEXT("%ls"), szServerType); lreturn = RegCreateKey(hkey, achTemp, &hsubkey); if (ERROR_SUCCESS != lreturn) { RegCloseKey(hkey); return AmHresultFromWin32(lreturn); } // set Server string // (void)StringCchPrintf(achTemp, NUMELMS(achTemp), TEXT("%ls"), szFileName); lreturn = RegSetValue(hsubkey, (LPCTSTR)NULL, REG_SZ, (LPCTSTR)achTemp, sizeof(TCHAR) * (lstrlen(achTemp) + 1)); if (ERROR_SUCCESS != lreturn) { RegCloseKey(hkey); RegCloseKey(hsubkey); return AmHresultFromWin32(lreturn); } (void)StringCchPrintf(achTemp, NUMELMS(achTemp), TEXT("%ls"), szThreadingModel); lreturn = RegSetValueEx(hsubkey, TEXT("ThreadingModel"), 0L, REG_SZ, (CONST BYTE *)achTemp, sizeof(TCHAR) * (lstrlen(achTemp) + 1)); // close hkeys // RegCloseKey(hkey); RegCloseKey(hsubkey); // and return // return HRESULT_FROM_WIN32(lreturn); } //--------------------------------------------------------------------------- // // AMovieSetupUnregisterServer() // // default ActiveMovie dll setup function // - to use must be called from an exported // function named DllRegisterServer() // //--------------------------------------------------------------------------- STDAPI AMovieSetupUnregisterServer(CLSID clsServer) { // convert CLSID uuid to string and write // out subkey CLSID\{} // OLECHAR szCLSID[CHARS_IN_GUID]; HRESULT hr = StringFromGUID2(clsServer, szCLSID, CHARS_IN_GUID); ASSERT(SUCCEEDED(hr)); TCHAR achBuffer[MAX_KEY_LEN]; (void)StringCchPrintf(achBuffer, NUMELMS(achBuffer), TEXT("CLSID\\%ls"), szCLSID); // delete subkey // hr = EliminateSubKey(HKEY_CLASSES_ROOT, achBuffer); ASSERT(SUCCEEDED(hr)); // return // return NOERROR; } //--------------------------------------------------------------------------- // // AMovieSetupRegisterFilter through IFilterMapper2 // //--------------------------------------------------------------------------- STDAPI AMovieSetupRegisterFilter2(const AMOVIESETUP_FILTER *const psetupdata, IFilterMapper2 *pIFM2, BOOL bRegister) { DbgLog((LOG_TRACE, 3, TEXT("= AMovieSetupRegisterFilter"))); // check we've got data // if (NULL == psetupdata) return S_FALSE; // unregister filter // (as pins are subkeys of filter's CLSID key // they do not need to be removed separately). // DbgLog((LOG_TRACE, 3, TEXT("= = unregister filter"))); HRESULT hr = pIFM2->UnregisterFilter(0, // default category 0, // default instance name *psetupdata->clsID); if (bRegister) { REGFILTER2 rf2; rf2.dwVersion = 1; rf2.dwMerit = psetupdata->dwMerit; rf2.cPins = psetupdata->nPins; rf2.rgPins = psetupdata->lpPin; // register filter // DbgLog((LOG_TRACE, 3, TEXT("= = register filter"))); hr = pIFM2->RegisterFilter(*psetupdata->clsID, psetupdata->strName, 0 // moniker , &psetupdata->filterCategory // category , NULL // instance , &rf2); } // handle one acceptable "error" - that // of filter not being registered! // (couldn't find a suitable #define'd // name for the error!) // if (0x80070002 == hr) return NOERROR; else return hr; } //--------------------------------------------------------------------------- // // RegisterAllServers() // //--------------------------------------------------------------------------- STDAPI RegisterAllServers(LPCWSTR szFileName, BOOL bRegister) { HRESULT hr = NOERROR; for (int i = 0; i < g_cTemplates; i++) { // get i'th template // const CFactoryTemplate *pT = &g_Templates[i]; DbgLog((LOG_TRACE, 2, TEXT("- - register %ls"), (LPCWSTR)pT->m_Name)); // register CLSID and InprocServer32 // if (bRegister) { hr = AMovieSetupRegisterServer(*(pT->m_ClsID), (LPCWSTR)pT->m_Name, szFileName); } else { hr = AMovieSetupUnregisterServer(*(pT->m_ClsID)); } // check final error for this pass // and break loop if we failed // if (FAILED(hr)) break; } return hr; } //--------------------------------------------------------------------------- // // AMovieDllRegisterServer2() // // default ActiveMovie dll setup function // - to use must be called from an exported // function named DllRegisterServer() // // this function is table driven using the // static members of the CFactoryTemplate // class defined in the dll. // // it registers the Dll as the InprocServer32 // and then calls the IAMovieSetup.Register // method. // //--------------------------------------------------------------------------- STDAPI AMovieDllRegisterServer2(BOOL bRegister) { HRESULT hr = NOERROR; DbgLog((LOG_TRACE, 2, TEXT("AMovieDllRegisterServer2()"))); // get file name (where g_hInst is the // instance handle of the filter dll) // WCHAR achFileName[MAX_PATH]; // WIN95 doesn't support GetModuleFileNameW // { char achTemp[MAX_PATH]; DbgLog((LOG_TRACE, 2, TEXT("- get module file name"))); // g_hInst handle is set in our dll entry point. Make sure // DllEntryPoint in dllentry.cpp is called ASSERT(g_hInst != 0); if (0 == GetModuleFileNameA(g_hInst, achTemp, sizeof(achTemp))) { // we've failed! DWORD dwerr = GetLastError(); return AmHresultFromWin32(dwerr); } MultiByteToWideChar(CP_ACP, 0L, achTemp, lstrlenA(achTemp) + 1, achFileName, NUMELMS(achFileName)); } // // first registering, register all OLE servers // if (bRegister) { DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers"))); hr = RegisterAllServers(achFileName, TRUE); } // // next, register/unregister all filters // if (SUCCEEDED(hr)) { // init is ref counted so call just in case // we're being called cold. // DbgLog((LOG_TRACE, 2, TEXT("- CoInitialize"))); hr = CoInitialize((LPVOID)NULL); ASSERT(SUCCEEDED(hr)); // get hold of IFilterMapper2 // DbgLog((LOG_TRACE, 2, TEXT("- obtain IFilterMapper2"))); IFilterMapper2 *pIFM2 = 0; IFilterMapper *pIFM = 0; hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER, IID_IFilterMapper2, (void **)&pIFM2); if (FAILED(hr)) { DbgLog((LOG_TRACE, 2, TEXT("- trying IFilterMapper instead"))); hr = CoCreateInstance(CLSID_FilterMapper, NULL, CLSCTX_INPROC_SERVER, IID_IFilterMapper, (void **)&pIFM); } if (SUCCEEDED(hr)) { // scan through array of CFactoryTemplates // registering servers and filters. // DbgLog((LOG_TRACE, 2, TEXT("- register Filters"))); for (int i = 0; i < g_cTemplates; i++) { // get i'th template // const CFactoryTemplate *pT = &g_Templates[i]; if (NULL != pT->m_pAMovieSetup_Filter) { DbgLog((LOG_TRACE, 2, TEXT("- - register %ls"), (LPCWSTR)pT->m_Name)); if (pIFM2) { hr = AMovieSetupRegisterFilter2(pT->m_pAMovieSetup_Filter, pIFM2, bRegister); } else { hr = AMovieSetupRegisterFilter(pT->m_pAMovieSetup_Filter, pIFM, bRegister); } } // check final error for this pass // and break loop if we failed // if (FAILED(hr)) break; } // release interface // if (pIFM2) pIFM2->Release(); else pIFM->Release(); } // and clear up // CoFreeUnusedLibraries(); CoUninitialize(); } // // if unregistering, unregister all OLE servers // if (SUCCEEDED(hr) && !bRegister) { DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers"))); hr = RegisterAllServers(achFileName, FALSE); } DbgLog((LOG_TRACE, 2, TEXT("- return %0x"), hr)); return hr; } //--------------------------------------------------------------------------- // // AMovieDllRegisterServer() // // default ActiveMovie dll setup function // - to use must be called from an exported // function named DllRegisterServer() // // this function is table driven using the // static members of the CFactoryTemplate // class defined in the dll. // // it registers the Dll as the InprocServer32 // and then calls the IAMovieSetup.Register // method. // //--------------------------------------------------------------------------- STDAPI AMovieDllRegisterServer(void) { HRESULT hr = NOERROR; // get file name (where g_hInst is the // instance handle of the filter dll) // WCHAR achFileName[MAX_PATH]; { // WIN95 doesn't support GetModuleFileNameW // char achTemp[MAX_PATH]; if (0 == GetModuleFileNameA(g_hInst, achTemp, sizeof(achTemp))) { // we've failed! DWORD dwerr = GetLastError(); return AmHresultFromWin32(dwerr); } MultiByteToWideChar(CP_ACP, 0L, achTemp, lstrlenA(achTemp) + 1, achFileName, NUMELMS(achFileName)); } // scan through array of CFactoryTemplates // registering servers and filters. // for (int i = 0; i < g_cTemplates; i++) { // get i'th template // const CFactoryTemplate *pT = &g_Templates[i]; // register CLSID and InprocServer32 // hr = AMovieSetupRegisterServer(*(pT->m_ClsID), (LPCWSTR)pT->m_Name, achFileName); // instantiate all servers and get hold of // IAMovieSetup, if implemented, and call // IAMovieSetup.Register() method // if (SUCCEEDED(hr) && (NULL != pT->m_lpfnNew)) { // instantiate object // PAMOVIESETUP psetup; hr = CoCreateInstance(*(pT->m_ClsID), 0, CLSCTX_INPROC_SERVER, IID_IAMovieSetup, reinterpret_cast(&psetup)); if (SUCCEEDED(hr)) { hr = psetup->Unregister(); if (SUCCEEDED(hr)) hr = psetup->Register(); psetup->Release(); } else { if ((E_NOINTERFACE == hr) || (VFW_E_NEED_OWNER == hr)) hr = NOERROR; } } // check final error for this pass // and break loop if we failed // if (FAILED(hr)) break; } // end-for return hr; } //--------------------------------------------------------------------------- // // AMovieDllUnregisterServer() // // default ActiveMovie dll uninstall function // - to use must be called from an exported // function named DllRegisterServer() // // this function is table driven using the // static members of the CFactoryTemplate // class defined in the dll. // // it calls the IAMovieSetup.Unregister // method and then unregisters the Dll // as the InprocServer32 // //--------------------------------------------------------------------------- STDAPI AMovieDllUnregisterServer() { // initialize return code // HRESULT hr = NOERROR; // scan through CFactory template and unregister // all OLE servers and filters. // for (int i = g_cTemplates; i--;) { // get i'th template // const CFactoryTemplate *pT = &g_Templates[i]; // check method exists // if (NULL != pT->m_lpfnNew) { // instantiate object // PAMOVIESETUP psetup; hr = CoCreateInstance(*(pT->m_ClsID), 0, CLSCTX_INPROC_SERVER, IID_IAMovieSetup, reinterpret_cast(&psetup)); if (SUCCEEDED(hr)) { hr = psetup->Unregister(); psetup->Release(); } else { if ((E_NOINTERFACE == hr) || (VFW_E_NEED_OWNER == hr)) hr = NOERROR; } } // unregister CLSID and InprocServer32 // if (SUCCEEDED(hr)) { hr = AMovieSetupUnregisterServer(*(pT->m_ClsID)); } // check final error for this pass // and break loop if we failed // if (FAILED(hr)) break; } return hr; } ================================================ FILE: common/baseclasses/dllsetup.h ================================================ //------------------------------------------------------------------------------ // File: DllSetup.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // To be self registering, OLE servers must // export functions named DllRegisterServer // and DllUnregisterServer. To allow use of // custom and default implementations the // defaults are named AMovieDllRegisterServer // and AMovieDllUnregisterServer. // // To the use the default implementation you // must provide stub functions. // // i.e. STDAPI DllRegisterServer() // { // return AMovieDllRegisterServer(); // } // // STDAPI DllUnregisterServer() // { // return AMovieDllUnregisterServer(); // } // // // AMovieDllRegisterServer calls IAMovieSetup.Register(), and // AMovieDllUnregisterServer calls IAMovieSetup.Unregister(). STDAPI AMovieDllRegisterServer2(BOOL); STDAPI AMovieDllRegisterServer(); STDAPI AMovieDllUnregisterServer(); // helper functions STDAPI EliminateSubKey(HKEY, LPCTSTR); STDAPI AMovieSetupRegisterFilter2(const AMOVIESETUP_FILTER *const psetupdata, IFilterMapper2 *pIFM2, BOOL bRegister); ================================================ FILE: common/baseclasses/dxmperf.h ================================================ //------------------------------------------------------------------------------ // File: DXMPerf.h // // Desc: Macros for DirectShow performance logging. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef _DXMPERF_H_ #define _DXMPERF_H_ #include #include "perflog.h" #ifdef _IA64_ extern "C" unsigned __int64 __getReg(int whichReg); #pragma intrinsic(__getReg) #endif // _IA64_ inline ULONGLONG _RDTSC(void) { #ifdef _X86_ LARGE_INTEGER li; __asm { _emit 0x0F _emit 0x31 mov li.LowPart,eax mov li.HighPart,edx } return li.QuadPart; #if 0 // This isn't tested yet #elif defined(_IA64_) #define INL_REGID_APITC 3116 return __getReg(INL_REGID_APITC); #endif // 0 #else // unsupported platform // not implemented on non x86/IA64 platforms return 0; #endif // _X86_/_IA64_ } #define DXMPERF_VIDEOREND 0x00000001 #define DXMPERF_AUDIOGLITCH 0x00000002 //#define GETTIME_BIT 0x00000001 //#define AUDIOREND_BIT 0x00000004 //#define FRAMEDROP_BIT 0x00000008 #define AUDIOBREAK_BIT 0x00000010 #define DXMPERF_AUDIORECV 0x00000020 #define DXMPERF_AUDIOSLAVE 0x00000040 #define DXMPERF_AUDIOBREAK 0x00000080 #define PERFLOG_CTOR(name, iface) #define PERFLOG_DTOR(name, iface) #define PERFLOG_DELIVER(name, source, dest, sample, pmt) #define PERFLOG_RECEIVE(name, source, dest, sample, pmt) #define PERFLOG_RUN(name, iface, time, oldstate) #define PERFLOG_PAUSE(name, iface, oldstate) #define PERFLOG_STOP(name, iface, oldstate) #define PERFLOG_JOINGRAPH(name, iface, graph) #define PERFLOG_GETBUFFER(allocator, sample) #define PERFLOG_RELBUFFER(allocator, sample) #define PERFLOG_CONNECT(connector, connectee, status, pmt) #define PERFLOG_RXCONNECT(connector, connectee, status, pmt) #define PERFLOG_DISCONNECT(disconnector, disconnectee, status) #define PERFLOG_GETTIME(clock, time) /*{ \ PERFINFO_WMI_GETTIME perfData; \ if (NULL != g_pTraceEvent) { \ memset( &perfData, 0, sizeof( perfData ) ); \ perfData.header.Size = sizeof( perfData ); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_GETTIME; \ perfData.data.cycleCounter = _RDTSC(); \ perfData.data.dshowClock = (ULONGLONG) (time); \ if (g_perfMasks[GETTIME_INDEX] & GETTIME_BIT) \ (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ } \ }*/ #define PERFLOG_AUDIOREND(clocktime, sampletime, psample, bytetime, cbytes) /*{ \ PERFINFO_WMI_AVREND perfData; \ if (NULL != g_pTraceEvent) { \ memset( &perfData, 0, sizeof( perfData ) ); \ perfData.header.Size = sizeof( perfData ); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_AUDIOREND; \ perfData.data.cycleCounter = _RDTSC(); \ perfData.data.dshowClock = (clocktime); \ perfData.data.sampleTime = (sampletime); \ if (g_perfMasks[AUDIOREND_INDEX] & AUDIOREND_BIT) \ (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ } \ }*/ #define PERFLOG_AUDIORECV(StreamTime, SampleStart, SampleStop, Discontinuity, Duration) \ if (PerflogEnableFlags & DXMPERF_AUDIORECV) \ { \ PERFINFO_WMI_AUDIORECV perfData; \ memset(&perfData, 0, sizeof(perfData)); \ perfData.header.Size = sizeof(perfData); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_AUDIORECV; \ perfData.data.streamTime = StreamTime; \ perfData.data.sampleStart = SampleStart; \ perfData.data.sampleStop = SampleStop; \ perfData.data.discontinuity = Discontinuity; \ perfData.data.hwduration = Duration; \ PerflogTraceEvent((PEVENT_TRACE_HEADER)&perfData); \ } #define PERFLOG_AUDIOSLAVE(MasterClock, SlaveClock, ErrorAccum, LastHighErrorSeen, LastLowErrorSeen) \ if (PerflogEnableFlags & DXMPERF_AUDIOSLAVE) \ { \ PERFINFO_WMI_AUDIOSLAVE perfData; \ memset(&perfData, 0, sizeof(perfData)); \ perfData.header.Size = sizeof(perfData); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_AUDIOSLAVE; \ perfData.data.masterClock = MasterClock; \ perfData.data.slaveClock = SlaveClock; \ perfData.data.errorAccum = ErrorAccum; \ perfData.data.lastHighErrorSeen = LastHighErrorSeen; \ perfData.data.lastLowErrorSeen = LastLowErrorSeen; \ PerflogTraceEvent((PEVENT_TRACE_HEADER)&perfData); \ } #define PERFLOG_AUDIOADDBREAK(IterNextWrite, OffsetNextWrite, IterWrite, OffsetWrite) \ if (PerflogEnableFlags & DXMPERF_AUDIOBREAK) \ { \ PERFINFO_WMI_AUDIOADDBREAK perfData; \ memset(&perfData, 0, sizeof(perfData)); \ perfData.header.Size = sizeof(perfData); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_AUDIOADDBREAK; \ perfData.data.iterNextWrite = IterNextWrite; \ perfData.data.offsetNextWrite = OffsetNextWrite; \ perfData.data.iterWrite = IterWrite; \ perfData.data.offsetWrite = OffsetWrite; \ PerflogTraceEvent((PEVENT_TRACE_HEADER)&perfData); \ } #define PERFLOG_VIDEOREND(sampletime, clocktime, psample) \ if (PerflogEnableFlags & DXMPERF_VIDEOREND) \ { \ PERFINFO_WMI_AVREND perfData; \ memset(&perfData, 0, sizeof(perfData)); \ perfData.header.Size = sizeof(perfData); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_VIDEOREND; \ perfData.data.cycleCounter = _RDTSC(); \ perfData.data.dshowClock = (clocktime); \ perfData.data.sampleTime = (sampletime); \ PerflogTraceEvent((PEVENT_TRACE_HEADER)&perfData); \ } #define PERFLOG_AUDIOGLITCH(instance, glitchtype, currenttime, previoustime) \ if (PerflogEnableFlags & DXMPERF_AUDIOGLITCH) \ { \ PERFINFO_WMI_AUDIOGLITCH perfData; \ memset(&perfData, 0, sizeof(perfData)); \ perfData.header.Size = sizeof(perfData); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_DSOUNDGLITCH; \ perfData.data.cycleCounter = _RDTSC(); \ perfData.data.glitchType = (glitchtype); \ perfData.data.sampleTime = (currenttime); \ perfData.data.previousTime = (previoustime); \ perfData.data.instanceId = (instance); \ PerflogTraceEvent((PEVENT_TRACE_HEADER)&perfData); \ } #define PERFLOG_FRAMEDROP(sampletime, clocktime, psample, renderer) /*{ \ PERFINFO_WMI_FRAMEDROP perfData; \ if (NULL != g_pTraceEvent) { \ memset( &perfData, 0, sizeof( perfData ) ); \ perfData.header.Size = sizeof( perfData ); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_FRAMEDROP; \ perfData.data.cycleCounter = _RDTSC(); \ perfData.data.dshowClock = (clocktime); \ perfData.data.frameTime = (sampletime); \ if (g_perfMasks[FRAMEDROP_INDEX] & FRAMEDROP_BIT) \ (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ } \ }*/ /* #define PERFLOG_AUDIOBREAK( nextwrite, writepos, msecs ) { \ PERFINFO_WMI_AUDIOBREAK perfData; \ if (NULL != g_pTraceEvent) { \ memset( &perfData, 0, sizeof( perfData ) ); \ perfData.header.Size = sizeof( perfData ); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_AUDIOBREAK; \ perfData.data.cycleCounter = _RDTSC(); \ perfData.data.dshowClock = (writepos); \ perfData.data.sampleTime = (nextwrite); \ perfData.data.sampleDuration = (msecs); \ if (g_perfMasks[AUDIOBREAK_INDEX] & AUDIOBREAK_BIT) \ (*g_pTraceEvent)( g_traceHandle, (PEVENT_TRACE_HEADER) &perfData ); \ } \ } */ #define PERFLOG_AUDIOBREAK(nextwrite, writepos, msecs) \ if (PerflogEnableFlags & AUDIOBREAK_BIT) \ { \ PERFINFO_WMI_AUDIOBREAK perfData; \ memset(&perfData, 0, sizeof(perfData)); \ perfData.header.Size = sizeof(perfData); \ perfData.header.Flags = WNODE_FLAG_TRACED_GUID; \ perfData.header.Guid = GUID_AUDIOBREAK; \ perfData.data.cycleCounter = _RDTSC(); \ perfData.data.dshowClock = (writepos); \ perfData.data.sampleTime = (nextwrite); \ perfData.data.sampleDuration = (msecs); \ PerflogTraceEvent((PEVENT_TRACE_HEADER)&perfData); \ } inline VOID PERFLOG_STREAMTRACE(ULONG Level, ULONG Id, ULONGLONG DShowClock, ULONGLONG Data1, ULONGLONG Data2, ULONGLONG Data3, ULONGLONG Data4) { if (Level <= PerflogModuleLevel) { PERFINFO_WMI_STREAMTRACE perfData; memset(&perfData, 0, sizeof(perfData)); perfData.header.Size = sizeof(perfData); perfData.header.Flags = WNODE_FLAG_TRACED_GUID; perfData.header.Guid = GUID_STREAMTRACE; perfData.data.dshowClock = DShowClock; perfData.data.id = Id; perfData.data.data[0] = Data1; perfData.data.data[1] = Data2; perfData.data.data[2] = Data3; perfData.data.data[3] = Data4; PerflogTraceEvent((PEVENT_TRACE_HEADER)&perfData); } } #endif // _DXMPERF_H_ ================================================ FILE: common/baseclasses/fourcc.h ================================================ //------------------------------------------------------------------------------ // File: FourCC.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // FOURCCMap // // provides a mapping between old-style multimedia format DWORDs // and new-style GUIDs. // // A range of 4 billion GUIDs has been allocated to ensure that this // mapping can be done straightforwardly one-to-one in both directions. // // January 95 #ifndef __FOURCC__ #define __FOURCC__ // Multimedia format types are marked with DWORDs built from four 8-bit // chars and known as FOURCCs. New multimedia AM_MEDIA_TYPE definitions include // a subtype GUID. In order to simplify the mapping, GUIDs in the range: // XXXXXXXX-0000-0010-8000-00AA00389B71 // are reserved for FOURCCs. class FOURCCMap : public GUID { public: FOURCCMap(); FOURCCMap(DWORD Fourcc); FOURCCMap(const GUID *); DWORD GetFOURCC(void); void SetFOURCC(DWORD fourcc); void SetFOURCC(const GUID *); private: void InitGUID(); }; #define GUID_Data2 0 #define GUID_Data3 0x10 #define GUID_Data4_1 0xaa000080 #define GUID_Data4_2 0x719b3800 inline void FOURCCMap::InitGUID() { Data2 = GUID_Data2; Data3 = GUID_Data3; ((DWORD *)Data4)[0] = GUID_Data4_1; ((DWORD *)Data4)[1] = GUID_Data4_2; } inline FOURCCMap::FOURCCMap() { InitGUID(); SetFOURCC(DWORD(0)); } inline FOURCCMap::FOURCCMap(DWORD fourcc) { InitGUID(); SetFOURCC(fourcc); } inline FOURCCMap::FOURCCMap(const GUID *pGuid) { InitGUID(); SetFOURCC(pGuid); } inline void FOURCCMap::SetFOURCC(const GUID *pGuid) { FOURCCMap *p = (FOURCCMap *)pGuid; SetFOURCC(p->GetFOURCC()); } inline void FOURCCMap::SetFOURCC(DWORD fourcc) { Data1 = fourcc; } inline DWORD FOURCCMap::GetFOURCC(void) { return Data1; } #endif /* __FOURCC__ */ ================================================ FILE: common/baseclasses/measure.h ================================================ //------------------------------------------------------------------------------ // File: Measure.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ /* The idea is to pepper the source code with interesting measurements and have the last few thousand of these recorded in a circular buffer that can be post-processed to give interesting numbers. WHAT THE LOG LOOKS LIKE: Time (sec) Type Delta Incident_Name 0.055,41 NOTE -. Incident Nine - Another note 0.055,42 NOTE 0.000,01 Incident Nine - Another note 0.055,44 NOTE 0.000,02 Incident Nine - Another note 0.055,45 STOP -. Incident Eight - Also random 0.055,47 START -. Incident Seven - Random 0.055,49 NOTE 0.000,05 Incident Nine - Another note ------- ---------------- 0.125,60 STOP 0.000,03 Msr_Stop 0.125,62 START -. Msr_Start 0.125,63 START -. Incident Two - Start/Stop 0.125,65 STOP 0.000,03 Msr_Start 0.125,66 START -. Msr_Stop 0.125,68 STOP 0.000,05 Incident Two - Start/Stop 0.125,70 STOP 0.000,04 Msr_Stop 0.125,72 START -. Msr_Start 0.125,73 START -. Incident Two - Start/Stop 0.125,75 STOP 0.000,03 Msr_Start 0.125,77 START -. Msr_Stop 0.125,78 STOP 0.000,05 Incident Two - Start/Stop 0.125,80 STOP 0.000,03 Msr_Stop 0.125,81 NOTE -. Incident Three - single Note 0.125,83 START -. Incident Four - Start, no stop 0.125,85 START -. Incident Five - Single Start/Stop 0.125,87 STOP 0.000,02 Incident Five - Single Start/Stop Number Average StdDev Smallest Largest Incident_Name 10 0.000,58 0.000,10 0.000,55 0.000,85 Incident One - Note 50 0.000,05 0.000,00 0.000,05 0.000,05 Incident Two - Start/Stop 1 -. -. -. -. Incident Three - single Note 0 -. -. -. -. Incident Four - Start, no stop 1 0.000,02 -. 0.000,02 0.000,02 Incident Five - Single Start/Stop 0 -. -. -. -. Incident Six - zero occurrences 100 0.000,25 0.000,12 0.000,02 0.000,62 Incident Seven - Random 100 0.000,79 0.000,48 0.000,02 0.001,92 Incident Eight - Also random 5895 0.000,01 0.000,01 0.000,01 0.000,56 Incident Nine - Another note 10 0.000,03 0.000,00 0.000,03 0.000,04 Msr_Note 50 0.000,03 0.000,00 0.000,03 0.000,04 Msr_Start 50 0.000,04 0.000,03 0.000,03 0.000,31 Msr_Stop WHAT IT MEANS: The log shows what happened and when. Each line shows the time at which something happened (see WHAT YOU CODE below) what it was that happened and (if approporate) the time since the corresponding previous event (that's the delta column). The statistics show how many times each event occurred, what the average delta time was, also the standard deviation, largest and smalles delta. WHAT YOU CODE: Before anything else executes: - register your ids int id1 = Msr_Register("Incident One - Note"); int id2 = Msr_Register("Incident Two - Start/Stop"); int id3 = Msr_Register("Incident Three - single Note"); etc. At interesting moments: // To measure a repetitive event - e.g. end of bitblt to screen Msr_Note(Id9); // e.g. "video frame hiting the screen NOW!" or // To measure an elapsed time e.g. time taken to decode an MPEG B-frame Msr_Start(Id2); // e.g. "Starting to decode MPEG B-frame" . . . MsrStop(Id2); // "Finished MPEG decode" At the end: HANDLE hFile; hFile = CreateFile("Perf.log", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); Msr_Dump(hFile); // This writes the log out to the file CloseHandle(hFile); or Msr_Dump(NULL); // This writes it to DbgLog((LOG_TRACE,0, ... )); // but if you are writing it out to the debugger // then the times are probably all garbage because // the debugger can make things run awfully slow. A given id should be used either for start / stop or Note calls. If Notes are mixed in with Starts and Stops their statistics will be gibberish. If you code the calls in upper case i.e. MSR_START(idMunge); then you get macros which will turn into nothing unless PERF is defined. You can reset the statistical counts for a given id by calling Reset(Id). They are reset by default at the start. It logs Reset as a special incident, so you can see it in the log. The log is a circular buffer in storage (to try to minimise disk I/O). It overwrites the oldest entries once full. The statistics include ALL incidents since the last Reset, whether still visible in the log or not. */ #ifndef __MEASURE__ #define __MEASURE__ #ifdef PERF #define MSR_INIT() Msr_Init() #define MSR_TERMINATE() Msr_Terminate() #define MSR_REGISTER(a) Msr_Register(a) #define MSR_RESET(a) Msr_Reset(a) #define MSR_CONTROL(a) Msr_Control(a) #define MSR_START(a) Msr_Start(a) #define MSR_STOP(a) Msr_Stop(a) #define MSR_NOTE(a) Msr_Note(a) #define MSR_INTEGER(a, b) Msr_Integer(a, b) #define MSR_DUMP(a) Msr_Dump(a) #define MSR_DUMPSTATS(a) Msr_DumpStats(a) #else #define MSR_INIT() ((void)0) #define MSR_TERMINATE() ((void)0) #define MSR_REGISTER(a) 0 #define MSR_RESET(a) ((void)0) #define MSR_CONTROL(a) ((void)0) #define MSR_START(a) ((void)0) #define MSR_STOP(a) ((void)0) #define MSR_NOTE(a) ((void)0) #define MSR_INTEGER(a, b) ((void)0) #define MSR_DUMP(a) ((void)0) #define MSR_DUMPSTATS(a) ((void)0) #endif #ifdef __cplusplus extern "C" { #endif // This must be called first - (called by the DllEntry) void WINAPI Msr_Init(void); // Call this last to clean up (or just let it fall off the end - who cares?) void WINAPI Msr_Terminate(void); // Call this to get an Id for an "incident" that you can pass to Start, Stop or Note // everything that's logged is called an "incident". int WINAPI Msr_Register(__in LPTSTR Incident); // Reset the statistical counts for an incident void WINAPI Msr_Reset(int Id); // Reset all the counts for all incidents #define MSR_RESET_ALL 0 #define MSR_PAUSE 1 #define MSR_RUN 2 void WINAPI Msr_Control(int iAction); // log the start of an operation void WINAPI Msr_Start(int Id); // log the end of an operation void WINAPI Msr_Stop(int Id); // log a one-off or repetitive operation void WINAPI Msr_Note(int Id); // log an integer (on which we can see statistics later) void WINAPI Msr_Integer(int Id, int n); // print out all the vaialable log (it may have wrapped) and then the statistics. // When the log wraps you lose log but the statistics are still complete. // hFIle==NULL => use DbgLog // otherwise hFile must have come from CreateFile or OpenFile. void WINAPI Msr_Dump(HANDLE hFile); // just dump the statistics - never mind the log void WINAPI Msr_DumpStats(HANDLE hFile); // Type definitions in case you want to declare a pointer to the dump functions // (makes it a trifle easier to do dynamic linking // i.e. LoadModule, GetProcAddress and call that) // Typedefs so can declare MSR_DUMPPROC *MsrDumpStats; or whatever typedef void WINAPI MSR_DUMPPROC(HANDLE hFile); typedef void WINAPI MSR_CONTROLPROC(int iAction); #ifdef __cplusplus } #endif #endif // __MEASURE__ ================================================ FILE: common/baseclasses/msgthrd.h ================================================ //------------------------------------------------------------------------------ // File: MsgThrd.h // // Desc: DirectShow base classes - provides support for a worker thread // class to which one can asynchronously post messages. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Message class - really just a structure. // class CMsg { public: UINT uMsg; DWORD dwFlags; LPVOID lpParam; CAMEvent *pEvent; CMsg(UINT u, DWORD dw, __inout_opt LPVOID lp, __in_opt CAMEvent *pEvnt) : uMsg(u) , dwFlags(dw) , lpParam(lp) , pEvent(pEvnt) { } CMsg() : uMsg(0) , dwFlags(0L) , lpParam(NULL) , pEvent(NULL) { } }; // This is the actual thread class. It exports all the usual thread control // functions. The created thread is different from a normal WIN32 thread in // that it is prompted to perform particaular tasks by responding to messages // posted to its message queue. // class AM_NOVTABLE CMsgThread { private: static DWORD WINAPI DefaultThreadProc(__inout LPVOID lpParam); DWORD m_ThreadId; HANDLE m_hThread; protected: // if you want to override GetThreadMsg to block on other things // as well as this queue, you need access to this CGenericList m_ThreadQueue; CCritSec m_Lock; HANDLE m_hSem; LONG m_lWaiting; public: CMsgThread() : m_ThreadId(0) , m_hThread(NULL) , m_lWaiting(0) , m_hSem(NULL) , // make a list with a cache of 5 items m_ThreadQueue(NAME("MsgThread list"), 5) { } ~CMsgThread(); // override this if you want to block on other things as well // as the message loop void virtual GetThreadMsg(__out CMsg *msg); // override this if you want to do something on thread startup virtual void OnThreadInit(){}; BOOL CreateThread(); BOOL WaitForThreadExit(__out LPDWORD lpdwExitCode) { if (m_hThread != NULL) { WaitForSingleObject(m_hThread, INFINITE); return GetExitCodeThread(m_hThread, lpdwExitCode); } return FALSE; } DWORD ResumeThread() { return ::ResumeThread(m_hThread); } DWORD SuspendThread() { return ::SuspendThread(m_hThread); } int GetThreadPriority() { return ::GetThreadPriority(m_hThread); } BOOL SetThreadPriority(int nPriority) { return ::SetThreadPriority(m_hThread, nPriority); } HANDLE GetThreadHandle() { return m_hThread; } DWORD GetThreadId() { return m_ThreadId; } void PutThreadMsg(UINT uMsg, DWORD dwMsgFlags, __in_opt LPVOID lpMsgParam, __in_opt CAMEvent *pEvent = NULL) { CAutoLock lck(&m_Lock); CMsg *pMsg = new CMsg(uMsg, dwMsgFlags, lpMsgParam, pEvent); m_ThreadQueue.AddTail(pMsg); if (m_lWaiting != 0) { ReleaseSemaphore(m_hSem, m_lWaiting, 0); m_lWaiting = 0; } } // This is the function prototype of the function that the client // supplies. It is always called on the created thread, never on // the creator thread. // virtual LRESULT ThreadMessageProc(UINT uMsg, DWORD dwFlags, __inout_opt LPVOID lpParam, __in_opt CAMEvent *pEvent) = 0; }; ================================================ FILE: common/baseclasses/mtype.cpp ================================================ //------------------------------------------------------------------------------ // File: MType.cpp // // Desc: DirectShow base classes - implements a class that holds and // manages media type information. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // helper class that derived pin objects can use to compare media // types etc. Has same data members as the struct AM_MEDIA_TYPE defined // in the streams IDL file, but also has (non-virtual) functions #include #include CMediaType::~CMediaType() { FreeMediaType(*this); } CMediaType::CMediaType() { InitMediaType(); } CMediaType::CMediaType(const GUID *type) { InitMediaType(); majortype = *type; } // copy constructor does a deep copy of the format block CMediaType::CMediaType(const AM_MEDIA_TYPE &rt, __out_opt HRESULT *phr) { HRESULT hr = CopyMediaType(this, &rt); if (FAILED(hr) && (NULL != phr)) { *phr = hr; } } CMediaType::CMediaType(const CMediaType &rt, __out_opt HRESULT *phr) { HRESULT hr = CopyMediaType(this, &rt); if (FAILED(hr) && (NULL != phr)) { *phr = hr; } } // this class inherits publicly from AM_MEDIA_TYPE so the compiler could generate // the following assignment operator itself, however it could introduce some // memory conflicts and leaks in the process because the structure contains // a dynamically allocated block (pbFormat) which it will not copy correctly CMediaType &CMediaType::operator=(const AM_MEDIA_TYPE &rt) { Set(rt); return *this; } CMediaType &CMediaType::operator=(const CMediaType &rt) { *this = (AM_MEDIA_TYPE &)rt; return *this; } BOOL CMediaType::operator==(const CMediaType &rt) const { // I don't believe we need to check sample size or // temporal compression flags, since I think these must // be represented in the type, subtype and format somehow. They // are pulled out as separate flags so that people who don't understand // the particular format representation can still see them, but // they should duplicate information in the format block. return ( (IsEqualGUID(majortype, rt.majortype) == TRUE) && (IsEqualGUID(subtype, rt.subtype) == TRUE) && (IsEqualGUID(formattype, rt.formattype) == TRUE) && (cbFormat == rt.cbFormat) && ((cbFormat == 0) || pbFormat != NULL && rt.pbFormat != NULL && (memcmp(pbFormat, rt.pbFormat, cbFormat) == 0))); } BOOL CMediaType::operator!=(const CMediaType &rt) const { /* Check to see if they are equal */ if (*this == rt) { return FALSE; } return TRUE; } HRESULT CMediaType::Set(const CMediaType &rt) { return Set((AM_MEDIA_TYPE &)rt); } HRESULT CMediaType::Set(const AM_MEDIA_TYPE &rt) { if (&rt != this) { FreeMediaType(*this); HRESULT hr = CopyMediaType(this, &rt); if (FAILED(hr)) { return E_OUTOFMEMORY; } } return S_OK; } BOOL CMediaType::IsValid() const { return (!IsEqualGUID(majortype, GUID_NULL)); } void CMediaType::SetType(const GUID *ptype) { majortype = *ptype; } void CMediaType::SetSubtype(const GUID *ptype) { subtype = *ptype; } ULONG CMediaType::GetSampleSize() const { if (IsFixedSize()) { return lSampleSize; } else { return 0; } } void CMediaType::SetSampleSize(ULONG sz) { if (sz == 0) { SetVariableSize(); } else { bFixedSizeSamples = TRUE; lSampleSize = sz; } } void CMediaType::SetVariableSize() { bFixedSizeSamples = FALSE; } void CMediaType::SetTemporalCompression(BOOL bCompressed) { bTemporalCompression = bCompressed; } BOOL CMediaType::SetFormat(__in_bcount(cb) BYTE *pformat, ULONG cb) { if (NULL == AllocFormatBuffer(cb)) return (FALSE); ASSERT(pbFormat); memcpy(pbFormat, pformat, cb); return (TRUE); } // set the type of the media type format block, this type defines what you // will actually find in the format pointer. For example FORMAT_VideoInfo or // FORMAT_WaveFormatEx. In the future this may be an interface pointer to a // property set. Before sending out media types this should be filled in. void CMediaType::SetFormatType(const GUID *pformattype) { formattype = *pformattype; } // reset the format buffer void CMediaType::ResetFormatBuffer() { if (cbFormat) { CoTaskMemFree((PVOID)pbFormat); } cbFormat = 0; pbFormat = NULL; } // allocate length bytes for the format and return a read/write pointer // If we cannot allocate the new block of memory we return NULL leaving // the original block of memory untouched (as does ReallocFormatBuffer) BYTE *CMediaType::AllocFormatBuffer(ULONG length) { ASSERT(length); // do the types have the same buffer size if (cbFormat == length) { return pbFormat; } // allocate the new format buffer BYTE *pNewFormat = (PBYTE)CoTaskMemAlloc(length); if (pNewFormat == NULL) { if (length <= cbFormat) return pbFormat; // reuse the old block anyway. return NULL; } // delete the old format if (cbFormat != 0) { ASSERT(pbFormat); CoTaskMemFree((PVOID)pbFormat); } cbFormat = length; pbFormat = pNewFormat; return pbFormat; } // reallocate length bytes for the format and return a read/write pointer // to it. We keep as much information as we can given the new buffer size // if this fails the original format buffer is left untouched. The caller // is responsible for ensuring the size of memory required is non zero BYTE *CMediaType::ReallocFormatBuffer(ULONG length) { ASSERT(length); // do the types have the same buffer size if (cbFormat == length) { return pbFormat; } // allocate the new format buffer BYTE *pNewFormat = (PBYTE)CoTaskMemAlloc(length); if (pNewFormat == NULL) { if (length <= cbFormat) return pbFormat; // reuse the old block anyway. return NULL; } // copy any previous format (or part of if new is smaller) // delete the old format and replace with the new one if (cbFormat != 0) { ASSERT(pbFormat); memcpy(pNewFormat, pbFormat, min(length, cbFormat)); CoTaskMemFree((PVOID)pbFormat); } cbFormat = length; pbFormat = pNewFormat; return pNewFormat; } // initialise a media type structure void CMediaType::InitMediaType() { ZeroMemory((PVOID)this, sizeof(*this)); lSampleSize = 1; bFixedSizeSamples = TRUE; } // a partially specified media type can be passed to IPin::Connect // as a constraint on the media type used in the connection. // the type, subtype or format type can be null. BOOL CMediaType::IsPartiallySpecified(void) const { if ((majortype == GUID_NULL) || (formattype == GUID_NULL)) { return TRUE; } else { return FALSE; } } BOOL CMediaType::MatchesPartial(const CMediaType *ppartial) const { if ((ppartial->majortype != GUID_NULL) && (majortype != ppartial->majortype)) { return FALSE; } if ((ppartial->subtype != GUID_NULL) && (subtype != ppartial->subtype)) { return FALSE; } if (ppartial->formattype != GUID_NULL) { // if the format block is specified then it must match exactly if (formattype != ppartial->formattype) { return FALSE; } if (cbFormat != ppartial->cbFormat) { return FALSE; } if ((cbFormat != 0) && (memcmp(pbFormat, ppartial->pbFormat, cbFormat) != 0)) { return FALSE; } } return TRUE; } // general purpose function to delete a heap allocated AM_MEDIA_TYPE structure // which is useful when calling IEnumMediaTypes::Next as the interface // implementation allocates the structures which you must later delete // the format block may also be a pointer to an interface to release void WINAPI DeleteMediaType(__inout_opt AM_MEDIA_TYPE *pmt) { // allow NULL pointers for coding simplicity if (pmt == NULL) { return; } FreeMediaType(*pmt); CoTaskMemFree((PVOID)pmt); } // this also comes in useful when using the IEnumMediaTypes interface so // that you can copy a media type, you can do nearly the same by creating // a CMediaType object but as soon as it goes out of scope the destructor // will delete the memory it allocated (this takes a copy of the memory) AM_MEDIA_TYPE *WINAPI CreateMediaType(AM_MEDIA_TYPE const *pSrc) { ASSERT(pSrc); // Allocate a block of memory for the media type AM_MEDIA_TYPE *pMediaType = (AM_MEDIA_TYPE *)CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE)); if (pMediaType == NULL) { return NULL; } // Copy the variable length format block HRESULT hr = CopyMediaType(pMediaType, pSrc); if (FAILED(hr)) { CoTaskMemFree((PVOID)pMediaType); return NULL; } return pMediaType; } // Copy 1 media type to another HRESULT WINAPI CopyMediaType(__out AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource) { // We'll leak if we copy onto one that already exists - there's one // case we can check like that - copying to itself. ASSERT(pmtSource != pmtTarget); *pmtTarget = *pmtSource; if (pmtSource->cbFormat != 0) { ASSERT(pmtSource->pbFormat != NULL); pmtTarget->pbFormat = (PBYTE)CoTaskMemAlloc(pmtSource->cbFormat); if (pmtTarget->pbFormat == NULL) { pmtTarget->cbFormat = 0; return E_OUTOFMEMORY; } else { CopyMemory((PVOID)pmtTarget->pbFormat, (PVOID)pmtSource->pbFormat, pmtTarget->cbFormat); } } if (pmtTarget->pUnk != NULL) { pmtTarget->pUnk->AddRef(); } return S_OK; } // Free an existing media type (ie free resources it holds) void WINAPI FreeMediaType(__inout AM_MEDIA_TYPE &mt) { if (mt.cbFormat != 0) { CoTaskMemFree((PVOID)mt.pbFormat); // Strictly unnecessary but tidier mt.cbFormat = 0; mt.pbFormat = NULL; } if (mt.pUnk != NULL) { mt.pUnk->Release(); mt.pUnk = NULL; } } // Initialize a media type from a WAVEFORMATEX STDAPI CreateAudioMediaType(const WAVEFORMATEX *pwfx, __out AM_MEDIA_TYPE *pmt, BOOL bSetFormat) { pmt->majortype = MEDIATYPE_Audio; if (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { pmt->subtype = ((PWAVEFORMATEXTENSIBLE)pwfx)->SubFormat; } else { pmt->subtype = FOURCCMap(pwfx->wFormatTag); } pmt->formattype = FORMAT_WaveFormatEx; pmt->bFixedSizeSamples = TRUE; pmt->bTemporalCompression = FALSE; pmt->lSampleSize = pwfx->nBlockAlign; pmt->pUnk = NULL; if (bSetFormat) { if (pwfx->wFormatTag == WAVE_FORMAT_PCM) { pmt->cbFormat = sizeof(WAVEFORMATEX); } else { pmt->cbFormat = sizeof(WAVEFORMATEX) + pwfx->cbSize; } pmt->pbFormat = (PBYTE)CoTaskMemAlloc(pmt->cbFormat); if (pmt->pbFormat == NULL) { return E_OUTOFMEMORY; } if (pwfx->wFormatTag == WAVE_FORMAT_PCM) { CopyMemory(pmt->pbFormat, pwfx, sizeof(PCMWAVEFORMAT)); ((WAVEFORMATEX *)pmt->pbFormat)->cbSize = 0; } else { CopyMemory(pmt->pbFormat, pwfx, pmt->cbFormat); } } return S_OK; } // eliminate very many spurious warnings from MS compiler #pragma warning(disable : 4514) ================================================ FILE: common/baseclasses/mtype.h ================================================ //------------------------------------------------------------------------------ // File: MtType.h // // Desc: DirectShow base classes - defines a class that holds and manages // media type information. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __MTYPE__ #define __MTYPE__ /* Helper class that derived pin objects can use to compare media types etc. Has same data members as the struct AM_MEDIA_TYPE defined in the streams IDL file, but also has (non-virtual) functions */ class CMediaType : public _AMMediaType { public: ~CMediaType(); CMediaType(); CMediaType(const GUID *majortype); CMediaType(const AM_MEDIA_TYPE &, __out_opt HRESULT *phr = NULL); CMediaType(const CMediaType &, __out_opt HRESULT *phr = NULL); CMediaType &operator=(const CMediaType &); CMediaType &operator=(const AM_MEDIA_TYPE &); BOOL operator==(const CMediaType &) const; BOOL operator!=(const CMediaType &) const; HRESULT Set(const CMediaType &rt); HRESULT Set(const AM_MEDIA_TYPE &rt); BOOL IsValid() const; const GUID *Type() const { return &majortype; }; void SetType(const GUID *); const GUID *Subtype() const { return &subtype; }; void SetSubtype(const GUID *); BOOL IsFixedSize() const { return bFixedSizeSamples; }; BOOL IsTemporalCompressed() const { return bTemporalCompression; }; ULONG GetSampleSize() const; void SetSampleSize(ULONG sz); void SetVariableSize(); void SetTemporalCompression(BOOL bCompressed); // read/write pointer to format - can't change length without // calling SetFormat, AllocFormatBuffer or ReallocFormatBuffer BYTE *Format() const { return pbFormat; }; ULONG FormatLength() const { return cbFormat; }; void SetFormatType(const GUID *); const GUID *FormatType() const { return &formattype; }; BOOL SetFormat(__in_bcount(length) BYTE *pFormat, ULONG length); void ResetFormatBuffer(); BYTE *AllocFormatBuffer(ULONG length); BYTE *ReallocFormatBuffer(ULONG length); void InitMediaType(); BOOL MatchesPartial(const CMediaType *ppartial) const; BOOL IsPartiallySpecified(void) const; }; /* General purpose functions to copy and delete a task allocated AM_MEDIA_TYPE structure which is useful when using the IEnumMediaFormats interface as the implementation allocates the structures which you must later delete */ void WINAPI DeleteMediaType(__inout_opt AM_MEDIA_TYPE *pmt); AM_MEDIA_TYPE *WINAPI CreateMediaType(AM_MEDIA_TYPE const *pSrc); HRESULT WINAPI CopyMediaType(__out AM_MEDIA_TYPE *pmtTarget, const AM_MEDIA_TYPE *pmtSource); void WINAPI FreeMediaType(__inout AM_MEDIA_TYPE &mt); // Initialize a media type from a WAVEFORMATEX STDAPI CreateAudioMediaType(const WAVEFORMATEX *pwfx, __out AM_MEDIA_TYPE *pmt, BOOL bSetFormat); #endif /* __MTYPE__ */ ================================================ FILE: common/baseclasses/outputq.cpp ================================================ //------------------------------------------------------------------------------ // File: OutputQ.cpp // // Desc: DirectShow base classes - implements COutputQueue class used by an // output pin which may sometimes want to queue output samples on a // separate thread and sometimes call Receive() directly on the input // pin. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include // // COutputQueue Constructor : // // Determines if a thread is to be created and creates resources // // pInputPin - the downstream input pin we're queueing samples to // // phr - changed to a failure code if this function fails // (otherwise unchanges) // // bAuto - Ask pInputPin if it can block in Receive by calling // its ReceiveCanBlock method and create a thread if // it can block, otherwise not. // // bQueue - if bAuto == FALSE then we create a thread if and only // if bQueue == TRUE // // lBatchSize - work in batches of lBatchSize // // bBatchEact - Use exact batch sizes so don't send until the // batch is full or SendAnyway() is called // // lListSize - If we create a thread make the list of samples queued // to the thread have this size cache // // dwPriority - If we create a thread set its priority to this // COutputQueue::COutputQueue(IPin *pInputPin, // Pin to send stuff to __inout HRESULT *phr, // 'Return code' BOOL bAuto, // Ask pin if queue or not BOOL bQueue, // Send through queue LONG lBatchSize, // Batch BOOL bBatchExact, // Batch exactly to BatchSize LONG lListSize, DWORD dwPriority, bool bFlushingOpt // flushing optimization ) : m_lBatchSize(lBatchSize) , m_bBatchExact(bBatchExact && (lBatchSize > 1)) , m_hThread(NULL) , m_hSem(NULL) , m_List(NULL) , m_pPin(pInputPin) , m_ppSamples(NULL) , m_lWaiting(0) , m_evFlushComplete(FALSE, phr) , m_pInputPin(NULL) , m_bSendAnyway(FALSE) , m_nBatched(0) , m_bFlushing(FALSE) , m_bFlushed(TRUE) , m_bFlushingOpt(bFlushingOpt) , m_bTerminate(FALSE) , m_hEventPop(NULL) , m_hr(S_OK) { ASSERT(m_lBatchSize > 0); if (FAILED(*phr)) { return; } // Check the input pin is OK and cache its IMemInputPin interface *phr = pInputPin->QueryInterface(IID_IMemInputPin, (void **)&m_pInputPin); if (FAILED(*phr)) { return; } // See if we should ask the downstream pin if (bAuto) { HRESULT hr = m_pInputPin->ReceiveCanBlock(); if (SUCCEEDED(hr)) { bQueue = hr == S_OK; } } // Create our sample batch m_ppSamples = new PMEDIASAMPLE[m_lBatchSize]; if (m_ppSamples == NULL) { *phr = E_OUTOFMEMORY; return; } // If we're queueing allocate resources if (bQueue) { DbgLog((LOG_TRACE, 2, TEXT("Creating thread for output pin"))); m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL); if (m_hSem == NULL) { DWORD dwError = GetLastError(); *phr = AmHresultFromWin32(dwError); return; } m_List = new CSampleList(NAME("Sample Queue List"), lListSize, FALSE // No lock ); if (m_List == NULL) { *phr = E_OUTOFMEMORY; return; } DWORD dwThreadId; m_hThread = CreateThread(NULL, 0, InitialThreadProc, (LPVOID)this, 0, &dwThreadId); if (m_hThread == NULL) { DWORD dwError = GetLastError(); *phr = AmHresultFromWin32(dwError); return; } SetThreadPriority(m_hThread, dwPriority); } else { DbgLog((LOG_TRACE, 2, TEXT("Calling input pin directly - no thread"))); } } // // COutputQueuee Destructor : // // Free all resources - // // Thread, // Batched samples // COutputQueue::~COutputQueue() { DbgLog((LOG_TRACE, 3, TEXT("COutputQueue::~COutputQueue"))); /* Free our pointer */ if (m_pInputPin != NULL) { m_pInputPin->Release(); } if (m_hThread != NULL) { { CAutoLock lck(this); m_bTerminate = TRUE; m_hr = S_FALSE; NotifyThread(); } DbgWaitForSingleObject(m_hThread); EXECUTE_ASSERT(CloseHandle(m_hThread)); // The thread frees the samples when asked to terminate ASSERT(m_List->GetCount() == 0); delete m_List; } else { FreeSamples(); } if (m_hSem != NULL) { EXECUTE_ASSERT(CloseHandle(m_hSem)); } delete[] m_ppSamples; } // // Call the real thread proc as a member function // DWORD WINAPI COutputQueue::InitialThreadProc(__in LPVOID pv) { HRESULT hrCoInit = CAMThread::CoInitializeHelper(); COutputQueue *pSampleQueue = (COutputQueue *)pv; DWORD dwReturn = pSampleQueue->ThreadProc(); if (hrCoInit == S_OK) { CoUninitialize(); } return dwReturn; } // // Thread sending the samples downstream : // // When there is nothing to do the thread sets m_lWaiting (while // holding the critical section) and then waits for m_hSem to be // set (not holding the critical section) // DWORD COutputQueue::ThreadProc() { while (TRUE) { BOOL bWait = FALSE; IMediaSample *pSample; LONG lNumberToSend; // Local copy NewSegmentPacket *ppacket; // // Get a batch of samples and send it if possible // In any case exit the loop if there is a control action // requested // { CAutoLock lck(this); while (TRUE) { if (m_bTerminate) { FreeSamples(); return 0; } if (m_bFlushing) { FreeSamples(); SetEvent(m_evFlushComplete); } // Get a sample off the list pSample = m_List->RemoveHead(); // inform derived class we took something off the queue if (m_hEventPop) { // DbgLog((LOG_TRACE,3,TEXT("Queue: Delivered SET EVENT"))); SetEvent(m_hEventPop); } if (pSample != NULL && !IsSpecialSample(pSample)) { // If its just a regular sample just add it to the batch // and exit the loop if the batch is full m_ppSamples[m_nBatched++] = pSample; if (m_nBatched == m_lBatchSize) { break; } } else { // If there was nothing in the queue and there's nothing // to send (either because there's nothing or the batch // isn't full) then prepare to wait if (pSample == NULL && (m_bBatchExact || m_nBatched == 0)) { // Tell other thread to set the event when there's // something do to ASSERT(m_lWaiting == 0); m_lWaiting++; bWait = TRUE; } else { // We break out of the loop on SEND_PACKET unless // there's nothing to send if (pSample == SEND_PACKET && m_nBatched == 0) { continue; } if (pSample == NEW_SEGMENT) { // now we need the parameters - we are // guaranteed that the next packet contains them ppacket = (NewSegmentPacket *)m_List->RemoveHead(); // we took something off the queue if (m_hEventPop) { // DbgLog((LOG_TRACE,3,TEXT("Queue: Delivered SET EVENT"))); SetEvent(m_hEventPop); } ASSERT(ppacket); } // EOS_PACKET falls through here and we exit the loop // In this way it acts like SEND_PACKET } break; } } if (!bWait) { // We look at m_nBatched from the client side so keep // it up to date inside the critical section lNumberToSend = m_nBatched; // Local copy m_nBatched = 0; } } // Wait for some more data if (bWait) { DbgWaitForSingleObject(m_hSem); continue; } // OK - send it if there's anything to send // We DON'T check m_bBatchExact here because either we've got // a full batch or we dropped through because we got // SEND_PACKET or EOS_PACKET - both of which imply we should // flush our batch if (lNumberToSend != 0) { long nProcessed; if (m_hr == S_OK) { ASSERT(!m_bFlushed); HRESULT hr = m_pInputPin->ReceiveMultiple(m_ppSamples, lNumberToSend, &nProcessed); /* Don't overwrite a flushing state HRESULT */ CAutoLock lck(this); if (m_hr == S_OK) { m_hr = hr; } ASSERT(!m_bFlushed); } while (lNumberToSend != 0) { m_ppSamples[--lNumberToSend]->Release(); } if (m_hr != S_OK) { // In any case wait for more data - S_OK just // means there wasn't an error DbgLog((LOG_ERROR, 2, TEXT("ReceiveMultiple returned %8.8X"), m_hr)); } } // Check for end of stream if (pSample == EOS_PACKET) { // We don't send even end of stream on if we've previously // returned something other than S_OK // This is because in that case the pin which returned // something other than S_OK should have either sent // EndOfStream() or notified the filter graph if (m_hr == S_OK) { DbgLog((LOG_TRACE, 2, TEXT("COutputQueue sending EndOfStream()"))); HRESULT hr = m_pPin->EndOfStream(); if (FAILED(hr)) { DbgLog((LOG_ERROR, 2, TEXT("COutputQueue got code 0x%8.8X from EndOfStream()"))); } } } // Data from a new source if (pSample == RESET_PACKET) { m_hr = S_OK; SetEvent(m_evFlushComplete); } if (pSample == NEW_SEGMENT) { m_pPin->NewSegment(ppacket->tStart, ppacket->tStop, ppacket->dRate); delete ppacket; } } } // Send batched stuff anyway void COutputQueue::SendAnyway() { if (!IsQueued()) { // m_bSendAnyway is a private parameter checked in ReceiveMultiple m_bSendAnyway = TRUE; LONG nProcessed; ReceiveMultiple(NULL, 0, &nProcessed); m_bSendAnyway = FALSE; } else { CAutoLock lck(this); QueueSample(SEND_PACKET); NotifyThread(); } } void COutputQueue::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { if (!IsQueued()) { if (S_OK == m_hr) { if (m_bBatchExact) { SendAnyway(); } m_pPin->NewSegment(tStart, tStop, dRate); } } else { if (m_hr == S_OK) { // // we need to queue the new segment to appear in order in the // data, but we need to pass parameters to it. Rather than // take the hit of wrapping every single sample so we can tell // special ones apart, we queue special pointers to indicate // special packets, and we guarantee (by holding the // critical section) that the packet immediately following a // NEW_SEGMENT value is a NewSegmentPacket containing the // parameters. NewSegmentPacket *ppack = new NewSegmentPacket; if (ppack == NULL) { return; } ppack->tStart = tStart; ppack->tStop = tStop; ppack->dRate = dRate; CAutoLock lck(this); QueueSample(NEW_SEGMENT); QueueSample((IMediaSample *)ppack); NotifyThread(); } } } // // End of Stream is queued to output device // void COutputQueue::EOS() { CAutoLock lck(this); if (!IsQueued()) { if (m_bBatchExact) { SendAnyway(); } if (m_hr == S_OK) { DbgLog((LOG_TRACE, 2, TEXT("COutputQueue sending EndOfStream()"))); m_bFlushed = FALSE; HRESULT hr = m_pPin->EndOfStream(); if (FAILED(hr)) { DbgLog((LOG_ERROR, 2, TEXT("COutputQueue got code 0x%8.8X from EndOfStream()"))); } } } else { if (m_hr == S_OK) { m_bFlushed = FALSE; QueueSample(EOS_PACKET); NotifyThread(); } } } // // Flush all the samples in the queue // void COutputQueue::BeginFlush() { if (IsQueued()) { { CAutoLock lck(this); // block receives -- we assume this is done by the // filter in which we are a component // discard all queued data m_bFlushing = TRUE; // Make sure we discard all samples from now on if (m_hr == S_OK) { m_hr = S_FALSE; } // Optimize so we don't keep calling downstream all the time if (m_bFlushed && m_bFlushingOpt) { return; } // Make sure we really wait for the flush to complete m_evFlushComplete.Reset(); NotifyThread(); } // pass this downstream m_pPin->BeginFlush(); } else { // pass downstream first to avoid deadlocks m_pPin->BeginFlush(); CAutoLock lck(this); // discard all queued data m_bFlushing = TRUE; // Make sure we discard all samples from now on if (m_hr == S_OK) { m_hr = S_FALSE; } } } // // leave flush mode - pass this downstream void COutputQueue::EndFlush() { { CAutoLock lck(this); ASSERT(m_bFlushing); if (m_bFlushingOpt && m_bFlushed && IsQueued()) { m_bFlushing = FALSE; m_hr = S_OK; return; } } // sync with pushing thread -- done in BeginFlush // ensure no more data to go downstream -- done in BeginFlush // // Because we are synching here there is no need to hold the critical // section (in fact we'd deadlock if we did!) if (IsQueued()) { m_evFlushComplete.Wait(); } else { FreeSamples(); } // Be daring - the caller has guaranteed no samples will arrive // before EndFlush() returns m_bFlushing = FALSE; m_bFlushed = TRUE; // call EndFlush on downstream pins m_pPin->EndFlush(); m_hr = S_OK; } // COutputQueue::QueueSample // // private method to Send a sample to the output queue // The critical section MUST be held when this is called void COutputQueue::QueueSample(IMediaSample *pSample) { if (NULL == m_List->AddTail(pSample)) { if (!IsSpecialSample(pSample)) { pSample->Release(); } } } // // COutputQueue::Receive() // // Send a single sample by the multiple sample route // (NOTE - this could be optimized if necessary) // // On return the sample will have been Release()'d // HRESULT COutputQueue::Receive(IMediaSample *pSample) { LONG nProcessed; return ReceiveMultiple(&pSample, 1, &nProcessed); } // // COutputQueue::ReceiveMultiple() // // Send a set of samples to the downstream pin // // ppSamples - array of samples // nSamples - how many // nSamplesProcessed - How many were processed // // On return all samples will have been Release()'d // HRESULT COutputQueue::ReceiveMultiple(__in_ecount(nSamples) IMediaSample **ppSamples, long nSamples, __out long *nSamplesProcessed) { if (nSamples < 0) { return E_INVALIDARG; } CAutoLock lck(this); // Either call directly or queue up the samples if (!IsQueued()) { // If we already had a bad return code then just return if (S_OK != m_hr) { // If we've never received anything since the last Flush() // and the sticky return code is not S_OK we must be // flushing // ((!A || B) is equivalent to A implies B) ASSERT(!m_bFlushed || m_bFlushing); // We're supposed to Release() them anyway! *nSamplesProcessed = 0; for (int i = 0; i < nSamples; i++) { DbgLog( (LOG_TRACE, 3, TEXT("COutputQueue (direct) : Discarding %d samples code 0x%8.8X"), nSamples, m_hr)); ppSamples[i]->Release(); } return m_hr; } // // If we're flushing the sticky return code should be S_FALSE // ASSERT(!m_bFlushing); m_bFlushed = FALSE; ASSERT(m_nBatched < m_lBatchSize); ASSERT(m_nBatched == 0 || m_bBatchExact); // Loop processing the samples in batches LONG iLost = 0; long iDone = 0; for (iDone = 0; iDone < nSamples || (m_nBatched != 0 && m_bSendAnyway);) { // pragma message (REMIND("Implement threshold scheme")) ASSERT(m_nBatched < m_lBatchSize); if (iDone < nSamples) { m_ppSamples[m_nBatched++] = ppSamples[iDone++]; } if (m_nBatched == m_lBatchSize || nSamples == 0 && (m_bSendAnyway || !m_bBatchExact)) { LONG nDone; DbgLog((LOG_TRACE, 4, TEXT("Batching %d samples"), m_nBatched)); if (m_hr == S_OK) { m_hr = m_pInputPin->ReceiveMultiple(m_ppSamples, m_nBatched, &nDone); } else { nDone = 0; } iLost += m_nBatched - nDone; for (LONG i = 0; i < m_nBatched; i++) { m_ppSamples[i]->Release(); } m_nBatched = 0; } } *nSamplesProcessed = iDone - iLost; if (*nSamplesProcessed < 0) { *nSamplesProcessed = 0; } return m_hr; } else { /* We're sending to our thread */ if (m_hr != S_OK) { *nSamplesProcessed = 0; DbgLog((LOG_TRACE, 3, TEXT("COutputQueue (queued) : Discarding %d samples code 0x%8.8X"), nSamples, m_hr)); for (int i = 0; i < nSamples; i++) { ppSamples[i]->Release(); } return m_hr; } m_bFlushed = FALSE; for (long i = 0; i < nSamples; i++) { QueueSample(ppSamples[i]); } *nSamplesProcessed = nSamples; if (!m_bBatchExact || m_nBatched + m_List->GetCount() >= m_lBatchSize) { NotifyThread(); } return S_OK; } } // Get ready for new data - cancels sticky m_hr void COutputQueue::Reset() { if (!IsQueued()) { m_hr = S_OK; } else { { CAutoLock lck(this); QueueSample(RESET_PACKET); NotifyThread(); } m_evFlushComplete.Wait(); } } // Remove and Release() all queued and Batched samples void COutputQueue::FreeSamples() { CAutoLock lck(this); if (IsQueued()) { while (TRUE) { IMediaSample *pSample = m_List->RemoveHead(); // inform derived class we took something off the queue if (m_hEventPop) { // DbgLog((LOG_TRACE,3,TEXT("Queue: Delivered SET EVENT"))); SetEvent(m_hEventPop); } if (pSample == NULL) { break; } if (!IsSpecialSample(pSample)) { pSample->Release(); } else { if (pSample == NEW_SEGMENT) { // Free NEW_SEGMENT packet NewSegmentPacket *ppacket = (NewSegmentPacket *)m_List->RemoveHead(); // inform derived class we took something off the queue if (m_hEventPop) { // DbgLog((LOG_TRACE,3,TEXT("Queue: Delivered SET EVENT"))); SetEvent(m_hEventPop); } ASSERT(ppacket != NULL); delete ppacket; } } } } for (int i = 0; i < m_nBatched; i++) { m_ppSamples[i]->Release(); } m_nBatched = 0; } // Notify the thread if there is something to do // // The critical section MUST be held when this is called void COutputQueue::NotifyThread() { // Optimize - no need to signal if it's not waiting ASSERT(IsQueued()); if (m_lWaiting) { ReleaseSemaphore(m_hSem, m_lWaiting, NULL); m_lWaiting = 0; } } // See if there's any work to do // Returns // TRUE if there is nothing on the queue and nothing in the batch // and all data has been sent // FALSE otherwise // BOOL COutputQueue::IsIdle() { CAutoLock lck(this); // We're idle if // there is no thread (!IsQueued()) OR // the thread is waiting for more work (m_lWaiting != 0) // AND // there's nothing in the current batch (m_nBatched == 0) if (IsQueued() && m_lWaiting == 0 || m_nBatched != 0) { return FALSE; } else { // If we're idle it shouldn't be possible for there // to be anything on the work queue ASSERT(!IsQueued() || m_List->GetCount() == 0); return TRUE; } } void COutputQueue::SetPopEvent(HANDLE hEvent) { m_hEventPop = hEvent; } ================================================ FILE: common/baseclasses/outputq.h ================================================ //------------------------------------------------------------------------------ // File: OutputQ.h // // Desc: DirectShow base classes - defines the COutputQueue class, which // makes a queue of samples and sends them to an output pin. The // class will optionally send the samples to the pin directly. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ typedef CGenericList CSampleList; class COutputQueue : public CCritSec { public: // Constructor COutputQueue(IPin *pInputPin, // Pin to send stuff to __inout HRESULT *phr, // 'Return code' BOOL bAuto = TRUE, // Ask pin if blocks BOOL bQueue = TRUE, // Send through queue (ignored if // bAuto set) LONG lBatchSize = 1, // Batch BOOL bBatchExact = FALSE, // Batch exactly to BatchSize LONG lListSize = // Likely number in the list DEFAULTCACHE, DWORD dwPriority = // Priority of thread to create THREAD_PRIORITY_NORMAL, bool bFlushingOpt = false // flushing optimization ); ~COutputQueue(); // enter flush state - discard all data void BeginFlush(); // Begin flushing samples // re-enable receives (pass this downstream) void EndFlush(); // Complete flush of samples - downstream // pin guaranteed not to block at this stage void EOS(); // Call this on End of stream void SendAnyway(); // Send batched samples anyway (if bBatchExact set) void NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); HRESULT Receive(IMediaSample *pSample); // do something with these media samples HRESULT ReceiveMultiple(__in_ecount(nSamples) IMediaSample **pSamples, long nSamples, __out long *nSamplesProcessed); void Reset(); // Reset m_hr ready for more data // See if its idle or not BOOL IsIdle(); // give the class an event to fire after everything removed from the queue void SetPopEvent(HANDLE hEvent); protected: static DWORD WINAPI InitialThreadProc(__in LPVOID pv); DWORD ThreadProc(); BOOL IsQueued() { return m_List != NULL; }; // The critical section MUST be held when this is called void QueueSample(IMediaSample *pSample); BOOL IsSpecialSample(IMediaSample *pSample) { return (DWORD_PTR)pSample > (DWORD_PTR)(LONG_PTR)(-16); }; // Remove and Release() batched and queued samples void FreeSamples(); // Notify the thread there is something to do void NotifyThread(); protected: // Queue 'messages' #define SEND_PACKET ((IMediaSample *)(LONG_PTR)(-2)) // Send batch #define EOS_PACKET ((IMediaSample *)(LONG_PTR)(-3)) // End of stream #define RESET_PACKET ((IMediaSample *)(LONG_PTR)(-4)) // Reset m_hr #define NEW_SEGMENT ((IMediaSample *)(LONG_PTR)(-5)) // send NewSegment // new segment packet is always followed by one of these struct NewSegmentPacket { REFERENCE_TIME tStart; REFERENCE_TIME tStop; double dRate; }; // Remember input stuff IPin *const m_pPin; IMemInputPin *m_pInputPin; BOOL const m_bBatchExact; LONG const m_lBatchSize; CSampleList *m_List; HANDLE m_hSem; CAMEvent m_evFlushComplete; HANDLE m_hThread; __field_ecount_opt(m_lBatchSize) IMediaSample **m_ppSamples; __range(0, m_lBatchSize) LONG m_nBatched; // Wait optimization LONG m_lWaiting; // Flush synchronization BOOL m_bFlushing; // flushing optimization. some downstream filters have trouble // with the queue's flushing optimization. other rely on it BOOL m_bFlushed; bool m_bFlushingOpt; // Terminate now BOOL m_bTerminate; // Send anyway flag for batching BOOL m_bSendAnyway; // Deferred 'return code' HRESULT volatile m_hr; // an event that can be fired after every deliver HANDLE m_hEventPop; }; ================================================ FILE: common/baseclasses/perflog.cpp ================================================ //------------------------------------------------------------------------------ // File: perflog.cpp // // Desc: Macros for DirectShow performance logging. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #pragma warning(disable : 4201) #include #include #include #include #include #include #include #include "perflog.h" // // Local function prototypes. // ULONG WINAPI PerflogCallback(WMIDPREQUESTCODE RequestCode, __in PVOID Context, __out ULONG *BufferSize, __in PVOID Buffer); // // Event tracing function pointers. // We have to do this to run on down-level platforms. // #ifdef UNICODE ULONG(__stdcall *_RegisterTraceGuids) (__in IN WMIDPREQUEST RequestAddress, __in IN PVOID RequestContext, IN LPCGUID ControlGuid, IN ULONG GuidCount, __in IN PTRACE_GUID_REGISTRATION TraceGuidReg, IN LPCWSTR MofImagePath, IN LPCWSTR MofResourceName, OUT PTRACEHANDLE RegistrationHandle); #define REGISTERTRACEGUIDS_NAME "RegisterTraceGuidsW" #else ULONG(__stdcall *_RegisterTraceGuids) (__in IN WMIDPREQUEST RequestAddress, __in IN PVOID RequestContext, IN LPCGUID ControlGuid, IN ULONG GuidCount, __in IN PTRACE_GUID_REGISTRATION TraceGuidReg, IN LPCSTR MofImagePath, IN LPCSTR MofResourceName, __out OUT PTRACEHANDLE RegistrationHandle); #define REGISTERTRACEGUIDS_NAME "RegisterTraceGuidsA" #endif ULONG(__stdcall *_UnregisterTraceGuids)(TRACEHANDLE RegistrationHandle); TRACEHANDLE(__stdcall *_GetTraceLoggerHandle)(__in PVOID Buffer); UCHAR(__stdcall *_GetTraceEnableLevel)(TRACEHANDLE TraceHandle); ULONG(__stdcall *_GetTraceEnableFlags)(TRACEHANDLE TraceHandle); ULONG(__stdcall *_TraceEvent)(TRACEHANDLE TraceHandle, __in PEVENT_TRACE_HEADER EventTrace); HINSTANCE _Advapi32; // // Global variables. // BOOL EventTracingAvailable = FALSE; ULONG PerflogEnableFlags; UCHAR PerflogEnableLevel; ULONG PerflogModuleLevel = 0; void (*OnStateChanged)(void); TRACEHANDLE PerflogTraceHandle = NULL; TRACEHANDLE PerflogRegHandle; // The Win32 wsprintf() function writes a maximum of 1024 characters to it's output buffer. // See the documentation for wsprintf()'s lpOut parameter for more information. const INT iDEBUGINFO = 1024; // Used to format strings // // This routine initializes performance logging. // It should be called from DllMain(). // VOID PerflogReadModuleLevel(HINSTANCE hInstance) { LONG lReturn; // Create key return value TCHAR szInfo[iDEBUGINFO]; // Constructs key names TCHAR szFullName[iDEBUGINFO]; // Load the full path and module name HKEY hModuleKey; // Module key handle LPTSTR pName; // Searches from the end for a backslash DWORD dwKeySize, dwKeyType, dwKeyValue; DWORD dwSize = GetModuleFileName((hInstance ? hInstance : GetModuleHandle(NULL)), szFullName, iDEBUGINFO); if (0 == dwSize || iDEBUGINFO == dwSize) { return; } pName = _tcsrchr(szFullName, '\\'); if (pName == NULL) { pName = szFullName; } else { pName++; } /* Construct the base key name */ (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("SOFTWARE\\Debug\\%s"), pName); /* Open the key for this module */ lReturn = RegOpenKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key szInfo, // Address of subkey name (DWORD)0, // Reserved value KEY_QUERY_VALUE, // Desired security access &hModuleKey); // Opened handle buffer if (lReturn != ERROR_SUCCESS) { return; } dwKeySize = sizeof(DWORD); lReturn = RegQueryValueEx(hModuleKey, // Handle to an open key TEXT("PERFLOG"), NULL, // Reserved field &dwKeyType, // Returns the field type (LPBYTE)&dwKeyValue, // Returns the field's value &dwKeySize); // Number of bytes transferred if ((lReturn == ERROR_SUCCESS) && (dwKeyType == REG_DWORD)) { PerflogModuleLevel = dwKeyValue; } RegCloseKey(hModuleKey); } BOOL PerflogInitIfEnabled(IN HINSTANCE hInstance, __in IN PPERFLOG_LOGGING_PARAMS LogParams) { PerflogReadModuleLevel(hInstance); if (PerflogModuleLevel) { return PerflogInitialize(LogParams); } else { return FALSE; } } BOOL PerflogInitialize(__in IN PPERFLOG_LOGGING_PARAMS LogParams) { ULONG status; // // If we're running on a recent-enough platform, this will get // pointers to the event tracing routines. // _Advapi32 = GetModuleHandle(_T("ADVAPI32.DLL")); if (_Advapi32 == NULL) { return FALSE; } *((FARPROC *)&_RegisterTraceGuids) = GetProcAddress(_Advapi32, REGISTERTRACEGUIDS_NAME); *((FARPROC *)&_UnregisterTraceGuids) = GetProcAddress(_Advapi32, "UnregisterTraceGuids"); *((FARPROC *)&_GetTraceLoggerHandle) = GetProcAddress(_Advapi32, "GetTraceLoggerHandle"); *((FARPROC *)&_GetTraceEnableLevel) = GetProcAddress(_Advapi32, "GetTraceEnableLevel"); *((FARPROC *)&_GetTraceEnableFlags) = GetProcAddress(_Advapi32, "GetTraceEnableFlags"); *((FARPROC *)&_TraceEvent) = GetProcAddress(_Advapi32, "TraceEvent"); if (_RegisterTraceGuids == NULL || _UnregisterTraceGuids == NULL || _GetTraceEnableLevel == NULL || _GetTraceEnableFlags == NULL || _TraceEvent == NULL) { return FALSE; } EventTracingAvailable = TRUE; OnStateChanged = LogParams->OnStateChanged; // // Register our GUIDs. // status = _RegisterTraceGuids(PerflogCallback, LogParams, &LogParams->ControlGuid, LogParams->NumberOfTraceGuids, LogParams->TraceGuids, NULL, NULL, &PerflogRegHandle); return (status == ERROR_SUCCESS); } // // This routine shuts down performance logging. // VOID PerflogShutdown(VOID) { if (!EventTracingAvailable) { return; } _UnregisterTraceGuids(PerflogRegHandle); PerflogRegHandle = NULL; PerflogTraceHandle = NULL; } // // Event tracing callback routine. // It's called when controllers call event tracing control functions. // ULONG WINAPI PerflogCallback(WMIDPREQUESTCODE RequestCode, __in PVOID Context, __out ULONG *BufferSize, __in PVOID Buffer) { ULONG status; UNREFERENCED_PARAMETER(Context); ASSERT(EventTracingAvailable); status = ERROR_SUCCESS; switch (RequestCode) { case WMI_ENABLE_EVENTS: PerflogTraceHandle = _GetTraceLoggerHandle(Buffer); PerflogEnableFlags = _GetTraceEnableFlags(PerflogTraceHandle); PerflogEnableLevel = _GetTraceEnableLevel(PerflogTraceHandle); break; case WMI_DISABLE_EVENTS: PerflogTraceHandle = NULL; PerflogEnableFlags = 0; PerflogEnableLevel = 0; break; default: status = ERROR_INVALID_PARAMETER; } if (OnStateChanged != NULL) { OnStateChanged(); } *BufferSize = 0; return status; } // // Logging routine. // VOID PerflogTraceEvent(__in PEVENT_TRACE_HEADER Event) { if (!EventTracingAvailable) { return; } _TraceEvent(PerflogTraceHandle, Event); } VOID PerflogTraceEventLevel(ULONG Level, __in PEVENT_TRACE_HEADER Event) { if ((!EventTracingAvailable) || (Level <= PerflogModuleLevel)) { return; } _TraceEvent(PerflogTraceHandle, Event); } ================================================ FILE: common/baseclasses/perflog.h ================================================ //------------------------------------------------------------------------------ // File: perflog.h // // Desc: Performance logging framework. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ typedef struct _PERFLOG_LOGGING_PARAMS { GUID ControlGuid; void (*OnStateChanged)(void); ULONG NumberOfTraceGuids; TRACE_GUID_REGISTRATION TraceGuids[ANYSIZE_ARRAY]; } PERFLOG_LOGGING_PARAMS, *PPERFLOG_LOGGING_PARAMS; BOOL PerflogInitIfEnabled(IN HINSTANCE hInstance, __in PPERFLOG_LOGGING_PARAMS LogParams); BOOL PerflogInitialize(__in PPERFLOG_LOGGING_PARAMS LogParams); VOID PerflogShutdown(VOID); VOID PerflogTraceEvent(__in PEVENT_TRACE_HEADER Event); extern ULONG PerflogEnableFlags; extern UCHAR PerflogEnableLevel; extern ULONG PerflogModuleLevel; extern TRACEHANDLE PerflogTraceHandle; extern TRACEHANDLE PerflogRegHandle; #define PerflogTracingEnabled() (PerflogTraceHandle != 0) #define PerflogEvent(_x_) PerflogTraceEventLevel _x_ VOID PerflogTraceEventLevel(ULONG Level, __in PEVENT_TRACE_HEADER Event); VOID PerflogTraceEvent(__in PEVENT_TRACE_HEADER Event); ================================================ FILE: common/baseclasses/perfstruct.h ================================================ //------------------------------------------------------------------------------ // File: PerfStruct.h // // Desc: Structures for DirectShow performance logging. // // Copyright (c) 2000-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef _PERFSTRUCT_H_ #define _PERFSTRUCT_H_ #include #include // {28CF047A-2437-4b24-B653-B9446A419A69} DEFINE_GUID(GUID_DSHOW_CTL, 0x28cf047a, 0x2437, 0x4b24, 0xb6, 0x53, 0xb9, 0x44, 0x6a, 0x41, 0x9a, 0x69); // {D0DA7AD6-AE80-4de5-AAFC-C126711E7593} DEFINE_GUID(GUID_VIDEOREND, 0xd0da7ad6, 0xae80, 0x4de5, 0xaa, 0xfc, 0xc1, 0x26, 0x71, 0x1e, 0x75, 0x93); // {DC70AC3E-93E5-48db-88AB-E42064EC276A} DEFINE_GUID(GUID_DSOUNDGLITCH, 0xdc70ac3e, 0x93e5, 0x48db, 0x88, 0xab, 0xe4, 0x20, 0x64, 0xec, 0x27, 0x6a); // {3d7e7d93-2fc8-4a07-a719-e0922ff2899} DEFINE_GUID(GUID_STREAMTRACE, 0x3d7e7d93, 0x2fc8, 0x4a07, 0xa7, 0x19, 0xe0, 0x92, 0x2f, 0xf2, 0x89, 0x9e); // AZFIX: the following GUIDs aren't useful right now. // {3C33F7F5-EE54-493c-BA25-1656539C05AC} DEFINE_GUID(GUID_GETTIME, 0x3c33f7f5, 0xee54, 0x493c, 0xba, 0x25, 0x16, 0x56, 0x53, 0x9c, 0x5, 0xac); // {CC44B44D-8169-4952-9E4A-A4E13295E492} DEFINE_GUID(GUID_AUDIOREND, 0xcc44b44d, 0x8169, 0x4952, 0x9e, 0x4a, 0xa4, 0xe1, 0x32, 0x95, 0xe4, 0x92); // {775D19BF-4D8B-4de6-8DC9-66BAC7B310A2} DEFINE_GUID(GUID_FRAMEDROP, 0x775d19bf, 0x4d8b, 0x4de6, 0x8d, 0xc9, 0x66, 0xba, 0xc7, 0xb3, 0x10, 0xa2); // {56D29065-EFBE-42dc-8C29-E325DC9C27D5} DEFINE_GUID(GUID_AUDIOBREAK, 0x56d29065, 0xefbe, 0x42dc, 0x8c, 0x29, 0xe3, 0x25, 0xdc, 0x9c, 0x27, 0xd5); // {E1E6EA87-95A8-497e-BFBA-0295AEBCC707} DEFINE_GUID(GUID_AUDIORECV, 0xe1e6ea87, 0x95a8, 0x497e, 0xbf, 0xba, 0x2, 0x95, 0xae, 0xbc, 0xc7, 0x7); // {10F7768A-B1E7-4242-AD90-A2D44683D9F0} DEFINE_GUID(GUID_AUDIOSLAVE, 0x10f7768a, 0xb1e7, 0x4242, 0xad, 0x90, 0xa2, 0xd4, 0x46, 0x83, 0xd9, 0xf0); // {8983803D-691A-49bc-8FF6-962A39C0198F} DEFINE_GUID(GUID_AUDIOADDBREAK, 0x8983803d, 0x691a, 0x49bc, 0x8f, 0xf6, 0x96, 0x2a, 0x39, 0xc0, 0x19, 0x8f); #define GLITCHTYPE_DSOUNDFIRSTGOOD 0 #define GLITCHTYPE_DSOUNDFIRSTBAD 1 typedef struct PERFINFO_DSHOW_AUDIOGLITCH { ULONGLONG cycleCounter; DWORD glitchType; LONGLONG sampleTime; LONGLONG previousTime; ULONG_PTR instanceId; } PERFINFO_DSHOW_AUDIOGLITCH, *PPERFINFO_DSHOW_AUDIOGLITCH; typedef struct PERFINFO_WMI_AUDIOGLITCH { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_AUDIOGLITCH data; } PERFINFO_WMI_AUDIO_GLITCH, *PPERFINFO_WMI_AUDIOGLITCH; typedef struct PERFINFO_DSHOW_GETTIME { ULONGLONG cycleCounter; ULONGLONG dshowClock; } PERFINFO_DSHOW_GETTIME, *PPERFINFO_DSHOW_GETTIME; typedef struct PERFINFO_WMI_GETTIME { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_GETTIME data; } PERFINFO_WMI_GETTIME, *PPERFINFO_WMI_GETTIME; typedef struct PERFINFO_DSHOW_AVREND { ULONGLONG cycleCounter; ULONGLONG dshowClock; ULONGLONG sampleTime; } PERFINFO_DSHOW_AVREND, *PPERFINFO_DSHOW_AVREND; typedef struct PERFINFO_WMI_AVREND { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_AVREND data; } PERFINFO_WMI_AVREND, *PPERFINFO_WMI_AVREND; typedef struct PERFINFO_DSHOW_AUDIOBREAK { ULONGLONG cycleCounter; ULONGLONG dshowClock; ULONGLONG sampleTime; ULONGLONG sampleDuration; } PERFINFO_DSHOW_AUDIOBREAK, *PPERFINFO_DSHOW_AUDIOBREAK; typedef struct PERFINFO_WMI_AUDIOBREAK { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_AUDIOBREAK data; } PERFINFO_WMI_AUDIOBREAK, *PPERFINFO_WMI_AUDIOBREAK; typedef struct PERFINFO_DSHOW_FRAMEDROP { ULONGLONG cycleCounter; ULONGLONG dshowClock; ULONGLONG frameTime; } PERFINFO_DSHOW_FRAMEDROP, *PPERFINFO_DSHOW_FRAMEDROP; typedef struct PERFINFO_WMI_FRAMEDROP { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_FRAMEDROP data; } PERFINFO_WMI_FRAMEDROP, *PPERFINFO_WMI_FRAMEDROP; #define PERFINFO_STREAMTRACE_MPEG2DEMUX_PTS_TRANSLATION 1 #define PERFINFO_STREAMTRACE_MPEG2DEMUX_SAMPLE_RECEIVED 2 #define PERFINFO_STREAMTRACE_VMR_BEGIN_ADVISE 3 #define PERFINFO_STREAMTRACE_VMR_END_ADVISE 4 #define PERFINFO_STREAMTRACE_VMR_RECEIVE 5 #define PERFINFO_STREAMTRACE_VMR_BEGIN_DEINTERLACE 6 #define PERFINFO_STREAMTRACE_VMR_END_DEINTERLACE 7 #define PERFINFO_STREAMTRACE_VMR_BEGIN_DECODE 8 #define PERFINFO_STREAMTRACE_VMR_END_DECODE 9 #define PERFINFO_STREAMTRACE_VMR_DROPPED_FRAME 10 #define PERFINFO_STREAMTRACE_ENCDEC_DTFILTERINPUT 11 #define PERFINFO_STREAMTRACE_ENCDEC_DTFILTEROUTPUT 12 #define PERFINFO_STREAMTRACE_ENCDEC_ETFILTERINPUT 13 #define PERFINFO_STREAMTRACE_ENCDEC_ETFILTEROUTPUT 14 #define PERFINFO_STREAMTRACE_ENCDEC_XDSCODECINPUT 15 #define PERFINFO_STREAMTRACE_SBE_DVRANALYSISINPUT_RECEIVE 16 #define PERFINFO_STREAMTRACE_SBE_DVRANALYSISINPUT_DELIVER 17 #define PERFINFO_STREAMTRACE_SBE_DVRINPUTPIN_RECEIVE 18 #define PERFINFO_STREAMTRACE_SBE_DVROUTPUTPIN_RECEIVE 19 #define PERFINFO_STREAMTRACE_VMR_RENDER_TIME 20 typedef struct _PERFINFO_DSHOW_STREAMTRACE { ULONG id; ULONG reserved; ULONGLONG dshowClock; ULONGLONG data[4]; } PERFINFO_DSHOW_STREAMTRACE, *PPERFINFO_DSHOW_STREAMTRACE; typedef struct _PERFINFO_WMI_STREAMTRACE { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_STREAMTRACE data; } PERFINFO_WMI_STREAMTRACE, *PPERFINFO_WMI_STREAMTRACE; typedef struct PERFINFO_DSHOW_AUDIORECV { LONGLONG streamTime; LONGLONG sampleStart; LONGLONG sampleStop; LONGLONG hwduration; BOOL discontinuity; } PERFINFO_DSHOW_AUDIORECV, *PPERFINFO_DSHOW_AUDIORECV; typedef struct PERFINFO_WMI_AUDIORECV { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_AUDIORECV data; } PERFINFO_WMI_AUDIORECV, *PPERFINFO_WMI_AUDIORECV; typedef struct PERFINFO_DSHOW_AUDIOSLAVE { LONGLONG masterClock; LONGLONG slaveClock; LONGLONG errorAccum; LONGLONG lastHighErrorSeen; LONGLONG lastLowErrorSeen; } PERFINFO_DSHOW_AUDIOSLAVE, *PPERFINFO_DSHOW_AUDIOSLAVE; typedef struct PERFINFO_WMI_AUDIOSLAVE { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_AUDIOSLAVE data; } PERFINFO_WMI_AUDIOSLAVE, *PPERFINFO_WMI_AUDIOSLAVE; typedef struct PERFINFO_DSHOW_AUDIOADDBREAK { DWORD iterNextWrite; DWORD offsetNextWrite; DWORD iterWrite; DWORD offsetWrite; } PERFINFO_DSHOW_AUDIOADDBREAK, *PPERFINFO_DSHOW_AUDIOADDBREAK; typedef struct PERFINFO_WMI_AUDIOADDBREAK { EVENT_TRACE_HEADER header; PERFINFO_DSHOW_AUDIOADDBREAK data; } PERFINFO_WMI_AUDIOADDBREAK, *PPERFINFO_WMI_AUDIOADDBREAK; #endif // _PREFSTRUCT_H_ ================================================ FILE: common/baseclasses/pstream.cpp ================================================ //------------------------------------------------------------------------------ // File: PStream.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include #ifdef PERF #include #endif // #include "pstream.h" in streams.h // // Constructor // CPersistStream::CPersistStream(IUnknown *punk, __inout HRESULT *phr) : mPS_fDirty(FALSE) { mPS_dwFileVersion = GetSoftwareVersion(); } // // Destructor // CPersistStream::~CPersistStream() { // Nothing to do } #if 0 SAMPLE CODE TO COPY - not active at the moment // // NonDelegatingQueryInterface // // This object supports IPersist & IPersistStream STDMETHODIMP CPersistStream::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_IPersist) { return GetInterface((IPersist *) this, ppv); // ??? } else if (riid == IID_IPersistStream) { return GetInterface((IPersistStream *) this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } #endif // // WriteToStream // // Writes to the stream (default action is to write nothing) HRESULT CPersistStream::WriteToStream(IStream *pStream) { // You can override this to do things like // hr = pStream->Write(MyStructure, sizeof(MyStructure), NULL); return NOERROR; } HRESULT CPersistStream::ReadFromStream(IStream *pStream) { // You can override this to do things like // hr = pStream->Read(MyStructure, sizeof(MyStructure), NULL); return NOERROR; } // // Load // // Load all the data from the given stream STDMETHODIMP CPersistStream::Load(LPSTREAM pStm) { HRESULT hr; // Load the version number then the data mPS_dwFileVersion = ReadInt(pStm, hr); if (FAILED(hr)) { return hr; } return ReadFromStream(pStm); } // Load // // Save // // Save the contents of this Stream. STDMETHODIMP CPersistStream::Save(LPSTREAM pStm, BOOL fClearDirty) { HRESULT hr = WriteInt(pStm, GetSoftwareVersion()); if (FAILED(hr)) { return hr; } hr = WriteToStream(pStm); if (FAILED(hr)) { return hr; } mPS_fDirty = !fClearDirty; return hr; } // Save // WriteInt // // Writes an integer to an IStream as 11 UNICODE characters followed by one space. // You could use this for shorts or unsigneds or anything (up to 32 bits) // where the value isn't actually truncated by squeezing it into 32 bits. // Values such as (unsigned) 0x80000000 would come out as -2147483648 // but would then load as 0x80000000 through ReadInt. Cast as you please. STDAPI WriteInt(IStream *pIStream, int n) { WCHAR Buff[13]; // Allows for trailing null that we don't write (void)StringCchPrintfW(Buff, NUMELMS(Buff), L"%011d ", n); return pIStream->Write(&(Buff[0]), 12 * sizeof(WCHAR), NULL); } // WriteInt // ReadInt // // Reads an integer from an IStream. // Read as 4 bytes. You could use this for shorts or unsigneds or anything // where the value isn't actually truncated by squeezing it into 32 bits // Striped down subset of what sscanf can do (without dragging in the C runtime) STDAPI_(int) ReadInt(IStream *pIStream, __out HRESULT &hr) { int Sign = 1; unsigned int n = 0; // result wil be n*Sign WCHAR wch; hr = pIStream->Read(&wch, sizeof(wch), NULL); if (FAILED(hr)) { return 0; } if (wch == L'-') { Sign = -1; hr = pIStream->Read(&wch, sizeof(wch), NULL); if (FAILED(hr)) { return 0; } } for (;;) { if (wch >= L'0' && wch <= L'9') { n = 10 * n + (int)(wch - L'0'); } else if (wch == L' ' || wch == L'\t' || wch == L'\r' || wch == L'\n' || wch == L'\0') { break; } else { hr = VFW_E_INVALID_FILE_FORMAT; return 0; } hr = pIStream->Read(&wch, sizeof(wch), NULL); if (FAILED(hr)) { return 0; } } if (n == 0x80000000 && Sign == -1) { // This is the negative number that has no positive version! return (int)n; } else return (int)n * Sign; } // ReadInt // The microsoft C/C++ compile generates level 4 warnings to the effect that // a particular inline function (from some base class) was not needed. // This line gets rid of hundreds of such unwanted messages and makes // -W4 compilation feasible: #pragma warning(disable : 4514) ================================================ FILE: common/baseclasses/pstream.h ================================================ //------------------------------------------------------------------------------ // File: PStream.h // // Desc: DirectShow base classes - defines a class for persistent properties // of filters. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __PSTREAM__ #define __PSTREAM__ // Base class for persistent properties of filters // (i.e. filter properties in saved graphs) // The simplest way to use this is: // 1. Arrange for your filter to inherit this class // 2. Implement in your class WriteToStream and ReadFromStream // These will override the "do nothing" functions here. // 3. Change your NonDelegatingQueryInterface to handle IPersistStream // 4. Implement SizeMax to return the number of bytes of data you save. // If you save UNICODE data, don't forget a char is 2 bytes. // 5. Whenever your data changes, call SetDirty() // // At some point you may decide to alter, or extend the format of your data. // At that point you will wish that you had a version number in all the old // saved graphs, so that you can tell, when you read them, whether they // represent the old or new form. To assist you in this, this class // writes and reads a version number. // When it writes, it calls GetSoftwareVersion() to enquire what version // of the software we have at the moment. (In effect this is a version number // of the data layout in the file). It writes this as the first thing in the data. // If you want to change the version, implement (override) GetSoftwareVersion(). // It reads this from the file into mPS_dwFileVersion before calling ReadFromStream, // so in ReadFromStream you can check mPS_dwFileVersion to see if you are reading // an old version file. // Normally you should accept files whose version is no newer than the software // version that's reading them. // CPersistStream // // Implements IPersistStream. // See 'OLE Programmers Reference (Vol 1):Structured Storage Overview' for // more implementation information. class CPersistStream : public IPersistStream { private: // Internal state: protected: DWORD mPS_dwFileVersion; // version number of file (being read) BOOL mPS_fDirty; public: // IPersistStream methods STDMETHODIMP IsDirty() { return (mPS_fDirty ? S_OK : S_FALSE); } // note FALSE means clean STDMETHODIMP Load(LPSTREAM pStm); STDMETHODIMP Save(LPSTREAM pStm, BOOL fClearDirty); STDMETHODIMP GetSizeMax(__out ULARGE_INTEGER *pcbSize) // Allow 24 bytes for version. { pcbSize->QuadPart = 12 * sizeof(WCHAR) + SizeMax(); return NOERROR; } // implementation CPersistStream(IUnknown *punk, __inout HRESULT *phr); ~CPersistStream(); HRESULT SetDirty(BOOL fDirty) { mPS_fDirty = fDirty; return NOERROR; } // override to reveal IPersist & IPersistStream // STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // --- IPersist --- // You must override this to provide your own class id STDMETHODIMP GetClassID(__out CLSID *pClsid) PURE; // overrideable if you want // file version number. Override it if you ever change format virtual DWORD GetSoftwareVersion(void) { return 0; } //========================================================================= // OVERRIDE THESE to read and write your data // OVERRIDE THESE to read and write your data // OVERRIDE THESE to read and write your data virtual int SizeMax() { return 0; } virtual HRESULT WriteToStream(IStream *pStream); virtual HRESULT ReadFromStream(IStream *pStream); //========================================================================= private: }; // --- Useful helpers --- // Writes an int to an IStream as UNICODE. STDAPI WriteInt(IStream *pIStream, int n); // inverse of WriteInt STDAPI_(int) ReadInt(IStream *pIStream, __out HRESULT &hr); #endif // __PSTREAM__ ================================================ FILE: common/baseclasses/pullpin.cpp ================================================ //------------------------------------------------------------------------------ // File: PullPin.cpp // // Desc: DirectShow base classes - implements CPullPin class that pulls data // from IAsyncReader. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include "pullpin.h" #ifdef DXMPERF #include "dxmperf.h" #endif // DXMPERF CPullPin::CPullPin() : m_pReader(NULL) , m_pAlloc(NULL) , m_State(TM_Exit) { #ifdef DXMPERF PERFLOG_CTOR(L"CPullPin", this); #endif // DXMPERF } CPullPin::~CPullPin() { Disconnect(); #ifdef DXMPERF PERFLOG_DTOR(L"CPullPin", this); #endif // DXMPERF } // returns S_OK if successfully connected to an IAsyncReader interface // from this object // Optional allocator should be proposed as a preferred allocator if // necessary HRESULT CPullPin::Connect(IUnknown *pUnk, IMemAllocator *pAlloc, BOOL bSync) { CAutoLock lock(&m_AccessLock); if (m_pReader) { return VFW_E_ALREADY_CONNECTED; } HRESULT hr = pUnk->QueryInterface(IID_IAsyncReader, (void **)&m_pReader); if (FAILED(hr)) { #ifdef DXMPERF { AM_MEDIA_TYPE *pmt = NULL; PERFLOG_CONNECT(this, pUnk, hr, pmt); } #endif // DXMPERF return (hr); } hr = DecideAllocator(pAlloc, NULL); if (FAILED(hr)) { Disconnect(); #ifdef DXMPERF { AM_MEDIA_TYPE *pmt = NULL; PERFLOG_CONNECT(this, pUnk, hr, pmt); } #endif // DXMPERF return hr; } LONGLONG llTotal, llAvail; hr = m_pReader->Length(&llTotal, &llAvail); if (FAILED(hr)) { Disconnect(); #ifdef DXMPERF { AM_MEDIA_TYPE *pmt = NULL; PERFLOG_CONNECT(this, pUnk, hr, pmt); } #endif return hr; } // convert from file position to reference time m_tDuration = llTotal * UNITS; m_tStop = m_tDuration; m_tStart = 0; m_bSync = bSync; #ifdef DXMPERF { AM_MEDIA_TYPE *pmt = NULL; PERFLOG_CONNECT(this, pUnk, S_OK, pmt); } #endif // DXMPERF return S_OK; } // disconnect any connection made in Connect HRESULT CPullPin::Disconnect() { CAutoLock lock(&m_AccessLock); StopThread(); #ifdef DXMPERF PERFLOG_DISCONNECT(this, m_pReader, S_OK); #endif // DXMPERF if (m_pReader) { m_pReader->Release(); m_pReader = NULL; } if (m_pAlloc) { m_pAlloc->Release(); m_pAlloc = NULL; } return S_OK; } // agree an allocator using RequestAllocator - optional // props param specifies your requirements (non-zero fields). // returns an error code if fail to match requirements. // optional IMemAllocator interface is offered as a preferred allocator // but no error occurs if it can't be met. HRESULT CPullPin::DecideAllocator(IMemAllocator *pAlloc, __inout_opt ALLOCATOR_PROPERTIES *pProps) { ALLOCATOR_PROPERTIES *pRequest; ALLOCATOR_PROPERTIES Request; if (pProps == NULL) { Request.cBuffers = 3; Request.cbBuffer = 64 * 1024; Request.cbAlign = 0; Request.cbPrefix = 0; pRequest = &Request; } else { pRequest = pProps; } HRESULT hr = m_pReader->RequestAllocator(pAlloc, pRequest, &m_pAlloc); return hr; } // start pulling data HRESULT CPullPin::Active(void) { ASSERT(!ThreadExists()); return StartThread(); } // stop pulling data HRESULT CPullPin::Inactive(void) { StopThread(); return S_OK; } HRESULT CPullPin::Seek(REFERENCE_TIME tStart, REFERENCE_TIME tStop) { CAutoLock lock(&m_AccessLock); ThreadMsg AtStart = m_State; if (AtStart == TM_Start) { BeginFlush(); PauseThread(); EndFlush(); } m_tStart = tStart; m_tStop = tStop; HRESULT hr = S_OK; if (AtStart == TM_Start) { hr = StartThread(); } return hr; } HRESULT CPullPin::Duration(__out REFERENCE_TIME *ptDuration) { *ptDuration = m_tDuration; return S_OK; } HRESULT CPullPin::StartThread() { CAutoLock lock(&m_AccessLock); if (!m_pAlloc || !m_pReader) { return E_UNEXPECTED; } HRESULT hr; if (!ThreadExists()) { // commit allocator hr = m_pAlloc->Commit(); if (FAILED(hr)) { return hr; } // start thread if (!Create()) { return E_FAIL; } } m_State = TM_Start; hr = (HRESULT)CallWorker(m_State); return hr; } HRESULT CPullPin::PauseThread() { CAutoLock lock(&m_AccessLock); if (!ThreadExists()) { return E_UNEXPECTED; } // need to flush to ensure the thread is not blocked // in WaitForNext HRESULT hr = m_pReader->BeginFlush(); if (FAILED(hr)) { return hr; } m_State = TM_Pause; hr = CallWorker(TM_Pause); m_pReader->EndFlush(); return hr; } HRESULT CPullPin::StopThread() { CAutoLock lock(&m_AccessLock); if (!ThreadExists()) { return S_FALSE; } // need to flush to ensure the thread is not blocked // in WaitForNext HRESULT hr = m_pReader->BeginFlush(); if (FAILED(hr)) { return hr; } m_State = TM_Exit; hr = CallWorker(TM_Exit); m_pReader->EndFlush(); // wait for thread to completely exit Close(); // decommit allocator if (m_pAlloc) { m_pAlloc->Decommit(); } return S_OK; } DWORD CPullPin::ThreadProc(void) { while (1) { DWORD cmd = GetRequest(); switch (cmd) { case TM_Exit: Reply(S_OK); return 0; case TM_Pause: // we are paused already Reply(S_OK); break; case TM_Start: Reply(S_OK); Process(); break; } // at this point, there should be no outstanding requests on the // upstream filter. // We should force begin/endflush to ensure that this is true. // !!!Note that we may currently be inside a BeginFlush/EndFlush pair // on another thread, but the premature EndFlush will do no harm now // that we are idle. m_pReader->BeginFlush(); CleanupCancelled(); m_pReader->EndFlush(); } } HRESULT CPullPin::QueueSample(__inout REFERENCE_TIME &tCurrent, REFERENCE_TIME tAlignStop, BOOL bDiscontinuity) { IMediaSample *pSample; HRESULT hr = m_pAlloc->GetBuffer(&pSample, NULL, NULL, 0); if (FAILED(hr)) { return hr; } LONGLONG tStopThis = tCurrent + (pSample->GetSize() * UNITS); if (tStopThis > tAlignStop) { tStopThis = tAlignStop; } pSample->SetTime(&tCurrent, &tStopThis); tCurrent = tStopThis; pSample->SetDiscontinuity(bDiscontinuity); hr = m_pReader->Request(pSample, 0); if (FAILED(hr)) { pSample->Release(); CleanupCancelled(); OnError(hr); } return hr; } HRESULT CPullPin::CollectAndDeliver(REFERENCE_TIME tStart, REFERENCE_TIME tStop) { IMediaSample *pSample = NULL; // better be sure pSample is set DWORD_PTR dwUnused; HRESULT hr = m_pReader->WaitForNext(INFINITE, &pSample, &dwUnused); if (FAILED(hr)) { if (pSample) { pSample->Release(); } } else { hr = DeliverSample(pSample, tStart, tStop); } if (FAILED(hr)) { CleanupCancelled(); OnError(hr); } return hr; } HRESULT CPullPin::DeliverSample(IMediaSample *pSample, REFERENCE_TIME tStart, REFERENCE_TIME tStop) { // fix up sample if past actual stop (for sector alignment) REFERENCE_TIME t1, t2; if (S_OK == pSample->GetTime(&t1, &t2)) { if (t2 > tStop) { t2 = tStop; } // adjust times to be relative to (aligned) start time t1 -= tStart; t2 -= tStart; HRESULT hr = pSample->SetTime(&t1, &t2); if (FAILED(hr)) { return hr; } } #ifdef DXMPERF { AM_MEDIA_TYPE *pmt = NULL; pSample->GetMediaType(&pmt); PERFLOG_RECEIVE(L"CPullPin", m_pReader, this, pSample, pmt); } #endif HRESULT hr = Receive(pSample); pSample->Release(); return hr; } void CPullPin::Process(void) { // is there anything to do? if (m_tStop <= m_tStart) { EndOfStream(); return; } BOOL bDiscontinuity = TRUE; // if there is more than one sample at the allocator, // then try to queue 2 at once in order to overlap. // -- get buffer count and required alignment ALLOCATOR_PROPERTIES Actual; HRESULT hr = m_pAlloc->GetProperties(&Actual); // align the start position downwards REFERENCE_TIME tStart = AlignDown(m_tStart / UNITS, Actual.cbAlign) * UNITS; REFERENCE_TIME tCurrent = tStart; REFERENCE_TIME tStop = m_tStop; if (tStop > m_tDuration) { tStop = m_tDuration; } // align the stop position - may be past stop, but that // doesn't matter REFERENCE_TIME tAlignStop = AlignUp(tStop / UNITS, Actual.cbAlign) * UNITS; DWORD dwRequest; if (!m_bSync) { // Break out of the loop either if we get to the end or we're asked // to do something else while (tCurrent < tAlignStop) { // Break out without calling EndOfStream if we're asked to // do something different if (CheckRequest(&dwRequest)) { return; } // queue a first sample if (Actual.cBuffers > 1) { hr = QueueSample(tCurrent, tAlignStop, TRUE); bDiscontinuity = FALSE; if (FAILED(hr)) { return; } } // loop queueing second and waiting for first.. while (tCurrent < tAlignStop) { hr = QueueSample(tCurrent, tAlignStop, bDiscontinuity); bDiscontinuity = FALSE; if (FAILED(hr)) { return; } hr = CollectAndDeliver(tStart, tStop); if (S_OK != hr) { // stop if error, or if downstream filter said // to stop. return; } } if (Actual.cBuffers > 1) { hr = CollectAndDeliver(tStart, tStop); if (FAILED(hr)) { return; } } } } else { // sync version of above loop while (tCurrent < tAlignStop) { // Break out without calling EndOfStream if we're asked to // do something different if (CheckRequest(&dwRequest)) { return; } IMediaSample *pSample; hr = m_pAlloc->GetBuffer(&pSample, NULL, NULL, 0); if (FAILED(hr)) { OnError(hr); return; } LONGLONG tStopThis = tCurrent + (pSample->GetSize() * UNITS); if (tStopThis > tAlignStop) { tStopThis = tAlignStop; } pSample->SetTime(&tCurrent, &tStopThis); tCurrent = tStopThis; if (bDiscontinuity) { pSample->SetDiscontinuity(TRUE); bDiscontinuity = FALSE; } hr = m_pReader->SyncReadAligned(pSample); if (FAILED(hr)) { pSample->Release(); OnError(hr); return; } hr = DeliverSample(pSample, tStart, tStop); if (hr != S_OK) { if (FAILED(hr)) { OnError(hr); } return; } } } EndOfStream(); } // after a flush, cancelled i/o will be waiting for collection // and release void CPullPin::CleanupCancelled(void) { while (1) { IMediaSample *pSample; DWORD_PTR dwUnused; HRESULT hr = m_pReader->WaitForNext(0, // no wait &pSample, &dwUnused); if (pSample) { pSample->Release(); } else { // no more samples return; } } } ================================================ FILE: common/baseclasses/pullpin.h ================================================ //------------------------------------------------------------------------------ // File: PullPin.h // // Desc: DirectShow base classes - defines CPullPin class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __PULLPIN_H__ #define __PULLPIN_H__ // // CPullPin // // object supporting pulling data from an IAsyncReader interface. // Given a start/stop position, calls a pure Receive method with each // IMediaSample received. // // This is essentially for use in a MemInputPin when it finds itself // connected to an IAsyncReader pin instead of a pushing pin. // class CPullPin : public CAMThread { IAsyncReader *m_pReader; REFERENCE_TIME m_tStart; REFERENCE_TIME m_tStop; REFERENCE_TIME m_tDuration; BOOL m_bSync; enum ThreadMsg { TM_Pause, // stop pulling and wait for next message TM_Start, // start pulling TM_Exit, // stop and exit }; ThreadMsg m_State; // override pure thread proc from CAMThread DWORD ThreadProc(void); // running pull method (check m_bSync) void Process(void); // clean up any cancelled i/o after a flush void CleanupCancelled(void); // suspend thread from pulling, eg during seek HRESULT PauseThread(); // start thread pulling - create thread if necy HRESULT StartThread(); // stop and close thread HRESULT StopThread(); // called from ProcessAsync to queue and collect requests HRESULT QueueSample(__inout REFERENCE_TIME &tCurrent, REFERENCE_TIME tAlignStop, BOOL bDiscontinuity); HRESULT CollectAndDeliver(REFERENCE_TIME tStart, REFERENCE_TIME tStop); HRESULT DeliverSample(IMediaSample *pSample, REFERENCE_TIME tStart, REFERENCE_TIME tStop); protected: IMemAllocator *m_pAlloc; public: CPullPin(); virtual ~CPullPin(); // returns S_OK if successfully connected to an IAsyncReader interface // from this object // Optional allocator should be proposed as a preferred allocator if // necessary // bSync is TRUE if we are to use sync reads instead of the // async methods. HRESULT Connect(IUnknown *pUnk, IMemAllocator *pAlloc, BOOL bSync); // disconnect any connection made in Connect HRESULT Disconnect(); // agree an allocator using RequestAllocator - optional // props param specifies your requirements (non-zero fields). // returns an error code if fail to match requirements. // optional IMemAllocator interface is offered as a preferred allocator // but no error occurs if it can't be met. virtual HRESULT DecideAllocator(IMemAllocator *pAlloc, __inout_opt ALLOCATOR_PROPERTIES *pProps); // set start and stop position. if active, will start immediately at // the new position. Default is 0 to duration HRESULT Seek(REFERENCE_TIME tStart, REFERENCE_TIME tStop); // return the total duration HRESULT Duration(__out REFERENCE_TIME *ptDuration); // start pulling data HRESULT Active(void); // stop pulling data HRESULT Inactive(void); // helper functions LONGLONG AlignDown(LONGLONG ll, LONG lAlign) { // aligning downwards is just truncation return ll & ~(lAlign - 1); }; LONGLONG AlignUp(LONGLONG ll, LONG lAlign) { // align up: round up to next boundary return (ll + (lAlign - 1)) & ~(lAlign - 1); }; // GetReader returns the (addrefed) IAsyncReader interface // for SyncRead etc IAsyncReader *GetReader() { m_pReader->AddRef(); return m_pReader; }; // -- pure -- // override this to handle data arrival // return value other than S_OK will stop data virtual HRESULT Receive(IMediaSample *) PURE; // override this to handle end-of-stream virtual HRESULT EndOfStream(void) PURE; // called on runtime errors that will have caused pulling // to stop // these errors are all returned from the upstream filter, who // will have already reported any errors to the filtergraph. virtual void OnError(HRESULT hr) PURE; // flush this pin and all downstream virtual HRESULT BeginFlush() PURE; virtual HRESULT EndFlush() PURE; }; #endif //__PULLPIN_H__ ================================================ FILE: common/baseclasses/refclock.cpp ================================================ //------------------------------------------------------------------------------ // File: RefClock.cpp // // Desc: DirectShow base classes - implements the IReferenceClock interface. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include #ifdef DXMPERF #include "dxmperf.h" #endif // DXMPERF // 'this' used in constructor list #pragma warning(disable : 4355) STDMETHODIMP CBaseReferenceClock::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { HRESULT hr; if (riid == IID_IReferenceClock) { hr = GetInterface((IReferenceClock *)this, ppv); } else if (riid == IID_IReferenceClockTimerControl) { hr = GetInterface((IReferenceClockTimerControl *)this, ppv); } else { hr = CUnknown::NonDelegatingQueryInterface(riid, ppv); } return hr; } CBaseReferenceClock::~CBaseReferenceClock() { #ifdef DXMPERF PERFLOG_DTOR(L"CBaseReferenceClock", (IReferenceClock *)this); #endif // DXMPERF if (m_TimerResolution) timeEndPeriod(m_TimerResolution); if (m_pSchedule) { m_pSchedule->DumpLinkedList(); } if (m_hThread) { m_bAbort = TRUE; TriggerThread(); WaitForSingleObject(m_hThread, INFINITE); EXECUTE_ASSERT(CloseHandle(m_hThread)); m_hThread = 0; EXECUTE_ASSERT(CloseHandle(m_pSchedule->GetEvent())); delete m_pSchedule; } } // A derived class may supply a hThreadEvent if it has its own thread that will take care // of calling the schedulers Advise method. (Refere to CBaseReferenceClock::AdviseThread() // to see what such a thread has to do.) CBaseReferenceClock::CBaseReferenceClock(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr, __inout_opt CAMSchedule *pShed) : CUnknown(pName, pUnk) , m_rtLastGotTime(0) , m_TimerResolution(0) , m_bAbort(FALSE) , m_pSchedule(pShed ? pShed : new CAMSchedule(CreateEvent(NULL, FALSE, FALSE, NULL))) , m_hThread(0) { #ifdef DXMPERF PERFLOG_CTOR(pName ? pName : L"CBaseReferenceClock", (IReferenceClock *)this); #endif // DXMPERF ASSERT(m_pSchedule); if (!m_pSchedule) { *phr = E_OUTOFMEMORY; } else { // Set up the highest resolution timer we can manage TIMECAPS tc; m_TimerResolution = (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(tc))) ? tc.wPeriodMin : 1; timeBeginPeriod(m_TimerResolution); /* Initialise our system times - the derived clock should set the right values */ m_dwPrevSystemTime = timeGetTime(); m_rtPrivateTime = (UNITS / MILLISECONDS) * m_dwPrevSystemTime; #ifdef PERF m_idGetSystemTime = MSR_REGISTER(TEXT("CBaseReferenceClock::GetTime")); #endif if (!pShed) { DWORD ThreadID; m_hThread = ::CreateThread(NULL, // Security attributes (DWORD)0, // Initial stack size AdviseThreadFunction, // Thread start address (LPVOID)this, // Thread parameter (DWORD)0, // Creation flags &ThreadID); // Thread identifier if (m_hThread) { SetThreadPriority(m_hThread, THREAD_PRIORITY_TIME_CRITICAL); } else { *phr = E_FAIL; EXECUTE_ASSERT(CloseHandle(m_pSchedule->GetEvent())); delete m_pSchedule; m_pSchedule = NULL; } } } } void CBaseReferenceClock::Restart(IN REFERENCE_TIME rtMinTime) { Lock(); m_rtLastGotTime = rtMinTime; Unlock(); } STDMETHODIMP CBaseReferenceClock::GetTime(__out REFERENCE_TIME *pTime) { HRESULT hr; if (pTime) { REFERENCE_TIME rtNow; Lock(); rtNow = GetPrivateTime(); if (rtNow > m_rtLastGotTime) { m_rtLastGotTime = rtNow; hr = S_OK; } else { hr = S_FALSE; } *pTime = m_rtLastGotTime; Unlock(); MSR_INTEGER(m_idGetSystemTime, LONG((*pTime) / (UNITS / MILLISECONDS))); #ifdef DXMPERF PERFLOG_GETTIME((IReferenceClock *)this, *pTime); #endif // DXMPERF } else hr = E_POINTER; return hr; } /* Ask for an async notification that a time has elapsed */ STDMETHODIMP CBaseReferenceClock::AdviseTime(REFERENCE_TIME baseTime, // base reference time REFERENCE_TIME streamTime, // stream offset time HEVENT hEvent, // advise via this event __out DWORD_PTR *pdwAdviseCookie) // where your cookie goes { CheckPointer(pdwAdviseCookie, E_POINTER); *pdwAdviseCookie = 0; // Check that the event is not already set ASSERT(WAIT_TIMEOUT == WaitForSingleObject(HANDLE(hEvent), 0)); HRESULT hr; const REFERENCE_TIME lRefTime = baseTime + streamTime; if (lRefTime <= 0 || lRefTime == MAX_TIME) { hr = E_INVALIDARG; } else { *pdwAdviseCookie = m_pSchedule->AddAdvisePacket(lRefTime, 0, HANDLE(hEvent), FALSE); hr = *pdwAdviseCookie ? NOERROR : E_OUTOFMEMORY; } return hr; } /* Ask for an asynchronous periodic notification that a time has elapsed */ STDMETHODIMP CBaseReferenceClock::AdvisePeriodic(REFERENCE_TIME StartTime, // starting at this time REFERENCE_TIME PeriodTime, // time between notifications HSEMAPHORE hSemaphore, // advise via a semaphore __out DWORD_PTR *pdwAdviseCookie) // where your cookie goes { CheckPointer(pdwAdviseCookie, E_POINTER); *pdwAdviseCookie = 0; HRESULT hr; if (StartTime > 0 && PeriodTime > 0 && StartTime != MAX_TIME) { *pdwAdviseCookie = m_pSchedule->AddAdvisePacket(StartTime, PeriodTime, HANDLE(hSemaphore), TRUE); hr = *pdwAdviseCookie ? NOERROR : E_OUTOFMEMORY; } else hr = E_INVALIDARG; return hr; } STDMETHODIMP CBaseReferenceClock::Unadvise(DWORD_PTR dwAdviseCookie) { return m_pSchedule->Unadvise(dwAdviseCookie); } REFERENCE_TIME CBaseReferenceClock::GetPrivateTime() { CAutoLock cObjectLock(this); /* If the clock has wrapped then the current time will be less than * the last time we were notified so add on the extra milliseconds * * The time period is long enough so that the likelihood of * successive calls spanning the clock cycle is not considered. */ DWORD dwTime = timeGetTime(); { m_rtPrivateTime += Int32x32To64(UNITS / MILLISECONDS, (DWORD)(dwTime - m_dwPrevSystemTime)); m_dwPrevSystemTime = dwTime; } return m_rtPrivateTime; } /* Adjust the current time by the input value. This allows an external time source to work out some of the latency of the clock system and adjust the "current" time accordingly. The intent is that the time returned to the user is synchronised to a clock source and allows drift to be catered for. For example: if the clock source detects a drift it can pass a delta to the current time rather than having to set an explicit time. */ STDMETHODIMP CBaseReferenceClock::SetTimeDelta(const REFERENCE_TIME &TimeDelta) { #ifdef DEBUG // Just break if passed an improper time delta value LONGLONG llDelta = TimeDelta > 0 ? TimeDelta : -TimeDelta; if (llDelta > UNITS * 1000) { DbgLog((LOG_TRACE, 0, TEXT("Bad Time Delta"))); // DebugBreak(); } // We're going to calculate a "severity" for the time change. Max -1 // min 8. We'll then use this as the debug logging level for a // debug log message. const LONG usDelta = LONG(TimeDelta / 10); // Delta in micro-secs DWORD delta = abs(usDelta); // varying delta // Severity == 8 - ceil(log(abs( micro-secs delta))) int Severity = 8; while (delta > 0) { delta >>= 3; // div 8 Severity--; } // Sev == 0 => > 2 second delta! DbgLog((LOG_TIMING, Severity < 0 ? 0 : Severity, TEXT("Sev %2i: CSystemClock::SetTimeDelta(%8ld us) %lu -> %lu ms."), Severity, usDelta, DWORD(ConvertToMilliseconds(m_rtPrivateTime)), DWORD(ConvertToMilliseconds(TimeDelta + m_rtPrivateTime)))); // Don't want the DbgBreak to fire when running stress on debug-builds. #ifdef BREAK_ON_SEVERE_TIME_DELTA if (Severity < 0) DbgBreakPoint(TEXT("SetTimeDelta > 16 seconds!"), TEXT(__FILE__), __LINE__); #endif #endif CAutoLock cObjectLock(this); m_rtPrivateTime += TimeDelta; // If time goes forwards, and we have advises, then we need to // trigger the thread so that it can re-evaluate its wait time. // Since we don't want the cost of the thread switches if the change // is really small, only do it if clock goes forward by more than // 0.5 millisecond. If the time goes backwards, the thread will // wake up "early" (relativly speaking) and will re-evaluate at // that time. if (TimeDelta > 5000 && m_pSchedule->GetAdviseCount() > 0) TriggerThread(); return NOERROR; } // Thread stuff DWORD __stdcall CBaseReferenceClock::AdviseThreadFunction(__in LPVOID p) { return DWORD(reinterpret_cast(p)->AdviseThread()); } HRESULT CBaseReferenceClock::AdviseThread() { DWORD dwWait = INFINITE; // The first thing we do is wait until something interesting happens // (meaning a first advise or shutdown). This prevents us calling // GetPrivateTime immediately which is goodness as that is a virtual // routine and the derived class may not yet be constructed. (This // thread is created in the base class constructor.) while (!m_bAbort) { // Wait for an interesting event to happen DbgLog((LOG_TIMING, 3, TEXT("CBaseRefClock::AdviseThread() Delay: %lu ms"), dwWait)); WaitForSingleObject(m_pSchedule->GetEvent(), dwWait); if (m_bAbort) break; // There are several reasons why we need to work from the internal // time, mainly to do with what happens when time goes backwards. // Mainly, it stop us looping madly if an event is just about to // expire when the clock goes backward (i.e. GetTime stop for a // while). const REFERENCE_TIME rtNow = GetPrivateTime(); DbgLog((LOG_TIMING, 3, TEXT("CBaseRefClock::AdviseThread() Woke at = %lu ms"), ConvertToMilliseconds(rtNow))); // We must add in a millisecond, since this is the resolution of our // WaitForSingleObject timer. Failure to do so will cause us to loop // franticly for (approx) 1 a millisecond. m_rtNextAdvise = m_pSchedule->Advise(10000 + rtNow); LONGLONG llWait = m_rtNextAdvise - rtNow; ASSERT(llWait > 0); llWait = ConvertToMilliseconds(llWait); // DON'T replace this with a max!! (The type's of these things is VERY important) dwWait = (llWait > REFERENCE_TIME(UINT_MAX)) ? UINT_MAX : DWORD(llWait); }; return NOERROR; } HRESULT CBaseReferenceClock::SetDefaultTimerResolution(REFERENCE_TIME timerResolution // in 100ns ) { CAutoLock cObjectLock(this); if (0 == timerResolution) { if (m_TimerResolution) { timeEndPeriod(m_TimerResolution); m_TimerResolution = 0; } } else { TIMECAPS tc; DWORD dwMinResolution = (TIMERR_NOERROR == timeGetDevCaps(&tc, sizeof(tc))) ? tc.wPeriodMin : 1; DWORD dwResolution = max(dwMinResolution, DWORD(timerResolution / 10000)); if (dwResolution != m_TimerResolution) { timeEndPeriod(m_TimerResolution); m_TimerResolution = dwResolution; timeBeginPeriod(m_TimerResolution); } } return S_OK; } HRESULT CBaseReferenceClock::GetDefaultTimerResolution(__out REFERENCE_TIME *pTimerResolution // in 100ns ) { if (!pTimerResolution) { return E_POINTER; } CAutoLock cObjectLock(this); *pTimerResolution = m_TimerResolution * 10000; return S_OK; } ================================================ FILE: common/baseclasses/refclock.h ================================================ //------------------------------------------------------------------------------ // File: RefClock.h // // Desc: DirectShow base classes - defines the IReferenceClock interface. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __BASEREFCLOCK__ #define __BASEREFCLOCK__ #include const UINT RESOLUTION = 1; /* High resolution timer */ const INT ADVISE_CACHE = 4; /* Default cache size */ const LONGLONG MAX_TIME = 0x7FFFFFFFFFFFFFFF; /* Maximum LONGLONG value */ inline LONGLONG WINAPI ConvertToMilliseconds(const REFERENCE_TIME &RT) { /* This converts an arbitrary value representing a reference time into a MILLISECONDS value for use in subsequent system calls */ return (RT / (UNITS / MILLISECONDS)); } /* This class hierarchy will support an IReferenceClock interface so that an audio card (or other externally driven clock) can update the system wide clock that everyone uses. The interface will be pretty thin with probably just one update method This interface has not yet been defined. */ /* This abstract base class implements the IReferenceClock * interface. Classes that actually provide clock signals (from * whatever source) have to be derived from this class. * * The abstract class provides implementations for: * CUnknown support * locking support (CCritSec) * client advise code (creates a thread) * * Question: what can we do about quality? Change the timer * resolution to lower the system load? Up the priority of the * timer thread to force more responsive signals? * * During class construction we create a worker thread that is destroyed during * destuction. This thread executes a series of WaitForSingleObject calls, * waking up when a command is given to the thread or the next wake up point * is reached. The wakeup points are determined by clients making Advise * calls. * * Each advise call defines a point in time when they wish to be notified. A * periodic advise is a series of these such events. We maintain a list of * advise links and calculate when the nearest event notification is due for. * We then call WaitForSingleObject with a timeout equal to this time. The * handle we wait on is used by the class to signal that something has changed * and that we must reschedule the next event. This typically happens when * someone comes in and asks for an advise link while we are waiting for an * event to timeout. * * While we are modifying the list of advise requests we * are protected from interference through a critical section. Clients are NOT * advised through callbacks. One shot clients have an event set, while * periodic clients have a semaphore released for each event notification. A * semaphore allows a client to be kept up to date with the number of events * actually triggered and be assured that they can't miss multiple events being * set. * * Keeping track of advises is taken care of by the CAMSchedule class. */ class CBaseReferenceClock : public CUnknown , public IReferenceClock , public CCritSec , public IReferenceClockTimerControl { protected: virtual ~CBaseReferenceClock(); // Don't let me be created on the stack! public: CBaseReferenceClock(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr, __inout_opt CAMSchedule *pSched = 0); STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); DECLARE_IUNKNOWN /* IReferenceClock methods */ // Derived classes must implement GetPrivateTime(). All our GetTime // does is call GetPrivateTime and then check so that time does not // go backwards. A return code of S_FALSE implies that the internal // clock has gone backwards and GetTime time has halted until internal // time has caught up. (Don't know if this will be much use to folk, // but it seems odd not to use the return code for something useful.) STDMETHODIMP GetTime(__out REFERENCE_TIME *pTime); // When this is called, it sets m_rtLastGotTime to the time it returns. /* Provide standard mechanisms for scheduling events */ /* Ask for an async notification that a time has elapsed */ STDMETHODIMP AdviseTime(REFERENCE_TIME baseTime, // base reference time REFERENCE_TIME streamTime, // stream offset time HEVENT hEvent, // advise via this event __out DWORD_PTR *pdwAdviseCookie // where your cookie goes ); /* Ask for an asynchronous periodic notification that a time has elapsed */ STDMETHODIMP AdvisePeriodic(REFERENCE_TIME StartTime, // starting at this time REFERENCE_TIME PeriodTime, // time between notifications HSEMAPHORE hSemaphore, // advise via a semaphore __out DWORD_PTR *pdwAdviseCookie // where your cookie goes ); /* Cancel a request for notification(s) - if the notification was * a one shot timer then this function doesn't need to be called * as the advise is automatically cancelled, however it does no * harm to explicitly cancel a one-shot advise. It is REQUIRED that * clients call Unadvise to clear a Periodic advise setting. */ STDMETHODIMP Unadvise(DWORD_PTR dwAdviseCookie); /* Methods for the benefit of derived classes or outer objects */ // GetPrivateTime() is the REAL clock. GetTime is just a cover for // it. Derived classes will probably override this method but not // GetTime() itself. // The important point about GetPrivateTime() is it's allowed to go // backwards. Our GetTime() will keep returning the LastGotTime // until GetPrivateTime() catches up. virtual REFERENCE_TIME GetPrivateTime(); /* Provide a method for correcting drift */ STDMETHODIMP SetTimeDelta(const REFERENCE_TIME &TimeDelta); CAMSchedule *GetSchedule() const { return m_pSchedule; } // IReferenceClockTimerControl methods // // Setting a default of 0 disables the default of 1ms STDMETHODIMP SetDefaultTimerResolution(REFERENCE_TIME timerResolution // in 100ns ); STDMETHODIMP GetDefaultTimerResolution(__out REFERENCE_TIME *pTimerResolution // in 100ns ); private: REFERENCE_TIME m_rtPrivateTime; // Current best estimate of time DWORD m_dwPrevSystemTime; // Last vaule we got from timeGetTime REFERENCE_TIME m_rtLastGotTime; // Last time returned by GetTime REFERENCE_TIME m_rtNextAdvise; // Time of next advise UINT m_TimerResolution; #ifdef PERF int m_idGetSystemTime; #endif // Thread stuff public: void TriggerThread() // Wakes thread up. Need to do this if { // time to next advise needs reevaluating. EXECUTE_ASSERT(SetEvent(m_pSchedule->GetEvent())); } private: BOOL m_bAbort; // Flag used for thread shutdown HANDLE m_hThread; // Thread handle HRESULT AdviseThread(); // Method in which the advise thread runs static DWORD __stdcall AdviseThreadFunction(__in LPVOID); // Function used to get there protected: CAMSchedule *m_pSchedule; void Restart(IN REFERENCE_TIME rtMinTime = 0I64); }; #endif ================================================ FILE: common/baseclasses/reftime.h ================================================ //------------------------------------------------------------------------------ // File: RefTime.h // // Desc: DirectShow base classes - defines CRefTime, a class that manages // reference times. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // // CRefTime // // Manage reference times. // Shares same data layout as REFERENCE_TIME, but adds some (nonvirtual) // functions providing simple comparison, conversion and arithmetic. // // A reference time (at the moment) is a unit of seconds represented in // 100ns units as is used in the Win32 FILETIME structure. BUT the time // a REFERENCE_TIME represents is NOT the time elapsed since 1/1/1601 it // will either be stream time or reference time depending upon context // // This class provides simple arithmetic operations on reference times // // keep non-virtual otherwise the data layout will not be the same as // REFERENCE_TIME // ----- // note that you are safe to cast a CRefTime* to a REFERENCE_TIME*, but // you will need to do so explicitly // ----- #ifndef __REFTIME__ #define __REFTIME__ const LONGLONG MILLISECONDS = (1000); // 10 ^ 3 const LONGLONG NANOSECONDS = (1000000000); // 10 ^ 9 const LONGLONG UNITS = (NANOSECONDS / 100); // 10 ^ 7 /* Unfortunately an inline function here generates a call to __allmul - even for constants! */ #define MILLISECONDS_TO_100NS_UNITS(lMs) Int32x32To64((lMs), (UNITS / MILLISECONDS)) class CRefTime { public: // *MUST* be the only data member so that this class is exactly // equivalent to a REFERENCE_TIME. // Also, must be *no virtual functions* REFERENCE_TIME m_time; inline CRefTime() { // default to 0 time m_time = 0; }; inline CRefTime(LONG msecs) { m_time = MILLISECONDS_TO_100NS_UNITS(msecs); }; inline CRefTime(REFERENCE_TIME rt) { m_time = rt; }; inline operator REFERENCE_TIME() const { return m_time; }; inline CRefTime &operator=(const CRefTime &rt) { m_time = rt.m_time; return *this; }; inline CRefTime &operator=(const LONGLONG ll) { m_time = ll; return *this; }; inline CRefTime &operator+=(const CRefTime &rt) { return (*this = *this + rt); }; inline CRefTime &operator-=(const CRefTime &rt) { return (*this = *this - rt); }; inline LONG Millisecs(void) { return (LONG)(m_time / (UNITS / MILLISECONDS)); }; inline LONGLONG GetUnits(void) { return m_time; }; }; const LONGLONG TimeZero = 0; #endif /* __REFTIME__ */ ================================================ FILE: common/baseclasses/renbase.cpp ================================================ //------------------------------------------------------------------------------ // File: RenBase.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include // DirectShow base class definitions #include // Needed for definition of timeGetTime #include // Standard data type limit definitions #include // Used for time critical log functions #pragma warning(disable : 4355) // Helper function for clamping time differences int inline TimeDiff(REFERENCE_TIME rt) { if (rt < -(50 * UNITS)) { return -(50 * UNITS); } else if (rt > 50 * UNITS) { return 50 * UNITS; } else return (int)rt; } // Implements the CBaseRenderer class CBaseRenderer::CBaseRenderer(REFCLSID RenderClass, // CLSID for this renderer __in_opt LPCTSTR pName, // Debug ONLY description __inout_opt LPUNKNOWN pUnk, // Aggregated owner object __inout HRESULT *phr) : // General OLE return code CBaseFilter(pName, pUnk, &m_InterfaceLock, RenderClass) , m_evComplete(TRUE, phr) , m_RenderEvent(FALSE, phr) , m_bAbort(FALSE) , m_pPosition(NULL) , m_ThreadSignal(TRUE, phr) , m_bStreaming(FALSE) , m_bEOS(FALSE) , m_bEOSDelivered(FALSE) , m_pMediaSample(NULL) , m_dwAdvise(0) , m_pQSink(NULL) , m_pInputPin(NULL) , m_bRepaintStatus(TRUE) , m_SignalTime(0) , m_bInReceive(FALSE) , m_EndOfStreamTimer(0) { if (SUCCEEDED(*phr)) { Ready(); #ifdef PERF m_idBaseStamp = MSR_REGISTER(TEXT("BaseRenderer: sample time stamp")); m_idBaseRenderTime = MSR_REGISTER(TEXT("BaseRenderer: draw time (msec)")); m_idBaseAccuracy = MSR_REGISTER(TEXT("BaseRenderer: Accuracy (msec)")); #endif } } // Delete the dynamically allocated IMediaPosition and IMediaSeeking helper // object. The object is created when somebody queries us. These are standard // control interfaces for seeking and setting start/stop positions and rates. // We will probably also have made an input pin based on CRendererInputPin // that has to be deleted, it's created when an enumerator calls our GetPin CBaseRenderer::~CBaseRenderer() { ASSERT(m_bStreaming == FALSE); ASSERT(m_EndOfStreamTimer == 0); StopStreaming(); ClearPendingSample(); // Delete any IMediaPosition implementation if (m_pPosition) { delete m_pPosition; m_pPosition = NULL; } // Delete any input pin created if (m_pInputPin) { delete m_pInputPin; m_pInputPin = NULL; } // Release any Quality sink ASSERT(m_pQSink == NULL); } // This returns the IMediaPosition and IMediaSeeking interfaces HRESULT CBaseRenderer::GetMediaPositionInterface(REFIID riid, __deref_out void **ppv) { CAutoLock cObjectCreationLock(&m_ObjectCreationLock); if (m_pPosition) { return m_pPosition->NonDelegatingQueryInterface(riid, ppv); } CBasePin *pPin = GetPin(0); if (NULL == pPin) { return E_OUTOFMEMORY; } HRESULT hr = NOERROR; // Create implementation of this dynamically since sometimes we may // never try and do a seek. The helper object implements a position // control interface (IMediaPosition) which in fact simply takes the // calls normally from the filter graph and passes them upstream m_pPosition = new CRendererPosPassThru(NAME("Renderer CPosPassThru"), CBaseFilter::GetOwner(), (HRESULT *)&hr, pPin); if (m_pPosition == NULL) { return E_OUTOFMEMORY; } if (FAILED(hr)) { delete m_pPosition; m_pPosition = NULL; return E_NOINTERFACE; } return GetMediaPositionInterface(riid, ppv); } // Overriden to say what interfaces we support and where STDMETHODIMP CBaseRenderer::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { // Do we have this interface if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking) { return GetMediaPositionInterface(riid, ppv); } else { return CBaseFilter::NonDelegatingQueryInterface(riid, ppv); } } // This is called whenever we change states, we have a manual reset event that // is signalled whenever we don't won't the source filter thread to wait in us // (such as in a stopped state) and likewise is not signalled whenever it can // wait (during paused and running) this function sets or resets the thread // event. The event is used to stop source filter threads waiting in Receive HRESULT CBaseRenderer::SourceThreadCanWait(BOOL bCanWait) { if (bCanWait == TRUE) { m_ThreadSignal.Reset(); } else { m_ThreadSignal.Set(); } return NOERROR; } #ifdef DEBUG // Dump the current renderer state to the debug terminal. The hardest part of // the renderer is the window where we unlock everything to wait for a clock // to signal it is time to draw or for the application to cancel everything // by stopping the filter. If we get things wrong we can leave the thread in // WaitForRenderTime with no way for it to ever get out and we will deadlock void CBaseRenderer::DisplayRendererState() { DbgLog((LOG_TIMING, 1, TEXT("\nTimed out in WaitForRenderTime"))); // No way should this be signalled at this point BOOL bSignalled = m_ThreadSignal.Check(); DbgLog((LOG_TIMING, 1, TEXT("Signal sanity check %d"), bSignalled)); // Now output the current renderer state variables DbgLog((LOG_TIMING, 1, TEXT("Filter state %d"), m_State)); DbgLog((LOG_TIMING, 1, TEXT("Abort flag %d"), m_bAbort)); DbgLog((LOG_TIMING, 1, TEXT("Streaming flag %d"), m_bStreaming)); DbgLog((LOG_TIMING, 1, TEXT("Clock advise link %d"), m_dwAdvise)); DbgLog((LOG_TIMING, 1, TEXT("Current media sample %x"), m_pMediaSample)); DbgLog((LOG_TIMING, 1, TEXT("EOS signalled %d"), m_bEOS)); DbgLog((LOG_TIMING, 1, TEXT("EOS delivered %d"), m_bEOSDelivered)); DbgLog((LOG_TIMING, 1, TEXT("Repaint status %d"), m_bRepaintStatus)); // Output the delayed end of stream timer information DbgLog((LOG_TIMING, 1, TEXT("End of stream timer %x"), m_EndOfStreamTimer)); DbgLog((LOG_TIMING, 1, TEXT("Deliver time %s"), CDisp((LONGLONG)m_SignalTime))); // Should never timeout during a flushing state BOOL bFlushing = m_pInputPin->IsFlushing(); DbgLog((LOG_TIMING, 1, TEXT("Flushing sanity check %d"), bFlushing)); // Display the time we were told to start at DbgLog((LOG_TIMING, 1, TEXT("Last run time %s"), CDisp((LONGLONG)m_tStart.m_time))); // Have we got a reference clock if (m_pClock == NULL) return; // Get the current time from the wall clock CRefTime CurrentTime, StartTime, EndTime; m_pClock->GetTime((REFERENCE_TIME *)&CurrentTime); CRefTime Offset = CurrentTime - m_tStart; // Display the current time from the clock DbgLog((LOG_TIMING, 1, TEXT("Clock time %s"), CDisp((LONGLONG)CurrentTime.m_time))); DbgLog((LOG_TIMING, 1, TEXT("Time difference %dms"), Offset.Millisecs())); // Do we have a sample ready to render if (m_pMediaSample == NULL) return; m_pMediaSample->GetTime((REFERENCE_TIME *)&StartTime, (REFERENCE_TIME *)&EndTime); DbgLog((LOG_TIMING, 1, TEXT("Next sample stream times (Start %d End %d ms)"), StartTime.Millisecs(), EndTime.Millisecs())); // Calculate how long it is until it is due for rendering CRefTime Wait = (m_tStart + StartTime) - CurrentTime; DbgLog((LOG_TIMING, 1, TEXT("Wait required %d ms"), Wait.Millisecs())); } #endif // Wait until the clock sets the timer event or we're otherwise signalled. We // set an arbitrary timeout for this wait and if it fires then we display the // current renderer state on the debugger. It will often fire if the filter's // left paused in an application however it may also fire during stress tests // if the synchronisation with application seeks and state changes is faulty #define RENDER_TIMEOUT 10000 HRESULT CBaseRenderer::WaitForRenderTime() { HANDLE WaitObjects[] = {m_ThreadSignal, m_RenderEvent}; DWORD Result = WAIT_TIMEOUT; // Wait for either the time to arrive or for us to be stopped OnWaitStart(); while (Result == WAIT_TIMEOUT) { Result = WaitForMultipleObjects(2, WaitObjects, FALSE, RENDER_TIMEOUT); #ifdef DEBUG if (Result == WAIT_TIMEOUT) DisplayRendererState(); #endif } OnWaitEnd(); // We may have been awoken without the timer firing if (Result == WAIT_OBJECT_0) { return VFW_E_STATE_CHANGED; } SignalTimerFired(); return NOERROR; } // Poll waiting for Receive to complete. This really matters when // Receive may set the palette and cause window messages // The problem is that if we don't really wait for a renderer to // stop processing we can deadlock waiting for a transform which // is calling the renderer's Receive() method because the transform's // Stop method doesn't know to process window messages to unblock // the renderer's Receive processing void CBaseRenderer::WaitForReceiveToComplete() { for (;;) { if (!m_bInReceive) { break; } MSG msg; // Receive all interthread snedmessages PeekMessage(&msg, NULL, WM_NULL, WM_NULL, PM_NOREMOVE); Sleep(1); } // If the wakebit for QS_POSTMESSAGE is set, the PeekMessage call // above just cleared the changebit which will cause some messaging // calls to block (waitMessage, MsgWaitFor...) now. // Post a dummy message to set the QS_POSTMESSAGE bit again if (HIWORD(GetQueueStatus(QS_POSTMESSAGE)) & QS_POSTMESSAGE) { // Send dummy message PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0); } } // A filter can have four discrete states, namely Stopped, Running, Paused, // Intermediate. We are in an intermediate state if we are currently trying // to pause but haven't yet got the first sample (or if we have been flushed // in paused state and therefore still have to wait for a sample to arrive) // This class contains an event called m_evComplete which is signalled when // the current state is completed and is not signalled when we are waiting to // complete the last state transition. As mentioned above the only time we // use this at the moment is when we wait for a media sample in paused state // If while we are waiting we receive an end of stream notification from the // source filter then we know no data is imminent so we can reset the event // This means that when we transition to paused the source filter must call // end of stream on us or send us an image otherwise we'll hang indefinately // Simple internal way of getting the real state FILTER_STATE CBaseRenderer::GetRealState() { return m_State; } // The renderer doesn't complete the full transition to paused states until // it has got one media sample to render. If you ask it for its state while // it's waiting it will return the state along with VFW_S_STATE_INTERMEDIATE STDMETHODIMP CBaseRenderer::GetState(DWORD dwMSecs, FILTER_STATE *State) { CheckPointer(State, E_POINTER); if (WaitDispatchingMessages(m_evComplete, dwMSecs) == WAIT_TIMEOUT) { *State = m_State; return VFW_S_STATE_INTERMEDIATE; } *State = m_State; return NOERROR; } // If we're pausing and we have no samples we don't complete the transition // to State_Paused and we return S_FALSE. However if the m_bAbort flag has // been set then all samples are rejected so there is no point waiting for // one. If we do have a sample then return NOERROR. We will only ever return // VFW_S_STATE_INTERMEDIATE from GetState after being paused with no sample // (calling GetState after either being stopped or Run will NOT return this) HRESULT CBaseRenderer::CompleteStateChange(FILTER_STATE OldState) { // Allow us to be paused when disconnected if (m_pInputPin->IsConnected() == FALSE) { Ready(); return S_OK; } // Have we run off the end of stream if (IsEndOfStream() == TRUE) { Ready(); return S_OK; } // Make sure we get fresh data after being stopped if (HaveCurrentSample() == TRUE) { if (OldState != State_Stopped) { Ready(); return S_OK; } } NotReady(); return S_FALSE; } // When we stop the filter the things we do are:- // Decommit the allocator being used in the connection // Release the source filter if it's waiting in Receive // Cancel any advise link we set up with the clock // Any end of stream signalled is now obsolete so reset // Allow us to be stopped when we are not connected STDMETHODIMP CBaseRenderer::Stop() { CAutoLock cRendererLock(&m_InterfaceLock); // Make sure there really is a state change if (m_State == State_Stopped) { return NOERROR; } // Is our input pin connected if (m_pInputPin->IsConnected() == FALSE) { NOTE("Input pin is not connected"); m_State = State_Stopped; return NOERROR; } CBaseFilter::Stop(); // If we are going into a stopped state then we must decommit whatever // allocator we are using it so that any source filter waiting in the // GetBuffer can be released and unlock themselves for a state change if (m_pInputPin->Allocator()) { m_pInputPin->Allocator()->Decommit(); } // Cancel any scheduled rendering SetRepaintStatus(TRUE); StopStreaming(); SourceThreadCanWait(FALSE); ResetEndOfStream(); CancelNotification(); // There should be no outstanding clock advise ASSERT(CancelNotification() == S_FALSE); ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent, 0)); ASSERT(m_EndOfStreamTimer == 0); Ready(); WaitForReceiveToComplete(); m_bAbort = FALSE; return NOERROR; } // When we pause the filter the things we do are:- // Commit the allocator being used in the connection // Allow a source filter thread to wait in Receive // Cancel any clock advise link (we may be running) // Possibly complete the state change if we have data // Allow us to be paused when we are not connected STDMETHODIMP CBaseRenderer::Pause() { CAutoLock cRendererLock(&m_InterfaceLock); FILTER_STATE OldState = m_State; ASSERT(m_pInputPin->IsFlushing() == FALSE); // Make sure there really is a state change if (m_State == State_Paused) { return CompleteStateChange(State_Paused); } // Has our input pin been connected if (m_pInputPin->IsConnected() == FALSE) { NOTE("Input pin is not connected"); m_State = State_Paused; return CompleteStateChange(State_Paused); } // Pause the base filter class HRESULT hr = CBaseFilter::Pause(); if (FAILED(hr)) { NOTE("Pause failed"); return hr; } // Enable EC_REPAINT events again SetRepaintStatus(TRUE); StopStreaming(); SourceThreadCanWait(TRUE); CancelNotification(); ResetEndOfStreamTimer(); // If we are going into a paused state then we must commit whatever // allocator we are using it so that any source filter can call the // GetBuffer and expect to get a buffer without returning an error if (m_pInputPin->Allocator()) { m_pInputPin->Allocator()->Commit(); } // There should be no outstanding advise ASSERT(CancelNotification() == S_FALSE); ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent, 0)); ASSERT(m_EndOfStreamTimer == 0); ASSERT(m_pInputPin->IsFlushing() == FALSE); // When we come out of a stopped state we must clear any image we were // holding onto for frame refreshing. Since renderers see state changes // first we can reset ourselves ready to accept the source thread data // Paused or running after being stopped causes the current position to // be reset so we're not interested in passing end of stream signals if (OldState == State_Stopped) { m_bAbort = FALSE; ClearPendingSample(); } return CompleteStateChange(OldState); } // When we run the filter the things we do are:- // Commit the allocator being used in the connection // Allow a source filter thread to wait in Receive // Signal the render event just to get us going // Start the base class by calling StartStreaming // Allow us to be run when we are not connected // Signal EC_COMPLETE if we are not connected STDMETHODIMP CBaseRenderer::Run(REFERENCE_TIME StartTime) { CAutoLock cRendererLock(&m_InterfaceLock); FILTER_STATE OldState = m_State; // Make sure there really is a state change if (m_State == State_Running) { return NOERROR; } // Send EC_COMPLETE if we're not connected if (m_pInputPin->IsConnected() == FALSE) { NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)(IBaseFilter *)this); m_State = State_Running; return NOERROR; } Ready(); // Pause the base filter class HRESULT hr = CBaseFilter::Run(StartTime); if (FAILED(hr)) { NOTE("Run failed"); return hr; } // Allow the source thread to wait ASSERT(m_pInputPin->IsFlushing() == FALSE); SourceThreadCanWait(TRUE); SetRepaintStatus(FALSE); // There should be no outstanding advise ASSERT(CancelNotification() == S_FALSE); ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent, 0)); ASSERT(m_EndOfStreamTimer == 0); ASSERT(m_pInputPin->IsFlushing() == FALSE); // If we are going into a running state then we must commit whatever // allocator we are using it so that any source filter can call the // GetBuffer and expect to get a buffer without returning an error if (m_pInputPin->Allocator()) { m_pInputPin->Allocator()->Commit(); } // When we come out of a stopped state we must clear any image we were // holding onto for frame refreshing. Since renderers see state changes // first we can reset ourselves ready to accept the source thread data // Paused or running after being stopped causes the current position to // be reset so we're not interested in passing end of stream signals if (OldState == State_Stopped) { m_bAbort = FALSE; ClearPendingSample(); } return StartStreaming(); } // Return the number of input pins we support int CBaseRenderer::GetPinCount() { if (m_pInputPin == NULL) { // Try to create it (void)GetPin(0); } return m_pInputPin != NULL ? 1 : 0; } // We only support one input pin and it is numbered zero CBasePin *CBaseRenderer::GetPin(int n) { CAutoLock cObjectCreationLock(&m_ObjectCreationLock); // Should only ever be called with zero ASSERT(n == 0); if (n != 0) { return NULL; } // Create the input pin if not already done so if (m_pInputPin == NULL) { // hr must be initialized to NOERROR because // CRendererInputPin's constructor only changes // hr's value if an error occurs. HRESULT hr = NOERROR; m_pInputPin = new CRendererInputPin(this, &hr, L"In"); if (NULL == m_pInputPin) { return NULL; } if (FAILED(hr)) { delete m_pInputPin; m_pInputPin = NULL; return NULL; } } return m_pInputPin; } // If "In" then return the IPin for our input pin, otherwise NULL and error STDMETHODIMP CBaseRenderer::FindPin(LPCWSTR Id, __deref_out IPin **ppPin) { CheckPointer(ppPin, E_POINTER); if (0 == lstrcmpW(Id, L"In")) { *ppPin = GetPin(0); if (*ppPin) { (*ppPin)->AddRef(); } else { return E_OUTOFMEMORY; } } else { *ppPin = NULL; return VFW_E_NOT_FOUND; } return NOERROR; } // Called when the input pin receives an EndOfStream notification. If we have // not got a sample, then notify EC_COMPLETE now. If we have samples, then set // m_bEOS and check for this on completing samples. If we're waiting to pause // then complete the transition to paused state by setting the state event HRESULT CBaseRenderer::EndOfStream() { // Ignore these calls if we are stopped if (m_State == State_Stopped) { return NOERROR; } // If we have a sample then wait for it to be rendered m_bEOS = TRUE; if (m_pMediaSample) { return NOERROR; } // If we are waiting for pause then we are now ready since we cannot now // carry on waiting for a sample to arrive since we are being told there // won't be any. This sets an event that the GetState function picks up Ready(); // Only signal completion now if we are running otherwise queue it until // we do run in StartStreaming. This is used when we seek because a seek // causes a pause where early notification of completion is misleading if (m_bStreaming) { SendEndOfStream(); } return NOERROR; } // When we are told to flush we should release the source thread HRESULT CBaseRenderer::BeginFlush() { // If paused then report state intermediate until we get some data if (m_State == State_Paused) { NotReady(); } SourceThreadCanWait(FALSE); CancelNotification(); ClearPendingSample(); // Wait for Receive to complete WaitForReceiveToComplete(); return NOERROR; } // After flushing the source thread can wait in Receive again HRESULT CBaseRenderer::EndFlush() { // Reset the current sample media time if (m_pPosition) m_pPosition->ResetMediaTime(); // There should be no outstanding advise ASSERT(CancelNotification() == S_FALSE); SourceThreadCanWait(TRUE); return NOERROR; } // We can now send EC_REPAINTs if so required HRESULT CBaseRenderer::CompleteConnect(IPin *pReceivePin) { // The caller should always hold the interface lock because // the function uses CBaseFilter::m_State. ASSERT(CritCheckIn(&m_InterfaceLock)); m_bAbort = FALSE; if (State_Running == GetRealState()) { HRESULT hr = StartStreaming(); if (FAILED(hr)) { return hr; } SetRepaintStatus(FALSE); } else { SetRepaintStatus(TRUE); } return NOERROR; } // Called when we go paused or running HRESULT CBaseRenderer::Active() { return NOERROR; } // Called when we go into a stopped state HRESULT CBaseRenderer::Inactive() { if (m_pPosition) { m_pPosition->ResetMediaTime(); } // People who derive from this may want to override this behaviour // to keep hold of the sample in some circumstances ClearPendingSample(); return NOERROR; } // Tell derived classes about the media type agreed HRESULT CBaseRenderer::SetMediaType(const CMediaType *pmt) { return NOERROR; } // When we break the input pin connection we should reset the EOS flags. When // we are asked for either IMediaPosition or IMediaSeeking we will create a // CPosPassThru object to handles media time pass through. When we're handed // samples we store (by calling CPosPassThru::RegisterMediaTime) their media // times so we can then return a real current position of data being rendered HRESULT CBaseRenderer::BreakConnect() { // Do we have a quality management sink if (m_pQSink) { m_pQSink->Release(); m_pQSink = NULL; } // Check we have a valid connection if (m_pInputPin->IsConnected() == FALSE) { return S_FALSE; } // Check we are stopped before disconnecting if (m_State != State_Stopped && !m_pInputPin->CanReconnectWhenActive()) { return VFW_E_NOT_STOPPED; } SetRepaintStatus(FALSE); ResetEndOfStream(); ClearPendingSample(); m_bAbort = FALSE; if (State_Running == m_State) { StopStreaming(); } return NOERROR; } // Retrieves the sample times for this samples (note the sample times are // passed in by reference not value). We return S_FALSE to say schedule this // sample according to the times on the sample. We also return S_OK in // which case the object should simply render the sample data immediately HRESULT CBaseRenderer::GetSampleTimes(IMediaSample *pMediaSample, __out REFERENCE_TIME *pStartTime, __out REFERENCE_TIME *pEndTime) { ASSERT(m_dwAdvise == 0); ASSERT(pMediaSample); // If the stop time for this sample is before or the same as start time, // then just ignore it (release it) and schedule the next one in line // Source filters should always fill in the start and end times properly! if (SUCCEEDED(pMediaSample->GetTime(pStartTime, pEndTime))) { if (*pEndTime < *pStartTime) { return VFW_E_START_TIME_AFTER_END; } } else { // no time set in the sample... draw it now? return S_OK; } // Can't synchronise without a clock so we return S_OK which tells the // caller that the sample should be rendered immediately without going // through the overhead of setting a timer advise link with the clock if (m_pClock == NULL) { return S_OK; } return ShouldDrawSampleNow(pMediaSample, pStartTime, pEndTime); } // By default all samples are drawn according to their time stamps so we // return S_FALSE. Returning S_OK means draw immediately, this is used // by the derived video renderer class in its quality management. HRESULT CBaseRenderer::ShouldDrawSampleNow(IMediaSample *pMediaSample, __out REFERENCE_TIME *ptrStart, __out REFERENCE_TIME *ptrEnd) { return S_FALSE; } // We must always reset the current advise time to zero after a timer fires // because there are several possible ways which lead us not to do any more // scheduling such as the pending image being cleared after state changes void CBaseRenderer::SignalTimerFired() { m_dwAdvise = 0; } // Cancel any notification currently scheduled. This is called by the owning // window object when it is told to stop streaming. If there is no timer link // outstanding then calling this is benign otherwise we go ahead and cancel // We must always reset the render event as the quality management code can // signal immediate rendering by setting the event without setting an advise // link. If we're subsequently stopped and run the first attempt to setup an // advise link with the reference clock will find the event still signalled HRESULT CBaseRenderer::CancelNotification() { ASSERT(m_dwAdvise == 0 || m_pClock); DWORD_PTR dwAdvise = m_dwAdvise; // Have we a live advise link if (m_dwAdvise) { m_pClock->Unadvise(m_dwAdvise); SignalTimerFired(); ASSERT(m_dwAdvise == 0); } // Clear the event and return our status m_RenderEvent.Reset(); return (dwAdvise ? S_OK : S_FALSE); } // Responsible for setting up one shot advise links with the clock // Return FALSE if the sample is to be dropped (not drawn at all) // Return TRUE if the sample is to be drawn and in this case also // arrange for m_RenderEvent to be set at the appropriate time BOOL CBaseRenderer::ScheduleSample(IMediaSample *pMediaSample) { REFERENCE_TIME StartSample, EndSample; // Is someone pulling our leg if (pMediaSample == NULL) { return FALSE; } // Get the next sample due up for rendering. If there aren't any ready // then GetNextSampleTimes returns an error. If there is one to be done // then it succeeds and yields the sample times. If it is due now then // it returns S_OK other if it's to be done when due it returns S_FALSE HRESULT hr = GetSampleTimes(pMediaSample, &StartSample, &EndSample); if (FAILED(hr)) { return FALSE; } // If we don't have a reference clock then we cannot set up the advise // time so we simply set the event indicating an image to render. This // will cause us to run flat out without any timing or synchronisation if (hr == S_OK) { EXECUTE_ASSERT(SetEvent((HANDLE)m_RenderEvent)); return TRUE; } ASSERT(m_dwAdvise == 0); ASSERT(m_pClock); ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent, 0)); // We do have a valid reference clock interface so we can ask it to // set an event when the image comes due for rendering. We pass in // the reference time we were told to start at and also the current // stream time which is the offset from the start reference time hr = m_pClock->AdviseTime((REFERENCE_TIME)m_tStart, // Start run time StartSample, // Stream time (HEVENT)(HANDLE)m_RenderEvent, // Render notification &m_dwAdvise); // Advise cookie if (SUCCEEDED(hr)) { return TRUE; } // We could not schedule the next sample for rendering despite the fact // we have a valid sample here. This is a fair indication that either // the system clock is wrong or the time stamp for the sample is duff ASSERT(m_dwAdvise == 0); return FALSE; } // This is called when a sample comes due for rendering. We pass the sample // on to the derived class. After rendering we will initialise the timer for // the next sample, NOTE signal that the last one fired first, if we don't // do this it thinks there is still one outstanding that hasn't completed HRESULT CBaseRenderer::Render(IMediaSample *pMediaSample) { // If the media sample is NULL then we will have been notified by the // clock that another sample is ready but in the mean time someone has // stopped us streaming which causes the next sample to be released if (pMediaSample == NULL) { return S_FALSE; } // If we have stopped streaming then don't render any more samples, the // thread that got in and locked us and then reset this flag does not // clear the pending sample as we can use it to refresh any output device if (m_bStreaming == FALSE) { return S_FALSE; } // Time how long the rendering takes OnRenderStart(pMediaSample); DoRenderSample(pMediaSample); OnRenderEnd(pMediaSample); return NOERROR; } // Checks if there is a sample waiting at the renderer BOOL CBaseRenderer::HaveCurrentSample() { CAutoLock cRendererLock(&m_RendererLock); return (m_pMediaSample == NULL ? FALSE : TRUE); } // Returns the current sample waiting at the video renderer. We AddRef the // sample before returning so that should it come due for rendering the // person who called this method will hold the remaining reference count // that will stop the sample being added back onto the allocator free list IMediaSample *CBaseRenderer::GetCurrentSample() { CAutoLock cRendererLock(&m_RendererLock); if (m_pMediaSample) { m_pMediaSample->AddRef(); } return m_pMediaSample; } // Called when the source delivers us a sample. We go through a few checks to // make sure the sample can be rendered. If we are running (streaming) then we // have the sample scheduled with the reference clock, if we are not streaming // then we have received an sample in paused mode so we can complete any state // transition. On leaving this function everything will be unlocked so an app // thread may get in and change our state to stopped (for example) in which // case it will also signal the thread event so that our wait call is stopped HRESULT CBaseRenderer::PrepareReceive(IMediaSample *pMediaSample) { CAutoLock cInterfaceLock(&m_InterfaceLock); m_bInReceive = TRUE; // Check our flushing and filter state // This function must hold the interface lock because it calls // CBaseInputPin::Receive() and CBaseInputPin::Receive() uses // CBasePin::m_bRunTimeError. HRESULT hr = m_pInputPin->CBaseInputPin::Receive(pMediaSample); if (hr != NOERROR) { m_bInReceive = FALSE; return E_FAIL; } // Has the type changed on a media sample. We do all rendering // synchronously on the source thread, which has a side effect // that only one buffer is ever outstanding. Therefore when we // have Receive called we can go ahead and change the format // Since the format change can cause a SendMessage we just don't // lock if (m_pInputPin->SampleProps()->pMediaType) { hr = m_pInputPin->SetMediaType((CMediaType *)m_pInputPin->SampleProps()->pMediaType); if (FAILED(hr)) { m_bInReceive = FALSE; return hr; } } CAutoLock cSampleLock(&m_RendererLock); ASSERT(IsActive() == TRUE); ASSERT(m_pInputPin->IsFlushing() == FALSE); ASSERT(m_pInputPin->IsConnected() == TRUE); ASSERT(m_pMediaSample == NULL); // Return an error if we already have a sample waiting for rendering // source pins must serialise the Receive calls - we also check that // no data is being sent after the source signalled an end of stream if (m_pMediaSample || m_bEOS || m_bAbort) { Ready(); m_bInReceive = FALSE; return E_UNEXPECTED; } // Store the media times from this sample if (m_pPosition) m_pPosition->RegisterMediaTime(pMediaSample); // Schedule the next sample if we are streaming if ((m_bStreaming == TRUE) && (ScheduleSample(pMediaSample) == FALSE)) { ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent, 0)); ASSERT(CancelNotification() == S_FALSE); m_bInReceive = FALSE; return VFW_E_SAMPLE_REJECTED; } // Store the sample end time for EC_COMPLETE handling m_SignalTime = m_pInputPin->SampleProps()->tStop; // BEWARE we sometimes keep the sample even after returning the thread to // the source filter such as when we go into a stopped state (we keep it // to refresh the device with) so we must AddRef it to keep it safely. If // we start flushing the source thread is released and any sample waiting // will be released otherwise GetBuffer may never return (see BeginFlush) m_pMediaSample = pMediaSample; m_pMediaSample->AddRef(); if (m_bStreaming == FALSE) { SetRepaintStatus(TRUE); } return NOERROR; } // Called by the source filter when we have a sample to render. Under normal // circumstances we set an advise link with the clock, wait for the time to // arrive and then render the data using the PURE virtual DoRenderSample that // the derived class will have overriden. After rendering the sample we may // also signal EOS if it was the last one sent before EndOfStream was called HRESULT CBaseRenderer::Receive(IMediaSample *pSample) { ASSERT(pSample); // It may return VFW_E_SAMPLE_REJECTED code to say don't bother HRESULT hr = PrepareReceive(pSample); ASSERT(m_bInReceive == SUCCEEDED(hr)); if (FAILED(hr)) { if (hr == VFW_E_SAMPLE_REJECTED) { return NOERROR; } return hr; } // We realize the palette in "PrepareRender()" so we have to give away the // filter lock here. if (m_State == State_Paused) { PrepareRender(); // no need to use InterlockedExchange m_bInReceive = FALSE; { // We must hold both these locks CAutoLock cRendererLock(&m_InterfaceLock); if (m_State == State_Stopped) return NOERROR; m_bInReceive = TRUE; CAutoLock cSampleLock(&m_RendererLock); OnReceiveFirstSample(pSample); } Ready(); } // Having set an advise link with the clock we sit and wait. We may be // awoken by the clock firing or by a state change. The rendering call // will lock the critical section and check we can still render the data hr = WaitForRenderTime(); if (FAILED(hr)) { m_bInReceive = FALSE; return NOERROR; } PrepareRender(); // Set this here and poll it until we work out the locking correctly // It can't be right that the streaming stuff grabs the interface // lock - after all we want to be able to wait for this stuff // to complete m_bInReceive = FALSE; // We must hold both these locks CAutoLock cRendererLock(&m_InterfaceLock); // since we gave away the filter wide lock, the sate of the filter could // have chnaged to Stopped if (m_State == State_Stopped) return NOERROR; CAutoLock cSampleLock(&m_RendererLock); // Deal with this sample Render(m_pMediaSample); ClearPendingSample(); SendEndOfStream(); CancelNotification(); return NOERROR; } // This is called when we stop or are inactivated to clear the pending sample // We release the media sample interface so that they can be allocated to the // source filter again, unless of course we are changing state to inactive in // which case GetBuffer will return an error. We must also reset the current // media sample to NULL so that we know we do not currently have an image HRESULT CBaseRenderer::ClearPendingSample() { CAutoLock cRendererLock(&m_RendererLock); if (m_pMediaSample) { m_pMediaSample->Release(); m_pMediaSample = NULL; } return NOERROR; } // Used to signal end of stream according to the sample end time void CALLBACK EndOfStreamTimer(UINT uID, // Timer identifier UINT uMsg, // Not currently used DWORD_PTR dwUser, // User information DWORD_PTR dw1, // Windows reserved DWORD_PTR dw2) // is also reserved { CBaseRenderer *pRenderer = (CBaseRenderer *)dwUser; NOTE1("EndOfStreamTimer called (%d)", uID); pRenderer->TimerCallback(); } // Do the timer callback work void CBaseRenderer::TimerCallback() { // Lock for synchronization (but don't hold this lock when calling // timeKillEvent) CAutoLock cRendererLock(&m_RendererLock); // See if we should signal end of stream now if (m_EndOfStreamTimer) { m_EndOfStreamTimer = 0; SendEndOfStream(); } } // If we are at the end of the stream signal the filter graph but do not set // the state flag back to FALSE. Once we drop off the end of the stream we // leave the flag set (until a subsequent ResetEndOfStream). Each sample we // get delivered will update m_SignalTime to be the last sample's end time. // We must wait this long before signalling end of stream to the filtergraph #define TIMEOUT_DELIVERYWAIT 50 #define TIMEOUT_RESOLUTION 10 HRESULT CBaseRenderer::SendEndOfStream() { ASSERT(CritCheckIn(&m_RendererLock)); if (m_bEOS == FALSE || m_bEOSDelivered || m_EndOfStreamTimer) { return NOERROR; } // If there is no clock then signal immediately if (m_pClock == NULL) { return NotifyEndOfStream(); } // How long into the future is the delivery time REFERENCE_TIME Signal = m_tStart + m_SignalTime; REFERENCE_TIME CurrentTime; m_pClock->GetTime(&CurrentTime); LONG Delay = LONG((Signal - CurrentTime) / 10000); // Dump the timing information to the debugger NOTE1("Delay until end of stream delivery %d", Delay); NOTE1("Current %s", (LPCTSTR)CDisp((LONGLONG)CurrentTime)); NOTE1("Signal %s", (LPCTSTR)CDisp((LONGLONG)Signal)); // Wait for the delivery time to arrive if (Delay < TIMEOUT_DELIVERYWAIT) { return NotifyEndOfStream(); } // Signal a timer callback on another worker thread m_EndOfStreamTimer = CompatibleTimeSetEvent((UINT)Delay, // Period of timer TIMEOUT_RESOLUTION, // Timer resolution EndOfStreamTimer, // Callback function DWORD_PTR(this), // Used information TIME_ONESHOT); // Type of callback if (m_EndOfStreamTimer == 0) { return NotifyEndOfStream(); } return NOERROR; } // Signals EC_COMPLETE to the filtergraph manager HRESULT CBaseRenderer::NotifyEndOfStream() { CAutoLock cRendererLock(&m_RendererLock); ASSERT(m_bEOSDelivered == FALSE); ASSERT(m_EndOfStreamTimer == 0); // Has the filter changed state if (m_bStreaming == FALSE) { ASSERT(m_EndOfStreamTimer == 0); return NOERROR; } // Reset the end of stream timer m_EndOfStreamTimer = 0; // If we've been using the IMediaPosition interface, set it's start // and end media "times" to the stop position by hand. This ensures // that we actually get to the end, even if the MPEG guestimate has // been bad or if the quality management dropped the last few frames if (m_pPosition) m_pPosition->EOS(); m_bEOSDelivered = TRUE; NOTE("Sending EC_COMPLETE..."); return NotifyEvent(EC_COMPLETE, S_OK, (LONG_PTR)(IBaseFilter *)this); } // Reset the end of stream flag, this is typically called when we transfer to // stopped states since that resets the current position back to the start so // we will receive more samples or another EndOfStream if there aren't any. We // keep two separate flags one to say we have run off the end of the stream // (this is the m_bEOS flag) and another to say we have delivered EC_COMPLETE // to the filter graph. We need the latter otherwise we can end up sending an // EC_COMPLETE every time the source changes state and calls our EndOfStream HRESULT CBaseRenderer::ResetEndOfStream() { ResetEndOfStreamTimer(); CAutoLock cRendererLock(&m_RendererLock); m_bEOS = FALSE; m_bEOSDelivered = FALSE; m_SignalTime = 0; return NOERROR; } // Kills any outstanding end of stream timer void CBaseRenderer::ResetEndOfStreamTimer() { ASSERT(CritCheckOut(&m_RendererLock)); if (m_EndOfStreamTimer) { timeKillEvent(m_EndOfStreamTimer); m_EndOfStreamTimer = 0; } } // This is called when we start running so that we can schedule any pending // image we have with the clock and display any timing information. If we // don't have any sample but we have queued an EOS flag then we send it. If // we do have a sample then we wait until that has been rendered before we // signal the filter graph otherwise we may change state before it's done HRESULT CBaseRenderer::StartStreaming() { CAutoLock cRendererLock(&m_RendererLock); if (m_bStreaming == TRUE) { return NOERROR; } // Reset the streaming times ready for running m_bStreaming = TRUE; timeBeginPeriod(1); OnStartStreaming(); // There should be no outstanding advise ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent, 0)); ASSERT(CancelNotification() == S_FALSE); // If we have an EOS and no data then deliver it now if (m_pMediaSample == NULL) { return SendEndOfStream(); } // Have the data rendered ASSERT(m_pMediaSample); if (!ScheduleSample(m_pMediaSample)) m_RenderEvent.Set(); return NOERROR; } // This is called when we stop streaming so that we can set our internal flag // indicating we are not now to schedule any more samples arriving. The state // change methods in the filter implementation take care of cancelling any // clock advise link we have set up and clearing any pending sample we have HRESULT CBaseRenderer::StopStreaming() { CAutoLock cRendererLock(&m_RendererLock); m_bEOSDelivered = FALSE; if (m_bStreaming == TRUE) { m_bStreaming = FALSE; OnStopStreaming(); timeEndPeriod(1); } return NOERROR; } // We have a boolean flag that is reset when we have signalled EC_REPAINT to // the filter graph. We set this when we receive an image so that should any // conditions arise again we can send another one. By having a flag we ensure // we don't flood the filter graph with redundant calls. We do not set the // event when we receive an EndOfStream call since there is no point in us // sending further EC_REPAINTs. In particular the AutoShowWindow method and // the DirectDraw object use this method to control the window repainting void CBaseRenderer::SetRepaintStatus(BOOL bRepaint) { CAutoLock cSampleLock(&m_RendererLock); m_bRepaintStatus = bRepaint; } // Pass the window handle to the upstream filter void CBaseRenderer::SendNotifyWindow(IPin *pPin, HWND hwnd) { IMediaEventSink *pSink; // Does the pin support IMediaEventSink HRESULT hr = pPin->QueryInterface(IID_IMediaEventSink, (void **)&pSink); if (SUCCEEDED(hr)) { pSink->Notify(EC_NOTIFY_WINDOW, LONG_PTR(hwnd), 0); pSink->Release(); } NotifyEvent(EC_NOTIFY_WINDOW, LONG_PTR(hwnd), 0); } // Signal an EC_REPAINT to the filter graph. This can be used to have data // sent to us. For example when a video window is first displayed it may // not have an image to display, at which point it signals EC_REPAINT. The // filtergraph will either pause the graph if stopped or if already paused // it will call put_CurrentPosition of the current position. Setting the // current position to itself has the stream flushed and the image resent #define RLOG(_x_) DbgLog((LOG_TRACE, 1, TEXT(_x_))); void CBaseRenderer::SendRepaint() { CAutoLock cSampleLock(&m_RendererLock); ASSERT(m_pInputPin); // We should not send repaint notifications when... // - An end of stream has been notified // - Our input pin is being flushed // - The input pin is not connected // - We have aborted a video playback // - There is a repaint already sent if (m_bAbort == FALSE) { if (m_pInputPin->IsConnected() == TRUE) { if (m_pInputPin->IsFlushing() == FALSE) { if (IsEndOfStream() == FALSE) { if (m_bRepaintStatus == TRUE) { IPin *pPin = (IPin *)m_pInputPin; NotifyEvent(EC_REPAINT, (LONG_PTR)pPin, 0); SetRepaintStatus(FALSE); RLOG("Sending repaint"); } } } } } } // When a video window detects a display change (WM_DISPLAYCHANGE message) it // can send an EC_DISPLAY_CHANGED event code along with the renderer pin. The // filtergraph will stop everyone and reconnect our input pin. As we're then // reconnected we can accept the media type that matches the new display mode // since we may no longer be able to draw the current image type efficiently BOOL CBaseRenderer::OnDisplayChange() { // Ignore if we are not connected yet CAutoLock cSampleLock(&m_RendererLock); if (m_pInputPin->IsConnected() == FALSE) { return FALSE; } RLOG("Notification of EC_DISPLAY_CHANGE"); // Pass our input pin as parameter on the event IPin *pPin = (IPin *)m_pInputPin; m_pInputPin->AddRef(); NotifyEvent(EC_DISPLAY_CHANGED, (LONG_PTR)pPin, 0); SetAbortSignal(TRUE); ClearPendingSample(); m_pInputPin->Release(); return TRUE; } // Called just before we start drawing. // Store the current time in m_trRenderStart to allow the rendering time to be // logged. Log the time stamp of the sample and how late it is (neg is early) void CBaseRenderer::OnRenderStart(IMediaSample *pMediaSample) { #ifdef PERF REFERENCE_TIME trStart, trEnd; pMediaSample->GetTime(&trStart, &trEnd); MSR_INTEGER(m_idBaseStamp, (int)trStart); // dump low order 32 bits m_pClock->GetTime(&m_trRenderStart); MSR_INTEGER(0, (int)m_trRenderStart); REFERENCE_TIME trStream; trStream = m_trRenderStart - m_tStart; // convert reftime to stream time MSR_INTEGER(0, (int)trStream); const int trLate = (int)(trStream - trStart); MSR_INTEGER(m_idBaseAccuracy, trLate / 10000); // dump in mSec #endif } // OnRenderStart // Called directly after drawing an image. // calculate the time spent drawing and log it. void CBaseRenderer::OnRenderEnd(IMediaSample *pMediaSample) { #ifdef PERF REFERENCE_TIME trNow; m_pClock->GetTime(&trNow); MSR_INTEGER(0, (int)trNow); int t = (int)((trNow - m_trRenderStart) / 10000); // convert UNITS->msec MSR_INTEGER(m_idBaseRenderTime, t); #endif } // OnRenderEnd // Constructor must be passed the base renderer object CRendererInputPin::CRendererInputPin(__inout CBaseRenderer *pRenderer, __inout HRESULT *phr, __in_opt LPCWSTR pPinName) : CBaseInputPin(NAME("Renderer pin"), pRenderer, &pRenderer->m_InterfaceLock, (HRESULT *)phr, pPinName) { m_pRenderer = pRenderer; ASSERT(m_pRenderer); } // Signals end of data stream on the input pin STDMETHODIMP CRendererInputPin::EndOfStream() { CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock); CAutoLock cSampleLock(&m_pRenderer->m_RendererLock); // Make sure we're streaming ok HRESULT hr = CheckStreaming(); if (hr != NOERROR) { return hr; } // Pass it onto the renderer hr = m_pRenderer->EndOfStream(); if (SUCCEEDED(hr)) { hr = CBaseInputPin::EndOfStream(); } return hr; } // Signals start of flushing on the input pin - we do the final reset end of // stream with the renderer lock unlocked but with the interface lock locked // We must do this because we call timeKillEvent, our timer callback method // has to take the renderer lock to serialise our state. Therefore holding a // renderer lock when calling timeKillEvent could cause a deadlock condition STDMETHODIMP CRendererInputPin::BeginFlush() { CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock); { CAutoLock cSampleLock(&m_pRenderer->m_RendererLock); CBaseInputPin::BeginFlush(); m_pRenderer->BeginFlush(); } return m_pRenderer->ResetEndOfStream(); } // Signals end of flushing on the input pin STDMETHODIMP CRendererInputPin::EndFlush() { CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock); CAutoLock cSampleLock(&m_pRenderer->m_RendererLock); HRESULT hr = m_pRenderer->EndFlush(); if (SUCCEEDED(hr)) { hr = CBaseInputPin::EndFlush(); } return hr; } // Pass the sample straight through to the renderer object STDMETHODIMP CRendererInputPin::Receive(IMediaSample *pSample) { HRESULT hr = m_pRenderer->Receive(pSample); if (FAILED(hr)) { // A deadlock could occur if the caller holds the renderer lock and // attempts to acquire the interface lock. ASSERT(CritCheckOut(&m_pRenderer->m_RendererLock)); { // The interface lock must be held when the filter is calling // IsStopped() or IsFlushing(). The interface lock must also // be held because the function uses m_bRunTimeError. CAutoLock cRendererLock(&m_pRenderer->m_InterfaceLock); // We do not report errors which occur while the filter is stopping, // flushing or if the m_bAbort flag is set . Errors are expected to // occur during these operations and the streaming thread correctly // handles the errors. if (!IsStopped() && !IsFlushing() && !m_pRenderer->m_bAbort && !m_bRunTimeError) { // EC_ERRORABORT's first parameter is the error which caused // the event and its' last parameter is 0. See the Direct // Show SDK documentation for more information. m_pRenderer->NotifyEvent(EC_ERRORABORT, hr, 0); { CAutoLock alRendererLock(&m_pRenderer->m_RendererLock); if (m_pRenderer->IsStreaming() && !m_pRenderer->IsEndOfStreamDelivered()) { m_pRenderer->NotifyEndOfStream(); } } m_bRunTimeError = TRUE; } } } return hr; } // Called when the input pin is disconnected HRESULT CRendererInputPin::BreakConnect() { HRESULT hr = m_pRenderer->BreakConnect(); if (FAILED(hr)) { return hr; } return CBaseInputPin::BreakConnect(); } // Called when the input pin is connected HRESULT CRendererInputPin::CompleteConnect(IPin *pReceivePin) { HRESULT hr = m_pRenderer->CompleteConnect(pReceivePin); if (FAILED(hr)) { return hr; } return CBaseInputPin::CompleteConnect(pReceivePin); } // Give the pin id of our one and only pin STDMETHODIMP CRendererInputPin::QueryId(__deref_out LPWSTR *Id) { CheckPointer(Id, E_POINTER); const WCHAR szIn[] = L"In"; *Id = (LPWSTR)CoTaskMemAlloc(sizeof(szIn)); if (*Id == NULL) { return E_OUTOFMEMORY; } CopyMemory(*Id, szIn, sizeof(szIn)); return NOERROR; } // Will the filter accept this media type HRESULT CRendererInputPin::CheckMediaType(const CMediaType *pmt) { return m_pRenderer->CheckMediaType(pmt); } // Called when we go paused or running HRESULT CRendererInputPin::Active() { return m_pRenderer->Active(); } // Called when we go into a stopped state HRESULT CRendererInputPin::Inactive() { // The caller must hold the interface lock because // this function uses m_bRunTimeError. ASSERT(CritCheckIn(&m_pRenderer->m_InterfaceLock)); m_bRunTimeError = FALSE; return m_pRenderer->Inactive(); } // Tell derived classes about the media type agreed HRESULT CRendererInputPin::SetMediaType(const CMediaType *pmt) { HRESULT hr = CBaseInputPin::SetMediaType(pmt); if (FAILED(hr)) { return hr; } return m_pRenderer->SetMediaType(pmt); } // We do not keep an event object to use when setting up a timer link with // the clock but are given a pointer to one by the owning object through the // SetNotificationObject method - this must be initialised before starting // We can override the default quality management process to have it always // draw late frames, this is currently done by having the following registry // key (actually an INI key) called DrawLateFrames set to 1 (default is 0) const TCHAR AMQUALITY[] = TEXT("ActiveMovie"); const TCHAR DRAWLATEFRAMES[] = TEXT("DrawLateFrames"); CBaseVideoRenderer::CBaseVideoRenderer(REFCLSID RenderClass, // CLSID for this renderer __in_opt LPCTSTR pName, // Debug ONLY description __inout_opt LPUNKNOWN pUnk, // Aggregated owner object __inout HRESULT *phr) : // General OLE return code CBaseRenderer(RenderClass, pName, pUnk, phr) , m_cFramesDropped(0) , m_cFramesDrawn(0) , m_bSupplierHandlingQuality(FALSE) { ResetStreamingTimes(); #ifdef PERF m_idTimeStamp = MSR_REGISTER(TEXT("Frame time stamp")); m_idEarliness = MSR_REGISTER(TEXT("Earliness fudge")); m_idTarget = MSR_REGISTER(TEXT("Target (mSec)")); m_idSchLateTime = MSR_REGISTER(TEXT("mSec late when scheduled")); m_idDecision = MSR_REGISTER(TEXT("Scheduler decision code")); m_idQualityRate = MSR_REGISTER(TEXT("Quality rate sent")); m_idQualityTime = MSR_REGISTER(TEXT("Quality time sent")); m_idWaitReal = MSR_REGISTER(TEXT("Render wait")); // m_idWait = MSR_REGISTER(TEXT("wait time recorded (msec)")); m_idFrameAccuracy = MSR_REGISTER(TEXT("Frame accuracy (msecs)")); m_bDrawLateFrames = GetProfileInt(AMQUALITY, DRAWLATEFRAMES, FALSE); // m_idSendQuality = MSR_REGISTER(TEXT("Processing Quality message")); m_idRenderAvg = MSR_REGISTER(TEXT("Render draw time Avg")); m_idFrameAvg = MSR_REGISTER(TEXT("FrameAvg")); m_idWaitAvg = MSR_REGISTER(TEXT("WaitAvg")); m_idDuration = MSR_REGISTER(TEXT("Duration")); m_idThrottle = MSR_REGISTER(TEXT("Audio-video throttle wait")); // m_idDebug = MSR_REGISTER(TEXT("Debug stuff")); #endif // PERF } // Constructor // Destructor is just a placeholder CBaseVideoRenderer::~CBaseVideoRenderer() { ASSERT(m_dwAdvise == 0); } // The timing functions in this class are called by the window object and by // the renderer's allocator. // The windows object calls timing functions as it receives media sample // images for drawing using GDI. // The allocator calls timing functions when it starts passing DCI/DirectDraw // surfaces which are not rendered in the same way; The decompressor writes // directly to the surface with no separate rendering, so those code paths // call direct into us. Since we only ever hand out DCI/DirectDraw surfaces // when we have allocated one and only one image we know there cannot be any // conflict between the two. // // We use timeGetTime to return the timing counts we use (since it's relative // performance we are interested in rather than absolute compared to a clock) // The window object sets the accuracy of the system clock (normally 1ms) by // calling timeBeginPeriod/timeEndPeriod when it changes streaming states // Reset all times controlling streaming. // Set them so that // 1. Frames will not initially be dropped // 2. The first frame will definitely be drawn (achieved by saying that there // has not ben a frame drawn for a long time). HRESULT CBaseVideoRenderer::ResetStreamingTimes() { m_trLastDraw = -1000; // set up as first frame since ages (1 sec) ago m_tStreamingStart = timeGetTime(); m_trRenderAvg = 0; m_trFrameAvg = -1; // -1000 fps == "unset" m_trDuration = 0; // 0 - strange value m_trRenderLast = 0; m_trWaitAvg = 0; m_tRenderStart = 0; m_cFramesDrawn = 0; m_cFramesDropped = 0; m_iTotAcc = 0; m_iSumSqAcc = 0; m_iSumSqFrameTime = 0; m_trFrame = 0; // hygeine - not really needed m_trLate = 0; // hygeine - not really needed m_iSumFrameTime = 0; m_nNormal = 0; m_trEarliness = 0; m_trTarget = -300000; // 30mSec early m_trThrottle = 0; m_trRememberStampForPerf = 0; #ifdef PERF m_trRememberFrameForPerf = 0; #endif return NOERROR; } // ResetStreamingTimes // Reset all times controlling streaming. Note that we're now streaming. We // don't need to set the rendering event to have the source filter released // as it is done during the Run processing. When we are run we immediately // release the source filter thread and draw any image waiting (that image // may already have been drawn once as a poster frame while we were paused) HRESULT CBaseVideoRenderer::OnStartStreaming() { ResetStreamingTimes(); return NOERROR; } // OnStartStreaming // Called at end of streaming. Fixes times for property page report HRESULT CBaseVideoRenderer::OnStopStreaming() { m_tStreamingStart = timeGetTime() - m_tStreamingStart; return NOERROR; } // OnStopStreaming // Called when we start waiting for a rendering event. // Used to update times spent waiting and not waiting. void CBaseVideoRenderer::OnWaitStart() { MSR_START(m_idWaitReal); } // OnWaitStart // Called when we are awoken from the wait in the window OR by our allocator // when it is hanging around until the next sample is due for rendering on a // DCI/DirectDraw surface. We add the wait time into our rolling average. // We grab the interface lock so that we're serialised with the application // thread going through the run code - which in due course ends up calling // ResetStreaming times - possibly as we run through this section of code void CBaseVideoRenderer::OnWaitEnd() { #ifdef PERF MSR_STOP(m_idWaitReal); // for a perf build we want to know just exactly how late we REALLY are. // even if this means that we have to look at the clock again. REFERENCE_TIME trRealStream; // the real time now expressed as stream time. #if 0 m_pClock->GetTime(&trRealStream); // Calling clock here causes W95 deadlock! #else // We will be discarding overflows like mad here! // This is wrong really because timeGetTime() can wrap but it's // only for PERF REFERENCE_TIME tr = timeGetTime() * 10000; trRealStream = tr + m_llTimeOffset; #endif trRealStream -= m_tStart; // convert to stream time (this is a reftime) if (m_trRememberStampForPerf == 0) { // This is probably the poster frame at the start, and it is not scheduled // in the usual way at all. Just count it. The rememberstamp gets set // in ShouldDrawSampleNow, so this does invalid frame recording until we // actually start playing. PreparePerformanceData(0, 0); } else { int trLate = (int)(trRealStream - m_trRememberStampForPerf); int trFrame = (int)(tr - m_trRememberFrameForPerf); PreparePerformanceData(trLate, trFrame); } m_trRememberFrameForPerf = tr; #endif // PERF } // OnWaitEnd // Put data on one side that describes the lateness of the current frame. // We don't yet know whether it will actually be drawn. In direct draw mode, // this decision is up to the filter upstream, and it could change its mind. // The rules say that if it did draw it must call Receive(). One way or // another we eventually get into either OnRenderStart or OnDirectRender and // these both call RecordFrameLateness to update the statistics. void CBaseVideoRenderer::PreparePerformanceData(int trLate, int trFrame) { m_trLate = trLate; m_trFrame = trFrame; } // PreparePerformanceData // update the statistics: // m_iTotAcc, m_iSumSqAcc, m_iSumSqFrameTime, m_iSumFrameTime, m_cFramesDrawn // Note that because the properties page reports using these variables, // 1. We need to be inside a critical section // 2. They must all be updated together. Updating the sums here and the count // elsewhere can result in imaginary jitter (i.e. attempts to find square roots // of negative numbers) in the property page code. void CBaseVideoRenderer::RecordFrameLateness(int trLate, int trFrame) { // Record how timely we are. int tLate = trLate / 10000; // Best estimate of moment of appearing on the screen is average of // start and end draw times. Here we have only the end time. This may // tend to show us as spuriously late by up to 1/2 frame rate achieved. // Decoder probably monitors draw time. We don't bother. MSR_INTEGER(m_idFrameAccuracy, tLate); // This is a kludge - we can get frames that are very late // especially (at start-up) and they invalidate the statistics. // So ignore things that are more than 1 sec off. if (tLate > 1000 || tLate < -1000) { if (m_cFramesDrawn <= 1) { tLate = 0; } else if (tLate > 0) { tLate = 1000; } else { tLate = -1000; } } // The very first frame often has a invalid time, so don't // count it into the statistics. (???) if (m_cFramesDrawn > 1) { m_iTotAcc += tLate; m_iSumSqAcc += (tLate * tLate); } // calculate inter-frame time. Doesn't make sense for first frame // second frame suffers from invalid first frame stamp. if (m_cFramesDrawn > 2) { int tFrame = trFrame / 10000; // convert to mSec else it overflows // This is a kludge. It can overflow anyway (a pause can cause // a very long inter-frame time) and it overflows at 2**31/10**7 // or about 215 seconds i.e. 3min 35sec if (tFrame > 1000 || tFrame < 0) tFrame = 1000; m_iSumSqFrameTime += tFrame * tFrame; ASSERT(m_iSumSqFrameTime >= 0); m_iSumFrameTime += tFrame; } ++m_cFramesDrawn; } // RecordFrameLateness void CBaseVideoRenderer::ThrottleWait() { if (m_trThrottle > 0) { int iThrottle = m_trThrottle / 10000; // convert to mSec MSR_INTEGER(m_idThrottle, iThrottle); DbgLog((LOG_TRACE, 0, TEXT("Throttle %d ms"), iThrottle)); Sleep(iThrottle); } else { Sleep(0); } } // ThrottleWait // Whenever a frame is rendered it goes though either OnRenderStart // or OnDirectRender. Data that are generated during ShouldDrawSample // are added to the statistics by calling RecordFrameLateness from both // these two places. // Called in place of OnRenderStart..OnRenderEnd // When a DirectDraw image is drawn void CBaseVideoRenderer::OnDirectRender(IMediaSample *pMediaSample) { m_trRenderAvg = 0; m_trRenderLast = 5000000; // If we mode switch, we do NOT want this // to inhibit the new average getting going! // so we set it to half a second // MSR_INTEGER(m_idRenderAvg, m_trRenderAvg/10000); RecordFrameLateness(m_trLate, m_trFrame); ThrottleWait(); } // OnDirectRender // Called just before we start drawing. All we do is to get the current clock // time (from the system) and return. We have to store the start render time // in a member variable because it isn't used until we complete the drawing // The rest is just performance logging. void CBaseVideoRenderer::OnRenderStart(IMediaSample *pMediaSample) { RecordFrameLateness(m_trLate, m_trFrame); m_tRenderStart = timeGetTime(); } // OnRenderStart // Called directly after drawing an image. We calculate the time spent in the // drawing code and if this doesn't appear to have any odd looking spikes in // it then we add it to the current average draw time. Measurement spikes may // occur if the drawing thread is interrupted and switched to somewhere else. void CBaseVideoRenderer::OnRenderEnd(IMediaSample *pMediaSample) { // The renderer time can vary erratically if we are interrupted so we do // some smoothing to help get more sensible figures out but even that is // not enough as figures can go 9,10,9,9,83,9 and we must disregard 83 int tr = (timeGetTime() - m_tRenderStart) * 10000; // convert mSec->UNITS if (tr < m_trRenderAvg * 2 || tr < 2 * m_trRenderLast) { // DO_MOVING_AVG(m_trRenderAvg, tr); m_trRenderAvg = (tr + (AVGPERIOD - 1) * m_trRenderAvg) / AVGPERIOD; } m_trRenderLast = tr; ThrottleWait(); } // OnRenderEnd STDMETHODIMP CBaseVideoRenderer::SetSink(IQualityControl *piqc) { m_pQSink = piqc; return NOERROR; } // SetSink STDMETHODIMP CBaseVideoRenderer::Notify(IBaseFilter *pSelf, Quality q) { // NOTE: We are NOT getting any locks here. We could be called // asynchronously and possibly even on a time critical thread of // someone else's - so we do the minumum. We only set one state // variable (an integer) and if that happens to be in the middle // of another thread reading it they will just get either the new // or the old value. Locking would achieve no more than this. // It might be nice to check that we are being called from m_pGraph, but // it turns out to be a millisecond or so per throw! // This is heuristics, these numbers are aimed at being "what works" // rather than anything based on some theory. // We use a hyperbola because it's easy to calculate and it includes // a panic button asymptote (which we push off just to the left) // The throttling fits the following table (roughly) // Proportion Throttle (msec) // >=1000 0 // 900 3 // 800 7 // 700 11 // 600 17 // 500 25 // 400 35 // 300 50 // 200 72 // 125 100 // 100 112 // 50 146 // 0 200 // (some evidence that we could go for a sharper kink - e.g. no throttling // until below the 750 mark - might give fractionally more frames on a // P60-ish machine). The easy way to get these coefficients is to use // Renbase.xls follow the instructions therein using excel solver. if (q.Proportion >= 1000) { m_trThrottle = 0; } else { // The DWORD is to make quite sure I get unsigned arithmetic // as the constant is between 2**31 and 2**32 m_trThrottle = -330000 + (388880000 / (q.Proportion + 167)); } return NOERROR; } // Notify // Send a message to indicate what our supplier should do about quality. // Theory: // What a supplier wants to know is "is the frame I'm working on NOW // going to be late?". // F1 is the frame at the supplier (as above) // Tf1 is the due time for F1 // T1 is the time at that point (NOW!) // Tr1 is the time that f1 WILL actually be rendered // L1 is the latency of the graph for frame F1 = Tr1-T1 // D1 (for delay) is how late F1 will be beyond its due time i.e. // D1 = (Tr1-Tf1) which is what the supplier really wants to know. // Unfortunately Tr1 is in the future and is unknown, so is L1 // // We could estimate L1 by its value for a previous frame, // L0 = Tr0-T0 and work off // D1' = ((T1+L0)-Tf1) = (T1 + (Tr0-T0) -Tf1) // Rearranging terms: // D1' = (T1-T0) + (Tr0-Tf1) // adding (Tf0-Tf0) and rearranging again: // = (T1-T0) + (Tr0-Tf0) + (Tf0-Tf1) // = (T1-T0) - (Tf1-Tf0) + (Tr0-Tf0) // But (Tr0-Tf0) is just D0 - how late frame zero was, and this is the // Late field in the quality message that we send. // The other two terms just state what correction should be applied before // using the lateness of F0 to predict the lateness of F1. // (T1-T0) says how much time has actually passed (we have lost this much) // (Tf1-Tf0) says how much time should have passed if we were keeping pace // (we have gained this much). // // Suppliers should therefore work off: // Quality.Late + (T1-T0) - (Tf1-Tf0) // and see if this is "acceptably late" or even early (i.e. negative). // They get T1 and T0 by polling the clock, they get Tf1 and Tf0 from // the time stamps in the frames. They get Quality.Late from us. // HRESULT CBaseVideoRenderer::SendQuality(REFERENCE_TIME trLate, REFERENCE_TIME trRealStream) { Quality q; HRESULT hr; // If we are the main user of time, then report this as Flood/Dry. // If our suppliers are, then report it as Famine/Glut. // // We need to take action, but avoid hunting. Hunting is caused by // 1. Taking too much action too soon and overshooting // 2. Taking too long to react (so averaging can CAUSE hunting). // // The reason why we use trLate as well as Wait is to reduce hunting; // if the wait time is coming down and about to go into the red, we do // NOT want to rely on some average which is only telling is that it used // to be OK once. q.TimeStamp = (REFERENCE_TIME)trRealStream; if (m_trFrameAvg < 0) { q.Type = Famine; // guess } // Is the greater part of the time taken bltting or something else else if (m_trFrameAvg > 2 * m_trRenderAvg) { q.Type = Famine; // mainly other } else { q.Type = Flood; // mainly bltting } q.Proportion = 1000; // default if (m_trFrameAvg < 0) { // leave it alone - we don't know enough } else if (trLate > 0) { // try to catch up over the next second // We could be Really, REALLY late, but rendering all the frames // anyway, just because it's so cheap. q.Proportion = 1000 - (int)((trLate) / (UNITS / 1000)); if (q.Proportion < 500) { q.Proportion = 500; // don't go daft. (could've been negative!) } else { } } else if (m_trWaitAvg > 20000 && trLate < -20000) { // Go cautiously faster - aim at 2mSec wait. if (m_trWaitAvg >= m_trFrameAvg) { // This can happen because of some fudges. // The waitAvg is how long we originally planned to wait // The frameAvg is more honest. // It means that we are spending a LOT of time waiting q.Proportion = 2000; // double. } else { if (m_trFrameAvg + 20000 > m_trWaitAvg) { q.Proportion = 1000 * (m_trFrameAvg / (m_trFrameAvg + 20000 - m_trWaitAvg)); } else { // We're apparently spending more than the whole frame time waiting. // Assume that the averages are slightly out of kilter, but that we // are indeed doing a lot of waiting. (This leg probably never // happens, but the code avoids any potential divide by zero). q.Proportion = 2000; } } if (q.Proportion > 2000) { q.Proportion = 2000; // don't go crazy. } } // Tell the supplier how late frames are when they get rendered // That's how late we are now. // If we are in directdraw mode then the guy upstream can see the drawing // times and we'll just report on the start time. He can figure out any // offset to apply. If we are in DIB Section mode then we will apply an // extra offset which is half of our drawing time. This is usually small // but can sometimes be the dominant effect. For this we will use the // average drawing time rather than the last frame. If the last frame took // a long time to draw and made us late, that's already in the lateness // figure. We should not add it in again unless we expect the next frame // to be the same. We don't, we expect the average to be a better shot. // In direct draw mode the RenderAvg will be zero. q.Late = trLate + m_trRenderAvg / 2; // log what we're doing MSR_INTEGER(m_idQualityRate, q.Proportion); MSR_INTEGER(m_idQualityTime, (int)q.Late / 10000); // A specific sink interface may be set through IPin if (m_pQSink == NULL) { // Get our input pin's peer. We send quality management messages // to any nominated receiver of these things (set in the IPin // interface), or else to our source filter. IQualityControl *pQC = NULL; IPin *pOutputPin = m_pInputPin->GetConnected(); ASSERT(pOutputPin != NULL); // And get an AddRef'd quality control interface hr = pOutputPin->QueryInterface(IID_IQualityControl, (void **)&pQC); if (SUCCEEDED(hr)) { m_pQSink = pQC; } } if (m_pQSink) { return m_pQSink->Notify(this, q); } return S_FALSE; } // SendQuality // We are called with a valid IMediaSample image to decide whether this is to // be drawn or not. There must be a reference clock in operation. // Return S_OK if it is to be drawn Now (as soon as possible) // Return S_FALSE if it is to be drawn when it's due // Return an error if we want to drop it // m_nNormal=-1 indicates that we dropped the previous frame and so this // one should be drawn early. Respect it and update it. // Use current stream time plus a number of heuristics (detailed below) // to make the decision HRESULT CBaseVideoRenderer::ShouldDrawSampleNow(IMediaSample *pMediaSample, __inout REFERENCE_TIME *ptrStart, __inout REFERENCE_TIME *ptrEnd) { // Don't call us unless there's a clock interface to synchronise with ASSERT(m_pClock); MSR_INTEGER(m_idTimeStamp, (int)((*ptrStart) >> 32)); // high order 32 bits MSR_INTEGER(m_idTimeStamp, (int)(*ptrStart)); // low order 32 bits // We lose a bit of time depending on the monitor type waiting for the next // screen refresh. On average this might be about 8mSec - so it will be // later than we think when the picture appears. To compensate a bit // we bias the media samples by -8mSec i.e. 80000 UNITs. // We don't ever make a stream time negative (call it paranoia) if (*ptrStart >= 80000) { *ptrStart -= 80000; *ptrEnd -= 80000; // bias stop to to retain valid frame duration } // Cache the time stamp now. We will want to compare what we did with what // we started with (after making the monitor allowance). m_trRememberStampForPerf = *ptrStart; // Get reference times (current and late) REFERENCE_TIME trRealStream; // the real time now expressed as stream time. m_pClock->GetTime(&trRealStream); #ifdef PERF // While the reference clock is expensive: // Remember the offset from timeGetTime and use that. // This overflows all over the place, but when we subtract to get // differences the overflows all cancel out. m_llTimeOffset = trRealStream - timeGetTime() * 10000; #endif trRealStream -= m_tStart; // convert to stream time (this is a reftime) // We have to wory about two versions of "lateness". The truth, which we // try to work out here and the one measured against m_trTarget which // includes long term feedback. We report statistics against the truth // but for operational decisions we work to the target. // We use TimeDiff to make sure we get an integer because we // may actually be late (or more likely early if there is a big time // gap) by a very long time. const int trTrueLate = TimeDiff(trRealStream - *ptrStart); const int trLate = trTrueLate; MSR_INTEGER(m_idSchLateTime, trTrueLate / 10000); // Send quality control messages upstream, measured against target HRESULT hr = SendQuality(trLate, trRealStream); // Note: the filter upstream is allowed to this FAIL meaning "you do it". m_bSupplierHandlingQuality = (hr == S_OK); // Decision time! Do we drop, draw when ready or draw immediately? const int trDuration = (int)(*ptrEnd - *ptrStart); { // We need to see if the frame rate of the file has just changed. // This would make comparing our previous frame rate with the current // frame rate inefficent. Hang on a moment though. I've seen files // where the frames vary between 33 and 34 mSec so as to average // 30fps. A minor variation like that won't hurt us. int t = m_trDuration / 32; if (trDuration > m_trDuration + t || trDuration < m_trDuration - t) { // There's a major variation. Reset the average frame rate to // exactly the current rate to disable decision 9002 for this frame, // and remember the new rate. m_trFrameAvg = trDuration; m_trDuration = trDuration; } } MSR_INTEGER(m_idEarliness, m_trEarliness / 10000); MSR_INTEGER(m_idRenderAvg, m_trRenderAvg / 10000); MSR_INTEGER(m_idFrameAvg, m_trFrameAvg / 10000); MSR_INTEGER(m_idWaitAvg, m_trWaitAvg / 10000); MSR_INTEGER(m_idDuration, trDuration / 10000); #ifdef PERF if (S_OK == pMediaSample->IsDiscontinuity()) { MSR_INTEGER(m_idDecision, 9000); } #endif // Control the graceful slide back from slow to fast machine mode. // After a frame drop accept an early frame and set the earliness to here // If this frame is already later than the earliness then slide it to here // otherwise do the standard slide (reduce by about 12% per frame). // Note: earliness is normally NEGATIVE BOOL bJustDroppedFrame = (m_bSupplierHandlingQuality // Can't use the pin sample properties because we might // not be in Receive when we call this && (S_OK == pMediaSample->IsDiscontinuity()) // he just dropped one ) || (m_nNormal == -1); // we just dropped one // Set m_trEarliness (slide back from slow to fast machine mode) if (trLate > 0) { m_trEarliness = 0; // we are no longer in fast machine mode at all! } else if ((trLate >= m_trEarliness) || bJustDroppedFrame) { m_trEarliness = trLate; // Things have slipped of their own accord } else { m_trEarliness = m_trEarliness - m_trEarliness / 8; // graceful slide } // prepare the new wait average - but don't pollute the old one until // we have finished with it. int trWaitAvg; { // We never mix in a negative wait. This causes us to believe in fast machines // slightly more. int trL = trLate < 0 ? -trLate : 0; trWaitAvg = (trL + m_trWaitAvg * (AVGPERIOD - 1)) / AVGPERIOD; } int trFrame; { REFERENCE_TIME tr = trRealStream - m_trLastDraw; // Cd be large - 4 min pause! if (tr > 10000000) { tr = 10000000; // 1 second - arbitrarily. } trFrame = int(tr); } // We will DRAW this frame IF... if ( // ...the time we are spending drawing is a small fraction of the total // observed inter-frame time so that dropping it won't help much. (3 * m_trRenderAvg <= m_trFrameAvg) // ...or our supplier is NOT handling things and the next frame would // be less timely than this one or our supplier CLAIMS to be handling // things, and is now less than a full FOUR frames late. || (m_bSupplierHandlingQuality ? (trLate <= trDuration * 4) : (trLate + trLate < trDuration)) // ...or we are on average waiting for over eight milliseconds then // this may be just a glitch. Draw it and we'll hope to catch up. || (m_trWaitAvg > 80000) // ...or we haven't drawn an image for over a second. We will update // the display, which stops the video looking hung. // Do this regardless of how late this media sample is. || ((trRealStream - m_trLastDraw) > UNITS) ) { HRESULT Result; // We are going to play this frame. We may want to play it early. // We will play it early if we think we are in slow machine mode. // If we think we are NOT in slow machine mode, we will still play // it early by m_trEarliness as this controls the graceful slide back. // and in addition we aim at being m_trTarget late rather than "on time". BOOL bPlayASAP = FALSE; // we will play it AT ONCE (slow machine mode) if... // ...we are playing catch-up if (bJustDroppedFrame) { bPlayASAP = TRUE; MSR_INTEGER(m_idDecision, 9001); } // ...or if we are running below the true frame rate // exact comparisons are glitchy, for these measurements, // so add an extra 5% or so else if ((m_trFrameAvg > trDuration + trDuration / 16) // It's possible to get into a state where we are losing ground, but // are a very long way ahead. To avoid this or recover from it // we refuse to play early by more than 10 frames. && (trLate > -trDuration * 10)) { bPlayASAP = TRUE; MSR_INTEGER(m_idDecision, 9002); } #if 0 // ...or if we have been late and are less than one frame early else if ( (trLate + trDuration > 0) && (m_trWaitAvg<=20000) ) { bPlayASAP = TRUE; MSR_INTEGER(m_idDecision, 9003); } #endif // We will NOT play it at once if we are grossly early. On very slow frame // rate movies - e.g. clock.avi - it is not a good idea to leap ahead just // because we got starved (for instance by the net) and dropped one frame // some time or other. If we are more than 900mSec early, then wait. if (trLate < -9000000) { bPlayASAP = FALSE; } if (bPlayASAP) { m_nNormal = 0; MSR_INTEGER(m_idDecision, 0); // When we are here, we are in slow-machine mode. trLate may well // oscillate between negative and positive when the supplier is // dropping frames to keep sync. We should not let that mislead // us into thinking that we have as much as zero spare time! // We just update with a zero wait. m_trWaitAvg = (m_trWaitAvg * (AVGPERIOD - 1)) / AVGPERIOD; // Assume that we draw it immediately. Update inter-frame stats m_trFrameAvg = (trFrame + m_trFrameAvg * (AVGPERIOD - 1)) / AVGPERIOD; #ifndef PERF // If this is NOT a perf build, then report what we know so far // without looking at the clock any more. This assumes that we // actually wait for exactly the time we hope to. It also reports // how close we get to the manipulated time stamps that we now have // rather than the ones we originally started with. It will // therefore be a little optimistic. However it's fast. PreparePerformanceData(trTrueLate, trFrame); #endif m_trLastDraw = trRealStream; if (m_trEarliness > trLate) { m_trEarliness = trLate; // if we are actually early, this is neg } Result = S_OK; // Draw it now } else { ++m_nNormal; // Set the average frame rate to EXACTLY the ideal rate. // If we are exiting slow-machine mode then we will have caught up // and be running ahead, so as we slide back to exact timing we will // have a longer than usual gap at this point. If we record this // real gap then we'll think that we're running slow and go back // into slow-machine mode and vever get it straight. m_trFrameAvg = trDuration; MSR_INTEGER(m_idDecision, 1); // Play it early by m_trEarliness and by m_trTarget { int trE = m_trEarliness; if (trE < -m_trFrameAvg) { trE = -m_trFrameAvg; } *ptrStart += trE; // N.B. earliness is negative } int Delay = -trTrueLate; Result = Delay <= 0 ? S_OK : S_FALSE; // OK = draw now, FALSE = wait m_trWaitAvg = trWaitAvg; // Predict when it will actually be drawn and update frame stats if (Result == S_FALSE) { // We are going to wait trFrame = TimeDiff(*ptrStart - m_trLastDraw); m_trLastDraw = *ptrStart; } else { // trFrame is already = trRealStream-m_trLastDraw; m_trLastDraw = trRealStream; } #ifndef PERF int iAccuracy; if (Delay > 0) { // Report lateness based on when we intend to play it iAccuracy = TimeDiff(*ptrStart - m_trRememberStampForPerf); } else { // Report lateness based on playing it *now*. iAccuracy = trTrueLate; // trRealStream-RememberStampForPerf; } PreparePerformanceData(iAccuracy, trFrame); #endif } return Result; } // We are going to drop this frame! // Of course in DirectDraw mode the guy upstream may draw it anyway. // This will probably give a large negative wack to the wait avg. m_trWaitAvg = trWaitAvg; #ifdef PERF // Respect registry setting - debug only! if (m_bDrawLateFrames) { return S_OK; // draw it when it's ready } // even though it's late. #endif // We are going to drop this frame so draw the next one early // n.b. if the supplier is doing direct draw then he may draw it anyway // but he's doing something funny to arrive here in that case. MSR_INTEGER(m_idDecision, 2); m_nNormal = -1; return E_FAIL; // drop it } // ShouldDrawSampleNow // NOTE we're called by both the window thread and the source filter thread // so we have to be protected by a critical section (locked before called) // Also, when the window thread gets signalled to render an image, it always // does so regardless of how late it is. All the degradation is done when we // are scheduling the next sample to be drawn. Hence when we start an advise // link to draw a sample, that sample's time will always become the last one // drawn - unless of course we stop streaming in which case we cancel links BOOL CBaseVideoRenderer::ScheduleSample(IMediaSample *pMediaSample) { // We override ShouldDrawSampleNow to add quality management BOOL bDrawImage = CBaseRenderer::ScheduleSample(pMediaSample); if (bDrawImage == FALSE) { ++m_cFramesDropped; return FALSE; } // m_cFramesDrawn must NOT be updated here. It has to be updated // in RecordFrameLateness at the same time as the other statistics. return TRUE; } // Implementation of IQualProp interface needed to support the property page // This is how the property page gets the data out of the scheduler. We are // passed into the constructor the owning object in the COM sense, this will // either be the video renderer or an external IUnknown if we're aggregated. // We initialise our CUnknown base class with this interface pointer. Then // all we have to do is to override NonDelegatingQueryInterface to expose // our IQualProp interface. The AddRef and Release are handled automatically // by the base class and will be passed on to the appropriate outer object STDMETHODIMP CBaseVideoRenderer::get_FramesDroppedInRenderer(__out int *pcFramesDropped) { CheckPointer(pcFramesDropped, E_POINTER); CAutoLock cVideoLock(&m_InterfaceLock); *pcFramesDropped = m_cFramesDropped; return NOERROR; } // get_FramesDroppedInRenderer // Set *pcFramesDrawn to the number of frames drawn since // streaming started. STDMETHODIMP CBaseVideoRenderer::get_FramesDrawn(int *pcFramesDrawn) { CheckPointer(pcFramesDrawn, E_POINTER); CAutoLock cVideoLock(&m_InterfaceLock); *pcFramesDrawn = m_cFramesDrawn; return NOERROR; } // get_FramesDrawn // Set iAvgFrameRate to the frames per hundred secs since // streaming started. 0 otherwise. STDMETHODIMP CBaseVideoRenderer::get_AvgFrameRate(int *piAvgFrameRate) { CheckPointer(piAvgFrameRate, E_POINTER); CAutoLock cVideoLock(&m_InterfaceLock); int t; if (m_bStreaming) { t = timeGetTime() - m_tStreamingStart; } else { t = m_tStreamingStart; } if (t <= 0) { *piAvgFrameRate = 0; ASSERT(m_cFramesDrawn == 0); } else { // i is frames per hundred seconds *piAvgFrameRate = MulDiv(100000, m_cFramesDrawn, t); } return NOERROR; } // get_AvgFrameRate // Set *piAvg to the average sync offset since streaming started // in mSec. The sync offset is the time in mSec between when the frame // should have been drawn and when the frame was actually drawn. STDMETHODIMP CBaseVideoRenderer::get_AvgSyncOffset(__out int *piAvg) { CheckPointer(piAvg, E_POINTER); CAutoLock cVideoLock(&m_InterfaceLock); if (NULL == m_pClock) { *piAvg = 0; return NOERROR; } // Note that we didn't gather the stats on the first frame // so we use m_cFramesDrawn-1 here if (m_cFramesDrawn <= 1) { *piAvg = 0; } else { *piAvg = (int)(m_iTotAcc / (m_cFramesDrawn - 1)); } return NOERROR; } // get_AvgSyncOffset // To avoid dragging in the maths library - a cheap // approximate integer square root. // We do this by getting a starting guess which is between 1 // and 2 times too large, followed by THREE iterations of // Newton Raphson. (That will give accuracy to the nearest mSec // for the range in question - roughly 0..1000) // // It would be faster to use a linear interpolation and ONE NR, but // who cares. If anyone does - the best linear interpolation is // to approximates sqrt(x) by // y = x * (sqrt(2)-1) + 1 - 1/sqrt(2) + 1/(8*(sqrt(2)-1)) // 0r y = x*0.41421 + 0.59467 // This minimises the maximal error in the range in question. // (error is about +0.008883 and then one NR will give error .0000something // (Of course these are integers, so you can't just multiply by 0.41421 // you'd have to do some sort of MulDiv). // Anyone wanna check my maths? (This is only for a property display!) int isqrt(int x) { int s = 1; // Make s an initial guess for sqrt(x) if (x > 0x40000000) { s = 0x8000; // prevent any conceivable closed loop } else { while (s * s < x) { // loop cannot possible go more than 31 times s = 2 * s; // normally it goes about 6 times } // Three NR iterations. if (x == 0) { s = 0; // Wouldn't it be tragic to divide by zero whenever our // accuracy was perfect! } else { s = (s * s + x) / (2 * s); if (s >= 0) s = (s * s + x) / (2 * s); if (s >= 0) s = (s * s + x) / (2 * s); } } return s; } // // Do estimates for standard deviations for per-frame // statistics // HRESULT CBaseVideoRenderer::GetStdDev(int nSamples, __out int *piResult, LONGLONG llSumSq, LONGLONG iTot) { CheckPointer(piResult, E_POINTER); CAutoLock cVideoLock(&m_InterfaceLock); if (NULL == m_pClock) { *piResult = 0; return NOERROR; } // If S is the Sum of the Squares of observations and // T the Total (i.e. sum) of the observations and there were // N observations, then an estimate of the standard deviation is // sqrt( (S - T**2/N) / (N-1) ) if (nSamples <= 1) { *piResult = 0; } else { LONGLONG x; // First frames have invalid stamps, so we get no stats for them // So we need 2 frames to get 1 datum, so N is cFramesDrawn-1 // so we use m_cFramesDrawn-1 here x = llSumSq - llMulDiv(iTot, iTot, nSamples, 0); x = x / (nSamples - 1); ASSERT(x >= 0); *piResult = isqrt((LONG)x); } return NOERROR; } // Set *piDev to the standard deviation in mSec of the sync offset // of each frame since streaming started. STDMETHODIMP CBaseVideoRenderer::get_DevSyncOffset(__out int *piDev) { // First frames have invalid stamps, so we get no stats for them // So we need 2 frames to get 1 datum, so N is cFramesDrawn-1 return GetStdDev(m_cFramesDrawn - 1, piDev, m_iSumSqAcc, m_iTotAcc); } // get_DevSyncOffset // Set *piJitter to the standard deviation in mSec of the inter-frame time // of frames since streaming started. STDMETHODIMP CBaseVideoRenderer::get_Jitter(__out int *piJitter) { // First frames have invalid stamps, so we get no stats for them // So second frame gives invalid inter-frame time // So we need 3 frames to get 1 datum, so N is cFramesDrawn-2 return GetStdDev(m_cFramesDrawn - 2, piJitter, m_iSumSqFrameTime, m_iSumFrameTime); } // get_Jitter // Overidden to return our IQualProp interface STDMETHODIMP CBaseVideoRenderer::NonDelegatingQueryInterface(REFIID riid, __deref_out VOID **ppv) { // We return IQualProp and delegate everything else if (riid == IID_IQualProp) { return GetInterface((IQualProp *)this, ppv); } else if (riid == IID_IQualityControl) { return GetInterface((IQualityControl *)this, ppv); } return CBaseRenderer::NonDelegatingQueryInterface(riid, ppv); } // Override JoinFilterGraph so that, just before leaving // the graph we can send an EC_WINDOW_DESTROYED event STDMETHODIMP CBaseVideoRenderer::JoinFilterGraph(__inout_opt IFilterGraph *pGraph, __in_opt LPCWSTR pName) { // Since we send EC_ACTIVATE, we also need to ensure // we send EC_WINDOW_DESTROYED or the resource manager may be // holding us as a focus object if (!pGraph && m_pGraph) { // We were in a graph and now we're not // Do this properly in case we are aggregated IBaseFilter *pFilter = this; NotifyEvent(EC_WINDOW_DESTROYED, (LPARAM)pFilter, 0); } return CBaseFilter::JoinFilterGraph(pGraph, pName); } // This removes a large number of level 4 warnings from the // Microsoft compiler which in this case are not very useful #pragma warning(disable : 4514) ================================================ FILE: common/baseclasses/renbase.h ================================================ //------------------------------------------------------------------------------ // File: RenBase.h // // Desc: DirectShow base classes - defines a generic ActiveX base renderer // class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __RENBASE__ #define __RENBASE__ // Forward class declarations class CBaseRenderer; class CBaseVideoRenderer; class CRendererInputPin; // This is our input pin class that channels calls to the renderer class CRendererInputPin : public CBaseInputPin { protected: CBaseRenderer *m_pRenderer; public: CRendererInputPin(__inout CBaseRenderer *pRenderer, __inout HRESULT *phr, __in_opt LPCWSTR Name); // Overriden from the base pin classes HRESULT BreakConnect(); HRESULT CompleteConnect(IPin *pReceivePin); HRESULT SetMediaType(const CMediaType *pmt); HRESULT CheckMediaType(const CMediaType *pmt); HRESULT Active(); HRESULT Inactive(); // Add rendering behaviour to interface functions STDMETHODIMP QueryId(__deref_out LPWSTR *Id); STDMETHODIMP EndOfStream(); STDMETHODIMP BeginFlush(); STDMETHODIMP EndFlush(); STDMETHODIMP Receive(IMediaSample *pMediaSample); // Helper IMemAllocator inline *Allocator() const { return m_pAllocator; } }; // Main renderer class that handles synchronisation and state changes class CBaseRenderer : public CBaseFilter { protected: friend class CRendererInputPin; friend void CALLBACK EndOfStreamTimer(UINT uID, // Timer identifier UINT uMsg, // Not currently used DWORD_PTR dwUser, // User information DWORD_PTR dw1, // Windows reserved DWORD_PTR dw2); // Is also reserved CRendererPosPassThru *m_pPosition; // Media seeking pass by object CAMEvent m_RenderEvent; // Used to signal timer events CAMEvent m_ThreadSignal; // Signalled to release worker thread CAMEvent m_evComplete; // Signalled when state complete BOOL m_bAbort; // Stop us from rendering more data BOOL m_bStreaming; // Are we currently streaming DWORD_PTR m_dwAdvise; // Timer advise cookie IMediaSample *m_pMediaSample; // Current image media sample BOOL m_bEOS; // Any more samples in the stream BOOL m_bEOSDelivered; // Have we delivered an EC_COMPLETE CRendererInputPin *m_pInputPin; // Our renderer input pin object CCritSec m_InterfaceLock; // Critical section for interfaces CCritSec m_RendererLock; // Controls access to internals IQualityControl *m_pQSink; // QualityControl sink BOOL m_bRepaintStatus; // Can we signal an EC_REPAINT // Avoid some deadlocks by tracking filter during stop volatile BOOL m_bInReceive; // Inside Receive between PrepareReceive // And actually processing the sample REFERENCE_TIME m_SignalTime; // Time when we signal EC_COMPLETE UINT m_EndOfStreamTimer; // Used to signal end of stream CCritSec m_ObjectCreationLock; // This lock protects the creation and // of m_pPosition and m_pInputPin. It // ensures that two threads cannot create // either object simultaneously. public: CBaseRenderer(REFCLSID RenderClass, // CLSID for this renderer __in_opt LPCTSTR pName, // Debug ONLY description __inout_opt LPUNKNOWN pUnk, // Aggregated owner object __inout HRESULT *phr); // General OLE return code ~CBaseRenderer(); // Overriden to say what interfaces we support and where virtual HRESULT GetMediaPositionInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP NonDelegatingQueryInterface(REFIID, __deref_out void **); virtual HRESULT SourceThreadCanWait(BOOL bCanWait); #ifdef DEBUG // Debug only dump of the renderer state void DisplayRendererState(); #endif virtual HRESULT WaitForRenderTime(); virtual HRESULT CompleteStateChange(FILTER_STATE OldState); // Return internal information about this filter BOOL IsEndOfStream() { return m_bEOS; }; BOOL IsEndOfStreamDelivered() { return m_bEOSDelivered; }; BOOL IsStreaming() { return m_bStreaming; }; void SetAbortSignal(BOOL bAbort) { m_bAbort = bAbort; }; virtual void OnReceiveFirstSample(IMediaSample *pMediaSample){}; CAMEvent *GetRenderEvent() { return &m_RenderEvent; }; // Permit access to the transition state void Ready() { m_evComplete.Set(); }; void NotReady() { m_evComplete.Reset(); }; BOOL CheckReady() { return m_evComplete.Check(); }; virtual int GetPinCount(); virtual CBasePin *GetPin(int n); FILTER_STATE GetRealState(); void SendRepaint(); void SendNotifyWindow(IPin *pPin, HWND hwnd); BOOL OnDisplayChange(); void SetRepaintStatus(BOOL bRepaint); // Override the filter and pin interface functions STDMETHODIMP Stop(); STDMETHODIMP Pause(); STDMETHODIMP Run(REFERENCE_TIME StartTime); STDMETHODIMP GetState(DWORD dwMSecs, __out FILTER_STATE *State); STDMETHODIMP FindPin(LPCWSTR Id, __deref_out IPin **ppPin); // These are available for a quality management implementation virtual void OnRenderStart(IMediaSample *pMediaSample); virtual void OnRenderEnd(IMediaSample *pMediaSample); virtual HRESULT OnStartStreaming() { return NOERROR; }; virtual HRESULT OnStopStreaming() { return NOERROR; }; virtual void OnWaitStart(){}; virtual void OnWaitEnd(){}; virtual void PrepareRender(){}; #ifdef PERF REFERENCE_TIME m_trRenderStart; // Just before we started drawing // Set in OnRenderStart, Used in OnRenderEnd int m_idBaseStamp; // MSR_id for frame time stamp int m_idBaseRenderTime; // MSR_id for true wait time int m_idBaseAccuracy; // MSR_id for time frame is late (int) #endif // Quality management implementation for scheduling rendering virtual BOOL ScheduleSample(IMediaSample *pMediaSample); virtual HRESULT GetSampleTimes(IMediaSample *pMediaSample, __out REFERENCE_TIME *pStartTime, __out REFERENCE_TIME *pEndTime); virtual HRESULT ShouldDrawSampleNow(IMediaSample *pMediaSample, __out REFERENCE_TIME *ptrStart, __out REFERENCE_TIME *ptrEnd); // Lots of end of stream complexities void TimerCallback(); void ResetEndOfStreamTimer(); HRESULT NotifyEndOfStream(); virtual HRESULT SendEndOfStream(); virtual HRESULT ResetEndOfStream(); virtual HRESULT EndOfStream(); // Rendering is based around the clock void SignalTimerFired(); virtual HRESULT CancelNotification(); virtual HRESULT ClearPendingSample(); // Called when the filter changes state virtual HRESULT Active(); virtual HRESULT Inactive(); virtual HRESULT StartStreaming(); virtual HRESULT StopStreaming(); virtual HRESULT BeginFlush(); virtual HRESULT EndFlush(); // Deal with connections and type changes virtual HRESULT BreakConnect(); virtual HRESULT SetMediaType(const CMediaType *pmt); virtual HRESULT CompleteConnect(IPin *pReceivePin); // These look after the handling of data samples virtual HRESULT PrepareReceive(IMediaSample *pMediaSample); virtual HRESULT Receive(IMediaSample *pMediaSample); virtual BOOL HaveCurrentSample(); virtual IMediaSample *GetCurrentSample(); virtual HRESULT Render(IMediaSample *pMediaSample); // Derived classes MUST override these virtual HRESULT DoRenderSample(IMediaSample *pMediaSample) PURE; virtual HRESULT CheckMediaType(const CMediaType *) PURE; // Helper void WaitForReceiveToComplete(); }; // CBaseVideoRenderer is a renderer class (see its ancestor class) and // it handles scheduling of media samples so that they are drawn at the // correct time by the reference clock. It implements a degradation // strategy. Possible degradation modes are: // Drop frames here (only useful if the drawing takes significant time) // Signal supplier (upstream) to drop some frame(s) - i.e. one-off skip. // Signal supplier to change the frame rate - i.e. ongoing skipping. // Or any combination of the above. // In order to determine what's useful to try we need to know what's going // on. This is done by timing various operations (including the supplier). // This timing is done by using timeGetTime as it is accurate enough and // usually cheaper than calling the reference clock. It also tells the // truth if there is an audio break and the reference clock stops. // We provide a number of public entry points (named OnXxxStart, OnXxxEnd) // which the rest of the renderer calls at significant moments. These do // the timing. // the number of frames that the sliding averages are averaged over. // the rule is (1024*NewObservation + (AVGPERIOD-1) * PreviousAverage)/AVGPERIOD #define AVGPERIOD 4 #define DO_MOVING_AVG(avg, obs) (avg = (1024 * obs + (AVGPERIOD - 1) * avg) / AVGPERIOD) // Spot the bug in this macro - I can't. but it doesn't work! class CBaseVideoRenderer : public CBaseRenderer , // Base renderer class public IQualProp , // Property page guff public IQualityControl // Allow throttling { protected: // Hungarian: // tFoo is the time Foo in mSec (beware m_tStart from filter.h) // trBar is the time Bar by the reference clock //****************************************************************** // State variables to control synchronisation //****************************************************************** // Control of sending Quality messages. We need to know whether // we are in trouble (e.g. frames being dropped) and where the time // is being spent. // When we drop a frame we play the next one early. // The frame after that is likely to wait before drawing and counting this // wait as spare time is unfair, so we count it as a zero wait. // We therefore need to know whether we are playing frames early or not. int m_nNormal; // The number of consecutive frames // drawn at their normal time (not early) // -1 means we just dropped a frame. #ifdef PERF BOOL m_bDrawLateFrames; // Don't drop any frames (debug and I'm // not keen on people using it!) #endif BOOL m_bSupplierHandlingQuality; // The response to Quality messages says // our supplier is handling things. // We will allow things to go extra late // before dropping frames. We will play // very early after he has dropped one. // Control of scheduling, frame dropping etc. // We need to know where the time is being spent so as to tell whether // we should be taking action here, signalling supplier or what. // The variables are initialised to a mode of NOT dropping frames. // They will tell the truth after a few frames. // We typically record a start time for an event, later we get the time // again and subtract to get the elapsed time, and we average this over // a few frames. The average is used to tell what mode we are in. // Although these are reference times (64 bit) they are all DIFFERENCES // between times which are small. An int will go up to 214 secs before // overflow. Avoiding 64 bit multiplications and divisions seems // worth while. // Audio-video throttling. If the user has turned up audio quality // very high (in principle it could be any other stream, not just audio) // then we can receive cries for help via the graph manager. In this case // we put in a wait for some time after rendering each frame. int m_trThrottle; // The time taken to render (i.e. BitBlt) frames controls which component // needs to degrade. If the blt is expensive, the renderer degrades. // If the blt is cheap it's done anyway and the supplier degrades. int m_trRenderAvg; // Time frames are taking to blt int m_trRenderLast; // Time for last frame blt int m_tRenderStart; // Just before we started drawing (mSec) // derived from timeGetTime. // When frames are dropped we will play the next frame as early as we can. // If it was a false alarm and the machine is fast we slide gently back to // normal timing. To do this, we record the offset showing just how early // we really are. This will normally be negative meaning early or zero. int m_trEarliness; // Target provides slow long-term feedback to try to reduce the // average sync offset to zero. Whenever a frame is actually rendered // early we add a msec or two, whenever late we take off a few. // We add or take off 1/32 of the error time. // Eventually we should be hovering around zero. For a really bad case // where we were (say) 300mSec off, it might take 100 odd frames to // settle down. The rate of change of this is intended to be slower // than any other mechanism in Quartz, thereby avoiding hunting. int m_trTarget; // The proportion of time spent waiting for the right moment to blt // controls whether we bother to drop a frame or whether we reckon that // we're doing well enough that we can stand a one-frame glitch. int m_trWaitAvg; // Average of last few wait times // (actually we just average how early // we were). Negative here means LATE. // The average inter-frame time. // This is used to calculate the proportion of the time used by the // three operations (supplying us, waiting, rendering) int m_trFrameAvg; // Average inter-frame time int m_trDuration; // duration of last frame. #ifdef PERF // Performance logging identifiers int m_idTimeStamp; // MSR_id for frame time stamp int m_idEarliness; // MSR_id for earliness fudge int m_idTarget; // MSR_id for Target fudge int m_idWaitReal; // MSR_id for true wait time int m_idWait; // MSR_id for wait time recorded int m_idFrameAccuracy; // MSR_id for time frame is late (int) int m_idRenderAvg; // MSR_id for Render time recorded (int) int m_idSchLateTime; // MSR_id for lateness at scheduler int m_idQualityRate; // MSR_id for Quality rate requested int m_idQualityTime; // MSR_id for Quality time requested int m_idDecision; // MSR_id for decision code int m_idDuration; // MSR_id for duration of a frame int m_idThrottle; // MSR_id for audio-video throttling // int m_idDebug; // MSR_id for trace style debugging // int m_idSendQuality; // MSR_id for timing the notifications per se #endif // PERF REFERENCE_TIME m_trRememberStampForPerf; // original time stamp of frame // with no earliness fudges etc. #ifdef PERF REFERENCE_TIME m_trRememberFrameForPerf; // time when previous frame rendered // debug... int m_idFrameAvg; int m_idWaitAvg; #endif // PROPERTY PAGE // This has edit fields that show the user what's happening // These member variables hold these counts. int m_cFramesDropped; // cumulative frames dropped IN THE RENDERER int m_cFramesDrawn; // Frames since streaming started seen BY THE // RENDERER (some may be dropped upstream) // Next two support average sync offset and standard deviation of sync offset. LONGLONG m_iTotAcc; // Sum of accuracies in mSec LONGLONG m_iSumSqAcc; // Sum of squares of (accuracies in mSec) // Next two allow jitter calculation. Jitter is std deviation of frame time. REFERENCE_TIME m_trLastDraw; // Time of prev frame (for inter-frame times) LONGLONG m_iSumSqFrameTime; // Sum of squares of (inter-frame time in mSec) LONGLONG m_iSumFrameTime; // Sum of inter-frame times in mSec // To get performance statistics on frame rate, jitter etc, we need // to record the lateness and inter-frame time. What we actually need are the // data above (sum, sum of squares and number of entries for each) but the data // is generated just ahead of time and only later do we discover whether the // frame was actually drawn or not. So we have to hang on to the data int m_trLate; // hold onto frame lateness int m_trFrame; // hold onto inter-frame time int m_tStreamingStart; // if streaming then time streaming started // else time of last streaming session // used for property page statistics #ifdef PERF LONGLONG m_llTimeOffset; // timeGetTime()*10000+m_llTimeOffset==ref time #endif public: CBaseVideoRenderer(REFCLSID RenderClass, // CLSID for this renderer __in_opt LPCTSTR pName, // Debug ONLY description __inout_opt LPUNKNOWN pUnk, // Aggregated owner object __inout HRESULT *phr); // General OLE return code ~CBaseVideoRenderer(); // IQualityControl methods - Notify allows audio-video throttling STDMETHODIMP SetSink(IQualityControl *piqc); STDMETHODIMP Notify(IBaseFilter *pSelf, Quality q); // These provide a full video quality management implementation void OnRenderStart(IMediaSample *pMediaSample); void OnRenderEnd(IMediaSample *pMediaSample); void OnWaitStart(); void OnWaitEnd(); HRESULT OnStartStreaming(); HRESULT OnStopStreaming(); void ThrottleWait(); // Handle the statistics gathering for our quality management void PreparePerformanceData(int trLate, int trFrame); virtual void RecordFrameLateness(int trLate, int trFrame); virtual void OnDirectRender(IMediaSample *pMediaSample); virtual HRESULT ResetStreamingTimes(); BOOL ScheduleSample(IMediaSample *pMediaSample); HRESULT ShouldDrawSampleNow(IMediaSample *pMediaSample, __inout REFERENCE_TIME *ptrStart, __inout REFERENCE_TIME *ptrEnd); virtual HRESULT SendQuality(REFERENCE_TIME trLate, REFERENCE_TIME trRealStream); STDMETHODIMP JoinFilterGraph(__inout_opt IFilterGraph *pGraph, __in_opt LPCWSTR pName); // // Do estimates for standard deviations for per-frame // statistics // // *piResult = (llSumSq - iTot * iTot / m_cFramesDrawn - 1) / // (m_cFramesDrawn - 2) // or 0 if m_cFramesDrawn <= 3 // HRESULT GetStdDev(int nSamples, __out int *piResult, LONGLONG llSumSq, LONGLONG iTot); public: // IQualProp property page support STDMETHODIMP get_FramesDroppedInRenderer(__out int *cFramesDropped); STDMETHODIMP get_FramesDrawn(__out int *pcFramesDrawn); STDMETHODIMP get_AvgFrameRate(__out int *piAvgFrameRate); STDMETHODIMP get_Jitter(__out int *piJitter); STDMETHODIMP get_AvgSyncOffset(__out int *piAvg); STDMETHODIMP get_DevSyncOffset(__out int *piDev); // Implement an IUnknown interface and expose IQualProp DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out VOID **ppv); }; #endif // __RENBASE__ ================================================ FILE: common/baseclasses/schedule.cpp ================================================ //------------------------------------------------------------------------------ // File: Schedule.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1996-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include // DbgLog values (all on LOG_TIMING): // // 2 for schedulting, firing and shunting of events // 3 for wait delays and wake-up times of event thread // 4 for details of whats on the list when the thread awakes /* Construct & destructors */ CAMSchedule::CAMSchedule(HANDLE ev) : CBaseObject(TEXT("CAMSchedule")) , head(&z, 0) , z(0, MAX_TIME) , m_dwNextCookie(0) , m_dwAdviseCount(0) , m_pAdviseCache(0) , m_dwCacheCount(0) , m_ev(ev) { head.m_dwAdviseCookie = z.m_dwAdviseCookie = 0; } CAMSchedule::~CAMSchedule() { m_Serialize.Lock(); // Delete cache CAdvisePacket *p = m_pAdviseCache; while (p) { CAdvisePacket *const p_next = p->m_next; delete p; p = p_next; } ASSERT(m_dwAdviseCount == 0); // Better to be safe than sorry if (m_dwAdviseCount > 0) { DumpLinkedList(); while (!head.m_next->IsZ()) { head.DeleteNext(); --m_dwAdviseCount; } } // If, in the debug version, we assert twice, it means, not only // did we have left over advises, but we have also let m_dwAdviseCount // get out of sync. with the number of advises actually on the list. ASSERT(m_dwAdviseCount == 0); m_Serialize.Unlock(); } /* Public methods */ DWORD CAMSchedule::GetAdviseCount() { // No need to lock, m_dwAdviseCount is 32bits & declared volatile return m_dwAdviseCount; } REFERENCE_TIME CAMSchedule::GetNextAdviseTime() { CAutoLock lck(&m_Serialize); // Need to stop the linked list from changing return head.m_next->m_rtEventTime; } DWORD_PTR CAMSchedule::AddAdvisePacket(const REFERENCE_TIME &time1, const REFERENCE_TIME &time2, HANDLE h, BOOL periodic) { // Since we use MAX_TIME as a sentry, we can't afford to // schedule a notification at MAX_TIME ASSERT(time1 < MAX_TIME); DWORD_PTR Result; CAdvisePacket *p; m_Serialize.Lock(); if (m_pAdviseCache) { p = m_pAdviseCache; m_pAdviseCache = p->m_next; --m_dwCacheCount; } else { p = new CAdvisePacket(); } if (p) { p->m_rtEventTime = time1; p->m_rtPeriod = time2; p->m_hNotify = h; p->m_bPeriodic = periodic; Result = AddAdvisePacket(p); } else Result = 0; m_Serialize.Unlock(); return Result; } HRESULT CAMSchedule::Unadvise(DWORD_PTR dwAdviseCookie) { HRESULT hr = S_FALSE; CAdvisePacket *p_prev = &head; CAdvisePacket *p_n; m_Serialize.Lock(); while (p_n = p_prev->Next()) // The Next() method returns NULL when it hits z { if (p_n->m_dwAdviseCookie == dwAdviseCookie) { Delete(p_prev->RemoveNext()); --m_dwAdviseCount; hr = S_OK; // Having found one cookie that matches, there should be no more #ifdef DEBUG while (p_n = p_prev->Next()) { ASSERT(p_n->m_dwAdviseCookie != dwAdviseCookie); p_prev = p_n; } #endif break; } p_prev = p_n; }; m_Serialize.Unlock(); return hr; } REFERENCE_TIME CAMSchedule::Advise(const REFERENCE_TIME &rtTime) { REFERENCE_TIME rtNextTime; CAdvisePacket *pAdvise; DbgLog((LOG_TIMING, 2, TEXT("CAMSchedule::Advise( %lu ms )"), ULONG(rtTime / (UNITS / MILLISECONDS)))); CAutoLock lck(&m_Serialize); #ifdef DEBUG if (DbgCheckModuleLevel(LOG_TIMING, 4)) DumpLinkedList(); #endif // Note - DON'T cache the difference, it might overflow while (rtTime >= (rtNextTime = (pAdvise = head.m_next)->m_rtEventTime) && !pAdvise->IsZ()) { ASSERT(pAdvise->m_dwAdviseCookie); // If this is zero, its the head or the tail!! ASSERT(pAdvise->m_hNotify != INVALID_HANDLE_VALUE); if (pAdvise->m_bPeriodic == TRUE) { ReleaseSemaphore(pAdvise->m_hNotify, 1, NULL); pAdvise->m_rtEventTime += pAdvise->m_rtPeriod; ShuntHead(); } else { ASSERT(pAdvise->m_bPeriodic == FALSE); EXECUTE_ASSERT(SetEvent(pAdvise->m_hNotify)); --m_dwAdviseCount; Delete(head.RemoveNext()); } } DbgLog((LOG_TIMING, 3, TEXT("CAMSchedule::Advise() Next time stamp: %lu ms, for advise %lu."), DWORD(rtNextTime / (UNITS / MILLISECONDS)), pAdvise->m_dwAdviseCookie)); return rtNextTime; } /* Private methods */ DWORD_PTR CAMSchedule::AddAdvisePacket(__inout CAdvisePacket *pPacket) { ASSERT(pPacket->m_rtEventTime >= 0 && pPacket->m_rtEventTime < MAX_TIME); ASSERT(CritCheckIn(&m_Serialize)); CAdvisePacket *p_prev = &head; CAdvisePacket *p_n; const DWORD_PTR Result = pPacket->m_dwAdviseCookie = ++m_dwNextCookie; // This relies on the fact that z is a sentry with a maximal m_rtEventTime for (;; p_prev = p_n) { p_n = p_prev->m_next; if (p_n->m_rtEventTime >= pPacket->m_rtEventTime) break; } p_prev->InsertAfter(pPacket); ++m_dwAdviseCount; DbgLog((LOG_TIMING, 2, TEXT("Added advise %lu, for thread 0x%02X, scheduled at %lu"), pPacket->m_dwAdviseCookie, GetCurrentThreadId(), (pPacket->m_rtEventTime / (UNITS / MILLISECONDS)))); // If packet added at the head, then clock needs to re-evaluate wait time. if (p_prev == &head) SetEvent(m_ev); return Result; } void CAMSchedule::Delete(__inout CAdvisePacket *pPacket) { if (m_dwCacheCount >= dwCacheMax) delete pPacket; else { m_Serialize.Lock(); pPacket->m_next = m_pAdviseCache; m_pAdviseCache = pPacket; ++m_dwCacheCount; m_Serialize.Unlock(); } } // Takes the head of the list & repositions it void CAMSchedule::ShuntHead() { CAdvisePacket *p_prev = &head; CAdvisePacket *p_n; m_Serialize.Lock(); CAdvisePacket *const pPacket = head.m_next; // This will catch both an empty list, // and if somehow a MAX_TIME time gets into the list // (which would also break this method). ASSERT(pPacket->m_rtEventTime < MAX_TIME); // This relies on the fact that z is a sentry with a maximal m_rtEventTime for (;; p_prev = p_n) { p_n = p_prev->m_next; if (p_n->m_rtEventTime > pPacket->m_rtEventTime) break; } // If p_prev == pPacket then we're already in the right place if (p_prev != pPacket) { head.m_next = pPacket->m_next; (p_prev->m_next = pPacket)->m_next = p_n; } #ifdef DEBUG DbgLog((LOG_TIMING, 2, TEXT("Periodic advise %lu, shunted to %lu"), pPacket->m_dwAdviseCookie, (pPacket->m_rtEventTime / (UNITS / MILLISECONDS)))); #endif m_Serialize.Unlock(); } #ifdef DEBUG void CAMSchedule::DumpLinkedList() { m_Serialize.Lock(); int i = 0; DbgLog((LOG_TIMING, 1, TEXT("CAMSchedule::DumpLinkedList() this = 0x%p"), this)); for (CAdvisePacket *p = &head; p; p = p->m_next, i++) { DbgLog((LOG_TIMING, 1, TEXT("Advise List # %lu, Cookie %d, RefTime %lu"), i, p->m_dwAdviseCookie, p->m_rtEventTime / (UNITS / MILLISECONDS))); } m_Serialize.Unlock(); } #endif ================================================ FILE: common/baseclasses/schedule.h ================================================ //------------------------------------------------------------------------------ // File: Schedule.h // // Desc: DirectShow base classes. // // Copyright (c) 1996-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __CAMSchedule__ #define __CAMSchedule__ class CAMSchedule : private CBaseObject { public: virtual ~CAMSchedule(); // ev is the event we should fire if the advise time needs re-evaluating CAMSchedule(HANDLE ev); DWORD GetAdviseCount(); REFERENCE_TIME GetNextAdviseTime(); // We need a method for derived classes to add advise packets, we return the cookie DWORD_PTR AddAdvisePacket(const REFERENCE_TIME &time1, const REFERENCE_TIME &time2, HANDLE h, BOOL periodic); // And a way to cancel HRESULT Unadvise(DWORD_PTR dwAdviseCookie); // Tell us the time please, and we'll dispatch the expired events. We return the time of the next event. // NB: The time returned will be "useless" if you start adding extra Advises. But that's the problem of // whoever is using this helper class (typically a clock). REFERENCE_TIME Advise(const REFERENCE_TIME &rtTime); // Get the event handle which will be set if advise time requires re-evaluation. HANDLE GetEvent() const { return m_ev; } private: // We define the nodes that will be used in our singly linked list // of advise packets. The list is ordered by time, with the // elements that will expire first at the front. class CAdvisePacket { public: CAdvisePacket() {} CAdvisePacket *m_next; DWORD_PTR m_dwAdviseCookie; REFERENCE_TIME m_rtEventTime; // Time at which event should be set REFERENCE_TIME m_rtPeriod; // Periodic time HANDLE m_hNotify; // Handle to event or semephore BOOL m_bPeriodic; // TRUE => Periodic event CAdvisePacket(__inout_opt CAdvisePacket *next, LONGLONG time) : m_next(next) , m_rtEventTime(time) { } void InsertAfter(__inout CAdvisePacket *p) { p->m_next = m_next; m_next = p; } int IsZ() const // That is, is it the node that represents the end of the list { return m_next == 0; } CAdvisePacket *RemoveNext() { CAdvisePacket *const next = m_next; CAdvisePacket *const new_next = next->m_next; m_next = new_next; return next; } void DeleteNext() { delete RemoveNext(); } CAdvisePacket *Next() const { CAdvisePacket *result = m_next; if (result->IsZ()) result = 0; return result; } DWORD_PTR Cookie() const { return m_dwAdviseCookie; } }; // Structure is: // head -> elmt1 -> elmt2 -> z -> null // So an empty list is: head -> z -> null // Having head & z as links makes insertaion, // deletion and shunting much easier. CAdvisePacket head, z; // z is both a tail and a sentry volatile DWORD_PTR m_dwNextCookie; // Strictly increasing volatile DWORD m_dwAdviseCount; // Number of elements on list CCritSec m_Serialize; // AddAdvisePacket: adds the packet, returns the cookie (0 if failed) DWORD_PTR AddAdvisePacket(__inout CAdvisePacket *pPacket); // Event that we should set if the packed added above will be the next to fire. const HANDLE m_ev; // A Shunt is where we have changed the first element in the // list and want it re-evaluating (i.e. repositioned) in // the list. void ShuntHead(); // Rather than delete advise packets, we cache them for future use CAdvisePacket *m_pAdviseCache; DWORD m_dwCacheCount; enum { dwCacheMax = 5 }; // Don't bother caching more than five void Delete(__inout CAdvisePacket *pLink); // This "Delete" will cache the Link // Attributes and methods for debugging public: #ifdef DEBUG void DumpLinkedList(); #else void DumpLinkedList() {} #endif }; #endif // __CAMSchedule__ ================================================ FILE: common/baseclasses/seekpt.cpp ================================================ //------------------------------------------------------------------------------ // File: SeekPT.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include "seekpt.h" //================================================================== // CreateInstance // This goes in the factory template table to create new instances // If there is already a mapper instance - return that, else make one // and save it in a static variable so that forever after we can return that. //================================================================== CUnknown *CSeekingPassThru::CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) { return new CSeekingPassThru(NAME("Seeking PassThru"), pUnk, phr); } STDMETHODIMP CSeekingPassThru::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_ISeekingPassThru) { return GetInterface((ISeekingPassThru *)this, ppv); } else { if (m_pPosPassThru && (riid == IID_IMediaSeeking || riid == IID_IMediaPosition)) { return m_pPosPassThru->NonDelegatingQueryInterface(riid, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } } CSeekingPassThru::CSeekingPassThru(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) : CUnknown(pName, pUnk, phr) , m_pPosPassThru(NULL) { } CSeekingPassThru::~CSeekingPassThru() { delete m_pPosPassThru; } STDMETHODIMP CSeekingPassThru::Init(BOOL bRendererSeeking, IPin *pPin) { HRESULT hr = NOERROR; if (m_pPosPassThru) { hr = E_FAIL; } else { m_pPosPassThru = bRendererSeeking ? new CRendererPosPassThru(NAME("Render Seeking COM object"), (IUnknown *)this, &hr, pPin) : new CPosPassThru(NAME("Render Seeking COM object"), (IUnknown *)this, &hr, pPin); if (!m_pPosPassThru) { hr = E_OUTOFMEMORY; } else { if (FAILED(hr)) { delete m_pPosPassThru; m_pPosPassThru = NULL; } } } return hr; } ================================================ FILE: common/baseclasses/seekpt.h ================================================ //------------------------------------------------------------------------------ // File: SeekPT.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __seekpt_h__ #define __seekpt_h__ class CSeekingPassThru : public ISeekingPassThru , public CUnknown { public: static CUnknown *CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); CSeekingPassThru(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); ~CSeekingPassThru(); DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP Init(BOOL bSupportRendering, IPin *pPin); private: CPosPassThru *m_pPosPassThru; }; #endif ================================================ FILE: common/baseclasses/source.cpp ================================================ //------------------------------------------------------------------------------ // File: Source.cpp // // Desc: DirectShow base classes - implements CSource, which is a Quartz // source filter 'template.' // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Locking Strategy. // // Hold the filter critical section (m_pFilter->pStateLock()) to serialise // access to functions. Note that, in general, this lock may be held // by a function when the worker thread may want to hold it. Therefore // if you wish to access shared state from the worker thread you will // need to add another critical section object. The execption is during // the threads processing loop, when it is safe to get the filter critical // section from within FillBuffer(). #include // // CSource::Constructor // // Initialise the pin count for the filter. The user will create the pins in // the derived class. CSource::CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid) : CBaseFilter(pName, lpunk, &m_cStateLock, clsid) , m_iPins(0) , m_paStreams(NULL) { } CSource::CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr) : CBaseFilter(pName, lpunk, &m_cStateLock, clsid) , m_iPins(0) , m_paStreams(NULL) { UNREFERENCED_PARAMETER(phr); } #ifdef UNICODE CSource::CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid) : CBaseFilter(pName, lpunk, &m_cStateLock, clsid) , m_iPins(0) , m_paStreams(NULL) { } CSource::CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr) : CBaseFilter(pName, lpunk, &m_cStateLock, clsid) , m_iPins(0) , m_paStreams(NULL) { UNREFERENCED_PARAMETER(phr); } #endif // // CSource::Destructor // CSource::~CSource() { /* Free our pins and pin array */ while (m_iPins != 0) { // deleting the pins causes them to be removed from the array... delete m_paStreams[m_iPins - 1]; } ASSERT(m_paStreams == NULL); } // // Add a new pin // HRESULT CSource::AddPin(__in CSourceStream *pStream) { CAutoLock lock(&m_cStateLock); /* Allocate space for this pin and the old ones */ CSourceStream **paStreams = new CSourceStream *[m_iPins + 1]; if (paStreams == NULL) { return E_OUTOFMEMORY; } if (m_paStreams != NULL) { CopyMemory((PVOID)paStreams, (PVOID)m_paStreams, m_iPins * sizeof(m_paStreams[0])); paStreams[m_iPins] = pStream; delete[] m_paStreams; } m_paStreams = paStreams; m_paStreams[m_iPins] = pStream; m_iPins++; return S_OK; } // // Remove a pin - pStream is NOT deleted // HRESULT CSource::RemovePin(__in CSourceStream *pStream) { int i; for (i = 0; i < m_iPins; i++) { if (m_paStreams[i] == pStream) { if (m_iPins == 1) { delete[] m_paStreams; m_paStreams = NULL; } else { /* no need to reallocate */ while (++i < m_iPins) m_paStreams[i - 1] = m_paStreams[i]; } m_iPins--; return S_OK; } } return S_FALSE; } // // FindPin // // Set *ppPin to the IPin* that has the id Id. // or to NULL if the Id cannot be matched. STDMETHODIMP CSource::FindPin(LPCWSTR Id, __deref_out IPin **ppPin) { CheckPointer(ppPin, E_POINTER); ValidateReadWritePtr(ppPin, sizeof(IPin *)); // The -1 undoes the +1 in QueryId and ensures that totally invalid // strings (for which WstrToInt delivers 0) give a deliver a NULL pin. int i = WstrToInt(Id) - 1; *ppPin = GetPin(i); if (*ppPin != NULL) { (*ppPin)->AddRef(); return NOERROR; } else { return VFW_E_NOT_FOUND; } } // // FindPinNumber // // return the number of the pin with this IPin* or -1 if none int CSource::FindPinNumber(__in IPin *iPin) { int i; for (i = 0; i < m_iPins; ++i) { if ((IPin *)(m_paStreams[i]) == iPin) { return i; } } return -1; } // // GetPinCount // // Returns the number of pins this filter has int CSource::GetPinCount(void) { CAutoLock lock(&m_cStateLock); return m_iPins; } // // GetPin // // Return a non-addref'd pointer to pin n // needed by CBaseFilter CBasePin *CSource::GetPin(int n) { CAutoLock lock(&m_cStateLock); // n must be in the range 0..m_iPins-1 // if m_iPins>n && n>=0 it follows that m_iPins>0 // which is what used to be checked (i.e. checking that we have a pin) if ((n >= 0) && (n < m_iPins)) { ASSERT(m_paStreams[n]); return m_paStreams[n]; } return NULL; } // // * // * --- CSourceStream ---- // * // // Set Id to point to a CoTaskMemAlloc'd STDMETHODIMP CSourceStream::QueryId(__deref_out LPWSTR *Id) { CheckPointer(Id, E_POINTER); ValidateReadWritePtr(Id, sizeof(LPWSTR)); // We give the pins id's which are 1,2,... // FindPinNumber returns -1 for an invalid pin int i = 1 + m_pFilter->FindPinNumber(this); if (i < 1) return VFW_E_NOT_FOUND; *Id = (LPWSTR)CoTaskMemAlloc(sizeof(WCHAR) * 12); if (*Id == NULL) { return E_OUTOFMEMORY; } IntToWstr(i, *Id); return NOERROR; } // // CSourceStream::Constructor // // increments the number of pins present on the filter CSourceStream::CSourceStream(__in_opt LPCTSTR pObjectName, __inout HRESULT *phr, __inout CSource *ps, __in_opt LPCWSTR pPinName) : CBaseOutputPin(pObjectName, ps, ps->pStateLock(), phr, pPinName) , m_pFilter(ps) { *phr = m_pFilter->AddPin(this); } #ifdef UNICODE CSourceStream::CSourceStream(__in_opt LPCSTR pObjectName, __inout HRESULT *phr, __inout CSource *ps, __in_opt LPCWSTR pPinName) : CBaseOutputPin(pObjectName, ps, ps->pStateLock(), phr, pPinName) , m_pFilter(ps) { *phr = m_pFilter->AddPin(this); } #endif // // CSourceStream::Destructor // // Decrements the number of pins on this filter CSourceStream::~CSourceStream(void) { m_pFilter->RemovePin(this); } // // CheckMediaType // // Do we support this type? Provides the default support for 1 type. HRESULT CSourceStream::CheckMediaType(const CMediaType *pMediaType) { CAutoLock lock(m_pFilter->pStateLock()); CMediaType mt; GetMediaType(&mt); if (mt == *pMediaType) { return NOERROR; } return E_FAIL; } // // GetMediaType/3 // // By default we support only one type // iPosition indexes are 0-n HRESULT CSourceStream::GetMediaType(int iPosition, __inout CMediaType *pMediaType) { CAutoLock lock(m_pFilter->pStateLock()); if (iPosition < 0) { return E_INVALIDARG; } if (iPosition > 0) { return VFW_S_NO_MORE_ITEMS; } return GetMediaType(pMediaType); } // // Active // // The pin is active - start up the worker thread HRESULT CSourceStream::Active(void) { CAutoLock lock(m_pFilter->pStateLock()); HRESULT hr; if (m_pFilter->IsActive()) { return S_FALSE; // succeeded, but did not allocate resources (they already exist...) } // do nothing if not connected - its ok not to connect to // all pins of a source filter if (!IsConnected()) { return NOERROR; } hr = CBaseOutputPin::Active(); if (FAILED(hr)) { return hr; } ASSERT(!ThreadExists()); // start the thread if (!Create()) { return E_FAIL; } // Tell thread to initialize. If OnThreadCreate Fails, so does this. hr = Init(); if (FAILED(hr)) return hr; return Pause(); } // // Inactive // // Pin is inactive - shut down the worker thread // Waits for the worker to exit before returning. HRESULT CSourceStream::Inactive(void) { CAutoLock lock(m_pFilter->pStateLock()); HRESULT hr; // do nothing if not connected - its ok not to connect to // all pins of a source filter if (!IsConnected()) { return NOERROR; } // !!! need to do this before trying to stop the thread, because // we may be stuck waiting for our own allocator!!! hr = CBaseOutputPin::Inactive(); // call this first to Decommit the allocator if (FAILED(hr)) { return hr; } if (ThreadExists()) { hr = Stop(); if (FAILED(hr)) { return hr; } hr = Exit(); if (FAILED(hr)) { return hr; } Close(); // Wait for the thread to exit, then tidy up. } // hr = CBaseOutputPin::Inactive(); // call this first to Decommit the allocator // if (FAILED(hr)) { // return hr; //} return NOERROR; } // // ThreadProc // // When this returns the thread exits // Return codes > 0 indicate an error occured DWORD CSourceStream::ThreadProc(void) { HRESULT hr; // the return code from calls Command com; do { com = GetRequest(); if (com != CMD_INIT) { DbgLog((LOG_ERROR, 1, TEXT("Thread expected init command"))); Reply((DWORD)E_UNEXPECTED); } } while (com != CMD_INIT); DbgLog((LOG_TRACE, 1, TEXT("CSourceStream worker thread initializing"))); hr = OnThreadCreate(); // perform set up tasks if (FAILED(hr)) { DbgLog((LOG_ERROR, 1, TEXT("CSourceStream::OnThreadCreate failed. Aborting thread."))); OnThreadDestroy(); Reply(hr); // send failed return code from OnThreadCreate return 1; } // Initialisation suceeded Reply(NOERROR); Command cmd; do { cmd = GetRequest(); switch (cmd) { case CMD_EXIT: Reply(NOERROR); break; case CMD_RUN: DbgLog((LOG_ERROR, 1, TEXT("CMD_RUN received before a CMD_PAUSE???"))); // !!! fall through??? case CMD_PAUSE: Reply(NOERROR); DoBufferProcessingLoop(); break; case CMD_STOP: Reply(NOERROR); break; default: DbgLog((LOG_ERROR, 1, TEXT("Unknown command %d received!"), cmd)); Reply((DWORD)E_NOTIMPL); break; } } while (cmd != CMD_EXIT); hr = OnThreadDestroy(); // tidy up. if (FAILED(hr)) { DbgLog((LOG_ERROR, 1, TEXT("CSourceStream::OnThreadDestroy failed. Exiting thread."))); return 1; } DbgLog((LOG_TRACE, 1, TEXT("CSourceStream worker thread exiting"))); return 0; } // // DoBufferProcessingLoop // // Grabs a buffer and calls the users processing function. // Overridable, so that different delivery styles can be catered for. HRESULT CSourceStream::DoBufferProcessingLoop(void) { Command com; OnThreadStartPlay(); do { while (!CheckRequest(&com)) { IMediaSample *pSample; HRESULT hr = GetDeliveryBuffer(&pSample, NULL, NULL, 0); if (FAILED(hr)) { Sleep(1); continue; // go round again. Perhaps the error will go away // or the allocator is decommited & we will be asked to // exit soon. } // Virtual function user will override. hr = FillBuffer(pSample); if (hr == S_OK) { hr = Deliver(pSample); pSample->Release(); // downstream filter returns S_FALSE if it wants us to // stop or an error if it's reporting an error. if (hr != S_OK) { DbgLog((LOG_TRACE, 2, TEXT("Deliver() returned %08x; stopping"), hr)); return S_OK; } } else if (hr == S_FALSE) { // derived class wants us to stop pushing data pSample->Release(); DeliverEndOfStream(); return S_OK; } else { // derived class encountered an error pSample->Release(); DbgLog((LOG_ERROR, 1, TEXT("Error %08lX from FillBuffer!!!"), hr)); DeliverEndOfStream(); m_pFilter->NotifyEvent(EC_ERRORABORT, hr, 0); return hr; } // all paths release the sample } // For all commands sent to us there must be a Reply call! if (com == CMD_RUN || com == CMD_PAUSE) { Reply(NOERROR); } else if (com != CMD_STOP) { Reply((DWORD)E_UNEXPECTED); DbgLog((LOG_ERROR, 1, TEXT("Unexpected command!!!"))); } } while (com != CMD_STOP); return S_FALSE; } ================================================ FILE: common/baseclasses/source.h ================================================ //------------------------------------------------------------------------------ // File: Source.h // // Desc: DirectShow base classes - defines classes to simplify creation of // ActiveX source filters that support continuous generation of data. // No support is provided for IMediaControl or IMediaPosition. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // // Derive your source filter from CSource. // During construction either: // Create some CSourceStream objects to manage your pins // Provide the user with a means of doing so eg, an IPersistFile interface. // // CSource provides: // IBaseFilter interface management // IMediaFilter interface management, via CBaseFilter // Pin counting for CBaseFilter // // Derive a class from CSourceStream to manage your output pin types // Implement GetMediaType/1 to return the type you support. If you support multiple // types then overide GetMediaType/3, CheckMediaType and GetMediaTypeCount. // Implement Fillbuffer() to put data into one buffer. // // CSourceStream provides: // IPin management via CBaseOutputPin // Worker thread management #ifndef __CSOURCE__ #define __CSOURCE__ class CSourceStream; // The class that will handle each pin // // CSource // // Override construction to provide a means of creating // CSourceStream derived objects - ie a way of creating pins. class CSource : public CBaseFilter { public: CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr); CSource(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid); #ifdef UNICODE CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid, __inout HRESULT *phr); CSource(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN lpunk, CLSID clsid); #endif ~CSource(); int GetPinCount(void); CBasePin *GetPin(int n); // -- Utilities -- CCritSec *pStateLock(void) { return &m_cStateLock; } // provide our critical section HRESULT AddPin(__in CSourceStream *); HRESULT RemovePin(__in CSourceStream *); STDMETHODIMP FindPin(LPCWSTR Id, __deref_out IPin **ppPin); int FindPinNumber(__in IPin *iPin); protected: int m_iPins; // The number of pins on this filter. Updated by CSourceStream // constructors & destructors. CSourceStream **m_paStreams; // the pins on this filter. CCritSec m_cStateLock; // Lock this to serialize function accesses to the filter state }; // // CSourceStream // // Use this class to manage a stream of data that comes from a // pin. // Uses a worker thread to put data on the pin. class CSourceStream : public CAMThread , public CBaseOutputPin { public: CSourceStream(__in_opt LPCTSTR pObjectName, __inout HRESULT *phr, __inout CSource *pms, __in_opt LPCWSTR pName); #ifdef UNICODE CSourceStream(__in_opt LPCSTR pObjectName, __inout HRESULT *phr, __inout CSource *pms, __in_opt LPCWSTR pName); #endif virtual ~CSourceStream(void); // virtual destructor ensures derived class destructors are called too. protected: CSource *m_pFilter; // The parent of this stream // * // * Data Source // * // * The following three functions: FillBuffer, OnThreadCreate/Destroy, are // * called from within the ThreadProc. They are used in the creation of // * the media samples this pin will provide // * // Override this to provide the worker thread a means // of processing a buffer virtual HRESULT FillBuffer(IMediaSample *pSamp) PURE; // Called as the thread is created/destroyed - use to perform // jobs such as start/stop streaming mode // If OnThreadCreate returns an error the thread will exit. virtual HRESULT OnThreadCreate(void) { return NOERROR; }; virtual HRESULT OnThreadDestroy(void) { return NOERROR; }; virtual HRESULT OnThreadStartPlay(void) { return NOERROR; }; // * // * Worker Thread // * HRESULT Active(void); // Starts up the worker thread HRESULT Inactive(void); // Exits the worker thread. public: // thread commands enum Command { CMD_INIT, CMD_PAUSE, CMD_RUN, CMD_STOP, CMD_EXIT }; HRESULT Init(void) { return CallWorker(CMD_INIT); } HRESULT Exit(void) { return CallWorker(CMD_EXIT); } HRESULT Run(void) { return CallWorker(CMD_RUN); } HRESULT Pause(void) { return CallWorker(CMD_PAUSE); } HRESULT Stop(void) { return CallWorker(CMD_STOP); } protected: Command GetRequest(void) { return (Command)CAMThread::GetRequest(); } BOOL CheckRequest(Command *pCom) { return CAMThread::CheckRequest((DWORD *)pCom); } // override these if you want to add thread commands virtual DWORD ThreadProc(void); // the thread function virtual HRESULT DoBufferProcessingLoop(void); // the loop executed whilst running // * // * AM_MEDIA_TYPE support // * // If you support more than one media type then override these 2 functions virtual HRESULT CheckMediaType(const CMediaType *pMediaType); virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); // List pos. 0-n // If you support only one type then override this fn. // This will only be called by the default implementations // of CheckMediaType and GetMediaType(int, CMediaType*) // You must override this fn. or the above 2! virtual HRESULT GetMediaType(__inout CMediaType *pMediaType) { return E_UNEXPECTED; } STDMETHODIMP QueryId(__deref_out LPWSTR *Id); }; #endif // __CSOURCE__ ================================================ FILE: common/baseclasses/streams.h ================================================ //------------------------------------------------------------------------------ // File: Streams.h // // Desc: DirectShow base classes - defines overall streams architecture. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __STREAMS__ #define __STREAMS__ #ifdef _MSC_VER // disable some level-4 warnings, use #pragma warning(enable:###) to re-enable #pragma warning(disable : 4100) // warning C4100: unreferenced formal parameter #pragma warning(disable : 4201) // warning C4201: nonstandard extension used : nameless struct/union #pragma warning(disable : 4511) // warning C4511: copy constructor could not be generated #pragma warning(disable : 4512) // warning C4512: assignment operator could not be generated #pragma warning(disable : 4514) // warning C4514: "unreferenced inline function has been removed" #if _MSC_VER >= 1100 #define AM_NOVTABLE __declspec(novtable) #else #define AM_NOVTABLE #endif #endif // MSC_VER // Because of differences between Visual C++ and older Microsoft SDKs, // you may have defined _DEBUG without defining DEBUG. This logic // ensures that both will be set if Visual C++ sets _DEBUG. #ifdef _DEBUG #ifndef DEBUG #define DEBUG #endif #endif #include #include #include #include #include #ifndef NUMELMS #if _WIN32_WINNT < 0x0600 #define NUMELMS(aa) (sizeof(aa) / sizeof((aa)[0])) #else #define NUMELMS(aa) ARRAYSIZE(aa) #endif #endif /////////////////////////////////////////////////////////////////////////// // The following definitions come from the Platform SDK and are required if // the applicaiton is being compiled with the headers from Visual C++ 6.0. /////////////////////////////////////////////////// //////////////////////// #ifndef InterlockedExchangePointer #define InterlockedExchangePointer(Target, Value) (PVOID) InterlockedExchange((PLONG)(Target), (LONG)(Value)) #endif #ifndef _WAVEFORMATEXTENSIBLE_ #define _WAVEFORMATEXTENSIBLE_ typedef struct { WAVEFORMATEX Format; union { WORD wValidBitsPerSample; /* bits of precision */ WORD wSamplesPerBlock; /* valid if wBitsPerSample==0 */ WORD wReserved; /* If neither applies, set to zero. */ } Samples; DWORD dwChannelMask; /* which channels are */ /* present in stream */ GUID SubFormat; } WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE; #endif // !_WAVEFORMATEXTENSIBLE_ #if !defined(WAVE_FORMAT_EXTENSIBLE) #define WAVE_FORMAT_EXTENSIBLE 0xFFFE #endif // !defined(WAVE_FORMAT_EXTENSIBLE) #ifndef GetWindowLongPtr #define GetWindowLongPtrA GetWindowLongA #define GetWindowLongPtrW GetWindowLongW #ifdef UNICODE #define GetWindowLongPtr GetWindowLongPtrW #else #define GetWindowLongPtr GetWindowLongPtrA #endif // !UNICODE #endif // !GetWindowLongPtr #ifndef SetWindowLongPtr #define SetWindowLongPtrA SetWindowLongA #define SetWindowLongPtrW SetWindowLongW #ifdef UNICODE #define SetWindowLongPtr SetWindowLongPtrW #else #define SetWindowLongPtr SetWindowLongPtrA #endif // !UNICODE #endif // !SetWindowLongPtr #ifndef GWLP_WNDPROC #define GWLP_WNDPROC (-4) #endif #ifndef GWLP_HINSTANCE #define GWLP_HINSTANCE (-6) #endif #ifndef GWLP_HWNDPARENT #define GWLP_HWNDPARENT (-8) #endif #ifndef GWLP_USERDATA #define GWLP_USERDATA (-21) #endif #ifndef GWLP_ID #define GWLP_ID (-12) #endif #ifndef DWLP_MSGRESULT #define DWLP_MSGRESULT 0 #endif #ifndef DWLP_DLGPROC #define DWLP_DLGPROC DWLP_MSGRESULT + sizeof(LRESULT) #endif #ifndef DWLP_USER #define DWLP_USER DWLP_DLGPROC + sizeof(DLGPROC) #endif #pragma warning(push) #pragma warning(disable : 4312 4244) // _GetWindowLongPtr // Templated version of GetWindowLongPtr, to suppress spurious compiler warning. template T _GetWindowLongPtr(HWND hwnd, int nIndex) { return (T)GetWindowLongPtr(hwnd, nIndex); } // _SetWindowLongPtr // Templated version of SetWindowLongPtr, to suppress spurious compiler warning. template LONG_PTR _SetWindowLongPtr(HWND hwnd, int nIndex, T p) { return SetWindowLongPtr(hwnd, nIndex, (LONG_PTR)p); } #pragma warning(pop) /////////////////////////////////////////////////////////////////////////// // End Platform SDK definitions /////////////////////////////////////////////////////////////////////////// #include // Generated IDL header file for streams interfaces #include // required by amvideo.h #include // Helper class for REFERENCE_TIME management #include // Debug support for logging and ASSERTs #include // ActiveMovie video interfaces and definitions // include amaudio.h explicitly if you need it. it requires the DX SDK. //#include // ActiveMovie audio interfaces and definitions #include // General helper classes for threads etc #include // Base COM classes to support IUnknown #include // Filter registration support functions #include // Performance measurement #include // Light weight com function prototypes #include // Simple cache container class #include // Non MFC generic list class #include // CMsgThread #include // Helper class for managing media types #include // conversions between FOURCCs and GUIDs #include // generated from control.odl #include // control interface utility classes #include // event code definitions #include // Main streams architecture class hierachy #include // Generic transform filter #include // Generic transform-in-place filter #include // declaration of type GUIDs and well-known clsids #include // Generic source filter #include // Output pin queueing #include // HRESULT status and error definitions #include // Base class for writing ActiveX renderers #include // Helps with filters that manage windows #include // Implements the IVideoWindow interface #include // Specifically video related classes #include // Base clock class #include // System clock #include // IPersistStream helper class #include // Video Transform Filter base class #include #include // Base property page class #include // IAMStreamControl support #include // External device control interface defines #include // audio filter device error event codes #else #ifdef DEBUG #pragma message("STREAMS.H included TWICE") #endif #endif // __STREAMS__ ================================================ FILE: common/baseclasses/strmctl.cpp ================================================ //------------------------------------------------------------------------------ // File: StrmCtl.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1996-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include CBaseStreamControl::CBaseStreamControl(__inout HRESULT *phr) : m_StreamState(STREAM_FLOWING) , m_StreamStateOnStop(STREAM_FLOWING) // means no pending stop , m_tStartTime(MAX_TIME) , m_tStopTime(MAX_TIME) , m_StreamEvent(FALSE, phr) , m_dwStartCookie(0) , m_dwStopCookie(0) , m_pRefClock(NULL) , m_FilterState(State_Stopped) , m_bIsFlushing(FALSE) , m_bStopSendExtra(FALSE) { } CBaseStreamControl::~CBaseStreamControl() { // Make sure we release the clock. SetSyncSource(NULL); return; } STDMETHODIMP CBaseStreamControl::StopAt(const REFERENCE_TIME *ptStop, BOOL bSendExtra, DWORD dwCookie) { CAutoLock lck(&m_CritSec); m_bStopSendExtra = FALSE; // reset m_bStopExtraSent = FALSE; if (ptStop) { if (*ptStop == MAX_TIME) { DbgLog((LOG_TRACE, 2, TEXT("StopAt: Cancel stop"))); CancelStop(); // If there's now a command to start in the future, we assume // they want to be stopped when the graph is first run if (m_FilterState == State_Stopped && m_tStartTime < MAX_TIME) { m_StreamState = STREAM_DISCARDING; DbgLog((LOG_TRACE, 2, TEXT("graph will begin by DISCARDING"))); } return NOERROR; } DbgLog((LOG_TRACE, 2, TEXT("StopAt: %dms extra=%d"), (int)(*ptStop / 10000), bSendExtra)); // if the first command is to stop in the future, then we assume they // want to be started when the graph is first run if (m_FilterState == State_Stopped && m_tStartTime > *ptStop) { m_StreamState = STREAM_FLOWING; DbgLog((LOG_TRACE, 2, TEXT("graph will begin by FLOWING"))); } m_bStopSendExtra = bSendExtra; m_tStopTime = *ptStop; m_dwStopCookie = dwCookie; m_StreamStateOnStop = STREAM_DISCARDING; } else { DbgLog((LOG_TRACE, 2, TEXT("StopAt: now"))); // sending an extra frame when told to stop now would mess people up m_bStopSendExtra = FALSE; m_tStopTime = MAX_TIME; m_dwStopCookie = 0; m_StreamState = STREAM_DISCARDING; m_StreamStateOnStop = STREAM_FLOWING; // no pending stop } // we might change our mind what to do with a sample we're blocking m_StreamEvent.Set(); return NOERROR; } STDMETHODIMP CBaseStreamControl::StartAt(const REFERENCE_TIME *ptStart, DWORD dwCookie) { CAutoLock lck(&m_CritSec); if (ptStart) { if (*ptStart == MAX_TIME) { DbgLog((LOG_TRACE, 2, TEXT("StartAt: Cancel start"))); CancelStart(); // If there's now a command to stop in the future, we assume // they want to be started when the graph is first run if (m_FilterState == State_Stopped && m_tStopTime < MAX_TIME) { DbgLog((LOG_TRACE, 2, TEXT("graph will begin by FLOWING"))); m_StreamState = STREAM_FLOWING; } return NOERROR; } DbgLog((LOG_TRACE, 2, TEXT("StartAt: %dms"), (int)(*ptStart / 10000))); // if the first command is to start in the future, then we assume they // want to be stopped when the graph is first run if (m_FilterState == State_Stopped && m_tStopTime >= *ptStart) { DbgLog((LOG_TRACE, 2, TEXT("graph will begin by DISCARDING"))); m_StreamState = STREAM_DISCARDING; } m_tStartTime = *ptStart; m_dwStartCookie = dwCookie; // if (m_tStopTime == m_tStartTime) CancelStop(); } else { DbgLog((LOG_TRACE, 2, TEXT("StartAt: now"))); m_tStartTime = MAX_TIME; m_dwStartCookie = 0; m_StreamState = STREAM_FLOWING; } // we might change our mind what to do with a sample we're blocking m_StreamEvent.Set(); return NOERROR; } // Retrieve information about current settings STDMETHODIMP CBaseStreamControl::GetInfo(__out AM_STREAM_INFO *pInfo) { if (pInfo == NULL) return E_POINTER; pInfo->tStart = m_tStartTime; pInfo->tStop = m_tStopTime; pInfo->dwStartCookie = m_dwStartCookie; pInfo->dwStopCookie = m_dwStopCookie; pInfo->dwFlags = m_bStopSendExtra ? AM_STREAM_INFO_STOP_SEND_EXTRA : 0; pInfo->dwFlags |= m_tStartTime == MAX_TIME ? 0 : AM_STREAM_INFO_START_DEFINED; pInfo->dwFlags |= m_tStopTime == MAX_TIME ? 0 : AM_STREAM_INFO_STOP_DEFINED; switch (m_StreamState) { default: DbgBreak("Invalid stream state"); case STREAM_FLOWING: break; case STREAM_DISCARDING: pInfo->dwFlags |= AM_STREAM_INFO_DISCARDING; break; } return S_OK; } void CBaseStreamControl::ExecuteStop() { ASSERT(CritCheckIn(&m_CritSec)); m_StreamState = m_StreamStateOnStop; if (m_dwStopCookie && m_pSink) { DbgLog((LOG_TRACE, 2, TEXT("*sending EC_STREAM_CONTROL_STOPPED (%d)"), m_dwStopCookie)); m_pSink->Notify(EC_STREAM_CONTROL_STOPPED, (LONG_PTR)this, m_dwStopCookie); } CancelStop(); // This will do the tidy up } void CBaseStreamControl::ExecuteStart() { ASSERT(CritCheckIn(&m_CritSec)); m_StreamState = STREAM_FLOWING; if (m_dwStartCookie) { DbgLog((LOG_TRACE, 2, TEXT("*sending EC_STREAM_CONTROL_STARTED (%d)"), m_dwStartCookie)); m_pSink->Notify(EC_STREAM_CONTROL_STARTED, (LONG_PTR)this, m_dwStartCookie); } CancelStart(); // This will do the tidy up } void CBaseStreamControl::CancelStop() { ASSERT(CritCheckIn(&m_CritSec)); m_tStopTime = MAX_TIME; m_dwStopCookie = 0; m_StreamStateOnStop = STREAM_FLOWING; } void CBaseStreamControl::CancelStart() { ASSERT(CritCheckIn(&m_CritSec)); m_tStartTime = MAX_TIME; m_dwStartCookie = 0; } // This guy will return one of the three StreamControlState's. Here's what the caller // should do for each one: // // STREAM_FLOWING: Proceed as usual (render or pass the sample on) // STREAM_DISCARDING: Calculate the time 'til *pSampleStart and wait that long // for the event handle (GetStreamEventHandle()). If the // wait expires, throw the sample away. If the event // fires, call me back, I've changed my mind. // I use pSampleStart (not Stop) so that live sources don't // block for the duration of their samples, since the clock // will always read approximately pSampleStart when called // All through this code, you'll notice the following rules: // - When start and stop time are the same, it's as if start was first // - An event is considered inside the sample when it's >= sample start time // but < sample stop time // - if any part of the sample is supposed to be sent, we'll send the whole // thing since we don't break it into smaller pieces // - If we skip over a start or stop without doing it, we still signal the event // and reset ourselves in case somebody's waiting for the event, and to make // sure we notice that the event is past and should be forgotten // Here are the 19 cases that have to be handled (x=start o=stop <-->=sample): // // 1. xo<--> start then stop // 2. ox<--> stop then start // 3. x start // 4. o stop then start // 5. x<-->o start // 6. o<-->x stop // 7. o start // 8. x no change // 9. start // 10. stop then start // 11. <-->xo no change // 12. <-->ox no change // 13. x<--> start // 14. start // 15. <-->x no change // 16. o<--> stop // 17. no change // 18. <-->o no change // 19. <--> no change enum CBaseStreamControl::StreamControlState CBaseStreamControl::CheckSampleTimes( __in const REFERENCE_TIME *pSampleStart, __in const REFERENCE_TIME *pSampleStop) { CAutoLock lck(&m_CritSec); ASSERT(!m_bIsFlushing); ASSERT(pSampleStart && pSampleStop); // Don't ask me how I came up with the code below to handle all 19 cases // - DannyMi if (m_tStopTime >= *pSampleStart) { if (m_tStartTime >= *pSampleStop) return m_StreamState; // cases 8 11 12 15 17 18 19 if (m_tStopTime < m_tStartTime) ExecuteStop(); // case 10 ExecuteStart(); // cases 3 5 7 9 13 14 return m_StreamState; } if (m_tStartTime >= *pSampleStop) { ExecuteStop(); // cases 6 16 return m_StreamState; } if (m_tStartTime <= m_tStopTime) { ExecuteStart(); ExecuteStop(); return m_StreamState; // case 1 } else { ExecuteStop(); ExecuteStart(); return m_StreamState; // cases 2 4 } } enum CBaseStreamControl::StreamControlState CBaseStreamControl::CheckStreamState(IMediaSample *pSample) { REFERENCE_TIME rtBufferStart, rtBufferStop; const BOOL bNoBufferTimes = pSample == NULL || FAILED(pSample->GetTime(&rtBufferStart, &rtBufferStop)); StreamControlState state; LONG lWait; do { // something has to break out of the blocking if (m_bIsFlushing || m_FilterState == State_Stopped) return STREAM_DISCARDING; if (bNoBufferTimes) { // Can't do anything until we get a time stamp state = m_StreamState; break; } else { state = CheckSampleTimes(&rtBufferStart, &rtBufferStop); if (state == STREAM_FLOWING) break; // we aren't supposed to send this, but we've been // told to send one more than we were supposed to // (and the stop isn't still pending and we're streaming) if (m_bStopSendExtra && !m_bStopExtraSent && m_tStopTime == MAX_TIME && m_FilterState != State_Stopped) { m_bStopExtraSent = TRUE; DbgLog((LOG_TRACE, 2, TEXT("%d sending an EXTRA frame"), m_dwStopCookie)); state = STREAM_FLOWING; break; } } // We're in discarding mode // If we've no clock, discard as fast as we can if (!m_pRefClock) { break; // If we're paused, we can't discard in a timely manner because // there's no such thing as stream times. We must block until // we run or stop, or we'll end up throwing the whole stream away // as quickly as possible } else if (m_FilterState == State_Paused) { lWait = INFINITE; } else { // wait until it's time for the sample until we say "discard" // ("discard in a timely fashion") REFERENCE_TIME rtNow; EXECUTE_ASSERT(SUCCEEDED(m_pRefClock->GetTime(&rtNow))); rtNow -= m_tRunStart; // Into relative ref-time lWait = LONG((rtBufferStart - rtNow) / 10000); // 100ns -> ms if (lWait < 10) break; // Not worth waiting - discard early } } while (WaitForSingleObject(GetStreamEventHandle(), lWait) != WAIT_TIMEOUT); return state; } void CBaseStreamControl::NotifyFilterState(FILTER_STATE new_state, REFERENCE_TIME tStart) { CAutoLock lck(&m_CritSec); // or we will get confused if (m_FilterState == new_state) return; switch (new_state) { case State_Stopped: DbgLog((LOG_TRACE, 2, TEXT("Filter is STOPPED"))); // execute any pending starts and stops in the right order, // to make sure all notifications get sent, and we end up // in the right state to begin next time (??? why not?) if (m_tStartTime != MAX_TIME && m_tStopTime == MAX_TIME) { ExecuteStart(); } else if (m_tStopTime != MAX_TIME && m_tStartTime == MAX_TIME) { ExecuteStop(); } else if (m_tStopTime != MAX_TIME && m_tStartTime != MAX_TIME) { if (m_tStartTime <= m_tStopTime) { ExecuteStart(); ExecuteStop(); } else { ExecuteStop(); ExecuteStart(); } } // always start off flowing when the graph starts streaming // unless told otherwise m_StreamState = STREAM_FLOWING; m_FilterState = new_state; break; case State_Running: DbgLog((LOG_TRACE, 2, TEXT("Filter is RUNNING"))); m_tRunStart = tStart; // fall-through default: // case State_Paused: m_FilterState = new_state; } // unblock! m_StreamEvent.Set(); } void CBaseStreamControl::Flushing(BOOL bInProgress) { CAutoLock lck(&m_CritSec); m_bIsFlushing = bInProgress; m_StreamEvent.Set(); } ================================================ FILE: common/baseclasses/strmctl.h ================================================ //------------------------------------------------------------------------------ // File: StrmCtl.h // // Desc: DirectShow base classes. // // Copyright (c) 1996-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __strmctl_h__ #define __strmctl_h__ class CBaseStreamControl : public IAMStreamControl { public: // Used by the implementation enum StreamControlState { STREAM_FLOWING = 0x1000, STREAM_DISCARDING }; private: enum StreamControlState m_StreamState; // Current stream state enum StreamControlState m_StreamStateOnStop; // State after next stop // (i.e.Blocking or Discarding) REFERENCE_TIME m_tStartTime; // MAX_TIME implies none REFERENCE_TIME m_tStopTime; // MAX_TIME implies none DWORD m_dwStartCookie; // Cookie for notification to app DWORD m_dwStopCookie; // Cookie for notification to app volatile BOOL m_bIsFlushing; // No optimization pls! volatile BOOL m_bStopSendExtra; // bSendExtra was set volatile BOOL m_bStopExtraSent; // the extra one was sent CCritSec m_CritSec; // CritSec to guard above attributes // Event to fire when we can come // out of blocking, or to come out of waiting // to discard if we change our minds. // CAMEvent m_StreamEvent; // All of these methods execute immediately. Helpers for others. // void ExecuteStop(); void ExecuteStart(); void CancelStop(); void CancelStart(); // Some things we need to be told by our owning filter // Your pin must also expose IAMStreamControl when QI'd for it! // IReferenceClock *m_pRefClock; // Need it to set advises // Filter must tell us via // SetSyncSource IMediaEventSink *m_pSink; // Event sink // Filter must tell us after it // creates it in JoinFilterGraph() FILTER_STATE m_FilterState; // Just need it! // Filter must tell us via // NotifyFilterState REFERENCE_TIME m_tRunStart; // Per the Run call to the filter // This guy will return one of the three StreamControlState's. Here's what // the caller should do for each one: // // STREAM_FLOWING: Proceed as usual (render or pass the sample on) // STREAM_DISCARDING: Calculate the time 'til *pSampleStop and wait // that long for the event handle // (GetStreamEventHandle()). If the wait // expires, throw the sample away. If the event // fires, call me back - I've changed my mind. // enum StreamControlState CheckSampleTimes(__in const REFERENCE_TIME *pSampleStart, __in const REFERENCE_TIME *pSampleStop); public: // You don't have to tell us much when we're created, but there are other // obligations that must be met. See SetSyncSource & NotifyFilterState // below. // CBaseStreamControl(__inout_opt HRESULT *phr = NULL); ~CBaseStreamControl(); // If you want this class to work properly, there are thing you need to // (keep) telling it. Filters with pins that use this class // should ensure that they pass through to this method any calls they // receive on their SetSyncSource. // We need a clock to see what time it is. This is for the // "discard in a timely fashion" logic. If we discard everything as // quick as possible, a whole 60 minute file could get discarded in the // first 10 seconds, and if somebody wants to turn streaming on at 30 // minutes into the file, and they make the call more than a few seconds // after the graph is run, it may be too late! // So we hold every sample until it's time has gone, then we discard it. // The filter should call this when it gets a SetSyncSource // void SetSyncSource(IReferenceClock *pRefClock) { CAutoLock lck(&m_CritSec); if (m_pRefClock) m_pRefClock->Release(); m_pRefClock = pRefClock; if (m_pRefClock) m_pRefClock->AddRef(); } // Set event sink for notifications // The filter should call this in its JoinFilterGraph after it creates the // IMediaEventSink // void SetFilterGraph(IMediaEventSink *pSink) { m_pSink = pSink; } // Since we schedule in stream time, we need the tStart and must track the // state of our owning filter. // The app should call this ever state change // void NotifyFilterState(FILTER_STATE new_state, REFERENCE_TIME tStart = 0); // Filter should call Flushing(TRUE) in BeginFlush, // and Flushing(FALSE) in EndFlush. // void Flushing(BOOL bInProgress); // The two main methods of IAMStreamControl // Class adds default values suitable for immediate // muting and unmuting of the stream. STDMETHODIMP StopAt(const REFERENCE_TIME *ptStop = NULL, BOOL bSendExtra = FALSE, DWORD dwCookie = 0); STDMETHODIMP StartAt(const REFERENCE_TIME *ptStart = NULL, DWORD dwCookie = 0); STDMETHODIMP GetInfo(__out AM_STREAM_INFO *pInfo); // Helper function for pin's receive method. Call this with // the sample and we'll tell you what to do with it. We'll do a // WaitForSingleObject within this call if one is required. This is // a "What should I do with this sample?" kind of call. We'll tell the // caller to either flow it or discard it. // If pSample is NULL we evaluate based on the current state // settings enum StreamControlState CheckStreamState(IMediaSample *pSample); private: // These don't require locking, but we are relying on the fact that // m_StreamState can be retrieved with integrity, and is a snap shot that // may have just been, or may be just about to be, changed. HANDLE GetStreamEventHandle() const { return m_StreamEvent; } enum StreamControlState GetStreamState() const { return m_StreamState; } BOOL IsStreaming() const { return m_StreamState == STREAM_FLOWING; } }; #endif ================================================ FILE: common/baseclasses/sysclock.cpp ================================================ //------------------------------------------------------------------------------ // File: SysClock.cpp // // Desc: DirectShow base classes - implements a system clock based on // IReferenceClock. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include #ifdef FILTER_DLL /* List of class IDs and creator functions for the class factory. This provides the link between the OLE entry point in the DLL and an object being created. The class factory will call the static CreateInstance function when it is asked to create a CLSID_SystemClock object */ CFactoryTemplate g_Templates[1] = {{&CLSID_SystemClock, CSystemClock::CreateInstance}}; int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); #endif /* This goes in the factory template table to create new instances */ CUnknown *WINAPI CSystemClock::CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) { return new CSystemClock(NAME("System reference clock"), pUnk, phr); } CSystemClock::CSystemClock(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr) : CBaseReferenceClock(pName, pUnk, phr) { } STDMETHODIMP CSystemClock::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_IPersist) { return GetInterface(static_cast(this), ppv); } else if (riid == IID_IAMClockAdjust) { return GetInterface(static_cast(this), ppv); } else { return CBaseReferenceClock::NonDelegatingQueryInterface(riid, ppv); } } /* Return the clock's clsid */ STDMETHODIMP CSystemClock::GetClassID(__out CLSID *pClsID) { CheckPointer(pClsID, E_POINTER); ValidateReadWritePtr(pClsID, sizeof(CLSID)); *pClsID = CLSID_SystemClock; return NOERROR; } STDMETHODIMP CSystemClock::SetClockDelta(REFERENCE_TIME rtDelta) { return SetTimeDelta(rtDelta); } ================================================ FILE: common/baseclasses/sysclock.h ================================================ //------------------------------------------------------------------------------ // File: SysClock.h // // Desc: DirectShow base classes - defines a system clock implementation of // IReferenceClock. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __SYSTEMCLOCK__ #define __SYSTEMCLOCK__ // // Base clock. Uses timeGetTime ONLY // Uses most of the code in the base reference clock. // Provides GetTime // class CSystemClock : public CBaseReferenceClock , public IAMClockAdjust , public IPersist { public: // We must be able to create an instance of ourselves static CUnknown *WINAPI CreateInstance(__inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); CSystemClock(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, __inout HRESULT *phr); DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // Yield up our class id so that we can be persisted // Implement required Ipersist method STDMETHODIMP GetClassID(__out CLSID *pClsID); // IAMClockAdjust methods STDMETHODIMP SetClockDelta(REFERENCE_TIME rtDelta); }; // CSystemClock #endif /* __SYSTEMCLOCK__ */ ================================================ FILE: common/baseclasses/transfrm.cpp ================================================ //------------------------------------------------------------------------------ // File: Transfrm.cpp // // Desc: DirectShow base classes - implements class for simple transform // filters such as video decompressors. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include // ================================================================= // Implements the CTransformFilter class // ================================================================= CTransformFilter::CTransformFilter(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, REFCLSID clsid) : CBaseFilter(pName, pUnk, &m_csFilter, clsid) , m_pInput(NULL) , m_pOutput(NULL) , m_bEOSDelivered(FALSE) , m_bQualityChanged(FALSE) , m_bSampleSkipped(FALSE) { #ifdef PERF RegisterPerfId(); #endif // PERF } #ifdef UNICODE CTransformFilter::CTransformFilter(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN pUnk, REFCLSID clsid) : CBaseFilter(pName, pUnk, &m_csFilter, clsid) , m_pInput(NULL) , m_pOutput(NULL) , m_bEOSDelivered(FALSE) , m_bQualityChanged(FALSE) , m_bSampleSkipped(FALSE) { #ifdef PERF RegisterPerfId(); #endif // PERF } #endif // destructor CTransformFilter::~CTransformFilter() { // Delete the pins delete m_pInput; delete m_pOutput; } // Transform place holder - should never be called HRESULT CTransformFilter::Transform(IMediaSample *pIn, IMediaSample *pOut) { UNREFERENCED_PARAMETER(pIn); UNREFERENCED_PARAMETER(pOut); DbgBreak("CTransformFilter::Transform() should never be called"); return E_UNEXPECTED; } // return the number of pins we provide int CTransformFilter::GetPinCount() { return 2; } // return a non-addrefed CBasePin * for the user to addref if he holds onto it // for longer than his pointer to us. We create the pins dynamically when they // are asked for rather than in the constructor. This is because we want to // give the derived class an oppportunity to return different pin objects // We return the objects as and when they are needed. If either of these fails // then we return NULL, the assumption being that the caller will realise the // whole deal is off and destroy us - which in turn will delete everything. CBasePin *CTransformFilter::GetPin(int n) { HRESULT hr = S_OK; // Create an input pin if necessary if (m_pInput == NULL) { m_pInput = new CTransformInputPin(NAME("Transform input pin"), this, // Owner filter &hr, // Result code L"XForm In"); // Pin name // Can't fail ASSERT(SUCCEEDED(hr)); if (m_pInput == NULL) { return NULL; } m_pOutput = (CTransformOutputPin *)new CTransformOutputPin(NAME("Transform output pin"), this, // Owner filter &hr, // Result code L"XForm Out"); // Pin name // Can't fail ASSERT(SUCCEEDED(hr)); if (m_pOutput == NULL) { delete m_pInput; m_pInput = NULL; } } // Return the appropriate pin if (n == 0) { return m_pInput; } else if (n == 1) { return m_pOutput; } else { return NULL; } } // // FindPin // // If Id is In or Out then return the IPin* for that pin // creating the pin if need be. Otherwise return NULL with an error. STDMETHODIMP CTransformFilter::FindPin(LPCWSTR Id, __deref_out IPin **ppPin) { CheckPointer(ppPin, E_POINTER); ValidateReadWritePtr(ppPin, sizeof(IPin *)); if (0 == lstrcmpW(Id, L"In")) { *ppPin = GetPin(0); } else if (0 == lstrcmpW(Id, L"Out")) { *ppPin = GetPin(1); } else { *ppPin = NULL; return VFW_E_NOT_FOUND; } HRESULT hr = NOERROR; // AddRef() returned pointer - but GetPin could fail if memory is low. if (*ppPin) { (*ppPin)->AddRef(); } else { hr = E_OUTOFMEMORY; // probably. There's no pin anyway. } return hr; } // override these two functions if you want to inform something // about entry to or exit from streaming state. HRESULT CTransformFilter::StartStreaming() { return NOERROR; } HRESULT CTransformFilter::StopStreaming() { return NOERROR; } // override this to grab extra interfaces on connection HRESULT CTransformFilter::CheckConnect(PIN_DIRECTION dir, IPin *pPin) { UNREFERENCED_PARAMETER(dir); UNREFERENCED_PARAMETER(pPin); return NOERROR; } // place holder to allow derived classes to release any extra interfaces HRESULT CTransformFilter::BreakConnect(PIN_DIRECTION dir) { UNREFERENCED_PARAMETER(dir); return NOERROR; } // Let derived classes know about connection completion HRESULT CTransformFilter::CompleteConnect(PIN_DIRECTION direction, IPin *pReceivePin) { UNREFERENCED_PARAMETER(direction); UNREFERENCED_PARAMETER(pReceivePin); return NOERROR; } // override this to know when the media type is really set HRESULT CTransformFilter::SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt) { UNREFERENCED_PARAMETER(direction); UNREFERENCED_PARAMETER(pmt); return NOERROR; } // Set up our output sample HRESULT CTransformFilter::InitializeOutputSample(IMediaSample *pSample, __deref_out IMediaSample **ppOutSample) { IMediaSample *pOutSample; // default - times are the same AM_SAMPLE2_PROPERTIES *const pProps = m_pInput->SampleProps(); DWORD dwFlags = m_bSampleSkipped ? AM_GBF_PREVFRAMESKIPPED : 0; // This will prevent the image renderer from switching us to DirectDraw // when we can't do it without skipping frames because we're not on a // keyframe. If it really has to switch us, it still will, but then we // will have to wait for the next keyframe if (!(pProps->dwSampleFlags & AM_SAMPLE_SPLICEPOINT)) { dwFlags |= AM_GBF_NOTASYNCPOINT; } ASSERT(m_pOutput->m_pAllocator != NULL); HRESULT hr = m_pOutput->m_pAllocator->GetBuffer( &pOutSample, pProps->dwSampleFlags & AM_SAMPLE_TIMEVALID ? &pProps->tStart : NULL, pProps->dwSampleFlags & AM_SAMPLE_STOPVALID ? &pProps->tStop : NULL, dwFlags); *ppOutSample = pOutSample; if (FAILED(hr)) { return hr; } ASSERT(pOutSample); IMediaSample2 *pOutSample2; if (SUCCEEDED(pOutSample->QueryInterface(IID_IMediaSample2, (void **)&pOutSample2))) { /* Modify it */ AM_SAMPLE2_PROPERTIES OutProps; EXECUTE_ASSERT( SUCCEEDED(pOutSample2->GetProperties(FIELD_OFFSET(AM_SAMPLE2_PROPERTIES, tStart), (PBYTE)&OutProps))); OutProps.dwTypeSpecificFlags = pProps->dwTypeSpecificFlags; OutProps.dwSampleFlags = (OutProps.dwSampleFlags & AM_SAMPLE_TYPECHANGED) | (pProps->dwSampleFlags & ~AM_SAMPLE_TYPECHANGED); OutProps.tStart = pProps->tStart; OutProps.tStop = pProps->tStop; OutProps.cbData = FIELD_OFFSET(AM_SAMPLE2_PROPERTIES, dwStreamId); hr = pOutSample2->SetProperties(FIELD_OFFSET(AM_SAMPLE2_PROPERTIES, dwStreamId), (PBYTE)&OutProps); if (pProps->dwSampleFlags & AM_SAMPLE_DATADISCONTINUITY) { m_bSampleSkipped = FALSE; } pOutSample2->Release(); } else { if (pProps->dwSampleFlags & AM_SAMPLE_TIMEVALID) { pOutSample->SetTime(&pProps->tStart, &pProps->tStop); } if (pProps->dwSampleFlags & AM_SAMPLE_SPLICEPOINT) { pOutSample->SetSyncPoint(TRUE); } if (pProps->dwSampleFlags & AM_SAMPLE_DATADISCONTINUITY) { pOutSample->SetDiscontinuity(TRUE); m_bSampleSkipped = FALSE; } // Copy the media times LONGLONG MediaStart, MediaEnd; if (pSample->GetMediaTime(&MediaStart, &MediaEnd) == NOERROR) { pOutSample->SetMediaTime(&MediaStart, &MediaEnd); } } return S_OK; } // override this to customize the transform process HRESULT CTransformFilter::Receive(IMediaSample *pSample) { /* Check for other streams and pass them on */ AM_SAMPLE2_PROPERTIES *const pProps = m_pInput->SampleProps(); if (pProps->dwStreamId != AM_STREAM_MEDIA) { return m_pOutput->m_pInputPin->Receive(pSample); } HRESULT hr; ASSERT(pSample); IMediaSample *pOutSample; // If no output to deliver to then no point sending us data ASSERT(m_pOutput != NULL); // Set up the output sample hr = InitializeOutputSample(pSample, &pOutSample); if (FAILED(hr)) { return hr; } // Start timing the transform (if PERF is defined) MSR_START(m_idTransform); // have the derived class transform the data hr = Transform(pSample, pOutSample); // Stop the clock and log it (if PERF is defined) MSR_STOP(m_idTransform); if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, TEXT("Error from transform"))); } else { // the Transform() function can return S_FALSE to indicate that the // sample should not be delivered; we only deliver the sample if it's // really S_OK (same as NOERROR, of course.) if (hr == NOERROR) { hr = m_pOutput->m_pInputPin->Receive(pOutSample); m_bSampleSkipped = FALSE; // last thing no longer dropped } else { // S_FALSE returned from Transform is a PRIVATE agreement // We should return NOERROR from Receive() in this cause because returning S_FALSE // from Receive() means that this is the end of the stream and no more data should // be sent. if (S_FALSE == hr) { // Release the sample before calling notify to avoid // deadlocks if the sample holds a lock on the system // such as DirectDraw buffers do pOutSample->Release(); m_bSampleSkipped = TRUE; if (!m_bQualityChanged) { NotifyEvent(EC_QUALITY_CHANGE, 0, 0); m_bQualityChanged = TRUE; } return NOERROR; } } } // release the output buffer. If the connected pin still needs it, // it will have addrefed it itself. pOutSample->Release(); return hr; } // Return S_FALSE to mean "pass the note on upstream" // Return NOERROR (Same as S_OK) // to mean "I've done something about it, don't pass it on" HRESULT CTransformFilter::AlterQuality(Quality q) { UNREFERENCED_PARAMETER(q); return S_FALSE; } // EndOfStream received. Default behaviour is to deliver straight // downstream, since we have no queued data. If you overrode Receive // and have queue data, then you need to handle this and deliver EOS after // all queued data is sent HRESULT CTransformFilter::EndOfStream(void) { HRESULT hr = NOERROR; if (m_pOutput != NULL) { hr = m_pOutput->DeliverEndOfStream(); } return hr; } // enter flush state. Receives already blocked // must override this if you have queued data or a worker thread HRESULT CTransformFilter::BeginFlush(void) { HRESULT hr = NOERROR; if (m_pOutput != NULL) { // block receives -- done by caller (CBaseInputPin::BeginFlush) // discard queued data -- we have no queued data // free anyone blocked on receive - not possible in this filter // call downstream hr = m_pOutput->DeliverBeginFlush(); } return hr; } // leave flush state. must override this if you have queued data // or a worker thread HRESULT CTransformFilter::EndFlush(void) { // sync with pushing thread -- we have no worker thread // ensure no more data to go downstream -- we have no queued data // call EndFlush on downstream pins ASSERT(m_pOutput != NULL); return m_pOutput->DeliverEndFlush(); // caller (the input pin's method) will unblock Receives } // override these so that the derived filter can catch them STDMETHODIMP CTransformFilter::Stop() { CAutoLock lck1(&m_csFilter); if (m_State == State_Stopped) { return NOERROR; } // Succeed the Stop if we are not completely connected ASSERT(m_pInput == NULL || m_pOutput != NULL); if (m_pInput == NULL || m_pInput->IsConnected() == FALSE || m_pOutput->IsConnected() == FALSE) { m_State = State_Stopped; m_bEOSDelivered = FALSE; return NOERROR; } ASSERT(m_pInput); ASSERT(m_pOutput); // decommit the input pin before locking or we can deadlock m_pInput->Inactive(); // synchronize with Receive calls CAutoLock lck2(&m_csReceive); m_pOutput->Inactive(); // allow a class derived from CTransformFilter // to know about starting and stopping streaming HRESULT hr = StopStreaming(); if (SUCCEEDED(hr)) { // complete the state transition m_State = State_Stopped; m_bEOSDelivered = FALSE; } return hr; } STDMETHODIMP CTransformFilter::Pause() { CAutoLock lck(&m_csFilter); HRESULT hr = NOERROR; if (m_State == State_Paused) { // (This space left deliberately blank) } // If we have no input pin or it isn't yet connected then when we are // asked to pause we deliver an end of stream to the downstream filter. // This makes sure that it doesn't sit there forever waiting for // samples which we cannot ever deliver without an input connection. else if (m_pInput == NULL || m_pInput->IsConnected() == FALSE) { if (m_pOutput && m_bEOSDelivered == FALSE) { m_pOutput->DeliverEndOfStream(); m_bEOSDelivered = TRUE; } m_State = State_Paused; } // We may have an input connection but no output connection // However, if we have an input pin we do have an output pin else if (m_pOutput->IsConnected() == FALSE) { m_State = State_Paused; } else { if (m_State == State_Stopped) { // allow a class derived from CTransformFilter // to know about starting and stopping streaming CAutoLock lck2(&m_csReceive); hr = StartStreaming(); } if (SUCCEEDED(hr)) { hr = CBaseFilter::Pause(); } } m_bSampleSkipped = FALSE; m_bQualityChanged = FALSE; return hr; } HRESULT CTransformFilter::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { if (m_pOutput != NULL) { return m_pOutput->DeliverNewSegment(tStart, tStop, dRate); } return S_OK; } // Check streaming status HRESULT CTransformInputPin::CheckStreaming() { ASSERT(m_pTransformFilter->m_pOutput != NULL); if (!m_pTransformFilter->m_pOutput->IsConnected()) { return VFW_E_NOT_CONNECTED; } else { // Shouldn't be able to get any data if we're not connected! ASSERT(IsConnected()); // we're flushing if (m_bFlushing) { return S_FALSE; } // Don't process stuff in Stopped state if (IsStopped()) { return VFW_E_WRONG_STATE; } if (m_bRunTimeError) { return VFW_E_RUNTIME_ERROR; } return S_OK; } } // ================================================================= // Implements the CTransformInputPin class // ================================================================= // constructor CTransformInputPin::CTransformInputPin(__in_opt LPCTSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBaseInputPin(pObjectName, pTransformFilter, &pTransformFilter->m_csFilter, phr, pName) { DbgLog((LOG_TRACE, 2, TEXT("CTransformInputPin::CTransformInputPin"))); m_pTransformFilter = pTransformFilter; } #ifdef UNICODE CTransformInputPin::CTransformInputPin(__in_opt LPCSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CBaseInputPin(pObjectName, pTransformFilter, &pTransformFilter->m_csFilter, phr, pName) { DbgLog((LOG_TRACE, 2, TEXT("CTransformInputPin::CTransformInputPin"))); m_pTransformFilter = pTransformFilter; } #endif // provides derived filter a chance to grab extra interfaces HRESULT CTransformInputPin::CheckConnect(IPin *pPin) { HRESULT hr = m_pTransformFilter->CheckConnect(PINDIR_INPUT, pPin); if (FAILED(hr)) { return hr; } return CBaseInputPin::CheckConnect(pPin); } // provides derived filter a chance to release it's extra interfaces HRESULT CTransformInputPin::BreakConnect() { // Can't disconnect unless stopped ASSERT(IsStopped()); m_pTransformFilter->BreakConnect(PINDIR_INPUT); return CBaseInputPin::BreakConnect(); } // Let derived class know when the input pin is connected HRESULT CTransformInputPin::CompleteConnect(IPin *pReceivePin) { HRESULT hr = m_pTransformFilter->CompleteConnect(PINDIR_INPUT, pReceivePin); if (FAILED(hr)) { return hr; } return CBaseInputPin::CompleteConnect(pReceivePin); } // check that we can support a given media type HRESULT CTransformInputPin::CheckMediaType(const CMediaType *pmt) { // Check the input type HRESULT hr = m_pTransformFilter->CheckInputType(pmt); if (S_OK != hr) { return hr; } // if the output pin is still connected, then we have // to check the transform not just the input format if ((m_pTransformFilter->m_pOutput != NULL) && (m_pTransformFilter->m_pOutput->IsConnected())) { return m_pTransformFilter->CheckTransform(pmt, &m_pTransformFilter->m_pOutput->CurrentMediaType()); } else { return hr; } } // set the media type for this connection HRESULT CTransformInputPin::SetMediaType(const CMediaType *mtIn) { // Set the base class media type (should always succeed) HRESULT hr = CBasePin::SetMediaType(mtIn); if (FAILED(hr)) { return hr; } // check the transform can be done (should always succeed) ASSERT(SUCCEEDED(m_pTransformFilter->CheckInputType(mtIn))); return m_pTransformFilter->SetMediaType(PINDIR_INPUT, mtIn); } // ================================================================= // Implements IMemInputPin interface // ================================================================= // provide EndOfStream that passes straight downstream // (there is no queued data) STDMETHODIMP CTransformInputPin::EndOfStream(void) { CAutoLock lck(&m_pTransformFilter->m_csReceive); HRESULT hr = CheckStreaming(); if (S_OK == hr) { hr = m_pTransformFilter->EndOfStream(); } return hr; } // enter flushing state. Call default handler to block Receives, then // pass to overridable method in filter STDMETHODIMP CTransformInputPin::BeginFlush(void) { CAutoLock lck(&m_pTransformFilter->m_csFilter); // Are we actually doing anything? ASSERT(m_pTransformFilter->m_pOutput != NULL); if (!IsConnected() || !m_pTransformFilter->m_pOutput->IsConnected()) { return VFW_E_NOT_CONNECTED; } HRESULT hr = CBaseInputPin::BeginFlush(); if (FAILED(hr)) { return hr; } return m_pTransformFilter->BeginFlush(); } // leave flushing state. // Pass to overridable method in filter, then call base class // to unblock receives (finally) STDMETHODIMP CTransformInputPin::EndFlush(void) { CAutoLock lck(&m_pTransformFilter->m_csFilter); // Are we actually doing anything? ASSERT(m_pTransformFilter->m_pOutput != NULL); if (!IsConnected() || !m_pTransformFilter->m_pOutput->IsConnected()) { return VFW_E_NOT_CONNECTED; } HRESULT hr = m_pTransformFilter->EndFlush(); if (FAILED(hr)) { return hr; } return CBaseInputPin::EndFlush(); } // here's the next block of data from the stream. // AddRef it yourself if you need to hold it beyond the end // of this call. HRESULT CTransformInputPin::Receive(IMediaSample *pSample) { HRESULT hr; CAutoLock lck(&m_pTransformFilter->m_csReceive); ASSERT(pSample); // check all is well with the base class hr = CBaseInputPin::Receive(pSample); if (S_OK == hr) { hr = m_pTransformFilter->Receive(pSample); } return hr; } // override to pass downstream STDMETHODIMP CTransformInputPin::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { // Save the values in the pin CBasePin::NewSegment(tStart, tStop, dRate); return m_pTransformFilter->NewSegment(tStart, tStop, dRate); } // ================================================================= // Implements the CTransformOutputPin class // ================================================================= // constructor CTransformOutputPin::CTransformOutputPin(__in_opt LPCTSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pPinName) : CBaseOutputPin(pObjectName, pTransformFilter, &pTransformFilter->m_csFilter, phr, pPinName) , m_pPosition(NULL) { DbgLog((LOG_TRACE, 2, TEXT("CTransformOutputPin::CTransformOutputPin"))); m_pTransformFilter = pTransformFilter; } #ifdef UNICODE CTransformOutputPin::CTransformOutputPin(__in_opt LPCSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pPinName) : CBaseOutputPin(pObjectName, pTransformFilter, &pTransformFilter->m_csFilter, phr, pPinName) , m_pPosition(NULL) { DbgLog((LOG_TRACE, 2, TEXT("CTransformOutputPin::CTransformOutputPin"))); m_pTransformFilter = pTransformFilter; } #endif // destructor CTransformOutputPin::~CTransformOutputPin() { DbgLog((LOG_TRACE, 2, TEXT("CTransformOutputPin::~CTransformOutputPin"))); if (m_pPosition) m_pPosition->Release(); } // overriden to expose IMediaPosition and IMediaSeeking control interfaces STDMETHODIMP CTransformOutputPin::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); ValidateReadWritePtr(ppv, sizeof(PVOID)); *ppv = NULL; if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking) { // we should have an input pin by now ASSERT(m_pTransformFilter->m_pInput != NULL); if (m_pPosition == NULL) { HRESULT hr = CreatePosPassThru(GetOwner(), FALSE, (IPin *)m_pTransformFilter->m_pInput, &m_pPosition); if (FAILED(hr)) { return hr; } } return m_pPosition->QueryInterface(riid, ppv); } else { return CBaseOutputPin::NonDelegatingQueryInterface(riid, ppv); } } // provides derived filter a chance to grab extra interfaces HRESULT CTransformOutputPin::CheckConnect(IPin *pPin) { // we should have an input connection first ASSERT(m_pTransformFilter->m_pInput != NULL); if ((m_pTransformFilter->m_pInput->IsConnected() == FALSE)) { return E_UNEXPECTED; } HRESULT hr = m_pTransformFilter->CheckConnect(PINDIR_OUTPUT, pPin); if (FAILED(hr)) { return hr; } return CBaseOutputPin::CheckConnect(pPin); } // provides derived filter a chance to release it's extra interfaces HRESULT CTransformOutputPin::BreakConnect() { // Can't disconnect unless stopped ASSERT(IsStopped()); m_pTransformFilter->BreakConnect(PINDIR_OUTPUT); return CBaseOutputPin::BreakConnect(); } // Let derived class know when the output pin is connected HRESULT CTransformOutputPin::CompleteConnect(IPin *pReceivePin) { HRESULT hr = m_pTransformFilter->CompleteConnect(PINDIR_OUTPUT, pReceivePin); if (FAILED(hr)) { return hr; } return CBaseOutputPin::CompleteConnect(pReceivePin); } // check a given transform - must have selected input type first HRESULT CTransformOutputPin::CheckMediaType(const CMediaType *pmtOut) { // must have selected input first ASSERT(m_pTransformFilter->m_pInput != NULL); if ((m_pTransformFilter->m_pInput->IsConnected() == FALSE)) { return E_INVALIDARG; } return m_pTransformFilter->CheckTransform(&m_pTransformFilter->m_pInput->CurrentMediaType(), pmtOut); } // called after we have agreed a media type to actually set it in which case // we run the CheckTransform function to get the output format type again HRESULT CTransformOutputPin::SetMediaType(const CMediaType *pmtOut) { HRESULT hr = NOERROR; ASSERT(m_pTransformFilter->m_pInput != NULL); ASSERT(m_pTransformFilter->m_pInput->CurrentMediaType().IsValid()); // Set the base class media type (should always succeed) hr = CBasePin::SetMediaType(pmtOut); if (FAILED(hr)) { return hr; } #ifdef DEBUG if (FAILED(m_pTransformFilter->CheckTransform(&m_pTransformFilter->m_pInput->CurrentMediaType(), pmtOut))) { DbgLog((LOG_ERROR, 0, TEXT("*** This filter is accepting an output media type"))); DbgLog((LOG_ERROR, 0, TEXT(" that it can't currently transform to. I hope"))); DbgLog((LOG_ERROR, 0, TEXT(" it's smart enough to reconnect its input."))); } #endif return m_pTransformFilter->SetMediaType(PINDIR_OUTPUT, pmtOut); } // pass the buffer size decision through to the main transform class HRESULT CTransformOutputPin::DecideBufferSize(IMemAllocator *pAllocator, __inout ALLOCATOR_PROPERTIES *pProp) { return m_pTransformFilter->DecideBufferSize(pAllocator, pProp); } // return a specific media type indexed by iPosition HRESULT CTransformOutputPin::GetMediaType(int iPosition, __inout CMediaType *pMediaType) { ASSERT(m_pTransformFilter->m_pInput != NULL); // We don't have any media types if our input is not connected if (m_pTransformFilter->m_pInput->IsConnected()) { return m_pTransformFilter->GetMediaType(iPosition, pMediaType); } else { return VFW_S_NO_MORE_ITEMS; } } // Override this if you can do something constructive to act on the // quality message. Consider passing it upstream as well // Pass the quality mesage on upstream. STDMETHODIMP CTransformOutputPin::Notify(IBaseFilter *pSender, Quality q) { UNREFERENCED_PARAMETER(pSender); ValidateReadPtr(pSender, sizeof(IBaseFilter)); // First see if we want to handle this ourselves HRESULT hr = m_pTransformFilter->AlterQuality(q); if (hr != S_FALSE) { return hr; // either S_OK or a failure } // S_FALSE means we pass the message on. // Find the quality sink for our input pin and send it there ASSERT(m_pTransformFilter->m_pInput != NULL); return m_pTransformFilter->m_pInput->PassNotify(q); } // Notify // the following removes a very large number of level 4 warnings from the microsoft // compiler output, which are not useful at all in this case. #pragma warning(disable : 4514) ================================================ FILE: common/baseclasses/transfrm.h ================================================ //------------------------------------------------------------------------------ // File: Transfrm.h // // Desc: DirectShow base classes - defines classes from which simple // transform codecs may be derived. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // It assumes the codec has one input and one output stream, and has no // interest in memory management, interface negotiation or anything else. // // derive your class from this, and supply Transform and the media type/format // negotiation functions. Implement that class, compile and link and // you're done. #ifndef __TRANSFRM__ #define __TRANSFRM__ // ====================================================================== // This is the com object that represents a simple transform filter. It // supports IBaseFilter, IMediaFilter and two pins through nested interfaces // ====================================================================== class CTransformFilter; // ================================================== // Implements the input pin // ================================================== class CTransformInputPin : public CBaseInputPin { friend class CTransformFilter; protected: CTransformFilter *m_pTransformFilter; public: CTransformInputPin(__in_opt LPCTSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName); #ifdef UNICODE CTransformInputPin(__in_opt LPCSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName); #endif STDMETHODIMP QueryId(__deref_out LPWSTR *Id) { return AMGetWideString(L"In", Id); } // Grab and release extra interfaces if required HRESULT CheckConnect(IPin *pPin); HRESULT BreakConnect(); HRESULT CompleteConnect(IPin *pReceivePin); // check that we can support this output type HRESULT CheckMediaType(const CMediaType *mtIn); // set the connection media type HRESULT SetMediaType(const CMediaType *mt); // --- IMemInputPin ----- // here's the next block of data from the stream. // AddRef it yourself if you need to hold it beyond the end // of this call. STDMETHODIMP Receive(IMediaSample *pSample); // provide EndOfStream that passes straight downstream // (there is no queued data) STDMETHODIMP EndOfStream(void); // passes it to CTransformFilter::BeginFlush STDMETHODIMP BeginFlush(void); // passes it to CTransformFilter::EndFlush STDMETHODIMP EndFlush(void); STDMETHODIMP NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); // Check if it's OK to process samples virtual HRESULT CheckStreaming(); // Media type public: CMediaType &CurrentMediaType() { return m_mt; }; }; // ================================================== // Implements the output pin // ================================================== class CTransformOutputPin : public CBaseOutputPin { friend class CTransformFilter; protected: CTransformFilter *m_pTransformFilter; public: // implement IMediaPosition by passing upstream IUnknown *m_pPosition; CTransformOutputPin(__in_opt LPCTSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName); #ifdef UNICODE CTransformOutputPin(__in_opt LPCSTR pObjectName, __inout CTransformFilter *pTransformFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName); #endif ~CTransformOutputPin(); // override to expose IMediaPosition STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // --- CBaseOutputPin ------------ STDMETHODIMP QueryId(__deref_out LPWSTR *Id) { return AMGetWideString(L"Out", Id); } // Grab and release extra interfaces if required HRESULT CheckConnect(IPin *pPin); HRESULT BreakConnect(); HRESULT CompleteConnect(IPin *pReceivePin); // check that we can support this output type HRESULT CheckMediaType(const CMediaType *mtOut); // set the connection media type HRESULT SetMediaType(const CMediaType *pmt); // called from CBaseOutputPin during connection to ask for // the count and size of buffers we need. HRESULT DecideBufferSize(IMemAllocator *pAlloc, __inout ALLOCATOR_PROPERTIES *pProp); // returns the preferred formats for a pin HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType); // inherited from IQualityControl via CBasePin STDMETHODIMP Notify(IBaseFilter *pSender, Quality q); // Media type public: CMediaType &CurrentMediaType() { return m_mt; }; }; class AM_NOVTABLE CTransformFilter : public CBaseFilter { public: // map getpin/getpincount for base enum of pins to owner // override this to return more specialised pin objects virtual int GetPinCount(); virtual CBasePin *GetPin(int n); STDMETHODIMP FindPin(LPCWSTR Id, __deref_out IPin **ppPin); // override state changes to allow derived transform filter // to control streaming start/stop STDMETHODIMP Stop(); STDMETHODIMP Pause(); public: CTransformFilter(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, REFCLSID clsid); #ifdef UNICODE CTransformFilter(__in_opt LPCSTR, __inout_opt LPUNKNOWN, REFCLSID clsid); #endif ~CTransformFilter(); // ================================================================= // ----- override these bits --------------------------------------- // ================================================================= // These must be supplied in a derived class virtual HRESULT Transform(IMediaSample *pIn, IMediaSample *pOut); // check if you can support mtIn virtual HRESULT CheckInputType(const CMediaType *mtIn) PURE; // check if you can support the transform from this input to this output virtual HRESULT CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut) PURE; // this goes in the factory template table to create new instances // static CCOMObject * CreateInstance(__inout_opt LPUNKNOWN, HRESULT *); // call the SetProperties function with appropriate arguments virtual HRESULT DecideBufferSize(IMemAllocator *pAllocator, __inout ALLOCATOR_PROPERTIES *pprop) PURE; // override to suggest OUTPUT pin media types virtual HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType) PURE; // ================================================================= // ----- Optional Override Methods ----------------------- // ================================================================= // you can also override these if you want to know about streaming virtual HRESULT StartStreaming(); virtual HRESULT StopStreaming(); // override if you can do anything constructive with quality notifications virtual HRESULT AlterQuality(Quality q); // override this to know when the media type is actually set virtual HRESULT SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt); // chance to grab extra interfaces on connection virtual HRESULT CheckConnect(PIN_DIRECTION dir, IPin *pPin); virtual HRESULT BreakConnect(PIN_DIRECTION dir); virtual HRESULT CompleteConnect(PIN_DIRECTION direction, IPin *pReceivePin); // chance to customize the transform process virtual HRESULT Receive(IMediaSample *pSample); // Standard setup for output sample HRESULT InitializeOutputSample(IMediaSample *pSample, __deref_out IMediaSample **ppOutSample); // if you override Receive, you may need to override these three too virtual HRESULT EndOfStream(void); virtual HRESULT BeginFlush(void); virtual HRESULT EndFlush(void); virtual HRESULT NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); #ifdef PERF // Override to register performance measurement with a less generic string // You should do this to avoid confusion with other filters virtual void RegisterPerfId() { m_idTransform = MSR_REGISTER(TEXT("Transform")); } #endif // PERF // implementation details protected: #ifdef PERF int m_idTransform; // performance measuring id #endif BOOL m_bEOSDelivered; // have we sent EndOfStream BOOL m_bSampleSkipped; // Did we just skip a frame BOOL m_bQualityChanged; // Have we degraded? // critical section protecting filter state. CCritSec m_csFilter; // critical section stopping state changes (ie Stop) while we're // processing a sample. // // This critical section is held when processing // events that occur on the receive thread - Receive() and EndOfStream(). // // If you want to hold both m_csReceive and m_csFilter then grab // m_csFilter FIRST - like CTransformFilter::Stop() does. CCritSec m_csReceive; // these hold our input and output pins friend class CTransformInputPin; friend class CTransformOutputPin; CTransformInputPin *m_pInput; CTransformOutputPin *m_pOutput; }; #endif /* __TRANSFRM__ */ ================================================ FILE: common/baseclasses/transip.cpp ================================================ //------------------------------------------------------------------------------ // File: TransIP.cpp // // Desc: DirectShow base classes - implements class for simple Transform- // In-Place filters such as audio. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // How allocators are decided. // // An in-place transform tries to do its work in someone else's buffers. // It tries to persuade the filters on either side to use the same allocator // (and for that matter the same media type). In desperation, if the downstream // filter refuses to supply an allocator and the upstream filter offers only // a read-only one then it will provide an allocator. // if the upstream filter insists on a read-only allocator then the transform // filter will (reluctantly) copy the data before transforming it. // // In order to pass an allocator through it needs to remember the one it got // from the first connection to pass it on to the second one. // // It is good if we can avoid insisting on a particular order of connection // (There is a precedent for insisting on the input // being connected first. Insisting on the output being connected first is // not allowed. That would break RenderFile.) // // The base pin classes (CBaseOutputPin and CBaseInputPin) both have a // m_pAllocator member which is used in places like // CBaseOutputPin::GetDeliveryBuffer and CBaseInputPin::Inactive. // To avoid lots of extra overriding, we should keep these happy // by using these pointers. // // When each pin is connected, it will set the corresponding m_pAllocator // and will have a single ref-count on that allocator. // // Refcounts are acquired by GetAllocator calls which return AddReffed // allocators and are released in one of: // CBaseInputPin::Disconnect // CBaseOutputPin::BreakConect // In each case m_pAllocator is set to NULL after the release, so this // is the last chance to ever release it. If there should ever be // multiple refcounts associated with the same pointer, this had better // be cleared up before that happens. To avoid such problems, we'll // stick with one per pointer. // RECONNECTING and STATE CHANGES // // Each pin could be disconnected, connected with a read-only allocator, // connected with an upstream read/write allocator, connected with an // allocator from downstream or connected with its own allocator. // Five states for each pin gives a data space of 25 states. // // Notation: // // R/W == read/write // R-O == read-only // // // // 00 means an unconnected pin. // <- means using a R/W allocator from the upstream filter // <= means using a R-O allocator from an upstream filter // || means using our own (R/W) allocator. // -> means using a R/W allocator from a downstream filter // (a R-O allocator from downstream is nonsense, it can't ever work). // // // That makes 25 possible states. Some states are nonsense (two different // allocators from the same place). These are just an artifact of the notation. // <= <- Nonsense. // <- <= Nonsense // Some states are illegal (the output pin never accepts a R-O allocator): // 00 <= !! Error !! // <= <= !! Error !! // || <= !! Error !! // -> <= !! Error !! // Three states appears to be inaccessible: // -> || Inaccessible // || -> Inaccessible // || <- Inaccessible // Some states only ever occur as intermediates with a pending reconnect which // is guaranteed to finish in another state. // -> 00 ?? unstable goes to || 00 // 00 <- ?? unstable goes to 00 || // -> <- ?? unstable goes to -> -> // <- || ?? unstable goes to <- <- // <- -> ?? unstable goes to <- <- // And that leaves 11 possible resting states: // 1 00 00 Nothing connected. // 2 <- 00 Input pin connected. // 3 <= 00 Input pin connected using R-O allocator. // 4 || 00 Needs several state changes to get here. // 5 00 || Output pin connected using our allocator // 6 00 -> Downstream only connected // 7 || || Undesirable but can be forced upon us. // 8 <= || Copy forced. <= -> is preferable // 9 <= -> OK - forced to copy. // 10 <- <- Transform in place (ideal) // 11 -> -> Transform in place (ideal) // // The object of the exercise is to ensure that we finish up in states // 10 or 11 whenever possible. State 10 is only possible if the upstream // filter has a R/W allocator (the AVI splitter notoriously // doesn't) and state 11 is only possible if the downstream filter does // offer an allocator. // // The transition table (entries marked * go via a reconnect) // // There are 8 possible transitions: // A: Connect upstream to filter with R-O allocator that insists on using it. // B: Connect upstream to filter with R-O allocator but chooses not to use it. // C: Connect upstream to filter with R/W allocator and insists on using it. // D: Connect upstream to filter with R/W allocator but chooses not to use it. // E: Connect downstream to a filter that offers an allocator // F: Connect downstream to a filter that does not offer an allocator // G: disconnect upstream // H: Disconnect downstream // // A B C D E F G H // --------------------------------------------------------- // 00 00 1 | 3 3 2 2 6 5 . . |1 00 00 // <- 00 2 | . . . . *10/11 10 1 . |2 <- 00 // <= 00 3 | . . . . *9/11 *7/8 1 . |3 <= 00 // || 00 4 | . . . . *8 *7 1 . |4 || 00 // 00 || 5 | 8 7 *10 7 . . . 1 |5 00 || // 00 -> 6 | 9 11 *10 11 . . . 1 |6 00 -> // || || 7 | . . . . . . 5 4 |7 || || // <= || 8 | . . . . . . 5 3 |8 <= || // <= -> 9 | . . . . . . 6 3 |9 <= -> // <- <- 10| . . . . . . *5/6 2 |10 <- <- // -> -> 11| . . . . . . 6 *2/3 |11 -> -> // --------------------------------------------------------- // A B C D E F G H // // All these states are accessible without requiring any filter to // change its behaviour but not all transitions are accessible, for // instance a transition from state 4 to anywhere other than // state 8 requires that the upstream filter first offer a R-O allocator // and then changes its mind and offer R/W. This is NOT allowable - it // leads to things like the output pin getting a R/W allocator from // upstream and then the input pin being told it can only have a R-O one. // Note that you CAN change (say) the upstream filter for a different one, but // only as a disconnect / connect, not as a Reconnect. (Exercise for // the reader is to see how you get into state 4). // // The reconnection stuff goes as follows (some of the cases shown here as // "no reconnect" may get one to finalise media type - an old story). // If there is a reconnect where it says "no reconnect" here then the // reconnection must not change the allocator choice. // // state 2: <- 00 transition E <- <- case C <- <- (no change) // case D -> <- and then to -> -> // // state 2: <- 00 transition F <- <- (no reconnect) // // state 3: <= 00 transition E <= -> case A <= -> (no change) // case B -> -> // transition F <= || case A <= || (no change) // case B || || // // state 4: || 00 transition E || || case B -> || and then all cases to -> -> // F || || case B || || (no change) // // state 5: 00 || transition A <= || (no reconnect) // B || || (no reconnect) // C <- || all cases <- <- // D || || (unfortunate, but upstream's choice) // // state 6: 00 -> transition A <= -> (no reconnect) // B -> -> (no reconnect) // C <- -> all cases <- <- // D -> -> (no reconnect) // // state 10:<- <- transition G 00 <- case E 00 -> // case F 00 || // // state 11:-> -> transition H -> 00 case A <= 00 (schizo) // case B <= 00 // case C <- 00 (schizo) // case D <- 00 // // The Rules: // To sort out media types: // The input is reconnected // if the input pin is connected and the output pin connects // The output is reconnected // If the output pin is connected // and the input pin connects to a different media type // // To sort out allocators: // The input is reconnected // if the output disconnects and the input was using a downstream allocator // The output pin calls SetAllocator to pass on a new allocator // if the output is connected and // if the input disconnects and the output was using an upstream allocator // if the input acquires an allocator different from the output one // and that new allocator is not R-O // // Data is copied (i.e. call getbuffer and copy the data before transforming it) // if the two allocators are different. // CHAINS of filters: // // We sit between two filters (call them A and Z). We should finish up // with the same allocator on both of our pins and that should be the // same one that A and Z would have agreed on if we hadn't been in the // way. Furthermore, it should not matter how many in-place transforms // are in the way. Let B, C, D... be in-place transforms ("us"). // Here's how it goes: // // 1. // A connects to B. They agree on A's allocator. // A-a->B // // 2. // B connects to C. Same story. There is no point in a reconnect, but // B will request an input reconnect anyway. // A-a->B-a->C // // 3. // C connects to Z. // C insists on using A's allocator, but compromises by requesting a reconnect. // of C's input. // A-a->B-?->C-a->Z // // We now have pending reconnects on both A--->B and B--->C // // 4. // The A--->B link is reconnected. // A asks B for an allocator. B sees that it has a downstream connection so // asks its downstream input pin i.e. C's input pin for an allocator. C sees // that it too has a downstream connection so asks Z for an allocator. // // Even though Z's input pin is connected, it is being asked for an allocator. // It could refuse, in which case the chain is done and will use A's allocator // Alternatively, Z may supply one. A chooses either Z's or A's own one. // B's input pin gets NotifyAllocator called to tell it the decision and it // propagates this downstream by calling ReceiveAllocator on its output pin // which calls NotifyAllocator on the next input pin downstream etc. // If the choice is Z then it goes: // A-z->B-a->C-a->Z // A-z->B-z->C-a->Z // A-z->B-z->C-z->Z // // And that's IT!! Any further (essentially spurious) reconnects peter out // with no change in the chain. #include #include #include // ================================================================= // Implements the CTransInPlaceFilter class // ================================================================= CTransInPlaceFilter::CTransInPlaceFilter(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, REFCLSID clsid, __inout HRESULT *phr, bool bModifiesData) : CTransformFilter(pName, pUnk, clsid) , m_bModifiesData(bModifiesData) { #ifdef PERF RegisterPerfId(); #endif // PERF } // constructor #ifdef UNICODE CTransInPlaceFilter::CTransInPlaceFilter(__in_opt LPCSTR pName, __inout_opt LPUNKNOWN pUnk, REFCLSID clsid, __inout HRESULT *phr, bool bModifiesData) : CTransformFilter(pName, pUnk, clsid) , m_bModifiesData(bModifiesData) { #ifdef PERF RegisterPerfId(); #endif // PERF } // constructor #endif // return a non-addrefed CBasePin * for the user to addref if he holds onto it // for longer than his pointer to us. We create the pins dynamically when they // are asked for rather than in the constructor. This is because we want to // give the derived class an oppportunity to return different pin objects // As soon as any pin is needed we create both (this is different from the // usual transform filter) because enumerators, allocators etc are passed // through from one pin to another and it becomes very painful if the other // pin isn't there. If we fail to create either pin we ensure we fail both. CBasePin *CTransInPlaceFilter::GetPin(int n) { HRESULT hr = S_OK; // Create an input pin if not already done if (m_pInput == NULL) { m_pInput = new CTransInPlaceInputPin(NAME("TransInPlace input pin"), this // Owner filter , &hr // Result code , L"Input" // Pin name ); // Constructor for CTransInPlaceInputPin can't fail ASSERT(SUCCEEDED(hr)); } // Create an output pin if not already done if (m_pInput != NULL && m_pOutput == NULL) { m_pOutput = new CTransInPlaceOutputPin(NAME("TransInPlace output pin"), this // Owner filter , &hr // Result code , L"Output" // Pin name ); // a failed return code should delete the object ASSERT(SUCCEEDED(hr)); if (m_pOutput == NULL) { delete m_pInput; m_pInput = NULL; } } // Return the appropriate pin ASSERT(n >= 0 && n <= 1); if (n == 0) { return m_pInput; } else if (n == 1) { return m_pOutput; } else { return NULL; } } // GetPin // dir is the direction of our pin. // pReceivePin is the pin we are connecting to. HRESULT CTransInPlaceFilter::CompleteConnect(PIN_DIRECTION dir, IPin *pReceivePin) { UNREFERENCED_PARAMETER(pReceivePin); ASSERT(m_pInput); ASSERT(m_pOutput); // if we are not part of a graph, then don't indirect the pointer // this probably prevents use of the filter without a filtergraph if (!m_pGraph) { return VFW_E_NOT_IN_GRAPH; } // Always reconnect the input to account for buffering changes // // Because we don't get to suggest a type on ReceiveConnection // we need another way of making sure the right type gets used. // // One way would be to have our EnumMediaTypes return our output // connection type first but more deterministic and simple is to // call ReconnectEx passing the type we want to reconnect with // via the base class ReconeectPin method. if (dir == PINDIR_OUTPUT) { if (m_pInput->IsConnected()) { return ReconnectPin(m_pInput, &m_pOutput->CurrentMediaType()); } return NOERROR; } ASSERT(dir == PINDIR_INPUT); // Reconnect output if necessary if (m_pOutput->IsConnected()) { if (m_pInput->CurrentMediaType() != m_pOutput->CurrentMediaType()) { return ReconnectPin(m_pOutput, &m_pInput->CurrentMediaType()); } } return NOERROR; } // ComnpleteConnect // // DecideBufferSize // // Tell the output pin's allocator what size buffers we require. // *pAlloc will be the allocator our output pin is using. // HRESULT CTransInPlaceFilter::DecideBufferSize(IMemAllocator *pAlloc, __inout ALLOCATOR_PROPERTIES *pProperties) { ALLOCATOR_PROPERTIES Request, Actual; HRESULT hr; // If we are connected upstream, get his views if (m_pInput->IsConnected()) { // Get the input pin allocator, and get its size and count. // we don't care about his alignment and prefix. hr = InputPin()->PeekAllocator()->GetProperties(&Request); if (FAILED(hr)) { // Input connected but with a secretive allocator - enough! return hr; } } else { // Propose one byte // If this isn't enough then when the other pin does get connected // we can revise it. ZeroMemory(&Request, sizeof(Request)); Request.cBuffers = 1; Request.cbBuffer = 1; } DbgLog((LOG_MEMORY, 1, TEXT("Setting Allocator Requirements"))); DbgLog((LOG_MEMORY, 1, TEXT("Count %d, Size %d"), Request.cBuffers, Request.cbBuffer)); // Pass the allocator requirements to our output side // but do a little sanity checking first or we'll just hit // asserts in the allocator. pProperties->cBuffers = Request.cBuffers; pProperties->cbBuffer = Request.cbBuffer; pProperties->cbAlign = Request.cbAlign; if (pProperties->cBuffers <= 0) { pProperties->cBuffers = 1; } if (pProperties->cbBuffer <= 0) { pProperties->cbBuffer = 1; } hr = pAlloc->SetProperties(pProperties, &Actual); if (FAILED(hr)) { return hr; } DbgLog((LOG_MEMORY, 1, TEXT("Obtained Allocator Requirements"))); DbgLog((LOG_MEMORY, 1, TEXT("Count %d, Size %d, Alignment %d"), Actual.cBuffers, Actual.cbBuffer, Actual.cbAlign)); // Make sure we got the right alignment and at least the minimum required if ((Request.cBuffers > Actual.cBuffers) || (Request.cbBuffer > Actual.cbBuffer) || (Request.cbAlign > Actual.cbAlign)) { return E_FAIL; } return NOERROR; } // DecideBufferSize // // Copy // // return a pointer to an identical copy of pSample __out_opt IMediaSample *CTransInPlaceFilter::Copy(IMediaSample *pSource) { IMediaSample *pDest; HRESULT hr; REFERENCE_TIME tStart, tStop; const BOOL bTime = S_OK == pSource->GetTime(&tStart, &tStop); // this may block for an indeterminate amount of time hr = OutputPin()->PeekAllocator()->GetBuffer(&pDest, bTime ? &tStart : NULL, bTime ? &tStop : NULL, m_bSampleSkipped ? AM_GBF_PREVFRAMESKIPPED : 0); if (FAILED(hr)) { return NULL; } ASSERT(pDest); IMediaSample2 *pSample2; if (SUCCEEDED(pDest->QueryInterface(IID_IMediaSample2, (void **)&pSample2))) { HRESULT hrProps = pSample2->SetProperties(FIELD_OFFSET(AM_SAMPLE2_PROPERTIES, pbBuffer), (PBYTE)m_pInput->SampleProps()); pSample2->Release(); if (FAILED(hrProps)) { pDest->Release(); return NULL; } } else { if (bTime) { pDest->SetTime(&tStart, &tStop); } if (S_OK == pSource->IsSyncPoint()) { pDest->SetSyncPoint(TRUE); } if (S_OK == pSource->IsDiscontinuity() || m_bSampleSkipped) { pDest->SetDiscontinuity(TRUE); } if (S_OK == pSource->IsPreroll()) { pDest->SetPreroll(TRUE); } // Copy the media type AM_MEDIA_TYPE *pMediaType; if (S_OK == pSource->GetMediaType(&pMediaType)) { pDest->SetMediaType(pMediaType); DeleteMediaType(pMediaType); } } m_bSampleSkipped = FALSE; // Copy the sample media times REFERENCE_TIME TimeStart, TimeEnd; if (pSource->GetMediaTime(&TimeStart, &TimeEnd) == NOERROR) { pDest->SetMediaTime(&TimeStart, &TimeEnd); } // Copy the actual data length and the actual data. { const long lDataLength = pSource->GetActualDataLength(); if (FAILED(pDest->SetActualDataLength(lDataLength))) { pDest->Release(); return NULL; } // Copy the sample data { BYTE *pSourceBuffer, *pDestBuffer; long lSourceSize = pSource->GetSize(); long lDestSize = pDest->GetSize(); ASSERT(lDestSize >= lSourceSize && lDestSize >= lDataLength); if (FAILED(pSource->GetPointer(&pSourceBuffer)) || FAILED(pDest->GetPointer(&pDestBuffer)) || lDestSize < lDataLength || lDataLength < 0) { pDest->Release(); return NULL; } ASSERT(lDestSize == 0 || pSourceBuffer != NULL && pDestBuffer != NULL); CopyMemory((PVOID)pDestBuffer, (PVOID)pSourceBuffer, lDataLength); } } return pDest; } // Copy // override this to customize the transform process HRESULT CTransInPlaceFilter::Receive(IMediaSample *pSample) { /* Check for other streams and pass them on */ AM_SAMPLE2_PROPERTIES *const pProps = m_pInput->SampleProps(); if (pProps->dwStreamId != AM_STREAM_MEDIA) { return m_pOutput->Deliver(pSample); } HRESULT hr; // Start timing the TransInPlace (if PERF is defined) MSR_START(m_idTransInPlace); if (UsingDifferentAllocators()) { // We have to copy the data. pSample = Copy(pSample); if (pSample == NULL) { MSR_STOP(m_idTransInPlace); return E_UNEXPECTED; } } // have the derived class transform the data hr = Transform(pSample); // Stop the clock and log it (if PERF is defined) MSR_STOP(m_idTransInPlace); if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, TEXT("Error from TransInPlace"))); if (UsingDifferentAllocators()) { pSample->Release(); } return hr; } // the Transform() function can return S_FALSE to indicate that the // sample should not be delivered; we only deliver the sample if it's // really S_OK (same as NOERROR, of course.) if (hr == NOERROR) { hr = m_pOutput->Deliver(pSample); } else { // But it would be an error to return this private workaround // to the caller ... if (S_FALSE == hr) { // S_FALSE returned from Transform is a PRIVATE agreement // We should return NOERROR from Receive() in this cause because // returning S_FALSE from Receive() means that this is the end // of the stream and no more data should be sent. m_bSampleSkipped = TRUE; if (!m_bQualityChanged) { NotifyEvent(EC_QUALITY_CHANGE, 0, 0); m_bQualityChanged = TRUE; } hr = NOERROR; } } // release the output buffer. If the connected pin still needs it, // it will have addrefed it itself. if (UsingDifferentAllocators()) { pSample->Release(); } return hr; } // Receive // ================================================================= // Implements the CTransInPlaceInputPin class // ================================================================= // constructor CTransInPlaceInputPin::CTransInPlaceInputPin(__in_opt LPCTSTR pObjectName, __inout CTransInPlaceFilter *pFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName) : CTransformInputPin(pObjectName, pFilter, phr, pName) , m_bReadOnly(FALSE) , m_pTIPFilter(pFilter) { DbgLog((LOG_TRACE, 2, TEXT("CTransInPlaceInputPin::CTransInPlaceInputPin"))); } // constructor // ================================================================= // Implements IMemInputPin interface // ================================================================= // If the downstream filter has one then offer that (even if our own output // pin is not using it yet. If the upstream filter chooses it then we will // tell our output pin to ReceiveAllocator). // Else if our output pin is using an allocator then offer that. // ( This could mean offering the upstream filter his own allocator, // it could mean offerring our own // ) or it could mean offering the one from downstream // Else fail to offer any allocator at all. STDMETHODIMP CTransInPlaceInputPin::GetAllocator(__deref_out IMemAllocator **ppAllocator) { CheckPointer(ppAllocator, E_POINTER); ValidateReadWritePtr(ppAllocator, sizeof(IMemAllocator *)); CAutoLock cObjectLock(m_pLock); HRESULT hr; if (m_pTIPFilter->m_pOutput->IsConnected()) { // Store the allocator we got hr = m_pTIPFilter->OutputPin()->ConnectedIMemInputPin()->GetAllocator(ppAllocator); if (SUCCEEDED(hr)) { m_pTIPFilter->OutputPin()->SetAllocator(*ppAllocator); } } else { // Help upstream filter (eg TIP filter which is having to do a copy) // by providing a temp allocator here - we'll never use // this allocator because when our output is connected we'll // reconnect this pin hr = CTransformInputPin::GetAllocator(ppAllocator); } return hr; } // GetAllocator /* Get told which allocator the upstream output pin is actually going to use */ STDMETHODIMP CTransInPlaceInputPin::NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly) { HRESULT hr = S_OK; CheckPointer(pAllocator, E_POINTER); ValidateReadPtr(pAllocator, sizeof(IMemAllocator)); CAutoLock cObjectLock(m_pLock); m_bReadOnly = bReadOnly; // If we modify data then don't accept the allocator if it's // the same as the output pin's allocator // If our output is not connected just accept the allocator // We're never going to use this allocator because when our // output pin is connected we'll reconnect this pin if (!m_pTIPFilter->OutputPin()->IsConnected()) { return CTransformInputPin::NotifyAllocator(pAllocator, bReadOnly); } // If the allocator is read-only and we're modifying data // and the allocator is the same as the output pin's // then reject if (bReadOnly && m_pTIPFilter->m_bModifiesData) { IMemAllocator *pOutputAllocator = m_pTIPFilter->OutputPin()->PeekAllocator(); // Make sure we have an output allocator if (pOutputAllocator == NULL) { hr = m_pTIPFilter->OutputPin()->ConnectedIMemInputPin()->GetAllocator(&pOutputAllocator); if (FAILED(hr)) { hr = CreateMemoryAllocator(&pOutputAllocator); } if (SUCCEEDED(hr)) { m_pTIPFilter->OutputPin()->SetAllocator(pOutputAllocator); pOutputAllocator->Release(); } } if (pAllocator == pOutputAllocator) { hr = E_FAIL; } else if (SUCCEEDED(hr)) { // Must copy so set the allocator properties on the output ALLOCATOR_PROPERTIES Props, Actual; hr = pAllocator->GetProperties(&Props); if (SUCCEEDED(hr)) { hr = pOutputAllocator->SetProperties(&Props, &Actual); } if (SUCCEEDED(hr)) { if ((Props.cBuffers > Actual.cBuffers) || (Props.cbBuffer > Actual.cbBuffer) || (Props.cbAlign > Actual.cbAlign)) { hr = E_FAIL; } } // Set the allocator on the output pin if (SUCCEEDED(hr)) { hr = m_pTIPFilter->OutputPin()->ConnectedIMemInputPin()->NotifyAllocator(pOutputAllocator, FALSE); } } } else { hr = m_pTIPFilter->OutputPin()->ConnectedIMemInputPin()->NotifyAllocator(pAllocator, bReadOnly); if (SUCCEEDED(hr)) { m_pTIPFilter->OutputPin()->SetAllocator(pAllocator); } } if (SUCCEEDED(hr)) { // It's possible that the old and the new are the same thing. // AddRef before release ensures that we don't unload it. pAllocator->AddRef(); if (m_pAllocator != NULL) m_pAllocator->Release(); m_pAllocator = pAllocator; // We have an allocator for the input pin } return hr; } // NotifyAllocator // EnumMediaTypes // - pass through to our downstream filter STDMETHODIMP CTransInPlaceInputPin::EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum) { // Can only pass through if connected if (!m_pTIPFilter->m_pOutput->IsConnected()) return VFW_E_NOT_CONNECTED; return m_pTIPFilter->m_pOutput->GetConnected()->EnumMediaTypes(ppEnum); } // EnumMediaTypes // CheckMediaType // - agree to anything if not connected, // otherwise pass through to the downstream filter. // This assumes that the filter does not change the media type. HRESULT CTransInPlaceInputPin::CheckMediaType(const CMediaType *pmt) { HRESULT hr = m_pTIPFilter->CheckInputType(pmt); if (hr != S_OK) return hr; if (m_pTIPFilter->m_pOutput->IsConnected()) return m_pTIPFilter->m_pOutput->GetConnected()->QueryAccept(pmt); else return S_OK; } // CheckMediaType // If upstream asks us what our requirements are, we will try to ask downstream // if that doesn't work, we'll just take the defaults. STDMETHODIMP CTransInPlaceInputPin::GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES *pProps) { if (m_pTIPFilter->m_pOutput->IsConnected()) return m_pTIPFilter->OutputPin()->ConnectedIMemInputPin()->GetAllocatorRequirements(pProps); else return E_NOTIMPL; } // GetAllocatorRequirements // CTransInPlaceInputPin::CompleteConnect() calls CBaseInputPin::CompleteConnect() // and then calls CTransInPlaceFilter::CompleteConnect(). It does this because // CTransInPlaceFilter::CompleteConnect() can reconnect a pin and we do not // want to reconnect a pin if CBaseInputPin::CompleteConnect() fails. HRESULT CTransInPlaceInputPin::CompleteConnect(IPin *pReceivePin) { HRESULT hr = CBaseInputPin::CompleteConnect(pReceivePin); if (FAILED(hr)) { return hr; } return m_pTransformFilter->CompleteConnect(PINDIR_INPUT, pReceivePin); } // CompleteConnect // ================================================================= // Implements the CTransInPlaceOutputPin class // ================================================================= // constructor CTransInPlaceOutputPin::CTransInPlaceOutputPin(__in_opt LPCTSTR pObjectName, __inout CTransInPlaceFilter *pFilter, __inout HRESULT *phr, __in_opt LPCWSTR pPinName) : CTransformOutputPin(pObjectName, pFilter, phr, pPinName) , m_pTIPFilter(pFilter) { DbgLog((LOG_TRACE, 2, TEXT("CTransInPlaceOutputPin::CTransInPlaceOutputPin"))); } // constructor // EnumMediaTypes // - pass through to our upstream filter STDMETHODIMP CTransInPlaceOutputPin::EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum) { // Can only pass through if connected. if (!m_pTIPFilter->m_pInput->IsConnected()) return VFW_E_NOT_CONNECTED; return m_pTIPFilter->m_pInput->GetConnected()->EnumMediaTypes(ppEnum); } // EnumMediaTypes // CheckMediaType // - agree to anything if not connected, // otherwise pass through to the upstream filter. HRESULT CTransInPlaceOutputPin::CheckMediaType(const CMediaType *pmt) { // Don't accept any output pin type changes if we're copying // between allocators - it's too late to change the input // allocator size. if (m_pTIPFilter->UsingDifferentAllocators() && !m_pFilter->IsStopped()) { if (*pmt == m_mt) { return S_OK; } else { return VFW_E_TYPE_NOT_ACCEPTED; } } // Assumes the type does not change. That's why we're calling // CheckINPUTType here on the OUTPUT pin. HRESULT hr = m_pTIPFilter->CheckInputType(pmt); if (hr != S_OK) return hr; if (m_pTIPFilter->m_pInput->IsConnected()) return m_pTIPFilter->m_pInput->GetConnected()->QueryAccept(pmt); else return S_OK; } // CheckMediaType /* Save the allocator pointer in the output pin */ void CTransInPlaceOutputPin::SetAllocator(IMemAllocator *pAllocator) { pAllocator->AddRef(); if (m_pAllocator) { m_pAllocator->Release(); } m_pAllocator = pAllocator; } // SetAllocator // CTransInPlaceOutputPin::CompleteConnect() calls CBaseOutputPin::CompleteConnect() // and then calls CTransInPlaceFilter::CompleteConnect(). It does this because // CTransInPlaceFilter::CompleteConnect() can reconnect a pin and we do not want to // reconnect a pin if CBaseOutputPin::CompleteConnect() fails. // CBaseOutputPin::CompleteConnect() often fails when our output pin is being connected // to the Video Mixing Renderer. HRESULT CTransInPlaceOutputPin::CompleteConnect(IPin *pReceivePin) { HRESULT hr = CBaseOutputPin::CompleteConnect(pReceivePin); if (FAILED(hr)) { return hr; } return m_pTransformFilter->CompleteConnect(PINDIR_OUTPUT, pReceivePin); } // CompleteConnect ================================================ FILE: common/baseclasses/transip.h ================================================ //------------------------------------------------------------------------------ // File: TransIP.h // // Desc: DirectShow base classes - defines classes from which simple // Transform-In-Place filters may be derived. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // // The difference between this and Transfrm.h is that Transfrm copies the data. // // It assumes the filter has one input and one output stream, and has no // interest in memory management, interface negotiation or anything else. // // Derive your class from this, and supply Transform and the media type/format // negotiation functions. Implement that class, compile and link and // you're done. #ifndef __TRANSIP__ #define __TRANSIP__ // ====================================================================== // This is the com object that represents a simple transform filter. It // supports IBaseFilter, IMediaFilter and two pins through nested interfaces // ====================================================================== class CTransInPlaceFilter; // Several of the pin functions call filter functions to do the work, // so you can often use the pin classes unaltered, just overriding the // functions in CTransInPlaceFilter. If that's not enough and you want // to derive your own pin class, override GetPin in the filter to supply // your own pin classes to the filter. // ================================================== // Implements the input pin // ================================================== class CTransInPlaceInputPin : public CTransformInputPin { protected: CTransInPlaceFilter *const m_pTIPFilter; // our filter BOOL m_bReadOnly; // incoming stream is read only public: CTransInPlaceInputPin(__in_opt LPCTSTR pObjectName, __inout CTransInPlaceFilter *pFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName); // --- IMemInputPin ----- // Provide an enumerator for media types by getting one from downstream STDMETHODIMP EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum); // Say whether media type is acceptable. HRESULT CheckMediaType(const CMediaType *pmt); // Return our upstream allocator STDMETHODIMP GetAllocator(__deref_out IMemAllocator **ppAllocator); // get told which allocator the upstream output pin is actually // going to use. STDMETHODIMP NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly); // Allow the filter to see what allocator we have // N.B. This does NOT AddRef __out IMemAllocator *PeekAllocator() const { return m_pAllocator; } // Pass this on downstream if it ever gets called. STDMETHODIMP GetAllocatorRequirements(__out ALLOCATOR_PROPERTIES *pProps); HRESULT CompleteConnect(IPin *pReceivePin); inline const BOOL ReadOnly() { return m_bReadOnly; } }; // CTransInPlaceInputPin // ================================================== // Implements the output pin // ================================================== class CTransInPlaceOutputPin : public CTransformOutputPin { protected: // m_pFilter points to our CBaseFilter CTransInPlaceFilter *const m_pTIPFilter; public: CTransInPlaceOutputPin(__in_opt LPCTSTR pObjectName, __inout CTransInPlaceFilter *pFilter, __inout HRESULT *phr, __in_opt LPCWSTR pName); // --- CBaseOutputPin ------------ // negotiate the allocator and its buffer size/count // Insists on using our own allocator. (Actually the one upstream of us). // We don't override this - instead we just agree the default // then let the upstream filter decide for itself on reconnect // virtual HRESULT DecideAllocator(IMemInputPin * pPin, IMemAllocator ** pAlloc); // Provide a media type enumerator. Get it from upstream. STDMETHODIMP EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum); // Say whether media type is acceptable. HRESULT CheckMediaType(const CMediaType *pmt); // This just saves the allocator being used on the output pin // Also called by input pin's GetAllocator() void SetAllocator(IMemAllocator *pAllocator); __out_opt IMemInputPin *ConnectedIMemInputPin() { return m_pInputPin; } // Allow the filter to see what allocator we have // N.B. This does NOT AddRef __out IMemAllocator *PeekAllocator() const { return m_pAllocator; } HRESULT CompleteConnect(IPin *pReceivePin); }; // CTransInPlaceOutputPin class AM_NOVTABLE CTransInPlaceFilter : public CTransformFilter { public: // map getpin/getpincount for base enum of pins to owner // override this to return more specialised pin objects virtual CBasePin *GetPin(int n); public: // Set bModifiesData == false if your derived filter does // not modify the data samples (for instance it's just copying // them somewhere else or looking at the timestamps). CTransInPlaceFilter(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, REFCLSID clsid, __inout HRESULT *, bool bModifiesData = true); #ifdef UNICODE CTransInPlaceFilter(__in_opt LPCSTR, __inout_opt LPUNKNOWN, REFCLSID clsid, __inout HRESULT *, bool bModifiesData = true); #endif // The following are defined to avoid undefined pure virtuals. // Even if they are never called, they will give linkage warnings/errors // We override EnumMediaTypes to bypass the transform class enumerator // which would otherwise call this. HRESULT GetMediaType(int iPosition, __inout CMediaType *pMediaType) { DbgBreak("CTransInPlaceFilter::GetMediaType should never be called"); return E_UNEXPECTED; } // This is called when we actually have to provide our own allocator. HRESULT DecideBufferSize(IMemAllocator *, __inout ALLOCATOR_PROPERTIES *); // The functions which call this in CTransform are overridden in this // class to call CheckInputType with the assumption that the type // does not change. In Debug builds some calls will be made and // we just ensure that they do not assert. HRESULT CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut) { return S_OK; }; // ================================================================= // ----- You may want to override this ----------------------------- // ================================================================= HRESULT CompleteConnect(PIN_DIRECTION dir, IPin *pReceivePin); // chance to customize the transform process virtual HRESULT Receive(IMediaSample *pSample); // ================================================================= // ----- You MUST override these ----------------------------------- // ================================================================= virtual HRESULT Transform(IMediaSample *pSample) PURE; // this goes in the factory template table to create new instances // static CCOMObject * CreateInstance(LPUNKNOWN, HRESULT *); #ifdef PERF // Override to register performance measurement with a less generic string // You should do this to avoid confusion with other filters virtual void RegisterPerfId() { m_idTransInPlace = MSR_REGISTER(TEXT("TransInPlace")); } #endif // PERF // implementation details protected: __out_opt IMediaSample *CTransInPlaceFilter::Copy(IMediaSample *pSource); #ifdef PERF int m_idTransInPlace; // performance measuring id #endif // PERF bool m_bModifiesData; // Does this filter change the data? // these hold our input and output pins friend class CTransInPlaceInputPin; friend class CTransInPlaceOutputPin; __out CTransInPlaceInputPin *InputPin() const { return (CTransInPlaceInputPin *)m_pInput; }; __out CTransInPlaceOutputPin *OutputPin() const { return (CTransInPlaceOutputPin *)m_pOutput; }; // Helper to see if the input and output types match BOOL TypesMatch() { return InputPin()->CurrentMediaType() == OutputPin()->CurrentMediaType(); } // Are the input and output allocators different? BOOL UsingDifferentAllocators() const { return InputPin()->PeekAllocator() != OutputPin()->PeekAllocator(); } }; // CTransInPlaceFilter #endif /* __TRANSIP__ */ ================================================ FILE: common/baseclasses/videoctl.cpp ================================================ //------------------------------------------------------------------------------ // File: VideoCtl.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include "ddmm.h" // Load a string from the resource file string table. The buffer must be at // least STR_MAX_LENGTH bytes. The easiest way to use this is to declare a // buffer in the property page class and use it for all string loading. It // cannot be static as multiple property pages may be active simultaneously LPTSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPTSTR pBuffer, int iResourceID) { if (LoadString(g_hInst, iResourceID, pBuffer, STR_MAX_LENGTH) == 0) { return TEXT(""); } return pBuffer; } #ifdef UNICODE LPSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPSTR pBuffer, int iResourceID) { if (LoadStringA(g_hInst, iResourceID, pBuffer, STR_MAX_LENGTH) == 0) { return ""; } return pBuffer; } #endif // Property pages typically are called through their OLE interfaces. These // use UNICODE strings regardless of how the binary is built. So when we // load strings from the resource file we sometimes want to convert them // to UNICODE. This method is passed the target UNICODE buffer and does a // convert after loading the string (if built UNICODE this is not needed) // On WinNT we can explicitly call LoadStringW which saves two conversions #ifndef UNICODE LPWSTR WINAPI WideStringFromResource(__out_ecount(STR_MAX_LENGTH) LPWSTR pBuffer, int iResourceID) { *pBuffer = 0; if (g_amPlatform == VER_PLATFORM_WIN32_NT) { LoadStringW(g_hInst, iResourceID, pBuffer, STR_MAX_LENGTH); } else { CHAR szBuffer[STR_MAX_LENGTH]; DWORD dwStringLength = LoadString(g_hInst, iResourceID, szBuffer, STR_MAX_LENGTH); // if we loaded a string convert it to wide characters, ensuring // that we also null terminate the result. if (dwStringLength++) { MultiByteToWideChar(CP_ACP, 0, szBuffer, dwStringLength, pBuffer, STR_MAX_LENGTH); } } return pBuffer; } #endif // Helper function to calculate the size of the dialog BOOL WINAPI GetDialogSize(int iResourceID, DLGPROC pDlgProc, LPARAM lParam, __out SIZE *pResult) { RECT rc; HWND hwnd; // Create a temporary property page hwnd = CreateDialogParam(g_hInst, MAKEINTRESOURCE(iResourceID), GetDesktopWindow(), pDlgProc, lParam); if (hwnd == NULL) { return FALSE; } GetWindowRect(hwnd, &rc); pResult->cx = rc.right - rc.left; pResult->cy = rc.bottom - rc.top; DestroyWindow(hwnd); return TRUE; } // Class that aggregates on the IDirectDraw interface. Although DirectDraw // has the ability in its interfaces to be aggregated they're not currently // implemented. This makes it difficult for various parts of Quartz that want // to aggregate these interfaces. In particular the video renderer passes out // media samples that expose IDirectDraw and IDirectDrawSurface. The filter // graph manager also exposes IDirectDraw as a plug in distributor. For these // objects we provide these aggregation classes that republish the interfaces STDMETHODIMP CAggDirectDraw::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ASSERT(m_pDirectDraw); // Do we have this interface if (riid == IID_IDirectDraw) { return GetInterface((IDirectDraw *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } STDMETHODIMP CAggDirectDraw::Compact() { ASSERT(m_pDirectDraw); return m_pDirectDraw->Compact(); } STDMETHODIMP CAggDirectDraw::CreateClipper(DWORD dwFlags, __deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper, __inout_opt IUnknown *pUnkOuter) { ASSERT(m_pDirectDraw); return m_pDirectDraw->CreateClipper(dwFlags, lplpDDClipper, pUnkOuter); } STDMETHODIMP CAggDirectDraw::CreatePalette(DWORD dwFlags, __in LPPALETTEENTRY lpColorTable, __deref_out LPDIRECTDRAWPALETTE *lplpDDPalette, __inout_opt IUnknown *pUnkOuter) { ASSERT(m_pDirectDraw); return m_pDirectDraw->CreatePalette(dwFlags, lpColorTable, lplpDDPalette, pUnkOuter); } STDMETHODIMP CAggDirectDraw::CreateSurface(__in LPDDSURFACEDESC lpDDSurfaceDesc, __deref_out LPDIRECTDRAWSURFACE *lplpDDSurface, __inout_opt IUnknown *pUnkOuter) { ASSERT(m_pDirectDraw); return m_pDirectDraw->CreateSurface(lpDDSurfaceDesc, lplpDDSurface, pUnkOuter); } STDMETHODIMP CAggDirectDraw::DuplicateSurface(__in LPDIRECTDRAWSURFACE lpDDSurface, __deref_out LPDIRECTDRAWSURFACE *lplpDupDDSurface) { ASSERT(m_pDirectDraw); return m_pDirectDraw->DuplicateSurface(lpDDSurface, lplpDupDDSurface); } STDMETHODIMP CAggDirectDraw::EnumDisplayModes(DWORD dwSurfaceDescCount, __in LPDDSURFACEDESC lplpDDSurfaceDescList, __in LPVOID lpContext, __in LPDDENUMMODESCALLBACK lpEnumCallback) { ASSERT(m_pDirectDraw); return m_pDirectDraw->EnumDisplayModes(dwSurfaceDescCount, lplpDDSurfaceDescList, lpContext, lpEnumCallback); } STDMETHODIMP CAggDirectDraw::EnumSurfaces(DWORD dwFlags, __in LPDDSURFACEDESC lpDDSD, __in LPVOID lpContext, __in LPDDENUMSURFACESCALLBACK lpEnumCallback) { ASSERT(m_pDirectDraw); return m_pDirectDraw->EnumSurfaces(dwFlags, lpDDSD, lpContext, lpEnumCallback); } STDMETHODIMP CAggDirectDraw::FlipToGDISurface() { ASSERT(m_pDirectDraw); return m_pDirectDraw->FlipToGDISurface(); } STDMETHODIMP CAggDirectDraw::GetCaps(__out LPDDCAPS lpDDDriverCaps, __out LPDDCAPS lpDDHELCaps) { ASSERT(m_pDirectDraw); return m_pDirectDraw->GetCaps(lpDDDriverCaps, lpDDHELCaps); } STDMETHODIMP CAggDirectDraw::GetDisplayMode(__out LPDDSURFACEDESC lpDDSurfaceDesc) { ASSERT(m_pDirectDraw); return m_pDirectDraw->GetDisplayMode(lpDDSurfaceDesc); } STDMETHODIMP CAggDirectDraw::GetFourCCCodes(__inout LPDWORD lpNumCodes, __out_ecount(*lpNumCodes) LPDWORD lpCodes) { ASSERT(m_pDirectDraw); return m_pDirectDraw->GetFourCCCodes(lpNumCodes, lpCodes); } STDMETHODIMP CAggDirectDraw::GetGDISurface(__deref_out LPDIRECTDRAWSURFACE *lplpGDIDDSurface) { ASSERT(m_pDirectDraw); return m_pDirectDraw->GetGDISurface(lplpGDIDDSurface); } STDMETHODIMP CAggDirectDraw::GetMonitorFrequency(__out LPDWORD lpdwFrequency) { ASSERT(m_pDirectDraw); return m_pDirectDraw->GetMonitorFrequency(lpdwFrequency); } STDMETHODIMP CAggDirectDraw::GetScanLine(__out LPDWORD lpdwScanLine) { ASSERT(m_pDirectDraw); return m_pDirectDraw->GetScanLine(lpdwScanLine); } STDMETHODIMP CAggDirectDraw::GetVerticalBlankStatus(__out LPBOOL lpblsInVB) { ASSERT(m_pDirectDraw); return m_pDirectDraw->GetVerticalBlankStatus(lpblsInVB); } STDMETHODIMP CAggDirectDraw::Initialize(__in GUID *lpGUID) { ASSERT(m_pDirectDraw); return m_pDirectDraw->Initialize(lpGUID); } STDMETHODIMP CAggDirectDraw::RestoreDisplayMode() { ASSERT(m_pDirectDraw); return m_pDirectDraw->RestoreDisplayMode(); } STDMETHODIMP CAggDirectDraw::SetCooperativeLevel(HWND hWnd, DWORD dwFlags) { ASSERT(m_pDirectDraw); return m_pDirectDraw->SetCooperativeLevel(hWnd, dwFlags); } STDMETHODIMP CAggDirectDraw::SetDisplayMode(DWORD dwWidth, DWORD dwHeight, DWORD dwBpp) { ASSERT(m_pDirectDraw); return m_pDirectDraw->SetDisplayMode(dwWidth, dwHeight, dwBpp); } STDMETHODIMP CAggDirectDraw::WaitForVerticalBlank(DWORD dwFlags, HANDLE hEvent) { ASSERT(m_pDirectDraw); return m_pDirectDraw->WaitForVerticalBlank(dwFlags, hEvent); } // Class that aggregates an IDirectDrawSurface interface. Although DirectDraw // has the ability in its interfaces to be aggregated they're not currently // implemented. This makes it difficult for various parts of Quartz that want // to aggregate these interfaces. In particular the video renderer passes out // media samples that expose IDirectDraw and IDirectDrawSurface. The filter // graph manager also exposes IDirectDraw as a plug in distributor. For these // objects we provide these aggregation classes that republish the interfaces STDMETHODIMP CAggDrawSurface::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { ASSERT(m_pDirectDrawSurface); // Do we have this interface if (riid == IID_IDirectDrawSurface) { return GetInterface((IDirectDrawSurface *)this, ppv); } else { return CUnknown::NonDelegatingQueryInterface(riid, ppv); } } STDMETHODIMP CAggDrawSurface::AddAttachedSurface(__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->AddAttachedSurface(lpDDSAttachedSurface); } STDMETHODIMP CAggDrawSurface::AddOverlayDirtyRect(__in LPRECT lpRect) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->AddOverlayDirtyRect(lpRect); } STDMETHODIMP CAggDrawSurface::Blt(__in LPRECT lpDestRect, __in LPDIRECTDRAWSURFACE lpDDSrcSurface, __in LPRECT lpSrcRect, DWORD dwFlags, __in LPDDBLTFX lpDDBltFx) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->Blt(lpDestRect, lpDDSrcSurface, lpSrcRect, dwFlags, lpDDBltFx); } STDMETHODIMP CAggDrawSurface::BltBatch(__in_ecount(dwCount) LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->BltBatch(lpDDBltBatch, dwCount, dwFlags); } STDMETHODIMP CAggDrawSurface::BltFast(DWORD dwX, DWORD dwY, __in LPDIRECTDRAWSURFACE lpDDSrcSurface, __in LPRECT lpSrcRect, DWORD dwTrans) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->BltFast(dwX, dwY, lpDDSrcSurface, lpSrcRect, dwTrans); } STDMETHODIMP CAggDrawSurface::DeleteAttachedSurface(DWORD dwFlags, __in LPDIRECTDRAWSURFACE lpDDSAttachedSurface) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->DeleteAttachedSurface(dwFlags, lpDDSAttachedSurface); } STDMETHODIMP CAggDrawSurface::EnumAttachedSurfaces(__in LPVOID lpContext, __in LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->EnumAttachedSurfaces(lpContext, lpEnumSurfacesCallback); } STDMETHODIMP CAggDrawSurface::EnumOverlayZOrders(DWORD dwFlags, __in LPVOID lpContext, __in LPDDENUMSURFACESCALLBACK lpfnCallback) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->EnumOverlayZOrders(dwFlags, lpContext, lpfnCallback); } STDMETHODIMP CAggDrawSurface::Flip(__in LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride, DWORD dwFlags) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->Flip(lpDDSurfaceTargetOverride, dwFlags); } STDMETHODIMP CAggDrawSurface::GetAttachedSurface(__in LPDDSCAPS lpDDSCaps, __deref_out LPDIRECTDRAWSURFACE *lplpDDAttachedSurface) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetAttachedSurface(lpDDSCaps, lplpDDAttachedSurface); } STDMETHODIMP CAggDrawSurface::GetBltStatus(DWORD dwFlags) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetBltStatus(dwFlags); } STDMETHODIMP CAggDrawSurface::GetCaps(__out LPDDSCAPS lpDDSCaps) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetCaps(lpDDSCaps); } STDMETHODIMP CAggDrawSurface::GetClipper(__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetClipper(lplpDDClipper); } STDMETHODIMP CAggDrawSurface::GetColorKey(DWORD dwFlags, __out LPDDCOLORKEY lpDDColorKey) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetColorKey(dwFlags, lpDDColorKey); } STDMETHODIMP CAggDrawSurface::GetDC(__out HDC *lphDC) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetDC(lphDC); } STDMETHODIMP CAggDrawSurface::GetFlipStatus(DWORD dwFlags) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetFlipStatus(dwFlags); } STDMETHODIMP CAggDrawSurface::GetOverlayPosition(__out LPLONG lpdwX, __out LPLONG lpdwY) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetOverlayPosition(lpdwX, lpdwY); } STDMETHODIMP CAggDrawSurface::GetPalette(__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetPalette(lplpDDPalette); } STDMETHODIMP CAggDrawSurface::GetPixelFormat(__out LPDDPIXELFORMAT lpDDPixelFormat) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->GetPixelFormat(lpDDPixelFormat); } // A bit of a warning here: Our media samples in DirectShow aggregate on // IDirectDraw and IDirectDrawSurface (ie are available through IMediaSample // by QueryInterface). Unfortunately the underlying DirectDraw code cannot // be aggregated so we have to use these classes. The snag is that when we // call a different surface and pass in this interface as perhaps the source // surface the call will fail because DirectDraw dereferences the pointer to // get at its private data structures. Therefore we supply this workaround to give // access to the real IDirectDraw surface. A filter can call GetSurfaceDesc // and we will fill in the lpSurface pointer with the real underlying surface STDMETHODIMP CAggDrawSurface::GetSurfaceDesc(__out LPDDSURFACEDESC lpDDSurfaceDesc) { ASSERT(m_pDirectDrawSurface); // First call down to the underlying DirectDraw HRESULT hr = m_pDirectDrawSurface->GetSurfaceDesc(lpDDSurfaceDesc); if (FAILED(hr)) { return hr; } // Store the real DirectDrawSurface interface lpDDSurfaceDesc->lpSurface = m_pDirectDrawSurface; return hr; } STDMETHODIMP CAggDrawSurface::Initialize(__in LPDIRECTDRAW lpDD, __in LPDDSURFACEDESC lpDDSurfaceDesc) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->Initialize(lpDD, lpDDSurfaceDesc); } STDMETHODIMP CAggDrawSurface::IsLost() { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->IsLost(); } STDMETHODIMP CAggDrawSurface::Lock(__in LPRECT lpDestRect, __inout LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->Lock(lpDestRect, lpDDSurfaceDesc, dwFlags, hEvent); } STDMETHODIMP CAggDrawSurface::ReleaseDC(HDC hDC) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->ReleaseDC(hDC); } STDMETHODIMP CAggDrawSurface::Restore() { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->Restore(); } STDMETHODIMP CAggDrawSurface::SetClipper(__in LPDIRECTDRAWCLIPPER lpDDClipper) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->SetClipper(lpDDClipper); } STDMETHODIMP CAggDrawSurface::SetColorKey(DWORD dwFlags, __in LPDDCOLORKEY lpDDColorKey) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->SetColorKey(dwFlags, lpDDColorKey); } STDMETHODIMP CAggDrawSurface::SetOverlayPosition(LONG dwX, LONG dwY) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->SetOverlayPosition(dwX, dwY); } STDMETHODIMP CAggDrawSurface::SetPalette(__in LPDIRECTDRAWPALETTE lpDDPalette) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->SetPalette(lpDDPalette); } STDMETHODIMP CAggDrawSurface::Unlock(__in LPVOID lpSurfaceData) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->Unlock(lpSurfaceData); } STDMETHODIMP CAggDrawSurface::UpdateOverlay(__in LPRECT lpSrcRect, __in LPDIRECTDRAWSURFACE lpDDDestSurface, __in LPRECT lpDestRect, DWORD dwFlags, __in LPDDOVERLAYFX lpDDOverlayFX) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->UpdateOverlay(lpSrcRect, lpDDDestSurface, lpDestRect, dwFlags, lpDDOverlayFX); } STDMETHODIMP CAggDrawSurface::UpdateOverlayDisplay(DWORD dwFlags) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->UpdateOverlayDisplay(dwFlags); } STDMETHODIMP CAggDrawSurface::UpdateOverlayZOrder(DWORD dwFlags, __in LPDIRECTDRAWSURFACE lpDDSReference) { ASSERT(m_pDirectDrawSurface); return m_pDirectDrawSurface->UpdateOverlayZOrder(dwFlags, lpDDSReference); } // DirectShow must work on multiple platforms. In particular, it also runs on // Windows NT 3.51 which does not have DirectDraw capabilities. The filters // cannot therefore link statically to the DirectDraw library. To make their // lives that little bit easier we provide this class that manages loading // and unloading the library and creating the initial IDirectDraw interface CLoadDirectDraw::CLoadDirectDraw() : m_pDirectDraw(NULL) , m_hDirectDraw(NULL) { } // Destructor forces unload CLoadDirectDraw::~CLoadDirectDraw() { ReleaseDirectDraw(); if (m_hDirectDraw) { NOTE("Unloading library"); FreeLibrary(m_hDirectDraw); } } // We can't be sure that DirectDraw is always available so we can't statically // link to the library. Therefore we load the library, get the function entry // point addresses and call them to create the driver objects. We return S_OK // if we manage to load DirectDraw correctly otherwise we return E_NOINTERFACE // We initialise a DirectDraw instance by explicitely loading the library and // calling GetProcAddress on the DirectDrawCreate entry point that it exports // On a multi monitor system, we can get the DirectDraw object for any // monitor (device) with the optional szDevice parameter HRESULT CLoadDirectDraw::LoadDirectDraw(__in LPSTR szDevice) { PDRAWCREATE pDrawCreate; PDRAWENUM pDrawEnum; LPDIRECTDRAWENUMERATEEXA pDrawEnumEx; HRESULT hr = NOERROR; NOTE("Entering DoLoadDirectDraw"); // Is DirectDraw already loaded if (m_pDirectDraw) { NOTE("Already loaded"); ASSERT(m_hDirectDraw); return NOERROR; } // Make sure the library is available if (!m_hDirectDraw) { UINT ErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX); m_hDirectDraw = LoadLibrary(TEXT("DDRAW.DLL")); SetErrorMode(ErrorMode); if (m_hDirectDraw == NULL) { DbgLog((LOG_ERROR, 1, TEXT("Can't load DDRAW.DLL"))); NOTE("No library"); return E_NOINTERFACE; } } // Get the DLL address for the creator function pDrawCreate = (PDRAWCREATE)GetProcAddress(m_hDirectDraw, "DirectDrawCreate"); // force ANSI, we assume it pDrawEnum = (PDRAWENUM)GetProcAddress(m_hDirectDraw, "DirectDrawEnumerateA"); pDrawEnumEx = (LPDIRECTDRAWENUMERATEEXA)GetProcAddress(m_hDirectDraw, "DirectDrawEnumerateExA"); // We don't NEED DirectDrawEnumerateEx, that's just for multimon stuff if (pDrawCreate == NULL || pDrawEnum == NULL) { DbgLog((LOG_ERROR, 1, TEXT("Can't get functions: Create=%x Enum=%x"), pDrawCreate, pDrawEnum)); NOTE("No entry point"); ReleaseDirectDraw(); return E_NOINTERFACE; } DbgLog((LOG_TRACE, 3, TEXT("Creating DDraw for device %s"), szDevice ? szDevice : "")); // Create a DirectDraw display provider for this device, using the fancy // multimon-aware version, if it exists if (pDrawEnumEx) m_pDirectDraw = DirectDrawCreateFromDeviceEx(szDevice, pDrawCreate, pDrawEnumEx); else m_pDirectDraw = DirectDrawCreateFromDevice(szDevice, pDrawCreate, pDrawEnum); if (m_pDirectDraw == NULL) { DbgLog((LOG_ERROR, 1, TEXT("Can't create DDraw"))); NOTE("No instance"); ReleaseDirectDraw(); return E_NOINTERFACE; } return NOERROR; } // Called to release any DirectDraw provider we previously loaded. We may be // called at any time especially when something goes horribly wrong and when // we need to clean up before returning so we can't guarantee that all state // variables are consistent so free only those really allocated allocated // This should only be called once all reference counts have been released void CLoadDirectDraw::ReleaseDirectDraw() { NOTE("Releasing DirectDraw driver"); // Release any DirectDraw provider interface if (m_pDirectDraw) { NOTE("Releasing instance"); m_pDirectDraw->Release(); m_pDirectDraw = NULL; } } // Return NOERROR (S_OK) if DirectDraw has been loaded by this object HRESULT CLoadDirectDraw::IsDirectDrawLoaded() { NOTE("Entering IsDirectDrawLoaded"); if (m_pDirectDraw == NULL) { NOTE("DirectDraw not loaded"); return S_FALSE; } return NOERROR; } // Return the IDirectDraw interface we look after LPDIRECTDRAW CLoadDirectDraw::GetDirectDraw() { NOTE("Entering GetDirectDraw"); if (m_pDirectDraw == NULL) { NOTE("No DirectDraw"); return NULL; } NOTE("Returning DirectDraw"); m_pDirectDraw->AddRef(); return m_pDirectDraw; } // Are we running on Direct Draw version 1? We need to find out as // we rely on specific bug fixes in DirectDraw 2 for fullscreen playback. To // find out, we simply see if it supports IDirectDraw2. Only version 2 and // higher support this. BOOL CLoadDirectDraw::IsDirectDrawVersion1() { if (m_pDirectDraw == NULL) return FALSE; IDirectDraw2 *p = NULL; HRESULT hr = m_pDirectDraw->QueryInterface(IID_IDirectDraw2, (void **)&p); if (p) p->Release(); if (hr == NOERROR) { DbgLog((LOG_TRACE, 3, TEXT("Direct Draw Version 2 or greater"))); return FALSE; } else { DbgLog((LOG_TRACE, 3, TEXT("Direct Draw Version 1"))); return TRUE; } } ================================================ FILE: common/baseclasses/videoctl.h ================================================ //------------------------------------------------------------------------------ // File: VideoCtl.h // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __VIDEOCTL__ #define __VIDEOCTL__ // These help with property page implementations. The first can be used to // load any string from a resource file. The buffer to load into is passed // as an input parameter. The same buffer is the return value if the string // was found otherwise it returns TEXT(""). The GetDialogSize is passed the // resource ID of a dialog box and returns the size of it in screen pixels #define STR_MAX_LENGTH 256 LPTSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPTSTR pBuffer, int iResourceID); #ifdef UNICODE #define WideStringFromResource StringFromResource LPSTR WINAPI StringFromResource(__out_ecount(STR_MAX_LENGTH) LPSTR pBuffer, int iResourceID); #else LPWSTR WINAPI WideStringFromResource(__out_ecount(STR_MAX_LENGTH) LPWSTR pBuffer, int iResourceID); #endif BOOL WINAPI GetDialogSize(int iResourceID, // Dialog box resource identifier DLGPROC pDlgProc, // Pointer to dialog procedure LPARAM lParam, // Any user data wanted in pDlgProc __out SIZE *pResult); // Returns the size of dialog box // Class that aggregates an IDirectDraw interface class CAggDirectDraw : public IDirectDraw , public CUnknown { protected: LPDIRECTDRAW m_pDirectDraw; public: DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // Constructor and destructor CAggDirectDraw(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk) : CUnknown(pName, pUnk) , m_pDirectDraw(NULL){}; virtual CAggDirectDraw::~CAggDirectDraw(){}; // Set the object we should be aggregating void SetDirectDraw(__inout LPDIRECTDRAW pDirectDraw) { m_pDirectDraw = pDirectDraw; } // IDirectDraw methods STDMETHODIMP Compact(); STDMETHODIMP CreateClipper(DWORD dwFlags, __deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper, __inout_opt IUnknown *pUnkOuter); STDMETHODIMP CreatePalette(DWORD dwFlags, __in LPPALETTEENTRY lpColorTable, __deref_out LPDIRECTDRAWPALETTE *lplpDDPalette, __inout_opt IUnknown *pUnkOuter); STDMETHODIMP CreateSurface(__in LPDDSURFACEDESC lpDDSurfaceDesc, __deref_out LPDIRECTDRAWSURFACE *lplpDDSurface, __inout_opt IUnknown *pUnkOuter); STDMETHODIMP DuplicateSurface(__in LPDIRECTDRAWSURFACE lpDDSurface, __deref_out LPDIRECTDRAWSURFACE *lplpDupDDSurface); STDMETHODIMP EnumDisplayModes(DWORD dwSurfaceDescCount, __in LPDDSURFACEDESC lplpDDSurfaceDescList, __in LPVOID lpContext, __in LPDDENUMMODESCALLBACK lpEnumCallback); STDMETHODIMP EnumSurfaces(DWORD dwFlags, __in LPDDSURFACEDESC lpDDSD, __in LPVOID lpContext, __in LPDDENUMSURFACESCALLBACK lpEnumCallback); STDMETHODIMP FlipToGDISurface(); STDMETHODIMP GetCaps(__out LPDDCAPS lpDDDriverCaps, __out LPDDCAPS lpDDHELCaps); STDMETHODIMP GetDisplayMode(__out LPDDSURFACEDESC lpDDSurfaceDesc); STDMETHODIMP GetFourCCCodes(__inout LPDWORD lpNumCodes, __out_ecount(*lpNumCodes) LPDWORD lpCodes); STDMETHODIMP GetGDISurface(__deref_out LPDIRECTDRAWSURFACE *lplpGDIDDSurface); STDMETHODIMP GetMonitorFrequency(__out LPDWORD lpdwFrequency); STDMETHODIMP GetScanLine(__out LPDWORD lpdwScanLine); STDMETHODIMP GetVerticalBlankStatus(__out LPBOOL lpblsInVB); STDMETHODIMP Initialize(__in GUID *lpGUID); STDMETHODIMP RestoreDisplayMode(); STDMETHODIMP SetCooperativeLevel(HWND hWnd, DWORD dwFlags); STDMETHODIMP SetDisplayMode(DWORD dwWidth, DWORD dwHeight, DWORD dwBpp); STDMETHODIMP WaitForVerticalBlank(DWORD dwFlags, HANDLE hEvent); }; // Class that aggregates an IDirectDrawSurface interface class CAggDrawSurface : public IDirectDrawSurface , public CUnknown { protected: LPDIRECTDRAWSURFACE m_pDirectDrawSurface; public: DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv); // Constructor and destructor CAggDrawSurface(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk) : CUnknown(pName, pUnk) , m_pDirectDrawSurface(NULL){}; virtual ~CAggDrawSurface(){}; // Set the object we should be aggregating void SetDirectDrawSurface(__inout LPDIRECTDRAWSURFACE pDirectDrawSurface) { m_pDirectDrawSurface = pDirectDrawSurface; } // IDirectDrawSurface methods STDMETHODIMP AddAttachedSurface(__in LPDIRECTDRAWSURFACE lpDDSAttachedSurface); STDMETHODIMP AddOverlayDirtyRect(__in LPRECT lpRect); STDMETHODIMP Blt(__in LPRECT lpDestRect, __in LPDIRECTDRAWSURFACE lpDDSrcSurface, __in LPRECT lpSrcRect, DWORD dwFlags, __in LPDDBLTFX lpDDBltFx); STDMETHODIMP BltBatch(__in_ecount(dwCount) LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags); STDMETHODIMP BltFast(DWORD dwX, DWORD dwY, __in LPDIRECTDRAWSURFACE lpDDSrcSurface, __in LPRECT lpSrcRect, DWORD dwTrans); STDMETHODIMP DeleteAttachedSurface(DWORD dwFlags, __in LPDIRECTDRAWSURFACE lpDDSAttachedSurface); STDMETHODIMP EnumAttachedSurfaces(__in LPVOID lpContext, __in LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback); STDMETHODIMP EnumOverlayZOrders(DWORD dwFlags, __in LPVOID lpContext, __in LPDDENUMSURFACESCALLBACK lpfnCallback); STDMETHODIMP Flip(__in LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride, DWORD dwFlags); STDMETHODIMP GetAttachedSurface(__in LPDDSCAPS lpDDSCaps, __deref_out LPDIRECTDRAWSURFACE *lplpDDAttachedSurface); STDMETHODIMP GetBltStatus(DWORD dwFlags); STDMETHODIMP GetCaps(__out LPDDSCAPS lpDDSCaps); STDMETHODIMP GetClipper(__deref_out LPDIRECTDRAWCLIPPER *lplpDDClipper); STDMETHODIMP GetColorKey(DWORD dwFlags, __out LPDDCOLORKEY lpDDColorKey); STDMETHODIMP GetDC(__out HDC *lphDC); STDMETHODIMP GetFlipStatus(DWORD dwFlags); STDMETHODIMP GetOverlayPosition(__out LPLONG lpdwX, __out LPLONG lpdwY); STDMETHODIMP GetPalette(__deref_out LPDIRECTDRAWPALETTE *lplpDDPalette); STDMETHODIMP GetPixelFormat(__out LPDDPIXELFORMAT lpDDPixelFormat); STDMETHODIMP GetSurfaceDesc(__out LPDDSURFACEDESC lpDDSurfaceDesc); STDMETHODIMP Initialize(__in LPDIRECTDRAW lpDD, __in LPDDSURFACEDESC lpDDSurfaceDesc); STDMETHODIMP IsLost(); STDMETHODIMP Lock(__in LPRECT lpDestRect, __inout LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent); STDMETHODIMP ReleaseDC(HDC hDC); STDMETHODIMP Restore(); STDMETHODIMP SetClipper(__in LPDIRECTDRAWCLIPPER lpDDClipper); STDMETHODIMP SetColorKey(DWORD dwFlags, __in LPDDCOLORKEY lpDDColorKey); STDMETHODIMP SetOverlayPosition(LONG dwX, LONG dwY); STDMETHODIMP SetPalette(__in LPDIRECTDRAWPALETTE lpDDPalette); STDMETHODIMP Unlock(__in LPVOID lpSurfaceData); STDMETHODIMP UpdateOverlay(__in LPRECT lpSrcRect, __in LPDIRECTDRAWSURFACE lpDDDestSurface, __in LPRECT lpDestRect, DWORD dwFlags, __in LPDDOVERLAYFX lpDDOverlayFX); STDMETHODIMP UpdateOverlayDisplay(DWORD dwFlags); STDMETHODIMP UpdateOverlayZOrder(DWORD dwFlags, __in LPDIRECTDRAWSURFACE lpDDSReference); }; class CLoadDirectDraw { LPDIRECTDRAW m_pDirectDraw; // The DirectDraw driver instance HINSTANCE m_hDirectDraw; // Handle to the loaded library public: CLoadDirectDraw(); ~CLoadDirectDraw(); HRESULT LoadDirectDraw(__in LPSTR szDevice); void ReleaseDirectDraw(); HRESULT IsDirectDrawLoaded(); LPDIRECTDRAW GetDirectDraw(); BOOL IsDirectDrawVersion1(); }; #endif // __VIDEOCTL__ ================================================ FILE: common/baseclasses/vtrans.cpp ================================================ //------------------------------------------------------------------------------ // File: Vtrans.cpp // // Desc: DirectShow base classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include // #include // now in precomp file streams.h CVideoTransformFilter::CVideoTransformFilter(__in_opt LPCTSTR pName, __inout_opt LPUNKNOWN pUnk, REFCLSID clsid) : CTransformFilter(pName, pUnk, clsid) , m_itrLate(0) , m_nKeyFramePeriod(0) // No QM until we see at least 2 key frames , m_nFramesSinceKeyFrame(0) , m_bSkipping(FALSE) , m_tDecodeStart(0) , m_itrAvgDecode(300000) // 30mSec - probably allows skipping , m_bQualityChanged(FALSE) { #ifdef PERF RegisterPerfId(); #endif // PERF } CVideoTransformFilter::~CVideoTransformFilter() { // nothing to do } // Reset our quality management state HRESULT CVideoTransformFilter::StartStreaming() { m_itrLate = 0; m_nKeyFramePeriod = 0; // No QM until we see at least 2 key frames m_nFramesSinceKeyFrame = 0; m_bSkipping = FALSE; m_tDecodeStart = 0; m_itrAvgDecode = 300000; // 30mSec - probably allows skipping m_bQualityChanged = FALSE; m_bSampleSkipped = FALSE; return NOERROR; } // Overriden to reset quality management information HRESULT CVideoTransformFilter::EndFlush() { { // Synchronize CAutoLock lck(&m_csReceive); // Reset our stats // // Note - we don't want to call derived classes here, // we only want to reset our internal variables and this // is a convenient way to do it CVideoTransformFilter::StartStreaming(); } return CTransformFilter::EndFlush(); } HRESULT CVideoTransformFilter::AbortPlayback(HRESULT hr) { NotifyEvent(EC_ERRORABORT, hr, 0); m_pOutput->DeliverEndOfStream(); return hr; } // Receive() // // Accept a sample from upstream, decide whether to process it // or drop it. If we process it then get a buffer from the // allocator of the downstream connection, transform it into the // new buffer and deliver it to the downstream filter. // If we decide not to process it then we do not get a buffer. // Remember that although this code will notice format changes coming into // the input pin, it will NOT change its output format if that results // in the filter needing to make a corresponding output format change. Your // derived filter will have to take care of that. (eg. a palette change if // the input and output is an 8 bit format). If the input sample is discarded // and nothing is sent out for this Receive, please remember to put the format // change on the first output sample that you actually do send. // If your filter will produce the same output type even when the input type // changes, then this base class code will do everything you need. HRESULT CVideoTransformFilter::Receive(IMediaSample *pSample) { // If the next filter downstream is the video renderer, then it may // be able to operate in DirectDraw mode which saves copying the data // and gives higher performance. In that case the buffer which we // get from GetDeliveryBuffer will be a DirectDraw buffer, and // drawing into this buffer draws directly onto the display surface. // This means that any waiting for the correct time to draw occurs // during GetDeliveryBuffer, and that once the buffer is given to us // the video renderer will count it in its statistics as a frame drawn. // This means that any decision to drop the frame must be taken before // calling GetDeliveryBuffer. ASSERT(CritCheckIn(&m_csReceive)); AM_MEDIA_TYPE *pmtOut, *pmt; #ifdef DEBUG FOURCCMap fccOut; #endif HRESULT hr; ASSERT(pSample); IMediaSample *pOutSample; // If no output pin to deliver to then no point sending us data ASSERT(m_pOutput != NULL); // The source filter may dynamically ask us to start transforming from a // different media type than the one we're using now. If we don't, we'll // draw garbage. (typically, this is a palette change in the movie, // but could be something more sinister like the compression type changing, // or even the video size changing) #define rcS1 ((VIDEOINFOHEADER *)(pmt->pbFormat))->rcSource #define rcT1 ((VIDEOINFOHEADER *)(pmt->pbFormat))->rcTarget pSample->GetMediaType(&pmt); if (pmt != NULL && pmt->pbFormat != NULL) { // spew some debug output ASSERT(!IsEqualGUID(pmt->majortype, GUID_NULL)); #ifdef DEBUG fccOut.SetFOURCC(&pmt->subtype); LONG lCompression = HEADER(pmt->pbFormat)->biCompression; LONG lBitCount = HEADER(pmt->pbFormat)->biBitCount; LONG lStride = (HEADER(pmt->pbFormat)->biWidth * lBitCount + 7) / 8; lStride = (lStride + 3) & ~3; DbgLog((LOG_TRACE, 3, TEXT("*Changing input type on the fly to"))); DbgLog((LOG_TRACE, 3, TEXT("FourCC: %lx Compression: %lx BitCount: %ld"), fccOut.GetFOURCC(), lCompression, lBitCount)); DbgLog((LOG_TRACE, 3, TEXT("biHeight: %ld rcDst: (%ld, %ld, %ld, %ld)"), HEADER(pmt->pbFormat)->biHeight, rcT1.left, rcT1.top, rcT1.right, rcT1.bottom)); DbgLog((LOG_TRACE, 3, TEXT("rcSrc: (%ld, %ld, %ld, %ld) Stride: %ld"), rcS1.left, rcS1.top, rcS1.right, rcS1.bottom, lStride)); #endif // now switch to using the new format. I am assuming that the // derived filter will do the right thing when its media type is // switched and streaming is restarted. StopStreaming(); m_pInput->CurrentMediaType() = *pmt; DeleteMediaType(pmt); // if this fails, playback will stop, so signal an error hr = StartStreaming(); if (FAILED(hr)) { return AbortPlayback(hr); } } // Now that we have noticed any format changes on the input sample, it's // OK to discard it. if (ShouldSkipFrame(pSample)) { MSR_NOTE(m_idSkip); m_bSampleSkipped = TRUE; return NOERROR; } // Set up the output sample hr = InitializeOutputSample(pSample, &pOutSample); if (FAILED(hr)) { return hr; } m_bSampleSkipped = FALSE; // The renderer may ask us to on-the-fly to start transforming to a // different format. If we don't obey it, we'll draw garbage #define rcS ((VIDEOINFOHEADER *)(pmtOut->pbFormat))->rcSource #define rcT ((VIDEOINFOHEADER *)(pmtOut->pbFormat))->rcTarget pOutSample->GetMediaType(&pmtOut); if (pmtOut != NULL && pmtOut->pbFormat != NULL) { // spew some debug output ASSERT(!IsEqualGUID(pmtOut->majortype, GUID_NULL)); #ifdef DEBUG fccOut.SetFOURCC(&pmtOut->subtype); LONG lCompression = HEADER(pmtOut->pbFormat)->biCompression; LONG lBitCount = HEADER(pmtOut->pbFormat)->biBitCount; LONG lStride = (HEADER(pmtOut->pbFormat)->biWidth * lBitCount + 7) / 8; lStride = (lStride + 3) & ~3; DbgLog((LOG_TRACE, 3, TEXT("*Changing output type on the fly to"))); DbgLog((LOG_TRACE, 3, TEXT("FourCC: %lx Compression: %lx BitCount: %ld"), fccOut.GetFOURCC(), lCompression, lBitCount)); DbgLog((LOG_TRACE, 3, TEXT("biHeight: %ld rcDst: (%ld, %ld, %ld, %ld)"), HEADER(pmtOut->pbFormat)->biHeight, rcT.left, rcT.top, rcT.right, rcT.bottom)); DbgLog((LOG_TRACE, 3, TEXT("rcSrc: (%ld, %ld, %ld, %ld) Stride: %ld"), rcS.left, rcS.top, rcS.right, rcS.bottom, lStride)); #endif // now switch to using the new format. I am assuming that the // derived filter will do the right thing when its media type is // switched and streaming is restarted. StopStreaming(); m_pOutput->CurrentMediaType() = *pmtOut; DeleteMediaType(pmtOut); hr = StartStreaming(); if (SUCCEEDED(hr)) { // a new format, means a new empty buffer, so wait for a keyframe // before passing anything on to the renderer. // !!! a keyframe may never come, so give up after 30 frames DbgLog((LOG_TRACE, 3, TEXT("Output format change means we must wait for a keyframe"))); m_nWaitForKey = 30; // if this fails, playback will stop, so signal an error } else { // Must release the sample before calling AbortPlayback // because we might be holding the win16 lock or // ddraw lock pOutSample->Release(); AbortPlayback(hr); return hr; } } // After a discontinuity, we need to wait for the next key frame if (pSample->IsDiscontinuity() == S_OK) { DbgLog((LOG_TRACE, 3, TEXT("Non-key discontinuity - wait for keyframe"))); m_nWaitForKey = 30; } // Start timing the transform (and log it if PERF is defined) if (SUCCEEDED(hr)) { m_tDecodeStart = timeGetTime(); MSR_START(m_idTransform); // have the derived class transform the data hr = Transform(pSample, pOutSample); // Stop the clock (and log it if PERF is defined) MSR_STOP(m_idTransform); m_tDecodeStart = timeGetTime() - m_tDecodeStart; m_itrAvgDecode = m_tDecodeStart * (10000 / 16) + 15 * (m_itrAvgDecode / 16); // Maybe we're waiting for a keyframe still? if (m_nWaitForKey) m_nWaitForKey--; if (m_nWaitForKey && pSample->IsSyncPoint() == S_OK) m_nWaitForKey = FALSE; // if so, then we don't want to pass this on to the renderer if (m_nWaitForKey && hr == NOERROR) { DbgLog((LOG_TRACE, 3, TEXT("still waiting for a keyframe"))); hr = S_FALSE; } } if (FAILED(hr)) { DbgLog((LOG_TRACE, 1, TEXT("Error from video transform"))); } else { // the Transform() function can return S_FALSE to indicate that the // sample should not be delivered; we only deliver the sample if it's // really S_OK (same as NOERROR, of course.) // Try not to return S_FALSE to a direct draw buffer (it's wasteful) // Try to take the decision earlier - before you get it. if (hr == NOERROR) { hr = m_pOutput->Deliver(pOutSample); } else { // S_FALSE returned from Transform is a PRIVATE agreement // We should return NOERROR from Receive() in this case because returning S_FALSE // from Receive() means that this is the end of the stream and no more data should // be sent. if (S_FALSE == hr) { // We must Release() the sample before doing anything // like calling the filter graph because having the // sample means we may have the DirectDraw lock // (== win16 lock on some versions) pOutSample->Release(); m_bSampleSkipped = TRUE; if (!m_bQualityChanged) { m_bQualityChanged = TRUE; NotifyEvent(EC_QUALITY_CHANGE, 0, 0); } return NOERROR; } } } // release the output buffer. If the connected pin still needs it, // it will have addrefed it itself. pOutSample->Release(); ASSERT(CritCheckIn(&m_csReceive)); return hr; } BOOL CVideoTransformFilter::ShouldSkipFrame(IMediaSample *pIn) { REFERENCE_TIME trStart, trStopAt; HRESULT hr = pIn->GetTime(&trStart, &trStopAt); // Don't skip frames with no timestamps if (hr != S_OK) return FALSE; int itrFrame = (int)(trStopAt - trStart); // frame duration if (S_OK == pIn->IsSyncPoint()) { MSR_INTEGER(m_idFrameType, 1); if (m_nKeyFramePeriod < m_nFramesSinceKeyFrame) { // record the max m_nKeyFramePeriod = m_nFramesSinceKeyFrame; } m_nFramesSinceKeyFrame = 0; m_bSkipping = FALSE; } else { MSR_INTEGER(m_idFrameType, 2); if (m_nFramesSinceKeyFrame > m_nKeyFramePeriod && m_nKeyFramePeriod > 0) { // We haven't seen the key frame yet, but we were clearly being // overoptimistic about how frequent they are. m_nKeyFramePeriod = m_nFramesSinceKeyFrame; } } // Whatever we might otherwise decide, // if we are taking only a small fraction of the required frame time to decode // then any quality problems are actually coming from somewhere else. // Could be a net problem at the source for instance. In this case there's // no point in us skipping frames here. if (m_itrAvgDecode * 4 > itrFrame) { // Don't skip unless we are at least a whole frame late. // (We would skip B frames if more than 1/2 frame late, but they're safe). if (m_itrLate > itrFrame) { // Don't skip unless the anticipated key frame would be no more than // 1 frame early. If the renderer has not been waiting (we *guess* // it hasn't because we're late) then it will allow frames to be // played early by up to a frame. // Let T = Stream time from now to anticipated next key frame // = (frame duration) * (KeyFramePeriod - FramesSinceKeyFrame) // So we skip if T - Late < one frame i.e. // (duration) * (freq - FramesSince) - Late < duration // or (duration) * (freq - FramesSince - 1) < Late // We don't dare skip until we have seen some key frames and have // some idea how often they occur and they are reasonably frequent. if (m_nKeyFramePeriod > 0) { // It would be crazy - but we could have a stream with key frames // a very long way apart - and if they are further than about // 3.5 minutes apart then we could get arithmetic overflow in // reference time units. Therefore we switch to mSec at this point int it = (itrFrame / 10000) * (m_nKeyFramePeriod - m_nFramesSinceKeyFrame - 1); MSR_INTEGER(m_idTimeTillKey, it); // For debug - might want to see the details - dump them as scratch pad #ifdef VTRANSPERF MSR_INTEGER(0, itrFrame); MSR_INTEGER(0, m_nFramesSinceKeyFrame); MSR_INTEGER(0, m_nKeyFramePeriod); #endif if (m_itrLate / 10000 > it) { m_bSkipping = TRUE; // Now we are committed. Once we start skipping, we // cannot stop until we hit a key frame. } else { #ifdef VTRANSPERF MSR_INTEGER(0, 777770); // not near enough to next key #endif } } else { #ifdef VTRANSPERF MSR_INTEGER(0, 777771); // Next key not predictable #endif } } else { #ifdef VTRANSPERF MSR_INTEGER(0, 777772); // Less than one frame late MSR_INTEGER(0, m_itrLate); MSR_INTEGER(0, itrFrame); #endif } } else { #ifdef VTRANSPERF MSR_INTEGER(0, 777773); // Decode time short - not not worth skipping MSR_INTEGER(0, m_itrAvgDecode); MSR_INTEGER(0, itrFrame); #endif } ++m_nFramesSinceKeyFrame; if (m_bSkipping) { // We will count down the lateness as we skip each frame. // We re-assess each frame. The key frame might not arrive when expected. // We reset m_itrLate if we get a new Quality message, but actually that's // not likely because we're not sending frames on to the Renderer. In // fact if we DID get another one it would mean that there's a long // pipe between us and the renderer and we might need an altogether // better strategy to avoid hunting! m_itrLate = m_itrLate - itrFrame; } MSR_INTEGER(m_idLate, (int)m_itrLate / 10000); // Note how late we think we are if (m_bSkipping) { if (!m_bQualityChanged) { m_bQualityChanged = TRUE; NotifyEvent(EC_QUALITY_CHANGE, 0, 0); } } return m_bSkipping; } HRESULT CVideoTransformFilter::AlterQuality(Quality q) { // to reduce the amount of 64 bit arithmetic, m_itrLate is an int. // +, -, >, == etc are not too bad, but * and / are painful. if (m_itrLate > 300000000) { // Avoid overflow and silliness - more than 30 secs late is already silly m_itrLate = 300000000; } else { m_itrLate = (int)q.Late; } // We ignore the other fields // We're actually not very good at handling this. In non-direct draw mode // most of the time can be spent in the renderer which can skip any frame. // In that case we'd rather the renderer handled things. // Nevertheless we will keep an eye on it and if we really start getting // a very long way behind then we will actually skip - but we'll still tell // the renderer (or whoever is downstream) that they should handle quality. return E_FAIL; // Tell the renderer to do his thing. } // This will avoid several hundred useless warnings if compiled -W4 by MS VC++ v4 #pragma warning(disable : 4514) ================================================ FILE: common/baseclasses/vtrans.h ================================================ //------------------------------------------------------------------------------ // File: VTrans.h // // Desc: DirectShow base classes - defines a video transform class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // This class is derived from CTransformFilter, but is specialised to handle // the requirements of video quality control by frame dropping. // This is a non-in-place transform, (i.e. it copies the data) such as a decoder. class CVideoTransformFilter : public CTransformFilter { public: CVideoTransformFilter(__in_opt LPCTSTR, __inout_opt LPUNKNOWN, REFCLSID clsid); ~CVideoTransformFilter(); HRESULT EndFlush(); // ================================================================= // ----- override these bits --------------------------------------- // ================================================================= // The following methods are in CTransformFilter which is inherited. // They are mentioned here for completeness // // These MUST be supplied in a derived class // // NOTE: // virtual HRESULT Transform(IMediaSample * pIn, IMediaSample *pOut); // virtual HRESULT CheckInputType(const CMediaType* mtIn) PURE; // virtual HRESULT CheckTransform // (const CMediaType* mtIn, const CMediaType* mtOut) PURE; // static CCOMObject * CreateInstance(LPUNKNOWN, HRESULT *); // virtual HRESULT DecideBufferSize // (IMemAllocator * pAllocator, ALLOCATOR_PROPERTIES *pprop) PURE; // virtual HRESULT GetMediaType(int iPosition, CMediaType *pMediaType) PURE; // // These MAY also be overridden // // virtual HRESULT StopStreaming(); // virtual HRESULT SetMediaType(PIN_DIRECTION direction,const CMediaType *pmt); // virtual HRESULT CheckConnect(PIN_DIRECTION dir,IPin *pPin); // virtual HRESULT BreakConnect(PIN_DIRECTION dir); // virtual HRESULT CompleteConnect(PIN_DIRECTION direction,IPin *pReceivePin); // virtual HRESULT EndOfStream(void); // virtual HRESULT BeginFlush(void); // virtual HRESULT EndFlush(void); // virtual HRESULT NewSegment // (REFERENCE_TIME tStart,REFERENCE_TIME tStop,double dRate); #ifdef PERF // If you override this - ensure that you register all these ids // as well as any of your own, virtual void RegisterPerfId() { m_idSkip = MSR_REGISTER(TEXT("Video Transform Skip frame")); m_idFrameType = MSR_REGISTER(TEXT("Video transform frame type")); m_idLate = MSR_REGISTER(TEXT("Video Transform Lateness")); m_idTimeTillKey = MSR_REGISTER(TEXT("Video Transform Estd. time to next key")); CTransformFilter::RegisterPerfId(); } #endif protected: // =========== QUALITY MANAGEMENT IMPLEMENTATION ======================== // Frames are assumed to come in three types: // Type 1: an AVI key frame or an MPEG I frame. // This frame can be decoded with no history. // Dropping this frame means that no further frame can be decoded // until the next type 1 frame. // Type 1 frames are sync points. // Type 2: an AVI non-key frame or an MPEG P frame. // This frame cannot be decoded unless the previous type 1 frame was // decoded and all type 2 frames since have been decoded. // Dropping this frame means that no further frame can be decoded // until the next type 1 frame. // Type 3: An MPEG B frame. // This frame cannot be decoded unless the previous type 1 or 2 frame // has been decoded AND the subsequent type 1 or 2 frame has also // been decoded. (This requires decoding the frames out of sequence). // Dropping this frame affects no other frames. This implementation // does not allow for these. All non-sync-point frames are treated // as being type 2. // // The spacing of frames of type 1 in a file is not guaranteed. There MUST // be a type 1 frame at (well, near) the start of the file in order to start // decoding at all. After that there could be one every half second or so, // there could be one at the start of each scene (aka "cut", "shot") or // there could be no more at all. // If there is only a single type 1 frame then NO FRAMES CAN BE DROPPED // without losing all the rest of the movie. There is no way to tell whether // this is the case, so we find that we are in the gambling business. // To try to improve the odds, we record the greatest interval between type 1s // that we have seen and we bet on things being no worse than this in the // future. // You can tell if it's a type 1 frame by calling IsSyncPoint(). // there is no architected way to test for a type 3, so you should override // the quality management here if you have B-frames. int m_nKeyFramePeriod; // the largest observed interval between type 1 frames // 1 means every frame is type 1, 2 means every other. int m_nFramesSinceKeyFrame; // Used to count frames since the last type 1. // becomes the new m_nKeyFramePeriod if greater. BOOL m_bSkipping; // we are skipping to the next type 1 frame #ifdef PERF int m_idFrameType; // MSR id Frame type. 1=Key, 2="non-key" int m_idSkip; // MSR id skipping int m_idLate; // MSR id lateness int m_idTimeTillKey; // MSR id for guessed time till next key frame. #endif virtual HRESULT StartStreaming(); HRESULT AbortPlayback(HRESULT hr); // if something bad happens HRESULT Receive(IMediaSample *pSample); HRESULT AlterQuality(Quality q); BOOL ShouldSkipFrame(IMediaSample *pIn); int m_itrLate; // lateness from last Quality message // (this overflows at 214 secs late). int m_tDecodeStart; // timeGetTime when decode started. int m_itrAvgDecode; // Average decode time in reference units. BOOL m_bNoSkip; // debug - no skipping. // We send an EC_QUALITY_CHANGE notification to the app if we have to degrade. // We send one when we start degrading, not one for every frame, this means // we track whether we've sent one yet. BOOL m_bQualityChanged; // When non-zero, don't pass anything to renderer until next keyframe // If there are few keys, give up and eventually draw something int m_nWaitForKey; }; ================================================ FILE: common/baseclasses/winctrl.cpp ================================================ //------------------------------------------------------------------------------ // File: WinCtrl.cpp // // Desc: DirectShow base classes - implements video control interface class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include #include // The control interface methods require us to be connected #define CheckConnected(pin, code) \ { \ if (pin == NULL) \ { \ ASSERT(!TEXT("Pin not set")); \ } \ else if (pin->IsConnected() == FALSE) \ { \ return (code); \ } \ } // This checks to see whether the window has a drain. An application can in // most environments set the owner/parent of windows so that they appear in // a compound document context (for example). In this case, the application // would probably like to be told of any keyboard/mouse messages. Therefore // we pass these messages on untranslated, returning TRUE if we're successful BOOL WINAPI PossiblyEatMessage(HWND hwndDrain, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (hwndDrain != NULL && !InSendMessage()) { switch (uMsg) { case WM_CHAR: case WM_DEADCHAR: case WM_KEYDOWN: case WM_KEYUP: case WM_LBUTTONDBLCLK: case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_MBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_MOUSEACTIVATE: case WM_MOUSEMOVE: // If we pass this on we don't get any mouse clicks // case WM_NCHITTEST: case WM_NCLBUTTONDBLCLK: case WM_NCLBUTTONDOWN: case WM_NCLBUTTONUP: case WM_NCMBUTTONDBLCLK: case WM_NCMBUTTONDOWN: case WM_NCMBUTTONUP: case WM_NCMOUSEMOVE: case WM_NCRBUTTONDBLCLK: case WM_NCRBUTTONDOWN: case WM_NCRBUTTONUP: case WM_RBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_SYSCHAR: case WM_SYSDEADCHAR: case WM_SYSKEYDOWN: case WM_SYSKEYUP: DbgLog((LOG_TRACE, 2, TEXT("Forwarding %x to drain"))); PostMessage(hwndDrain, uMsg, wParam, lParam); return TRUE; } } return FALSE; } // This class implements the IVideoWindow control functions (dual interface) // we support a large number of properties and methods designed to allow the // client (whether it be an automation controller or a C/C++ application) to // set and get a number of window related properties such as it's position. // We also support some methods that duplicate the properties but provide a // more direct and efficient mechanism as many values may be changed in one CBaseControlWindow::CBaseControlWindow(__inout CBaseFilter *pFilter, // Owning filter __in CCritSec *pInterfaceLock, // Locking object __in_opt LPCTSTR pName, // Object description __inout_opt LPUNKNOWN pUnk, // Normal COM ownership __inout HRESULT *phr) : // OLE return code CBaseVideoWindow(pName, pUnk) , m_pInterfaceLock(pInterfaceLock) , m_hwndOwner(NULL) , m_hwndDrain(NULL) , m_bAutoShow(TRUE) , m_pFilter(pFilter) , m_bCursorHidden(FALSE) , m_pPin(NULL) { ASSERT(m_pFilter); ASSERT(m_pInterfaceLock); ASSERT(phr); m_BorderColour = VIDEO_COLOUR; } // Set the title caption on the base window, we don't do any field checking // as we really don't care what title they intend to have. We can always get // it back again later with GetWindowText. The only other complication is to // do the necessary string conversions between ANSI and OLE Unicode strings STDMETHODIMP CBaseControlWindow::put_Caption(__in BSTR strCaption) { CheckPointer((PVOID)strCaption, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); #ifdef UNICODE SetWindowText(m_hwnd, strCaption); #else CHAR Caption[CAPTION]; WideCharToMultiByte(CP_ACP, 0, strCaption, -1, Caption, CAPTION, NULL, NULL); SetWindowText(m_hwnd, Caption); #endif return NOERROR; } // Get the current base window title caption, once again we do no real field // checking. We allocate a string for the window title to be filled in with // which ensures the interface doesn't fiddle around with getting memory. A // BSTR is a normal C string with the length at position (-1), we use the // WriteBSTR helper function to create the caption to try and avoid OLE32 STDMETHODIMP CBaseControlWindow::get_Caption(__out BSTR *pstrCaption) { CheckPointer(pstrCaption, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); WCHAR WideCaption[CAPTION]; #ifdef UNICODE GetWindowText(m_hwnd, WideCaption, CAPTION); #else // Convert the ASCII caption to a UNICODE string TCHAR Caption[CAPTION]; GetWindowText(m_hwnd, Caption, CAPTION); MultiByteToWideChar(CP_ACP, 0, Caption, -1, WideCaption, CAPTION); #endif return WriteBSTR(pstrCaption, WideCaption); } // Set the window style using GWL_EXSTYLE STDMETHODIMP CBaseControlWindow::put_WindowStyleEx(long WindowStyleEx) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // Should we be taking off WS_EX_TOPMOST if (GetWindowLong(m_hwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) { if ((WindowStyleEx & WS_EX_TOPMOST) == 0) { SendMessage(m_hwnd, m_ShowStageTop, (WPARAM)FALSE, (LPARAM)0); } } // Likewise should we be adding WS_EX_TOPMOST if (WindowStyleEx & WS_EX_TOPMOST) { SendMessage(m_hwnd, m_ShowStageTop, (WPARAM)TRUE, (LPARAM)0); WindowStyleEx &= (~WS_EX_TOPMOST); if (WindowStyleEx == 0) return NOERROR; } return DoSetWindowStyle(WindowStyleEx, GWL_EXSTYLE); } // Gets the current GWL_EXSTYLE base window style STDMETHODIMP CBaseControlWindow::get_WindowStyleEx(__out long *pWindowStyleEx) { CheckPointer(pWindowStyleEx, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); return DoGetWindowStyle(pWindowStyleEx, GWL_EXSTYLE); } // Set the window style using GWL_STYLE STDMETHODIMP CBaseControlWindow::put_WindowStyle(long WindowStyle) { // These styles cannot be changed dynamically if ((WindowStyle & WS_DISABLED) || (WindowStyle & WS_ICONIC) || (WindowStyle & WS_MAXIMIZE) || (WindowStyle & WS_MINIMIZE) || (WindowStyle & WS_HSCROLL) || (WindowStyle & WS_VSCROLL)) { return E_INVALIDARG; } CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); return DoSetWindowStyle(WindowStyle, GWL_STYLE); } // Get the current GWL_STYLE base window style STDMETHODIMP CBaseControlWindow::get_WindowStyle(__out long *pWindowStyle) { CheckPointer(pWindowStyle, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); return DoGetWindowStyle(pWindowStyle, GWL_STYLE); } // Change the base window style or the extended styles depending on whether // WindowLong is GWL_STYLE or GWL_EXSTYLE. We must call SetWindowPos to have // the window displayed in it's new style after the change which is a little // tricky if the window is not currently visible as we realise it offscreen. // In most cases the client will call get_WindowStyle before they call this // and then AND and OR in extra bit settings according to the requirements HRESULT CBaseControlWindow::DoSetWindowStyle(long Style, long WindowLong) { RECT WindowRect; // Get the window's visibility before setting the style BOOL bVisible = IsWindowVisible(m_hwnd); EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); // Set the new style flags for the window SetWindowLong(m_hwnd, WindowLong, Style); UINT WindowFlags = SWP_SHOWWINDOW | SWP_FRAMECHANGED | SWP_NOACTIVATE; WindowFlags |= SWP_NOZORDER | SWP_NOSIZE | SWP_NOMOVE; // Show the window again in the current position if (bVisible == TRUE) { SetWindowPos(m_hwnd, // Base window handle HWND_TOP, // Just a place holder 0, 0, 0, 0, // Leave size and position WindowFlags); // Just draw it again return NOERROR; } // Move the window offscreen so the user doesn't see the changes MoveWindow((HWND)m_hwnd, // Base window handle GetSystemMetrics(SM_CXSCREEN), // Current desktop width GetSystemMetrics(SM_CYSCREEN), // Likewise it's height WIDTH(&WindowRect), // Use the same width HEIGHT(&WindowRect), // Keep height same to TRUE); // May as well repaint // Now show the previously hidden window SetWindowPos(m_hwnd, // Base window handle HWND_TOP, // Just a place holder 0, 0, 0, 0, // Leave size and position WindowFlags); // Just draw it again ShowWindow(m_hwnd, SW_HIDE); if (GetParent(m_hwnd)) { MapWindowPoints(HWND_DESKTOP, GetParent(m_hwnd), (LPPOINT)&WindowRect, 2); } MoveWindow((HWND)m_hwnd, // Base window handle WindowRect.left, // Existing x coordinate WindowRect.top, // Existing y coordinate WIDTH(&WindowRect), // Use the same width HEIGHT(&WindowRect), // Keep height same to TRUE); // May as well repaint return NOERROR; } // Get the current base window style (either GWL_STYLE or GWL_EXSTYLE) HRESULT CBaseControlWindow::DoGetWindowStyle(__out long *pStyle, long WindowLong) { *pStyle = GetWindowLong(m_hwnd, WindowLong); return NOERROR; } // Change the visibility of the base window, this takes the same parameters // as the ShowWindow Win32 API does, so the client can have the window hidden // or shown, minimised to an icon, or maximised to play in full screen mode // We pass the request on to the base window to actually make the change STDMETHODIMP CBaseControlWindow::put_WindowState(long WindowState) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); DoShowWindow(WindowState); return NOERROR; } // Get the current window state, this function returns a subset of the SW bit // settings available in ShowWindow, if the window is visible then SW_SHOW is // set, if it is hidden then the SW_HIDDEN is set, if it is either minimised // or maximised then the SW_MINIMIZE or SW_MAXIMIZE is set respectively. The // other SW bit settings are really set commands not readable output values STDMETHODIMP CBaseControlWindow::get_WindowState(__out long *pWindowState) { CheckPointer(pWindowState, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); ASSERT(pWindowState); *pWindowState = FALSE; // Is the window visible, a window is termed visible if it is somewhere on // the current desktop even if it is completely obscured by other windows // so the flag is a style for each window set with the WS_VISIBLE bit if (IsWindowVisible(m_hwnd) == TRUE) { // Is the base window iconic if (IsIconic(m_hwnd) == TRUE) { *pWindowState |= SW_MINIMIZE; } // Has the window been maximised else if (IsZoomed(m_hwnd) == TRUE) { *pWindowState |= SW_MAXIMIZE; } // Window is normal else { *pWindowState |= SW_SHOW; } } else { *pWindowState |= SW_HIDE; } return NOERROR; } // This makes sure that any palette we realise in the base window (through a // media type or through the overlay interface) is done in the background and // is therefore mapped to existing device entries rather than taking it over // as it will do when we this window gets the keyboard focus. An application // uses this to make sure it doesn't have it's palette removed by the window STDMETHODIMP CBaseControlWindow::put_BackgroundPalette(long BackgroundPalette) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cWindowLock(&m_WindowLock); // Check this is a valid automation boolean type if (BackgroundPalette != OATRUE) { if (BackgroundPalette != OAFALSE) { return E_INVALIDARG; } } // Make sure the window realises any palette it has again m_bBackground = (BackgroundPalette == OATRUE ? TRUE : FALSE); PostMessage(m_hwnd, m_RealizePalette, 0, 0); PaintWindow(FALSE); return NOERROR; } // This returns the current background realisation setting STDMETHODIMP CBaseControlWindow::get_BackgroundPalette(__out long *pBackgroundPalette) { CheckPointer(pBackgroundPalette, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cWindowLock(&m_WindowLock); // Get the current background palette setting *pBackgroundPalette = (m_bBackground == TRUE ? OATRUE : OAFALSE); return NOERROR; } // Change the visibility of the base window STDMETHODIMP CBaseControlWindow::put_Visible(long Visible) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // Check this is a valid automation boolean type if (Visible != OATRUE) { if (Visible != OAFALSE) { return E_INVALIDARG; } } // Convert the boolean visibility into SW_SHOW and SW_HIDE INT Mode = (Visible == OATRUE ? SW_SHOWNORMAL : SW_HIDE); DoShowWindow(Mode); return NOERROR; } // Return OATRUE if the window is currently visible otherwise OAFALSE STDMETHODIMP CBaseControlWindow::get_Visible(__out long *pVisible) { CheckPointer(pVisible, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // See if the base window has a WS_VISIBLE style - this will return TRUE // even if the window is completely obscured by other desktop windows, we // return FALSE if the window is not showing because of earlier calls BOOL Mode = IsWindowVisible(m_hwnd); *pVisible = (Mode == TRUE ? OATRUE : OAFALSE); return NOERROR; } // Change the left position of the base window. This keeps the window width // and height properties the same so it effectively shunts the window left or // right accordingly - there is the Width property to change that dimension STDMETHODIMP CBaseControlWindow::put_Left(long Left) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); BOOL bSuccess; RECT WindowRect; // Get the current window position in a RECT EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); if (GetParent(m_hwnd)) { MapWindowPoints(HWND_DESKTOP, GetParent(m_hwnd), (LPPOINT)&WindowRect, 2); } // Adjust the coordinates ready for SetWindowPos, the window rectangle we // get back from GetWindowRect is in left,top,right and bottom while the // coordinates SetWindowPos wants are left,top,width and height values WindowRect.bottom = WindowRect.bottom - WindowRect.top; WindowRect.right = WindowRect.right - WindowRect.left; UINT WindowFlags = SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE; bSuccess = SetWindowPos(m_hwnd, // Window handle HWND_TOP, // Put it at the top Left, // New left position WindowRect.top, // Leave top alone WindowRect.right, // The WIDTH (not right) WindowRect.bottom, // The HEIGHT (not bottom) WindowFlags); // Show window options if (bSuccess == FALSE) { return E_INVALIDARG; } return NOERROR; } // Return the current base window left position STDMETHODIMP CBaseControlWindow::get_Left(__out long *pLeft) { CheckPointer(pLeft, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); RECT WindowRect; EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); *pLeft = WindowRect.left; return NOERROR; } // Change the current width of the base window. This property complements the // left position property so we must keep the left edge constant and expand or // contract to the right, the alternative would be to change the left edge so // keeping the right edge constant but this is maybe a little more intuitive STDMETHODIMP CBaseControlWindow::put_Width(long Width) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); BOOL bSuccess; RECT WindowRect; // Adjust the coordinates ready for SetWindowPos, the window rectangle we // get back from GetWindowRect is in left,top,right and bottom while the // coordinates SetWindowPos wants are left,top,width and height values EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); if (GetParent(m_hwnd)) { MapWindowPoints(HWND_DESKTOP, GetParent(m_hwnd), (LPPOINT)&WindowRect, 2); } WindowRect.bottom = WindowRect.bottom - WindowRect.top; UINT WindowFlags = SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE; // This seems to have a bug in that calling SetWindowPos on a window with // just the width changing causes it to ignore the width that you pass in // and sets it to a mimimum value of 110 pixels wide (Windows NT 3.51) bSuccess = SetWindowPos(m_hwnd, // Window handle HWND_TOP, // Put it at the top WindowRect.left, // Leave left alone WindowRect.top, // Leave top alone Width, // New WIDTH dimension WindowRect.bottom, // The HEIGHT (not bottom) WindowFlags); // Show window options if (bSuccess == FALSE) { return E_INVALIDARG; } return NOERROR; } // Return the current base window width STDMETHODIMP CBaseControlWindow::get_Width(__out long *pWidth) { CheckPointer(pWidth, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); RECT WindowRect; EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); *pWidth = WindowRect.right - WindowRect.left; return NOERROR; } // This allows the client program to change the top position for the window in // the same way that changing the left position does not affect the width of // the image so changing the top position does not affect the window height STDMETHODIMP CBaseControlWindow::put_Top(long Top) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); BOOL bSuccess; RECT WindowRect; // Get the current window position in a RECT EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); if (GetParent(m_hwnd)) { MapWindowPoints(HWND_DESKTOP, GetParent(m_hwnd), (LPPOINT)&WindowRect, 2); } // Adjust the coordinates ready for SetWindowPos, the window rectangle we // get back from GetWindowRect is in left,top,right and bottom while the // coordinates SetWindowPos wants are left,top,width and height values WindowRect.bottom = WindowRect.bottom - WindowRect.top; WindowRect.right = WindowRect.right - WindowRect.left; UINT WindowFlags = SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE; bSuccess = SetWindowPos(m_hwnd, // Window handle HWND_TOP, // Put it at the top WindowRect.left, // Leave left alone Top, // New top position WindowRect.right, // The WIDTH (not right) WindowRect.bottom, // The HEIGHT (not bottom) WindowFlags); // Show window flags if (bSuccess == FALSE) { return E_INVALIDARG; } return NOERROR; } // Return the current base window top position STDMETHODIMP CBaseControlWindow::get_Top(long *pTop) { CheckPointer(pTop, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); RECT WindowRect; EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); *pTop = WindowRect.top; return NOERROR; } // Change the height of the window, this complements the top property so when // we change this we must keep the top position for the base window, as said // before we could keep the bottom and grow upwards although this is perhaps // a little more intuitive since we already have a top position property STDMETHODIMP CBaseControlWindow::put_Height(long Height) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); BOOL bSuccess; RECT WindowRect; // Adjust the coordinates ready for SetWindowPos, the window rectangle we // get back from GetWindowRect is in left,top,right and bottom while the // coordinates SetWindowPos wants are left,top,width and height values EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); if (GetParent(m_hwnd)) { MapWindowPoints(HWND_DESKTOP, GetParent(m_hwnd), (LPPOINT)&WindowRect, 2); } WindowRect.right = WindowRect.right - WindowRect.left; UINT WindowFlags = SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE; bSuccess = SetWindowPos(m_hwnd, // Window handle HWND_TOP, // Put it at the top WindowRect.left, // Leave left alone WindowRect.top, // Leave top alone WindowRect.right, // The WIDTH (not right) Height, // New height dimension WindowFlags); // Show window flags if (bSuccess == FALSE) { return E_INVALIDARG; } return NOERROR; } // Return the current base window height STDMETHODIMP CBaseControlWindow::get_Height(__out long *pHeight) { CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); RECT WindowRect; EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); *pHeight = WindowRect.bottom - WindowRect.top; return NOERROR; } // This can be called to change the owning window. Setting the owner is done // through this function, however to make the window a true child window the // style must also be set to WS_CHILD. After resetting the owner to NULL an // application should also set the style to WS_OVERLAPPED | WS_CLIPCHILDREN. // We cannot lock the object here because the SetParent causes an interthread // SendMessage to the owner window. If they are in GetState we will sit here // incomplete with the critical section locked therefore blocking out source // filter threads from accessing us. Because the source thread can't enter us // it can't get buffers or call EndOfStream so the GetState will not complete STDMETHODIMP CBaseControlWindow::put_Owner(OAHWND Owner) { // Check we are connected otherwise reject the call CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); m_hwndOwner = (HWND)Owner; HWND hwndParent = m_hwndOwner; // Add or remove WS_CHILD as appropriate LONG Style = GetWindowLong(m_hwnd, GWL_STYLE); if (Owner == NULL) { Style &= (~WS_CHILD); } else { Style |= (WS_CHILD); } SetWindowLong(m_hwnd, GWL_STYLE, Style); // Don't call this with the filter locked SetParent(m_hwnd, hwndParent); PaintWindow(TRUE); NOTE1("Changed parent %lx", hwndParent); return NOERROR; } // This complements the put_Owner to get the current owning window property // we always return NOERROR although the returned window handle may be NULL // to indicate no owning window (the desktop window doesn't qualify as one) // If an application sets the owner we call SetParent, however that returns // NULL until the WS_CHILD bit is set on, so we store the owner internally STDMETHODIMP CBaseControlWindow::get_Owner(__out OAHWND *Owner) { CheckPointer(Owner, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); *Owner = (OAHWND)m_hwndOwner; return NOERROR; } // And renderer supporting IVideoWindow may have an HWND set who will get any // keyboard and mouse messages we receive posted on to them. This is separate // from setting an owning window. By separating the two, applications may get // messages sent on even when they have set no owner (perhaps it's maximised) STDMETHODIMP CBaseControlWindow::put_MessageDrain(OAHWND Drain) { // Check we are connected otherwise reject the call CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); m_hwndDrain = (HWND)Drain; return NOERROR; } // Return the current message drain STDMETHODIMP CBaseControlWindow::get_MessageDrain(__out OAHWND *Drain) { CheckPointer(Drain, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); *Drain = (OAHWND)m_hwndDrain; return NOERROR; } // This is called by the filter graph to inform us of a message we should know // is being sent to our owning window. We have this because as a child window // we do not get certain messages that are only sent to top level windows. We // must see the palette changed/changing/query messages so that we know if we // have the foreground palette or not. We pass the message on to our window // using SendMessage - this will cause an interthread send message to occur STDMETHODIMP CBaseControlWindow::NotifyOwnerMessage(OAHWND hwnd, // Window handle long uMsg, // Message ID LONG_PTR wParam, // Parameters LONG_PTR lParam) // for message { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // Only interested in these Windows messages switch (uMsg) { case WM_SYSCOLORCHANGE: case WM_PALETTECHANGED: case WM_PALETTEISCHANGING: case WM_QUERYNEWPALETTE: case WM_DEVMODECHANGE: case WM_DISPLAYCHANGE: case WM_ACTIVATEAPP: // If we do not have an owner then ignore if (m_hwndOwner == NULL) { return NOERROR; } SendMessage(m_hwnd, uMsg, (WPARAM)wParam, (LPARAM)lParam); break; // do NOT fwd WM_MOVE. the parameters are the location of the parent // window, NOT what the renderer should be looking at. But we need // to make sure the overlay is moved with the parent window, so we // do this. case WM_MOVE: PostMessage(m_hwnd, WM_PAINT, 0, 0); break; } return NOERROR; } // Allow an application to have us set the base window in the foreground. We // have this because it is difficult for one thread to do do this to a window // owned by another thread. We ask the base window class to do the real work STDMETHODIMP CBaseControlWindow::SetWindowForeground(long Focus) { // Check this is a valid automation boolean type if (Focus != OATRUE) { if (Focus != OAFALSE) { return E_INVALIDARG; } } // We shouldn't lock as this sends a message CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); BOOL bFocus = (Focus == OATRUE ? TRUE : FALSE); DoSetWindowForeground(bFocus); return NOERROR; } // This allows a client to set the complete window size and position in one // atomic operation. The same affect can be had by changing each dimension // in turn through their individual properties although some flashing will // occur as each of them gets updated (they are better set at design time) STDMETHODIMP CBaseControlWindow::SetWindowPosition(long Left, long Top, long Width, long Height) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); BOOL bSuccess; // Set the new size and position UINT WindowFlags = SWP_NOZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE; ASSERT(IsWindow(m_hwnd)); bSuccess = SetWindowPos(m_hwnd, // Window handle HWND_TOP, // Put it at the top Left, // Left position Top, // Top position Width, // Window width Height, // Window height WindowFlags); // Show window flags ASSERT(bSuccess); #ifdef DEBUG DbgLog((LOG_TRACE, 1, TEXT("SWP failed error %d"), GetLastError())); #endif if (bSuccess == FALSE) { return E_INVALIDARG; } return NOERROR; } // This complements the SetWindowPosition to return the current window place // in device coordinates. As before the same information can be retrived by // calling the property get functions individually but this is atomic and is // therefore more suitable to a live environment rather than design time STDMETHODIMP CBaseControlWindow::GetWindowPosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight) { // Should check the pointers are not NULL CheckPointer(pLeft, E_POINTER); CheckPointer(pTop, E_POINTER); CheckPointer(pWidth, E_POINTER); CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); RECT WindowRect; // Get the current window coordinates EXECUTE_ASSERT(GetWindowRect(m_hwnd, &WindowRect)); // Convert the RECT into left,top,width and height values *pLeft = WindowRect.left; *pTop = WindowRect.top; *pWidth = WindowRect.right - WindowRect.left; *pHeight = WindowRect.bottom - WindowRect.top; return NOERROR; } // When a window is maximised or iconic calling GetWindowPosition will return // the current window position (likewise for the properties). However if the // restored size (ie the size we'll return to when normally shown) is needed // then this should be used. When in a normal position (neither iconic nor // maximised) then this returns the same coordinates as GetWindowPosition STDMETHODIMP CBaseControlWindow::GetRestorePosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight) { // Should check the pointers are not NULL CheckPointer(pLeft, E_POINTER); CheckPointer(pTop, E_POINTER); CheckPointer(pWidth, E_POINTER); CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // Use GetWindowPlacement to find the restore position WINDOWPLACEMENT Place; Place.length = sizeof(WINDOWPLACEMENT); EXECUTE_ASSERT(GetWindowPlacement(m_hwnd, &Place)); RECT WorkArea; // We must take into account any task bar present if (SystemParametersInfo(SPI_GETWORKAREA, 0, &WorkArea, FALSE) == TRUE) { if (GetParent(m_hwnd) == NULL) { Place.rcNormalPosition.top += WorkArea.top; Place.rcNormalPosition.bottom += WorkArea.top; Place.rcNormalPosition.left += WorkArea.left; Place.rcNormalPosition.right += WorkArea.left; } } // Convert the RECT into left,top,width and height values *pLeft = Place.rcNormalPosition.left; *pTop = Place.rcNormalPosition.top; *pWidth = Place.rcNormalPosition.right - Place.rcNormalPosition.left; *pHeight = Place.rcNormalPosition.bottom - Place.rcNormalPosition.top; return NOERROR; } // Return the current border colour, if we are playing something to a subset // of the base window display there is an outside area exposed. The default // action is to paint this colour in the Windows background colour (defined // as value COLOR_WINDOW) We reset to this default when we're disconnected STDMETHODIMP CBaseControlWindow::get_BorderColor(__out long *Color) { CheckPointer(Color, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); *Color = (long)m_BorderColour; return NOERROR; } // This can be called to set the current border colour STDMETHODIMP CBaseControlWindow::put_BorderColor(long Color) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // Have the window repainted with the new border colour m_BorderColour = (COLORREF)Color; PaintWindow(TRUE); return NOERROR; } // Delegate fullscreen handling to plug in distributor STDMETHODIMP CBaseControlWindow::get_FullScreenMode(__out long *FullScreenMode) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CheckPointer(FullScreenMode, E_POINTER); return E_NOTIMPL; } // Delegate fullscreen handling to plug in distributor STDMETHODIMP CBaseControlWindow::put_FullScreenMode(long FullScreenMode) { return E_NOTIMPL; } // This sets the auto show property, this property causes the base window to // be displayed whenever we change state. This allows an application to have // to do nothing to have the window appear but still allow them to change the // default behaviour if for example they want to keep it hidden for longer STDMETHODIMP CBaseControlWindow::put_AutoShow(long AutoShow) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // Check this is a valid automation boolean type if (AutoShow != OATRUE) { if (AutoShow != OAFALSE) { return E_INVALIDARG; } } m_bAutoShow = (AutoShow == OATRUE ? TRUE : FALSE); return NOERROR; } // This can be called to get the current auto show flag. The flag is updated // when we connect and disconnect and through this interface all of which are // controlled and serialised by means of the main renderer critical section STDMETHODIMP CBaseControlWindow::get_AutoShow(__out long *AutoShow) { CheckPointer(AutoShow, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); *AutoShow = (m_bAutoShow == TRUE ? OATRUE : OAFALSE); return NOERROR; } // Return the minimum ideal image size for the current video. This may differ // to the actual video dimensions because we may be using DirectDraw hardware // that has specific stretching requirements. For example the Cirrus Logic // cards have a minimum stretch factor depending on the overlay surface size STDMETHODIMP CBaseControlWindow::GetMinIdealImageSize(__out long *pWidth, __out long *pHeight) { CheckPointer(pWidth, E_POINTER); CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); FILTER_STATE State; // Must not be stopped for this to work correctly m_pFilter->GetState(0, &State); if (State == State_Stopped) { return VFW_E_WRONG_STATE; } RECT DefaultRect = GetDefaultRect(); *pWidth = WIDTH(&DefaultRect); *pHeight = HEIGHT(&DefaultRect); return NOERROR; } // Return the maximum ideal image size for the current video. This may differ // to the actual video dimensions because we may be using DirectDraw hardware // that has specific stretching requirements. For example the Cirrus Logic // cards have a maximum stretch factor depending on the overlay surface size STDMETHODIMP CBaseControlWindow::GetMaxIdealImageSize(__out long *pWidth, __out long *pHeight) { CheckPointer(pWidth, E_POINTER); CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); FILTER_STATE State; // Must not be stopped for this to work correctly m_pFilter->GetState(0, &State); if (State == State_Stopped) { return VFW_E_WRONG_STATE; } RECT DefaultRect = GetDefaultRect(); *pWidth = WIDTH(&DefaultRect); *pHeight = HEIGHT(&DefaultRect); return NOERROR; } // Allow an application to hide the cursor on our window STDMETHODIMP CBaseControlWindow::HideCursor(long HideCursor) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); // Check this is a valid automation boolean type if (HideCursor != OATRUE) { if (HideCursor != OAFALSE) { return E_INVALIDARG; } } m_bCursorHidden = (HideCursor == OATRUE ? TRUE : FALSE); return NOERROR; } // Returns whether we have the cursor hidden or not STDMETHODIMP CBaseControlWindow::IsCursorHidden(__out long *CursorHidden) { CheckPointer(CursorHidden, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); *CursorHidden = (m_bCursorHidden == TRUE ? OATRUE : OAFALSE); return NOERROR; } // This class implements the IBasicVideo control functions (dual interface) // we support a large number of properties and methods designed to allow the // client (whether it be an automation controller or a C/C++ application) to // set and get a number of video related properties such as the native video // size. We support some methods that duplicate the properties but provide a // more direct and efficient mechanism as many values may be changed in one CBaseControlVideo::CBaseControlVideo(__inout CBaseFilter *pFilter, // Owning filter __in CCritSec *pInterfaceLock, // Locking object __in_opt LPCTSTR pName, // Object description __inout_opt LPUNKNOWN pUnk, // Normal COM ownership __inout HRESULT *phr) : // OLE return code CBaseBasicVideo(pName, pUnk) , m_pFilter(pFilter) , m_pInterfaceLock(pInterfaceLock) , m_pPin(NULL) { ASSERT(m_pFilter); ASSERT(m_pInterfaceLock); ASSERT(phr); } // Return an approximate average time per frame STDMETHODIMP CBaseControlVideo::get_AvgTimePerFrame(__out REFTIME *pAvgTimePerFrame) { CheckPointer(pAvgTimePerFrame, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; COARefTime AvgTime(pVideoInfo->AvgTimePerFrame); *pAvgTimePerFrame = (REFTIME)AvgTime; return NOERROR; } // Return an approximate bit rate for the video STDMETHODIMP CBaseControlVideo::get_BitRate(__out long *pBitRate) { CheckPointer(pBitRate, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; *pBitRate = pVideoInfo->dwBitRate; return NOERROR; } // Return an approximate bit error rate STDMETHODIMP CBaseControlVideo::get_BitErrorRate(__out long *pBitErrorRate) { CheckPointer(pBitErrorRate, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; *pBitErrorRate = pVideoInfo->dwBitErrorRate; return NOERROR; } // This returns the current video width STDMETHODIMP CBaseControlVideo::get_VideoWidth(__out long *pVideoWidth) { CheckPointer(pVideoWidth, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; *pVideoWidth = pVideoInfo->bmiHeader.biWidth; return NOERROR; } // This returns the current video height STDMETHODIMP CBaseControlVideo::get_VideoHeight(__out long *pVideoHeight) { CheckPointer(pVideoHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; *pVideoHeight = pVideoInfo->bmiHeader.biHeight; return NOERROR; } // This returns the current palette the video is using as an array allocated // by the user. To remain consistent we use PALETTEENTRY fields to return the // colours in rather than RGBQUADs that multimedia decided to use. The memory // is allocated by the user so we simple copy each in turn. We check that the // number of entries requested and the start position offset are both valid // If the number of entries evaluates to zero then we return an S_FALSE code STDMETHODIMP CBaseControlVideo::GetVideoPaletteEntries(long StartIndex, long Entries, __out long *pRetrieved, __out_ecount_part(Entries, *pRetrieved) long *pPalette) { CheckPointer(pRetrieved, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); CMediaType MediaType; // Get the video format from the derived class VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo); // Is the current format palettised if (PALETTISED(pVideoInfo) == FALSE) { *pRetrieved = 0; return VFW_E_NO_PALETTE_AVAILABLE; } // Do they just want to know how many are available if (pPalette == NULL) { *pRetrieved = pHeader->biClrUsed; return NOERROR; } // Make sure the start position is a valid offset if (StartIndex >= (LONG)pHeader->biClrUsed || StartIndex < 0) { *pRetrieved = 0; return E_INVALIDARG; } // Correct the number we can retrieve LONG Available = (LONG)pHeader->biClrUsed - StartIndex; *pRetrieved = max(0, min(Available, Entries)); if (*pRetrieved == 0) { return S_FALSE; } // Copy the palette entries to the output buffer PALETTEENTRY *pEntries = (PALETTEENTRY *)pPalette; RGBQUAD *pColours = COLORS(pVideoInfo) + StartIndex; for (LONG Count = 0; Count < *pRetrieved; Count++) { pEntries[Count].peRed = pColours[Count].rgbRed; pEntries[Count].peGreen = pColours[Count].rgbGreen; pEntries[Count].peBlue = pColours[Count].rgbBlue; pEntries[Count].peFlags = 0; } return NOERROR; } // This returns the current video dimensions as a method rather than a number // of individual property get calls. For the same reasons as said before we // cannot access the renderer media type directly as the window object thread // may be updating it since dynamic format changes may change these values STDMETHODIMP CBaseControlVideo::GetVideoSize(__out long *pWidth, __out long *pHeight) { CheckPointer(pWidth, E_POINTER); CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); // Get the video format from the derived class VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; *pWidth = pVideoInfo->bmiHeader.biWidth; *pHeight = pVideoInfo->bmiHeader.biHeight; return NOERROR; } // Set the source video rectangle as left,top,right and bottom coordinates // rather than left,top,width and height as per OLE automation interfaces // Then pass the rectangle on to the window object to set the source STDMETHODIMP CBaseControlVideo::SetSourcePosition(long Left, long Top, long Width, long Height) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; SourceRect.left = Left; SourceRect.top = Top; SourceRect.right = Left + Width; SourceRect.bottom = Top + Height; // Check the source rectangle is valid HRESULT hr = CheckSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } // Now set the source rectangle hr = SetSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the source rectangle in left,top,width and height rather than the // left,top,right and bottom values that RECT uses (and which the window // object returns through GetSourceRect) which requires a little work STDMETHODIMP CBaseControlVideo::GetSourcePosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight) { // Should check the pointers are non NULL CheckPointer(pLeft, E_POINTER); CheckPointer(pTop, E_POINTER); CheckPointer(pWidth, E_POINTER); CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); RECT SourceRect; CAutoLock cInterfaceLock(m_pInterfaceLock); GetSourceRect(&SourceRect); *pLeft = SourceRect.left; *pTop = SourceRect.top; *pWidth = WIDTH(&SourceRect); *pHeight = HEIGHT(&SourceRect); return NOERROR; } // Set the video destination as left,top,right and bottom coordinates rather // than the left,top,width and height uses as per OLE automation interfaces // Then pass the rectangle on to the window object to set the destination STDMETHODIMP CBaseControlVideo::SetDestinationPosition(long Left, long Top, long Width, long Height) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; DestinationRect.left = Left; DestinationRect.top = Top; DestinationRect.right = Left + Width; DestinationRect.bottom = Top + Height; // Check the target rectangle is valid HRESULT hr = CheckTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } // Now set the new target rectangle hr = SetTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the destination rectangle in left,top,width and height rather than // the left,top,right and bottom values that RECT uses (and which the window // object returns through GetDestinationRect) which requires a little work STDMETHODIMP CBaseControlVideo::GetDestinationPosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight) { // Should check the pointers are not NULL CheckPointer(pLeft, E_POINTER); CheckPointer(pTop, E_POINTER); CheckPointer(pWidth, E_POINTER); CheckPointer(pHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); RECT DestinationRect; CAutoLock cInterfaceLock(m_pInterfaceLock); GetTargetRect(&DestinationRect); *pLeft = DestinationRect.left; *pTop = DestinationRect.top; *pWidth = WIDTH(&DestinationRect); *pHeight = HEIGHT(&DestinationRect); return NOERROR; } // Set the source left position, the source rectangle we get back from the // window object is a true rectangle in left,top,right and bottom positions // so all we have to do is to update the left position and pass it back. We // must keep the current width constant when we're updating this property STDMETHODIMP CBaseControlVideo::put_SourceLeft(long SourceLeft) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); SourceRect.right = SourceLeft + WIDTH(&SourceRect); SourceRect.left = SourceLeft; // Check the source rectangle is valid HRESULT hr = CheckSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } // Now set the source rectangle hr = SetSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the current left source video position STDMETHODIMP CBaseControlVideo::get_SourceLeft(__out long *pSourceLeft) { CheckPointer(pSourceLeft, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); *pSourceLeft = SourceRect.left; return NOERROR; } // Set the source width, we get the current source rectangle and then update // the right position to be the left position (thereby keeping it constant) // plus the new source width we are passed in (it expands to the right) STDMETHODIMP CBaseControlVideo::put_SourceWidth(long SourceWidth) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); SourceRect.right = SourceRect.left + SourceWidth; // Check the source rectangle is valid HRESULT hr = CheckSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } // Now set the source rectangle hr = SetSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the current source width STDMETHODIMP CBaseControlVideo::get_SourceWidth(__out long *pSourceWidth) { CheckPointer(pSourceWidth, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); *pSourceWidth = WIDTH(&SourceRect); return NOERROR; } // Set the source top position - changing this property does not affect the // current source height. So changing this shunts the source rectangle up and // down appropriately. Changing the height complements this functionality by // keeping the top position constant and simply changing the source height STDMETHODIMP CBaseControlVideo::put_SourceTop(long SourceTop) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); SourceRect.bottom = SourceTop + HEIGHT(&SourceRect); SourceRect.top = SourceTop; // Check the source rectangle is valid HRESULT hr = CheckSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } // Now set the source rectangle hr = SetSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the current top position STDMETHODIMP CBaseControlVideo::get_SourceTop(__out long *pSourceTop) { CheckPointer(pSourceTop, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); *pSourceTop = SourceRect.top; return NOERROR; } // Set the source height STDMETHODIMP CBaseControlVideo::put_SourceHeight(long SourceHeight) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); SourceRect.bottom = SourceRect.top + SourceHeight; // Check the source rectangle is valid HRESULT hr = CheckSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } // Now set the source rectangle hr = SetSourceRect(&SourceRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the current source height STDMETHODIMP CBaseControlVideo::get_SourceHeight(__out long *pSourceHeight) { CheckPointer(pSourceHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT SourceRect; GetSourceRect(&SourceRect); *pSourceHeight = HEIGHT(&SourceRect); return NOERROR; } // Set the target left position, the target rectangle we get back from the // window object is a true rectangle in left,top,right and bottom positions // so all we have to do is to update the left position and pass it back. We // must keep the current width constant when we're updating this property STDMETHODIMP CBaseControlVideo::put_DestinationLeft(long DestinationLeft) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); DestinationRect.right = DestinationLeft + WIDTH(&DestinationRect); DestinationRect.left = DestinationLeft; // Check the target rectangle is valid HRESULT hr = CheckTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } // Now set the new target rectangle hr = SetTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the left position for the destination rectangle STDMETHODIMP CBaseControlVideo::get_DestinationLeft(__out long *pDestinationLeft) { CheckPointer(pDestinationLeft, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); *pDestinationLeft = DestinationRect.left; return NOERROR; } // Set the destination width STDMETHODIMP CBaseControlVideo::put_DestinationWidth(long DestinationWidth) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); DestinationRect.right = DestinationRect.left + DestinationWidth; // Check the target rectangle is valid HRESULT hr = CheckTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } // Now set the new target rectangle hr = SetTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the width for the destination rectangle STDMETHODIMP CBaseControlVideo::get_DestinationWidth(__out long *pDestinationWidth) { CheckPointer(pDestinationWidth, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); *pDestinationWidth = WIDTH(&DestinationRect); return NOERROR; } // Set the target top position - changing this property does not affect the // current target height. So changing this shunts the target rectangle up and // down appropriately. Changing the height complements this functionality by // keeping the top position constant and simply changing the target height STDMETHODIMP CBaseControlVideo::put_DestinationTop(long DestinationTop) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); DestinationRect.bottom = DestinationTop + HEIGHT(&DestinationRect); DestinationRect.top = DestinationTop; // Check the target rectangle is valid HRESULT hr = CheckTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } // Now set the new target rectangle hr = SetTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the top position for the destination rectangle STDMETHODIMP CBaseControlVideo::get_DestinationTop(__out long *pDestinationTop) { CheckPointer(pDestinationTop, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); *pDestinationTop = DestinationRect.top; return NOERROR; } // Set the destination height STDMETHODIMP CBaseControlVideo::put_DestinationHeight(long DestinationHeight) { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); DestinationRect.bottom = DestinationRect.top + DestinationHeight; // Check the target rectangle is valid HRESULT hr = CheckTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } // Now set the new target rectangle hr = SetTargetRect(&DestinationRect); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return the height for the destination rectangle STDMETHODIMP CBaseControlVideo::get_DestinationHeight(__out long *pDestinationHeight) { CheckPointer(pDestinationHeight, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); RECT DestinationRect; GetTargetRect(&DestinationRect); *pDestinationHeight = HEIGHT(&DestinationRect); return NOERROR; } // Reset the source rectangle to the full video dimensions STDMETHODIMP CBaseControlVideo::SetDefaultSourcePosition() { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); HRESULT hr = SetDefaultSourceRect(); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return S_OK if we're using the default source otherwise S_FALSE STDMETHODIMP CBaseControlVideo::IsUsingDefaultSource() { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); return IsDefaultSourceRect(); } // Reset the video renderer to use the entire playback area STDMETHODIMP CBaseControlVideo::SetDefaultDestinationPosition() { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); HRESULT hr = SetDefaultTargetRect(); if (FAILED(hr)) { return hr; } return OnUpdateRectangles(); } // Return S_OK if we're using the default target otherwise S_FALSE STDMETHODIMP CBaseControlVideo::IsUsingDefaultDestination() { CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); return IsDefaultTargetRect(); } // Return a copy of the current image in the video renderer STDMETHODIMP CBaseControlVideo::GetCurrentImage(__inout long *pBufferSize, __out_bcount_part(*pBufferSize, *pBufferSize) long *pVideoImage) { CheckPointer(pBufferSize, E_POINTER); CheckConnected(m_pPin, VFW_E_NOT_CONNECTED); CAutoLock cInterfaceLock(m_pInterfaceLock); FILTER_STATE State; // Make sure we are in a paused state if (pVideoImage != NULL) { m_pFilter->GetState(0, &State); if (State != State_Paused) { return VFW_E_NOT_PAUSED; } return GetStaticImage(pBufferSize, pVideoImage); } // Just return the memory required VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; RECT SourceRect; GetSourceRect(&SourceRect); return GetImageSize(pVideoInfo, pBufferSize, &SourceRect); } // An application has two ways of using GetCurrentImage, one is to pass a real // buffer which should be filled with the current image. The other is to pass // a NULL buffer pointer which is interpreted as asking us to return how much // memory is required for the image. The constraints for when the latter can // be called are much looser. To calculate the memory required we synthesize // a VIDEOINFO that takes into account the source rectangle that's being used HRESULT CBaseControlVideo::GetImageSize(__in VIDEOINFOHEADER *pVideoInfo, __out long *pBufferSize, __in RECT *pSourceRect) { NOTE("Entering GetImageSize"); ASSERT(pSourceRect); // Check we have the correct input parameters if (pSourceRect == NULL || pVideoInfo == NULL || pBufferSize == NULL) { return E_UNEXPECTED; } // Is the data format compatible if (pVideoInfo->bmiHeader.biCompression != BI_RGB) { if (pVideoInfo->bmiHeader.biCompression != BI_BITFIELDS) { return E_INVALIDARG; } } ASSERT(IsRectEmpty(pSourceRect) == FALSE); BITMAPINFOHEADER bih; bih.biWidth = WIDTH(pSourceRect); bih.biHeight = HEIGHT(pSourceRect); bih.biBitCount = pVideoInfo->bmiHeader.biBitCount; LONG Size = DIBSIZE(bih); Size += GetBitmapFormatSize(HEADER(pVideoInfo)) - SIZE_PREHEADER; *pBufferSize = Size; return NOERROR; } // Given an IMediaSample containing a linear buffer with an image and a type // describing the bitmap make a rendering of the image into the output buffer // This may be called by derived classes who render typical video images to // handle the IBasicVideo GetCurrentImage method. The pVideoImage pointer may // be NULL when passed to GetCurrentImage in which case GetImageSize will be // called instead, which will just do the calculation of the memory required HRESULT CBaseControlVideo::CopyImage(IMediaSample *pMediaSample, __in VIDEOINFOHEADER *pVideoInfo, __inout long *pBufferSize, __out_bcount_part(*pBufferSize, *pBufferSize) BYTE *pVideoImage, __in RECT *pSourceRect) { NOTE("Entering CopyImage"); ASSERT(pSourceRect); BYTE *pCurrentImage; // Check we have an image to copy if (pMediaSample == NULL || pSourceRect == NULL || pVideoInfo == NULL || pVideoImage == NULL || pBufferSize == NULL) { return E_UNEXPECTED; } // Is the data format compatible if (pVideoInfo->bmiHeader.biCompression != BI_RGB) { if (pVideoInfo->bmiHeader.biCompression != BI_BITFIELDS) { return E_INVALIDARG; } } if (*pBufferSize < 0) { return E_INVALIDARG; } // Arbitrarily large size to prevent integer overflow problems if (pVideoInfo->bmiHeader.biSize > 4096) { return E_INVALIDARG; } ASSERT(IsRectEmpty(pSourceRect) == FALSE); BITMAPINFOHEADER bih; bih.biWidth = WIDTH(pSourceRect); bih.biHeight = HEIGHT(pSourceRect); bih.biBitCount = pVideoInfo->bmiHeader.biBitCount; DWORD Size = GetBitmapFormatSize(HEADER(pVideoInfo)) - SIZE_PREHEADER; DWORD Total; DWORD dwDibSize; if (!ValidateBitmapInfoHeader(HEADER(pVideoInfo), Size)) { return E_INVALIDARG; } // ValidateBitmapInfoHeader checks this but for some reason code scanning // tools aren't picking up the annotation __analysis_assume(Size >= sizeof(BITMAPINFOHEADER)); if (FAILED(SAFE_DIBSIZE(&bih, &dwDibSize))) { return E_INVALIDARG; } if (FAILED(DWordAdd(Size, dwDibSize, &Total))) { return E_INVALIDARG; } // Make sure we have a large enough buffer if ((DWORD)*pBufferSize < Total) { return E_OUTOFMEMORY; } // Copy the BITMAPINFO CopyMemory((PVOID)pVideoImage, (PVOID)&pVideoInfo->bmiHeader, Size); ((BITMAPINFOHEADER *)pVideoImage)->biWidth = WIDTH(pSourceRect); ((BITMAPINFOHEADER *)pVideoImage)->biHeight = HEIGHT(pSourceRect); ((BITMAPINFOHEADER *)pVideoImage)->biSizeImage = DIBSIZE(bih); BYTE *pImageData = pVideoImage + Size; // Get the pointer to it's image data HRESULT hr = pMediaSample->GetPointer(&pCurrentImage); if (FAILED(hr)) { return hr; } // Now we are ready to start copying the source scan lines LONG ScanLine = (pVideoInfo->bmiHeader.biBitCount / 8) * WIDTH(pSourceRect); LONG LinesToSkip = pVideoInfo->bmiHeader.biHeight; LinesToSkip -= pSourceRect->top + HEIGHT(pSourceRect); pCurrentImage += LinesToSkip * DIBWIDTHBYTES(pVideoInfo->bmiHeader); pCurrentImage += pSourceRect->left * (pVideoInfo->bmiHeader.biBitCount / 8); // Even money on this GP faulting sometime... for (LONG Line = 0; Line < HEIGHT(pSourceRect); Line++) { CopyMemory((PVOID)pImageData, (PVOID)pCurrentImage, ScanLine); pImageData += DIBWIDTHBYTES(*(BITMAPINFOHEADER *)pVideoImage); pCurrentImage += DIBWIDTHBYTES(pVideoInfo->bmiHeader); } return NOERROR; } // Called when we change media types either during connection or dynamically // We inform the filter graph and therefore the application that the video // size may have changed, we don't bother looking to see if it really has as // we leave that to the application - the dimensions are the event parameters HRESULT CBaseControlVideo::OnVideoSizeChange() { // Get the video format from the derived class VIDEOINFOHEADER *pVideoInfo = GetVideoFormat(); if (pVideoInfo == NULL) return E_OUTOFMEMORY; WORD Width = (WORD)pVideoInfo->bmiHeader.biWidth; WORD Height = (WORD)pVideoInfo->bmiHeader.biHeight; return m_pFilter->NotifyEvent(EC_VIDEO_SIZE_CHANGED, MAKELPARAM(Width, Height), MAKEWPARAM(0, 0)); } // Set the video source rectangle. We must check the source rectangle against // the actual video dimensions otherwise when we come to draw the pictures we // get access violations as GDI tries to touch data outside of the image data // Although we store the rectangle in left, top, right and bottom coordinates // instead of left, top, width and height as OLE uses we do take into account // that the rectangle is used up to, but not including, the right column and // bottom row of pixels, see the Win32 documentation on RECT for more details HRESULT CBaseControlVideo::CheckSourceRect(__in RECT *pSourceRect) { CheckPointer(pSourceRect, E_POINTER); LONG Width, Height; GetVideoSize(&Width, &Height); // Check the coordinates are greater than zero // and that the rectangle is valid (leftleft >= pSourceRect->right) || (pSourceRect->left < 0) || (pSourceRect->top >= pSourceRect->bottom) || (pSourceRect->top < 0)) { return E_INVALIDARG; } // Check the coordinates are less than the extents if ((pSourceRect->right > Width) || (pSourceRect->bottom > Height)) { return E_INVALIDARG; } return NOERROR; } // Check the target rectangle has some valid coordinates, which amounts to // little more than checking the destination rectangle isn't empty. Derived // classes may call this when they have their SetTargetRect method called to // check the rectangle validity, we do not update the rectangles passed in // Although we store the rectangle in left, top, right and bottom coordinates // instead of left, top, width and height as OLE uses we do take into account // that the rectangle is used up to, but not including, the right column and // bottom row of pixels, see the Win32 documentation on RECT for more details HRESULT CBaseControlVideo::CheckTargetRect(__in RECT *pTargetRect) { // Check the pointer is valid if (pTargetRect == NULL) { return E_POINTER; } // These overflow the WIDTH and HEIGHT checks if (pTargetRect->left > pTargetRect->right || pTargetRect->top > pTargetRect->bottom) { return E_INVALIDARG; } // Check the rectangle has valid coordinates if (WIDTH(pTargetRect) <= 0 || HEIGHT(pTargetRect) <= 0) { return E_INVALIDARG; } ASSERT(IsRectEmpty(pTargetRect) == FALSE); return NOERROR; } ================================================ FILE: common/baseclasses/winctrl.h ================================================ //------------------------------------------------------------------------------ // File: WinCtrl.h // // Desc: DirectShow base classes - defines classes for video control // interfaces. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __WINCTRL__ #define __WINCTRL__ #define ABSOL(x) (x < 0 ? -x : x) #define NEGAT(x) (x > 0 ? -x : x) // Helper BOOL WINAPI PossiblyEatMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); class CBaseControlWindow : public CBaseVideoWindow , public CBaseWindow { protected: CBaseFilter *m_pFilter; // Pointer to owning media filter CBasePin *m_pPin; // Controls media types for connection CCritSec *m_pInterfaceLock; // Externally defined critical section COLORREF m_BorderColour; // Current window border colour BOOL m_bAutoShow; // What happens when the state changes HWND m_hwndOwner; // Owner window that we optionally have HWND m_hwndDrain; // HWND to post any messages received BOOL m_bCursorHidden; // Should we hide the window cursor public: // Internal methods for other objects to get information out HRESULT DoSetWindowStyle(long Style, long WindowLong); HRESULT DoGetWindowStyle(__out long *pStyle, long WindowLong); BOOL IsAutoShowEnabled() { return m_bAutoShow; }; COLORREF GetBorderColour() { return m_BorderColour; }; HWND GetOwnerWindow() { return m_hwndOwner; }; BOOL IsCursorHidden() { return m_bCursorHidden; }; inline BOOL PossiblyEatMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) { return ::PossiblyEatMessage(m_hwndDrain, uMsg, wParam, lParam); } // Derived classes must call this to set the pin the filter is using // We don't have the pin passed in to the constructor (as we do with // the CBaseFilter object) because filters typically create the // pins dynamically when requested in CBaseFilter::GetPin. This can // not be called from our constructor because is is a virtual method void SetControlWindowPin(CBasePin *pPin) { m_pPin = pPin; } public: CBaseControlWindow(__inout CBaseFilter *pFilter, // Owning media filter __in CCritSec *pInterfaceLock, // Locking object __in_opt LPCTSTR pName, // Object description __inout_opt LPUNKNOWN pUnk, // Normal COM ownership __inout HRESULT *phr); // OLE return code // These are the properties we support STDMETHODIMP put_Caption(__in BSTR strCaption); STDMETHODIMP get_Caption(__out BSTR *pstrCaption); STDMETHODIMP put_AutoShow(long AutoShow); STDMETHODIMP get_AutoShow(__out long *AutoShow); STDMETHODIMP put_WindowStyle(long WindowStyle); STDMETHODIMP get_WindowStyle(__out long *pWindowStyle); STDMETHODIMP put_WindowStyleEx(long WindowStyleEx); STDMETHODIMP get_WindowStyleEx(__out long *pWindowStyleEx); STDMETHODIMP put_WindowState(long WindowState); STDMETHODIMP get_WindowState(__out long *pWindowState); STDMETHODIMP put_BackgroundPalette(long BackgroundPalette); STDMETHODIMP get_BackgroundPalette(__out long *pBackgroundPalette); STDMETHODIMP put_Visible(long Visible); STDMETHODIMP get_Visible(__out long *pVisible); STDMETHODIMP put_Left(long Left); STDMETHODIMP get_Left(__out long *pLeft); STDMETHODIMP put_Width(long Width); STDMETHODIMP get_Width(__out long *pWidth); STDMETHODIMP put_Top(long Top); STDMETHODIMP get_Top(__out long *pTop); STDMETHODIMP put_Height(long Height); STDMETHODIMP get_Height(__out long *pHeight); STDMETHODIMP put_Owner(OAHWND Owner); STDMETHODIMP get_Owner(__out OAHWND *Owner); STDMETHODIMP put_MessageDrain(OAHWND Drain); STDMETHODIMP get_MessageDrain(__out OAHWND *Drain); STDMETHODIMP get_BorderColor(__out long *Color); STDMETHODIMP put_BorderColor(long Color); STDMETHODIMP get_FullScreenMode(__out long *FullScreenMode); STDMETHODIMP put_FullScreenMode(long FullScreenMode); // And these are the methods STDMETHODIMP SetWindowForeground(long Focus); STDMETHODIMP NotifyOwnerMessage(OAHWND hwnd, long uMsg, LONG_PTR wParam, LONG_PTR lParam); STDMETHODIMP GetMinIdealImageSize(__out long *pWidth, __out long *pHeight); STDMETHODIMP GetMaxIdealImageSize(__out long *pWidth, __out long *pHeight); STDMETHODIMP SetWindowPosition(long Left, long Top, long Width, long Height); STDMETHODIMP GetWindowPosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight); STDMETHODIMP GetRestorePosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight); STDMETHODIMP HideCursor(long HideCursor); STDMETHODIMP IsCursorHidden(__out long *CursorHidden); }; // This class implements the IBasicVideo interface class CBaseControlVideo : public CBaseBasicVideo { protected: CBaseFilter *m_pFilter; // Pointer to owning media filter CBasePin *m_pPin; // Controls media types for connection CCritSec *m_pInterfaceLock; // Externally defined critical section public: // Derived classes must provide these for the implementation virtual HRESULT IsDefaultTargetRect() PURE; virtual HRESULT SetDefaultTargetRect() PURE; virtual HRESULT SetTargetRect(RECT *pTargetRect) PURE; virtual HRESULT GetTargetRect(RECT *pTargetRect) PURE; virtual HRESULT IsDefaultSourceRect() PURE; virtual HRESULT SetDefaultSourceRect() PURE; virtual HRESULT SetSourceRect(RECT *pSourceRect) PURE; virtual HRESULT GetSourceRect(RECT *pSourceRect) PURE; virtual HRESULT GetStaticImage(__inout long *pBufferSize, __out_bcount_part(*pBufferSize, *pBufferSize) long *pDIBImage) PURE; // Derived classes must override this to return a VIDEOINFO representing // the video format. We cannot call IPin ConnectionMediaType to get this // format because various filters dynamically change the type when using // DirectDraw such that the format shows the position of the logical // bitmap in a frame buffer surface, so the size might be returned as // 1024x768 pixels instead of 320x240 which is the real video dimensions __out virtual VIDEOINFOHEADER *GetVideoFormat() PURE; // Helper functions for creating memory renderings of a DIB image HRESULT GetImageSize(__in VIDEOINFOHEADER *pVideoInfo, __out LONG *pBufferSize, __in RECT *pSourceRect); HRESULT CopyImage(IMediaSample *pMediaSample, __in VIDEOINFOHEADER *pVideoInfo, __inout LONG *pBufferSize, __out_bcount_part(*pBufferSize, *pBufferSize) BYTE *pVideoImage, __in RECT *pSourceRect); // Override this if you want notifying when the rectangles change virtual HRESULT OnUpdateRectangles() { return NOERROR; }; virtual HRESULT OnVideoSizeChange(); // Derived classes must call this to set the pin the filter is using // We don't have the pin passed in to the constructor (as we do with // the CBaseFilter object) because filters typically create the // pins dynamically when requested in CBaseFilter::GetPin. This can // not be called from our constructor because is is a virtual method void SetControlVideoPin(__inout CBasePin *pPin) { m_pPin = pPin; } // Helper methods for checking rectangles virtual HRESULT CheckSourceRect(__in RECT *pSourceRect); virtual HRESULT CheckTargetRect(__in RECT *pTargetRect); public: CBaseControlVideo(__inout CBaseFilter *pFilter, // Owning media filter __in CCritSec *pInterfaceLock, // Serialise interface __in_opt LPCTSTR pName, // Object description __inout_opt LPUNKNOWN pUnk, // Normal COM ownership __inout HRESULT *phr); // OLE return code // These are the properties we support STDMETHODIMP get_AvgTimePerFrame(__out REFTIME *pAvgTimePerFrame); STDMETHODIMP get_BitRate(__out long *pBitRate); STDMETHODIMP get_BitErrorRate(__out long *pBitErrorRate); STDMETHODIMP get_VideoWidth(__out long *pVideoWidth); STDMETHODIMP get_VideoHeight(__out long *pVideoHeight); STDMETHODIMP put_SourceLeft(long SourceLeft); STDMETHODIMP get_SourceLeft(__out long *pSourceLeft); STDMETHODIMP put_SourceWidth(long SourceWidth); STDMETHODIMP get_SourceWidth(__out long *pSourceWidth); STDMETHODIMP put_SourceTop(long SourceTop); STDMETHODIMP get_SourceTop(__out long *pSourceTop); STDMETHODIMP put_SourceHeight(long SourceHeight); STDMETHODIMP get_SourceHeight(__out long *pSourceHeight); STDMETHODIMP put_DestinationLeft(long DestinationLeft); STDMETHODIMP get_DestinationLeft(__out long *pDestinationLeft); STDMETHODIMP put_DestinationWidth(long DestinationWidth); STDMETHODIMP get_DestinationWidth(__out long *pDestinationWidth); STDMETHODIMP put_DestinationTop(long DestinationTop); STDMETHODIMP get_DestinationTop(__out long *pDestinationTop); STDMETHODIMP put_DestinationHeight(long DestinationHeight); STDMETHODIMP get_DestinationHeight(__out long *pDestinationHeight); // And these are the methods STDMETHODIMP GetVideoSize(__out long *pWidth, __out long *pHeight); STDMETHODIMP SetSourcePosition(long Left, long Top, long Width, long Height); STDMETHODIMP GetSourcePosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight); STDMETHODIMP GetVideoPaletteEntries(long StartIndex, long Entries, __out long *pRetrieved, __out_ecount_part(Entries, *pRetrieved) long *pPalette); STDMETHODIMP SetDefaultSourcePosition(); STDMETHODIMP IsUsingDefaultSource(); STDMETHODIMP SetDestinationPosition(long Left, long Top, long Width, long Height); STDMETHODIMP GetDestinationPosition(__out long *pLeft, __out long *pTop, __out long *pWidth, __out long *pHeight); STDMETHODIMP SetDefaultDestinationPosition(); STDMETHODIMP IsUsingDefaultDestination(); STDMETHODIMP GetCurrentImage(__inout long *pBufferSize, __out_bcount_part(*pBufferSize, *pBufferSize) long *pVideoImage); }; #endif // __WINCTRL__ ================================================ FILE: common/baseclasses/winutil.cpp ================================================ //------------------------------------------------------------------------------ // File: WinUtil.cpp // // Desc: DirectShow base classes - implements generic window handler class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #include #include #include #include static UINT MsgDestroy; // Constructor CBaseWindow::CBaseWindow(BOOL bDoGetDC, bool bDoPostToDestroy) : m_hInstance(g_hInst) , m_hwnd(NULL) , m_hdc(NULL) , m_bActivated(FALSE) , m_pClassName(NULL) , m_ClassStyles(0) , m_WindowStyles(0) , m_WindowStylesEx(0) , m_ShowStageMessage(0) , m_ShowStageTop(0) , m_MemoryDC(NULL) , m_hPalette(NULL) , m_bBackground(FALSE) , #ifdef DEBUG m_bRealizing(FALSE) , #endif m_bNoRealize(FALSE) , m_bDoPostToDestroy(bDoPostToDestroy) { m_bDoGetDC = bDoGetDC; } // Prepare a window by spinning off a worker thread to do the creation and // also poll the message input queue. We leave this to be called by derived // classes because they might want to override methods like MessageLoop and // InitialiseWindow, if we do this during construction they'll ALWAYS call // this base class methods. We make the worker thread create the window so // it owns it rather than the filter graph thread which is constructing us HRESULT CBaseWindow::PrepareWindow() { if (m_hwnd) return NOERROR; ASSERT(m_hwnd == NULL); ASSERT(m_hdc == NULL); // Get the derived object's window and class styles m_pClassName = GetClassWindowStyles(&m_ClassStyles, &m_WindowStyles, &m_WindowStylesEx); if (m_pClassName == NULL) { return E_FAIL; } // Register our special private messages m_ShowStageMessage = RegisterWindowMessage(SHOWSTAGE); // RegisterWindowMessage() returns 0 if an error occurs. if (0 == m_ShowStageMessage) { return AmGetLastErrorToHResult(); } m_ShowStageTop = RegisterWindowMessage(SHOWSTAGETOP); if (0 == m_ShowStageTop) { return AmGetLastErrorToHResult(); } m_RealizePalette = RegisterWindowMessage(REALIZEPALETTE); if (0 == m_RealizePalette) { return AmGetLastErrorToHResult(); } MsgDestroy = RegisterWindowMessage(TEXT("AM_DESTROY")); if (0 == MsgDestroy) { return AmGetLastErrorToHResult(); } return DoCreateWindow(); } // Destructor just a placeholder so that we know it becomes virtual // Derived classes MUST call DoneWithWindow in their destructors so // that no messages arrive after the derived class constructor ends #ifdef DEBUG CBaseWindow::~CBaseWindow() { ASSERT(m_hwnd == NULL); ASSERT(m_hdc == NULL); } #endif // We use the sync worker event to have the window destroyed. All we do is // signal the event and wait on the window thread handle. Trying to send it // messages causes too many problems, furthermore to be on the safe side we // just wait on the thread handle while it returns WAIT_TIMEOUT or there is // a sent message to process on this thread. If the constructor failed to // create the thread in the first place then the loop will get terminated HRESULT CBaseWindow::DoneWithWindow() { if (!IsWindow(m_hwnd) || (GetWindowThreadProcessId(m_hwnd, NULL) != GetCurrentThreadId())) { if (IsWindow(m_hwnd)) { // This code should only be executed if the window exists and if the window's // messages are processed on a different thread. ASSERT(GetWindowThreadProcessId(m_hwnd, NULL) != GetCurrentThreadId()); if (m_bDoPostToDestroy) { HRESULT hr = S_OK; CAMEvent m_evDone(FALSE, &hr); if (FAILED(hr)) { return hr; } // We must post a message to destroy the window // That way we can't be in the middle of processing a // message posted to our window when we do go away // Sending a message gives less synchronization. PostMessage(m_hwnd, MsgDestroy, (WPARAM)(HANDLE)m_evDone, 0); WaitDispatchingMessages(m_evDone, INFINITE); } else { SendMessage(m_hwnd, MsgDestroy, 0, 0); } } // // This is not a leak, the window manager automatically free's // hdc's that were got via GetDC, which is the case here. // We set it to NULL so that we don't get any asserts later. // m_hdc = NULL; // // We need to free this DC though because USER32 does not know // anything about it. // if (m_MemoryDC) { EXECUTE_ASSERT(DeleteDC(m_MemoryDC)); m_MemoryDC = NULL; } // Reset the window variables m_hwnd = NULL; return NOERROR; } const HWND hwnd = m_hwnd; if (hwnd == NULL) { return NOERROR; } InactivateWindow(); NOTE("Inactivated"); // Reset the window styles before destruction SetWindowLong(hwnd, GWL_STYLE, m_WindowStyles); ASSERT(GetParent(hwnd) == NULL); NOTE1("Reset window styles %d", m_WindowStyles); // UnintialiseWindow sets m_hwnd to NULL so save a copy UninitialiseWindow(); DbgLog((LOG_TRACE, 2, TEXT("Destroying 0x%8.8X"), hwnd)); if (!DestroyWindow(hwnd)) { DbgLog((LOG_TRACE, 0, TEXT("DestroyWindow %8.8X failed code %d"), hwnd, GetLastError())); DbgBreak(""); } // Reset our state so we can be prepared again m_pClassName = NULL; m_ClassStyles = 0; m_WindowStyles = 0; m_WindowStylesEx = 0; m_ShowStageMessage = 0; m_ShowStageTop = 0; return NOERROR; } // Called at the end to put the window in an inactive state. The pending list // will always have been cleared by this time so event if the worker thread // gets has been signaled and gets in to render something it will find both // the state has been changed and that there are no available sample images // Since we wait on the window thread to complete we don't lock the object HRESULT CBaseWindow::InactivateWindow() { // Has the window been activated if (m_bActivated == FALSE) { return S_FALSE; } m_bActivated = FALSE; ShowWindow(m_hwnd, SW_HIDE); return NOERROR; } HRESULT CBaseWindow::CompleteConnect() { m_bActivated = FALSE; return NOERROR; } // This displays a normal window. We ask the base window class for default // sizes which unless overriden will return DEFWIDTH and DEFHEIGHT. We go // through a couple of extra hoops to get the client area the right size // as the object specifies which accounts for the AdjustWindowRectEx calls // We also DWORD align the left and top coordinates of the window here to // maximise the chance of being able to use DCI/DirectDraw primary surface HRESULT CBaseWindow::ActivateWindow() { // Has the window been sized and positioned already if (m_bActivated == TRUE || GetParent(m_hwnd) != NULL) { SetWindowPos(m_hwnd, // Our window handle HWND_TOP, // Put it at the top 0, 0, 0, 0, // Leave in current position SWP_NOMOVE | // Don't change it's place SWP_NOSIZE); // Change Z-order only m_bActivated = TRUE; return S_FALSE; } // Calculate the desired client rectangle RECT WindowRect, ClientRect = GetDefaultRect(); GetWindowRect(m_hwnd, &WindowRect); AdjustWindowRectEx(&ClientRect, GetWindowLong(m_hwnd, GWL_STYLE), FALSE, GetWindowLong(m_hwnd, GWL_EXSTYLE)); // Align left and top edges on DWORD boundaries UINT WindowFlags = (SWP_NOACTIVATE | SWP_FRAMECHANGED); WindowRect.left -= (WindowRect.left & 3); WindowRect.top -= (WindowRect.top & 3); SetWindowPos(m_hwnd, // Window handle HWND_TOP, // Put it at the top WindowRect.left, // Align left edge WindowRect.top, // And also top place WIDTH(&ClientRect), // Horizontal size HEIGHT(&ClientRect), // Vertical size WindowFlags); // Don't show window m_bActivated = TRUE; return NOERROR; } // This can be used to DWORD align the window for maximum performance HRESULT CBaseWindow::PerformanceAlignWindow() { RECT ClientRect, WindowRect; GetWindowRect(m_hwnd, &WindowRect); ASSERT(m_bActivated == TRUE); // Don't do this if we're owned if (GetParent(m_hwnd)) { return NOERROR; } // Align left and top edges on DWORD boundaries GetClientRect(m_hwnd, &ClientRect); MapWindowPoints(m_hwnd, HWND_DESKTOP, (LPPOINT)&ClientRect, 2); WindowRect.left -= (ClientRect.left & 3); WindowRect.top -= (ClientRect.top & 3); UINT WindowFlags = (SWP_NOACTIVATE | SWP_NOSIZE); SetWindowPos(m_hwnd, // Window handle HWND_TOP, // Put it at the top WindowRect.left, // Align left edge WindowRect.top, // And also top place (int)0, (int)0, // Ignore these sizes WindowFlags); // Don't show window return NOERROR; } // Install a palette into the base window - we may be called by a different // thread to the one that owns the window. We have to be careful how we do // the palette realisation as we could be a different thread to the window // which would cause an inter thread send message. Therefore we realise the // palette by sending it a special message but without the window locked HRESULT CBaseWindow::SetPalette(HPALETTE hPalette) { // We must own the window lock during the change { CAutoLock cWindowLock(&m_WindowLock); CAutoLock cPaletteLock(&m_PaletteLock); ASSERT(hPalette); m_hPalette = hPalette; } return SetPalette(); } HRESULT CBaseWindow::SetPalette() { if (!m_bNoRealize) { SendMessage(m_hwnd, m_RealizePalette, 0, 0); return S_OK; } else { // Just select the palette ASSERT(m_hdc); ASSERT(m_MemoryDC); CAutoLock cPaletteLock(&m_PaletteLock); SelectPalette(m_hdc, m_hPalette, m_bBackground); SelectPalette(m_MemoryDC, m_hPalette, m_bBackground); return S_OK; } } void CBaseWindow::UnsetPalette() { CAutoLock cWindowLock(&m_WindowLock); CAutoLock cPaletteLock(&m_PaletteLock); // Get a standard VGA colour palette HPALETTE hPalette = (HPALETTE)GetStockObject(DEFAULT_PALETTE); ASSERT(hPalette); SelectPalette(GetWindowHDC(), hPalette, TRUE); SelectPalette(GetMemoryHDC(), hPalette, TRUE); m_hPalette = NULL; } void CBaseWindow::LockPaletteLock() { m_PaletteLock.Lock(); } void CBaseWindow::UnlockPaletteLock() { m_PaletteLock.Unlock(); } // Realise our palettes in the window and device contexts HRESULT CBaseWindow::DoRealisePalette(BOOL bForceBackground) { { CAutoLock cPaletteLock(&m_PaletteLock); if (m_hPalette == NULL) { return NOERROR; } // Realize the palette on the window thread ASSERT(m_hdc); ASSERT(m_MemoryDC); SelectPalette(m_hdc, m_hPalette, m_bBackground || bForceBackground); SelectPalette(m_MemoryDC, m_hPalette, m_bBackground); } // If we grab a critical section here we can deadlock // with the window thread because one of the side effects // of RealizePalette is to send a WM_PALETTECHANGED message // to every window in the system. In our handling // of WM_PALETTECHANGED we used to grab this CS too. // The really bad case is when our renderer calls DoRealisePalette() // while we're in the middle of processing a palette change // for another window. // So don't hold the critical section while actually realising // the palette. In any case USER is meant to manage palette // handling - we shouldn't have to serialize everything as well ASSERT(CritCheckOut(&m_WindowLock)); ASSERT(CritCheckOut(&m_PaletteLock)); EXECUTE_ASSERT(RealizePalette(m_hdc) != GDI_ERROR); EXECUTE_ASSERT(RealizePalette(m_MemoryDC) != GDI_ERROR); return (GdiFlush() == FALSE ? S_FALSE : S_OK); } // This is the global window procedure LRESULT CALLBACK WndProc(HWND hwnd, // Window handle UINT uMsg, // Message ID WPARAM wParam, // First parameter LPARAM lParam) // Other parameter { // Get the window long that holds our window object pointer // If it is NULL then we are initialising the window in which // case the object pointer has been passed in the window creation // structure. IF we get any messages before WM_NCCREATE we will // pass them to DefWindowProc. CBaseWindow *pBaseWindow = _GetWindowLongPtr(hwnd, 0); if (pBaseWindow == NULL) { // Get the structure pointer from the create struct. // We can only do this for WM_NCCREATE which should be one of // the first messages we receive. Anything before this will // have to be passed to DefWindowProc (i.e. WM_GETMINMAXINFO) // If the message is WM_NCCREATE we set our pBaseWindow pointer // and will then place it in the window structure // turn off WS_EX_LAYOUTRTL style for quartz windows if (uMsg == WM_NCCREATE) { SetWindowLong(hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) & ~0x400000); } if ((uMsg != WM_NCCREATE) || (NULL == (pBaseWindow = *(CBaseWindow **)((LPCREATESTRUCT)lParam)->lpCreateParams))) { return (DefWindowProc(hwnd, uMsg, wParam, lParam)); } // Set the window LONG to be the object who created us #ifdef DEBUG SetLastError(0); // because of the way SetWindowLong works #endif LONG_PTR rc = _SetWindowLongPtr(hwnd, (DWORD)0, pBaseWindow); #ifdef DEBUG if (0 == rc) { // SetWindowLong MIGHT have failed. (Read the docs which admit // that it is awkward to work out if you have had an error.) LONG lasterror = GetLastError(); ASSERT(0 == lasterror); // If this is not the case we have not set the pBaseWindow pointer // into the window structure and we will blow up. } #endif } // See if this is the packet of death if (uMsg == MsgDestroy && uMsg != 0) { pBaseWindow->DoneWithWindow(); if (pBaseWindow->m_bDoPostToDestroy) { EXECUTE_ASSERT(SetEvent((HANDLE)wParam)); } return 0; } return pBaseWindow->OnReceiveMessage(hwnd, uMsg, wParam, lParam); } // When the window size changes we adjust our member variables that // contain the dimensions of the client rectangle for our window so // that we come to render an image we will know whether to stretch BOOL CBaseWindow::OnSize(LONG Width, LONG Height) { m_Width = Width; m_Height = Height; return TRUE; } // This function handles the WM_CLOSE message BOOL CBaseWindow::OnClose() { ShowWindow(m_hwnd, SW_HIDE); return TRUE; } // This is called by the worker window thread when it receives a terminate // message from the window object destructor to delete all the resources we // allocated during initialisation. By the time the worker thread exits all // processing will have been completed as the source filter disconnection // flushes the image pending sample, therefore the GdiFlush should succeed HRESULT CBaseWindow::UninitialiseWindow() { // Have we already cleaned up if (m_hwnd == NULL) { ASSERT(m_hdc == NULL); ASSERT(m_MemoryDC == NULL); return NOERROR; } // Release the window resources EXECUTE_ASSERT(GdiFlush()); if (m_hdc) { EXECUTE_ASSERT(ReleaseDC(m_hwnd, m_hdc)); m_hdc = NULL; } if (m_MemoryDC) { EXECUTE_ASSERT(DeleteDC(m_MemoryDC)); m_MemoryDC = NULL; } // Reset the window variables m_hwnd = NULL; return NOERROR; } // This is called by the worker window thread after it has created the main // window and it wants to initialise the rest of the owner objects window // variables such as the device contexts. We execute this function with the // critical section still locked. Nothing in this function must generate any // SendMessage calls to the window because this is executing on the window // thread so the message will never be processed and we will deadlock HRESULT CBaseWindow::InitialiseWindow(HWND hwnd) { // Initialise the window variables ASSERT(IsWindow(hwnd)); m_hwnd = hwnd; if (m_bDoGetDC) { EXECUTE_ASSERT(m_hdc = GetDC(hwnd)); EXECUTE_ASSERT(m_MemoryDC = CreateCompatibleDC(m_hdc)); EXECUTE_ASSERT(SetStretchBltMode(m_hdc, COLORONCOLOR)); EXECUTE_ASSERT(SetStretchBltMode(m_MemoryDC, COLORONCOLOR)); } return NOERROR; } HRESULT CBaseWindow::DoCreateWindow() { WNDCLASS wndclass; // Used to register classes BOOL bRegistered; // Is this class registered HWND hwnd; // Handle to our window bRegistered = GetClassInfo(m_hInstance, // Module instance m_pClassName, // Window class &wndclass); // Info structure // if the window is to be used for drawing puposes and we are getting a DC // for the entire lifetime of the window then changes the class style to do // say so. If we don't set this flag then the DC comes from the cache and is // really bad. if (m_bDoGetDC) { m_ClassStyles |= CS_OWNDC; } if (bRegistered == FALSE) { // Register the renderer window class wndclass.lpszClassName = m_pClassName; wndclass.style = m_ClassStyles; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = sizeof(CBaseWindow *); wndclass.hInstance = m_hInstance; wndclass.hIcon = NULL; wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)NULL; wndclass.lpszMenuName = NULL; RegisterClass(&wndclass); } // Create the frame window. Pass the pBaseWindow information in the // CreateStruct which allows our message handling loop to get hold of // the pBaseWindow pointer. CBaseWindow *pBaseWindow = this; // The owner window object hwnd = CreateWindowEx(m_WindowStylesEx, // Extended styles m_pClassName, // Registered name TEXT("ActiveMovie Window"), // Window title m_WindowStyles, // Window styles CW_USEDEFAULT, // Start x position CW_USEDEFAULT, // Start y position DEFWIDTH, // Window width DEFHEIGHT, // Window height NULL, // Parent handle NULL, // Menu handle m_hInstance, // Instance handle &pBaseWindow); // Creation data // If we failed signal an error to the object constructor (based on the // last Win32 error on this thread) then signal the constructor thread // to continue, release the mutex to let others have a go and exit if (hwnd == NULL) { DWORD Error = GetLastError(); return AmHresultFromWin32(Error); } // Check the window LONG is the object who created us ASSERT(GetWindowLongPtr(hwnd, 0) == (LONG_PTR)this); // Initialise the window and then signal the constructor so that it can // continue and then finally unlock the object's critical section. The // window class is left registered even after we terminate the thread // as we don't know when the last window has been closed. So we allow // the operating system to free the class resources as appropriate InitialiseWindow(hwnd); DbgLog((LOG_TRACE, 2, TEXT("Created window class (%s) HWND(%8.8X)"), m_pClassName, hwnd)); return S_OK; } // The base class provides some default handling and calls DefWindowProc LRESULT CBaseWindow::OnReceiveMessage(HWND hwnd, // Window handle UINT uMsg, // Message ID WPARAM wParam, // First parameter LPARAM lParam) // Other parameter { ASSERT(IsWindow(hwnd)); if (PossiblyEatMessage(uMsg, wParam, lParam)) return 0; // This is sent by the IVideoWindow SetWindowForeground method. If the // window is invisible we will show it and make it topmost without the // foreground focus. If the window is visible it will also be made the // topmost window without the foreground focus. If wParam is TRUE then // for both cases the window will be forced into the foreground focus if (uMsg == m_ShowStageMessage) { BOOL bVisible = IsWindowVisible(hwnd); SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | (bVisible ? SWP_NOACTIVATE : 0)); // Should we bring the window to the foreground if (wParam == TRUE) { SetForegroundWindow(hwnd); } return (LRESULT)1; } // When we go fullscreen we have to add the WS_EX_TOPMOST style to the // video window so that it comes out above any task bar (this is more // relevant to WindowsNT than Windows95). However the SetWindowPos call // must be on the same thread as that which created the window. The // wParam parameter can be TRUE or FALSE to set and reset the topmost if (uMsg == m_ShowStageTop) { HWND HwndTop = (wParam == TRUE ? HWND_TOPMOST : HWND_NOTOPMOST); BOOL bVisible = IsWindowVisible(hwnd); SetWindowPos(hwnd, HwndTop, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | (wParam == TRUE ? SWP_SHOWWINDOW : 0) | (bVisible ? SWP_NOACTIVATE : 0)); return (LRESULT)1; } // New palette stuff if (uMsg == m_RealizePalette) { ASSERT(m_hwnd == hwnd); return OnPaletteChange(m_hwnd, WM_QUERYNEWPALETTE); } switch (uMsg) { // Repaint the window if the system colours change case WM_SYSCOLORCHANGE: InvalidateRect(hwnd, NULL, FALSE); return (LRESULT)1; // Somebody has changed the palette case WM_PALETTECHANGED: OnPaletteChange((HWND)wParam, uMsg); return (LRESULT)0; // We are about to receive the keyboard focus so we ask GDI to realise // our logical palette again and hopefully it will be fully installed // without any mapping having to be done during any picture rendering case WM_QUERYNEWPALETTE: ASSERT(m_hwnd == hwnd); return OnPaletteChange(m_hwnd, uMsg); // do NOT fwd WM_MOVE. the parameters are the location of the parent // window, NOT what the renderer should be looking at. But we need // to make sure the overlay is moved with the parent window, so we // do this. case WM_MOVE: if (IsWindowVisible(m_hwnd)) { PostMessage(m_hwnd, WM_PAINT, 0, 0); } break; // Store the width and height as useful base class members case WM_SIZE: OnSize(LOWORD(lParam), HIWORD(lParam)); return (LRESULT)0; // Intercept the WM_CLOSE messages to hide the window case WM_CLOSE: OnClose(); return (LRESULT)0; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } // This handles the Windows palette change messages - if we do realise our // palette then we return TRUE otherwise we return FALSE. If our window is // foreground application then we should get first choice of colours in the // system palette entries. We get best performance when our logical palette // includes the standard VGA colours (at the beginning and end) otherwise // GDI may have to map from our palette to the device palette while drawing LRESULT CBaseWindow::OnPaletteChange(HWND hwnd, UINT Message) { // First check we are not changing the palette during closedown if (m_hwnd == NULL || hwnd == NULL) { return (LRESULT)0; } ASSERT(!m_bRealizing); // Should we realise our palette again if ((Message == WM_QUERYNEWPALETTE || hwnd != m_hwnd)) { // It seems that even if we're invisible that we can get asked // to realize our palette and this can cause really ugly side-effects // Seems like there's another bug but this masks it a least for the // shutting down case. if (!IsWindowVisible(m_hwnd)) { DbgLog((LOG_TRACE, 1, TEXT("Realizing when invisible!"))); return (LRESULT)0; } // Avoid recursion with multiple graphs in the same app #ifdef DEBUG m_bRealizing = TRUE; #endif DoRealisePalette(Message != WM_QUERYNEWPALETTE); #ifdef DEBUG m_bRealizing = FALSE; #endif // Should we redraw the window with the new palette if (Message == WM_PALETTECHANGED) { InvalidateRect(m_hwnd, NULL, FALSE); } } return (LRESULT)1; } // Determine if the window exists. bool CBaseWindow::WindowExists() { return !!IsWindow(m_hwnd); } // Return the default window rectangle RECT CBaseWindow::GetDefaultRect() { RECT DefaultRect = {0, 0, DEFWIDTH, DEFHEIGHT}; ASSERT(m_hwnd); // ASSERT(m_hdc); return DefaultRect; } // Return the current window width LONG CBaseWindow::GetWindowWidth() { ASSERT(m_hwnd); // ASSERT(m_hdc); return m_Width; } // Return the current window height LONG CBaseWindow::GetWindowHeight() { ASSERT(m_hwnd); // ASSERT(m_hdc); return m_Height; } // Return the window handle HWND CBaseWindow::GetWindowHWND() { ASSERT(m_hwnd); // ASSERT(m_hdc); return m_hwnd; } // Return the window drawing device context HDC CBaseWindow::GetWindowHDC() { ASSERT(m_hwnd); ASSERT(m_hdc); return m_hdc; } // Return the offscreen window drawing device context HDC CBaseWindow::GetMemoryHDC() { ASSERT(m_hwnd); ASSERT(m_MemoryDC); return m_MemoryDC; } #ifdef DEBUG HPALETTE CBaseWindow::GetPalette() { // The palette lock should always be held when accessing // m_hPalette. ASSERT(CritCheckIn(&m_PaletteLock)); return m_hPalette; } #endif // DEBUG // This is available to clients who want to change the window visiblity. It's // little more than an indirection to the Win32 ShowWindow although these is // some benefit in going through here as this function may change sometime HRESULT CBaseWindow::DoShowWindow(LONG ShowCmd) { ShowWindow(m_hwnd, ShowCmd); return NOERROR; } // Generate a WM_PAINT message for the video window void CBaseWindow::PaintWindow(BOOL bErase) { InvalidateRect(m_hwnd, NULL, bErase); } // Allow an application to have us set the video window in the foreground. We // have this because it is difficult for one thread to do do this to a window // owned by another thread. Rather than expose the message we use to execute // the inter thread send message we provide the interface function. All we do // is to SendMessage to the video window renderer thread with a WM_SHOWSTAGE void CBaseWindow::DoSetWindowForeground(BOOL bFocus) { SendMessage(m_hwnd, m_ShowStageMessage, (WPARAM)bFocus, (LPARAM)0); } // Constructor initialises the owning object pointer. Since we are a worker // class for the main window object we have relatively few state variables to // look after. We are given device context handles to use later on as well as // the source and destination rectangles (but reset them here just in case) CDrawImage::CDrawImage(__inout CBaseWindow *pBaseWindow) : m_pBaseWindow(pBaseWindow) , m_hdc(NULL) , m_MemoryDC(NULL) , m_bStretch(FALSE) , m_pMediaType(NULL) , m_bUsingImageAllocator(FALSE) { ASSERT(pBaseWindow); ResetPaletteVersion(); SetRectEmpty(&m_TargetRect); SetRectEmpty(&m_SourceRect); m_perfidRenderTime = MSR_REGISTER(TEXT("Single Blt time")); } // Overlay the image time stamps on the picture. Access to this method is // serialised by the caller. We display the sample start and end times on // top of the video using TextOut on the device context we are handed. If // there isn't enough room in the window for the times we don't show them void CDrawImage::DisplaySampleTimes(IMediaSample *pSample) { #ifdef DEBUG // // Only allow the "annoying" time messages if the users has turned the // logging "way up" // BOOL bAccept = DbgCheckModuleLevel(LOG_TRACE, 5); if (bAccept == FALSE) { return; } #endif TCHAR szTimes[TIMELENGTH]; // Time stamp strings ASSERT(pSample); // Quick sanity check RECT ClientRect; // Client window size SIZE Size; // Size of text output // Get the time stamps and window size pSample->GetTime((REFERENCE_TIME *)&m_StartSample, (REFERENCE_TIME *)&m_EndSample); HWND hwnd = m_pBaseWindow->GetWindowHWND(); EXECUTE_ASSERT(GetClientRect(hwnd, &ClientRect)); // Format the sample time stamps (void)StringCchPrintf(szTimes, NUMELMS(szTimes), TEXT("%08d : %08d"), m_StartSample.Millisecs(), m_EndSample.Millisecs()); ASSERT(lstrlen(szTimes) < TIMELENGTH); // Put the times in the middle at the bottom of the window GetTextExtentPoint32(m_hdc, szTimes, lstrlen(szTimes), &Size); INT XPos = ((ClientRect.right - ClientRect.left) - Size.cx) / 2; INT YPos = ((ClientRect.bottom - ClientRect.top) - Size.cy) * 4 / 5; // Check the window is big enough to have sample times displayed if ((XPos > 0) && (YPos > 0)) { TextOut(m_hdc, XPos, YPos, szTimes, lstrlen(szTimes)); } } // This is called when the drawing code sees that the image has a down level // palette cookie. We simply call the SetDIBColorTable Windows API with the // palette that is found after the BITMAPINFOHEADER - we return no errors void CDrawImage::UpdateColourTable(HDC hdc, __in BITMAPINFOHEADER *pbmi) { ASSERT(pbmi->biClrUsed); RGBQUAD *pColourTable = (RGBQUAD *)(pbmi + 1); // Set the new palette in the device context UINT uiReturn = SetDIBColorTable(hdc, (UINT)0, pbmi->biClrUsed, pColourTable); // Should always succeed but check in debug builds ASSERT(uiReturn == pbmi->biClrUsed); } // No source rectangle scaling is done by the base class RECT CDrawImage::ScaleSourceRect(const RECT *pSource) { ASSERT(pSource); return *pSource; } // This is called when the funky output pin uses our allocator. The samples we // allocate are special because the memory is shared between us and GDI thus // removing one copy when we ask for the image to be rendered. The source type // information is in the main renderer m_mtIn field which is initialised when // the media type is agreed in SetMediaType, the media type may be changed on // the fly if, for example, the source filter needs to change the palette void CDrawImage::FastRender(IMediaSample *pMediaSample) { BITMAPINFOHEADER *pbmi; // Image format data DIBDATA *pDibData; // Stores DIB information BYTE *pImage; // Pointer to image data HBITMAP hOldBitmap; // Store the old bitmap CImageSample *pSample; // Pointer to C++ object ASSERT(m_pMediaType); // From the untyped source format block get the VIDEOINFO and subsequently // the BITMAPINFOHEADER structure. We can cast the IMediaSample interface // to a CImageSample object so we can retrieve it's DIBSECTION details pbmi = HEADER(m_pMediaType->Format()); pSample = (CImageSample *)pMediaSample; pDibData = pSample->GetDIBData(); hOldBitmap = (HBITMAP)SelectObject(m_MemoryDC, pDibData->hBitmap); // Get a pointer to the real image data HRESULT hr = pMediaSample->GetPointer(&pImage); if (FAILED(hr)) { return; } // Do we need to update the colour table, we increment our palette cookie // each time we get a dynamic format change. The sample palette cookie is // stored in the DIBDATA structure so we try to keep the fields in sync // By the time we get to draw the images the format change will be done // so all we do is ask the renderer for what it's palette version is if (pDibData->PaletteVersion < GetPaletteVersion()) { ASSERT(pbmi->biBitCount <= iPALETTE); UpdateColourTable(m_MemoryDC, pbmi); pDibData->PaletteVersion = GetPaletteVersion(); } // This allows derived classes to change the source rectangle that we do // the drawing with. For example a renderer may ask a codec to stretch // the video from 320x240 to 640x480, in which case the source we see in // here will still be 320x240, although the source we want to draw with // should be scaled up to 640x480. The base class implementation of this // method does nothing but return the same rectangle as we are passed in RECT SourceRect = ScaleSourceRect(&m_SourceRect); // Is the window the same size as the video if (m_bStretch == FALSE) { // Put the image straight into the window BitBlt((HDC)m_hdc, // Target device HDC m_TargetRect.left, // X sink position m_TargetRect.top, // Y sink position m_TargetRect.right - m_TargetRect.left, // Destination width m_TargetRect.bottom - m_TargetRect.top, // Destination height m_MemoryDC, // Source device context SourceRect.left, // X source position SourceRect.top, // Y source position SRCCOPY); // Simple copy } else { // Stretch the image when copying to the window StretchBlt((HDC)m_hdc, // Target device HDC m_TargetRect.left, // X sink position m_TargetRect.top, // Y sink position m_TargetRect.right - m_TargetRect.left, // Destination width m_TargetRect.bottom - m_TargetRect.top, // Destination height m_MemoryDC, // Source device HDC SourceRect.left, // X source position SourceRect.top, // Y source position SourceRect.right - SourceRect.left, // Source width SourceRect.bottom - SourceRect.top, // Source height SRCCOPY); // Simple copy } // This displays the sample times over the top of the image. This used to // draw the times into the offscreen device context however that actually // writes the text into the image data buffer which may not be writable #ifdef DEBUG DisplaySampleTimes(pMediaSample); #endif // Put the old bitmap back into the device context so we don't leak SelectObject(m_MemoryDC, hOldBitmap); } // This is called when there is a sample ready to be drawn, unfortunately the // output pin was being rotten and didn't choose our super excellent shared // memory DIB allocator so we have to do this slow render using boring old GDI // SetDIBitsToDevice and StretchDIBits. The down side of using these GDI // functions is that the image data has to be copied across from our address // space into theirs before going to the screen (although in reality the cost // is small because all they do is to map the buffer into their address space) void CDrawImage::SlowRender(IMediaSample *pMediaSample) { // Get the BITMAPINFOHEADER for the connection ASSERT(m_pMediaType); BITMAPINFOHEADER *pbmi = HEADER(m_pMediaType->Format()); BYTE *pImage; // Get the image data buffer HRESULT hr = pMediaSample->GetPointer(&pImage); if (FAILED(hr)) { return; } // This allows derived classes to change the source rectangle that we do // the drawing with. For example a renderer may ask a codec to stretch // the video from 320x240 to 640x480, in which case the source we see in // here will still be 320x240, although the source we want to draw with // should be scaled up to 640x480. The base class implementation of this // method does nothing but return the same rectangle as we are passed in RECT SourceRect = ScaleSourceRect(&m_SourceRect); LONG lAdjustedSourceTop = SourceRect.top; // if the origin of bitmap is bottom-left, adjust soruce_rect_top // to be the bottom-left corner instead of the top-left. if (pbmi->biHeight > 0) { lAdjustedSourceTop = pbmi->biHeight - SourceRect.bottom; } // Is the window the same size as the video if (m_bStretch == FALSE) { // Put the image straight into the window SetDIBitsToDevice((HDC)m_hdc, // Target device HDC m_TargetRect.left, // X sink position m_TargetRect.top, // Y sink position m_TargetRect.right - m_TargetRect.left, // Destination width m_TargetRect.bottom - m_TargetRect.top, // Destination height SourceRect.left, // X source position lAdjustedSourceTop, // Adjusted Y source position (UINT)0, // Start scan line pbmi->biHeight, // Scan lines present pImage, // Image data (BITMAPINFO *)pbmi, // DIB header DIB_RGB_COLORS); // Type of palette } else { // Stretch the image when copying to the window StretchDIBits((HDC)m_hdc, // Target device HDC m_TargetRect.left, // X sink position m_TargetRect.top, // Y sink position m_TargetRect.right - m_TargetRect.left, // Destination width m_TargetRect.bottom - m_TargetRect.top, // Destination height SourceRect.left, // X source position lAdjustedSourceTop, // Adjusted Y source position SourceRect.right - SourceRect.left, // Source width SourceRect.bottom - SourceRect.top, // Source height pImage, // Image data (BITMAPINFO *)pbmi, // DIB header DIB_RGB_COLORS, // Type of palette SRCCOPY); // Simple image copy } // This shows the sample reference times over the top of the image which // looks a little flickery. I tried using GdiSetBatchLimit and GdiFlush to // control the screen updates but it doesn't quite work as expected and // only partially reduces the flicker. I also tried using a memory context // and combining the two in that before doing a final BitBlt operation to // the screen, unfortunately this has considerable performance penalties // and also means that this code is not executed when compiled retail #ifdef DEBUG DisplaySampleTimes(pMediaSample); #endif } // This is called with an IMediaSample interface on the image to be drawn. We // decide on the drawing mechanism based on who's allocator we are using. We // may be called when the window wants an image painted by WM_PAINT messages // We can't realise the palette here because we have the renderer lock, any // call to realise may cause an interthread send message to the window thread // which may in turn be waiting to get the renderer lock before servicing it BOOL CDrawImage::DrawImage(IMediaSample *pMediaSample) { ASSERT(m_hdc); ASSERT(m_MemoryDC); NotifyStartDraw(); // If the output pin used our allocator then the samples passed are in // fact CVideoSample objects that contain CreateDIBSection data that we // use to do faster image rendering, they may optionally also contain a // DirectDraw surface pointer in which case we do not do the drawing if (m_bUsingImageAllocator == FALSE) { SlowRender(pMediaSample); EXECUTE_ASSERT(GdiFlush()); NotifyEndDraw(); return TRUE; } // This is a DIBSECTION buffer FastRender(pMediaSample); EXECUTE_ASSERT(GdiFlush()); NotifyEndDraw(); return TRUE; } BOOL CDrawImage::DrawVideoImageHere(HDC hdc, IMediaSample *pMediaSample, __in LPRECT lprcSrc, __in LPRECT lprcDst) { ASSERT(m_pMediaType); BITMAPINFOHEADER *pbmi = HEADER(m_pMediaType->Format()); BYTE *pImage; // Get the image data buffer HRESULT hr = pMediaSample->GetPointer(&pImage); if (FAILED(hr)) { return FALSE; } RECT SourceRect; RECT TargetRect; if (lprcSrc) { SourceRect = *lprcSrc; } else SourceRect = ScaleSourceRect(&m_SourceRect); if (lprcDst) { TargetRect = *lprcDst; } else TargetRect = m_TargetRect; LONG lAdjustedSourceTop = SourceRect.top; // if the origin of bitmap is bottom-left, adjust soruce_rect_top // to be the bottom-left corner instead of the top-left. if (pbmi->biHeight > 0) { lAdjustedSourceTop = pbmi->biHeight - SourceRect.bottom; } // Stretch the image when copying to the DC BOOL bRet = (0 != StretchDIBits(hdc, TargetRect.left, TargetRect.top, TargetRect.right - TargetRect.left, TargetRect.bottom - TargetRect.top, SourceRect.left, lAdjustedSourceTop, SourceRect.right - SourceRect.left, SourceRect.bottom - SourceRect.top, pImage, (BITMAPINFO *)pbmi, DIB_RGB_COLORS, SRCCOPY)); return bRet; } // This is called by the owning window object after it has created the window // and it's drawing contexts. We are constructed with the base window we'll // be drawing into so when given the notification we retrive the device HDCs // to draw with. We cannot call these in our constructor as they are virtual void CDrawImage::SetDrawContext() { m_MemoryDC = m_pBaseWindow->GetMemoryHDC(); m_hdc = m_pBaseWindow->GetWindowHDC(); } // This is called to set the target rectangle in the video window, it will be // called whenever a WM_SIZE message is retrieved from the message queue. We // simply store the rectangle and use it later when we do the drawing calls void CDrawImage::SetTargetRect(__in RECT *pTargetRect) { ASSERT(pTargetRect); m_TargetRect = *pTargetRect; SetStretchMode(); } // Return the current target rectangle void CDrawImage::GetTargetRect(__out RECT *pTargetRect) { ASSERT(pTargetRect); *pTargetRect = m_TargetRect; } // This is called when we want to change the section of the image to draw. We // use this information in the drawing operation calls later on. We must also // see if the source and destination rectangles have the same dimensions. If // not we must stretch during the drawing rather than a direct pixel copy void CDrawImage::SetSourceRect(__in RECT *pSourceRect) { ASSERT(pSourceRect); m_SourceRect = *pSourceRect; SetStretchMode(); } // Return the current source rectangle void CDrawImage::GetSourceRect(__out RECT *pSourceRect) { ASSERT(pSourceRect); *pSourceRect = m_SourceRect; } // This is called when either the source or destination rectanges change so we // can update the stretch flag. If the rectangles don't match we stretch the // video during the drawing otherwise we call the fast pixel copy functions // NOTE the source and/or the destination rectangle may be completely empty void CDrawImage::SetStretchMode() { // Calculate the overall rectangle dimensions LONG SourceWidth = m_SourceRect.right - m_SourceRect.left; LONG SinkWidth = m_TargetRect.right - m_TargetRect.left; LONG SourceHeight = m_SourceRect.bottom - m_SourceRect.top; LONG SinkHeight = m_TargetRect.bottom - m_TargetRect.top; m_bStretch = TRUE; if (SourceWidth == SinkWidth) { if (SourceHeight == SinkHeight) { m_bStretch = FALSE; } } } // Tell us whose allocator we are using. This should be called with TRUE if // the filter agrees to use an allocator based around the CImageAllocator // SDK base class - whose image buffers are made through CreateDIBSection. // Otherwise this should be called with FALSE and we will draw the images // using SetDIBitsToDevice and StretchDIBitsToDevice. None of these calls // can handle buffers which have non zero strides (like DirectDraw uses) void CDrawImage::NotifyAllocator(BOOL bUsingImageAllocator) { m_bUsingImageAllocator = bUsingImageAllocator; } // Are we using the image DIBSECTION allocator BOOL CDrawImage::UsingImageAllocator() { return m_bUsingImageAllocator; } // We need the media type of the connection so that we can get the BITMAPINFO // from it. We use that in the calls to draw the image such as StretchDIBits // and also when updating the colour table held in shared memory DIBSECTIONs void CDrawImage::NotifyMediaType(__in CMediaType *pMediaType) { m_pMediaType = pMediaType; } // We store in this object a cookie maintaining the current palette version. // Each time a palettised format is changed we increment this value so that // when we come to draw the images we look at the colour table value they // have and if less than the current we know to update it. This version is // only needed and indeed used when working with shared memory DIBSECTIONs LONG CDrawImage::GetPaletteVersion() { return m_PaletteVersion; } // Resets the current palette version number void CDrawImage::ResetPaletteVersion() { m_PaletteVersion = PALETTE_VERSION; } // Increment the current palette version void CDrawImage::IncrementPaletteVersion() { m_PaletteVersion++; } // Constructor must initialise the base allocator. Each sample we create has a // palette version cookie on board. When the source filter changes the palette // during streaming the window object increments an internal cookie counter it // keeps as well. When it comes to render the samples it looks at the cookie // values and if they don't match then it knows to update the sample's colour // table. However we always create samples with a cookie of PALETTE_VERSION // If there have been multiple format changes and we disconnect and reconnect // thereby causing the samples to be reallocated we will create them with a // cookie much lower than the current version, this isn't a problem since it // will be seen by the window object and the versions will then be updated CImageAllocator::CImageAllocator(__inout CBaseFilter *pFilter, __in_opt LPCTSTR pName, __inout HRESULT *phr) : CBaseAllocator(pName, NULL, phr, TRUE, TRUE) , m_pFilter(pFilter) { ASSERT(phr); ASSERT(pFilter); } // Check our DIB buffers have been released #ifdef DEBUG CImageAllocator::~CImageAllocator() { ASSERT(m_bCommitted == FALSE); } #endif // Called from destructor and also from base class to free resources. We work // our way through the list of media samples deleting the DIBSECTION created // for each. All samples should be back in our list so there is no chance a // filter is still using one to write on the display or hold on a pending list void CImageAllocator::Free() { ASSERT(m_lAllocated == m_lFree.GetCount()); EXECUTE_ASSERT(GdiFlush()); CImageSample *pSample; DIBDATA *pDibData; while (m_lFree.GetCount() != 0) { pSample = (CImageSample *)m_lFree.RemoveHead(); pDibData = pSample->GetDIBData(); EXECUTE_ASSERT(DeleteObject(pDibData->hBitmap)); EXECUTE_ASSERT(CloseHandle(pDibData->hMapping)); delete pSample; } m_lAllocated = 0; } // Prepare the allocator by checking all the input parameters STDMETHODIMP CImageAllocator::CheckSizes(__in ALLOCATOR_PROPERTIES *pRequest) { // Check we have a valid connection if (m_pMediaType == NULL) { return VFW_E_NOT_CONNECTED; } // NOTE We always create a DIB section with the source format type which // may contain a source palette. When we do the BitBlt drawing operation // the target display device may contain a different palette (we may not // have the focus) in which case GDI will do after the palette mapping VIDEOINFOHEADER *pVideoInfo = (VIDEOINFOHEADER *)m_pMediaType->Format(); // When we call CreateDIBSection it implicitly maps only enough memory // for the image as defined by thee BITMAPINFOHEADER. If the user asks // for an image smaller than this then we reject the call, if they ask // for an image larger than this then we return what they can have if ((DWORD)pRequest->cbBuffer < pVideoInfo->bmiHeader.biSizeImage) { return E_INVALIDARG; } // Reject buffer prefixes if (pRequest->cbPrefix > 0) { return E_INVALIDARG; } pRequest->cbBuffer = pVideoInfo->bmiHeader.biSizeImage; return NOERROR; } // Agree the number of media sample buffers and their sizes. The base class // this allocator is derived from allows samples to be aligned only on byte // boundaries NOTE the buffers are not allocated until the Commit call STDMETHODIMP CImageAllocator::SetProperties(__in ALLOCATOR_PROPERTIES *pRequest, __out ALLOCATOR_PROPERTIES *pActual) { ALLOCATOR_PROPERTIES Adjusted = *pRequest; // Check the parameters fit with the current connection HRESULT hr = CheckSizes(&Adjusted); if (FAILED(hr)) { return hr; } return CBaseAllocator::SetProperties(&Adjusted, pActual); } // Commit the memory by allocating the agreed number of media samples. For // each sample we are committed to creating we have a CImageSample object // that we use to manage it's resources. This is initialised with a DIBDATA // structure that contains amongst other things the GDI DIBSECTION handle // We will access the renderer media type during this so we must have locked // (to prevent the format changing for example). The class overrides Commit // and Decommit to do this locking (base class Commit in turn calls Alloc) HRESULT CImageAllocator::Alloc(void) { ASSERT(m_pMediaType); CImageSample *pSample; DIBDATA DibData; // Check the base allocator says it's ok to continue HRESULT hr = CBaseAllocator::Alloc(); if (FAILED(hr)) { return hr; } // We create a new memory mapped object although we don't map it into our // address space because GDI does that in CreateDIBSection. It is possible // that we run out of resources before creating all the samples in which // case the available sample list is left with those already created ASSERT(m_lAllocated == 0); while (m_lAllocated < m_lCount) { // Create and initialise a shared memory GDI buffer hr = CreateDIB(m_lSize, DibData); if (FAILED(hr)) { return hr; } // Create the sample object and pass it the DIBDATA pSample = CreateImageSample(DibData.pBase, m_lSize); if (pSample == NULL) { EXECUTE_ASSERT(DeleteObject(DibData.hBitmap)); EXECUTE_ASSERT(CloseHandle(DibData.hMapping)); return E_OUTOFMEMORY; } // Add the completed sample to the available list pSample->SetDIBData(&DibData); m_lFree.Add(pSample); m_lAllocated++; } return NOERROR; } // We have a virtual method that allocates the samples so that a derived class // may override it and allocate more specialised sample objects. So long as it // derives its samples from CImageSample then all this code will still work ok CImageSample *CImageAllocator::CreateImageSample(__in_bcount(Length) LPBYTE pData, LONG Length) { HRESULT hr = NOERROR; CImageSample *pSample; // Allocate the new sample and check the return codes pSample = new CImageSample((CBaseAllocator *)this, // Base class NAME("Video sample"), // DEBUG name (HRESULT *)&hr, // Return code (LPBYTE)pData, // DIB address (LONG)Length); // Size of DIB if (pSample == NULL || FAILED(hr)) { delete pSample; return NULL; } return pSample; } // This function allocates a shared memory block for use by the source filter // generating DIBs for us to render. The memory block is created in shared // memory so that GDI doesn't have to copy the memory when we do a BitBlt HRESULT CImageAllocator::CreateDIB(LONG InSize, DIBDATA &DibData) { BITMAPINFO *pbmi; // Format information for pin BYTE *pBase; // Pointer to the actual image HANDLE hMapping; // Handle to mapped object HBITMAP hBitmap; // DIB section bitmap handle // Create a file mapping object and map into our address space hMapping = CreateFileMapping(hMEMORY, // Use system page file NULL, // No security attributes PAGE_READWRITE, // Full access to memory (DWORD)0, // Less than 4Gb in size InSize, // Size of buffer NULL); // No name to section if (hMapping == NULL) { DWORD Error = GetLastError(); return MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, Error); } // NOTE We always create a DIB section with the source format type which // may contain a source palette. When we do the BitBlt drawing operation // the target display device may contain a different palette (we may not // have the focus) in which case GDI will do after the palette mapping pbmi = (BITMAPINFO *)HEADER(m_pMediaType->Format()); if (m_pMediaType == NULL) { DbgBreak("Invalid media type"); } hBitmap = CreateDIBSection((HDC)NULL, // NO device context pbmi, // Format information DIB_RGB_COLORS, // Use the palette (VOID **)&pBase, // Pointer to image data hMapping, // Mapped memory handle (DWORD)0); // Offset into memory if (hBitmap == NULL || pBase == NULL) { EXECUTE_ASSERT(CloseHandle(hMapping)); DWORD Error = GetLastError(); return MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, Error); } // Initialise the DIB information structure DibData.hBitmap = hBitmap; DibData.hMapping = hMapping; DibData.pBase = pBase; DibData.PaletteVersion = PALETTE_VERSION; GetObject(hBitmap, sizeof(DIBSECTION), (VOID *)&DibData.DibSection); return NOERROR; } // We use the media type during the DIBSECTION creation void CImageAllocator::NotifyMediaType(__in CMediaType *pMediaType) { m_pMediaType = pMediaType; } // Overriden to increment the owning object's reference count STDMETHODIMP_(ULONG) CImageAllocator::NonDelegatingAddRef() { return m_pFilter->AddRef(); } // Overriden to decrement the owning object's reference count STDMETHODIMP_(ULONG) CImageAllocator::NonDelegatingRelease() { return m_pFilter->Release(); } // If you derive a class from CMediaSample that has to transport specialised // member variables and entry points then there are three alternate solutions // The first is to create a memory buffer larger than actually required by the // sample and store your information either at the beginning of it or at the // end, the former being moderately safer allowing for misbehaving transform // filters. You then adjust the buffer address when you create the base media // sample. This has the disadvantage of breaking up the memory allocated to // the samples into separate blocks. The second solution is to implement a // class derived from CMediaSample and support additional interface(s) that // convey your private data. This means defining a custom interface. The final // alternative is to create a class that inherits from CMediaSample and adds // the private data structures, when you get an IMediaSample in your Receive() // call check to see if your allocator is being used, and if it is then cast // the IMediaSample into one of your objects. Additional checks can be made // to ensure the sample's this pointer is known to be one of your own objects CImageSample::CImageSample(__inout CBaseAllocator *pAllocator, __in_opt LPCTSTR pName, __inout HRESULT *phr, __in_bcount(length) LPBYTE pBuffer, LONG length) : CMediaSample(pName, pAllocator, phr, pBuffer, length) , m_bInit(FALSE) { ASSERT(pAllocator); ASSERT(pBuffer); } // Set the shared memory DIB information void CImageSample::SetDIBData(__in DIBDATA *pDibData) { ASSERT(pDibData); m_DibData = *pDibData; m_bInit = TRUE; } // Retrieve the shared memory DIB data __out DIBDATA *CImageSample::GetDIBData() { ASSERT(m_bInit == TRUE); return &m_DibData; } // This class handles the creation of a palette. It is fairly specialist and // is intended to simplify palette management for video renderer filters. It // is for this reason that the constructor requires three other objects with // which it interacts, namely a base media filter, a base window and a base // drawing object although the base window or the draw object may be NULL to // ignore that part of us. We try not to create and install palettes unless // absolutely necessary as they typically require WM_PALETTECHANGED messages // to be sent to every window thread in the system which is very expensive CImagePalette::CImagePalette(__inout CBaseFilter *pBaseFilter, __inout CBaseWindow *pBaseWindow, __inout CDrawImage *pDrawImage) : m_pBaseWindow(pBaseWindow) , m_pFilter(pBaseFilter) , m_pDrawImage(pDrawImage) , m_hPalette(NULL) { ASSERT(m_pFilter); } // Destructor #ifdef DEBUG CImagePalette::~CImagePalette() { ASSERT(m_hPalette == NULL); } #endif // We allow dynamic format changes of the palette but rather than change the // palette every time we call this to work out whether an update is required. // If the original type didn't use a palette and the new one does (or vica // versa) then we return TRUE. If neither formats use a palette we'll return // FALSE. If both formats use a palette we compare their colours and return // FALSE if they match. This therefore short circuits palette creation unless // absolutely necessary since installing palettes is an expensive operation BOOL CImagePalette::ShouldUpdate(const VIDEOINFOHEADER *pNewInfo, const VIDEOINFOHEADER *pOldInfo) { // We may not have a current format yet if (pOldInfo == NULL) { return TRUE; } // Do both formats not require a palette if (ContainsPalette(pNewInfo) == FALSE) { if (ContainsPalette(pOldInfo) == FALSE) { return FALSE; } } // Compare the colours to see if they match DWORD VideoEntries = pNewInfo->bmiHeader.biClrUsed; if (ContainsPalette(pNewInfo) == TRUE) if (ContainsPalette(pOldInfo) == TRUE) if (pOldInfo->bmiHeader.biClrUsed == VideoEntries) if (pOldInfo->bmiHeader.biClrUsed > 0) if (memcmp((PVOID)GetBitmapPalette(pNewInfo), (PVOID)GetBitmapPalette(pOldInfo), VideoEntries * sizeof(RGBQUAD)) == 0) { return FALSE; } return TRUE; } // This is normally called when the input pin type is set to install a palette // We will typically be called from two different places. The first is when we // have negotiated a palettised media type after connection, the other is when // we receive a new type during processing with an updated palette in which // case we must remove and release the resources held by the current palette // We can be passed an optional device name if we wish to prepare a palette // for a specific monitor on a multi monitor system HRESULT CImagePalette::PreparePalette(const CMediaType *pmtNew, const CMediaType *pmtOld, __in LPSTR szDevice) { const VIDEOINFOHEADER *pNewInfo = (VIDEOINFOHEADER *)pmtNew->Format(); const VIDEOINFOHEADER *pOldInfo = (VIDEOINFOHEADER *)pmtOld->Format(); ASSERT(pNewInfo); // This is an performance optimisation, when we get a media type we check // to see if the format requires a palette change. If either we need one // when previously we didn't or vica versa then this returns TRUE, if we // previously needed a palette and we do now it compares their colours if (ShouldUpdate(pNewInfo, pOldInfo) == FALSE) { NOTE("No update needed"); return S_FALSE; } // We must notify the filter graph that the application may have changed // the palette although in practice we don't bother checking to see if it // is really different. If it tries to get the palette either the window // or renderer lock will ensure it doesn't get in until we are finished RemovePalette(); m_pFilter->NotifyEvent(EC_PALETTE_CHANGED, 0, 0); // Do we need a palette for the new format if (ContainsPalette(pNewInfo) == FALSE) { NOTE("New has no palette"); return S_FALSE; } if (m_pBaseWindow) { m_pBaseWindow->LockPaletteLock(); } // If we're changing the palette on the fly then we increment our palette // cookie which is compared against the cookie also stored in all of our // DIBSECTION media samples. If they don't match when we come to draw it // then we know the sample is out of date and we'll update it's palette NOTE("Making new colour palette"); m_hPalette = MakePalette(pNewInfo, szDevice); ASSERT(m_hPalette != NULL); if (m_pBaseWindow) { m_pBaseWindow->UnlockPaletteLock(); } // The window in which the new palette is to be realised may be a NULL // pointer to signal that no window is in use, if so we don't call it // Some filters just want to use this object to create/manage palettes if (m_pBaseWindow) m_pBaseWindow->SetPalette(m_hPalette); // This is the only time where we need access to the draw object to say // to it that a new palette will be arriving on a sample real soon. The // constructor may take a NULL pointer in which case we don't call this if (m_pDrawImage) m_pDrawImage->IncrementPaletteVersion(); return NOERROR; } // Helper function to copy a palette out of any kind of VIDEOINFO (ie it may // be YUV or true colour) into a palettised VIDEOINFO. We use this changing // palettes on DirectDraw samples as a source filter can attach a palette to // any buffer (eg YUV) and hand it back. We make a new palette out of that // format and then copy the palette colours into the current connection type HRESULT CImagePalette::CopyPalette(const CMediaType *pSrc, __out CMediaType *pDest) { // Reset the destination palette before starting VIDEOINFOHEADER *pDestInfo = (VIDEOINFOHEADER *)pDest->Format(); pDestInfo->bmiHeader.biClrUsed = 0; pDestInfo->bmiHeader.biClrImportant = 0; // Does the destination have a palette if (PALETTISED(pDestInfo) == FALSE) { NOTE("No destination palette"); return S_FALSE; } // Does the source contain a palette const VIDEOINFOHEADER *pSrcInfo = (VIDEOINFOHEADER *)pSrc->Format(); if (ContainsPalette(pSrcInfo) == FALSE) { NOTE("No source palette"); return S_FALSE; } // The number of colours may be zero filled DWORD PaletteEntries = pSrcInfo->bmiHeader.biClrUsed; if (PaletteEntries == 0) { DWORD Maximum = (1 << pSrcInfo->bmiHeader.biBitCount); NOTE1("Setting maximum colours (%d)", Maximum); PaletteEntries = Maximum; } // Make sure the destination has enough room for the palette ASSERT(pSrcInfo->bmiHeader.biClrUsed <= iPALETTE_COLORS); ASSERT(pSrcInfo->bmiHeader.biClrImportant <= PaletteEntries); ASSERT(COLORS(pDestInfo) == GetBitmapPalette(pDestInfo)); pDestInfo->bmiHeader.biClrUsed = PaletteEntries; pDestInfo->bmiHeader.biClrImportant = pSrcInfo->bmiHeader.biClrImportant; ULONG BitmapSize = GetBitmapFormatSize(HEADER(pSrcInfo)); if (pDest->FormatLength() < BitmapSize) { NOTE("Reallocating destination"); pDest->ReallocFormatBuffer(BitmapSize); } // Now copy the palette colours across CopyMemory((PVOID)COLORS(pDestInfo), (PVOID)GetBitmapPalette(pSrcInfo), PaletteEntries * sizeof(RGBQUAD)); return NOERROR; } // This is normally called when the palette is changed (typically during a // dynamic format change) to remove any palette we previously installed. We // replace it (if necessary) in the video window with a standard VGA palette // that should always be available even if this is a true colour display HRESULT CImagePalette::RemovePalette() { if (m_pBaseWindow) { m_pBaseWindow->LockPaletteLock(); } // Do we have a palette to remove if (m_hPalette != NULL) { if (m_pBaseWindow) { // Make sure that the window's palette handle matches // our palette handle. ASSERT(m_hPalette == m_pBaseWindow->GetPalette()); m_pBaseWindow->UnsetPalette(); } EXECUTE_ASSERT(DeleteObject(m_hPalette)); m_hPalette = NULL; } if (m_pBaseWindow) { m_pBaseWindow->UnlockPaletteLock(); } return NOERROR; } // Called to create a palette for the object, the data structure used by GDI // to describe a palette is a LOGPALETTE, this includes a variable number of // PALETTEENTRY fields which are the colours, we have to convert the RGBQUAD // colour fields we are handed in a BITMAPINFO from the media type into these // This handles extraction of palettes from true colour and YUV media formats // We can be passed an optional device name if we wish to prepare a palette // for a specific monitor on a multi monitor system HPALETTE CImagePalette::MakePalette(const VIDEOINFOHEADER *pVideoInfo, __in LPSTR szDevice) { ASSERT(ContainsPalette(pVideoInfo) == TRUE); ASSERT(pVideoInfo->bmiHeader.biClrUsed <= iPALETTE_COLORS); BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo); const RGBQUAD *pColours; // Pointer to the palette LOGPALETTE *lp; // Used to create a palette HPALETTE hPalette; // Logical palette object lp = (LOGPALETTE *)new BYTE[sizeof(LOGPALETTE) + SIZE_PALETTE]; if (lp == NULL) { return NULL; } // Unfortunately for some hare brained reason a GDI palette entry (a // PALETTEENTRY structure) is different to a palette entry from a DIB // format (a RGBQUAD structure) so we have to do the field conversion // The VIDEOINFO containing the palette may be a true colour type so // we use GetBitmapPalette to skip over any bit fields if they exist lp->palVersion = PALVERSION; lp->palNumEntries = (USHORT)pHeader->biClrUsed; if (lp->palNumEntries == 0) lp->palNumEntries = (1 << pHeader->biBitCount); pColours = GetBitmapPalette(pVideoInfo); for (DWORD dwCount = 0; dwCount < lp->palNumEntries; dwCount++) { lp->palPalEntry[dwCount].peRed = pColours[dwCount].rgbRed; lp->palPalEntry[dwCount].peGreen = pColours[dwCount].rgbGreen; lp->palPalEntry[dwCount].peBlue = pColours[dwCount].rgbBlue; lp->palPalEntry[dwCount].peFlags = 0; } MakeIdentityPalette(lp->palPalEntry, lp->palNumEntries, szDevice); // Create a logical palette hPalette = CreatePalette(lp); ASSERT(hPalette != NULL); delete[] lp; return hPalette; } // GDI does a fair job of compressing the palette entries you give it, so for // example if you have five entries with an RGB colour (0,0,0) it will remove // all but one of them. When you subsequently draw an image it will map from // your logical palette to the compressed device palette. This function looks // to see if it is trying to be an identity palette and if so sets the flags // field in the PALETTEENTRYs so they remain expanded to boost performance // We can be passed an optional device name if we wish to prepare a palette // for a specific monitor on a multi monitor system HRESULT CImagePalette::MakeIdentityPalette(__inout_ecount_full(iColours) PALETTEENTRY *pEntry, INT iColours, __in LPSTR szDevice) { PALETTEENTRY SystemEntries[10]; // System palette entries BOOL bIdentityPalette = TRUE; // Is an identity palette ASSERT(iColours <= iPALETTE_COLORS); // Should have a palette const int PalLoCount = 10; // First ten reserved colours const int PalHiStart = 246; // Last VGA palette entries // Does this have the full colour range if (iColours < 10) { return S_FALSE; } // Apparently some displays have odd numbers of system colours // Get a DC on the right monitor - it's ugly, but this is the way you have // to do it HDC hdc; if (szDevice == NULL || lstrcmpiLocaleIndependentA(szDevice, "DISPLAY") == 0) hdc = CreateDCA("DISPLAY", NULL, NULL, NULL); else hdc = CreateDCA(NULL, szDevice, NULL, NULL); if (NULL == hdc) { return E_OUTOFMEMORY; } INT Reserved = GetDeviceCaps(hdc, NUMRESERVED); if (Reserved != 20) { DeleteDC(hdc); return S_FALSE; } // Compare our palette against the first ten system entries. The reason I // don't do a memory compare between our two arrays of colours is because // I am not sure what will be in the flags fields for the system entries UINT Result = GetSystemPaletteEntries(hdc, 0, PalLoCount, SystemEntries); for (UINT Count = 0; Count < Result; Count++) { if (SystemEntries[Count].peRed != pEntry[Count].peRed || SystemEntries[Count].peGreen != pEntry[Count].peGreen || SystemEntries[Count].peBlue != pEntry[Count].peBlue) { bIdentityPalette = FALSE; } } // And likewise compare against the last ten entries Result = GetSystemPaletteEntries(hdc, PalHiStart, PalLoCount, SystemEntries); for (UINT Count = 0; Count < Result; Count++) { if (INT(Count) + PalHiStart < iColours) { if (SystemEntries[Count].peRed != pEntry[PalHiStart + Count].peRed || SystemEntries[Count].peGreen != pEntry[PalHiStart + Count].peGreen || SystemEntries[Count].peBlue != pEntry[PalHiStart + Count].peBlue) { bIdentityPalette = FALSE; } } } // If not an identity palette then return S_FALSE DeleteDC(hdc); if (bIdentityPalette == FALSE) { return S_FALSE; } // Set the non VGA entries so that GDI doesn't map them for (UINT Count = PalLoCount; INT(Count) < min(PalHiStart, iColours); Count++) { pEntry[Count].peFlags = PC_NOCOLLAPSE; } return NOERROR; } // Constructor initialises the VIDEOINFO we keep storing the current display // format. The format can be changed at any time, to reset the format held // by us call the RefreshDisplayType directly (it's a public method). Since // more than one thread will typically call us (ie window threads resetting // the type and source threads in the type checking methods) we have a lock CImageDisplay::CImageDisplay() { RefreshDisplayType(NULL); } // This initialises the format we hold which contains the display device type // We do a conversion on the display device type in here so that when we start // type checking input formats we can assume that certain fields have been set // correctly, an example is when we make the 16 bit mask fields explicit. This // is normally called when we receive WM_DEVMODECHANGED device change messages // The optional szDeviceName parameter tells us which monitor we are interested // in for a multi monitor system HRESULT CImageDisplay::RefreshDisplayType(__in_opt LPSTR szDeviceName) { CAutoLock cDisplayLock(this); // Set the preferred format type ZeroMemory((PVOID)&m_Display, sizeof(VIDEOINFOHEADER) + sizeof(TRUECOLORINFO)); m_Display.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); m_Display.bmiHeader.biBitCount = FALSE; // Get the bit depth of a device compatible bitmap // get caps of whichever monitor they are interested in (multi monitor) HDC hdcDisplay; // it's ugly, but this is the way you have to do it if (szDeviceName == NULL || lstrcmpiLocaleIndependentA(szDeviceName, "DISPLAY") == 0) hdcDisplay = CreateDCA("DISPLAY", NULL, NULL, NULL); else hdcDisplay = CreateDCA(NULL, szDeviceName, NULL, NULL); if (hdcDisplay == NULL) { ASSERT(FALSE); DbgLog((LOG_ERROR, 1, TEXT("ACK! Can't get a DC for %hs"), szDeviceName ? szDeviceName : "")); return E_FAIL; } else { DbgLog((LOG_TRACE, 3, TEXT("Created a DC for %s"), szDeviceName ? szDeviceName : "")); } HBITMAP hbm = CreateCompatibleBitmap(hdcDisplay, 1, 1); if (hbm) { GetDIBits(hdcDisplay, hbm, 0, 1, NULL, (BITMAPINFO *)&m_Display.bmiHeader, DIB_RGB_COLORS); // This call will get the colour table or the proper bitfields GetDIBits(hdcDisplay, hbm, 0, 1, NULL, (BITMAPINFO *)&m_Display.bmiHeader, DIB_RGB_COLORS); DeleteObject(hbm); } DeleteDC(hdcDisplay); // Complete the display type initialisation ASSERT(CheckHeaderValidity(&m_Display)); UpdateFormat(&m_Display); DbgLog((LOG_TRACE, 3, TEXT("New DISPLAY bit depth =%d"), m_Display.bmiHeader.biBitCount)); return NOERROR; } // We assume throughout this code that any bitfields masks are allowed no // more than eight bits to store a colour component. This checks that the // bit count assumption is enforced and also makes sure that all the bits // set are contiguous. We return a boolean TRUE if the field checks out ok BOOL CImageDisplay::CheckBitFields(const VIDEOINFO *pInput) { DWORD *pBitFields = (DWORD *)BITMASKS(pInput); for (INT iColour = iRED; iColour <= iBLUE; iColour++) { // First of all work out how many bits are set DWORD SetBits = CountSetBits(pBitFields[iColour]); if (SetBits > iMAXBITS || SetBits == 0) { NOTE1("Bit fields for component %d invalid", iColour); return FALSE; } // Next work out the number of zero bits prefix DWORD PrefixBits = CountPrefixBits(pBitFields[iColour]); // This is going to see if all the bits set are contiguous (as they // should be). We know how much to shift them right by from the // count of prefix bits. The number of bits set defines a mask, we // invert this (ones complement) and AND it with the shifted bit // fields. If the result is NON zero then there are bit(s) sticking // out the left hand end which means they are not contiguous DWORD TestField = pBitFields[iColour] >> PrefixBits; DWORD Mask = ULONG_MAX << SetBits; if (TestField & Mask) { NOTE1("Bit fields for component %d not contiguous", iColour); return FALSE; } } return TRUE; } // This counts the number of bits set in the input field DWORD CImageDisplay::CountSetBits(DWORD Field) { // This is a relatively well known bit counting algorithm DWORD Count = 0; DWORD init = Field; // Until the input is exhausted, count the number of bits while (init) { init = init & (init - 1); // Turn off the bottommost bit Count++; } return Count; } // This counts the number of zero bits upto the first one set NOTE the input // field should have been previously checked to ensure there is at least one // set although if we don't find one set we return the impossible value 32 DWORD CImageDisplay::CountPrefixBits(DWORD Field) { DWORD Mask = 1; DWORD Count = 0; while (TRUE) { if (Field & Mask) { return Count; } Count++; ASSERT(Mask != 0x80000000); if (Mask == 0x80000000) { return Count; } Mask <<= 1; } } // This is called to check the BITMAPINFOHEADER for the input type. There are // many implicit dependancies between the fields in a header structure which // if we validate now make for easier manipulation in subsequent handling. We // also check that the BITMAPINFOHEADER matches it's specification such that // fields likes the number of planes is one, that it's structure size is set // correctly and that the bitmap dimensions have not been set as negative BOOL CImageDisplay::CheckHeaderValidity(const VIDEOINFO *pInput) { // Check the bitmap width and height are not negative. if (pInput->bmiHeader.biWidth <= 0 || pInput->bmiHeader.biHeight <= 0) { NOTE("Invalid bitmap dimensions"); return FALSE; } // Check the compression is either BI_RGB or BI_BITFIELDS if (pInput->bmiHeader.biCompression != BI_RGB) { if (pInput->bmiHeader.biCompression != BI_BITFIELDS) { NOTE("Invalid compression format"); return FALSE; } } // If BI_BITFIELDS compression format check the colour depth if (pInput->bmiHeader.biCompression == BI_BITFIELDS) { if (pInput->bmiHeader.biBitCount != 16) { if (pInput->bmiHeader.biBitCount != 32) { NOTE("BI_BITFIELDS not 16/32 bit depth"); return FALSE; } } } // Check the assumptions about the layout of the bit fields if (pInput->bmiHeader.biCompression == BI_BITFIELDS) { if (CheckBitFields(pInput) == FALSE) { NOTE("Bit fields are not valid"); return FALSE; } } // Are the number of planes equal to one if (pInput->bmiHeader.biPlanes != 1) { NOTE("Number of planes not one"); return FALSE; } // Check the image size is consistent (it can be zero) if (pInput->bmiHeader.biSizeImage != GetBitmapSize(&pInput->bmiHeader)) { if (pInput->bmiHeader.biSizeImage) { NOTE("Image size incorrectly set"); return FALSE; } } // Check the size of the structure if (pInput->bmiHeader.biSize != sizeof(BITMAPINFOHEADER)) { NOTE("Size of BITMAPINFOHEADER wrong"); return FALSE; } return CheckPaletteHeader(pInput); } // This runs a few simple tests against the palette fields in the input to // see if it looks vaguely correct. The tests look at the number of palette // colours present, the number considered important and the biCompression // field which should always be BI_RGB as no other formats are meaningful BOOL CImageDisplay::CheckPaletteHeader(const VIDEOINFO *pInput) { // The checks here are for palettised videos only if (PALETTISED(pInput) == FALSE) { if (pInput->bmiHeader.biClrUsed) { NOTE("Invalid palette entries"); return FALSE; } return TRUE; } // Compression type of BI_BITFIELDS is meaningless for palette video if (pInput->bmiHeader.biCompression != BI_RGB) { NOTE("Palettised video must be BI_RGB"); return FALSE; } // Check the number of palette colours is correct if (pInput->bmiHeader.biClrUsed > PALETTE_ENTRIES(pInput)) { NOTE("Too many colours in palette"); return FALSE; } // The number of important colours shouldn't exceed the number used if (pInput->bmiHeader.biClrImportant > pInput->bmiHeader.biClrUsed) { NOTE("Too many important colours"); return FALSE; } return TRUE; } // Return the format of the video display const VIDEOINFO *CImageDisplay::GetDisplayFormat() { return &m_Display; } // Return TRUE if the display uses a palette BOOL CImageDisplay::IsPalettised() { return PALETTISED(&m_Display); } // Return the bit depth of the current display setting WORD CImageDisplay::GetDisplayDepth() { return m_Display.bmiHeader.biBitCount; } // Initialise the optional fields in a VIDEOINFO. These are mainly to do with // the source and destination rectangles and palette information such as the // number of colours present. It simplifies our code just a little if we don't // have to keep checking for all the different valid permutations in a header // every time we want to do anything with it (an example would be creating a // palette). We set the base class media type before calling this function so // that the media types between the pins match after a connection is made HRESULT CImageDisplay::UpdateFormat(__inout VIDEOINFO *pVideoInfo) { ASSERT(pVideoInfo); BITMAPINFOHEADER *pbmi = HEADER(pVideoInfo); SetRectEmpty(&pVideoInfo->rcSource); SetRectEmpty(&pVideoInfo->rcTarget); // Set the number of colours explicitly if (PALETTISED(pVideoInfo)) { if (pVideoInfo->bmiHeader.biClrUsed == 0) { pVideoInfo->bmiHeader.biClrUsed = PALETTE_ENTRIES(pVideoInfo); } } // The number of important colours shouldn't exceed the number used, on // some displays the number of important colours is not initialised when // retrieving the display type so we set the colours used correctly if (pVideoInfo->bmiHeader.biClrImportant > pVideoInfo->bmiHeader.biClrUsed) { pVideoInfo->bmiHeader.biClrImportant = PALETTE_ENTRIES(pVideoInfo); } // Change the image size field to be explicit if (pVideoInfo->bmiHeader.biSizeImage == 0) { pVideoInfo->bmiHeader.biSizeImage = GetBitmapSize(&pVideoInfo->bmiHeader); } return NOERROR; } // Lots of video rendering filters want code to check proposed formats are ok // This checks the VIDEOINFO we are passed as a media type. If the media type // is a valid media type then we return NOERROR otherwise E_INVALIDARG. Note // however we only accept formats that can be easily displayed in the display // so if we are on a 16 bit device we will not accept 24 bit images. The one // complexity is that most displays draw 8 bit palettised images efficiently // Also if the input format is less colour bits per pixel then we also accept HRESULT CImageDisplay::CheckVideoType(const VIDEOINFO *pInput) { // First of all check the VIDEOINFOHEADER looks correct if (CheckHeaderValidity(pInput) == FALSE) { return E_INVALIDARG; } // Virtually all devices support palettised images efficiently if (m_Display.bmiHeader.biBitCount == pInput->bmiHeader.biBitCount) { if (PALETTISED(pInput) == TRUE) { ASSERT(PALETTISED(&m_Display) == TRUE); NOTE("(Video) Type connection ACCEPTED"); return NOERROR; } } // Is the display depth greater than the input format if (m_Display.bmiHeader.biBitCount > pInput->bmiHeader.biBitCount) { NOTE("(Video) Mismatch agreed"); return NOERROR; } // Is the display depth less than the input format if (m_Display.bmiHeader.biBitCount < pInput->bmiHeader.biBitCount) { NOTE("(Video) Format mismatch"); return E_INVALIDARG; } // Both input and display formats are either BI_RGB or BI_BITFIELDS ASSERT(m_Display.bmiHeader.biBitCount == pInput->bmiHeader.biBitCount); ASSERT(PALETTISED(pInput) == FALSE); ASSERT(PALETTISED(&m_Display) == FALSE); // BI_RGB 16 bit representation is implicitly RGB555, and likewise BI_RGB // 24 bit representation is RGB888. So we initialise a pointer to the bit // fields they really mean and check against the display device format // This is only going to be called when both formats are equal bits pixel const DWORD *pInputMask = GetBitMasks(pInput); const DWORD *pDisplayMask = GetBitMasks((VIDEOINFO *)&m_Display); if (pInputMask[iRED] != pDisplayMask[iRED] || pInputMask[iGREEN] != pDisplayMask[iGREEN] || pInputMask[iBLUE] != pDisplayMask[iBLUE]) { NOTE("(Video) Bit field mismatch"); return E_INVALIDARG; } NOTE("(Video) Type connection ACCEPTED"); return NOERROR; } // Return the bit masks for the true colour VIDEOINFO provided const DWORD *CImageDisplay::GetBitMasks(const VIDEOINFO *pVideoInfo) { static const DWORD FailMasks[] = {0, 0, 0}; if (pVideoInfo->bmiHeader.biCompression == BI_BITFIELDS) { return BITMASKS(pVideoInfo); } ASSERT(pVideoInfo->bmiHeader.biCompression == BI_RGB); switch (pVideoInfo->bmiHeader.biBitCount) { case 16: return bits555; case 24: return bits888; case 32: return bits888; default: return FailMasks; } } // Check to see if we can support media type pmtIn as proposed by the output // pin - We first check that the major media type is video and also identify // the media sub type. Then we thoroughly check the VIDEOINFO type provided // As well as the contained VIDEOINFO being correct the major type must be // video, the subtype a recognised video format and the type GUID correct HRESULT CImageDisplay::CheckMediaType(const CMediaType *pmtIn) { // Does this have a VIDEOINFOHEADER format block const GUID *pFormatType = pmtIn->FormatType(); if (*pFormatType != FORMAT_VideoInfo) { NOTE("Format GUID not a VIDEOINFOHEADER"); return E_INVALIDARG; } ASSERT(pmtIn->Format()); // Check the format looks reasonably ok ULONG Length = pmtIn->FormatLength(); if (Length < SIZE_VIDEOHEADER) { NOTE("Format smaller than a VIDEOHEADER"); return E_FAIL; } VIDEOINFO *pInput = (VIDEOINFO *)pmtIn->Format(); // Check the major type is MEDIATYPE_Video const GUID *pMajorType = pmtIn->Type(); if (*pMajorType != MEDIATYPE_Video) { NOTE("Major type not MEDIATYPE_Video"); return E_INVALIDARG; } // Check we can identify the media subtype const GUID *pSubType = pmtIn->Subtype(); if (GetBitCount(pSubType) == USHRT_MAX) { NOTE("Invalid video media subtype"); return E_INVALIDARG; } return CheckVideoType(pInput); } // Given a video format described by a VIDEOINFO structure we return the mask // that is used to obtain the range of acceptable colours for this type, for // example, the mask for a 24 bit true colour format is 0xFF in all cases. A // 16 bit 5:6:5 display format uses 0xF8, 0xFC and 0xF8, therefore given any // RGB triplets we can AND them with these fields to find one that is valid BOOL CImageDisplay::GetColourMask(__out DWORD *pMaskRed, __out DWORD *pMaskGreen, __out DWORD *pMaskBlue) { CAutoLock cDisplayLock(this); *pMaskRed = 0xFF; *pMaskGreen = 0xFF; *pMaskBlue = 0xFF; // If this format is palettised then it doesn't have bit fields if (m_Display.bmiHeader.biBitCount < 16) { return FALSE; } // If this is a 24 bit true colour display then it can handle all the // possible colour component ranges described by a byte. It is never // allowed for a 24 bit colour depth image to have BI_BITFIELDS set if (m_Display.bmiHeader.biBitCount == 24) { ASSERT(m_Display.bmiHeader.biCompression == BI_RGB); return TRUE; } // Calculate the mask based on the format's bit fields const DWORD *pBitFields = (DWORD *)GetBitMasks((VIDEOINFO *)&m_Display); DWORD *pOutputMask[] = {pMaskRed, pMaskGreen, pMaskBlue}; // We know from earlier testing that there are no more than iMAXBITS // bits set in the mask and that they are all contiguous. All that // therefore remains is to shift them into the correct position for (INT iColour = iRED; iColour <= iBLUE; iColour++) { // This works out how many bits there are and where they live DWORD PrefixBits = CountPrefixBits(pBitFields[iColour]); DWORD SetBits = CountSetBits(pBitFields[iColour]); // The first shift moves the bit field so that it is right justified // in the DWORD, after which we then shift it back left which then // puts the leading bit in the bytes most significant bit position *(pOutputMask[iColour]) = pBitFields[iColour] >> PrefixBits; *(pOutputMask[iColour]) <<= (iMAXBITS - SetBits); } return TRUE; } /* Helper to convert to VIDEOINFOHEADER2 */ STDAPI ConvertVideoInfoToVideoInfo2(__inout AM_MEDIA_TYPE *pmt) { if (pmt->formattype != FORMAT_VideoInfo) { return E_INVALIDARG; } if (NULL == pmt->pbFormat || pmt->cbFormat < sizeof(VIDEOINFOHEADER)) { return E_INVALIDARG; } VIDEOINFO *pVideoInfo = (VIDEOINFO *)pmt->pbFormat; DWORD dwNewSize; HRESULT hr = DWordAdd(pmt->cbFormat, sizeof(VIDEOINFOHEADER2) - sizeof(VIDEOINFOHEADER), &dwNewSize); if (FAILED(hr)) { return hr; } PVOID pvNew = CoTaskMemAlloc(dwNewSize); if (pvNew == NULL) { return E_OUTOFMEMORY; } CopyMemory(pvNew, pmt->pbFormat, FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader)); ZeroMemory((PBYTE)pvNew + FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader), sizeof(VIDEOINFOHEADER2) - sizeof(VIDEOINFOHEADER)); CopyMemory((PBYTE)pvNew + FIELD_OFFSET(VIDEOINFOHEADER2, bmiHeader), pmt->pbFormat + FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader), pmt->cbFormat - FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader)); VIDEOINFOHEADER2 *pVideoInfo2 = (VIDEOINFOHEADER2 *)pvNew; pVideoInfo2->dwPictAspectRatioX = (DWORD)pVideoInfo2->bmiHeader.biWidth; pVideoInfo2->dwPictAspectRatioY = (DWORD)abs(pVideoInfo2->bmiHeader.biHeight); pmt->formattype = FORMAT_VideoInfo2; CoTaskMemFree(pmt->pbFormat); pmt->pbFormat = (PBYTE)pvNew; pmt->cbFormat += sizeof(VIDEOINFOHEADER2) - sizeof(VIDEOINFOHEADER); return S_OK; } // Check a media type containing VIDEOINFOHEADER STDAPI CheckVideoInfoType(const AM_MEDIA_TYPE *pmt) { if (NULL == pmt || NULL == pmt->pbFormat) { return E_POINTER; } if (pmt->majortype != MEDIATYPE_Video || pmt->formattype != FORMAT_VideoInfo || pmt->cbFormat < sizeof(VIDEOINFOHEADER)) { return VFW_E_TYPE_NOT_ACCEPTED; } const VIDEOINFOHEADER *pHeader = (const VIDEOINFOHEADER *)pmt->pbFormat; if (!ValidateBitmapInfoHeader(&pHeader->bmiHeader, pmt->cbFormat - FIELD_OFFSET(VIDEOINFOHEADER, bmiHeader))) { return VFW_E_TYPE_NOT_ACCEPTED; } return S_OK; } // Check a media type containing VIDEOINFOHEADER2 STDAPI CheckVideoInfo2Type(const AM_MEDIA_TYPE *pmt) { if (NULL == pmt || NULL == pmt->pbFormat) { return E_POINTER; } if (pmt->majortype != MEDIATYPE_Video || pmt->formattype != FORMAT_VideoInfo2 || pmt->cbFormat < sizeof(VIDEOINFOHEADER2)) { return VFW_E_TYPE_NOT_ACCEPTED; } const VIDEOINFOHEADER2 *pHeader = (const VIDEOINFOHEADER2 *)pmt->pbFormat; if (!ValidateBitmapInfoHeader(&pHeader->bmiHeader, pmt->cbFormat - FIELD_OFFSET(VIDEOINFOHEADER2, bmiHeader))) { return VFW_E_TYPE_NOT_ACCEPTED; } return S_OK; } ================================================ FILE: common/baseclasses/winutil.h ================================================ //------------------------------------------------------------------------------ // File: WinUtil.h // // Desc: DirectShow base classes - defines generic handler classes. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ // Make sure that you call PrepareWindow to initialise the window after // the object has been constructed. It is a separate method so that // derived classes can override useful methods like MessageLoop. Also // any derived class must call DoneWithWindow in its destructor. If it // doesn't a message may be retrieved and call a derived class member // function while a thread is executing the base class destructor code #ifndef __WINUTIL__ #define __WINUTIL__ const int DEFWIDTH = 320; // Initial window width const int DEFHEIGHT = 240; // Initial window height const int CAPTION = 256; // Maximum length of caption const int TIMELENGTH = 50; // Maximum length of times const int PROFILESTR = 128; // Normal profile string const WORD PALVERSION = 0x300; // GDI palette version const LONG PALETTE_VERSION = (LONG)1; // Initial palette version const COLORREF VIDEO_COLOUR = 0; // Defaults to black background const HANDLE hMEMORY = (HANDLE)(-1); // Says to open as memory file #define WIDTH(x) ((*(x)).right - (*(x)).left) #define HEIGHT(x) ((*(x)).bottom - (*(x)).top) #define SHOWSTAGE TEXT("WM_SHOWSTAGE") #define SHOWSTAGETOP TEXT("WM_SHOWSTAGETOP") #define REALIZEPALETTE TEXT("WM_REALIZEPALETTE") class AM_NOVTABLE CBaseWindow { protected: HINSTANCE m_hInstance; // Global module instance handle HWND m_hwnd; // Handle for our window HDC m_hdc; // Device context for the window LONG m_Width; // Client window width LONG m_Height; // Client window height BOOL m_bActivated; // Has the window been activated LPTSTR m_pClassName; // Static string holding class name DWORD m_ClassStyles; // Passed in to our constructor DWORD m_WindowStyles; // Likewise the initial window styles DWORD m_WindowStylesEx; // And the extended window styles UINT m_ShowStageMessage; // Have the window shown with focus UINT m_ShowStageTop; // Makes the window WS_EX_TOPMOST UINT m_RealizePalette; // Makes us realize our new palette HDC m_MemoryDC; // Used for fast BitBlt operations HPALETTE m_hPalette; // Handle to any palette we may have BYTE m_bNoRealize; // Don't realize palette now BYTE m_bBackground; // Should we realise in background BYTE m_bRealizing; // already realizing the palette CCritSec m_WindowLock; // Serialise window object access BOOL m_bDoGetDC; // Should this window get a DC bool m_bDoPostToDestroy; // Use PostMessage to destroy CCritSec m_PaletteLock; // This lock protects m_hPalette. // It should be held anytime the // program use the value of m_hPalette. // Maps windows message procedure into C++ methods friend LRESULT CALLBACK WndProc(HWND hwnd, // Window handle UINT uMsg, // Message ID WPARAM wParam, // First parameter LPARAM lParam); // Other parameter virtual LRESULT OnPaletteChange(HWND hwnd, UINT Message); public: CBaseWindow(BOOL bDoGetDC = TRUE, bool bPostToDestroy = false); #ifdef DEBUG virtual ~CBaseWindow(); #endif virtual HRESULT DoneWithWindow(); virtual HRESULT PrepareWindow(); virtual HRESULT InactivateWindow(); virtual HRESULT ActivateWindow(); virtual BOOL OnSize(LONG Width, LONG Height); virtual BOOL OnClose(); virtual RECT GetDefaultRect(); virtual HRESULT UninitialiseWindow(); virtual HRESULT InitialiseWindow(HWND hwnd); HRESULT CompleteConnect(); HRESULT DoCreateWindow(); HRESULT PerformanceAlignWindow(); HRESULT DoShowWindow(LONG ShowCmd); void PaintWindow(BOOL bErase); void DoSetWindowForeground(BOOL bFocus); virtual HRESULT SetPalette(HPALETTE hPalette); void SetRealize(BOOL bRealize) { m_bNoRealize = !bRealize; } // Jump over to the window thread to set the current palette HRESULT SetPalette(); void UnsetPalette(void); virtual HRESULT DoRealisePalette(BOOL bForceBackground = FALSE); void LockPaletteLock(); void UnlockPaletteLock(); virtual BOOL PossiblyEatMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) { return FALSE; }; // Access our window information bool WindowExists(); LONG GetWindowWidth(); LONG GetWindowHeight(); HWND GetWindowHWND(); HDC GetMemoryHDC(); HDC GetWindowHDC(); #ifdef DEBUG HPALETTE GetPalette(); #endif // DEBUG // This is the window procedure the derived object should override virtual LRESULT OnReceiveMessage(HWND hwnd, // Window handle UINT uMsg, // Message ID WPARAM wParam, // First parameter LPARAM lParam); // Other parameter // Must be overriden to return class and window styles virtual LPTSTR GetClassWindowStyles(__out DWORD *pClassStyles, // Class styles __out DWORD *pWindowStyles, // Window styles __out DWORD *pWindowStylesEx) PURE; // Extended styles }; // This helper class is entirely subservient to the owning CBaseWindow object // All this object does is to split out the actual drawing operation from the // main object (because it was becoming too large). We have a number of entry // points to set things like the draw device contexts, to implement the actual // drawing and to set the destination rectangle in the client window. We have // no critical section locking in this class because we are used exclusively // by the owning window object which looks after serialising calls into us // If you want to use this class make sure you call NotifyAllocator once the // allocate has been agreed, also call NotifyMediaType with a pointer to a // NON stack based CMediaType once that has been set (we keep a pointer to // the original rather than taking a copy). When the palette changes call // IncrementPaletteVersion (easiest thing to do is to also call this method // in the SetMediaType method most filters implement). Finally before you // start rendering anything call SetDrawContext so that we can get the HDCs // for drawing from the CBaseWindow object we are given during construction class CDrawImage { protected: CBaseWindow *m_pBaseWindow; // Owning video window object CRefTime m_StartSample; // Start time for the current sample CRefTime m_EndSample; // And likewise it's end sample time HDC m_hdc; // Main window device context HDC m_MemoryDC; // Offscreen draw device context RECT m_TargetRect; // Target destination rectangle RECT m_SourceRect; // Source image rectangle BOOL m_bStretch; // Do we have to stretch the images BOOL m_bUsingImageAllocator; // Are the samples shared DIBSECTIONs CMediaType *m_pMediaType; // Pointer to the current format int m_perfidRenderTime; // Time taken to render an image LONG m_PaletteVersion; // Current palette version cookie // Draw the video images in the window void SlowRender(IMediaSample *pMediaSample); void FastRender(IMediaSample *pMediaSample); void DisplaySampleTimes(IMediaSample *pSample); void UpdateColourTable(HDC hdc, __in BITMAPINFOHEADER *pbmi); void SetStretchMode(); public: // Used to control the image drawing CDrawImage(__inout CBaseWindow *pBaseWindow); BOOL DrawImage(IMediaSample *pMediaSample); BOOL DrawVideoImageHere(HDC hdc, IMediaSample *pMediaSample, __in LPRECT lprcSrc, __in LPRECT lprcDst); void SetDrawContext(); void SetTargetRect(__in RECT *pTargetRect); void SetSourceRect(__in RECT *pSourceRect); void GetTargetRect(__out RECT *pTargetRect); void GetSourceRect(__out RECT *pSourceRect); virtual RECT ScaleSourceRect(const RECT *pSource); // Handle updating palettes as they change LONG GetPaletteVersion(); void ResetPaletteVersion(); void IncrementPaletteVersion(); // Tell us media types and allocator assignments void NotifyAllocator(BOOL bUsingImageAllocator); void NotifyMediaType(__in CMediaType *pMediaType); BOOL UsingImageAllocator(); // Called when we are about to draw an image void NotifyStartDraw() { MSR_START(m_perfidRenderTime); }; // Called when we complete an image rendering void NotifyEndDraw() { MSR_STOP(m_perfidRenderTime); }; }; // This is the structure used to keep information about each GDI DIB. All the // samples we create from our allocator will have a DIBSECTION allocated to // them. When we receive the sample we know we can BitBlt straight to an HDC typedef struct tagDIBDATA { LONG PaletteVersion; // Current palette version in use DIBSECTION DibSection; // Details of DIB section allocated HBITMAP hBitmap; // Handle to bitmap for drawing HANDLE hMapping; // Handle to shared memory block BYTE *pBase; // Pointer to base memory address } DIBDATA; // This class inherits from CMediaSample and uses all of it's methods but it // overrides the constructor to initialise itself with the DIBDATA structure // When we come to render an IMediaSample we will know if we are using our own // allocator, and if we are, we can cast the IMediaSample to a pointer to one // of these are retrieve the DIB section information and hence the HBITMAP class CImageSample : public CMediaSample { protected: DIBDATA m_DibData; // Information about the DIBSECTION BOOL m_bInit; // Is the DIB information setup public: // Constructor CImageSample(__inout CBaseAllocator *pAllocator, __in_opt LPCTSTR pName, __inout HRESULT *phr, __in_bcount(length) LPBYTE pBuffer, LONG length); // Maintain the DIB/DirectDraw state void SetDIBData(__in DIBDATA *pDibData); __out DIBDATA *GetDIBData(); }; // This is an allocator based on the abstract CBaseAllocator base class that // allocates sample buffers in shared memory. The number and size of these // are determined when the output pin calls Prepare on us. The shared memory // blocks are used in subsequent calls to GDI CreateDIBSection, once that // has been done the output pin can fill the buffers with data which will // then be handed to GDI through BitBlt calls and thereby remove one copy class CImageAllocator : public CBaseAllocator { protected: CBaseFilter *m_pFilter; // Delegate reference counts to CMediaType *m_pMediaType; // Pointer to the current format // Used to create and delete samples HRESULT Alloc(); void Free(); // Manage the shared DIBSECTION and DCI/DirectDraw buffers HRESULT CreateDIB(LONG InSize, DIBDATA &DibData); STDMETHODIMP CheckSizes(__in ALLOCATOR_PROPERTIES *pRequest); virtual CImageSample *CreateImageSample(__in_bcount(Length) LPBYTE pData, LONG Length); public: // Constructor and destructor CImageAllocator(__inout CBaseFilter *pFilter, __in_opt LPCTSTR pName, __inout HRESULT *phr); #ifdef DEBUG ~CImageAllocator(); #endif STDMETHODIMP_(ULONG) NonDelegatingAddRef(); STDMETHODIMP_(ULONG) NonDelegatingRelease(); void NotifyMediaType(__in CMediaType *pMediaType); // Agree the number of buffers to be used and their size STDMETHODIMP SetProperties(__in ALLOCATOR_PROPERTIES *pRequest, __out ALLOCATOR_PROPERTIES *pActual); }; // This class is a fairly specialised helper class for image renderers that // have to create and manage palettes. The CBaseWindow class looks after // realising palettes once they have been installed. This class can be used // to create the palette handles from a media format (which must contain a // VIDEOINFO structure in the format block). We try to make the palette an // identity palette to maximise performance and also only change palettes // if actually required to (we compare palette colours before updating). // All the methods are virtual so that they can be overriden if so required class CImagePalette { protected: CBaseWindow *m_pBaseWindow; // Window to realise palette in CBaseFilter *m_pFilter; // Media filter to send events CDrawImage *m_pDrawImage; // Object who will be drawing HPALETTE m_hPalette; // The palette handle we own public: CImagePalette(__inout CBaseFilter *pBaseFilter, __inout CBaseWindow *pBaseWindow, __inout CDrawImage *pDrawImage); #ifdef DEBUG virtual ~CImagePalette(); #endif static HPALETTE MakePalette(const VIDEOINFOHEADER *pVideoInfo, __in LPSTR szDevice); HRESULT RemovePalette(); static HRESULT MakeIdentityPalette(__inout_ecount_full(iColours) PALETTEENTRY *pEntry, INT iColours, __in LPSTR szDevice); HRESULT CopyPalette(const CMediaType *pSrc, __out CMediaType *pDest); BOOL ShouldUpdate(const VIDEOINFOHEADER *pNewInfo, const VIDEOINFOHEADER *pOldInfo); HRESULT PreparePalette(const CMediaType *pmtNew, const CMediaType *pmtOld, __in LPSTR szDevice); BOOL DrawVideoImageHere(HDC hdc, IMediaSample *pMediaSample, __in LPRECT lprcSrc, __in LPRECT lprcDst) { return m_pDrawImage->DrawVideoImageHere(hdc, pMediaSample, lprcSrc, lprcDst); } }; // Another helper class really for video based renderers. Most such renderers // need to know what the display format is to some degree or another. This // class initialises itself with the display format. The format can be asked // for through GetDisplayFormat and various other accessor functions. If a // filter detects a display format change (perhaps it gets a WM_DEVMODECHANGE // message then it can call RefreshDisplayType to reset that format). Also // many video renderers will want to check formats as they are proposed by // source filters. This class provides methods to check formats and only // accept those video formats that can be efficiently drawn using GDI calls class CImageDisplay : public CCritSec { protected: // This holds the display format; biSize should not be too big, so we can // safely use the VIDEOINFO structure VIDEOINFO m_Display; static DWORD CountSetBits(const DWORD Field); static DWORD CountPrefixBits(const DWORD Field); static BOOL CheckBitFields(const VIDEOINFO *pInput); public: // Constructor and destructor CImageDisplay(); // Used to manage BITMAPINFOHEADERs and the display format const VIDEOINFO *GetDisplayFormat(); HRESULT RefreshDisplayType(__in_opt LPSTR szDeviceName); static BOOL CheckHeaderValidity(const VIDEOINFO *pInput); static BOOL CheckPaletteHeader(const VIDEOINFO *pInput); BOOL IsPalettised(); WORD GetDisplayDepth(); // Provide simple video format type checking HRESULT CheckMediaType(const CMediaType *pmtIn); HRESULT CheckVideoType(const VIDEOINFO *pInput); HRESULT UpdateFormat(__inout VIDEOINFO *pVideoInfo); const DWORD *GetBitMasks(const VIDEOINFO *pVideoInfo); BOOL GetColourMask(__out DWORD *pMaskRed, __out DWORD *pMaskGreen, __out DWORD *pMaskBlue); }; // Convert a FORMAT_VideoInfo to FORMAT_VideoInfo2 STDAPI ConvertVideoInfoToVideoInfo2(__inout AM_MEDIA_TYPE *pmt); // Check a media type containing VIDEOINFOHEADER STDAPI CheckVideoInfoType(const AM_MEDIA_TYPE *pmt); // Check a media type containing VIDEOINFOHEADER STDAPI CheckVideoInfo2Type(const AM_MEDIA_TYPE *pmt); #endif // __WINUTIL__ ================================================ FILE: common/baseclasses/wxdebug.cpp ================================================ //------------------------------------------------------------------------------ // File: WXDebug.cpp // // Desc: DirectShow base classes - implements ActiveX system debugging // facilities. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #define _WINDLL #include #include #include #include #ifdef DEBUG #ifdef UNICODE #ifndef _UNICODE #define _UNICODE #endif // _UNICODE #endif // UNICODE #endif // DEBUG #include #include #ifdef DEBUG static void DisplayBITMAPINFO(const BITMAPINFOHEADER *pbmi); static void DisplayRECT(LPCTSTR szLabel, const RECT &rc); // The Win32 wsprintf() function writes a maximum of 1024 characters to it's output buffer. // See the documentation for wsprintf()'s lpOut parameter for more information. const INT iDEBUGINFO = 1024; // Used to format strings /* For every module and executable we store a debugging level for each of the five categories (eg LOG_ERROR and LOG_TIMING). This makes it easy to isolate and debug individual modules without seeing everybody elses spurious debug output. The keys are stored in the registry under the HKEY_LOCAL_MACHINE\SOFTWARE\Debug\\ key values NOTE these must be in the same order as their enumeration definition */ const LPCTSTR pKeyNames[] = {TEXT("TIMING"), // Timing and performance measurements TEXT("TRACE"), // General step point call tracing TEXT("MEMORY"), // Memory and object allocation/destruction TEXT("LOCKING"), // Locking/unlocking of critical sections TEXT("ERROR"), // Debug error notification TEXT("CUSTOM1"), TEXT("CUSTOM2"), TEXT("CUSTOM3"), TEXT("CUSTOM4"), TEXT("CUSTOM5")}; const TCHAR CAutoTrace::_szEntering[] = TEXT("->: %s"); const TCHAR CAutoTrace::_szLeaving[] = TEXT("<-: %s"); const INT iMAXLEVELS = NUMELMS(pKeyNames); // Maximum debug categories HINSTANCE m_hInst; // Module instance handle TCHAR m_ModuleName[iDEBUGINFO]; // Cut down module name DWORD m_Levels[iMAXLEVELS]; // Debug level per category CRITICAL_SECTION m_CSDebug; // Controls access to list DWORD m_dwNextCookie; // Next active object ID ObjectDesc *pListHead = NULL; // First active object DWORD m_dwObjectCount; // Active object count BOOL m_bInit = FALSE; // Have we been initialised HANDLE m_hOutput = INVALID_HANDLE_VALUE; // Optional output written here DWORD dwWaitTimeout = INFINITE; // Default timeout value DWORD dwTimeOffset; // Time of first DbgLog call bool g_fUseKASSERT = false; // don't create messagebox bool g_fDbgInDllEntryPoint = false; bool g_fAutoRefreshLevels = false; LPCTSTR pBaseKey = TEXT("SOFTWARE\\Microsoft\\DirectShow\\Debug"); LPCTSTR pGlobalKey = TEXT("GLOBAL"); static CHAR *pUnknownName = "UNKNOWN"; LPCTSTR TimeoutName = TEXT("TIMEOUT"); /* This sets the instance handle that the debug library uses to find the module's file name from the Win32 GetModuleFileName function */ void WINAPI DbgInitialise(HINSTANCE hInst) { InitializeCriticalSection(&m_CSDebug); m_bInit = TRUE; m_hInst = hInst; DbgInitModuleName(); if (GetProfileInt(m_ModuleName, TEXT("BreakOnLoad"), 0)) DebugBreak(); DbgInitModuleSettings(false); DbgInitGlobalSettings(true); dwTimeOffset = timeGetTime(); } /* This is called to clear up any resources the debug library uses - at the moment we delete our critical section and the object list. The values we retrieve from the registry are all done during initialisation but we don't go looking for update notifications while we are running, if the values are changed then the application has to be restarted to pick them up */ void WINAPI DbgTerminate() { if (m_hOutput != INVALID_HANDLE_VALUE) { EXECUTE_ASSERT(CloseHandle(m_hOutput)); m_hOutput = INVALID_HANDLE_VALUE; } DeleteCriticalSection(&m_CSDebug); m_bInit = FALSE; } /* This is called by DbgInitLogLevels to read the debug settings for each logging category for this module from the registry */ void WINAPI DbgInitKeyLevels(HKEY hKey, bool fTakeMax) { LONG lReturn; // Create key return value LONG lKeyPos; // Current key category DWORD dwKeySize; // Size of the key value DWORD dwKeyType; // Receives it's type DWORD dwKeyValue; // This fields value /* Try and read a value for each key position in turn */ for (lKeyPos = 0; lKeyPos < iMAXLEVELS; lKeyPos++) { dwKeySize = sizeof(DWORD); lReturn = RegQueryValueEx(hKey, // Handle to an open key pKeyNames[lKeyPos], // Subkey name derivation NULL, // Reserved field &dwKeyType, // Returns the field type (LPBYTE)&dwKeyValue, // Returns the field's value &dwKeySize); // Number of bytes transferred /* If either the key was not available or it was not a DWORD value then we ensure only the high priority debug logging is output but we try and update the field to a zero filled DWORD value */ if (lReturn != ERROR_SUCCESS || dwKeyType != REG_DWORD) { dwKeyValue = 0; lReturn = RegSetValueEx(hKey, // Handle of an open key pKeyNames[lKeyPos], // Address of subkey name (DWORD)0, // Reserved field REG_DWORD, // Type of the key field (PBYTE)&dwKeyValue, // Value for the field sizeof(DWORD)); // Size of the field buffer if (lReturn != ERROR_SUCCESS) { DbgLog((LOG_ERROR, 1, TEXT("Could not create subkey %s"), pKeyNames[lKeyPos])); dwKeyValue = 0; } } if (fTakeMax) { m_Levels[lKeyPos] = max(dwKeyValue, m_Levels[lKeyPos]); } else { if ((m_Levels[lKeyPos] & LOG_FORCIBLY_SET) == 0) { m_Levels[lKeyPos] = dwKeyValue; } } } /* Read the timeout value for catching hangs */ dwKeySize = sizeof(DWORD); lReturn = RegQueryValueEx(hKey, // Handle to an open key TimeoutName, // Subkey name derivation NULL, // Reserved field &dwKeyType, // Returns the field type (LPBYTE)&dwWaitTimeout, // Returns the field's value &dwKeySize); // Number of bytes transferred /* If either the key was not available or it was not a DWORD value then we ensure only the high priority debug logging is output but we try and update the field to a zero filled DWORD value */ if (lReturn != ERROR_SUCCESS || dwKeyType != REG_DWORD) { dwWaitTimeout = INFINITE; lReturn = RegSetValueEx(hKey, // Handle of an open key TimeoutName, // Address of subkey name (DWORD)0, // Reserved field REG_DWORD, // Type of the key field (PBYTE)&dwWaitTimeout, // Value for the field sizeof(DWORD)); // Size of the field buffer if (lReturn != ERROR_SUCCESS) { DbgLog((LOG_ERROR, 1, TEXT("Could not create subkey %s"), pKeyNames[lKeyPos])); dwWaitTimeout = INFINITE; } } } void WINAPI DbgOutString(LPCTSTR psz) { if (m_hOutput != INVALID_HANDLE_VALUE) { UINT cb = lstrlen(psz); DWORD dw; #ifdef UNICODE CHAR szDest[2048]; WideCharToMultiByte(CP_ACP, 0, psz, -1, szDest, NUMELMS(szDest), 0, 0); WriteFile(m_hOutput, szDest, cb, &dw, NULL); #else WriteFile(m_hOutput, psz, cb, &dw, NULL); #endif } OutputDebugString(psz); } HRESULT DbgUniqueProcessName(LPCTSTR inName, LPTSTR outName) { HRESULT hr = S_OK; const TCHAR *pIn = inName; int dotPos = -1; // scan the input and record the last '.' position while (*pIn && (pIn - inName) < MAX_PATH) { if (TEXT('.') == *pIn) dotPos = (int)(pIn - inName); ++pIn; } if (*pIn) // input should be zero-terminated within MAX_PATH return E_INVALIDARG; DWORD dwProcessId = GetCurrentProcessId(); if (dotPos < 0) { // no extension in the input, appending process id to the input hr = StringCchPrintf(outName, MAX_PATH, TEXT("%s_%d"), inName, dwProcessId); } else { TCHAR pathAndBasename[MAX_PATH] = {0}; // there's an extension - zero-terminate the path and basename first by copying hr = StringCchCopyN(pathAndBasename, MAX_PATH, inName, (size_t)dotPos); // re-combine path, basename and extension with processId appended to a basename if (SUCCEEDED(hr)) hr = StringCchPrintf(outName, MAX_PATH, TEXT("%s_%d%s"), pathAndBasename, dwProcessId, inName + dotPos); } return hr; } /* Called by DbgInitGlobalSettings to setup alternate logging destinations */ void WINAPI DbgInitLogTo(HKEY hKey) { LONG lReturn; DWORD dwKeyType; DWORD dwKeySize; TCHAR szFile[MAX_PATH] = {0}; static const TCHAR cszKey[] = TEXT("LogToFile"); dwKeySize = MAX_PATH; lReturn = RegQueryValueEx(hKey, // Handle to an open key cszKey, // Subkey name derivation NULL, // Reserved field &dwKeyType, // Returns the field type (LPBYTE)szFile, // Returns the field's value &dwKeySize); // Number of bytes transferred // create an empty key if it does not already exist // if (lReturn != ERROR_SUCCESS || dwKeyType != REG_SZ) { dwKeySize = sizeof(TCHAR); lReturn = RegSetValueEx(hKey, // Handle of an open key cszKey, // Address of subkey name (DWORD)0, // Reserved field REG_SZ, // Type of the key field (PBYTE)szFile, // Value for the field dwKeySize); // Size of the field buffer } // if an output-to was specified. try to open it. // if (m_hOutput != INVALID_HANDLE_VALUE) { EXECUTE_ASSERT(CloseHandle(m_hOutput)); m_hOutput = INVALID_HANDLE_VALUE; } if (szFile[0] != 0) { if (!lstrcmpi(szFile, TEXT("Console"))) { m_hOutput = GetStdHandle(STD_OUTPUT_HANDLE); if (m_hOutput == INVALID_HANDLE_VALUE) { AllocConsole(); m_hOutput = GetStdHandle(STD_OUTPUT_HANDLE); } SetConsoleTitle(TEXT("ActiveX Debug Output")); } else if (szFile[0] && lstrcmpi(szFile, TEXT("Debug")) && lstrcmpi(szFile, TEXT("Debugger")) && lstrcmpi(szFile, TEXT("Deb"))) { m_hOutput = CreateFile(szFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == m_hOutput && GetLastError() == ERROR_SHARING_VIOLATION) { TCHAR uniqueName[MAX_PATH] = {0}; if (SUCCEEDED(DbgUniqueProcessName(szFile, uniqueName))) { m_hOutput = CreateFile(uniqueName, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); } } if (INVALID_HANDLE_VALUE != m_hOutput) { static const TCHAR cszBar[] = TEXT("\r\n\r\n=====DbgInitialize()=====\r\n\r\n"); SetFilePointer(m_hOutput, 0, NULL, FILE_END); DbgOutString(cszBar); } } } } /* This is called by DbgInitLogLevels to read the global debug settings for each logging category for this module from the registry. Normally each module has it's own values set for it's different debug categories but setting the global SOFTWARE\Debug\Global applies them to ALL modules */ void WINAPI DbgInitGlobalSettings(bool fTakeMax) { LONG lReturn; // Create key return value TCHAR szInfo[iDEBUGINFO]; // Constructs key names HKEY hGlobalKey; // Global override key /* Construct the global base key name */ (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%s\\%s"), pBaseKey, pGlobalKey); /* Create or open the key for this module */ lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key szInfo, // Address of subkey name (DWORD)0, // Reserved value NULL, // Address of class name (DWORD)0, // Special options flags GENERIC_READ | GENERIC_WRITE, // Desired security access NULL, // Key security descriptor &hGlobalKey, // Opened handle buffer NULL); // What really happened if (lReturn != ERROR_SUCCESS) { lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key szInfo, // Address of subkey name (DWORD)0, // Reserved value NULL, // Address of class name (DWORD)0, // Special options flags GENERIC_READ, // Desired security access NULL, // Key security descriptor &hGlobalKey, // Opened handle buffer NULL); // What really happened if (lReturn != ERROR_SUCCESS) { DbgLog((LOG_ERROR, 1, TEXT("Could not access GLOBAL module key"))); } return; } DbgInitKeyLevels(hGlobalKey, fTakeMax); RegCloseKey(hGlobalKey); } /* This sets the debugging log levels for the different categories. We start by opening (or creating if not already available) the SOFTWARE\Debug key that all these settings live under. We then look at the global values set under SOFTWARE\Debug\Global which apply on top of the individual module settings. We then load the individual module registry settings */ void WINAPI DbgInitModuleSettings(bool fTakeMax) { LONG lReturn; // Create key return value TCHAR szInfo[iDEBUGINFO]; // Constructs key names HKEY hModuleKey; // Module key handle /* Construct the base key name */ (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%s\\%s"), pBaseKey, m_ModuleName); /* Create or open the key for this module */ lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key szInfo, // Address of subkey name (DWORD)0, // Reserved value NULL, // Address of class name (DWORD)0, // Special options flags GENERIC_READ | GENERIC_WRITE, // Desired security access NULL, // Key security descriptor &hModuleKey, // Opened handle buffer NULL); // What really happened if (lReturn != ERROR_SUCCESS) { lReturn = RegCreateKeyEx(HKEY_LOCAL_MACHINE, // Handle of an open key szInfo, // Address of subkey name (DWORD)0, // Reserved value NULL, // Address of class name (DWORD)0, // Special options flags GENERIC_READ, // Desired security access NULL, // Key security descriptor &hModuleKey, // Opened handle buffer NULL); // What really happened if (lReturn != ERROR_SUCCESS) { DbgLog((LOG_ERROR, 1, TEXT("Could not access module key"))); } return; } DbgInitLogTo(hModuleKey); DbgInitKeyLevels(hModuleKey, fTakeMax); RegCloseKey(hModuleKey); } /* Initialise the module file name */ void WINAPI DbgInitModuleName() { TCHAR FullName[iDEBUGINFO]; // Load the full path and module name LPTSTR pName; // Searches from the end for a backslash GetModuleFileName(m_hInst, FullName, iDEBUGINFO); pName = _tcsrchr(FullName, '\\'); if (pName == NULL) { pName = FullName; } else { pName++; } (void)StringCchCopy(m_ModuleName, NUMELMS(m_ModuleName), pName); } struct MsgBoxMsg { HWND hwnd; LPCTSTR szTitle; LPCTSTR szMessage; DWORD dwFlags; INT iResult; }; // // create a thread to call MessageBox(). calling MessageBox() on // random threads at bad times can confuse the host (eg IE). // DWORD WINAPI MsgBoxThread(__inout LPVOID lpParameter // thread data ) { MsgBoxMsg *pmsg = (MsgBoxMsg *)lpParameter; pmsg->iResult = MessageBox(pmsg->hwnd, pmsg->szTitle, pmsg->szMessage, pmsg->dwFlags); return 0; } INT MessageBoxOtherThread(HWND hwnd, LPCTSTR szTitle, LPCTSTR szMessage, DWORD dwFlags) { if (g_fDbgInDllEntryPoint) { // can't wait on another thread because we have the loader // lock held in the dll entry point. // This can crash sometimes so just skip it // return MessageBox(hwnd, szTitle, szMessage, dwFlags); return IDCANCEL; } else { MsgBoxMsg msg = {hwnd, szTitle, szMessage, dwFlags, 0}; DWORD dwid; HANDLE hThread = CreateThread(0, // security 0, // stack size MsgBoxThread, (void *)&msg, // arg 0, // flags &dwid); if (hThread) { WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); return msg.iResult; } // break into debugger on failure. return IDCANCEL; } } /* Displays a message box if the condition evaluated to FALSE */ void WINAPI DbgAssert(LPCTSTR pCondition, LPCTSTR pFileName, INT iLine) { if (g_fUseKASSERT) { DbgKernelAssert(pCondition, pFileName, iLine); } else { TCHAR szInfo[iDEBUGINFO]; (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%s \nAt line %d of %s\nContinue? (Cancel to debug)"), pCondition, iLine, pFileName); INT MsgId = MessageBoxOtherThread(NULL, szInfo, TEXT("ASSERT Failed"), MB_SYSTEMMODAL | MB_ICONHAND | MB_YESNOCANCEL | MB_SETFOREGROUND); switch (MsgId) { case IDNO: /* Kill the application */ FatalAppExit(FALSE, TEXT("Application terminated")); break; case IDCANCEL: /* Break into the debugger */ DebugBreak(); break; case IDYES: /* Ignore assertion continue execution */ break; } } } /* Displays a message box at a break point */ void WINAPI DbgBreakPoint(LPCTSTR pCondition, LPCTSTR pFileName, INT iLine) { if (g_fUseKASSERT) { DbgKernelAssert(pCondition, pFileName, iLine); } else { TCHAR szInfo[iDEBUGINFO]; (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%s \nAt line %d of %s\nContinue? (Cancel to debug)"), pCondition, iLine, pFileName); INT MsgId = MessageBoxOtherThread(NULL, szInfo, TEXT("Hard coded break point"), MB_SYSTEMMODAL | MB_ICONHAND | MB_YESNOCANCEL | MB_SETFOREGROUND); switch (MsgId) { case IDNO: /* Kill the application */ FatalAppExit(FALSE, TEXT("Application terminated")); break; case IDCANCEL: /* Break into the debugger */ DebugBreak(); break; case IDYES: /* Ignore break point continue execution */ break; } } } void WINAPI DbgBreakPoint(LPCTSTR pFileName, INT iLine, __format_string LPCTSTR szFormatString, ...) { // A debug break point message can have at most 2000 characters if // ANSI or UNICODE characters are being used. A debug break point message // can have between 1000 and 2000 double byte characters in it. If a // particular message needs more characters, then the value of this constant // should be increased. const DWORD MAX_BREAK_POINT_MESSAGE_SIZE = 2000; TCHAR szBreakPointMessage[MAX_BREAK_POINT_MESSAGE_SIZE]; va_list va; va_start(va, szFormatString); HRESULT hr = StringCchVPrintf(szBreakPointMessage, NUMELMS(szBreakPointMessage), szFormatString, va); va_end(va); if (FAILED(hr)) { DbgBreak("ERROR in DbgBreakPoint(). The variable length debug message could not be displayed because " "StringCchVPrintf() failed."); return; } ::DbgBreakPoint(szBreakPointMessage, pFileName, iLine); } /* When we initialised the library we stored in the m_Levels array the current debug output level for this module for each of the five categories. When some debug logging is sent to us it can be sent with a combination of the categories (if it is applicable to many for example) in which case we map the type's categories into their current debug levels and see if any of them can be accepted. The function looks at each bit position in turn from the input type field and then compares it's debug level with the modules. A level of 0 means that output is always sent to the debugger. This is due to producing output if the input level is <= m_Levels. */ BOOL WINAPI DbgCheckModuleLevel(DWORD Type, DWORD Level) { if (g_fAutoRefreshLevels) { // re-read the registry every second. We cannot use RegNotify() to // notice registry changes because it's not available on win9x. static DWORD g_dwLastRefresh = 0; DWORD dwTime = timeGetTime(); if (dwTime - g_dwLastRefresh > 1000) { g_dwLastRefresh = dwTime; // there's a race condition: multiple threads could update the // values. plus read and write not synchronized. no harm // though. DbgInitModuleSettings(false); } } DWORD Mask = 0x01; // If no valid bits are set return FALSE if ((Type & ((1 << iMAXLEVELS) - 1))) { // speed up unconditional output. if (0 == Level) return (TRUE); for (LONG lKeyPos = 0; lKeyPos < iMAXLEVELS; lKeyPos++) { if (Type & Mask) { if (Level <= (m_Levels[lKeyPos] & ~LOG_FORCIBLY_SET)) { return TRUE; } } Mask <<= 1; } } return FALSE; } /* Set debug levels to a given value */ void WINAPI DbgSetModuleLevel(DWORD Type, DWORD Level) { DWORD Mask = 0x01; for (LONG lKeyPos = 0; lKeyPos < iMAXLEVELS; lKeyPos++) { if (Type & Mask) { m_Levels[lKeyPos] = Level | LOG_FORCIBLY_SET; } Mask <<= 1; } } /* whether to check registry values periodically. this isn't turned automatically because of the potential performance hit. */ void WINAPI DbgSetAutoRefreshLevels(bool fAuto) { g_fAutoRefreshLevels = fAuto; } #ifdef UNICODE // // warning -- this function is implemented twice for ansi applications // linking to the unicode library // void WINAPI DbgLogInfo(DWORD Type, DWORD Level, __format_string LPCSTR pFormat, ...) { /* Check the current level for this type combination */ BOOL bAccept = DbgCheckModuleLevel(Type, Level); if (bAccept == FALSE) { return; } TCHAR szInfo[2000]; /* Format the variable length parameter list */ va_list va; va_start(va, pFormat); (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%s(tid %x) %8d : "), m_ModuleName, GetCurrentThreadId(), timeGetTime() - dwTimeOffset); CHAR szInfoA[2000]; WideCharToMultiByte(CP_ACP, 0, szInfo, -1, szInfoA, NUMELMS(szInfoA), 0, 0); (void)StringCchVPrintfA(szInfoA + lstrlenA(szInfoA), NUMELMS(szInfoA) - lstrlenA(szInfoA), pFormat, va); (void)StringCchCatA(szInfoA, NUMELMS(szInfoA), "\r\n"); WCHAR wszOutString[2000]; MultiByteToWideChar(CP_ACP, 0, szInfoA, -1, wszOutString, NUMELMS(wszOutString)); DbgOutString(wszOutString); va_end(va); } void WINAPI DbgAssert(LPCSTR pCondition, LPCSTR pFileName, INT iLine) { if (g_fUseKASSERT) { DbgKernelAssert(pCondition, pFileName, iLine); } else { TCHAR szInfo[iDEBUGINFO]; (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%hs \nAt line %d of %hs\nContinue? (Cancel to debug)"), pCondition, iLine, pFileName); INT MsgId = MessageBoxOtherThread(NULL, szInfo, TEXT("ASSERT Failed"), MB_SYSTEMMODAL | MB_ICONHAND | MB_YESNOCANCEL | MB_SETFOREGROUND); switch (MsgId) { case IDNO: /* Kill the application */ FatalAppExit(FALSE, TEXT("Application terminated")); break; case IDCANCEL: /* Break into the debugger */ DebugBreak(); break; case IDYES: /* Ignore assertion continue execution */ break; } } } /* Displays a message box at a break point */ void WINAPI DbgBreakPoint(LPCSTR pCondition, LPCSTR pFileName, INT iLine) { if (g_fUseKASSERT) { DbgKernelAssert(pCondition, pFileName, iLine); } else { TCHAR szInfo[iDEBUGINFO]; (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%hs \nAt line %d of %hs\nContinue? (Cancel to debug)"), pCondition, iLine, pFileName); INT MsgId = MessageBoxOtherThread(NULL, szInfo, TEXT("Hard coded break point"), MB_SYSTEMMODAL | MB_ICONHAND | MB_YESNOCANCEL | MB_SETFOREGROUND); switch (MsgId) { case IDNO: /* Kill the application */ FatalAppExit(FALSE, TEXT("Application terminated")); break; case IDCANCEL: /* Break into the debugger */ DebugBreak(); break; case IDYES: /* Ignore break point continue execution */ break; } } } void WINAPI DbgKernelAssert(LPCSTR pCondition, LPCSTR pFileName, INT iLine) { DbgLog((LOG_ERROR, 0, TEXT("Assertion FAILED (%hs) at line %d in file %hs"), pCondition, iLine, pFileName)); DebugBreak(); } #endif /* Print a formatted string to the debugger prefixed with this module's name Because the COMBASE classes are linked statically every module loaded will have their own copy of this code. It therefore helps if the module name is included on the output so that the offending code can be easily found */ // // warning -- this function is implemented twice for ansi applications // linking to the unicode library // void WINAPI DbgLogInfo(DWORD Type, DWORD Level, LPCTSTR pFormat, ...) { /* Check the current level for this type combination */ BOOL bAccept = DbgCheckModuleLevel(Type, Level); if (bAccept == FALSE) { return; } TCHAR szInfo[2000]; /* Format the variable length parameter list */ va_list va; va_start(va, pFormat); (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%s(tid %x) %8d : "), m_ModuleName, GetCurrentThreadId(), timeGetTime() - dwTimeOffset); (void)StringCchVPrintf(szInfo + lstrlen(szInfo), NUMELMS(szInfo) - lstrlen(szInfo), pFormat, va); (void)StringCchCat(szInfo, NUMELMS(szInfo), TEXT("\r\n")); DbgOutString(szInfo); va_end(va); } /* If we are executing as a pure kernel filter we cannot display message boxes to the user, this provides an alternative which puts the error condition on the debugger output with a suitable eye catching message */ void WINAPI DbgKernelAssert(LPCTSTR pCondition, LPCTSTR pFileName, INT iLine) { DbgLog((LOG_ERROR, 0, TEXT("Assertion FAILED (%s) at line %d in file %s"), pCondition, iLine, pFileName)); DebugBreak(); } /* Each time we create an object derived from CBaseObject the constructor will call us to register the creation of the new object. We are passed a string description which we store away. We return a cookie that the constructor uses to identify the object when it is destroyed later on. We update the total number of active objects in the DLL mainly for debugging purposes */ DWORD WINAPI DbgRegisterObjectCreation(LPCSTR szObjectName, LPCWSTR wszObjectName) { /* If this fires you have a mixed DEBUG/RETAIL build */ ASSERT(!!szObjectName ^ !!wszObjectName); /* Create a place holder for this object description */ ObjectDesc *pObject = new ObjectDesc; ASSERT(pObject); /* It is valid to pass a NULL object name */ if (pObject == NULL) { return FALSE; } /* Check we have been initialised - we may not be initialised when we are being pulled in from an executable which has globally defined objects as they are created by the C++ run time before WinMain is called */ if (m_bInit == FALSE) { DbgInitialise(GetModuleHandle(NULL)); } /* Grab the list critical section */ EnterCriticalSection(&m_CSDebug); /* If no name then default to UNKNOWN */ if (!szObjectName && !wszObjectName) { szObjectName = pUnknownName; } /* Put the new description at the head of the list */ pObject->m_szName = szObjectName; pObject->m_wszName = wszObjectName; pObject->m_dwCookie = ++m_dwNextCookie; pObject->m_pNext = pListHead; pListHead = pObject; m_dwObjectCount++; DWORD ObjectCookie = pObject->m_dwCookie; ASSERT(ObjectCookie); if (wszObjectName) { DbgLog((LOG_MEMORY, 2, TEXT("Object created %d (%ls) %d Active"), pObject->m_dwCookie, wszObjectName, m_dwObjectCount)); } else { DbgLog((LOG_MEMORY, 2, TEXT("Object created %d (%hs) %d Active"), pObject->m_dwCookie, szObjectName, m_dwObjectCount)); } LeaveCriticalSection(&m_CSDebug); return ObjectCookie; } /* This is called by the CBaseObject destructor when an object is about to be destroyed, we are passed the cookie we returned during construction that identifies this object. We scan the object list for a matching cookie and remove the object if successful. We also update the active object count */ BOOL WINAPI DbgRegisterObjectDestruction(DWORD dwCookie) { /* Grab the list critical section */ EnterCriticalSection(&m_CSDebug); ObjectDesc *pObject = pListHead; ObjectDesc *pPrevious = NULL; /* Scan the object list looking for a cookie match */ while (pObject) { if (pObject->m_dwCookie == dwCookie) { break; } pPrevious = pObject; pObject = pObject->m_pNext; } if (pObject == NULL) { DbgBreak("Apparently destroying a bogus object"); LeaveCriticalSection(&m_CSDebug); return FALSE; } /* Is the object at the head of the list */ if (pPrevious == NULL) { pListHead = pObject->m_pNext; } else { pPrevious->m_pNext = pObject->m_pNext; } /* Delete the object and update the housekeeping information */ m_dwObjectCount--; if (pObject->m_wszName) { DbgLog((LOG_MEMORY, 2, TEXT("Object destroyed %d (%ls) %d Active"), pObject->m_dwCookie, pObject->m_wszName, m_dwObjectCount)); } else { DbgLog((LOG_MEMORY, 2, TEXT("Object destroyed %d (%hs) %d Active"), pObject->m_dwCookie, pObject->m_szName, m_dwObjectCount)); } delete pObject; LeaveCriticalSection(&m_CSDebug); return TRUE; } /* This runs through the active object list displaying their details */ void WINAPI DbgDumpObjectRegister() { TCHAR szInfo[iDEBUGINFO]; /* Grab the list critical section */ EnterCriticalSection(&m_CSDebug); ObjectDesc *pObject = pListHead; /* Scan the object list displaying the name and cookie */ DbgLog((LOG_MEMORY, 2, TEXT(""))); DbgLog((LOG_MEMORY, 2, TEXT(" ID Object Description"))); DbgLog((LOG_MEMORY, 2, TEXT(""))); while (pObject) { if (pObject->m_wszName) { (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%5d (%p) %30ls"), pObject->m_dwCookie, &pObject, pObject->m_wszName); } else { (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%5d (%p) %30hs"), pObject->m_dwCookie, &pObject, pObject->m_szName); } DbgLog((LOG_MEMORY, 2, szInfo)); pObject = pObject->m_pNext; } (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("Total object count %5d"), m_dwObjectCount); DbgLog((LOG_MEMORY, 2, TEXT(""))); DbgLog((LOG_MEMORY, 1, szInfo)); LeaveCriticalSection(&m_CSDebug); } /* Debug infinite wait stuff */ DWORD WINAPI DbgWaitForSingleObject(HANDLE h) { DWORD dwWaitResult; do { dwWaitResult = WaitForSingleObject(h, dwWaitTimeout); ASSERT(dwWaitResult == WAIT_OBJECT_0); } while (dwWaitResult == WAIT_TIMEOUT); return dwWaitResult; } DWORD WINAPI DbgWaitForMultipleObjects(DWORD nCount, __in_ecount(nCount) CONST HANDLE *lpHandles, BOOL bWaitAll) { DWORD dwWaitResult; do { dwWaitResult = WaitForMultipleObjects(nCount, lpHandles, bWaitAll, dwWaitTimeout); ASSERT((DWORD)(dwWaitResult - WAIT_OBJECT_0) < MAXIMUM_WAIT_OBJECTS); } while (dwWaitResult == WAIT_TIMEOUT); return dwWaitResult; } void WINAPI DbgSetWaitTimeout(DWORD dwTimeout) { dwWaitTimeout = dwTimeout; } #endif /* DEBUG */ #ifdef _OBJBASE_H_ /* Stuff for printing out our GUID names */ GUID_STRING_ENTRY g_GuidNames[] = { #define OUR_GUID_ENTRY(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ {#name, {l, w1, w2, {b1, b2, b3, b4, b5, b6, b7, b8}}}, #include }; CGuidNameList GuidNames; int g_cGuidNames = sizeof(g_GuidNames) / sizeof(g_GuidNames[0]); char *CGuidNameList::operator[](const GUID &guid) { for (int i = 0; i < g_cGuidNames; i++) { if (g_GuidNames[i].guid == guid) { return g_GuidNames[i].szName; } } if (guid == GUID_NULL) { return "GUID_NULL"; } // !!! add something to print FOURCC guids? // shouldn't this print the hex CLSID? return "Unknown GUID Name"; } #endif /* _OBJBASE_H_ */ /* CDisp class - display our data types */ // clashes with REFERENCE_TIME CDisp::CDisp(LONGLONG ll, int Format) { // note: this could be combined with CDisp(LONGLONG) by // introducing a default format of CDISP_REFTIME LARGE_INTEGER li; li.QuadPart = ll; switch (Format) { case CDISP_DEC: { TCHAR temp[20]; int pos = 20; temp[--pos] = 0; int digit; // always output at least one digit do { // Get the rightmost digit - we only need the low word digit = li.LowPart % 10; li.QuadPart /= 10; temp[--pos] = (TCHAR)digit + L'0'; } while (li.QuadPart); (void)StringCchCopy(m_String, NUMELMS(m_String), temp + pos); break; } case CDISP_HEX: default: (void)StringCchPrintf(m_String, NUMELMS(m_String), TEXT("0x%X%8.8X"), li.HighPart, li.LowPart); } }; CDisp::CDisp(REFCLSID clsid) { #ifdef UNICODE (void)StringFromGUID2(clsid, m_String, NUMELMS(m_String)); #else WCHAR wszTemp[50]; (void)StringFromGUID2(clsid, wszTemp, NUMELMS(wszTemp)); (void)StringCchPrintf(m_String, NUMELMS(m_String), TEXT("%S"), wszTemp); #endif }; #ifdef __STREAMS__ /* Display stuff */ CDisp::CDisp(CRefTime llTime) { LONGLONG llDiv; if (llTime < 0) { llTime = -llTime; (void)StringCchCopy(m_String, NUMELMS(m_String), TEXT("-")); } llDiv = (LONGLONG)24 * 3600 * 10000000; if (llTime >= llDiv) { (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d days "), (LONG)(llTime / llDiv)); llTime = llTime % llDiv; } llDiv = (LONGLONG)3600 * 10000000; if (llTime >= llDiv) { (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d hrs "), (LONG)(llTime / llDiv)); llTime = llTime % llDiv; } llDiv = (LONGLONG)60 * 10000000; if (llTime >= llDiv) { (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d mins "), (LONG)(llTime / llDiv)); llTime = llTime % llDiv; } (void)StringCchPrintf(m_String + lstrlen(m_String), NUMELMS(m_String) - lstrlen(m_String), TEXT("%d.%3.3d sec"), (LONG)llTime / 10000000, (LONG)((llTime % 10000000) / 10000)); }; #endif // __STREAMS__ /* Display pin */ CDisp::CDisp(IPin *pPin) { PIN_INFO pi; TCHAR str[MAX_PIN_NAME]; CLSID clsid; if (pPin) { pPin->QueryPinInfo(&pi); pi.pFilter->GetClassID(&clsid); QueryPinInfoReleaseFilter(pi); #ifndef UNICODE WideCharToMultiByte(GetACP(), 0, pi.achName, lstrlenW(pi.achName) + 1, str, MAX_PIN_NAME, NULL, NULL); #else (void)StringCchCopy(str, NUMELMS(str), pi.achName); #endif } else { (void)StringCchCopy(str, NUMELMS(str), TEXT("NULL IPin")); } m_pString = (PTCHAR) new TCHAR[lstrlen(str) + 64]; if (!m_pString) { return; } (void)StringCchPrintf(m_pString, lstrlen(str) + 64, TEXT("%hs(%s)"), GuidNames[clsid], str); } /* Display filter or pin */ CDisp::CDisp(IUnknown *pUnk) { IBaseFilter *pf; HRESULT hr = pUnk->QueryInterface(IID_IBaseFilter, (void **)&pf); if (SUCCEEDED(hr)) { FILTER_INFO fi; hr = pf->QueryFilterInfo(&fi); if (SUCCEEDED(hr)) { QueryFilterInfoReleaseGraph(fi); size_t len = lstrlenW(fi.achName) + 1; m_pString = new TCHAR[len]; if (m_pString) { #ifdef UNICODE (void)StringCchCopy(m_pString, len, fi.achName); #else (void)StringCchPrintf(m_pString, len, "%S", fi.achName); #endif } } pf->Release(); return; } IPin *pp; hr = pUnk->QueryInterface(IID_IPin, (void **)&pp); if (SUCCEEDED(hr)) { CDisp::CDisp(pp); pp->Release(); return; } } CDisp::~CDisp() { } CDispBasic::~CDispBasic() { if (m_pString != m_String) { delete[] m_pString; } } CDisp::CDisp(double d) { (void)StringCchPrintf(m_String, NUMELMS(m_String), TEXT("%d.%03d"), (int)d, (int)((d - (int)d) * 1000)); } /* If built for debug this will display the media type details. We convert the major and subtypes into strings and also ask the base classes for a string description of the subtype, so MEDIASUBTYPE_RGB565 becomes RGB 565 16 bit We also display the fields in the BITMAPINFOHEADER structure, this should succeed as we do not accept input types unless the format is big enough */ #ifdef DEBUG void WINAPI DisplayType(LPCTSTR label, const AM_MEDIA_TYPE *pmtIn) { /* Dump the GUID types and a short description */ DbgLog((LOG_TRACE, 5, TEXT(""))); DbgLog((LOG_TRACE, 2, TEXT("%s M type %hs S type %hs"), label, GuidNames[pmtIn->majortype], GuidNames[pmtIn->subtype])); DbgLog((LOG_TRACE, 5, TEXT("Subtype description %s"), GetSubtypeName(&pmtIn->subtype))); /* Dump the generic media types */ if (pmtIn->bTemporalCompression) { DbgLog((LOG_TRACE, 5, TEXT("Temporally compressed"))); } else { DbgLog((LOG_TRACE, 5, TEXT("Not temporally compressed"))); } if (pmtIn->bFixedSizeSamples) { DbgLog((LOG_TRACE, 5, TEXT("Sample size %d"), pmtIn->lSampleSize)); } else { DbgLog((LOG_TRACE, 5, TEXT("Variable size samples"))); } if (pmtIn->formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER *pVideoInfo = (VIDEOINFOHEADER *)pmtIn->pbFormat; DisplayRECT(TEXT("Source rectangle"), pVideoInfo->rcSource); DisplayRECT(TEXT("Target rectangle"), pVideoInfo->rcTarget); DisplayBITMAPINFO(HEADER(pmtIn->pbFormat)); } if (pmtIn->formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2 *pVideoInfo2 = (VIDEOINFOHEADER2 *)pmtIn->pbFormat; DisplayRECT(TEXT("Source rectangle"), pVideoInfo2->rcSource); DisplayRECT(TEXT("Target rectangle"), pVideoInfo2->rcTarget); DbgLog((LOG_TRACE, 5, TEXT("Aspect Ratio: %d:%d"), pVideoInfo2->dwPictAspectRatioX, pVideoInfo2->dwPictAspectRatioY)); DisplayBITMAPINFO(&pVideoInfo2->bmiHeader); } else if (pmtIn->majortype == MEDIATYPE_Audio) { DbgLog((LOG_TRACE, 2, TEXT(" Format type %hs"), GuidNames[pmtIn->formattype])); DbgLog((LOG_TRACE, 2, TEXT(" Subtype %hs"), GuidNames[pmtIn->subtype])); if ((pmtIn->subtype != MEDIASUBTYPE_MPEG1Packet) && (pmtIn->cbFormat >= sizeof(PCMWAVEFORMAT))) { /* Dump the contents of the WAVEFORMATEX type-specific format structure */ WAVEFORMATEX *pwfx = (WAVEFORMATEX *)pmtIn->pbFormat; DbgLog((LOG_TRACE, 2, TEXT("wFormatTag %u"), pwfx->wFormatTag)); DbgLog((LOG_TRACE, 2, TEXT("nChannels %u"), pwfx->nChannels)); DbgLog((LOG_TRACE, 2, TEXT("nSamplesPerSec %lu"), pwfx->nSamplesPerSec)); DbgLog((LOG_TRACE, 2, TEXT("nAvgBytesPerSec %lu"), pwfx->nAvgBytesPerSec)); DbgLog((LOG_TRACE, 2, TEXT("nBlockAlign %u"), pwfx->nBlockAlign)); DbgLog((LOG_TRACE, 2, TEXT("wBitsPerSample %u"), pwfx->wBitsPerSample)); /* PCM uses a WAVEFORMAT and does not have the extra size field */ if (pmtIn->cbFormat >= sizeof(WAVEFORMATEX)) { DbgLog((LOG_TRACE, 2, TEXT("cbSize %u"), pwfx->cbSize)); } } else { } } else { DbgLog((LOG_TRACE, 2, TEXT(" Format type %hs"), GuidNames[pmtIn->formattype])); } } void DisplayBITMAPINFO(const BITMAPINFOHEADER *pbmi) { DbgLog((LOG_TRACE, 5, TEXT("Size of BITMAPINFO structure %d"), pbmi->biSize)); if (pbmi->biCompression < 256) { DbgLog((LOG_TRACE, 2, TEXT("%dx%dx%d bit (%d)"), pbmi->biWidth, pbmi->biHeight, pbmi->biBitCount, pbmi->biCompression)); } else { DbgLog((LOG_TRACE, 2, TEXT("%dx%dx%d bit '%4.4hs'"), pbmi->biWidth, pbmi->biHeight, pbmi->biBitCount, &pbmi->biCompression)); } DbgLog((LOG_TRACE, 2, TEXT("Image size %d"), pbmi->biSizeImage)); DbgLog((LOG_TRACE, 5, TEXT("Planes %d"), pbmi->biPlanes)); DbgLog((LOG_TRACE, 5, TEXT("X Pels per metre %d"), pbmi->biXPelsPerMeter)); DbgLog((LOG_TRACE, 5, TEXT("Y Pels per metre %d"), pbmi->biYPelsPerMeter)); DbgLog((LOG_TRACE, 5, TEXT("Colours used %d"), pbmi->biClrUsed)); } void DisplayRECT(LPCTSTR szLabel, const RECT &rc) { DbgLog( (LOG_TRACE, 5, TEXT("%s (Left %d Top %d Right %d Bottom %d)"), szLabel, rc.left, rc.top, rc.right, rc.bottom)); } void WINAPI DumpGraph(IFilterGraph *pGraph, DWORD dwLevel) { if (!pGraph) { return; } IEnumFilters *pFilters; DbgLog((LOG_TRACE, dwLevel, TEXT("DumpGraph [%x]"), pGraph)); if (FAILED(pGraph->EnumFilters(&pFilters))) { DbgLog((LOG_TRACE, dwLevel, TEXT("EnumFilters failed!"))); } IBaseFilter *pFilter; ULONG n; while (pFilters->Next(1, &pFilter, &n) == S_OK) { FILTER_INFO info; if (FAILED(pFilter->QueryFilterInfo(&info))) { DbgLog((LOG_TRACE, dwLevel, TEXT(" Filter [%p] -- failed QueryFilterInfo"), pFilter)); } else { QueryFilterInfoReleaseGraph(info); // !!! should QueryVendorInfo here! DbgLog((LOG_TRACE, dwLevel, TEXT(" Filter [%p] '%ls'"), pFilter, info.achName)); IEnumPins *pins; if (FAILED(pFilter->EnumPins(&pins))) { DbgLog((LOG_TRACE, dwLevel, TEXT("EnumPins failed!"))); } else { IPin *pPin; while (pins->Next(1, &pPin, &n) == S_OK) { PIN_INFO pinInfo; if (FAILED(pPin->QueryPinInfo(&pinInfo))) { DbgLog((LOG_TRACE, dwLevel, TEXT(" Pin [%x] -- failed QueryPinInfo"), pPin)); } else { QueryPinInfoReleaseFilter(pinInfo); IPin *pPinConnected = NULL; HRESULT hr = pPin->ConnectedTo(&pPinConnected); if (pPinConnected) { DbgLog((LOG_TRACE, dwLevel, TEXT(" Pin [%p] '%ls' [%sput]") TEXT(" Connected to pin [%p]"), pPin, pinInfo.achName, pinInfo.dir == PINDIR_INPUT ? TEXT("In") : TEXT("Out"), pPinConnected)); pPinConnected->Release(); // perhaps we should really dump the type both ways as a sanity // check? if (pinInfo.dir == PINDIR_OUTPUT) { AM_MEDIA_TYPE mt; hr = pPin->ConnectionMediaType(&mt); if (SUCCEEDED(hr)) { DisplayType(TEXT("Connection type"), &mt); FreeMediaType(mt); } } } else { DbgLog((LOG_TRACE, dwLevel, TEXT(" Pin [%x] '%ls' [%sput]"), pPin, pinInfo.achName, pinInfo.dir == PINDIR_INPUT ? TEXT("In") : TEXT("Out"))); } } pPin->Release(); } pins->Release(); } } pFilter->Release(); } pFilters->Release(); } #endif ================================================ FILE: common/baseclasses/wxdebug.h ================================================ //------------------------------------------------------------------------------ // File: WXDebug.h // // Desc: DirectShow base classes - provides debugging facilities. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __WXDEBUG__ #define __WXDEBUG__ // This library provides fairly straight forward debugging functionality, this // is split into two main sections. The first is assertion handling, there are // three types of assertions provided here. The most commonly used one is the // ASSERT(condition) macro which will pop up a message box including the file // and line number if the condition evaluates to FALSE. Then there is the // EXECUTE_ASSERT macro which is the same as ASSERT except the condition will // still be executed in NON debug builds. The final type of assertion is the // KASSERT macro which is more suitable for pure (perhaps kernel) filters as // the condition is printed onto the debugger rather than in a message box. // // The other part of the debug module facilties is general purpose logging. // This is accessed by calling DbgLog(). The function takes a type and level // field which define the type of informational string you are presenting and // it's relative importance. The type field can be a combination (one or more) // of LOG_TIMING, LOG_TRACE, LOG_MEMORY, LOG_LOCKING and LOG_ERROR. The level // is a DWORD value where zero defines highest important. Use of zero as the // debug logging level is to be encouraged ONLY for major errors or events as // they will ALWAYS be displayed on the debugger. Other debug output has it's // level matched against the current debug output level stored in the registry // for this module and if less than the current setting it will be displayed. // // Each module or executable has it's own debug output level for each of the // five types. These are read in when the DbgInitialise function is called // for DLLs linking to STRMBASE.LIB this is done automatically when the DLL // is loaded, executables must call it explicitely with the module instance // handle given to them through the WINMAIN entry point. An executable must // also call DbgTerminate when they have finished to clean up the resources // the debug library uses, once again this is done automatically for DLLs // These are the five different categories of logging information enum { LOG_TIMING = 0x01, // Timing and performance measurements LOG_TRACE = 0x02, // General step point call tracing LOG_MEMORY = 0x04, // Memory and object allocation/destruction LOG_LOCKING = 0x08, // Locking/unlocking of critical sections LOG_ERROR = 0x10, // Debug error notification LOG_CUSTOM1 = 0x20, LOG_CUSTOM2 = 0x40, LOG_CUSTOM3 = 0x80, LOG_CUSTOM4 = 0x100, LOG_CUSTOM5 = 0x200, }; #define LOG_FORCIBLY_SET 0x80000000 enum { CDISP_HEX = 0x01, CDISP_DEC = 0x02 }; // For each object created derived from CBaseObject (in debug builds) we // create a descriptor that holds it's name (statically allocated memory) // and a cookie we assign it. We keep a list of all the active objects // we have registered so that we can dump a list of remaining objects typedef struct tag_ObjectDesc { LPCSTR m_szName; LPCWSTR m_wszName; DWORD m_dwCookie; tag_ObjectDesc *m_pNext; } ObjectDesc; #define DLLIMPORT __declspec(dllimport) #define DLLEXPORT __declspec(dllexport) #ifdef DEBUG #define NAME(x) TEXT(x) // These are used internally by the debug library (PRIVATE) void WINAPI DbgInitKeyLevels(HKEY hKey, bool fTakeMax); void WINAPI DbgInitGlobalSettings(bool fTakeMax); void WINAPI DbgInitModuleSettings(bool fTakeMax); void WINAPI DbgInitModuleName(); DWORD WINAPI DbgRegisterObjectCreation(LPCSTR szObjectName, LPCWSTR wszObjectName); BOOL WINAPI DbgRegisterObjectDestruction(DWORD dwCookie); // These are the PUBLIC entry points BOOL WINAPI DbgCheckModuleLevel(DWORD Type, DWORD Level); void WINAPI DbgSetModuleLevel(DWORD Type, DWORD Level); void WINAPI DbgSetAutoRefreshLevels(bool fAuto); // Initialise the library with the module handle void WINAPI DbgInitialise(HINSTANCE hInst); void WINAPI DbgTerminate(); void WINAPI DbgDumpObjectRegister(); // Display error and logging to the user void WINAPI DbgAssert(LPCTSTR pCondition, LPCTSTR pFileName, INT iLine); void WINAPI DbgBreakPoint(LPCTSTR pCondition, LPCTSTR pFileName, INT iLine); void WINAPI DbgBreakPoint(LPCTSTR pFileName, INT iLine, __format_string LPCTSTR szFormatString, ...); void WINAPI DbgKernelAssert(LPCTSTR pCondition, LPCTSTR pFileName, INT iLine); void WINAPI DbgLogInfo(DWORD Type, DWORD Level, __format_string LPCTSTR pFormat, ...); #ifdef UNICODE void WINAPI DbgLogInfo(DWORD Type, DWORD Level, __format_string LPCSTR pFormat, ...); void WINAPI DbgAssert(LPCSTR pCondition, LPCSTR pFileName, INT iLine); void WINAPI DbgBreakPoint(LPCSTR pCondition, LPCSTR pFileName, INT iLine); void WINAPI DbgKernelAssert(LPCSTR pCondition, LPCSTR pFileName, INT iLine); #endif void WINAPI DbgOutString(LPCTSTR psz); // Debug infinite wait stuff DWORD WINAPI DbgWaitForSingleObject(HANDLE h); DWORD WINAPI DbgWaitForMultipleObjects(DWORD nCount, __in_ecount(nCount) CONST HANDLE *lpHandles, BOOL bWaitAll); void WINAPI DbgSetWaitTimeout(DWORD dwTimeout); #ifdef __strmif_h__ // Display a media type: Terse at level 2, verbose at level 5 void WINAPI DisplayType(LPCTSTR label, const AM_MEDIA_TYPE *pmtIn); // Dump lots of information about a filter graph void WINAPI DumpGraph(IFilterGraph *pGraph, DWORD dwLevel); #endif #define KASSERT(_x_) \ if (!(_x_)) \ DbgKernelAssert(TEXT(#_x_), TEXT(__FILE__), __LINE__) // Break on the debugger without putting up a message box // message goes to debugger instead #define KDbgBreak(_x_) DbgKernelAssert(TEXT(#_x_), TEXT(__FILE__), __LINE__) // We chose a common name for our ASSERT macro, MFC also uses this name // So long as the implementation evaluates the condition and handles it // then we will be ok. Rather than override the behaviour expected we // will leave whatever first defines ASSERT as the handler (i.e. MFC) #ifndef ASSERT #define ASSERT(_x_) \ if (!(_x_)) \ DbgAssert(TEXT(#_x_), TEXT(__FILE__), __LINE__) #endif #define DbgAssertAligned(_ptr_, _alignment_) ASSERT(((DWORD_PTR)(_ptr_)) % (_alignment_) == 0) // Put up a message box informing the user of a halt // condition in the program #define DbgBreak(_x_) DbgBreakPoint(TEXT(#_x_), TEXT(__FILE__), __LINE__) #define EXECUTE_ASSERT(_x_) ASSERT(_x_) #define DbgLog(_x_) DbgLogInfo _x_ // MFC style trace macros #define NOTE(_x_) DbgLog((LOG_TRACE, 5, TEXT(_x_))) #define NOTE1(_x_, a) DbgLog((LOG_TRACE, 5, TEXT(_x_), a)) #define NOTE2(_x_, a, b) DbgLog((LOG_TRACE, 5, TEXT(_x_), a, b)) #define NOTE3(_x_, a, b, c) DbgLog((LOG_TRACE, 5, TEXT(_x_), a, b, c)) #define NOTE4(_x_, a, b, c, d) DbgLog((LOG_TRACE, 5, TEXT(_x_), a, b, c, d)) #define NOTE5(_x_, a, b, c, d, e) DbgLog((LOG_TRACE, 5, TEXT(_x_), a, b, c, d, e)) #else // Retail builds make public debug functions inert - WARNING the source // files do not define or build any of the entry points in debug builds // (public entry points compile to nothing) so if you go trying to call // any of the private entry points in your source they won't compile #define NAME(_x_) ((LPTSTR)NULL) #define DbgInitialise(hInst) #define DbgTerminate() #define DbgLog(_x_) 0 #define DbgOutString(psz) #define DbgAssertAligned(_ptr_, _alignment_) 0 #define DbgRegisterObjectCreation(pObjectName) #define DbgRegisterObjectDestruction(dwCookie) #define DbgDumpObjectRegister() #define DbgCheckModuleLevel(Type, Level) #define DbgSetModuleLevel(Type, Level) #define DbgSetAutoRefreshLevels(fAuto) #define DbgWaitForSingleObject(h) WaitForSingleObject(h, INFINITE) #define DbgWaitForMultipleObjects(nCount, lpHandles, bWaitAll) \ WaitForMultipleObjects(nCount, lpHandles, bWaitAll, INFINITE) #define DbgSetWaitTimeout(dwTimeout) #define KDbgBreak(_x_) #define DbgBreak(_x_) #define KASSERT(_x_) ((void)0) #ifndef ASSERT #define ASSERT(_x_) ((void)0) #endif #define EXECUTE_ASSERT(_x_) ((void)(_x_)) // MFC style trace macros #define NOTE(_x_) ((void)0) #define NOTE1(_x_, a) ((void)0) #define NOTE2(_x_, a, b) ((void)0) #define NOTE3(_x_, a, b, c) ((void)0) #define NOTE4(_x_, a, b, c, d) ((void)0) #define NOTE5(_x_, a, b, c, d, e) ((void)0) #define DisplayType(label, pmtIn) ((void)0) #define DumpGraph(pGraph, label) ((void)0) #endif // Checks a pointer which should be non NULL - can be used as follows. #define CheckPointer(p, ret) \ { \ if ((p) == NULL) \ return (ret); \ } // HRESULT Foo(VOID *pBar) // { // CheckPointer(pBar,E_INVALIDARG) // } // // Or if the function returns a boolean // // BOOL Foo(VOID *pBar) // { // CheckPointer(pBar,FALSE) // } #define ValidateReadPtr(p, cb) 0 #define ValidateWritePtr(p, cb) 0 #define ValidateReadWritePtr(p, cb) 0 #define ValidateStringPtr(p) 0 #define ValidateStringPtrA(p) 0 #define ValidateStringPtrW(p) 0 #ifdef _OBJBASE_H_ // Outputting GUID names. If you want to include the name // associated with a GUID (eg CLSID_...) then // // GuidNames[yourGUID] // // Returns the name defined in uuids.h as a string typedef struct { CHAR *szName; GUID guid; } GUID_STRING_ENTRY; class CGuidNameList { public: CHAR *operator[](const GUID &guid); }; extern CGuidNameList GuidNames; #endif #ifndef REMIND // REMIND macro - generates warning as reminder to complete coding // (eg) usage: // // #pragma message (REMIND("Add automation support")) #define QUOTE(x) #x #define QQUOTE(y) QUOTE(y) #define REMIND(str) __FILE__ "(" QQUOTE(__LINE__) ") : " str #endif // Method to display objects in a useful format // // eg If you want to display a LONGLONG ll in a debug string do (eg) // // DbgLog((LOG_TRACE, n, TEXT("Value is %s"), (LPCTSTR)CDisp(ll, CDISP_HEX))); class CDispBasic { public: CDispBasic() { m_pString = m_String; }; ~CDispBasic(); protected: PTCHAR m_pString; // normally points to m_String... unless too much data TCHAR m_String[50]; }; class CDisp : public CDispBasic { public: CDisp(LONGLONG ll, int Format = CDISP_HEX); // Display a LONGLONG in CDISP_HEX or CDISP_DEC form CDisp(REFCLSID clsid); // Display a GUID CDisp(double d); // Display a floating point number #ifdef __strmif_h__ #ifdef __STREAMS__ CDisp(CRefTime t); // Display a Reference Time #endif CDisp(IPin *pPin); // Display a pin as {filter clsid}(pin name) CDisp(IUnknown *pUnk); // Display a filter or pin #endif // __strmif_h__ ~CDisp(); // Implement cast to (LPCTSTR) as parameter to logger operator LPCTSTR() { return (LPCTSTR)m_pString; }; }; #if defined(DEBUG) class CAutoTrace { private: LPCTSTR _szBlkName; const int _level; static const TCHAR _szEntering[]; static const TCHAR _szLeaving[]; public: CAutoTrace(LPCTSTR szBlkName, const int level = 15) : _szBlkName(szBlkName) , _level(level) { DbgLog((LOG_TRACE, _level, _szEntering, _szBlkName)); } ~CAutoTrace() { DbgLog((LOG_TRACE, _level, _szLeaving, _szBlkName)); } }; #if defined(__FUNCTION__) #define AMTRACEFN() CAutoTrace __trace(TEXT(__FUNCTION__)) #define AMTRACE(_x_) CAutoTrace __trace(TEXT(__FUNCTION__)) #else #define AMTRACE(_x_) CAutoTrace __trace _x_ #define AMTRACEFN() #endif #else #define AMTRACE(_x_) #define AMTRACEFN() #endif #endif // __WXDEBUG__ ================================================ FILE: common/baseclasses/wxlist.cpp ================================================ //------------------------------------------------------------------------------ // File: WXList.cpp // // Desc: DirectShow base classes - implements a non-MFC based generic list // template class. // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ /* A generic list of pointers to objects. Objectives: avoid using MFC libraries in ndm kernel mode and provide a really useful list type. The class is thread safe in that separate threads may add and delete items in the list concurrently although the application must ensure that constructor and destructor access is suitably synchronised. The list name must not conflict with MFC classes as an application may use both The nodes form a doubly linked, NULL terminated chain with an anchor block (the list object per se) holding pointers to the first and last nodes and a count of the nodes. There is a node cache to reduce the allocation and freeing overhead. It optionally (determined at construction time) has an Event which is set whenever the list becomes non-empty and reset whenever it becomes empty. It optionally (determined at construction time) has a Critical Section which is entered during the important part of each operation. (About all you can do outside it is some parameter checking). The node cache is a repository of nodes that are NOT in the list to speed up storage allocation. Each list has its own cache to reduce locking and serialising. The list accesses are serialised anyway for a given list - a common cache would mean that we would have to separately serialise access of all lists within the cache. Because the cache only stores nodes that are not in the list, releasing the cache does not release any list nodes. This means that list nodes can be copied or rechained from one list to another without danger of creating a dangling reference if the original cache goes away. Questionable design decisions: 1. Retaining the warts for compatibility 2. Keeping an element count -i.e. counting whenever we do anything instead of only when we want the count. 3. Making the chain pointers NULL terminated. If the list object itself looks just like a node and the list is kept as a ring then it reduces the number of special cases. All inserts look the same. */ #include /* set cursor to the position of each element of list in turn */ #define INTERNALTRAVERSELIST(list, cursor) \ for (cursor = (list).GetHeadPositionI(); cursor != NULL; cursor = (list).Next(cursor)) /* set cursor to the position of each element of list in turn in reverse order */ #define INTERNALREVERSETRAVERSELIST(list, cursor) \ for (cursor = (list).GetTailPositionI(); cursor != NULL; cursor = (list).Prev(cursor)) /* Constructor calls a separate initialisation function that creates a node cache, optionally creates a lock object and optionally creates a signaling object. By default we create a locking object, a DEFAULTCACHE sized cache but no event object so the list cannot be used in calls to WaitForSingleObject */ CBaseList::CBaseList(__in_opt LPCTSTR pName, // Descriptive list name INT iItems) : // Node cache size #ifdef DEBUG CBaseObject(pName) , #endif m_pFirst(NULL) , m_pLast(NULL) , m_Count(0) , m_Cache(iItems) { } // constructor CBaseList::CBaseList(__in_opt LPCTSTR pName) : // Descriptive list name #ifdef DEBUG CBaseObject(pName) , #endif m_pFirst(NULL) , m_pLast(NULL) , m_Count(0) , m_Cache(DEFAULTCACHE) { } // constructor #ifdef UNICODE CBaseList::CBaseList(__in_opt LPCSTR pName, // Descriptive list name INT iItems) : // Node cache size #ifdef DEBUG CBaseObject(pName) , #endif m_pFirst(NULL) , m_pLast(NULL) , m_Count(0) , m_Cache(iItems) { } // constructor CBaseList::CBaseList(__in_opt LPCSTR pName) : // Descriptive list name #ifdef DEBUG CBaseObject(pName) , #endif m_pFirst(NULL) , m_pLast(NULL) , m_Count(0) , m_Cache(DEFAULTCACHE) { } // constructor #endif /* The destructor enumerates all the node objects in the list and in the cache deleting each in turn. We do not do any processing on the objects that the list holds (i.e. points to) so if they represent interfaces for example the creator of the list should ensure that each of them is released before deleting us */ CBaseList::~CBaseList() { /* Delete all our list nodes */ RemoveAll(); } // destructor /* Remove all the nodes from the list but don't do anything with the objects that each node looks after (this is the responsibility of the creator). Aa a last act we reset the signalling event (if available) to indicate to clients that the list does not have any entries in it. */ void CBaseList::RemoveAll() { /* Free up all the CNode objects NOTE we don't bother putting the deleted nodes into the cache as this method is only really called in serious times of change such as when we are being deleted at which point the cache will be deleted anway */ CNode *pn = m_pFirst; while (pn) { CNode *op = pn; pn = pn->Next(); delete op; } /* Reset the object count and the list pointers */ m_Count = 0; m_pFirst = m_pLast = NULL; } // RemoveAll /* Return a position enumerator for the entire list. A position enumerator is a pointer to a node object cast to a transparent type so all we do is return the head/tail node pointer in the list. WARNING because the position is a pointer to a node there is an implicit assumption for users a the list class that after deleting an object from the list that any other position enumerators that you have may be invalid (since the node may be gone). */ __out_opt POSITION CBaseList::GetHeadPositionI() const { return (POSITION)m_pFirst; } // GetHeadPosition __out_opt POSITION CBaseList::GetTailPositionI() const { return (POSITION)m_pLast; } // GetTailPosition /* Get the number of objects in the list, Get the lock before accessing the count. Locking may not be entirely necessary but it has the side effect of making sure that all operations are complete before we get it. So for example if a list is being added to this list then that will have completed in full before we continue rather than seeing an intermediate albeit valid state */ int CBaseList::GetCountI() const { return m_Count; } // GetCount /* Return the object at rp, update rp to the next object from the list or NULL if you have moved over the last object. You may still call this function once we return NULL but we will continue to return a NULL position value */ __out void *CBaseList::GetNextI(__inout POSITION &rp) const { /* have we reached the end of the list */ if (rp == NULL) { return NULL; } /* Lock the object before continuing */ void *pObject; /* Copy the original position then step on */ CNode *pn = (CNode *)rp; ASSERT(pn != NULL); rp = (POSITION)pn->Next(); /* Get the object at the original position from the list */ pObject = pn->GetData(); // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. return pObject; } // GetNext /* Return the object at p. Asking for the object at NULL ASSERTs then returns NULL The object is NOT locked. The list is not being changed in any way. If another thread is busy deleting the object then locking would only result in a change from one bad behaviour to another. */ __out_opt void *CBaseList::GetI(__in_opt POSITION p) const { if (p == NULL) { return NULL; } CNode *pn = (CNode *)p; void *pObject = pn->GetData(); // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. return pObject; } // Get __out void *CBaseList::GetValidI(__in POSITION p) const { CNode *pn = (CNode *)p; void *pObject = pn->GetData(); // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. return pObject; } // Get /* Return the first position in the list which holds the given pointer. Return NULL if it's not found. */ __out_opt POSITION CBaseList::FindI(__in void *pObj) const { POSITION pn; INTERNALTRAVERSELIST(*this, pn) { if (GetI(pn) == pObj) { return pn; } } return NULL; } // Find /* Remove the first node in the list (deletes the pointer to its object from the list, does not free the object itself). Return the pointer to its object or NULL if empty */ __out_opt void *CBaseList::RemoveHeadI() { /* All we do is get the head position and ask for that to be deleted. We could special case this since some of the code path checking in Remove() is redundant as we know there is no previous node for example but it seems to gain little over the added complexity */ return RemoveI((POSITION)m_pFirst); } // RemoveHead /* Remove the last node in the list (deletes the pointer to its object from the list, does not free the object itself). Return the pointer to its object or NULL if empty */ __out_opt void *CBaseList::RemoveTailI() { /* All we do is get the tail position and ask for that to be deleted. We could special case this since some of the code path checking in Remove() is redundant as we know there is no previous node for example but it seems to gain little over the added complexity */ return RemoveI((POSITION)m_pLast); } // RemoveTail /* Remove the pointer to the object in this position from the list. Deal with all the chain pointers Return a pointer to the object removed from the list. The node object that is freed as a result of this operation is added to the node cache where it can be used again. Remove(NULL) is a harmless no-op - but probably is a wart. */ __out_opt void *CBaseList::RemoveI(__in_opt POSITION pos) { /* Lock the critical section before continuing */ // ASSERT (pos!=NULL); // Removing NULL is to be harmless! if (pos == NULL) return NULL; CNode *pCurrent = (CNode *)pos; ASSERT(pCurrent != NULL); /* Update the previous node */ CNode *pNode = pCurrent->Prev(); if (pNode == NULL) { m_pFirst = pCurrent->Next(); } else { pNode->SetNext(pCurrent->Next()); } /* Update the following node */ pNode = pCurrent->Next(); if (pNode == NULL) { m_pLast = pCurrent->Prev(); } else { pNode->SetPrev(pCurrent->Prev()); } /* Get the object this node was looking after */ void *pObject = pCurrent->GetData(); // ASSERT(pObject != NULL); // NULL pointers in the list are allowed. /* Try and add the node object to the cache - a NULL return code from the cache means we ran out of room. The cache size is fixed by a constructor argument when the list is created and defaults to DEFAULTCACHE. This means that the cache will have room for this many node objects. So if you have a list of media samples and you know there will never be more than five active at any given time of them for example then override the default constructor */ m_Cache.AddToCache(pCurrent); /* If the list is empty then reset the list event */ --m_Count; ASSERT(m_Count >= 0); return pObject; } // Remove /* Add this object to the tail end of our list Return the new tail position. */ __out_opt POSITION CBaseList::AddTailI(__in void *pObject) { /* Lock the critical section before continuing */ CNode *pNode; // ASSERT(pObject); // NULL pointers in the list are allowed. /* If there is a node objects in the cache then use that otherwise we will have to create a new one */ pNode = (CNode *)m_Cache.RemoveFromCache(); if (pNode == NULL) { pNode = new CNode; } /* Check we have a valid object */ if (pNode == NULL) { return NULL; } /* Initialise all the CNode object just in case it came from the cache */ pNode->SetData(pObject); pNode->SetNext(NULL); pNode->SetPrev(m_pLast); if (m_pLast == NULL) { m_pFirst = pNode; } else { m_pLast->SetNext(pNode); } /* Set the new last node pointer and also increment the number of list entries, the critical section is unlocked when we exit the function */ m_pLast = pNode; ++m_Count; return (POSITION)pNode; } // AddTail(object) /* Add this object to the head end of our list Return the new head position. */ __out_opt POSITION CBaseList::AddHeadI(__in void *pObject) { CNode *pNode; // ASSERT(pObject); // NULL pointers in the list are allowed. /* If there is a node objects in the cache then use that otherwise we will have to create a new one */ pNode = (CNode *)m_Cache.RemoveFromCache(); if (pNode == NULL) { pNode = new CNode; } /* Check we have a valid object */ if (pNode == NULL) { return NULL; } /* Initialise all the CNode object just in case it came from the cache */ pNode->SetData(pObject); /* chain it in (set four pointers) */ pNode->SetPrev(NULL); pNode->SetNext(m_pFirst); if (m_pFirst == NULL) { m_pLast = pNode; } else { m_pFirst->SetPrev(pNode); } m_pFirst = pNode; ++m_Count; return (POSITION)pNode; } // AddHead(object) /* Add all the elements in *pList to the tail of this list. Return TRUE if it all worked, FALSE if it didn't. If it fails some elements may have been added. */ BOOL CBaseList::AddTail(__in CBaseList *pList) { /* lock the object before starting then enumerate each entry in the source list and add them one by one to our list (while still holding the object lock) Lock the other list too. */ POSITION pos = pList->GetHeadPositionI(); while (pos) { if (NULL == AddTailI(pList->GetNextI(pos))) { return FALSE; } } return TRUE; } // AddTail(list) /* Add all the elements in *pList to the head of this list. Return TRUE if it all worked, FALSE if it didn't. If it fails some elements may have been added. */ BOOL CBaseList::AddHead(__in CBaseList *pList) { /* lock the object before starting then enumerate each entry in the source list and add them one by one to our list (while still holding the object lock) Lock the other list too. To avoid reversing the list, traverse it backwards. */ POSITION pos; INTERNALREVERSETRAVERSELIST(*pList, pos) { if (NULL == AddHeadI(pList->GetValidI(pos))) { return FALSE; } } return TRUE; } // AddHead(list) /* Add the object after position p p is still valid after the operation. AddAfter(NULL,x) adds x to the start - same as AddHead Return the position of the new object, NULL if it failed */ __out_opt POSITION CBaseList::AddAfterI(__in_opt POSITION pos, __in void *pObj) { if (pos == NULL) return AddHeadI(pObj); /* As someone else might be furkling with the list - Lock the critical section before continuing */ CNode *pAfter = (CNode *)pos; ASSERT(pAfter != NULL); if (pAfter == m_pLast) return AddTailI(pObj); /* set pnode to point to a new node, preferably from the cache */ CNode *pNode = (CNode *)m_Cache.RemoveFromCache(); if (pNode == NULL) { pNode = new CNode; } /* Check we have a valid object */ if (pNode == NULL) { return NULL; } /* Initialise all the CNode object just in case it came from the cache */ pNode->SetData(pObj); /* It is to be added to the middle of the list - there is a before and after node. Chain it after pAfter, before pBefore. */ CNode *pBefore = pAfter->Next(); ASSERT(pBefore != NULL); /* chain it in (set four pointers) */ pNode->SetPrev(pAfter); pNode->SetNext(pBefore); pBefore->SetPrev(pNode); pAfter->SetNext(pNode); ++m_Count; return (POSITION)pNode; } // AddAfter(object) BOOL CBaseList::AddAfter(__in_opt POSITION p, __in CBaseList *pList) { POSITION pos; INTERNALTRAVERSELIST(*pList, pos) { /* p follows along the elements being added */ p = AddAfterI(p, pList->GetValidI(pos)); if (p == NULL) return FALSE; } return TRUE; } // AddAfter(list) /* Mirror images: Add the element or list after position p. p is still valid after the operation. AddBefore(NULL,x) adds x to the end - same as AddTail */ __out_opt POSITION CBaseList::AddBeforeI(__in_opt POSITION pos, __in void *pObj) { if (pos == NULL) return AddTailI(pObj); /* set pnode to point to a new node, preferably from the cache */ CNode *pBefore = (CNode *)pos; ASSERT(pBefore != NULL); if (pBefore == m_pFirst) return AddHeadI(pObj); CNode *pNode = (CNode *)m_Cache.RemoveFromCache(); if (pNode == NULL) { pNode = new CNode; } /* Check we have a valid object */ if (pNode == NULL) { return NULL; } /* Initialise all the CNode object just in case it came from the cache */ pNode->SetData(pObj); /* It is to be added to the middle of the list - there is a before and after node. Chain it after pAfter, before pBefore. */ CNode *pAfter = pBefore->Prev(); ASSERT(pAfter != NULL); /* chain it in (set four pointers) */ pNode->SetPrev(pAfter); pNode->SetNext(pBefore); pBefore->SetPrev(pNode); pAfter->SetNext(pNode); ++m_Count; return (POSITION)pNode; } // Addbefore(object) BOOL CBaseList::AddBefore(__in_opt POSITION p, __in CBaseList *pList) { POSITION pos; INTERNALREVERSETRAVERSELIST(*pList, pos) { /* p follows along the elements being added */ p = AddBeforeI(p, pList->GetValidI(pos)); if (p == NULL) return FALSE; } return TRUE; } // AddBefore(list) /* Split *this after position p in *this Retain as *this the tail portion of the original *this Add the head portion to the tail end of *pList Return TRUE if it all worked, FALSE if it didn't. e.g. foo->MoveToTail(foo->GetHeadPosition(), bar); moves one element from the head of foo to the tail of bar foo->MoveToTail(NULL, bar); is a no-op foo->MoveToTail(foo->GetTailPosition, bar); concatenates foo onto the end of bar and empties foo. A better, except excessively long name might be MoveElementsFromHeadThroughPositionToOtherTail */ BOOL CBaseList::MoveToTail(__in_opt POSITION pos, __in CBaseList *pList) { /* Algorithm: Note that the elements (including their order) in the concatenation of *pList to the head of *this is invariant. 1. Count elements to be moved 2. Join *pList onto the head of this to make one long chain 3. Set first/Last pointers in *this and *pList 4. Break the chain at the new place 5. Adjust counts 6. Set/Reset any events */ if (pos == NULL) return TRUE; // no-op. Eliminates special cases later. /* Make cMove the number of nodes to move */ CNode *p = (CNode *)pos; int cMove = 0; // number of nodes to move while (p != NULL) { p = p->Prev(); ++cMove; } /* Join the two chains together */ if (pList->m_pLast != NULL) pList->m_pLast->SetNext(m_pFirst); if (m_pFirst != NULL) m_pFirst->SetPrev(pList->m_pLast); /* set first and last pointers */ p = (CNode *)pos; if (pList->m_pFirst == NULL) pList->m_pFirst = m_pFirst; m_pFirst = p->Next(); if (m_pFirst == NULL) m_pLast = NULL; pList->m_pLast = p; /* Break the chain after p to create the new pieces */ if (m_pFirst != NULL) m_pFirst->SetPrev(NULL); p->SetNext(NULL); /* Adjust the counts */ m_Count -= cMove; pList->m_Count += cMove; return TRUE; } // MoveToTail /* Mirror image of MoveToTail: Split *this before position p in *this. Retain in *this the head portion of the original *this Add the tail portion to the start (i.e. head) of *pList Return TRUE if it all worked, FALSE if it didn't. e.g. foo->MoveToHead(foo->GetTailPosition(), bar); moves one element from the tail of foo to the head of bar foo->MoveToHead(NULL, bar); is a no-op foo->MoveToHead(foo->GetHeadPosition, bar); concatenates foo onto the start of bar and empties foo. */ BOOL CBaseList::MoveToHead(__in_opt POSITION pos, __in CBaseList *pList) { /* See the comments on the algorithm in MoveToTail */ if (pos == NULL) return TRUE; // no-op. Eliminates special cases later. /* Make cMove the number of nodes to move */ CNode *p = (CNode *)pos; int cMove = 0; // number of nodes to move while (p != NULL) { p = p->Next(); ++cMove; } /* Join the two chains together */ if (pList->m_pFirst != NULL) pList->m_pFirst->SetPrev(m_pLast); if (m_pLast != NULL) m_pLast->SetNext(pList->m_pFirst); /* set first and last pointers */ p = (CNode *)pos; if (pList->m_pLast == NULL) pList->m_pLast = m_pLast; m_pLast = p->Prev(); if (m_pLast == NULL) m_pFirst = NULL; pList->m_pFirst = p; /* Break the chain after p to create the new pieces */ if (m_pLast != NULL) m_pLast->SetNext(NULL); p->SetPrev(NULL); /* Adjust the counts */ m_Count -= cMove; pList->m_Count += cMove; return TRUE; } // MoveToHead /* Reverse the order of the [pointers to] objects in *this */ void CBaseList::Reverse() { /* algorithm: The obvious booby trap is that you flip pointers around and lose addressability to the node that you are going to process next. The easy way to avoid this is do do one chain at a time. Run along the forward chain, For each node, set the reverse pointer to the one ahead of us. The reverse chain is now a copy of the old forward chain, including the NULL termination. Run along the reverse chain (i.e. old forward chain again) For each node set the forward pointer of the node ahead to point back to the one we're standing on. The first node needs special treatment, it's new forward pointer is NULL. Finally set the First/Last pointers */ CNode *p; // Yes we COULD use a traverse, but it would look funny! p = m_pFirst; while (p != NULL) { CNode *q; q = p->Next(); p->SetNext(p->Prev()); p->SetPrev(q); p = q; } p = m_pFirst; m_pFirst = m_pLast; m_pLast = p; #if 0 // old version if (m_pFirst==NULL) return; // empty list if (m_pFirst->Next()==NULL) return; // single node list /* run along forward chain */ for ( p = m_pFirst ; p!=NULL ; p = p->Next() ){ p->SetPrev(p->Next()); } /* special case first element */ m_pFirst->SetNext(NULL); // fix the old first element /* run along new reverse chain i.e. old forward chain again */ for ( p = m_pFirst // start at the old first element ; p->Prev()!=NULL // while there's a node still to be set ; p = p->Prev() // work in the same direction as before ){ p->Prev()->SetNext(p); } /* fix forward and reverse pointers - the triple XOR swap would work but all the casts look hideous */ p = m_pFirst; m_pFirst = m_pLast; m_pLast = p; #endif } // Reverse ================================================ FILE: common/baseclasses/wxlist.h ================================================ //------------------------------------------------------------------------------ // File: WXList.h // // Desc: DirectShow base classes - defines a non-MFC generic template list // class. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ /* A generic list of pointers to objects. No storage management or copying is done on the objects pointed to. Objectives: avoid using MFC libraries in ndm kernel mode and provide a really useful list type. The class is thread safe in that separate threads may add and delete items in the list concurrently although the application must ensure that constructor and destructor access is suitably synchronised. An application can cause deadlock with operations which use two lists by simultaneously calling list1->Operation(list2) and list2->Operation(list1). So don't! The names must not conflict with MFC classes as an application may use both. */ #ifndef __WXLIST__ #define __WXLIST__ /* A POSITION represents (in some fashion that's opaque) a cursor on the list that can be set to identify any element. NULL is a valid value and several operations regard NULL as the position "one step off the end of the list". (In an n element list there are n+1 places to insert and NULL is that "n+1-th" value). The POSITION of an element in the list is only invalidated if that element is deleted. Move operations may mean that what was a valid POSITION in one list is now a valid POSITION in a different list. Some operations which at first sight are illegal are allowed as harmless no-ops. For instance RemoveHead is legal on an empty list and it returns NULL. This allows an atomic way to test if there is an element there, and if so, get it. The two operations AddTail and RemoveHead thus implement a MONITOR (See Hoare's paper). Single element operations return POSITIONs, non-NULL means it worked. whole list operations return a BOOL. TRUE means it all worked. This definition is the same as the POSITION type for MFCs, so we must avoid defining it twice. */ #ifndef __AFX_H__ struct __POSITION { int unused; }; typedef __POSITION *POSITION; #endif const int DEFAULTCACHE = 10; /* Default node object cache size */ /* A class representing one node in a list. Each node knows a pointer to it's adjacent nodes and also a pointer to the object that it looks after. All of these pointers can be retrieved or set through member functions. */ class CBaseList #ifdef DEBUG : public CBaseObject #endif { /* Making these classes inherit from CBaseObject does nothing functionally but it allows us to check there are no memory leaks in debug builds. */ public: #ifdef DEBUG class CNode : public CBaseObject { #else class CNode { #endif CNode *m_pPrev; /* Previous node in the list */ CNode *m_pNext; /* Next node in the list */ void *m_pObject; /* Pointer to the object */ public: /* Constructor - initialise the object's pointers */ CNode() #ifdef DEBUG : CBaseObject(NAME("List node")) #endif {}; /* Return the previous node before this one */ __out CNode *Prev() const { return m_pPrev; }; /* Return the next node after this one */ __out CNode *Next() const { return m_pNext; }; /* Set the previous node before this one */ void SetPrev(__in_opt CNode *p) { m_pPrev = p; }; /* Set the next node after this one */ void SetNext(__in_opt CNode *p) { m_pNext = p; }; /* Get the pointer to the object for this node */ __out void *GetData() const { return m_pObject; }; /* Set the pointer to the object for this node */ void SetData(__in void *p) { m_pObject = p; }; }; class CNodeCache { public: CNodeCache(INT iCacheSize) : m_iCacheSize(iCacheSize) , m_pHead(NULL) , m_iUsed(0){}; ~CNodeCache() { CNode *pNode = m_pHead; while (pNode) { CNode *pCurrent = pNode; pNode = pNode->Next(); delete pCurrent; } }; void AddToCache(__inout CNode *pNode) { if (m_iUsed < m_iCacheSize) { pNode->SetNext(m_pHead); m_pHead = pNode; m_iUsed++; } else { delete pNode; } }; CNode *RemoveFromCache() { CNode *pNode = m_pHead; if (pNode != NULL) { m_pHead = pNode->Next(); m_iUsed--; ASSERT(m_iUsed >= 0); } else { ASSERT(m_iUsed == 0); } return pNode; }; private: INT m_iCacheSize; INT m_iUsed; CNode *m_pHead; }; protected: CNode *m_pFirst; /* Pointer to first node in the list */ CNode *m_pLast; /* Pointer to the last node in the list */ LONG m_Count; /* Number of nodes currently in the list */ private: CNodeCache m_Cache; /* Cache of unused node pointers */ private: /* These override the default copy constructor and assignment operator for all list classes. They are in the private class declaration section so that anybody trying to pass a list object by value will generate a compile time error of "cannot access the private member function". If these were not here then the compiler will create default constructors and assignment operators which when executed first take a copy of all member variables and then during destruction delete them all. This must not be done for any heap allocated data. */ CBaseList(const CBaseList &refList); CBaseList &operator=(const CBaseList &refList); public: CBaseList(__in_opt LPCTSTR pName, INT iItems); CBaseList(__in_opt LPCTSTR pName); #ifdef UNICODE CBaseList(__in_opt LPCSTR pName, INT iItems); CBaseList(__in_opt LPCSTR pName); #endif ~CBaseList(); /* Remove all the nodes from *this i.e. make the list empty */ void RemoveAll(); /* Return a cursor which identifies the first element of *this */ __out_opt POSITION GetHeadPositionI() const; /* Return a cursor which identifies the last element of *this */ __out_opt POSITION GetTailPositionI() const; /* Return the number of objects in *this */ int GetCountI() const; protected: /* Return the pointer to the object at rp, Update rp to the next node in *this but make it NULL if it was at the end of *this. This is a wart retained for backwards compatibility. GetPrev is not implemented. Use Next, Prev and Get separately. */ __out void *GetNextI(__inout POSITION &rp) const; /* Return a pointer to the object at p Asking for the object at NULL will return NULL harmlessly. */ __out_opt void *GetI(__in_opt POSITION p) const; __out void *GetValidI(__in POSITION p) const; public: /* return the next / prev position in *this return NULL when going past the end/start. Next(NULL) is same as GetHeadPosition() Prev(NULL) is same as GetTailPosition() An n element list therefore behaves like a n+1 element cycle with NULL at the start/end. !!WARNING!! - This handling of NULL is DIFFERENT from GetNext. Some reasons are: 1. For a list of n items there are n+1 positions to insert These are conveniently encoded as the n POSITIONs and NULL. 2. If you are keeping a list sorted (fairly common) and you search forward for an element to insert before and don't find it you finish up with NULL as the element before which to insert. You then want that NULL to be a valid POSITION so that you can insert before it and you want that insertion point to mean the (n+1)-th one that doesn't have a POSITION. (symmetrically if you are working backwards through the list). 3. It simplifies the algebra which the methods generate. e.g. AddBefore(p,x) is identical to AddAfter(Prev(p),x) in ALL cases. All the other arguments probably are reflections of the algebraic point. */ __out_opt POSITION Next(__in_opt POSITION pos) const { if (pos == NULL) { return (POSITION)m_pFirst; } CNode *pn = (CNode *)pos; return (POSITION)pn->Next(); } // Next // See Next __out_opt POSITION Prev(__in_opt POSITION pos) const { if (pos == NULL) { return (POSITION)m_pLast; } CNode *pn = (CNode *)pos; return (POSITION)pn->Prev(); } // Prev /* Return the first position in *this which holds the given pointer. Return NULL if the pointer was not not found. */ protected: __out_opt POSITION FindI(__in void *pObj) const; // ??? Should there be (or even should there be only) // ??? POSITION FindNextAfter(void * pObj, POSITION p) // ??? And of course FindPrevBefore too. // ??? List.Find(&Obj) then becomes List.FindNextAfter(&Obj, NULL) /* Remove the first node in *this (deletes the pointer to its object from the list, does not free the object itself). Return the pointer to its object. If *this was already empty it will harmlessly return NULL. */ __out_opt void *RemoveHeadI(); /* Remove the last node in *this (deletes the pointer to its object from the list, does not free the object itself). Return the pointer to its object. If *this was already empty it will harmlessly return NULL. */ __out_opt void *RemoveTailI(); /* Remove the node identified by p from the list (deletes the pointer to its object from the list, does not free the object itself). Asking to Remove the object at NULL will harmlessly return NULL. Return the pointer to the object removed. */ __out_opt void *RemoveI(__in_opt POSITION p); /* Add single object *pObj to become a new last element of the list. Return the new tail position, NULL if it fails. If you are adding a COM objects, you might want AddRef it first. Other existing POSITIONs in *this are still valid */ __out_opt POSITION AddTailI(__in void *pObj); public: /* Add all the elements in *pList to the tail of *this. This duplicates all the nodes in *pList (i.e. duplicates all its pointers to objects). It does not duplicate the objects. If you are adding a list of pointers to a COM object into the list it's a good idea to AddRef them all it when you AddTail it. Return TRUE if it all worked, FALSE if it didn't. If it fails some elements may have been added. Existing POSITIONs in *this are still valid If you actually want to MOVE the elements, use MoveToTail instead. */ BOOL AddTail(__in CBaseList *pList); /* Mirror images of AddHead: */ /* Add single object to become a new first element of the list. Return the new head position, NULL if it fails. Existing POSITIONs in *this are still valid */ protected: __out_opt POSITION AddHeadI(__in void *pObj); public: /* Add all the elements in *pList to the head of *this. Same warnings apply as for AddTail. Return TRUE if it all worked, FALSE if it didn't. If it fails some of the objects may have been added. If you actually want to MOVE the elements, use MoveToHead instead. */ BOOL AddHead(__in CBaseList *pList); /* Add the object *pObj to *this after position p in *this. AddAfter(NULL,x) adds x to the start - equivalent to AddHead Return the position of the object added, NULL if it failed. Existing POSITIONs in *this are undisturbed, including p. */ protected: __out_opt POSITION AddAfterI(__in_opt POSITION p, __in void *pObj); public: /* Add the list *pList to *this after position p in *this AddAfter(NULL,x) adds x to the start - equivalent to AddHead Return TRUE if it all worked, FALSE if it didn't. If it fails, some of the objects may be added Existing POSITIONs in *this are undisturbed, including p. */ BOOL AddAfter(__in_opt POSITION p, __in CBaseList *pList); /* Mirror images: Add the object *pObj to this-List after position p in *this. AddBefore(NULL,x) adds x to the end - equivalent to AddTail Return the position of the new object, NULL if it fails Existing POSITIONs in *this are undisturbed, including p. */ protected: __out_opt POSITION AddBeforeI(__in_opt POSITION p, __in void *pObj); public: /* Add the list *pList to *this before position p in *this AddAfter(NULL,x) adds x to the start - equivalent to AddHead Return TRUE if it all worked, FALSE if it didn't. If it fails, some of the objects may be added Existing POSITIONs in *this are undisturbed, including p. */ BOOL AddBefore(__in_opt POSITION p, __in CBaseList *pList); /* Note that AddAfter(p,x) is equivalent to AddBefore(Next(p),x) even in cases where p is NULL or Next(p) is NULL. Similarly for mirror images etc. This may make it easier to argue about programs. */ /* The following operations do not copy any elements. They move existing blocks of elements around by switching pointers. They are fairly efficient for long lists as for short lists. (Alas, the Count slows things down). They split the list into two parts. One part remains as the original list, the other part is appended to the second list. There are eight possible variations: Split the list {after/before} a given element keep the {head/tail} portion in the original list append the rest to the {head/tail} of the new list. Since After is strictly equivalent to Before Next we are not in serious need of the Before/After variants. That leaves only four. If you are processing a list left to right and dumping the bits that you have processed into another list as you go, the Tail/Tail variant gives the most natural result. If you are processing in reverse order, Head/Head is best. By using NULL positions and empty lists judiciously either of the other two can be built up in two operations. The definition of NULL (see Next/Prev etc) means that degenerate cases include "move all elements to new list" "Split a list into two lists" "Concatenate two lists" (and quite a few no-ops) !!WARNING!! The type checking won't buy you much if you get list positions muddled up - e.g. use a POSITION that's in a different list and see what a mess you get! */ /* Split *this after position p in *this Retain as *this the tail portion of the original *this Add the head portion to the tail end of *pList Return TRUE if it all worked, FALSE if it didn't. e.g. foo->MoveToTail(foo->GetHeadPosition(), bar); moves one element from the head of foo to the tail of bar foo->MoveToTail(NULL, bar); is a no-op, returns NULL foo->MoveToTail(foo->GetTailPosition, bar); concatenates foo onto the end of bar and empties foo. A better, except excessively long name might be MoveElementsFromHeadThroughPositionToOtherTail */ BOOL MoveToTail(__in_opt POSITION pos, __in CBaseList *pList); /* Mirror image: Split *this before position p in *this. Retain in *this the head portion of the original *this Add the tail portion to the start (i.e. head) of *pList e.g. foo->MoveToHead(foo->GetTailPosition(), bar); moves one element from the tail of foo to the head of bar foo->MoveToHead(NULL, bar); is a no-op, returns NULL foo->MoveToHead(foo->GetHeadPosition, bar); concatenates foo onto the start of bar and empties foo. */ BOOL MoveToHead(__in_opt POSITION pos, __in CBaseList *pList); /* Reverse the order of the [pointers to] objects in *this */ void Reverse(); /* set cursor to the position of each element of list in turn */ #define TRAVERSELIST(list, cursor) for (cursor = (list).GetHeadPosition(); cursor != NULL; cursor = (list).Next(cursor)) /* set cursor to the position of each element of list in turn in reverse order */ #define REVERSETRAVERSELIST(list, cursor) \ for (cursor = (list).GetTailPosition(); cursor != NULL; cursor = (list).Prev(cursor)) }; // end of class declaration template class CGenericList : public CBaseList { public: CGenericList(__in_opt LPCTSTR pName, INT iItems, BOOL bLock = TRUE, BOOL bAlert = FALSE) : CBaseList(pName, iItems) { UNREFERENCED_PARAMETER(bAlert); UNREFERENCED_PARAMETER(bLock); }; CGenericList(__in_opt LPCTSTR pName) : CBaseList(pName){}; __out_opt POSITION GetHeadPosition() const { return (POSITION)m_pFirst; } __out_opt POSITION GetTailPosition() const { return (POSITION)m_pLast; } int GetCount() const { return m_Count; } __out OBJECT *GetNext(__inout POSITION &rp) const { return (OBJECT *)GetNextI(rp); } __out_opt OBJECT *Get(__in_opt POSITION p) const { return (OBJECT *)GetI(p); } __out OBJECT *GetValid(__in POSITION p) const { return (OBJECT *)GetValidI(p); } __out_opt OBJECT *GetHead() const { return Get(GetHeadPosition()); } __out_opt OBJECT *RemoveHead() { return (OBJECT *)RemoveHeadI(); } __out_opt OBJECT *RemoveTail() { return (OBJECT *)RemoveTailI(); } __out_opt OBJECT *Remove(__in_opt POSITION p) { return (OBJECT *)RemoveI(p); } __out_opt POSITION AddBefore(__in_opt POSITION p, __in OBJECT *pObj) { return AddBeforeI(p, pObj); } __out_opt POSITION AddAfter(__in_opt POSITION p, __in OBJECT *pObj) { return AddAfterI(p, pObj); } __out_opt POSITION AddHead(__in OBJECT *pObj) { return AddHeadI(pObj); } __out_opt POSITION AddTail(__in OBJECT *pObj) { return AddTailI(pObj); } BOOL AddTail(__in CGenericList *pList) { return CBaseList::AddTail((CBaseList *)pList); } BOOL AddHead(__in CGenericList *pList) { return CBaseList::AddHead((CBaseList *)pList); } BOOL AddAfter(__in_opt POSITION p, __in CGenericList *pList) { return CBaseList::AddAfter(p, (CBaseList *)pList); }; BOOL AddBefore(__in_opt POSITION p, __in CGenericList *pList) { return CBaseList::AddBefore(p, (CBaseList *)pList); }; __out_opt POSITION Find(__in OBJECT *pObj) const { return FindI(pObj); } }; // end of class declaration /* These define the standard list types */ typedef CGenericList CBaseObjectList; typedef CGenericList CBaseInterfaceList; #endif /* __WXLIST__ */ ================================================ FILE: common/baseclasses/wxutil.cpp ================================================ //------------------------------------------------------------------------------ // File: WXUtil.cpp // // Desc: DirectShow base classes - implements helper classes for building // multimedia filters. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include #define STRSAFE_NO_DEPRECATE #include #include // --- CAMEvent ----------------------- CAMEvent::CAMEvent(BOOL fManualReset, __inout_opt HRESULT *phr) { m_hEvent = CreateEvent(NULL, fManualReset, FALSE, NULL); if (NULL == m_hEvent) { if (NULL != phr && SUCCEEDED(*phr)) { *phr = E_OUTOFMEMORY; } } } CAMEvent::CAMEvent(__inout_opt HRESULT *phr) { m_hEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (NULL == m_hEvent) { if (NULL != phr && SUCCEEDED(*phr)) { *phr = E_OUTOFMEMORY; } } } CAMEvent::~CAMEvent() { if (m_hEvent) { EXECUTE_ASSERT(CloseHandle(m_hEvent)); } } // --- CAMMsgEvent ----------------------- // One routine. The rest is handled in CAMEvent CAMMsgEvent::CAMMsgEvent(__inout_opt HRESULT *phr) : CAMEvent(FALSE, phr) { } BOOL CAMMsgEvent::WaitMsg(DWORD dwTimeout) { // wait for the event to be signalled, or for the // timeout (in MS) to expire. allow SENT messages // to be processed while we wait DWORD dwWait; DWORD dwStartTime; // set the waiting period. DWORD dwWaitTime = dwTimeout; // the timeout will eventually run down as we iterate // processing messages. grab the start time so that // we can calculate elapsed times. if (dwWaitTime != INFINITE) { dwStartTime = timeGetTime(); } do { dwWait = MsgWaitForMultipleObjects(1, &m_hEvent, FALSE, dwWaitTime, QS_SENDMESSAGE); if (dwWait == WAIT_OBJECT_0 + 1) { MSG Message; PeekMessage(&Message, NULL, 0, 0, PM_NOREMOVE); // If we have an explicit length of time to wait calculate // the next wake up point - which might be now. // If dwTimeout is INFINITE, it stays INFINITE if (dwWaitTime != INFINITE) { DWORD dwElapsed = timeGetTime() - dwStartTime; dwWaitTime = (dwElapsed >= dwTimeout) ? 0 // wake up with WAIT_TIMEOUT : dwTimeout - dwElapsed; } } } while (dwWait == WAIT_OBJECT_0 + 1); // return TRUE if we woke on the event handle, // FALSE if we timed out. return (dwWait == WAIT_OBJECT_0); } // --- CAMThread ---------------------- CAMThread::CAMThread(__inout_opt HRESULT *phr) : m_EventSend(TRUE, phr) , // must be manual-reset for CheckRequest() m_EventComplete(FALSE, phr) { m_hThread = NULL; } CAMThread::~CAMThread() { Close(); } // when the thread starts, it calls this function. We unwrap the 'this' // pointer and call ThreadProc. unsigned int WINAPI CAMThread::InitialThreadProc(__inout LPVOID pv) { HRESULT hrCoInit = CAMThread::CoInitializeHelper(); if (FAILED(hrCoInit)) { DbgLog((LOG_ERROR, 1, TEXT("CoInitializeEx failed."))); } CAMThread *pThread = (CAMThread *)pv; HRESULT hr = pThread->ThreadProc(); if (SUCCEEDED(hrCoInit)) { CoUninitialize(); } return hr; } BOOL CAMThread::Create() { CAutoLock lock(&m_AccessLock); if (ThreadExists()) { return FALSE; } m_hThread = (HANDLE)_beginthreadex(NULL, /* Security */ 0, /* Stack Size */ CAMThread::InitialThreadProc, /* Thread process */ (LPVOID)this, /* Arguments */ 0, /* 0 = Start Immediately */ NULL /* Thread Address */ ); if (!m_hThread) { return FALSE; } return TRUE; } DWORD CAMThread::CallWorker(DWORD dwParam) { // lock access to the worker thread for scope of this object CAutoLock lock(&m_AccessLock); if (!ThreadExists()) { return (DWORD)E_FAIL; } // set the parameter m_dwParam = dwParam; // signal the worker thread m_EventSend.Set(); // wait for the completion to be signalled m_EventComplete.Wait(); // done - this is the thread's return value return m_dwReturnVal; } // Wait for a request from the client DWORD CAMThread::GetRequest() { m_EventSend.Wait(); return m_dwParam; } // is there a request? BOOL CAMThread::CheckRequest(__out_opt DWORD *pParam) { if (!m_EventSend.Check()) { return FALSE; } else { if (pParam) { *pParam = m_dwParam; } return TRUE; } } // reply to the request void CAMThread::Reply(DWORD dw) { m_dwReturnVal = dw; // The request is now complete so CheckRequest should fail from // now on // // This event should be reset BEFORE we signal the client or // the client may Set it before we reset it and we'll then // reset it (!) m_EventSend.Reset(); // Tell the client we're finished m_EventComplete.Set(); } HRESULT CAMThread::CoInitializeHelper() { // call CoInitializeEx and tell OLE not to create a window (this // thread probably won't dispatch messages and will hang on // broadcast msgs o/w). // // If CoInitEx is not available, threads that don't call CoCreate // aren't affected. Threads that do will have to handle the // failure. Perhaps we should fall back to CoInitialize and risk // hanging? // // older versions of ole32.dll don't have CoInitializeEx HRESULT hr = E_FAIL; HINSTANCE hOle = GetModuleHandle(TEXT("ole32.dll")); if (hOle) { typedef HRESULT(STDAPICALLTYPE * PCoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit); PCoInitializeEx pCoInitializeEx = (PCoInitializeEx)(GetProcAddress(hOle, "CoInitializeEx")); if (pCoInitializeEx) { hr = (*pCoInitializeEx)(0, COINIT_DISABLE_OLE1DDE); } } else { // caller must load ole32.dll DbgBreak("couldn't locate ole32.dll"); } return hr; } // destructor for CMsgThread - cleans up any messages left in the // queue when the thread exited CMsgThread::~CMsgThread() { if (m_hThread != NULL) { WaitForSingleObject(m_hThread, INFINITE); EXECUTE_ASSERT(CloseHandle(m_hThread)); } POSITION pos = m_ThreadQueue.GetHeadPosition(); while (pos) { CMsg *pMsg = m_ThreadQueue.GetNext(pos); delete pMsg; } m_ThreadQueue.RemoveAll(); if (m_hSem != NULL) { EXECUTE_ASSERT(CloseHandle(m_hSem)); } } BOOL CMsgThread::CreateThread() { m_hSem = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL); if (m_hSem == NULL) { return FALSE; } m_hThread = ::CreateThread(NULL, 0, DefaultThreadProc, (LPVOID)this, 0, &m_ThreadId); return m_hThread != NULL; } // This is the threads message pump. Here we get and dispatch messages to // clients thread proc until the client refuses to process a message. // The client returns a non-zero value to stop the message pump, this // value becomes the threads exit code. DWORD WINAPI CMsgThread::DefaultThreadProc(__inout LPVOID lpParam) { CMsgThread *lpThis = (CMsgThread *)lpParam; CMsg msg; LRESULT lResult; // !!! CoInitialize(NULL); // allow a derived class to handle thread startup lpThis->OnThreadInit(); do { lpThis->GetThreadMsg(&msg); lResult = lpThis->ThreadMessageProc(msg.uMsg, msg.dwFlags, msg.lpParam, msg.pEvent); } while (lResult == 0L); // !!! CoUninitialize(); return (DWORD)lResult; } // Block until the next message is placed on the list m_ThreadQueue. // copies the message to the message pointed to by *pmsg void CMsgThread::GetThreadMsg(__out CMsg *msg) { CMsg *pmsg = NULL; // keep trying until a message appears while (TRUE) { { CAutoLock lck(&m_Lock); pmsg = m_ThreadQueue.RemoveHead(); if (pmsg == NULL) { m_lWaiting++; } else { break; } } // the semaphore will be signalled when it is non-empty WaitForSingleObject(m_hSem, INFINITE); } // copy fields to caller's CMsg *msg = *pmsg; // this CMsg was allocated by the 'new' in PutThreadMsg delete pmsg; } // Helper function - convert int to WSTR void WINAPI IntToWstr(int i, __out_ecount(12) LPWSTR wstr) { #ifdef UNICODE if (FAILED(StringCchPrintf(wstr, 12, L"%d", i))) { wstr[0] = 0; } #else TCHAR temp[12]; if (FAILED(StringCchPrintf(temp, NUMELMS(temp), "%d", i))) { wstr[0] = 0; } else { MultiByteToWideChar(CP_ACP, 0, temp, -1, wstr, 12); } #endif } // IntToWstr #define MEMORY_ALIGNMENT 4 #define MEMORY_ALIGNMENT_LOG2 2 #define MEMORY_ALIGNMENT_MASK MEMORY_ALIGNMENT - 1 void *__stdcall memmoveInternal(void *dst, const void *src, size_t count) { void *ret = dst; #ifdef _X86_ if (dst <= src || (char *)dst >= ((char *)src + count)) { /* * Non-Overlapping Buffers * copy from lower addresses to higher addresses */ _asm { mov esi,src mov edi,dst mov ecx,count cld mov edx,ecx and edx,MEMORY_ALIGNMENT_MASK shr ecx,MEMORY_ALIGNMENT_LOG2 rep movsd or ecx,edx jz memmove_done rep movsb memmove_done: } } else { /* * Overlapping Buffers * copy from higher addresses to lower addresses */ _asm { mov esi,src mov edi,dst mov ecx,count std add esi,ecx add edi,ecx dec esi dec edi rep movsb cld } } #else MoveMemory(dst, src, count); #endif return ret; } HRESULT AMSafeMemMoveOffset(__in_bcount(dst_size) void *dst, __in size_t dst_size, __in DWORD cb_dst_offset, __in_bcount(src_size) const void *src, __in size_t src_size, __in DWORD cb_src_offset, __in size_t count) { // prevent read overruns if (count + cb_src_offset < count || // prevent integer overflow count + cb_src_offset > src_size) // prevent read overrun { return E_INVALIDARG; } // prevent write overruns if (count + cb_dst_offset < count || // prevent integer overflow count + cb_dst_offset > dst_size) // prevent write overrun { return E_INVALIDARG; } memmoveInternal((BYTE *)dst + cb_dst_offset, (BYTE *)src + cb_src_offset, count); return S_OK; } #ifdef DEBUG /******************************Public*Routine******************************\ * Debug CCritSec helpers * * We provide debug versions of the Constructor, destructor, Lock and Unlock * routines. The debug code tracks who owns each critical section by * maintaining a depth count. * * History: * \**************************************************************************/ CCritSec::CCritSec() { InitializeCriticalSection(&m_CritSec); m_currentOwner = m_lockCount = 0; m_fTrace = FALSE; } CCritSec::~CCritSec() { DeleteCriticalSection(&m_CritSec); } void CCritSec::Lock() { UINT tracelevel = 3; DWORD us = GetCurrentThreadId(); DWORD currentOwner = m_currentOwner; if (currentOwner && (currentOwner != us)) { // already owned, but not by us if (m_fTrace) { DbgLog((LOG_LOCKING, 2, TEXT("Thread %d about to wait for lock %x owned by %d"), GetCurrentThreadId(), &m_CritSec, currentOwner)); tracelevel = 2; // if we saw the message about waiting for the critical // section we ensure we see the message when we get the // critical section } } EnterCriticalSection(&m_CritSec); if (0 == m_lockCount++) { // we now own it for the first time. Set owner information m_currentOwner = us; if (m_fTrace) { DbgLog((LOG_LOCKING, tracelevel, TEXT("Thread %d now owns lock %x"), m_currentOwner, &m_CritSec)); } } } void CCritSec::Unlock() { if (0 == --m_lockCount) { // about to be unowned if (m_fTrace) { DbgLog((LOG_LOCKING, 3, TEXT("Thread %d releasing lock %x"), m_currentOwner, &m_CritSec)); } m_currentOwner = 0; } LeaveCriticalSection(&m_CritSec); } void WINAPI DbgLockTrace(CCritSec *pcCrit, BOOL fTrace) { pcCrit->m_fTrace = fTrace; } BOOL WINAPI CritCheckIn(CCritSec *pcCrit) { return (GetCurrentThreadId() == pcCrit->m_currentOwner); } BOOL WINAPI CritCheckIn(const CCritSec *pcCrit) { return (GetCurrentThreadId() == pcCrit->m_currentOwner); } BOOL WINAPI CritCheckOut(CCritSec *pcCrit) { return (GetCurrentThreadId() != pcCrit->m_currentOwner); } BOOL WINAPI CritCheckOut(const CCritSec *pcCrit) { return (GetCurrentThreadId() != pcCrit->m_currentOwner); } #endif STDAPI WriteBSTR(__deref_out BSTR *pstrDest, LPCWSTR szSrc) { *pstrDest = SysAllocString(szSrc); if (!(*pstrDest)) return E_OUTOFMEMORY; return NOERROR; } STDAPI FreeBSTR(__deref_in BSTR *pstr) { if ((PVOID)*pstr == NULL) return S_FALSE; SysFreeString(*pstr); return NOERROR; } // Return a wide string - allocating memory for it // Returns: // S_OK - no error // E_POINTER - ppszReturn == NULL // E_OUTOFMEMORY - can't allocate memory for returned string STDAPI AMGetWideString(LPCWSTR psz, __deref_out LPWSTR *ppszReturn) { CheckPointer(ppszReturn, E_POINTER); ValidateReadWritePtr(ppszReturn, sizeof(LPWSTR)); *ppszReturn = NULL; size_t nameLen; HRESULT hr = StringCbLengthW(psz, 100000, &nameLen); if (FAILED(hr)) { return hr; } *ppszReturn = (LPWSTR)CoTaskMemAlloc(nameLen + sizeof(WCHAR)); if (*ppszReturn == NULL) { return E_OUTOFMEMORY; } CopyMemory(*ppszReturn, psz, nameLen + sizeof(WCHAR)); return NOERROR; } // Waits for the HANDLE hObject. While waiting messages sent // to windows on our thread by SendMessage will be processed. // Using this function to do waits and mutual exclusion // avoids some deadlocks in objects with windows. // Return codes are the same as for WaitForSingleObject DWORD WINAPI WaitDispatchingMessages(HANDLE hObject, DWORD dwWait, HWND hwnd, UINT uMsg, HANDLE hEvent) { BOOL bPeeked = FALSE; DWORD dwResult; DWORD dwStart; DWORD dwThreadPriority; static UINT uMsgId = 0; HANDLE hObjects[2] = {hObject, hEvent}; if (dwWait != INFINITE && dwWait != 0) { dwStart = GetTickCount(); } for (;;) { DWORD nCount = NULL != hEvent ? 2 : 1; // Minimize the chance of actually dispatching any messages // by seeing if we can lock immediately. dwResult = WaitForMultipleObjects(nCount, hObjects, FALSE, 0); if (dwResult < WAIT_OBJECT_0 + nCount) { break; } DWORD dwTimeOut = dwWait; if (dwTimeOut > 10) { dwTimeOut = 10; } dwResult = MsgWaitForMultipleObjects(nCount, hObjects, FALSE, dwTimeOut, hwnd == NULL ? QS_SENDMESSAGE : QS_SENDMESSAGE + QS_POSTMESSAGE); if (dwResult == WAIT_OBJECT_0 + nCount || dwResult == WAIT_TIMEOUT && dwTimeOut != dwWait) { MSG msg; if (hwnd != NULL) { while (PeekMessage(&msg, hwnd, uMsg, uMsg, PM_REMOVE)) { DispatchMessage(&msg); } } // Do this anyway - the previous peek doesn't flush out the // messages PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); if (dwWait != INFINITE && dwWait != 0) { DWORD dwNow = GetTickCount(); // Working with differences handles wrap-around DWORD dwDiff = dwNow - dwStart; if (dwDiff > dwWait) { dwWait = 0; } else { dwWait -= dwDiff; } dwStart = dwNow; } if (!bPeeked) { // Raise our priority to prevent our message queue // building up dwThreadPriority = GetThreadPriority(GetCurrentThread()); if (dwThreadPriority < THREAD_PRIORITY_HIGHEST) { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); } bPeeked = TRUE; } } else { break; } } if (bPeeked) { SetThreadPriority(GetCurrentThread(), dwThreadPriority); if (HIWORD(GetQueueStatus(QS_POSTMESSAGE)) & QS_POSTMESSAGE) { if (uMsgId == 0) { uMsgId = RegisterWindowMessage(TEXT("AMUnblock")); } if (uMsgId != 0) { MSG msg; // Remove old ones while (PeekMessage(&msg, (HWND)-1, uMsgId, uMsgId, PM_REMOVE)) { } } PostThreadMessage(GetCurrentThreadId(), uMsgId, 0, 0); } } return dwResult; } HRESULT AmGetLastErrorToHResult() { DWORD dwLastError = GetLastError(); if (dwLastError != 0) { return HRESULT_FROM_WIN32(dwLastError); } else { return E_FAIL; } } IUnknown *QzAtlComPtrAssign(__deref_inout_opt IUnknown **pp, __in_opt IUnknown *lp) { if (lp != NULL) lp->AddRef(); if (*pp) (*pp)->Release(); *pp = lp; return lp; } ================================================ FILE: common/baseclasses/wxutil.h ================================================ //------------------------------------------------------------------------------ // File: WXUtil.h // // Desc: DirectShow base classes - defines helper classes and functions for // building multimedia filters. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #ifndef __WXUTIL__ #define __WXUTIL__ // eliminate spurious "statement has no effect" warnings. #pragma warning(disable : 4705) // wrapper for whatever critical section we have class CCritSec { // make copy constructor and assignment operator inaccessible CCritSec(const CCritSec &refCritSec); CCritSec &operator=(const CCritSec &refCritSec); CRITICAL_SECTION m_CritSec; #ifdef DEBUG public: DWORD m_currentOwner; DWORD m_lockCount; BOOL m_fTrace; // Trace this one public: CCritSec(); ~CCritSec(); void Lock(); void Unlock(); #else public: CCritSec() { InitializeCriticalSection(&m_CritSec); }; ~CCritSec() { DeleteCriticalSection(&m_CritSec); }; void Lock() { EnterCriticalSection(&m_CritSec); }; void Unlock() { LeaveCriticalSection(&m_CritSec); }; #endif }; // // To make deadlocks easier to track it is useful to insert in the // code an assertion that says whether we own a critical section or // not. We make the routines that do the checking globals to avoid // having different numbers of member functions in the debug and // retail class implementations of CCritSec. In addition we provide // a routine that allows usage of specific critical sections to be // traced. This is NOT on by default - there are far too many. // #ifdef DEBUG BOOL WINAPI CritCheckIn(CCritSec *pcCrit); BOOL WINAPI CritCheckIn(const CCritSec *pcCrit); BOOL WINAPI CritCheckOut(CCritSec *pcCrit); BOOL WINAPI CritCheckOut(const CCritSec *pcCrit); void WINAPI DbgLockTrace(CCritSec *pcCrit, BOOL fTrace); #else #define CritCheckIn(x) TRUE #define CritCheckOut(x) TRUE #define DbgLockTrace(pc, fT) #endif // locks a critical section, and unlocks it automatically // when the lock goes out of scope class CAutoLock { // make copy constructor and assignment operator inaccessible CAutoLock(const CAutoLock &refAutoLock); CAutoLock &operator=(const CAutoLock &refAutoLock); protected: CCritSec *m_pLock; public: CAutoLock(CCritSec *plock) { m_pLock = plock; m_pLock->Lock(); }; ~CAutoLock() { m_pLock->Unlock(); }; }; // wrapper for event objects class CAMEvent { // make copy constructor and assignment operator inaccessible CAMEvent(const CAMEvent &refEvent); CAMEvent &operator=(const CAMEvent &refEvent); protected: HANDLE m_hEvent; public: CAMEvent(BOOL fManualReset = FALSE, __inout_opt HRESULT *phr = NULL); CAMEvent(__inout_opt HRESULT *phr); ~CAMEvent(); // Cast to HANDLE - we don't support this as an lvalue operator HANDLE() const { return m_hEvent; }; void Set() { EXECUTE_ASSERT(SetEvent(m_hEvent)); }; BOOL Wait(DWORD dwTimeout = INFINITE) { return (WaitForSingleObject(m_hEvent, dwTimeout) == WAIT_OBJECT_0); }; void Reset() { ResetEvent(m_hEvent); }; BOOL Check() { return Wait(0); }; }; // wrapper for event objects that do message processing // This adds ONE method to the CAMEvent object to allow sent // messages to be processed while waiting class CAMMsgEvent : public CAMEvent { public: CAMMsgEvent(__inout_opt HRESULT *phr = NULL); // Allow SEND messages to be processed while waiting BOOL WaitMsg(DWORD dwTimeout = INFINITE); }; // old name supported for the time being #define CTimeoutEvent CAMEvent // support for a worker thread #ifdef AM_NOVTABLE // simple thread class supports creation of worker thread, synchronization // and communication. Can be derived to simplify parameter passing class AM_NOVTABLE CAMThread { // make copy constructor and assignment operator inaccessible CAMThread(const CAMThread &refThread); CAMThread &operator=(const CAMThread &refThread); CAMEvent m_EventSend; CAMEvent m_EventComplete; DWORD m_dwParam; DWORD m_dwReturnVal; protected: HANDLE m_hThread; // thread will run this function on startup // must be supplied by derived class virtual DWORD ThreadProc() = 0; public: CAMThread(__inout_opt HRESULT *phr = NULL); virtual ~CAMThread(); CCritSec m_AccessLock; // locks access by client threads CCritSec m_WorkerLock; // locks access to shared objects // thread initially runs this. param is actually 'this'. function // just gets this and calls ThreadProc static unsigned int WINAPI InitialThreadProc(__inout LPVOID pv); // start thread running - error if already running BOOL Create(); // signal the thread, and block for a response // DWORD CallWorker(DWORD); // accessor thread calls this when done with thread (having told thread // to exit) void Close() { // Disable warning: Conversion from LONG to PVOID of greater size #pragma warning(push) #pragma warning(disable : 4312) HANDLE hThread = (HANDLE)InterlockedExchangePointer(&m_hThread, 0); #pragma warning(pop) if (hThread) { WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); } }; // ThreadExists // Return TRUE if the thread exists. FALSE otherwise BOOL ThreadExists(void) const { if (m_hThread == 0) { return FALSE; } else { return TRUE; } } // wait for the next request DWORD GetRequest(); // is there a request? BOOL CheckRequest(__out_opt DWORD *pParam); // reply to the request void Reply(DWORD); // If you want to do WaitForMultipleObjects you'll need to include // this handle in your wait list or you won't be responsive HANDLE GetRequestHandle() const { return m_EventSend; }; // Find out what the request was DWORD GetRequestParam() const { return m_dwParam; }; // call CoInitializeEx (COINIT_DISABLE_OLE1DDE) if // available. S_FALSE means it's not available. static HRESULT CoInitializeHelper(); }; #endif // AM_NOVTABLE // CQueue // // Implements a simple Queue ADT. The queue contains a finite number of // objects, access to which is controlled by a semaphore. The semaphore // is created with an initial count (N). Each time an object is added // a call to WaitForSingleObject is made on the semaphore's handle. When // this function returns a slot has been reserved in the queue for the new // object. If no slots are available the function blocks until one becomes // available. Each time an object is removed from the queue ReleaseSemaphore // is called on the semaphore's handle, thus freeing a slot in the queue. // If no objects are present in the queue the function blocks until an // object has been added. #define DEFAULT_QUEUESIZE 2 template class CQueue { private: HANDLE hSemPut; // Semaphore controlling queue "putting" HANDLE hSemGet; // Semaphore controlling queue "getting" CRITICAL_SECTION CritSect; // Thread seriallization int nMax; // Max objects allowed in queue int iNextPut; // Array index of next "PutMsg" int iNextGet; // Array index of next "GetMsg" T *QueueObjects; // Array of objects (ptr's to void) void Initialize(int n) { iNextPut = iNextGet = 0; nMax = n; InitializeCriticalSection(&CritSect); hSemPut = CreateSemaphore(NULL, n, n, NULL); hSemGet = CreateSemaphore(NULL, 0, n, NULL); QueueObjects = new T[n]; } public: CQueue(int n) { Initialize(n); } CQueue() { Initialize(DEFAULT_QUEUESIZE); } ~CQueue() { delete[] QueueObjects; DeleteCriticalSection(&CritSect); CloseHandle(hSemPut); CloseHandle(hSemGet); } T GetQueueObject() { int iSlot; T Object; LONG lPrevious; // Wait for someone to put something on our queue, returns straight // away is there is already an object on the queue. // WaitForSingleObject(hSemGet, INFINITE); EnterCriticalSection(&CritSect); iSlot = iNextGet++ % nMax; Object = QueueObjects[iSlot]; LeaveCriticalSection(&CritSect); // Release anyone waiting to put an object onto our queue as there // is now space available in the queue. // ReleaseSemaphore(hSemPut, 1L, &lPrevious); return Object; } void PutQueueObject(T Object) { int iSlot; LONG lPrevious; // Wait for someone to get something from our queue, returns straight // away is there is already an empty slot on the queue. // WaitForSingleObject(hSemPut, INFINITE); EnterCriticalSection(&CritSect); iSlot = iNextPut++ % nMax; QueueObjects[iSlot] = Object; LeaveCriticalSection(&CritSect); // Release anyone waiting to remove an object from our queue as there // is now an object available to be removed. // ReleaseSemaphore(hSemGet, 1L, &lPrevious); } }; // Ensures that memory is not read past the length source buffer // and that memory is not written past the length of the dst buffer // dst - buffer to copy to // dst_size - total size of destination buffer // cb_dst_offset - offset, first byte copied to dst+cb_dst_offset // src - buffer to copy from // src_size - total size of source buffer // cb_src_offset - offset, first byte copied from src+cb_src_offset // count - number of bytes to copy // // Returns: // S_OK - no error // E_INVALIDARG - values passed would lead to overrun HRESULT AMSafeMemMoveOffset(__in_bcount(dst_size) void *dst, __in size_t dst_size, __in DWORD cb_dst_offset, __in_bcount(src_size) const void *src, __in size_t src_size, __in DWORD cb_src_offset, __in size_t count); extern "C" void *__stdcall memmoveInternal(void *, const void *, size_t); inline void *__cdecl memchrInternal(const void *buf, int chr, size_t cnt) { #ifdef _X86_ void *pRet = NULL; _asm { cld // make sure we get the direction right mov ecx, cnt // num of bytes to scan mov edi, buf // pointer byte stream mov eax, chr // byte to scan for repne scasb // look for the byte in the byte stream jnz exit_memchr // Z flag set if byte found dec edi // scasb always increments edi even when it // finds the required byte mov pRet, edi exit_memchr: } return pRet; #else while (cnt && (*(unsigned char *)buf != (unsigned char)chr)) { buf = (unsigned char *)buf + 1; cnt--; } return (cnt ? (void *)buf : NULL); #endif } void WINAPI IntToWstr(int i, __out_ecount(12) LPWSTR wstr); #define WstrToInt(sz) _wtoi(sz) #define atoiW(sz) _wtoi(sz) #define atoiA(sz) atoi(sz) // These are available to help managing bitmap VIDEOINFOHEADER media structures extern const DWORD bits555[3]; extern const DWORD bits565[3]; extern const DWORD bits888[3]; // These help convert between VIDEOINFOHEADER and BITMAPINFO structures STDAPI_(const GUID) GetTrueColorType(const BITMAPINFOHEADER *pbmiHeader); STDAPI_(const GUID) GetBitmapSubtype(const BITMAPINFOHEADER *pbmiHeader); STDAPI_(WORD) GetBitCount(const GUID *pSubtype); // strmbase.lib implements this for compatibility with people who // managed to link to this directly. we don't want to advertise it. // // STDAPI_(/* T */ CHAR *) GetSubtypeName(const GUID *pSubtype); STDAPI_(CHAR *) GetSubtypeNameA(const GUID *pSubtype); STDAPI_(WCHAR *) GetSubtypeNameW(const GUID *pSubtype); #ifdef UNICODE #define GetSubtypeName GetSubtypeNameW #else #define GetSubtypeName GetSubtypeNameA #endif STDAPI_(LONG) GetBitmapFormatSize(const BITMAPINFOHEADER *pHeader); STDAPI_(DWORD) GetBitmapSize(const BITMAPINFOHEADER *pHeader); #ifdef __AMVIDEO__ STDAPI_(BOOL) ContainsPalette(const VIDEOINFOHEADER *pVideoInfo); STDAPI_(const RGBQUAD *) GetBitmapPalette(const VIDEOINFOHEADER *pVideoInfo); #endif // __AMVIDEO__ // Compares two interfaces and returns TRUE if they are on the same object BOOL WINAPI IsEqualObject(IUnknown *pFirst, IUnknown *pSecond); // This is for comparing pins #define EqualPins(pPin1, pPin2) IsEqualObject(pPin1, pPin2) // Arithmetic helper functions // Compute (a * b + rnd) / c LONGLONG WINAPI llMulDiv(LONGLONG a, LONGLONG b, LONGLONG c, LONGLONG rnd); LONGLONG WINAPI Int64x32Div32(LONGLONG a, LONG b, LONG c, LONG rnd); // Avoids us dyna-linking to SysAllocString to copy BSTR strings STDAPI WriteBSTR(__deref_out BSTR *pstrDest, LPCWSTR szSrc); STDAPI FreeBSTR(__deref_in BSTR *pstr); // Return a wide string - allocating memory for it // Returns: // S_OK - no error // E_POINTER - ppszReturn == NULL // E_OUTOFMEMORY - can't allocate memory for returned string STDAPI AMGetWideString(LPCWSTR pszString, __deref_out LPWSTR *ppszReturn); // Special wait for objects owning windows DWORD WINAPI WaitDispatchingMessages(HANDLE hObject, DWORD dwWait, HWND hwnd = NULL, UINT uMsg = 0, HANDLE hEvent = NULL); // HRESULT_FROM_WIN32 converts ERROR_SUCCESS to a success code, but in // our use of HRESULT_FROM_WIN32, it typically means a function failed // to call SetLastError(), and we still want a failure code. // #define AmHresultFromWin32(x) (MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, x)) // call GetLastError and return an HRESULT value that will fail the // SUCCEEDED() macro. HRESULT AmGetLastErrorToHResult(void); // duplicate of ATL's CComPtr to avoid linker conflicts. IUnknown *QzAtlComPtrAssign(__deref_inout_opt IUnknown **pp, __in_opt IUnknown *lp); template class QzCComPtr { public: typedef T _PtrClass; QzCComPtr() { p = NULL; } QzCComPtr(T *lp) { if ((p = lp) != NULL) p->AddRef(); } QzCComPtr(const QzCComPtr &lp) { if ((p = lp.p) != NULL) p->AddRef(); } ~QzCComPtr() { if (p) p->Release(); } void Release() { if (p) p->Release(); p = NULL; } operator T *() { return (T *)p; } T &operator*() { ASSERT(p != NULL); return *p; } // The assert on operator& usually indicates a bug. If this is really // what is needed, however, take the address of the p member explicitly. T **operator&() { ASSERT(p == NULL); return &p; } T *operator->() { ASSERT(p != NULL); return p; } T *operator=(T *lp) { return (T *)QzAtlComPtrAssign((IUnknown **)&p, lp); } T *operator=(const QzCComPtr &lp) { return (T *)QzAtlComPtrAssign((IUnknown **)&p, lp.p); } #if _MSC_VER > 1020 bool operator!() { return (p == NULL); } #else BOOL operator!() { return (p == NULL) ? TRUE : FALSE; } #endif T *p; }; #define CompatibleTimeSetEvent(uDelay, uResolution, lpTimeProc, dwUser, fuEvent) \ timeSetEvent((uDelay), (uResolution), (lpTimeProc), (dwUser), (fuEvent) | TIME_KILL_SYNCHRONOUS) // Helper to replace lstrcpmi __inline int lstrcmpiLocaleIndependentW(LPCWSTR lpsz1, LPCWSTR lpsz2) { return CompareStringW(LOCALE_INVARIANT, NORM_IGNORECASE, lpsz1, -1, lpsz2, -1) - CSTR_EQUAL; } __inline int lstrcmpiLocaleIndependentA(LPCSTR lpsz1, LPCSTR lpsz2) { return CompareStringA(LOCALE_INVARIANT, NORM_IGNORECASE, lpsz1, -1, lpsz2, -1) - CSTR_EQUAL; } #endif /* __WXUTIL__ */ ================================================ FILE: common/common.props ================================================ false true $(SolutionDir)bin_$(PlatformName)d\lib\ $(SolutionDir)bin_$(PlatformName)d\$(ProjectName)\ false $(SolutionDir)bin_$(PlatformName)\lib\ $(SolutionDir)bin_$(PlatformName)\$(ProjectName)\ $(ProjectDir);$(SolutionDir)include;$(SolutionDir)common\includes;$(SolutionDir)common\baseclasses;$(SolutionDir)ffmpeg;$(SolutionDir)libbluray\src;$(SolutionDir)common\DSUtilLite;%(AdditionalIncludeDirectories) /Zc:inline,referenceBinding,rvalueCast,throwingNew,ternary %(AdditionalOptions) Level3 Use stdafx.h stdcpp17 stdc11 Windows true Disabled MultiThreadedDebugDLL ProgramDatabase Default $(SolutionDir)bin_$(PlatformName)d\lib;%(AdditionalLibraryDirectories) /Gw /Zo %(AdditionalOptions) MaxSpeed Speed true true true true MultiThreaded /OPT:ICF=3 %(AdditionalOptions) true true $(SolutionDir)bin_$(PlatformName)\lib;%(AdditionalLibraryDirectories) StreamingSIMDExtensions2 ================================================ FILE: common/genversion.bat ================================================ @ECHO OFF SETLOCAL PUSHD "%~dp0" SET nbMAJOR_PART=0 SET nbCOMMIT_PART=0 SET nbHASH_PART=00000 SET OLDVER= :: check for git presence CALL git describe >NUL 2>&1 IF ERRORLEVEL 1 ( GOTO NOGIT ) :: Get git-describe output FOR /F "tokens=*" %%A IN ('"git describe --long --abbrev=5 HEAD"') DO ( SET strFILE_VERSION=%%A ) :: Split into tag, nb commits, hash FOR /F "tokens=1,2,3 delims=-" %%A IN ("%strFILE_VERSION%") DO ( SET nbMAJOR_PART=%%A SET nbCOMMIT_PART=%%B SET nbHASH_PART=%%C ) :: strip the "g" off the hash SET nbHASH_PART=%nbHASH_PART:~1% :WRITE_VER :: check if info changed, and write if needed IF EXIST includes\version_rev.h ( SET /P OLDVER= includes\version_rev.h ECHO %NEWVER% ) GOTO :END :NOGIT echo Git not found goto WRITE_VER :END POPD ENDLOCAL ================================================ FILE: common/includes/ILAVPinInfo.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // {FD220BF4-3F26-4AD4-A4A9-348C1273A141} DEFINE_GUID(IID_ILAVPinInfo, 0xfd220bf4, 0x3f26, 0x4ad4, 0xa4, 0xa9, 0x34, 0x8c, 0x12, 0x73, 0xa1, 0x41); interface __declspec(uuid("FD220BF4-3F26-4AD4-A4A9-348C1273A141")) ILAVPinInfo : public IUnknown { // Get a set of flags that convey a special information for this kind of stream STDMETHOD_(DWORD, GetStreamFlags)() PURE; #define LAV_STREAM_FLAG_ONLY_DTS 0x0000001 ///< Stream has only DTS timestamps (AVI, MKV in MS-Compat mode) #define LAV_STREAM_FLAG_RV34_MKV 0x0000002 ///< RV30/40 in MKV or similar container with horrible timstamps #define LAV_STREAM_FLAG_LIVE 0x0000004 ///< Stream is from a Live source // Get the pixel format detected for this video stream STDMETHOD_(int, GetPixelFormat)() PURE; // Get the interface version STDMETHOD_(int, GetVersion)() PURE; // Get the number of B-Frames probed for this format STDMETHOD_(int, GetHasBFrames)() PURE; }; ================================================ FILE: common/includes/IMediaSideDataFFmpeg.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #pragma once // {08CA03D5-1803-4FDC-8515-5B9DEC92437A} DEFINE_GUID(IID_MediaSideDataFFMpeg, 0x8ca03d5, 0x1803, 0x4fdc, 0x85, 0x15, 0x5b, 0x9d, 0xec, 0x92, 0x43, 0x7a); extern "C" { #include "libavcodec/avcodec.h" } #pragma pack(push, 1) struct MediaSideDataFFMpeg { AVPacketSideData *side_data; int side_data_elems; }; #pragma pack(pop) ================================================ FILE: common/includes/LAVSplitterSettingsInternal.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "LAVSplitterSettings.h" #include class FormatInfo { public: FormatInfo() {} FormatInfo(LPCSTR name, LPCSTR desc) : strName(name) , strDescription(desc) { } LPCSTR strName = nullptr; LPCSTR strDescription = nullptr; // Comparison operators for sorting (NULL safe) bool FormatInfo::operator<(const FormatInfo &rhs) const { return strName ? (rhs.strName ? _stricmp(strName, rhs.strName) < 0 : false) : true; } bool FormatInfo::operator>(const FormatInfo &rhs) const { return !(*this < rhs); } bool FormatInfo::operator==(const FormatInfo &rhs) const { return (strName == rhs.strName) || (strName && rhs.strName && (_stricmp(strName, rhs.strName) == 0)); } }; // GUID: 72b2c5fa-a7a5-4463-9c1b-9f4749c35c79 DEFINE_GUID(IID_ILAVFSettingsInternal, 0x72b2c5fa, 0xa7a5, 0x4463, 0x9c, 0x1b, 0x9f, 0x47, 0x49, 0xc3, 0x5c, 0x79); interface __declspec(uuid("72b2c5fa-a7a5-4463-9c1b-9f4749c35c79")) ILAVFSettingsInternal : public ILAVFSettings { // Query if the current filter graph requires VC1 Correction STDMETHOD_(BOOL, IsVC1CorrectionRequired)() = 0; STDMETHOD_(LPCSTR, GetInputFormat)() = 0; STDMETHOD_(std::set &, GetInputFormats)() = 0; STDMETHOD_(CMediaType *, GetOutputMediatype)(int stream) = 0; STDMETHOD_(IFilterGraph *, GetFilterGraph)() = 0; }; ================================================ FILE: common/includes/SubRenderIntf.h ================================================ // *************************************************************** // SubRenderIntf.h version: 1.0.9 - date: 2015-10-10 // ------------------------------------------------------------- // Copyright (C) 2011-2015, BSD license // *************************************************************** // 2015-10-10 1.0.9 added some optional information fields // 2014-03-06 1.0.8 added ISubRenderConsumer2::Clear() interface/method // 2014-03-05 1.0.7 auto-loading is now the provider's own responsibility // 2013-07-01 1.0.6 added support for TV level subtitle transport // 2013-06-05 1.0.5 added support for BT.2020 matrix // 2012-12-04 1.0.4 changed auto-loading to supports multiple sub renderers // 2012-10-15 1.0.3 (1) added some comments about interface management // (2) added "context" parameter to "Request/DeliverFrame" // 2012-09-11 1.0.2 (1) modified "yuvMatrix" fields to match Aegisub ("None") // (2) added a clarification about LPWSTR property case // 2012-08-30 1.0.1 (1) added mandatory consumer field "arAdjustedVideoSize" // (2) added "subtitle color correction" info text // (3) added mandatory provider field "yuvMatrix" // (4) modified optional consumer field "yuvMatrix" // 2011-12-20 1.0.0 initial release // --------------------------------------------------------------------------- // introduction // --------------------------------------------------------------------------- // This header defines a set of interfaces which a subtitle renderer can // export to make its services available. The purpose of these interfaces is // to allow a more flexible communication between subtitle renderer and // subtitle consumer (e.g. video renderer) than DirectShow allows. // A typical DirectShow subtitle renderer using these interfaces would have // a subtitle input pin, but no video input pin and no output pins. // --------------------------------------------------------------------------- // basic interface principle // --------------------------------------------------------------------------- // (1) The subtitle consumer exports the interface "ISubRenderConsumer" and // waits for a subtitle renderer to connect. // (2) The first time the graph is paused or started the subtitle renderer // searches through the DirectShow graph and looks for filters which // expose the "ISubRenderConsumer" interface. // (3) If there are multiple subtitle consumers in the graph, the subtitle // renderer needs to decide which one to service. This should be done by // picking the consumer with the highest merit. There's a "GetMerit()" // method in the "ISubRenderConsumer" interface for this purpose. // (4) Once the subtitle renderer has found a consumer it wants to service, // it calls "ISubRenderConsumer.Connect()", providing the consumer with // the "ISubRenderProvider" interface, which allows the consumer to // configure the subtitle renderer and to fetch rendered subtitles. // --------------------------------------------------------------------------- // subtitle color correction // --------------------------------------------------------------------------- // Today we have a number of different subtitle formats which define colors // in different color spaces. E.g. SRT subtitles are usually considered to be // native RGB, while DVD and Blu-Ray bitmap subtitles are native YCbCr. // The most difficult to handle format is ASS. ASS subtitle colors are defined // as RGB values. However, the historically most commonly used ASS renderer // (VSFilter) and the most commonly used ASS authoring software (Aegisub) both // render subtitles by drawing them directly onto the YCbCr video. Furthermore // up until very recently Aegisub always used to convert all videos to RGB by // using the BT.601 matrix. Practically that means that almost every ASS // subtitle file out there which is color matched to the video, requires // rendering in the same way, with hard coded BT.601 matrix, in order to ensure // that subtitle and video colors match exactly. // The subtitle interface defined in this header file passes subtitles from // the subtitle provider to the consumer in RGB format. Since some subtitle // formats are native YCbCr and due to the ASS color problem mentioned above, // it may be necessary to perform color correction to guarantee that the // rendered subtitle colors match perfectly to the video colors. // When rendering native YCbCr subtitles (DVD and Blu-Ray bitmap subtitles), // the subtitle renderer should try to use the correct YCbCr -> RGB matrix. // The subtitle renderer may either use the "yuvMatrix" information field // which the subtitle consumer may optionally provide. Or alternatively the // subtitle renderer can auto guess the correct matrix based on subtitle // resolution. The subtitle renderer informs the consumer about the matrix // that was used for subtitle YCbCr -> RGB conversion by setting the // "yuvMatrix" information field. // When rendering native RGB subtitles (e.g. SRT), the subtitle renderer // should render the subtitles untouched, and set the "yuvMatrix" information // field to "None". // When rendering ASS subtitles, the subtitle renderer should render the // subtitles in untouched RGB. If the ASS subtitle file has a "yuvMatrix" // header field, the subtitle renderer has to forward this field to the // subtitle consumer. If the ASS subtitle file does not have a "yuvMatrix" // header field, the subtitle renderer should set the "yuvMatrix" field to // "TV.601". // Subtitle consumers should read the subtitle renderer's "yuvMatrix" field. // If it is set to anything other than "None", the subtitle consumer should // double check whether the subtitle matrix matches the video matrix. If the // matrixes differ, the consumer should perform the necessary color correction // to make sure that subtitle and video colors match perfectly. // --------------------------------------------------------------------------- // subtitle levels // --------------------------------------------------------------------------- // Subtitles are by default transported as premultiplied RGBA pixels with // PC levels (black = 0; white = 255). All consumers and providers are // required to support this format. // Optionally, the consumer can signal (see "supportedLevels" info field) // that it supports TV levels, too. If it does (and only then), the provider // can optionally output subtitles in TV levels. If it does, it has to set // the info field "outputLevels" to "TV". // --------------------------------------------------------------------------- // subtitle repositioning // --------------------------------------------------------------------------- // In certain situations a user might have specific wishes for subtitle // positioning. E.g. a 4:3 TV owner may want to have subtitles rendered into // the big black bars on his TV, when watching 16:9 content. Or a CIH front // projection owner may want to have subtitles rendered into the active video // area instead of the black bars of the Cinemascope movie. // Now some subtitle sources (e.g. many fan made ASS subtitles for Anime) are // designed to be positioned very exactly. Other subtitle formats (e.g. SRT) // don't care about positioning at all. The consumer doesn't really know // which formats can be repostioned and which can't. So this interface allows // the consumer to express a wish for subtitle positioning. The subtitle // renderer can then decide whether it can (and wants to) honor this wish. // If the consumer wants subtitles to be moved, he sets "subtitleTargetRect" // to a different value (can be bigger or smaller) than "videoOutputRect". // Example 1: anamorphic 16:9 DVD playback, 4:3 computer monitor // consumer sets: // - displayModeSize, 1024x768 // - originalVideoSize, 720x480 // - arAdjustedVideoSize, 853x480 // - videoOutputRect, 0x96x1024x672 // - subtitleTargetRect, 0x0x1024x768 <- move request // subtitle renderer provides: // - ISubRender.GetVideoOutputRect() -> 0x0x720x480 // - ISubRender.GetClipRect() -> 0x-80x720x560 <- request granted // Example 2: anamorphic 16:9 DVD playback, CIH front projection // consumer sets: // - displayModeSize, 1920x1080 // - originalVideoSize, 720x480 // - arAdjustedVideoSize, 853x480 // - videoOutputRect, 0x0x1920x1080 // - subtitleTargetRect, 0x140x1920x940 <- move request // subtitle renderer provides: // - ISubRender.GetVideoOutputRect() -> 0x0x720x480 // - ISubRender.GetClipRect() -> 0x62x720x418 <- request granted // Example 3: reencoded Anime, ASS subtitles, CIH front projection // consumer sets: // - displayModeSize, 1920x1080 // - originalVideoSize, 853x480 // - arAdjustedVideoSize, 853x480 // - videoOutputRect, 0x0x1920x1080 // - subtitleTargetRect, 0x140x1920x940 <- move request // subtitle renderer provides: // - ISubRender.GetVideoOutputRect() -> 0x0x1920x1080 // - ISubRender.GetClipRect() -> 0x0x1920x1080 <- request denied // --------------------------------------------------------------------------- #ifndef __SubtitleInterface__ #define __SubtitleInterface__ interface ISubRenderConsumer; interface ISubRenderProvider; interface ISubRenderFrame; // --------------------------------------------------------------------------- // ISubRenderOptions // --------------------------------------------------------------------------- // Base interface for both ISubRenderConsumer and ISubRenderProvider. //[uuid("7CFD3728-235E-4430-9A2D-9F25F426BD70")] //interface ISubRenderOptions : public IUnknown DECLARE_INTERFACE_IID_(ISubRenderOptions, IUnknown, "7CFD3728-235E-4430-9A2D-9F25F426BD70") { // Allows one party to get information from the other party. // The memory for strings and binary data is allocated by the callee // by using LocalAlloc. It is the caller's responsibility to release the // memory by calling LocalFree. // Field names and LPWSTR values should be read case insensitive. STDMETHOD(GetBool )(LPCSTR field, bool *value) = 0; STDMETHOD(GetInt )(LPCSTR field, int *value) = 0; STDMETHOD(GetSize )(LPCSTR field, SIZE *value) = 0; STDMETHOD(GetRect )(LPCSTR field, RECT *value) = 0; STDMETHOD(GetUlonglong)(LPCSTR field, ULONGLONG *value) = 0; STDMETHOD(GetDouble )(LPCSTR field, double *value) = 0; STDMETHOD(GetString )(LPCSTR field, LPWSTR *value, int *chars) = 0; STDMETHOD(GetBin )(LPCSTR field, LPVOID *value, int *size ) = 0; // Allows one party to configure or send information to the other party. // The callee should copy the strings/binary data, if needed. // Field names and LPWSTR values should be set with the exact case listed // in this header (just to be safe). STDMETHOD(SetBool )(LPCSTR field, bool value) = 0; STDMETHOD(SetInt )(LPCSTR field, int value) = 0; STDMETHOD(SetSize )(LPCSTR field, SIZE value) = 0; STDMETHOD(SetRect )(LPCSTR field, RECT value) = 0; STDMETHOD(SetUlonglong)(LPCSTR field, ULONGLONG value) = 0; STDMETHOD(SetDouble )(LPCSTR field, double value) = 0; STDMETHOD(SetString )(LPCSTR field, LPWSTR value, int chars) = 0; STDMETHOD(SetBin )(LPCSTR field, LPVOID value, int size ) = 0; // "field" must be zero terminated // mandatory fields for consumers: // "name", LPWSTR, info, read only, get name / description of the consumer // "version", LPWSTR, info, read only, get version number of the consumer // "originalVideoSize", SIZE, info, read only, size of the video before scaling and AR adjustments // "arAdjustedVideoSize", SIZE, info, read only, size of the video after AR adjustments // "videoOutputRect", RECT, info, read only, final pos/size of the video after all scaling operations // "subtitleTargetRect", RECT, info, read only, consumer wish for where to place the subtitles // "frameRate", ULONGLONG, info, read only, frame rate of the video after deinterlacing (REFERENCE_TIME) // "refreshRate", double, info, read only, display refresh rate (0, if unknown) // mandatory fields for providers: // "name", LPWSTR, info, read only, get name / description of the provider // "version", LPWSTR, info, read only, get version number of the provider // "yuvMatrix", LPWSTR, info, read only, RGB Subtitles: "None" (fullrange); YCbCr Subtitles: "Levels.Matrix", Levels: TV|PC, Matrix: 601|709|240M|FCC|2020 // "combineBitmaps", bool, option, write/read, must the provider combine all bitmaps into one? (default: false) // optional fields for consumers: // "videoCropRect", RECT, info, read only, crops "originalVideoSize" down, e.g. because of detected black bars // "croppedVideoOutputRect", RECT, info, read only, final pos/size of the "videoCropRect", after all scaling operations // "fullscreenRect", RECT, info, read only, for fullscreen drawing, this is the rect you want to stay in (left/top can be non-zero!) // "displayModeSize", SIZE, info, read only, display mode width/height // "yuvMatrix", LPWSTR, info, read only, RGB Video: "None" (fullrange); YCbCr Video: "Levels.Matrix", Levels: TV|PC, Matrix: 601|709|240M|FCC|2020 // "supportedLevels", int, info, read only, 0: PC only (default); 1: PC+TV, no preference; 2: PC+TV, PC preferred; 3: PC+TV, TV preferred // optional fields for providers: // "outputLevels", LPWSTR, info, read only, are subtitles rendered/output in RGB "PC" (default) or "TV" levels? // "isBitmap", bool, info, read only, are the subtitles bitmap based or text based? // "isMovable", bool, info, read only, can the subtitles be repositioned safely? }; // --------------------------------------------------------------------------- // ISubRenderConsumer // --------------------------------------------------------------------------- // This interface is exposed by every subtitle consumer. //[uuid("9DF90966-FE9F-4F0E-881E-DAF8A572D900")] //interface ISubRenderConsumer : public ISubRenderOptions DECLARE_INTERFACE_IID_(ISubRenderConsumer, ISubRenderOptions, "9DF90966-FE9F-4F0E-881E-DAF8A572D900") { // Called by the subtitle renderer to ask the merit of the consumer. // Recommended merits: // - Subtitle Manager 0x00080000 // - Video Renderer 0x00040000 // - Video Post Processor 0x00020000 // - Video Decoder 0x00010000 STDMETHOD(GetMerit)(ULONG *merit) = 0; // Called by the subtitle renderer to init the provider <-> consumer // connection. The subtitle renderer provides an "ISubRenderProvider" // interface for the consumer to store and use. The consumer should // call "AddRef()" to make sure that the interface instance stays alive // as long as needed. STDMETHOD(Connect)(ISubRenderProvider *subtitleRenderer) = 0; // Called by the subtitle renderer to close the connection. The // consumer should react by immediately "Release()"ing the stored // "ISubRenderProvider" instance. STDMETHOD(Disconnect)(void) = 0; // Called by the subtitle renderer to deliver a rendered subtitle frame // to the consumer. The renderer may only deliver frames which were // requested before by the consumer. // The frames will be delivered in the same order as they were requested. // The deliverance can occur in different threads than the request, though. // The subtitle renderer can deliver a "NULL" subtitle frame to indicate // that the specified frame has no visible subtitles. The subtitle renderer // can also reuse the same "ISubRenderFrame" instance for multiple video // frames, if the subtitles didn't change. // The consumer should "AddRef()" the "ISubRenderFrame", if the consumer // wants to use it after returning from "DeliverFrame()". If the consumer // does that, it also needs to call "Release()" later when the // "ISubRenderFrame" instance is no longer needed. // The subtitle renderer should not require the "ISubRenderFrame" instance // to be released immediately. The consumer may store it for buffering/queue // purposes. All properties of the "ISubRenderFrame" instance must return // the correct results until it is released by the consumer. STDMETHOD(DeliverFrame)(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context, ISubRenderFrame *subtitleFrame) = 0; }; //[uuid("1A1737C8-2BF8-4BEA-97EA-3AB4FA8F7AC9")] //interface ISubRenderConsumer2 : public ISubRenderConsumer DECLARE_INTERFACE_IID_(ISubRenderConsumer2, ISubRenderConsumer, "1A1737C8-2BF8-4BEA-97EA-3AB4FA8F7AC9") { // Called by the subtitle renderer e.g. when the user switches to a // different subtitle track. The consumer should immediately release // all stored subtitle frames and request them anew from the subtitle // renderer. STDMETHOD(Clear)(REFERENCE_TIME clearNewerThan = 0) = 0; }; // --------------------------------------------------------------------------- // ISubRenderProvider // --------------------------------------------------------------------------- // The subtitle renderer provides the consumer with this interface, when // calling the "ISubRenderConsumer.Connect()" method. //[uuid("20752113-C883-455A-BA7B-ABA4E9115CA8")] //interface ISubRenderProvider : public ISubRenderOptions DECLARE_INTERFACE_IID_(ISubRenderProvider, ISubRenderOptions, "20752113-C883-455A-BA7B-ABA4E9115CA8") { // Called by the consumer to request a rendered subtitle frame. // The subtitle renderer will deliver the frame when it is completed, by // calling "ISubRenderConsumer.DeliverFrame()". // The subtitle renderer must pass the "context" parameter to the // consumer when calling "DeliverFrame()". // Depending on the internal thread design of the subtitle renderer, // "RequestFrame()" can return at once, with delivery being performed // asynchronously in a different thread. Alternatively, "RequestFrame()" // may also block until the frame was delivered. The consumer should not // depend on either threading model, but leave this decision to the // subtitle renderer. STDMETHOD(RequestFrame)(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context) = 0; // Called by the consumer to close the connection. The subtitle renderer // should react by immediately "Release()"ing any stored // "ISubRenderConsumer" interface instances pointing to this specific // consumer. STDMETHOD(Disconnect)(void) = 0; }; // --------------------------------------------------------------------------- // ISubRenderFrame // --------------------------------------------------------------------------- // This interface is the reply to a consumer's frame render request. //[uuid("81746AB5-9407-4B43-A014-1FAAC340F973")] //interface ISubRenderFrame : public IUnknown DECLARE_INTERFACE_IID_(ISubRenderFrame, IUnknown, "81746AB5-9407-4B43-A014-1FAAC340F973") { // "GetOutputRect()" specifies for which video rect the subtitles were // rendered. If the subtitle renderer doesn't scale the subtitles at all, // which is the recommended method for bitmap (DVD/PGS) subtitles formats, // GetOutputRect() should return "0, 0, originalVideoSize". If the subtitle // renderer scales the subtitles, which is the recommend method for text // (SRT, ASS) subtitle formats, GetOutputRect() should aim to match the // consumer's "videoOutputRect". In any case, the consumer can look at // GetOutputRect() to see if (and how) the rendered subtitles need to be // scaled before blending them onto the video image. STDMETHOD(GetOutputRect)(RECT *outputRect) = 0; // "GetClipRect()" specifies how the consumer should clip the rendered // subtitles, before blending them onto the video image. Usually, // GetClipRect() should be identical to "GetVideoOutputRect()", unless the // subtitle renderer repositioned the subtitles (see the top of this header // for more information about repositioning). STDMETHOD(GetClipRect)(RECT *clipRect) = 0; // How many separate bitmaps does this subtitle frame consist of? // The subtitle renderer should combine small subtitle elements which are // positioned near to each other, in order to optimize performance. // Ideally, if there are e.g. two subtitle lines, one at the top and one // at the bottom of the frame, the subtitle renderer should output two // bitmaps per frame. STDMETHOD(GetBitmapCount)(int *count) = 0; // Returns the premultiplied RGBA pixel data for the specified bitmap. // The ID is guaranteed to change if the content of the bitmap has changed. // The ID can stay identical if only the position changes. // Reusing the same ID for unchanged bitmaps can improve performance. // Subtitle bitmaps may move in and out of the video frame rectangle, so // the position of the subtitle bitmaps can become negative. The consumer // is required to do proper clipping if the subtitle bitmap is partially // outside the video rectangle. // The memory pointed to by "pixels" is only valid until the next // "GetBitmap" call, or until the "ISubRenderFrame" instance is released. STDMETHOD(GetBitmap)(int index, ULONGLONG *id, POINT *position, SIZE *size, LPCVOID *pixels, int *pitch) = 0; }; // =========================================================================== #endif // __SubtitelInterface__ ================================================ FILE: common/includes/common_defines.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // Set minimal target OS (Vista+) #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0600 #ifdef WINVER #undef WINVER #endif #define WINVER _WIN32_WINNT #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #define LAV_AUDIO "LAV Audio Decoder" #define LAV_VIDEO "LAV Video Decoder" #define LAV_SPLITTER "LAV Splitter" ================================================ FILE: common/includes/moreuuids.h ================================================ /* * Copyright (C) 2003-2006 Gabest * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Note: This interface was defined for the matroska container format * originally, but can be implemented for other formats as well. */ #pragma once #include #include #include #include #include #include #define WAVE_FORMAT_DOLBY_AC3 0x2000 // {00002000-0000-0010-8000-00aa00389b71} DEFINE_GUID(MEDIASUBTYPE_WAVE_DOLBY_AC3, WAVE_FORMAT_DOLBY_AC3, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_DVD_DTS 0x2001 // {00002001-0000-0010-8000-00aa00389b71} DEFINE_GUID(MEDIASUBTYPE_WAVE_DTS, WAVE_FORMAT_DVD_DTS, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // Be compatible with 3ivx #define WAVE_FORMAT_AAC 0x00FF // {000000FF-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_AAC, WAVE_FORMAT_AAC, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_LATM_AAC 0x01FF // {000001FF-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_LATM_AAC, WAVE_FORMAT_LATM_AAC, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // ... and also compatible with nero // btw, older nero parsers use a lower-case fourcc, newer upper-case (why can't it just offer both?) // {4134504D-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_MP4A, 0x4134504D, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {6134706D-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_mp4a, 0x6134706D, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_MP3 0x0055 // 00000055-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MP3, WAVE_FORMAT_MP3, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_FLAC 0xF1AC // 0000F1AC-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_FLAC, WAVE_FORMAT_FLAC, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {1541C5C0-CDDF-477d-BC0A-86F8AE7F8354} DEFINE_GUID(MEDIASUBTYPE_FLAC_FRAMED, 0x1541c5c0, 0xcddf, 0x477d, 0xbc, 0xa, 0x86, 0xf8, 0xae, 0x7f, 0x83, 0x54); #define WAVE_FORMAT_TTA1 0x77A1 // {000077A1-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_TTA1, WAVE_FORMAT_TTA1, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_WAVPACK4 0x5756 // {00005756-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_WAVPACK4, WAVE_FORMAT_WAVPACK4, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(MEDIASUBTYPE_AMR, 0x000000FE, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {726D6173-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_SAMR, 0x726D6173, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(MEDIASUBTYPE_VP70, 0x30375056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(MEDIASUBTYPE_VP80, 0x30385056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(MEDIASUBTYPE_VP90, 0x30395056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(MEDIASUBTYPE_AV01, 0x31305641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(MEDIASUBTYPE_IMA4, 0x34616D69, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {34616D69-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_SAWB, 0x62776173, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {DA5B82EE-6BD2-426f-BF1E-30112DA78AE1} DEFINE_GUID(MEDIASUBTYPE_SVCD_SUBPICTURE, 0xda5b82ee, 0x6bd2, 0x426f, 0xbf, 0x1e, 0x30, 0x11, 0x2d, 0xa7, 0x8a, 0xe1); // {7B57308F-5154-4c36-B903-52FE76E184FC} DEFINE_GUID(MEDIASUBTYPE_CVD_SUBPICTURE, 0x7b57308f, 0x5154, 0x4c36, 0xb9, 0x3, 0x52, 0xfe, 0x76, 0xe1, 0x84, 0xfc); // {0E3A2342-F6E2-4c91-BDAE-87C71EAD0D63} DEFINE_GUID(MEDIASUBTYPE_MPEG2_PVA, 0xe3a2342, 0xf6e2, 0x4c91, 0xbd, 0xae, 0x87, 0xc7, 0x1e, 0xad, 0xd, 0x63); // {6B6D0800-9ADA-11d0-A520-00A0D10129C0} DEFINE_GUID(CLSID_NetShowSource, 0x6b6d0800, 0x9ada, 0x11d0, 0xa5, 0x20, 0x0, 0xa0, 0xd1, 0x1, 0x29, 0xc0); // DirectShowMedia // {5E9C9EE0-2E4A-4f22-9906-7BBBB75AA2B6} DEFINE_GUID(MEDIASUBTYPE_DirectShowMedia, 0x5e9c9ee0, 0x2e4a, 0x4f22, 0x99, 0x6, 0x7b, 0xbb, 0xb7, 0x5a, 0xa2, 0xb6); // Dirac // {A29DA00F-A22B-40ea-98DE-2F7FECADA5DE} DEFINE_GUID(MEDIASUBTYPE_Dirac, 0xa29da00f, 0xa22b, 0x40ea, 0x98, 0xde, 0x2f, 0x7f, 0xec, 0xad, 0xa5, 0xde); // {64726376-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_DiracVideo, 0x64726376, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {D2667A7E-4055-4244-A65F-DDDDF2B74BD7} DEFINE_GUID(FORMAT_DiracVideoInfo, 0xd2667a7e, 0x4055, 0x4244, 0xa6, 0x5f, 0xdd, 0xdd, 0xf2, 0xb7, 0x4b, 0xd7); // {63617264-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_DRAC, 0x63617264, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); struct DIRACINFOHEADER { VIDEOINFOHEADER2 hdr; DWORD cbSequenceHeader; DWORD dwSequenceHeader[1]; }; // MP4 // {08E22ADA-B715-45ed-9D20-7B87750301D4} DEFINE_GUID(MEDIASUBTYPE_MP4, 0x8e22ada, 0xb715, 0x45ed, 0x9d, 0x20, 0x7b, 0x87, 0x75, 0x3, 0x1, 0xd4); // FLV // {F2FAC0F1-3852-4670-AAC0-9051D400AC54} DEFINE_GUID(MEDIASUBTYPE_FLV, 0xf2fac0f1, 0x3852, 0x4670, 0xaa, 0xc0, 0x90, 0x51, 0xd4, 0x0, 0xac, 0x54); // 31564C46-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_FLV1, 0x31564C46, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31766C66-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_flv1, 0x31766C66, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34564C46-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_FLV4, 0x34564C46, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34766C66-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_flv4, 0x34766C66, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30355056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP50, 0x30355056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30357076-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_vp50, 0x30357076, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30365056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP60, 0x30365056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30367076-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_vp60, 0x30367076, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31365056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP61, 0x31365056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31367076-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_vp61, 0x31367076, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32365056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP62, 0x32365056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32367076-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_vp62, 0x32367076, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 41365056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP6A, 0x41365056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 61367076-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_vp6a, 0x61367076, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 46365056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP6F, 0x46365056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 66367076-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_vp6f, 0x66367076, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // // RealMedia // enum { WAVE_FORMAT_14_4 = 0x2002, WAVE_FORMAT_28_8 = 0x2003, WAVE_FORMAT_ATRC = 0x0270, // WAVE_FORMAT_SONY_SCX, WAVE_FORMAT_COOK = 0x2004, WAVE_FORMAT_DNET = 0x2005, WAVE_FORMAT_RAAC = 0x2006, WAVE_FORMAT_RACP = 0x2007, WAVE_FORMAT_SIPR = 0x0130, // WAVE_FORMAT_SIPROLAB_ACEPLNET, }; // {57428EC6-C2B2-44a2-AA9C-28F0B6A5C48E} DEFINE_GUID(MEDIASUBTYPE_RealMedia, 0x57428ec6, 0xc2b2, 0x44a2, 0xaa, 0x9c, 0x28, 0xf0, 0xb6, 0xa5, 0xc4, 0x8e); // 30315652-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RV10, 0x30315652, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30325652-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RV20, 0x30325652, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30335652-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RV30, 0x30335652, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30345652-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RV40, 0x30345652, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31345652-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RV41, 0x31345652, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 345f3431-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_14_4, 0x345f3431, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 385f3832-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_28_8, 0x385f3832, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4b4f4f43-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_COOK, 0x4b4f4f43, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 54454e44-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DNET, 0x54454e44, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 52504953-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SIPR, 0x52504953, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 00000130-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SIPR_WAVE, WAVE_FORMAT_SIPR, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 43414152-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RAAC, 0x43414152, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 50434152-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RACP, 0x50434152, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); #define WAVE_FORMAT_RALF mmioFOURCC('R', 'A', 'L', 'F') DEFINE_GUID(MEDIASUBTYPE_RALF, WAVE_FORMAT_RALF, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // QuickTime PCM // 454E4F4E-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PCM_NONE, 0x454E4F4E, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 20776172-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PCM_RAW, 0x20776172, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 736f7774-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PCM_TWOS, 0x736f7774, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 74776f73-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PCM_SOWT, 0x74776f73, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34326E69-0000-0010-8000-00AA00389B71 (big-endian int24) DEFINE_GUID(MEDIASUBTYPE_PCM_IN24, 0x34326E69, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32336E69-0000-0010-8000-00AA00389B71 (big-endian int32) DEFINE_GUID(MEDIASUBTYPE_PCM_IN32, 0x32336E69, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32336C66-0000-0010-8000-00AA00389B71 (big-endian float32) DEFINE_GUID(MEDIASUBTYPE_PCM_FL32, 0x32336C66, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34366C66-0000-0010-8000-00AA00389B71 (big-endian float64) DEFINE_GUID(MEDIASUBTYPE_PCM_FL64, 0x34366C66, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // Reverse GUIDs for little-endian 'in24', 'in32', 'fl32', 'fl64' // 696E3234-0000-0010-8000-00AA00389B71 (little-endian int24, reverse 'in24') DEFINE_GUID(MEDIASUBTYPE_PCM_IN24_le, 0x696E3234, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 696E3332-0000-0010-8000-00AA00389B71 (little-endian int32, reverse 'in32') DEFINE_GUID(MEDIASUBTYPE_PCM_IN32_le, 0x696E3332, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 666C3332-0000-0010-8000-00AA00389B71 (little-endian float32, reverse 'fl32') DEFINE_GUID(MEDIASUBTYPE_PCM_FL32_le, 0x666C3332, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 666C3634-0000-0010-8000-00AA00389B71 (little-endian float64, reverse 'fl64') DEFINE_GUID(MEDIASUBTYPE_PCM_FL64_le, 0x666C3634, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // // PS2 // #define WAVE_FORMAT_PS2_PCM 0xF521 // 0000F521-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PS2_PCM, WAVE_FORMAT_PS2_PCM, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_PS2_ADPCM 0xF522 // 0000F522-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PS2_ADPCM, WAVE_FORMAT_PS2_ADPCM, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); struct WAVEFORMATEXPS2 : public WAVEFORMATEX { DWORD dwInterleave; struct WAVEFORMATEXPS2() { memset(this, 0, sizeof(*this)); cbSize = sizeof(WAVEFORMATEXPS2) - sizeof(WAVEFORMATEX); } }; // {4F3D3D21-6D7C-4f73-AA05-E397B5EAE0AA} DEFINE_GUID(MEDIASUBTYPE_PS2_SUB, 0x4f3d3d21, 0x6d7c, 0x4f73, 0xaa, 0x5, 0xe3, 0x97, 0xb5, 0xea, 0xe0, 0xaa); // ATRAC // 43525441-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ATRC, 0x43525441, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 00000270-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ATRAC3, WAVE_FORMAT_SONY_SCX, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); #define WAVE_FORMAT_ATRAC3P 0xE923AABF // E923AABF-CB58-4471-A119-FFFA01E4CE62 DEFINE_GUID(MEDIASUBTYPE_ATRAC3P, 0xE923AABF, 0xCB58, 0x4471, 0xA1, 0x19, 0xFF, 0xFA, 0x01, 0xE4, 0xCE, 0x62); // Haali's video renderer // {760A8F35-97E7-479d-AAF5-DA9EFF95D751} DEFINE_GUID(CLSID_DXR, 0x760a8f35, 0x97e7, 0x479d, 0xaa, 0xf5, 0xda, 0x9e, 0xff, 0x95, 0xd7, 0x51); DEFINE_GUID(CLSID_madVR, 0xe1a8b82a, 0x32ce, 0x4b0d, 0xbe, 0x0d, 0xaa, 0x68, 0xc7, 0x72, 0xe4, 0x23); DEFINE_GUID(CLSID_JRVR, 0x555E6803, 0x14EF, 0x4946, 0x86, 0x46, 0xB6, 0xEF, 0x9E, 0x91, 0x21, 0xE2); // // Ogg // // 9FF48807-E133-40AA-826F-9B2959E5232D DEFINE_GUID(CLSID_MPCHCOggSplitter, 0x9FF48807, 0xE133, 0x40AA, 0x82, 0x6F, 0x9B, 0x29, 0x59, 0xE5, 0x23, 0x2D); // 6D3688CE-3E9D-42F4-92CA-8A11119D25CD DEFINE_GUID(CLSID_MPCHCOggSource, 0x6D3688CE, 0x3E9D, 0x42F4, 0x92, 0xCA, 0x8A, 0x11, 0x11, 0x9D, 0x25, 0xCD); // f07e245f-5a1f-4d1e-8bff-dc31d84a55ab DEFINE_GUID(CLSID_OggSplitter, 0xf07e245f, 0x5a1f, 0x4d1e, 0x8b, 0xff, 0xdc, 0x31, 0xd8, 0x4a, 0x55, 0xab); // {078C3DAA-9E58-4d42-9E1C-7C8EE79539C5} DEFINE_GUID(CLSID_OggSplitPropPage, 0x78c3daa, 0x9e58, 0x4d42, 0x9e, 0x1c, 0x7c, 0x8e, 0xe7, 0x95, 0x39, 0xc5); // 8cae96b7-85b1-4605-b23c-17ff5262b296 DEFINE_GUID(CLSID_OggMux, 0x8cae96b7, 0x85b1, 0x4605, 0xb2, 0x3c, 0x17, 0xff, 0x52, 0x62, 0xb2, 0x96); // {AB97AFC3-D08E-4e2d-98E0-AEE6D4634BA4} DEFINE_GUID(CLSID_OggMuxPropPage, 0xab97afc3, 0xd08e, 0x4e2d, 0x98, 0xe0, 0xae, 0xe6, 0xd4, 0x63, 0x4b, 0xa4); // {889EF574-0656-4B52-9091-072E52BB1B80} DEFINE_GUID(CLSID_VorbisEnc, 0x889ef574, 0x0656, 0x4b52, 0x90, 0x91, 0x07, 0x2e, 0x52, 0xbb, 0x1b, 0x80); // {c5379125-fd36-4277-a7cd-fab469ef3a2f} DEFINE_GUID(CLSID_VorbisEncPropPage, 0xc5379125, 0xfd36, 0x4277, 0xa7, 0xcd, 0xfa, 0xb4, 0x69, 0xef, 0x3a, 0x2f); // 02391f44-2767-4e6a-a484-9b47b506f3a4 DEFINE_GUID(CLSID_VorbisDec, 0x02391f44, 0x2767, 0x4e6a, 0xa4, 0x84, 0x9b, 0x47, 0xb5, 0x06, 0xf3, 0xa4); // 77983549-ffda-4a88-b48f-b924e8d1f01c DEFINE_GUID(CLSID_OggDSAboutPage, 0x77983549, 0xffda, 0x4a88, 0xb4, 0x8f, 0xb9, 0x24, 0xe8, 0xd1, 0xf0, 0x1c); // {D2855FA9-61A7-4db0-B979-71F297C17A04} DEFINE_GUID(MEDIASUBTYPE_Ogg, 0xd2855fa9, 0x61a7, 0x4db0, 0xb9, 0x79, 0x71, 0xf2, 0x97, 0xc1, 0x7a, 0x4); // cddca2d5-6d75-4f98-840e-737bedd5c63b DEFINE_GUID(MEDIASUBTYPE_Vorbis, 0xcddca2d5, 0x6d75, 0x4f98, 0x84, 0x0e, 0x73, 0x7b, 0xed, 0xd5, 0xc6, 0x3b); // 6bddfa7e-9f22-46a9-ab5e-884eff294d9f DEFINE_GUID(FORMAT_VorbisFormat, 0x6bddfa7e, 0x9f22, 0x46a9, 0xab, 0x5e, 0x88, 0x4e, 0xff, 0x29, 0x4d, 0x9f); typedef struct tagVORBISFORMAT { WORD nChannels; DWORD nSamplesPerSec; DWORD nMinBitsPerSec; DWORD nAvgBitsPerSec; DWORD nMaxBitsPerSec; float fQuality; } VORBISFORMAT, *PVORBISFORMAT, FAR *LPVORBISFORMAT; // {8D2FD10B-5841-4a6b-8905-588FEC1ADED9} DEFINE_GUID(MEDIASUBTYPE_Vorbis2, 0x8d2fd10b, 0x5841, 0x4a6b, 0x89, 0x5, 0x58, 0x8f, 0xec, 0x1a, 0xde, 0xd9); // {B36E107F-A938-4387-93C7-55E966757473} DEFINE_GUID(FORMAT_VorbisFormat2, 0xb36e107f, 0xa938, 0x4387, 0x93, 0xc7, 0x55, 0xe9, 0x66, 0x75, 0x74, 0x73); typedef struct tagVORBISFORMAT2 { DWORD Channels; DWORD SamplesPerSec; DWORD BitsPerSample; DWORD HeaderSize[3]; // 0: Identification, 1: Comment, 2: Setup } VORBISFORMAT2, *PVORBISFORMAT2, FAR *LPVORBISFORMAT2; // // Matroska // // {1AC0BEBD-4D2B-45ad-BCEB-F2C41C5E3788} DEFINE_GUID(MEDIASUBTYPE_Matroska, 0x1ac0bebd, 0x4d2b, 0x45ad, 0xbc, 0xeb, 0xf2, 0xc4, 0x1c, 0x5e, 0x37, 0x88); // {E487EB08-6B26-4be9-9DD3-993434D313FD} DEFINE_GUID(MEDIATYPE_Subtitle, 0xe487eb08, 0x6b26, 0x4be9, 0x9d, 0xd3, 0x99, 0x34, 0x34, 0xd3, 0x13, 0xfd); // {87C0B230-03A8-4fdf-8010-B27A5848200D} DEFINE_GUID(MEDIASUBTYPE_UTF8, 0x87c0b230, 0x3a8, 0x4fdf, 0x80, 0x10, 0xb2, 0x7a, 0x58, 0x48, 0x20, 0xd); // {3020560F-255A-4ddc-806E-6C5CC6DCD70A} DEFINE_GUID(MEDIASUBTYPE_SSA, 0x3020560f, 0x255a, 0x4ddc, 0x80, 0x6e, 0x6c, 0x5c, 0xc6, 0xdc, 0xd7, 0xa); // {326444F7-686F-47ff-A4B2-C8C96307B4C2} DEFINE_GUID(MEDIASUBTYPE_ASS, 0x326444f7, 0x686f, 0x47ff, 0xa4, 0xb2, 0xc8, 0xc9, 0x63, 0x7, 0xb4, 0xc2); // {370689E7-B226-4f67-978D-F10BC1A9C6AE} DEFINE_GUID(MEDIASUBTYPE_ASS2, 0x370689e7, 0xb226, 0x4f67, 0x97, 0x8d, 0xf1, 0xb, 0xc1, 0xa9, 0xc6, 0xae); // {76C421C4-DB89-42ec-936E-A9FBC1794714} DEFINE_GUID(MEDIASUBTYPE_SSF, 0x76c421c4, 0xdb89, 0x42ec, 0x93, 0x6e, 0xa9, 0xfb, 0xc1, 0x79, 0x47, 0x14); // {B753B29A-0A96-45be-985F-68351D9CAB90} DEFINE_GUID(MEDIASUBTYPE_USF, 0xb753b29a, 0xa96, 0x45be, 0x98, 0x5f, 0x68, 0x35, 0x1d, 0x9c, 0xab, 0x90); // {F7239E31-9599-4e43-8DD5-FBAF75CF37F1} DEFINE_GUID(MEDIASUBTYPE_VOBSUB, 0xf7239e31, 0x9599, 0x4e43, 0x8d, 0xd5, 0xfb, 0xaf, 0x75, 0xcf, 0x37, 0xf1); // {A33D2F7D-96BC-4337-B23B-A8B9FBC295E9} DEFINE_GUID(FORMAT_SubtitleInfo, 0xa33d2f7d, 0x96bc, 0x4337, 0xb2, 0x3b, 0xa8, 0xb9, 0xfb, 0xc2, 0x95, 0xe9); // {04EBA53E-9330-436c-9133-553EC87031DC} DEFINE_GUID(MEDIASUBTYPE_HDMVSUB, 0x4eba53e, 0x9330, 0x436c, 0x91, 0x33, 0x55, 0x3e, 0xc8, 0x70, 0x31, 0xdc); // {C886D215-F485-40BB-8DB6-FADBC619A45D} DEFINE_GUID(MEDIASUBTYPE_WEBVTT, 0xc886d215, 0xf485, 0x40bb, 0x8d, 0xb6, 0xfa, 0xdb, 0xc6, 0x19, 0xa4, 0x5d); #pragma pack(push, 1) typedef struct { DWORD dwOffset; CHAR IsoLang[4]; // three letter lang code + terminating zero WCHAR TrackName[256]; // 256 chars ought to be enough for everyone :) } SUBTITLEINFO; #pragma pack(pop) // SUBTITLEINFO structure content starting at dwOffset (also the content of CodecPrivate) // -------------------------------------------------------------------------------------- // // Here the text should start with the Byte Order Mark, even though // UTF-8 is preferred, it also helps identifying the encoding type. // // MEDIASUBTYPE_USF: // // // // // // // ... every element excluding ... // // // MEDIASUBTYPE_SSA/ASS: // // The file header and all sub-sections except [Events] // // MEDIATYPE_VOBSUB: // // TODO // // Data description of the media samples (everything is UTF-8 encoded here) // ------------------------------------------------------------------------ // // MEDIASUBTYPE_USF: // // The text _inside_ the .. element. // // Since timing is set on the sample, there is no need to put // into the data. // // MEDIASUBTYPE_SSA/ASS: // // Comma separated values similar to the "Dialogue: ..." line with these fields: // ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text // // With the exception of ReadOrder every field can be found in ASS files. The // ReadOrder field is needed for the decoder to be able to reorder the streamed // samples as they were placed originally in the file. // // If the source is only SSA, the Layer field can be left empty. // // MEDIATYPE_VOBSUB: // // Standard dvd subpic data, without the stream id at the beginning. // // Matroska CodecID mappings // ------------------------ // // S_TEXT/ASCII <-> MEDIATYPE_Text MEDIASUBTYPE_NULL FORMAT_None // S_TEXT/UTF8 <-> MEDIATYPE_Subtitle MEDIASUBTYPE_UTF8 FORMAT_SubtitleInfo // S_TEXT/SSA <-> MEDIATYPE_Subtitle MEDIASUBTYPE_SSA FORMAT_SubtitleInfo // S_TEXT/ASS <-> MEDIATYPE_Subtitle MEDIASUBTYPE_ASS FORMAT_SubtitleInfo // S_TEXT/USF <-> MEDIATYPE_Subtitle MEDIASUBTYPE_USF FORMAT_SubtitleInfo // S_VOBSUB <-> MEDIATYPE_Subtitle MEDIASUBTYPE_VOBSUB FORMAT_SubtitleInfo // S_VOBSUB/ZLIB<-> MEDIATYPE_Subtitle MEDIASUBTYPE_VOBSUB FORMAT_SubtitleInfo // /* DEFINE_GUID( MEDIATYPE_MPEG2_SECTIONS, 0x455f176c, 0x4b06, 0x47ce, 0x9a, 0xef, 0x8c, 0xae, 0xf7, 0x3d, 0xf7, 0xb5); DEFINE_GUID(MEDIASUBTYPE_ATSC_SI, 0xb3c7397c, 0xd303, 0x414d, 0xb3, 0x3c, 0x4e, 0xd2, 0xc9, 0xd2, 0x97, 0x33); DEFINE_GUID(MEDIASUBTYPE_DVB_SI, 0xe9dd31a3, 0x221d, 0x4adb, 0x85, 0x32, 0x9a, 0xf3, 0x9, 0xc1, 0xa4, 0x8); // {C892E55B-252D-42b5-A316-D997E7A5D995} DEFINE_GUID(MEDIASUBTYPE_MPEG2DATA, 0xc892e55b, 0x252d, 0x42b5, 0xa3, 0x16, 0xd9, 0x97, 0xe7, 0xa5, 0xd9, 0x95); */ // H264 // 6F29D2AD-E130-45AA-B42F-F623AD354A90 DEFINE_GUID(MEDIASUBTYPE_ArcsoftH264, 0x6F29D2AD, 0xE130, 0x45AA, 0xB4, 0x2F, 0xF6, 0x23, 0xAD, 0x35, 0x4A, 0x90); // 48535356-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VSSH, 0x48535356, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 68737376-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_vssh, 0x68737376, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 43564144-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DAVC, 0x43564144, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 63766164-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_davc, 0x63766164, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 43564150-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PAVC, 0x43564150, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 63766170-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_pavc, 0x63766170, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31637661-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_avc1, 0x31637661, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31564343-0000-0010-8000-00AA00389B71 (custom H.264 FourCC used by Haali Media Splitter) DEFINE_GUID(MEDIASUBTYPE_CCV1, 0x31564343, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 8D2D71CB-243F-45E3-B2D8-5FD7967EC09B <= Use by MediaPortal for example... DEFINE_GUID(MEDIASUBTYPE_H264_bis, 0x8D2D71CB, 0x243F, 0x45E3, 0xB2, 0xD8, 0x5F, 0xD7, 0x96, 0x7E, 0xC0, 0x9B); // 33515653-0000-0010-8000-00aa00389b71 DEFINE_GUID(MEDIASUBTYPE_SVQ3, 0x33515653, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 56564D41-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_XVID, 0x44495658, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 56564D41-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_xvid, 0x64697678, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30355844-0000-0010-8000-00aa00389b71 DEFINE_GUID(MEDIASUBTYPE_DX50, 0x30355844, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30357864-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_dx50, 0x30357864, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 56564D41-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DIVX, 0x58564944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 78766964-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_divx, 0x78766964, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 78766944-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_Divx, 0x78766944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 5634504d-0000-0010-8000-00aa00389b71 DEFINE_GUID(MEDIASUBTYPE_MP4V, 0x5634504d, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 7634706D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_mp4v, 0x7634706D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31564933-0000-0010-8000-00aa00389b71 DEFINE_GUID(MEDIASUBTYPE_3IV1, 0x31564933, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31766933-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_3iv1, 0x31766933, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32564933-0000-0010-8000-00aa00389b71 DEFINE_GUID(MEDIASUBTYPE_3IV2, 0x32564933, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32766933-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_3iv2, 0x32766933, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 58564933-0000-0010-8000-00aa00389b71 DEFINE_GUID(MEDIASUBTYPE_3IVX, 0x58564933, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 78766933-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_3ivx, 0x78766933, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 305A4C42-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_BLZ0, 0x305A4C42, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 307A6C62-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_blz0, 0x307A6C62, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // {564F4547-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_GEOV, 0x564F4547, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 56344D44-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DM4V, 0x56344D44, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 76346D64-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_dm4v, 0x76346D64, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4D475844-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DXGM, 0x4D475844, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 6D677864-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_dxgm, 0x6D677864, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 53444646-0000-0010-8000-00aa00389b71 DEFINE_GUID(MEDIASUBTYPE_FFDS, 0x53444646, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 73646666-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ffds, 0x73646666, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 57465646-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_FVFW, 0x57465646, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 77667666-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_fvfw, 0x77667666, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34504D46-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_FMP4, 0x34504D46, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34706D66-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_fmp4, 0x34706D66, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34584448-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_HDX4, 0x34584448, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34786468-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_hdx4, 0x34786468, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34504D4C-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_LMP4, 0x34504D4C, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34706D6C-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_lmp4, 0x34706D6C, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4749444E-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_NDIG, 0x4749444E, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 6769646E-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ndig, 0x6769646E, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34504D52-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RMP4, 0x34504D52, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34706D72-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_rmp4, 0x34706D72, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34504D53-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SMP4, 0x34504D53, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34706D73-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_smp4, 0x34706D73, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 47444553-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SEDG, 0x47444553, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 67646573-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_sedg, 0x67646573, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34504D55-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_UMP4, 0x34504D55, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34706D75-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ump4, 0x34706D75, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 46315657-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_WV1F, 0x46315657, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 66317677-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_wv1f, 0x66317677, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 58495658-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_XVIX, 0x58495658, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 78697678-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_xvix, 0x78697678, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31515653-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SVQ1, 0x31515653, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33363248-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_H263, 0x33363248, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33363268-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_h263, 0x33363268, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33363249-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_I263, 0x33363249, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33363269-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_i263, 0x33363269, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31363248-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_H261, 0x31363248, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31363268-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_h261, 0x31363268, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_S263, 0x33363273, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33363273-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_s263, 0x33363273, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 56564D41-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AMVV, 0x56564D41, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 46564D41-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AMVF, 0x46564D41, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33585644-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVX3, 0x33585644, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33787664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_dvx3, 0x33787664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 44564933-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_3IVD, 0x44564933, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33564944-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DIV3, 0x33564944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33766964-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_div3, 0x33766964, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 314C4F43-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_COL1, 0x314C4F43, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 316C6F63-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_col1, 0x316C6F63, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34564944-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DIV4, 0x34564944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34766964-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_div4, 0x34766964, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 35564944-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DIV5, 0x35564944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 35766964-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_div5, 0x35766964, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 36564944-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DIV6, 0x36564944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 36766964-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_div6, 0x36766964, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31345041-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AP41, 0x31345041, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31347061-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ap41, 0x31347061, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 3347504D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MPG3, 0x3347504D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 3367706D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_mpg3, 0x3367706D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32564944-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DIV2, 0x32564944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32766964-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_div2, 0x32766964, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31564944-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DIV1, 0x31564944, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31766964-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_div1, 0x31766964, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 3134504D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MP41, 0x3134504D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 3134706D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_mp41, 0x3134706D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4F454854-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_THEORA, 0x4F454854, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 6F656874-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_theora, 0x6F656874, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 63637374-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_TSCC, 0x63637374, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32637374-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_TSC2, 0x32637374, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30355649-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_IV50, 0x30355649, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31345649-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_IV41, 0x31345649, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31335649-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_IV31, 0x31335649, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32335649-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_IV32, 0x32335649, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 48564443-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_CDVH, 0x48564443, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 43564443-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_CDVC, 0x43564443, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 35564443-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_CDV5, 0x35564443, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 35325644-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DV25, 0x35325644, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 30355644-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DV50, 0x30355644, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 70637664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVCP, 0x70637664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 70707664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVPP, 0x70707664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 70357664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DV5P, 0x70357664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 6E357664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DV5N, 0x6E357664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 70637664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVC, 0x20637664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 31687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVH1, 0x31687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 32687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVH2, 0x32687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 33687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVH3, 0x33687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 34687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVH4, 0x34687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 35687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVH5, 0x35687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 36687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVH6, 0x36687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 71687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVHQ, 0x71687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 70687664-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DVHP, 0x70687664, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 76645641-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AVdv, 0x76645641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 31645641-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AVd1, 0x31645641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 31535046-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_FPS1, 0x31535046, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 55594648-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_HuffYUV, 0x55594648, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 5347414C-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_Lagarith, 0x5347414C, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 64697663-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_CVID, 0x64697663, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 694B4942-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_BIKI, 0x694B4942, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 624B4942-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_BIKB, 0x624B4942, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 664b4942-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_BIKf, 0x664b4942, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(FORMAT_RLTheora, 0xe69b30d1, 0x7d65, 0x4166, 0xb9, 0x90, 0x10, 0x3d, 0xa8, 0xc9, 0x11, 0xe3); // 62706A6D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MJPGB, 0x62706A6D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 30365056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP30, 0x30335056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30365056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP31, 0x31335056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 324B4D53-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SMK2, 0x324B4D53, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 344B4D53-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SMK4, 0x344B4D53, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 44435343-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_CSCD, 0x44435343, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 47455051-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_QPEG, 0x47455051, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 302E3151-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_QP10, 0x302E3151, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 312E3151-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_QP11, 0x312E3151, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 485A534D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MSZH, 0x485A534D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 42494C5A-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ZLIB, 0x42494C5A, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 20676E70-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_PNG, 0x20676E70, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_TIFF, MAKEFOURCC('T', 'I', 'F', 'F'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_BMP, MAKEFOURCC('B', 'M', 'P', ' '), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_GIF, MAKEFOURCC('G', 'I', 'F', ' '), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_TGA, MAKEFOURCC('T', 'G', 'A', ' '), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_FSV1, 0x31565346, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_CRAM, MAKEFOURCC('C', 'R', 'A', 'M'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_MSVC, MAKEFOURCC('M', 'S', 'V', 'C'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_WHAM, MAKEFOURCC('W', 'H', 'A', 'M'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_8BPS, MAKEFOURCC('8', 'B', 'P', 'S'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_LOCO, MAKEFOURCC('L', 'O', 'C', 'O'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ZMBV, MAKEFOURCC('Z', 'M', 'B', 'V'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_VCR1, MAKEFOURCC('V', 'C', 'R', '1'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_AASC, MAKEFOURCC('A', 'A', 'S', 'C'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_SNOW, MAKEFOURCC('S', 'N', 'O', 'W'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_FFV1, MAKEFOURCC('F', 'F', 'V', '1'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_FFVH, MAKEFOURCC('F', 'F', 'V', 'H'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_v410, MAKEFOURCC('v', '4', '1', '0'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_VMNC, MAKEFOURCC('V', 'M', 'n', 'c'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // Apple ProRes DEFINE_GUID(MEDIASUBTYPE_apch, 0x68637061, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_apcn, 0x6e637061, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_apcs, 0x73637061, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_apco, 0x6f637061, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ap4h, 0x68347061, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ap4x, 0x78347061, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // Apple ICOD DEFINE_GUID(MEDIASUBTYPE_icod, 0x646F6369, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // Ut Video DEFINE_GUID(MEDIASUBTYPE_ULRA, MAKEFOURCC('U', 'L', 'R', 'A'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ULRG, MAKEFOURCC('U', 'L', 'R', 'G'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ULY0, MAKEFOURCC('U', 'L', 'Y', '0'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ULY2, MAKEFOURCC('U', 'L', 'Y', '2'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ULY4, MAKEFOURCC('U', 'L', 'Y', '4'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UQY2, MAKEFOURCC('U', 'Q', 'Y', '2'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UQRG, MAKEFOURCC('U', 'Q', 'R', 'G'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UQRA, MAKEFOURCC('U', 'Q', 'R', 'A'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ULH0, MAKEFOURCC('U', 'L', 'H', '0'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ULH2, MAKEFOURCC('U', 'L', 'H', '2'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ULH4, MAKEFOURCC('U', 'L', 'H', '4'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UMY2, MAKEFOURCC('U', 'M', 'Y', '2'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UMH2, MAKEFOURCC('U', 'M', 'H', '2'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UMY4, MAKEFOURCC('U', 'M', 'Y', '4'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UMH4, MAKEFOURCC('U', 'M', 'H', '4'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UMRG, MAKEFOURCC('U', 'M', 'R', 'G'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_UMRA, MAKEFOURCC('U', 'M', 'R', 'A'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // G2M DEFINE_GUID(MEDIASUBTYPE_G2M2, MAKEFOURCC('G', '2', 'M', '2'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_G2M3, MAKEFOURCC('G', '2', 'M', '3'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_G2M4, MAKEFOURCC('G', '2', 'M', '4'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_G2M5, MAKEFOURCC('G', '2', 'M', '5'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // CFHD DEFINE_GUID(MEDIASUBTYPE_CFHD, MAKEFOURCC('C', 'F', 'H', 'D'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // MagicYUV DEFINE_GUID(MEDIASUBTYPE_MAGY, MAKEFOURCC('M', 'A', 'G', 'Y'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_M8RG, MAKEFOURCC('M', '8', 'R', 'G'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_M8RA, MAKEFOURCC('M', '8', 'R', 'A'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_M8G0, MAKEFOURCC('M', '8', 'G', '0'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_M8Y0, MAKEFOURCC('M', '8', 'Y', '0'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_M8Y2, MAKEFOURCC('M', '8', 'Y', '2'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_M8Y4, MAKEFOURCC('M', '8', 'Y', '4'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_M8YA, MAKEFOURCC('M', '8', 'Y', 'A'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // MagicYUV DEFINE_GUID(MEDIASUBTYPE_FICV, MAKEFOURCC('F', 'I', 'C', 'V'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // DNxHD // {6E645641-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_AVdn, 0x6E645641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // DNxHR // {68645641-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_AVdh, 0x68645641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // JPEG2000 // {32706A6D-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_mjp2, 0x32706A6D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // {43324A4D-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_MJ2C, 0x43324A4D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // {43324A4C-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_LJ2C, 0x43324A4C, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // {4B324A4C-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_LJ2K, 0x4B324A4C, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // {324A5049-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_IPJ2, 0x324A5049, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // {D80FA03C-35C1-4FA1-8C8E-375C8667166E} DEFINE_GUID(MEDIASUBTYPE_LAV_RAWVIDEO, 0xd80fa03c, 0x35c1, 0x4fa1, 0x8c, 0x8e, 0x37, 0x5c, 0x86, 0x67, 0x16, 0x6e); // {434C4641-0000-0010-8000-00AA00389B71} DEFINE_GUID(MEDIASUBTYPE_FLIC, 0x434C4641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // {} DEFINE_GUID(MEDIASUBTYPE_THPV, MAKEFOURCC('T', 'H', 'P', 'V'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_ROQV, MAKEFOURCC('R', 'o', 'Q', 'V'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31435648-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_HVC1, 0x31435648, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 43564548-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_HEVC, 0x43564548, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30314D48-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_HM10, 0x30314D48, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 35363248-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_H265, 0x35363248, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // VVC ("VVC1") DEFINE_GUID(MEDIASUBTYPE_VVC1, MAKEFOURCC('V', 'V', 'C', '1'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // Full MVC DEFINE_GUID(MEDIASUBTYPE_AMVC, MAKEFOURCC('A', 'M', 'V', 'C'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // Full MVC in mp4-form DEFINE_GUID(MEDIASUBTYPE_MVC1, MAKEFOURCC('M', 'V', 'C', '1'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // Subset MVC DEFINE_GUID(MEDIASUBTYPE_EMVC, MAKEFOURCC('E', 'M', 'V', 'C'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); DEFINE_GUID(MEDIASUBTYPE_WEBP, MAKEFOURCC('W', 'E', 'B', 'P'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); DEFINE_GUID(MEDIASUBTYPE_APV1, MAKEFOURCC('A', 'P', 'V', '1'), 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4B435544-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DUCK, 0x4B435544, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30324D54-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_TM20, 0x30324D54, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 20636D73-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_smc, 0x20636D73, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4C584956-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VIXL, 0x4C584956, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 49544C55-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ULTI, 0x49544C55, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31564E57-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_WNV1, 0x31564E57, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 76757963-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_CYUV, 0x76757963, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31565341-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AVS1, 0x31565341, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 32565341-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AVS2, 0x32565341, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31325452-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_RT21, 0x31325452, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 6E525641-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_AVRn, 0x6E525641, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 47504a4c-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_LJPG, 0x47504a4c, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4C47504A-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_JPGL, 0x4C47504A, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 534c4a4d-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MJLS, 0x534c4a4d, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 41504a4d-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MJPA, 0x41504a4d, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 42504a4d-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MJPB, 0x42504a4d, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 58355053-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SP5X, 0x58355053, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 31706148-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_Hap1, 0x31706148, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 35706148-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_Hap5, 0x35706148, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 59706148-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_HapY, 0x59706148, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 33445844-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DXD3, 0x33445844, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 49445844-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_DXDI, 0x49445844, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 574D5632-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_2VMW, 0x574D5632, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 56334357-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_WC3V, 0x56334357, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 4345444D-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MDEC, 0x4345444D, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 564D5834-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_4XMV, 0x564D5834, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 43425241-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ARBC, 0x43425241, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 30345056-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VP40, 0x30345056, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 34355053-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_SP54, 0x34355053, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // 3156474B-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_KGV1, 0x3156474B, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); // Audio codecs // 41564D41-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_IMA_AMV, 0x41564D41, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 4C4C454E-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_NELLYMOSER, 0x4C4C454E, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000006-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ALAW, WAVE_FORMAT_ALAW, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000007-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MULAW, WAVE_FORMAT_MULAW, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000031-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_MSGSM610, WAVE_FORMAT_GSM610, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000002-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ADPCM_MS, WAVE_FORMAT_ADPCM, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000022-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_TRUESPEECH, WAVE_FORMAT_DSPGROUP_TRUESPEECH, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000075-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_VOXWARE_RT29, WAVE_FORMAT_VOXWARE_RT29, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 324D4451-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_QDM2, 0x324D4451, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 63616C61-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ALAC, 0x63616C61, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // B82196E9-1B3F-4796-A636-46239087B38E dsfTAKsource specific DEFINE_GUID(MEDIASUBTYPE_TAK, 0xB82196E9, 0x1B3F, 0x4796, 0xA6, 0x36, 0x46, 0x23, 0x90, 0x87, 0xB3, 0x8E); // 20534C41-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_ALS, 0x20534C41, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 0000729A-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_729A, 0x0000729A, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000133-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_G729, 0x00000133, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 36323767-0000-0010-8000-00AA00389B71Add commentMore actions DEFINE_GUID(MEDIASUBTYPE_G726, 0x36323767, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 00000401-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_IMC, 0x00000401, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // 0000011-0000-0010-8000-00AA00389B71 DEFINE_GUID(MEDIASUBTYPE_IMA_WAV, WAVE_FORMAT_IMA_ADPCM, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {A23EB7FC-510B-466F-9FBF-5F878F69347C} LAVF/LAVC specific DEFINE_GUID(MEDIASUBTYPE_BD_LPCM_AUDIO, 0xa23eb7fc, 0x510b, 0x466f, 0x9f, 0xbf, 0x5f, 0x87, 0x8f, 0x69, 0x34, 0x7c); // {53544441-0000-0010-8000-00AA00389B71} AAC-ADTS LAVF/LAVC specific #define WAVE_FORMAT_AAC_ADTS mmioFOURCC('A', 'D', 'T', 'S') DEFINE_GUID(MEDIASUBTYPE_AAC_ADTS, WAVE_FORMAT_AAC_ADTS, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {33534541-0000-0010-8000-00AA00389B71} S302M AES3 #define WAVE_FORMAT_S302M_AES3 mmioFOURCC('A', 'E', 'S', '3') DEFINE_GUID(MEDIASUBTYPE_AES3, WAVE_FORMAT_S302M_AES3, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // {949F97FD-56F6-4527-B4AE-DDEB375AB80F} Mpc-hc specific ! DEFINE_GUID(MEDIASUBTYPE_HDMV_LPCM_AUDIO, 0x949f97fd, 0x56f6, 0x4527, 0xb4, 0xae, 0xdd, 0xeb, 0x37, 0x5a, 0xb8, 0xf); #define WAVE_FORMAT_MLP mmioFOURCC('M', 'L', 'P', ' ') DEFINE_GUID(MEDIASUBTYPE_MLP, WAVE_FORMAT_MLP, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); #define WAVE_FORMAT_SPEEX 0xA109 DEFINE_GUID(MEDIASUBTYPE_SPEEX, WAVE_FORMAT_SPEEX, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71); #ifndef WAVE_FORMAT_OPUS #define WAVE_FORMAT_OPUS 0x704F #endif DEFINE_GUID(MEDIASUBTYPE_OPUS, WAVE_FORMAT_OPUS, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_OPUS_OLD mmioFOURCC('O', 'P', 'U', 'S') DEFINE_GUID(MEDIASUBTYPE_OPUS_OLD, WAVE_FORMAT_OPUS_OLD, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_DSDL mmioFOURCC('D', 'S', 'D', 'L') DEFINE_GUID(MEDIASUBTYPE_DSDL, WAVE_FORMAT_DSDL, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_DSDM mmioFOURCC('D', 'S', 'D', 'M') DEFINE_GUID(MEDIASUBTYPE_DSDM, WAVE_FORMAT_DSDM, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_DSD1 mmioFOURCC('D', 'S', 'D', '1') DEFINE_GUID(MEDIASUBTYPE_DSD1, WAVE_FORMAT_DSD1, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); #define WAVE_FORMAT_DSD8 mmioFOURCC('D', 'S', 'D', '8') DEFINE_GUID(MEDIASUBTYPE_DSD8, WAVE_FORMAT_DSD8, 0x000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); struct WAVEFORMATEX_HDMV_LPCM : public WAVEFORMATEX { BYTE channel_conf; struct WAVEFORMATEX_HDMV_LPCM() { memset(this, 0, sizeof(*this)); cbSize = sizeof(WAVEFORMATEX_HDMV_LPCM) - sizeof(WAVEFORMATEX); } }; // {AFBC2343-3DCB-4047-9655-E1E62A61B1C5} DEFINE_GUID(MEDIASUBTYPE_FFMPEG_AUDIO, 0xafbc2343, 0x3dcb, 0x4047, 0x96, 0x55, 0xe1, 0xe6, 0x2a, 0x61, 0xb1, 0xc5); // {35189950-CAC9-4C8D-819D-B6FAEE15DD9D} DEFINE_GUID(FORMAT_WaveFormatExFFMPEG, 0x35189950, 0xcac9, 0x4c8d, 0x81, 0x9d, 0xb6, 0xfa, 0xee, 0x15, 0xdd, 0x9d); struct WAVEFORMATEXFFMPEG { int nCodecId; WAVEFORMATEX wfex; struct WAVEFORMATEXFFMPEG() { nCodecId = 0; } }; // {20884BC2-629F-45EA-B1C5-FA4FFA438250} DEFINE_GUID(MEDIASUBTYPE_LAVBluRay, 0x20884bc2, 0x629f, 0x45ea, 0xb1, 0xc5, 0xfa, 0x4f, 0xfa, 0x43, 0x82, 0x50); // Additionnal DXVA GUIDs // Intel ClearVideo VC1 bitstream decoder DEFINE_GUID(DXVA_Intel_VC1_ClearVideo, 0xBCC5DB6D, 0xA2B6, 0x4AF0, 0xAC, 0xE4, 0xAD, 0xB1, 0xF7, 0x87, 0xBC, 0x89); DEFINE_GUID(DXVA_Intel_VC1_ClearVideo_2, 0xE07EC519, 0xE651, 0x4CD6, 0xAC, 0x84, 0x13, 0x70, 0xCC, 0xEE, 0xC8, 0x51); // Intel ClearVideo H264 decoders DEFINE_GUID(DXVADDI_Intel_ModeH264_A, 0x604F8E64, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6); DEFINE_GUID(DXVADDI_Intel_ModeH264_C, 0x604F8E66, 0x4951, 0x4c54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6); DEFINE_GUID(DXVADDI_Intel_ModeH264_E, 0x604F8E68, 0x4951, 0x4C54, 0x88, 0xFE, 0xAB, 0xD2, 0x5C, 0x15, 0xB3, 0xD6); // Generic DXVA2 GUIDs DEFINE_GUID(DXVA2_ModeMPEG2and1_VLD, 0x86695f12, 0x340e, 0x4f04, 0x9f, 0xd3, 0x92, 0x53, 0xdd, 0x32, 0x74, 0x60); DEFINE_GUID(DXVA2_ModeMPEG1_VLD, 0x6f3ec719, 0x3735, 0x42cc, 0x80, 0x63, 0x65, 0xcc, 0x3c, 0xb3, 0x66, 0x16); DEFINE_GUID(DXVA_ModeH264_VLD_WithFMOASO_NoFGT, 0xd5f04ff9, 0x3418, 0x45d8, 0x95, 0x61, 0x32, 0xa7, 0x6a, 0xae, 0x2d, 0xdd); DEFINE_GUID(DXVA_ModeH264_VLD_NoFGT_Flash, 0x4245F676, 0x2BBC, 0x4166, 0xa0, 0xBB, 0x54, 0xE7, 0xB8, 0x49, 0xC3, 0x80); /* Conformity to the August 2010 update of the specification, ModeVC1_VLD2010 */ DEFINE_GUID(DXVA2_ModeVC1_D2010, 0x1b81beA4, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); // MPEG4-ASP DEFINE_GUID(DXVA_nVidia_MPEG4_ASP, 0x9947EC6F, 0x689B, 0x11DC, 0xA3, 0x20, 0x00, 0x19, 0xDB, 0xBC, 0x41, 0x84); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_Simple, 0xefd64d74, 0xc9e8, 0x41d7, 0xa5, 0xe9, 0xe9, 0xb0, 0xe3, 0x9f, 0xa3, 0x19); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC, 0xed418a9f, 0x10d, 0x4eda, 0x9a, 0xe3, 0x9a, 0x65, 0x35, 0x8d, 0x8d, 0x2e); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC, 0xab998b5b, 0x4258, 0x44a9, 0x9f, 0xeb, 0x94, 0xe5, 0x97, 0xa6, 0xba, 0xae); DEFINE_GUID(DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo, 0x7C74ADC6, 0xe2ba, 0x4ade, 0x86, 0xde, 0x30, 0xbe, 0xab, 0xb4, 0x0c, 0xc1); // DXVA2 MVC modes DEFINE_GUID(DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT, 0xd79be8da, 0xcf1, 0x4c81, 0xb8, 0x2a, 0x69, 0xa4, 0xe2, 0x36, 0xf4, 0x3d); DEFINE_GUID(DXVA_ModeH264_VLD_Stereo_NoFGT, 0xf9aaccbb, 0xc2b6, 0x4cfc, 0x87, 0x79, 0x57, 0x7, 0xb1, 0x76, 0x5, 0x52); DEFINE_GUID(DXVA_ModeH264_VLD_Multiview_NoFGT, 0x705b9d82, 0x76cf, 0x49d6, 0xb7, 0xe6, 0xac, 0x88, 0x72, 0xdb, 0x1, 0x3c); // DXVA2 SVC modes DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Scalable_Baseline, 0xc30700c4, 0xe384, 0x43e0, 0xb9, 0x82, 0x2d, 0x89, 0xee, 0x7f, 0x77, 0xc4); DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline, 0x9b8175d4, 0xd670, 0x4cf2, 0xa9, 0xf0, 0xfa, 0x56, 0xdf, 0x71, 0xa1, 0xae); DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Scalable_High, 0x728012c9, 0x66a8, 0x422f, 0x97, 0xe9, 0xb5, 0xe3, 0x9b, 0x51, 0xc0, 0x53); DEFINE_GUID(DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive, 0x8efa5926, 0xbd9e, 0x4b04, 0x8b, 0x72, 0x8f, 0x97, 0x7d, 0xc4, 0x4c, 0x36); DEFINE_GUID(DXVA2_ModeMPEG2_MoComp, 0xe6a9f44b, 0x61b0, 0x4563, 0x9e, 0xa4, 0x63, 0xd2, 0xa3, 0xc6, 0xfe, 0x66); DEFINE_GUID(DXVA2_ModeMPEG2_IDCT, 0xbf22ad00, 0x03ea, 0x4690, 0x80, 0x77, 0x47, 0x33, 0x46, 0x20, 0x9b, 0x7e); DEFINE_GUID(DXVA2_ModeMPEG2_VLD, 0xee27417f, 0x5e28, 0x4e65, 0xbe, 0xea, 0x1d, 0x26, 0xb5, 0x08, 0xad, 0xc9); DEFINE_GUID(DXVA2_ModeH264_A, 0x1b81be64, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeH264_B, 0x1b81be65, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeH264_C, 0x1b81be66, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeH264_D, 0x1b81be67, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeH264_E, 0x1b81be68, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeH264_F, 0x1b81be69, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeWMV8_A, 0x1b81be80, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeWMV8_B, 0x1b81be81, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeWMV9_A, 0x1b81be90, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeWMV9_B, 0x1b81be91, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeWMV9_C, 0x1b81be94, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeVC1_A, 0x1b81beA0, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeVC1_B, 0x1b81beA1, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeVC1_C, 0x1b81beA2, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_ModeVC1_D, 0x1b81beA3, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); DEFINE_GUID(DXVA2_NoEncrypt, 0x1b81beD0, 0xa0c7, 0x11d3, 0xb9, 0x84, 0x00, 0xc0, 0x4f, 0x2e, 0x73, 0xc5); // HEVC DEFINE_GUID(DXVA_ModeHEVC_VLD_Main, 0x5b11d51b, 0x2f4c, 0x4452, 0xbc, 0xc3, 0x09, 0xf2, 0xa1, 0x16, 0x0c, 0xc0); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main10, 0x107af0e0, 0xef1a, 0x4d19, 0xab, 0xa8, 0x67, 0xa1, 0x63, 0x07, 0x3d, 0x13); DEFINE_GUID(DXVA_ModeHEVC_VLD_Monochrome, 0x0685b993, 0x3d8c, 0x43a0, 0x8b, 0x28, 0xd7, 0x4c, 0x2d, 0x68, 0x99, 0xa4); DEFINE_GUID(DXVA_ModeHEVC_VLD_Monochrome10, 0x142a1d0f, 0x69dd, 0x4ec9, 0x85, 0x91, 0xb1, 0x2f, 0xfc, 0xb9, 0x1a, 0x29); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main12, 0x1a72925f, 0x0c2c, 0x4f15, 0x96, 0xfb, 0xb1, 0x7d, 0x14, 0x73, 0x60, 0x3f); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main10_422, 0x0bac4fe5, 0x1532, 0x4429, 0xa8, 0x54, 0xf8, 0x4d, 0xe0, 0x49, 0x53, 0xdb); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main12_422, 0x55bcac81, 0xf311, 0x4093, 0xa7, 0xd0, 0x1c, 0xbc, 0x0b, 0x84, 0x9b, 0xee); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main_444, 0x4008018f, 0xf537, 0x4b36, 0x98, 0xcf, 0x61, 0xaf, 0x8a, 0x2c, 0x1a, 0x33); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main10_Ext, 0x9cc55490, 0xe37c, 0x4932, 0x86, 0x84, 0x49, 0x20, 0xf9, 0xf6, 0x40, 0x9c); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main10_444, 0x0dabeffa, 0x4458, 0x4602, 0xbc, 0x03, 0x07, 0x95, 0x65, 0x9d, 0x61, 0x7c); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main12_444, 0x9798634d, 0xfe9d, 0x48e5, 0xb4, 0xda, 0xdb, 0xec, 0x45, 0xb3, 0xdf, 0x01); DEFINE_GUID(DXVA_ModeHEVC_VLD_Main16, 0xa4fbdbb0, 0xa113, 0x482b, 0xa2, 0x32, 0x63, 0x5c, 0xc0, 0x69, 0x7f, 0x6d); // VP8/9 DEFINE_GUID(DXVA_ModeVP9_VLD_Profile0, 0x463707f8, 0xa1d0, 0x4585, 0x87, 0x6d, 0x83, 0xaa, 0x6d, 0x60, 0xb8, 0x9e); DEFINE_GUID(DXVA_ModeVP9_VLD_10bit_Profile2, 0xa4c749ef, 0x6ecf, 0x48aa, 0x84, 0x48, 0x50, 0xa7, 0xa1, 0x16, 0x5f, 0xf7); DEFINE_GUID(DXVA_ModeVP8_VLD, 0x90b899ea, 0x3a62, 0x4705, 0x88, 0xb3, 0x8d, 0xf0, 0x4b, 0x27, 0x44, 0xe7); DEFINE_GUID(DXVA_ModeAV1_VLD_Profile0, 0xb8be4ccb, 0xcf53, 0x46ba, 0x8d, 0x59, 0xd6, 0xb8, 0xa6, 0xda, 0x5d, 0x2a); DEFINE_GUID(DXVA_ModeAV1_VLD_Profile1, 0x6936ff0f, 0x45b1, 0x4163, 0x9c, 0xc1, 0x64, 0x6e, 0xf6, 0x94, 0x61, 0x08); DEFINE_GUID(DXVA_ModeAV1_VLD_Profile2, 0x0c5f2aa1, 0xe541, 0x4089, 0xbb, 0x7b, 0x98, 0x11, 0x0a, 0x19, 0xd7, 0xc8); DEFINE_GUID(DXVA_ModeAV1_VLD_12bit_Profile2, 0x17127009, 0xa00f, 0x4ce1, 0x99, 0x4e, 0xbf, 0x40, 0x81, 0xf6, 0xf3, 0xf0); DEFINE_GUID(DXVA_ModeAV1_VLD_12bit_Profile2_420, 0x2d80bed6, 0x9cac, 0x4835, 0x9e, 0x91, 0x32, 0x7b, 0xbc, 0x4f, 0x9e, 0xe8); DEFINE_GUID(IID_IDirectXVideoDecoderService, 0xfc51a551, 0xd5e7, 0x11d9, 0xaf, 0x55, 0x00, 0x05, 0x4e, 0x43, 0xff, 0x02); DEFINE_GUID(CLSID_AC3Filter, 0xA753A1EC, 0x973E, 0x4718, 0xAF, 0x8E, 0xA3, 0xF5, 0x54, 0xD4, 0x5C, 0x44); // "{48025243-2D39-11CE-875D-00608CB78066} DEFINE_GUID(CLSID_ISCR, 0x48025243, 0x2D39, 0x11CE, 0x87, 0x5D, 0x00, 0x60, 0x8C, 0xB7, 0x80, 0x66); // Filter/Commercial GUIDs // MPC-HC MPEG-TS Splitter // DC257063-045F-4BE2-BD5B-E12279C464F0 DEFINE_GUID(CLSID_MPCHCMPEGSplitter, 0xDC257063, 0x045F, 0x4BE2, 0xBD, 0x5B, 0xE1, 0x22, 0x79, 0xC4, 0x64, 0xF0); // MPC-HC MPEG-TS Splitter Source // 1365BE7A-C86A-473C-9A41-C0A6E82C9FA3 DEFINE_GUID(CLSID_MPCHCMPEGSplitterSource, 0x1365BE7A, 0xC86A, 0x473C, 0x9A, 0x41, 0xC0, 0xA6, 0xE8, 0x2C, 0x9F, 0xA3); // MPC-HC MP4 Splitter // 61F47056-E400-43d3-AF1E-AB7DFFD4C4AD DEFINE_GUID(CLSID_MPCHCMP4Splitter, 0x61F47056, 0xE400, 0x43D3, 0xAF, 0x1E, 0xAB, 0x7D, 0xFF, 0xD4, 0xC4, 0xAD); // MPC-HC MP4 Splitter Source // 3CCC052E-BDEE-408a-BEA7-90914EF2964B DEFINE_GUID(CLSID_MPCHCMP4SplitterSource, 0x3CCC052E, 0xBDEE, 0x408A, 0xBE, 0xA7, 0x90, 0x91, 0x4E, 0xF2, 0x96, 0x4B); // MediaPortal BD Reader DEFINE_GUID(CLSID_MPBDReader, 0x79a37017, 0x3178, 0x4859, 0x80, 0x79, 0xec, 0xb9, 0xd5, 0x46, 0xfe, 0xb2); // MPC Video Dec // 008BAC12-FBAF-497b-9670-BC6F6FBAE2C4 DEFINE_GUID(CLSID_MPCVideoDec, 0x008BAC12, 0xFBAF, 0x497B, 0x96, 0x70, 0xBC, 0x6F, 0x6F, 0xBA, 0xE2, 0xC4); // ffdshow DXVA Video Decoder // 0B0EFF97-C750-462C-9488-B10E7D87F1A6 DEFINE_GUID(CLSID_ffdshowDXVA, 0x0B0EFF97, 0xC750, 0x462C, 0x94, 0x88, 0xB1, 0x0E, 0x7D, 0x87, 0xF1, 0xA6); // LAV CUVID Decoder // 62D767FE-4F1B-478B-B350-8ACE9E4DB00E DEFINE_GUID(CLSID_LAVCUVID, 0x62D767FE, 0x4F1B, 0x478B, 0xB3, 0x50, 0x8A, 0xCE, 0x9E, 0x4D, 0xB0, 0x0E); // LAV Video Decoder // EE30215D-164F-4A92-A4EB-9D4C13390F9F DEFINE_GUID(CLSID_LAVVideo, 0xEE30215D, 0x164F, 0x4A92, 0xA4, 0xEB, 0x9D, 0x4C, 0x13, 0x39, 0x0F, 0x9F); // LAV Splitter // 171252A0-8820-4AFE-9DF8-5C92B2D66B04 DEFINE_GUID(CLSID_LAVSplitter, 0x171252A0, 0x8820, 0x4AFE, 0x9D, 0xF8, 0x5C, 0x92, 0xB2, 0xD6, 0x6B, 0x04); // LAV Splitter // B98D13E7-55DB-4385-A33D-09FD1BA26338 DEFINE_GUID(CLSID_LAVSplitterSource, 0xB98D13E7, 0x55DB, 0x4385, 0xA3, 0x3D, 0x09, 0xFD, 0x1B, 0xA2, 0x63, 0x38); // SageTV MpegDeMux // ABD65DEA-5701-4F21-863B-591B057D2268 DEFINE_GUID(CLSID_SageTVMpegDeMux, 0xABD65DEA, 0x5701, 0x4F21, 0x86, 0x3B, 0x59, 0x1B, 0x05, 0x7D, 0x22, 0x68); // Cyberlink VC-1 GUID // D979F77B-DBEA-4BF6-9E6D-1D7E57FBAD53 DEFINE_GUID(MEDIASUBTYPE_WVC1_CYBERLINK, 0xD979F77B, 0xDBEA, 0x4BF6, 0x9E, 0x6D, 0x1D, 0x7E, 0x57, 0xFB, 0xAD, 0x53); // Cyberlink Video Decoder GUID (PDVD10) // D00E73D7-06F5-44F9-8BE4-B7DB191E9E7E DEFINE_GUID(CLSID_CyberlinkVidDec, 0xD00E73D7, 0x06F5, 0x44F9, 0x8B, 0xE4, 0xB7, 0xDB, 0x19, 0x1E, 0x9E, 0x7E); // ArcSoft VC-1 GUID // 629B40AD-AD74-4EF4-A985-F0C8D92E5ECA DEFINE_GUID(MEDIASUBTYPE_WVC1_ARCSOFT, 0x629B40AD, 0xAD74, 0x4EF4, 0xA9, 0x85, 0xF0, 0xC8, 0xD9, 0x2E, 0x5E, 0xCA); // ArcSoft Video Decoder // B793E9A8-C53E-4845-9DE9-C32326EACCAD DEFINE_GUID(CLSID_ArcSoftVidDec, 0xB793E9A8, 0xC53E, 0x4845, 0x9D, 0xE9, 0xC3, 0x23, 0x26, 0xEA, 0xCC, 0xAD); // ArcSoft TrueHD // 4288B843-610B-4E15-A53B-43007FCFF614 DEFINE_GUID(MEDIASUBTYPE_DOLBY_TRUEHD_ARCSOFT, 0x4288B843, 0x610B, 0x4E15, 0xA5, 0x3B, 0x43, 0x00, 0x7F, 0xCF, 0xF6, 0x14); // ArcSoft DD+ DEFINE_GUID(MEDIASUBTYPE_DOLBY_DDPLUS_ARCSOFT, 0x71cfa727, 0x37e4, 0x404a, 0xae, 0xc0, 0x34, 0x84, 0x25, 0x32, 0xef, 0xf7); // uncompressed #define DEFINE_GUID_FOURCC(FOURCC) \ DEFINE_GUID(MEDIASUBTYPE_##FOURCC, FOURCC_##FOURCC, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); // uncompressed #define FOURCC_YUY2 mmioFOURCC('Y', 'U', 'Y', '2') #define FOURCC_V422 mmioFOURCC('V', '4', '2', '2') #define FOURCC_YV12 mmioFOURCC('Y', 'V', '1', '2') #define FOURCC_YVYU mmioFOURCC('Y', 'V', 'Y', 'U') #define FOURCC_UYVY mmioFOURCC('U', 'Y', 'V', 'Y') #define FOURCC_YUYV mmioFOURCC('Y', 'U', 'Y', 'V') #define FOURCC_VYUY mmioFOURCC('V', 'Y', 'U', 'Y') #define FOURCC_I420 mmioFOURCC('I', '4', '2', '0') #define FOURCC_IYUV mmioFOURCC('I', 'Y', 'U', 'V') #define FOURCC_444P mmioFOURCC('4', '4', '4', 'P') #define FOURCC_YV24 mmioFOURCC('Y', 'V', '2', '4') // YUV 4:4:4 #define FOURCC_422P mmioFOURCC('4', '2', '2', 'P') #define FOURCC_YV16 mmioFOURCC('Y', 'V', '1', '6') // YUV 4:2:2 #define FOURCC_411P mmioFOURCC('4', '1', '1', 'P') #define FOURCC_Y41B mmioFOURCC('Y', '4', '1', 'B') // YUV 4:1:1 #define FOURCC_410P mmioFOURCC('4', '1', '0', 'P') #define FOURCC_PAL1 mmioFOURCC('P', 'A', 'L', '1') #define FOURCC_PAL4 mmioFOURCC('P', 'A', 'L', '4') #define FOURCC_PAL8 mmioFOURCC('P', 'A', 'L', '8') #define FOURCC_RGB2 mmioFOURCC('R', 'G', 'B', '2') #define FOURCC_RGB3 mmioFOURCC('R', 'G', 'B', '3') #define FOURCC_RGB5 mmioFOURCC('R', 'G', 'B', '5') #define FOURCC_RGB6 mmioFOURCC('R', 'G', 'B', '6') #define FOURCC_CLJR mmioFOURCC('C', 'L', 'J', 'R') #define FOURCC_Y800 mmioFOURCC('Y', '8', '0', '0') #define FOURCC_NV12 mmioFOURCC('N', 'V', '1', '2') #define FOURCC_NV21 mmioFOURCC('N', 'V', '2', '1') #define FOURCC_P010 mmioFOURCC('P', '0', '1', '0') #define FOURCC_P016 mmioFOURCC('P', '0', '1', '6') #define FOURCC_Y410 mmioFOURCC('Y', '4', '1', '0') #define FOURCC_Y416 mmioFOURCC('Y', '4', '1', '6') DEFINE_GUID_FOURCC(422P) DEFINE_GUID_FOURCC(444P) DEFINE_GUID_FOURCC(411P) DEFINE_GUID_FOURCC(410P) DEFINE_GUID_FOURCC(VYUY) DEFINE_GUID_FOURCC(Y800) DEFINE_GUID_FOURCC(NV21) DEFINE_GUID_FOURCC(YV16) DEFINE_GUID_FOURCC(YV24) DEFINE_GUID_FOURCC(Y410) DEFINE_GUID_FOURCC(Y416) ================================================ FILE: common/includes/version.h ================================================ #pragma once #include "version_rev.h" #define LAV_VERSION_MAJOR 0 #define LAV_VERSION_MINOR 81 #define LAV_VERSION_REVISION 0 ///////////////////////////////////////////////////////// #ifndef ISPP_INCLUDED #define DO_MAKE_STR(x) #x #define MAKE_STR(x) DO_MAKE_STR(x) #if LAV_VERSION_BUILD > 0 #define LAV_VERSION LAV_VERSION_MAJOR.LAV_VERSION_MINOR.LAV_VERSION_REVISION.LAV_VERSION_BUILD-git #define LAV_VERSION_TAG LAV_VERSION_MAJOR, LAV_VERSION_MINOR, LAV_VERSION_REVISION, LAV_VERSION_BUILD #else #define LAV_VERSION LAV_VERSION_MAJOR.LAV_VERSION_MINOR.LAV_VERSION_REVISION #define LAV_VERSION_TAG LAV_VERSION_MAJOR, LAV_VERSION_MINOR, LAV_VERSION_REVISION #endif #define LAV_VERSION_STR MAKE_STR(LAV_VERSION) #endif ================================================ FILE: common/platform.props ================================================ v141 false 8.1 v142 false 10.0 v143 false 10.0 true ================================================ FILE: decoder/LAVAudio/AudioSettingsProp.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "AudioSettingsProp.h" #include "Media.h" #include #include "resource.h" #include "version.h" CLAVAudioSettingsProp::CLAVAudioSettingsProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVCAudioProp"), pUnk, IDD_PROPPAGE_AUDIO_SETTINGS, IDS_SETTINGS) { } CLAVAudioSettingsProp::~CLAVAudioSettingsProp() { } HRESULT CLAVAudioSettingsProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pAudioSettings == nullptr); return pUnk->QueryInterface(&m_pAudioSettings); } HRESULT CLAVAudioSettingsProp::OnDisconnect() { SafeRelease(&m_pAudioSettings); return S_OK; } HRESULT CLAVAudioSettingsProp::OnApplyChanges() { ASSERT(m_pAudioSettings != nullptr); HRESULT hr = S_OK; BOOL bFlag; // DRC int iDRCLevel = (int)SendDlgItemMessage(m_Dlg, IDC_DRC_LEVEL, TBM_GETPOS, 0, 0); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_DRC, BM_GETCHECK, 0, 0); hr = m_pAudioSettings->SetDRC(bFlag, iDRCLevel); // Bitstreaming codec options bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BS_AC3, BM_GETCHECK, 0, 0); m_pAudioSettings->SetBitstreamConfig(Bitstream_AC3, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BS_EAC3, BM_GETCHECK, 0, 0); m_pAudioSettings->SetBitstreamConfig(Bitstream_EAC3, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BS_TRUEHD, BM_GETCHECK, 0, 0); m_pAudioSettings->SetBitstreamConfig(Bitstream_TRUEHD, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BS_DTS, BM_GETCHECK, 0, 0); m_pAudioSettings->SetBitstreamConfig(Bitstream_DTS, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BS_DTSHD, BM_GETCHECK, 0, 0); m_pAudioSettings->SetBitstreamConfig(Bitstream_DTSHD, bFlag); // DTS-HD framing bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BS_DTSHD_FRAMING, BM_GETCHECK, 0, 0); m_pAudioSettings->SetDTSHDFraming(bFlag); // Fallback to audio decoding bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BS_FALLBACK, BM_GETCHECK, 0, 0); m_pAudioSettings->SetBitstreamingFallback(bFlag); // The other playback options bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_AUTO_AVSYNC, BM_GETCHECK, 0, 0); m_pAudioSettings->SetAutoAVSync(bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_STANDARD_CH_LAYOUT, BM_GETCHECK, 0, 0); m_pAudioSettings->SetOutputStandardLayout(bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUTPUT51_LEGACY, BM_GETCHECK, 0, 0); m_pAudioSettings->SetOutput51LegacyLayout(bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_EXPAND_MONO, BM_GETCHECK, 0, 0); m_pAudioSettings->SetExpandMono(bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_EXPAND61, BM_GETCHECK, 0, 0); m_pAudioSettings->SetExpand61(bFlag); // Sample Formats bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_S16, BM_GETCHECK, 0, 0); m_pAudioSettings->SetSampleFormat(SampleFormat_16, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_S24, BM_GETCHECK, 0, 0); m_pAudioSettings->SetSampleFormat(SampleFormat_24, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_S32, BM_GETCHECK, 0, 0); m_pAudioSettings->SetSampleFormat(SampleFormat_32, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_FP32, BM_GETCHECK, 0, 0); m_pAudioSettings->SetSampleFormat(SampleFormat_FP32, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_U8, BM_GETCHECK, 0, 0); m_pAudioSettings->SetSampleFormat(SampleFormat_U8, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_S16_DITHER, BM_GETCHECK, 0, 0); m_pAudioSettings->SetSampleConvertDithering(bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_DELAY_ENABLED, BM_GETCHECK, 0, 0); WCHAR buffer[100]; SendDlgItemMessage(m_Dlg, IDC_DELAY, WM_GETTEXT, 100, (LPARAM)&buffer); int delay = _wtoi(buffer); m_pAudioSettings->SetAudioDelay(bFlag, delay); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_GETCHECK, 0, 0); m_pAudioSettings->SetTrayIcon(bFlag); LoadData(); return hr; } HRESULT CLAVAudioSettingsProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pAudioSettings != nullptr); const WCHAR *version = TEXT(LAV_AUDIO) L" " TEXT(LAV_VERSION_STR); SendDlgItemMessage(m_Dlg, IDC_LAVAUDIO_FOOTER, WM_SETTEXT, 0, (LPARAM)version); hr = LoadData(); if (SUCCEEDED(hr)) { SendDlgItemMessage(m_Dlg, IDC_DRC, BM_SETCHECK, m_bDRCEnabled, 0); EnableWindow(GetDlgItem(m_Dlg, IDC_DRC_LEVEL), m_bDRCEnabled); SendDlgItemMessage(m_Dlg, IDC_DRC_LEVEL, TBM_SETRANGE, 0, MAKELONG(0, 100)); SendDlgItemMessage(m_Dlg, IDC_DRC_LEVEL, TBM_SETTICFREQ, 10, 0); SendDlgItemMessage(m_Dlg, IDC_DRC_LEVEL, TBM_SETPOS, 1, m_iDRCLevel); WCHAR buffer[10]; _snwprintf_s(buffer, _TRUNCATE, L"%d%%", m_iDRCLevel); SendDlgItemMessage(m_Dlg, IDC_DRC_LEVEL_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); SendDlgItemMessage(m_Dlg, IDC_BS_AC3, BM_SETCHECK, m_bBitstreaming[Bitstream_AC3], 0); SendDlgItemMessage(m_Dlg, IDC_BS_EAC3, BM_SETCHECK, m_bBitstreaming[Bitstream_EAC3], 0); SendDlgItemMessage(m_Dlg, IDC_BS_TRUEHD, BM_SETCHECK, m_bBitstreaming[Bitstream_TRUEHD], 0); SendDlgItemMessage(m_Dlg, IDC_BS_DTS, BM_SETCHECK, m_bBitstreaming[Bitstream_DTS], 0); SendDlgItemMessage(m_Dlg, IDC_BS_DTSHD, BM_SETCHECK, m_bBitstreaming[Bitstream_DTSHD], 0); EnableWindow(GetDlgItem(m_Dlg, IDC_BS_DTSHD), m_bBitstreaming[Bitstream_DTS]); SendDlgItemMessage(m_Dlg, IDC_BS_DTSHD_FRAMING, BM_SETCHECK, m_bDTSHDFraming, 0); EnableWindow(GetDlgItem(m_Dlg, IDC_BS_DTSHD_FRAMING), m_bBitstreaming[Bitstream_DTSHD]); addHint(IDC_BS_DTSHD_FRAMING, L"With some Receivers, this setting might be needed to achieve the full features of DTS. However, on " L"other Receivers, this option will cause DTS to not work at all.\n\nIf you do not experience any " L"problems, its recommended to leave this setting untouched."); SendDlgItemMessage(m_Dlg, IDC_BS_FALLBACK, BM_SETCHECK, m_bBitstreamingFallback, 0); addHint(IDC_BS_FALLBACK, L"Fallback to audio decoding if bitstreaming is not supported by the audio renderer/hardware."); SendDlgItemMessage(m_Dlg, IDC_AUTO_AVSYNC, BM_SETCHECK, m_bAutoAVSync, 0); addHint(IDC_AUTO_AVSYNC, L"Enables automatic tracking and correction of A/V sync.\n\nIf you encounter any sync " L"issues, disabling this option can help in debugging the source of the problem."); SendDlgItemMessage(m_Dlg, IDC_STANDARD_CH_LAYOUT, BM_SETCHECK, m_bOutputStdLayout, 0); addHint(IDC_STANDARD_CH_LAYOUT, L"Converts all channel layouts to one of the \"standard\" layouts (5.1/6.1/7.1) by adding silent " L"channels. This is required for sending the PCM over HDMI if not using another downstream mixer, for " L"example when using WASAPI."); SendDlgItemMessage(m_Dlg, IDC_OUTPUT51_LEGACY, BM_SETCHECK, m_bOutput51Legacy, 0); addHint(IDC_OUTPUT51_LEGACY, L"Use the legacy 5.1 channel layout which uses back channels instead of side " L"channels, required for some audio devices and/or software."); SendDlgItemMessage(m_Dlg, IDC_EXPAND_MONO, BM_SETCHECK, m_bExpandMono, 0); addHint(IDC_EXPAND_MONO, L"Plays Mono Audio in both Left/Right Front channels, instead of the center."); SendDlgItemMessage(m_Dlg, IDC_EXPAND61, BM_SETCHECK, m_bExpand61, 0); addHint(IDC_EXPAND61, L"Converts 6.1 Audio to 7.1 by copying the Back Center into both Back Left and Right channels."); SendDlgItemMessage(m_Dlg, IDC_OUT_S16, BM_SETCHECK, m_bSampleFormats[SampleFormat_16], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_S24, BM_SETCHECK, m_bSampleFormats[SampleFormat_24], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_S32, BM_SETCHECK, m_bSampleFormats[SampleFormat_32], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_FP32, BM_SETCHECK, m_bSampleFormats[SampleFormat_FP32], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_U8, BM_SETCHECK, m_bSampleFormats[SampleFormat_U8], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_S16_DITHER, BM_SETCHECK, m_bDither, 0); SendDlgItemMessage(m_Dlg, IDC_DELAY_ENABLED, BM_SETCHECK, m_bAudioDelay, 0); EnableWindow(GetDlgItem(m_Dlg, IDC_DELAYSPIN), m_bAudioDelay); EnableWindow(GetDlgItem(m_Dlg, IDC_DELAY), m_bAudioDelay); SendDlgItemMessage(m_Dlg, IDC_DELAYSPIN, UDM_SETRANGE32, -1000 * 60 * 60 * 24, 1000 * 60 * 60 * 24); WCHAR stringBuffer[100]; swprintf_s(stringBuffer, L"%d", m_iAudioDelay); SendDlgItemMessage(m_Dlg, IDC_DELAY, WM_SETTEXT, 0, (LPARAM)stringBuffer); SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_SETCHECK, m_TrayIcon, 0); } return hr; } HRESULT CLAVAudioSettingsProp::LoadData() { HRESULT hr = S_OK; hr = m_pAudioSettings->GetDRC(&m_bDRCEnabled, &m_iDRCLevel); for (unsigned i = 0; i < Bitstream_NB; ++i) m_bBitstreaming[i] = m_pAudioSettings->GetBitstreamConfig((LAVBitstreamCodec)i) != 0; m_bDTSHDFraming = m_pAudioSettings->GetDTSHDFraming(); m_bBitstreamingFallback = m_pAudioSettings->GetBitstreamingFallback(); m_bAutoAVSync = m_pAudioSettings->GetAutoAVSync(); m_bOutputStdLayout = m_pAudioSettings->GetOutputStandardLayout(); m_bOutput51Legacy = m_pAudioSettings->GetOutput51LegacyLayout(); m_bExpandMono = m_pAudioSettings->GetExpandMono(); m_bExpand61 = m_pAudioSettings->GetExpand61(); for (unsigned i = 0; i < SampleFormat_NB; ++i) m_bSampleFormats[i] = m_pAudioSettings->GetSampleFormat((LAVAudioSampleFormat)i) != 0; m_bDither = m_pAudioSettings->GetSampleConvertDithering(); m_pAudioSettings->GetAudioDelay(&m_bAudioDelay, &m_iAudioDelay); m_TrayIcon = m_pAudioSettings->GetTrayIcon(); return hr; } INT_PTR CLAVAudioSettingsProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT lValue; switch (uMsg) { case WM_COMMAND: if (LOWORD(wParam) == IDC_DRC && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, IDC_DRC, BM_GETCHECK, 0, 0); if (lValue != m_bDRCEnabled) { SetDirty(); } EnableWindow(GetDlgItem(m_Dlg, IDC_DRC_LEVEL), (BOOL)lValue); } else if (LOWORD(wParam) == IDC_BS_AC3 && HIWORD(wParam) == BN_CLICKED) { bool bFlag = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bBitstreaming[Bitstream_AC3]) SetDirty(); } else if (LOWORD(wParam) == IDC_BS_EAC3 && HIWORD(wParam) == BN_CLICKED) { bool bFlag = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bBitstreaming[Bitstream_EAC3]) SetDirty(); } else if (LOWORD(wParam) == IDC_BS_TRUEHD && HIWORD(wParam) == BN_CLICKED) { bool bFlag = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bBitstreaming[Bitstream_TRUEHD]) SetDirty(); } else if (LOWORD(wParam) == IDC_BS_DTS && HIWORD(wParam) == BN_CLICKED) { bool bFlag = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bBitstreaming[Bitstream_DTS]) SetDirty(); EnableWindow(GetDlgItem(m_Dlg, IDC_BS_DTSHD), bFlag); } else if (LOWORD(wParam) == IDC_BS_DTSHD && HIWORD(wParam) == BN_CLICKED) { bool bFlag = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bBitstreaming[Bitstream_DTSHD]) SetDirty(); EnableWindow(GetDlgItem(m_Dlg, IDC_BS_DTSHD_FRAMING), bFlag); } else if (LOWORD(wParam) == IDC_BS_DTSHD_FRAMING && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bDTSHDFraming) SetDirty(); } else if (LOWORD(wParam) == IDC_BS_FALLBACK && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bBitstreamingFallback) SetDirty(); } else if (LOWORD(wParam) == IDC_AUTO_AVSYNC && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bAutoAVSync) SetDirty(); } else if (LOWORD(wParam) == IDC_STANDARD_CH_LAYOUT && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bOutputStdLayout) SetDirty(); } else if (LOWORD(wParam) == IDC_OUTPUT51_LEGACY && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bOutput51Legacy) SetDirty(); } else if (LOWORD(wParam) == IDC_EXPAND_MONO && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bExpandMono) SetDirty(); } else if (LOWORD(wParam) == IDC_EXPAND61 && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bExpand61) SetDirty(); } else if (LOWORD(wParam) == IDC_OUT_S16 && HIWORD(wParam) == BN_CLICKED) { bool bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bSampleFormats[SampleFormat_16]) SetDirty(); } else if (LOWORD(wParam) == IDC_OUT_S24 && HIWORD(wParam) == BN_CLICKED) { bool bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bSampleFormats[SampleFormat_24]) SetDirty(); } else if (LOWORD(wParam) == IDC_OUT_S32 && HIWORD(wParam) == BN_CLICKED) { bool bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bSampleFormats[SampleFormat_32]) SetDirty(); } else if (LOWORD(wParam) == IDC_OUT_FP32 && HIWORD(wParam) == BN_CLICKED) { bool bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bSampleFormats[SampleFormat_FP32]) SetDirty(); } else if (LOWORD(wParam) == IDC_OUT_U8 && HIWORD(wParam) == BN_CLICKED) { bool bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_bSampleFormats[SampleFormat_U8]) SetDirty(); } else if (LOWORD(wParam) == IDC_OUT_S16_DITHER && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bDither) SetDirty(); } else if (LOWORD(wParam) == IDC_DELAY_ENABLED && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bFlag != m_bAudioDelay) SetDirty(); EnableWindow(GetDlgItem(m_Dlg, IDC_DELAYSPIN), bFlag); EnableWindow(GetDlgItem(m_Dlg, IDC_DELAY), bFlag); } else if (LOWORD(wParam) == IDC_DELAY && HIWORD(wParam) == EN_CHANGE) { WCHAR buffer[100]; SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, 100, (LPARAM)&buffer); int delay = _wtoi(buffer); size_t len = wcslen(buffer); if (delay == 0 && (buffer[0] != L'0' || len > 1)) { SendDlgItemMessage(m_Dlg, LOWORD(wParam), EM_UNDO, 0, 0); } else { swprintf_s(buffer, L"%d", delay); if (wcslen(buffer) != len) SendDlgItemMessage(m_Dlg, IDC_DELAY, WM_SETTEXT, 0, (LPARAM)buffer); if (delay != m_iAudioDelay) SetDirty(); } } else if (LOWORD(wParam) == IDC_TRAYICON && HIWORD(wParam) == BN_CLICKED) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0) != 0; if (bFlag != m_TrayIcon) SetDirty(); } break; case WM_HSCROLL: lValue = SendDlgItemMessage(m_Dlg, IDC_DRC_LEVEL, TBM_GETPOS, 0, 0); if (lValue != m_iDRCLevel) { SetDirty(); } WCHAR buffer[10]; _snwprintf_s(buffer, _TRUNCATE, L"%d%%", (int)lValue); SendDlgItemMessage(m_Dlg, IDC_DRC_LEVEL_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// // Mixer Configurations CLAVAudioMixingProp::CLAVAudioMixingProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVCAudioMixing"), pUnk, IDD_PROPPAGE_AUDIO_MIXING, IDS_MIXER) { } CLAVAudioMixingProp::~CLAVAudioMixingProp() { } HRESULT CLAVAudioMixingProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pAudioSettings == nullptr); return pUnk->QueryInterface(&m_pAudioSettings); } HRESULT CLAVAudioMixingProp::OnDisconnect() { SafeRelease(&m_pAudioSettings); return S_OK; } static DWORD dwSpkLayouts[] = { AV_CH_LAYOUT_MONO, AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_2_2, AV_CH_LAYOUT_5POINT1, AV_CH_LAYOUT_6POINT1, AV_CH_LAYOUT_7POINT1, }; static DWORD get_speaker_index(DWORD dwLayout) { int i = 0; for (i = 0; i < countof(dwSpkLayouts); i++) { if (dwSpkLayouts[i] == dwLayout) return i; } return (DWORD)-1; } HRESULT CLAVAudioMixingProp::OnApplyChanges() { ASSERT(m_pAudioSettings != nullptr); HRESULT hr = S_OK; DWORD dwVal = 0; BOOL bVal = FALSE; dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_GETCURSEL, 0, 0); if (dwVal >= 0 && dwVal < countof(dwSpkLayouts)) m_pAudioSettings->SetMixingLayout(dwSpkLayouts[dwVal]); bVal = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MIXING, BM_GETCHECK, 0, 0); m_pAudioSettings->SetMixingEnabled(bVal); DWORD dwMixingFlags = 0; bVal = (BOOL)SendDlgItemMessage(m_Dlg, IDC_UNTOUCHED_STEREO, BM_GETCHECK, 0, 0); if (bVal) dwMixingFlags |= LAV_MIXING_FLAG_UNTOUCHED_STEREO; bVal = (BOOL)SendDlgItemMessage(m_Dlg, IDC_NORMALIZE_MATRIX, BM_GETCHECK, 0, 0); if (bVal) dwMixingFlags |= LAV_MIXING_FLAG_NORMALIZE_MATRIX; bVal = (BOOL)SendDlgItemMessage(m_Dlg, IDC_CLIP_PROTECTION, BM_GETCHECK, 0, 0); if (bVal) dwMixingFlags |= LAV_MIXING_FLAG_CLIP_PROTECTION; m_pAudioSettings->SetMixingFlags(dwMixingFlags); BOOL bNormal = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MIXMODE_NORMAL, BM_GETCHECK, 0, 0); BOOL bDolby = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MIXMODE_DOLBY, BM_GETCHECK, 0, 0); BOOL bDPL2 = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MIXMODE_DPL2, BM_GETCHECK, 0, 0); m_pAudioSettings->SetMixingMode(bDolby ? MatrixEncoding_Dolby : (bDPL2 ? MatrixEncoding_DPLII : MatrixEncoding_None)); DWORD dwMixCenter = (DWORD)SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER, TBM_GETPOS, 0, 0); DWORD dwMixSurround = (DWORD)SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND, TBM_GETPOS, 0, 0); DWORD dwMixLFE = (DWORD)SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE, TBM_GETPOS, 0, 0); m_pAudioSettings->SetMixingLevels(dwMixCenter, dwMixSurround, dwMixLFE); LoadData(); return hr; } HRESULT CLAVAudioMixingProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pAudioSettings != nullptr); WCHAR spkMono[] = L"Mono"; WCHAR spkStereo[] = L"Stereo"; WCHAR spkQuadro[] = L"4.0"; WCHAR spk51Surround[] = L"5.1"; WCHAR spk61Surround[] = L"6.1"; WCHAR spk71Surround[] = L"7.1"; SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_RESETCONTENT, 0, 0); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)spkMono); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)spkStereo); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)spkQuadro); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)spk51Surround); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)spk61Surround); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_ADDSTRING, 0, (LPARAM)spk71Surround); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER, TBM_SETRANGE, 0, MAKELONG(0, 10000)); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER, TBM_SETTICFREQ, 100, 0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER, TBM_SETLINESIZE, 0, 100); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER, TBM_SETPAGESIZE, 0, 100); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND, TBM_SETRANGE, 0, MAKELONG(0, 10000)); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND, TBM_SETTICFREQ, 100, 0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND, TBM_SETLINESIZE, 0, 100); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND, TBM_SETPAGESIZE, 0, 100); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE, TBM_SETRANGE, 0, MAKELONG(0, 30000)); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE, TBM_SETTICFREQ, 100, 0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE, TBM_SETLINESIZE, 0, 100); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE, TBM_SETPAGESIZE, 0, 100); addHint(IDC_UNTOUCHED_STEREO, L"With this option on, stereo sources will not be mixed. This is useful when you " L"want to mix all surround sources to e.g. 5.1, but leave stereo untouched."); addHint(IDC_NORMALIZE_MATRIX, L"Normalizing the matrix will apply a global attenuation to the audio, in effect making it quieter to " L"ensure that there is a consistent volume throughout the file, and no clipping occurs.\n\n" L"This mode will produce inconsistent volumes between different source formats (stereo will be louder than " L"5.1), but the volume during playback of one file will not change."); addHint(IDC_CLIP_PROTECTION, L"Clipping protection analyzes the audio, and reduces the volume if clipping is detected.\n\n" L"This mode tries to preserve the original volume of the audio, and is generally more consistent between " L"different source formats. It may however cause a sudden volume change during playback. " L"In addition, this mode has a higher volume than a normalized matrix and is preferred on weak speakers or " L"headphones."); hr = LoadData(); if (SUCCEEDED(hr)) { SendDlgItemMessage(m_Dlg, IDC_MIXING, BM_SETCHECK, m_bMixing, 0); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SPEAKERS, CB_SETCURSEL, get_speaker_index(m_dwSpeakerLayout), 0); SendDlgItemMessage(m_Dlg, IDC_UNTOUCHED_STEREO, BM_SETCHECK, !!(m_dwFlags & LAV_MIXING_FLAG_UNTOUCHED_STEREO), 0); SendDlgItemMessage(m_Dlg, IDC_NORMALIZE_MATRIX, BM_SETCHECK, !!(m_dwFlags & LAV_MIXING_FLAG_NORMALIZE_MATRIX), 0); SendDlgItemMessage(m_Dlg, IDC_CLIP_PROTECTION, BM_SETCHECK, !!(m_dwFlags & LAV_MIXING_FLAG_CLIP_PROTECTION), 0); SendDlgItemMessage(m_Dlg, IDC_MIXMODE_NORMAL, BM_SETCHECK, (m_dwMixingMode == MatrixEncoding_None), 0); SendDlgItemMessage(m_Dlg, IDC_MIXMODE_DOLBY, BM_SETCHECK, (m_dwMixingMode == MatrixEncoding_Dolby), 0); SendDlgItemMessage(m_Dlg, IDC_MIXMODE_DPL2, BM_SETCHECK, (m_dwMixingMode == MatrixEncoding_DPLII), 0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER, TBM_SETPOS, 1, m_dwMixCenter); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND, TBM_SETPOS, 1, m_dwMixSurround); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE, TBM_SETPOS, 1, m_dwMixLFE); WCHAR buffer[10]; _snwprintf_s(buffer, _TRUNCATE, L"%.2f", (double)m_dwMixCenter / 10000.0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"%.2f", (double)m_dwMixSurround / 10000.0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"%.2f", (double)m_dwMixLFE / 10000.0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); } return hr; } HRESULT CLAVAudioMixingProp::LoadData() { HRESULT hr = S_OK; m_dwSpeakerLayout = m_pAudioSettings->GetMixingLayout(); m_bMixing = m_pAudioSettings->GetMixingEnabled(); m_dwFlags = m_pAudioSettings->GetMixingFlags(); m_dwMixingMode = m_pAudioSettings->GetMixingMode(); m_pAudioSettings->GetMixingLevels(&m_dwMixCenter, &m_dwMixSurround, &m_dwMixLFE); return hr; } INT_PTR CLAVAudioMixingProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT lValue; switch (uMsg) { case WM_COMMAND: if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_OUTPUT_SPEAKERS) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETCURSEL, 0, 0); if (dwSpkLayouts[lValue] != m_dwSpeakerLayout) { SetDirty(); } } else if (LOWORD(wParam) == IDC_MIXING && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != m_bMixing) { SetDirty(); } } else if (LOWORD(wParam) == IDC_UNTOUCHED_STEREO && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue == !(m_dwFlags & LAV_MIXING_FLAG_UNTOUCHED_STEREO)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_NORMALIZE_MATRIX && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue == !(m_dwFlags & LAV_MIXING_FLAG_NORMALIZE_MATRIX)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_CLIP_PROTECTION && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue == !(m_dwFlags & LAV_MIXING_FLAG_CLIP_PROTECTION)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_MIXMODE_NORMAL && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_dwMixingMode == MatrixEncoding_None)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_MIXMODE_DOLBY && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_dwMixingMode == MatrixEncoding_Dolby)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_MIXMODE_DPL2 && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_dwMixingMode == MatrixEncoding_DPLII)) { SetDirty(); } } break; case WM_HSCROLL: if ((HWND)lParam == GetDlgItem(m_Dlg, IDC_MIX_LEVEL_CENTER)) { lValue = SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER, TBM_GETPOS, 0, 0); if (lValue != m_dwMixCenter) { SetDirty(); } WCHAR buffer[10]; _snwprintf_s(buffer, _TRUNCATE, L"%.2f", (double)lValue / 10000.0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_CENTER_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); } else if ((HWND)lParam == GetDlgItem(m_Dlg, IDC_MIX_LEVEL_SURROUND)) { lValue = SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND, TBM_GETPOS, 0, 0); if (lValue != m_dwMixSurround) { SetDirty(); } WCHAR buffer[10]; _snwprintf_s(buffer, _TRUNCATE, L"%.2f", (double)lValue / 10000.0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_SURROUND_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); } else if ((HWND)lParam == GetDlgItem(m_Dlg, IDC_MIX_LEVEL_LFE)) { lValue = SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE, TBM_GETPOS, 0, 0); if (lValue != m_dwMixLFE) { SetDirty(); } WCHAR buffer[10]; _snwprintf_s(buffer, _TRUNCATE, L"%.2f", (double)lValue / 10000.0); SendDlgItemMessage(m_Dlg, IDC_MIX_LEVEL_LFE_TEXT, WM_SETTEXT, 0, (LPARAM)buffer); } break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// // Format Configurations CLAVAudioFormatsProp::CLAVAudioFormatsProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVCAudioFormats"), pUnk, IDD_PROPPAGE_FORMATS, IDS_FORMATS) { } CLAVAudioFormatsProp::~CLAVAudioFormatsProp() { } HRESULT CLAVAudioFormatsProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pAudioSettings == nullptr); return pUnk->QueryInterface(&m_pAudioSettings); } HRESULT CLAVAudioFormatsProp::OnDisconnect() { SafeRelease(&m_pAudioSettings); return S_OK; } HRESULT CLAVAudioFormatsProp::OnApplyChanges() { ASSERT(m_pAudioSettings != nullptr); HRESULT hr = S_OK; HWND hlv = GetDlgItem(m_Dlg, IDC_CODECS); // Get checked state BOOL bFlag; for (int nItem = 0; nItem < ListView_GetItemCount(hlv); nItem++) { bFlag = ListView_GetCheckState(hlv, nItem); m_pAudioSettings->SetFormatConfiguration((LAVAudioCodec)nItem, bFlag); } LoadData(); return hr; } HRESULT CLAVAudioFormatsProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES | ICC_LISTVIEW_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pAudioSettings != nullptr); // Setup ListView control for format configuration SendDlgItemMessage(m_Dlg, IDC_CODECS, CCM_DPISCALE, TRUE, 0); HWND hlv = GetDlgItem(m_Dlg, IDC_CODECS); ListView_SetExtendedListViewStyle(hlv, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); int nCol = 1; LVCOLUMN lvc = {LVCF_WIDTH, 0, 20, 0}; ListView_InsertColumn(hlv, 0, &lvc); ListView_AddCol(hlv, nCol, 75, L"Codec", false); ListView_AddCol(hlv, nCol, 350, L"Description", false); ListView_DeleteAllItems(hlv); ListView_SetItemCount(hlv, Codec_AudioNB); // Create entries for the formats LVITEM lvi; memset(&lvi, 0, sizeof(lvi)); lvi.mask = LVIF_TEXT | LVIF_PARAM; int nItem = 0; for (nItem = 0; nItem < Codec_AudioNB; ++nItem) { const codec_config_t *config = get_codec_config((LAVAudioCodec)nItem); // Create main entry lvi.iItem = nItem + 1; ListView_InsertItem(hlv, &lvi); // Set sub item texts ATL::CA2W name(config->name); ListView_SetItemText(hlv, nItem, 1, (LPWSTR)name); ATL::CA2W desc(config->description); ListView_SetItemText(hlv, nItem, 2, (LPWSTR)desc); } hr = LoadData(); if (SUCCEEDED(hr)) { // Set checked state for (nItem = 0; nItem < ListView_GetItemCount(hlv); nItem++) { ListView_SetCheckState(hlv, nItem, m_bFormats[nItem]); } } return hr; } HRESULT CLAVAudioFormatsProp::LoadData() { HRESULT hr = S_OK; for (unsigned i = 0; i < Codec_AudioNB; ++i) m_bFormats[i] = m_pAudioSettings->GetFormatConfiguration((LAVAudioCodec)i) != 0; return hr; } INT_PTR CLAVAudioFormatsProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_NOTIFY: NMHDR *hdr = (LPNMHDR)lParam; if (hdr->idFrom == IDC_CODECS) { switch (hdr->code) { case LVN_ITEMCHANGED: LPNMLISTVIEW nmlv = (LPNMLISTVIEW)lParam; bool check = ListView_GetCheckState(hdr->hwndFrom, nmlv->iItem) ? true : false; if (check != m_bFormats[nmlv->iItem]) { SetDirty(); } return TRUE; } } break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// // Audio Status Panel #define MAX_CHANNELS 8 static int iddVolumeControls[MAX_CHANNELS] = {IDC_VOLUME1, IDC_VOLUME2, IDC_VOLUME3, IDC_VOLUME4, IDC_VOLUME5, IDC_VOLUME6, IDC_VOLUME7, IDC_VOLUME8}; static int iddVolumeDescs[MAX_CHANNELS] = {IDC_VOLUME1_DESC, IDC_VOLUME2_DESC, IDC_VOLUME3_DESC, IDC_VOLUME4_DESC, IDC_VOLUME5_DESC, IDC_VOLUME6_DESC, IDC_VOLUME7_DESC, IDC_VOLUME8_DESC}; CLAVAudioStatusProp::CLAVAudioStatusProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVCAudioStatusProp"), pUnk, IDD_PROPPAGE_STATUS, IDS_STATUS) { } CLAVAudioStatusProp::~CLAVAudioStatusProp() { } HRESULT CLAVAudioStatusProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pAudioStatus == nullptr); return pUnk->QueryInterface(&m_pAudioStatus); } HRESULT CLAVAudioStatusProp::OnDisconnect() { SafeRelease(&m_pAudioStatus); return S_OK; } HRESULT CLAVAudioStatusProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_STANDARD_CLASSES | ICC_BAR_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pAudioStatus != nullptr); m_nChannels = 0; const char *codec = nullptr; const char *decodeFormat = nullptr; int nDecodeChannels = 0; int nDecodeSampleRate = 0; DWORD dwDecodeChannelMask; hr = m_pAudioStatus->GetDecodeDetails(&codec, &decodeFormat, &nDecodeChannels, &nDecodeSampleRate, &dwDecodeChannelMask); if (SUCCEEDED(hr)) { WCHAR buffer[100]; _snwprintf_s(buffer, _TRUNCATE, L"%d / 0x%x", nDecodeChannels, dwDecodeChannelMask); SendDlgItemMessage(m_Dlg, IDC_INPUT_CHANNEL, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"%d", nDecodeSampleRate); SendDlgItemMessage(m_Dlg, IDC_INPUT_SAMPLERATE, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"%S", codec); SendDlgItemMessage(m_Dlg, IDC_INPUT_CODEC, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"%S", decodeFormat); SendDlgItemMessage(m_Dlg, IDC_INPUT_FORMAT, WM_SETTEXT, 0, (LPARAM)buffer); } const char *outputFormat = nullptr; int nOutputChannels = 0; int nOutputSampleRate = 0; DWORD dwOutputChannelMask = 0; hr = m_pAudioStatus->GetOutputDetails(&outputFormat, &nOutputChannels, &nOutputSampleRate, &dwOutputChannelMask); if (SUCCEEDED(hr)) { WCHAR buffer[100]; if (hr == S_OK) { _snwprintf_s(buffer, _TRUNCATE, L"%d / 0x%x", nOutputChannels, dwOutputChannelMask); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_CHANNEL, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"%d", nOutputSampleRate); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_SAMPLERATE, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"PCM"); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_CODEC, WM_SETTEXT, 0, (LPARAM)buffer); _snwprintf_s(buffer, _TRUNCATE, L"%S", outputFormat); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_FORMAT, WM_SETTEXT, 0, (LPARAM)buffer); m_nChannels = nOutputChannels; } else { _snwprintf_s(buffer, _TRUNCATE, L"Bitstreaming"); SendDlgItemMessage(m_Dlg, IDC_OUTPUT_CODEC, WM_SETTEXT, 0, (LPARAM)buffer); } } SetTimer(m_Dlg, 1, 250, nullptr); m_pAudioStatus->EnableVolumeStats(); WCHAR chBuffer[5]; if (dwOutputChannelMask == 0 && nOutputChannels != 0) { // 0x4 is only front center, 0x3 is front left+right dwOutputChannelMask = nOutputChannels == 1 ? 0x4 : 0x3; } for (int i = 0; i < MAX_CHANNELS; ++i) { SendDlgItemMessage(m_Dlg, iddVolumeControls[i], PBM_SETRANGE, 0, MAKELPARAM(0, 50)); _snwprintf_s(chBuffer, _TRUNCATE, L"%S", get_channel_desc(get_flag_from_channel(dwOutputChannelMask, i))); SendDlgItemMessage(m_Dlg, iddVolumeDescs[i], WM_SETTEXT, 0, (LPARAM)chBuffer); } return hr; } HRESULT CLAVAudioStatusProp::OnDeactivate() { KillTimer(m_Dlg, 1); m_pAudioStatus->DisableVolumeStats(); return S_OK; } void CLAVAudioStatusProp::UpdateVolumeDisplay() { for (int i = 0; i < m_nChannels; ++i) { float fDB = 0.0f; if (SUCCEEDED(m_pAudioStatus->GetChannelVolumeAverage(i, &fDB))) { int value = (int)fDB + 50; SendDlgItemMessage(m_Dlg, iddVolumeControls[i], PBM_SETPOS, value, 0); } else { SendDlgItemMessage(m_Dlg, iddVolumeControls[i], PBM_SETPOS, 0, 0); } } } INT_PTR CLAVAudioStatusProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_TIMER: UpdateVolumeDisplay(); break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } ================================================ FILE: decoder/LAVAudio/AudioSettingsProp.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "LAVAudioSettings.h" #include "BaseDSPropPage.h" #include "Media.h" // {2D8F1801-A70D-48F4-B76B-7F5AE022AB54} DEFINE_GUID(CLSID_LAVAudioSettingsProp, 0x2d8f1801, 0xa70d, 0x48f4, 0xb7, 0x6b, 0x7f, 0x5a, 0xe0, 0x22, 0xab, 0x54); // {C89FC33C-E60A-4C97-BEF4-ACC5762B6404} DEFINE_GUID(CLSID_LAVAudioMixingProp, 0xc89fc33c, 0xe60a, 0x4c97, 0xbe, 0xf4, 0xac, 0xc5, 0x76, 0x2b, 0x64, 0x4); // {20ED4A03-6AFD-4FD9-980B-2F6143AA0892} DEFINE_GUID(CLSID_LAVAudioStatusProp, 0x20ed4a03, 0x6afd, 0x4fd9, 0x98, 0xb, 0x2f, 0x61, 0x43, 0xaa, 0x8, 0x92); // {BD72668E-6BFF-4CD1-8480-D465708B336B} DEFINE_GUID(CLSID_LAVAudioFormatsProp, 0xbd72668e, 0x6bff, 0x4cd1, 0x84, 0x80, 0xd4, 0x65, 0x70, 0x8b, 0x33, 0x6b); class CLAVAudioSettingsProp : public CBaseDSPropPage { public: CLAVAudioSettingsProp(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVAudioSettingsProp(); HRESULT OnActivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); HRESULT OnApplyChanges(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: HRESULT LoadData(); void SetDirty() { m_bDirty = TRUE; if (m_pPageSite) { m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY); } } private: ILAVAudioSettings *m_pAudioSettings = nullptr; BOOL m_bDRCEnabled; int m_iDRCLevel; bool m_bBitstreaming[Bitstream_NB]; BOOL m_bDTSHDFraming; BOOL m_bBitstreamingFallback; BOOL m_bAutoAVSync; BOOL m_bOutputStdLayout; BOOL m_bOutput51Legacy; BOOL m_bExpandMono; BOOL m_bExpand61; bool m_bSampleFormats[SampleFormat_NB]; BOOL m_bDither; BOOL m_bAudioDelay; int m_iAudioDelay; BOOL m_TrayIcon; }; class CLAVAudioMixingProp : public CBaseDSPropPage { public: CLAVAudioMixingProp(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVAudioMixingProp(); HRESULT OnActivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); HRESULT OnApplyChanges(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: HRESULT LoadData(); void SetDirty() { m_bDirty = TRUE; if (m_pPageSite) { m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY); } } private: ILAVAudioSettings *m_pAudioSettings = nullptr; BOOL m_bMixing; DWORD m_dwSpeakerLayout; DWORD m_dwFlags; DWORD m_dwMixingMode; DWORD m_dwMixCenter; DWORD m_dwMixSurround; DWORD m_dwMixLFE; }; class CLAVAudioFormatsProp : public CBaseDSPropPage { public: CLAVAudioFormatsProp(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVAudioFormatsProp(); HRESULT OnActivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); HRESULT OnApplyChanges(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: HRESULT LoadData(); void SetDirty() { m_bDirty = TRUE; if (m_pPageSite) { m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY); } } private: ILAVAudioSettings *m_pAudioSettings = nullptr; bool m_bFormats[Codec_AudioNB]; }; class CLAVAudioStatusProp : public CBaseDSPropPage { public: CLAVAudioStatusProp(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVAudioStatusProp(); HRESULT OnActivate(); HRESULT OnDeactivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: void UpdateVolumeDisplay(); private: ILAVAudioStatus *m_pAudioStatus = nullptr; int m_nChannels = 0; }; ================================================ FILE: decoder/LAVAudio/Bitstream.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVAudio.h" #include #include "moreuuids.h" #define LAV_BITSTREAM_BUFFER_SIZE 4096 #define LAV_BITSTREAM_DTS_HD_HR_RATE 192000 #define LAV_BITSTREAM_DTS_HD_MA_RATE 768000 static struct { AVCodecID codec; LAVBitstreamCodec config; } lavf_bitstream_config[] = { {AV_CODEC_ID_AC3, Bitstream_AC3}, {AV_CODEC_ID_EAC3, Bitstream_EAC3}, {AV_CODEC_ID_TRUEHD, Bitstream_TRUEHD}, {AV_CODEC_ID_DTS, Bitstream_DTS} // DTS-HD is still DTS, and handled special below }; // Check whether a codec is bitstreaming eligible and enabled BOOL CLAVAudio::IsBitstreaming(AVCodecID codec) { for (int i = 0; i < countof(lavf_bitstream_config); ++i) { if (lavf_bitstream_config[i].codec == codec) { return m_bBitstreamOverride[lavf_bitstream_config[i].config] ? FALSE : m_settings.bBitstream[lavf_bitstream_config[i].config]; } } return FALSE; } HRESULT CLAVAudio::InitBitstreaming() { // Alloc buffer for the AVIO context BYTE *buffer = (BYTE *)CoTaskMemAlloc(LAV_BITSTREAM_BUFFER_SIZE + AV_INPUT_BUFFER_PADDING_SIZE); if (!buffer) return E_OUTOFMEMORY; // Create AVIO context m_avioBitstream = avio_alloc_context(buffer, LAV_BITSTREAM_BUFFER_SIZE, 1, this, nullptr, BSWriteBuffer, nullptr); if (!m_avioBitstream) { SAFE_CO_FREE(buffer); return E_FAIL; } return S_OK; } HRESULT CLAVAudio::ShutdownBitstreaming() { if (m_avioBitstream) { SAFE_CO_FREE(m_avioBitstream->buffer); av_freep(&m_avioBitstream); } return S_OK; } // Static function for the AVIO context that writes the buffer into our own output buffer int CLAVAudio::BSWriteBuffer(void *opaque, const uint8_t *buf, int buf_size) { CLAVAudio *filter = (CLAVAudio *)opaque; filter->m_bsOutput.Append(buf, buf_size); return buf_size; } HRESULT CLAVAudio::CreateBitstreamContext(AVCodecID codec, WAVEFORMATEX *wfe) { int ret = 0; if (m_avBSContext) FreeBitstreamContext(); m_bsParser.Reset(); DbgLog((LOG_TRACE, 20, "Creating Bistreaming Context...")); ret = avformat_alloc_output_context2(&m_avBSContext, nullptr, "spdif", nullptr); if (ret < 0 || !m_avBSContext) { DbgLog((LOG_ERROR, 10, L"::CreateBitstreamContext() -- alloc of avformat spdif muxer failed (ret: %d)", ret)); goto fail; } m_avBSContext->pb = m_avioBitstream; // flush IO after every packet, so we can send it to the audio renderer immediately m_avBSContext->flags |= AVFMT_FLAG_FLUSH_PACKETS; // DTS-HD is by default off, unless explicitly asked for if (m_settings.DTSHDFraming && m_settings.bBitstream[Bitstream_DTSHD] && !m_bForceDTSCore) { m_DTSBitstreamMode = DTS_HDMA; av_opt_set_int(m_avBSContext->priv_data, "dtshd_rate", LAV_BITSTREAM_DTS_HD_MA_RATE, 0); } else { m_DTSBitstreamMode = DTS_Core; av_opt_set_int(m_avBSContext->priv_data, "dtshd_rate", 0, 0); } av_opt_set_int(m_avBSContext->priv_data, "dtshd_fallback_time", -1, 0); AVStream *st = avformat_new_stream(m_avBSContext, 0); if (!st) { DbgLog((LOG_ERROR, 10, L"::CreateBitstreamContext() -- alloc of output stream failed")); goto fail; } st->codecpar->codec_id = codec; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->ch_layout.order = AV_CHANNEL_ORDER_UNSPEC; st->codecpar->ch_layout.nb_channels = wfe->nChannels; st->codecpar->sample_rate = wfe->nSamplesPerSec; ret = avformat_write_header(m_avBSContext, nullptr); if (ret < 0) { DbgLog((LOG_ERROR, 10, L"::CreateBitstreamContext() -- av_write_header returned an error code (%d)", -ret)); goto fail; } return S_OK; fail: FreeBitstreamContext(); return E_FAIL; } HRESULT CLAVAudio::UpdateBitstreamContext() { if (!m_pInput || !m_pInput->IsConnected()) return E_UNEXPECTED; BOOL bBitstream = IsBitstreaming(m_nCodecId); if ((bBitstream && !m_avBSContext) || (!bBitstream && m_avBSContext)) { CMediaType mt = m_pInput->CurrentMediaType(); const void *format = mt.Format(); GUID format_type = mt.formattype; DWORD formatlen = mt.cbFormat; // Override the format type if (mt.subtype == MEDIASUBTYPE_FFMPEG_AUDIO && format_type == FORMAT_WaveFormatExFFMPEG) { WAVEFORMATEXFFMPEG *wfexff = (WAVEFORMATEXFFMPEG *)mt.Format(); format = &wfexff->wfex; format_type = FORMAT_WaveFormatEx; formatlen -= sizeof(WAVEFORMATEXFFMPEG) - sizeof(WAVEFORMATEX); } ffmpeg_init(m_nCodecId, format, format_type, formatlen); m_bQueueResync = TRUE; } // Configure DTS-HD setting if (m_avBSContext) { if (m_settings.bBitstream[Bitstream_DTSHD] && m_settings.DTSHDFraming && !m_bForceDTSCore) { m_DTSBitstreamMode = DTS_HDMA; av_opt_set_int(m_avBSContext->priv_data, "dtshd_rate", LAV_BITSTREAM_DTS_HD_MA_RATE, 0); } else { m_DTSBitstreamMode = DTS_Core; // Force auto-detection av_opt_set_int(m_avBSContext->priv_data, "dtshd_rate", 0, 0); } } return S_OK; } HRESULT CLAVAudio::FreeBitstreamContext() { if (m_avBSContext) { av_write_trailer(m_avBSContext); // For the SPDIF muxer that frees the buffers avformat_free_context(m_avBSContext); } m_avBSContext = nullptr; av_packet_free(&m_pBitstreamPacket); // Dump any remaining data m_bsOutput.SetSize(0); // reset TrueHD MAT state memset(&m_TrueHDMATState, 0, sizeof(m_TrueHDMATState)); return S_OK; } CMediaType CLAVAudio::CreateBitstreamMediaType(AVCodecID codec, DWORD dwSampleRate, BOOL bDTSHDOverride) { CMediaType mt; mt.majortype = MEDIATYPE_Audio; mt.subtype = MEDIASUBTYPE_PCM; mt.formattype = FORMAT_WaveFormatEx; WAVEFORMATEXTENSIBLE wfex; memset(&wfex, 0, sizeof(wfex)); WAVEFORMATEX *wfe = &wfex.Format; wfe->nChannels = 2; wfe->wBitsPerSample = 16; GUID subtype = GUID_NULL; switch (codec) { case AV_CODEC_ID_AC3: wfe->wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF; wfe->nSamplesPerSec = min(dwSampleRate, 48000); break; case AV_CODEC_ID_EAC3: wfe->nSamplesPerSec = 192000; wfe->nChannels = 2; subtype = KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL_PLUS; break; case AV_CODEC_ID_TRUEHD: wfe->nSamplesPerSec = 192000; wfe->nChannels = 8; subtype = KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_MLP; break; case AV_CODEC_ID_DTS: if (m_settings.bBitstream[Bitstream_DTSHD] && !bDTSHDOverride && m_DTSBitstreamMode != DTS_Core) { wfe->nSamplesPerSec = 192000; wfe->nChannels = (m_DTSBitstreamMode == DTS_HDHR) ? 2 : 8; subtype = KSDATAFORMAT_SUBTYPE_IEC61937_DTS_HD; } else { wfe->wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF; // huh? but it works. wfe->nSamplesPerSec = min(dwSampleRate, 48000); } break; default: ASSERT(0); break; } wfe->nBlockAlign = wfe->nChannels * wfe->wBitsPerSample / 8; wfe->nAvgBytesPerSec = wfe->nSamplesPerSec * wfe->nBlockAlign; if (subtype != GUID_NULL) { wfex.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; wfex.Format.cbSize = sizeof(wfex) - sizeof(wfex.Format); wfex.dwChannelMask = get_channel_mask(wfe->nChannels); wfex.Samples.wValidBitsPerSample = wfex.Format.wBitsPerSample; wfex.SubFormat = subtype; } mt.SetSampleSize(1); mt.SetFormat((BYTE *)&wfex, sizeof(wfex.Format) + wfex.Format.cbSize); return mt; } CLAVAudio::DTSBitstreamMode CLAVAudio::GetDTSHDBitstreamMode() { if (m_bForceDTSCore || !m_settings.bBitstream[Bitstream_DTSHD]) return DTS_Core; if (m_settings.DTSHDFraming) return DTS_HDMA; if (!m_bsParser.m_bDTSHD) return DTS_Core; if (m_pAVCtx->profile == AV_PROFILE_DTS_HD_HRA) return DTS_HDHR; return DTS_HDMA; } void CLAVAudio::ActivateDTSHDMuxing() { DbgLog((LOG_TRACE, 20, L"::ActivateDTSHDMuxing(): Found DTS-HD marker - switching to DTS-HD muxing mode")); m_DTSBitstreamMode = GetDTSHDBitstreamMode(); // Check if downstream actually accepts it.. const CMediaType &mt = CreateBitstreamMediaType(m_nCodecId, m_bsParser.m_dwSampleRate); HRESULT hr = m_pOutput->GetConnected()->QueryAccept(&mt); if (hr != S_OK) { DbgLog((LOG_TRACE, 20, L"-> But downstream doesn't want DTS-HD, sticking to DTS core")); m_DTSBitstreamMode = DTS_Core; m_bForceDTSCore = TRUE; } else { av_opt_set_int(m_avBSContext->priv_data, "dtshd_rate", (m_DTSBitstreamMode == DTS_HDHR) ? LAV_BITSTREAM_DTS_HD_HR_RATE : LAV_BITSTREAM_DTS_HD_MA_RATE, 0); } } HRESULT CLAVAudio::Bitstream(const BYTE *pDataBuffer, int buffsize, int &consumed, HRESULT *hrDeliver) { HRESULT hr = S_OK; int ret = 0; BOOL bFlush = (pDataBuffer == nullptr); if (m_pBitstreamPacket == nullptr) m_pBitstreamPacket = av_packet_alloc(); m_pBitstreamPacket->duration = 1; consumed = 0; while (buffsize > 0) { if (bFlush) buffsize = 0; BYTE *pOut = nullptr; int pOut_size = 0; int used_bytes = av_parser_parse2(m_pParser, m_pAVCtx, &pOut, &pOut_size, pDataBuffer, buffsize, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (used_bytes < 0) { DbgLog((LOG_TRACE, 50, L"::Bitstream() - audio parsing failed (ret: %d)", -used_bytes)); return E_FAIL; } else if (used_bytes == 0 && pOut_size == 0) { DbgLog((LOG_TRACE, 50, L"::Bitstream() - could not process buffer, starving?")); break; } // Timestamp cache to compensate for one frame delay the parser might introduce, in case the frames were already // perfectly sliced apart If we used more (or equal) bytes then was output again, we encountered a new frame, // update timestamps if (used_bytes >= pOut_size && m_bUpdateTimeCache) { m_rtStartInputCache = m_rtStartInput; m_rtStopInputCache = m_rtStopInput; m_bUpdateTimeCache = FALSE; } if (!bFlush && used_bytes > 0) { buffsize -= used_bytes; pDataBuffer += used_bytes; consumed += used_bytes; } if (pOut_size > 0) { hr = m_bsParser.Parse(m_nCodecId, pOut, pOut_size); if (FAILED(hr)) { continue; } if (m_nCodecId == AV_CODEC_ID_TRUEHD) { m_bUpdateTimeCache = TRUE; // Set long-time cache to the first timestamp encountered, used by TrueHD and E-AC3 because the S/PDIF // muxer caches data internally If the current timestamp is not valid, use the last delivery timestamp // in m_rtStart if (m_rtBitstreamCache == AV_NOPTS_VALUE) m_rtBitstreamCache = m_rtStartInputCache != AV_NOPTS_VALUE ? m_rtStartInputCache : m_rtStart; BitstreamTrueHD(pOut, pOut_size, hrDeliver); } else { if (m_nCodecId == AV_CODEC_ID_DTS) { DTSBitstreamMode mode = GetDTSHDBitstreamMode(); if (mode != DTS_Core && mode != m_DTSBitstreamMode) ActivateDTSHDMuxing(); } m_pBitstreamPacket->data = pOut; m_pBitstreamPacket->size = pOut_size; // Write SPDIF muxed frame ret = av_write_frame(m_avBSContext, m_pBitstreamPacket); if (ret < 0) { DbgLog((LOG_ERROR, 20, "::Bitstream(): av_write_frame returned error code (%d)", -ret)); m_bsOutput.SetSize(0); continue; } m_bUpdateTimeCache = TRUE; // Set long-time cache to the first timestamp encountered, used by TrueHD and E-AC3 because the S/PDIF // muxer caches data internally If the current timestamp is not valid, use the last delivery timestamp // in m_rtStart if (m_rtBitstreamCache == AV_NOPTS_VALUE) m_rtBitstreamCache = m_rtStartInputCache != AV_NOPTS_VALUE ? m_rtStartInputCache : m_rtStart; // Deliver frame if (m_bsOutput.GetCount() > 0) { *hrDeliver = DeliverBitstream(m_nCodecId, m_bsOutput.Ptr(), m_bsOutput.GetCount(), m_rtStartInputCache, m_rtStopInputCache); m_bsOutput.SetSize(0); } } /* if the bitstreaming context is lost at this point, then the deliver function caused a fallback to PCM */ if (m_avBSContext == nullptr) return S_FALSE; } } return S_OK; } HRESULT CLAVAudio::DeliverBitstream(AVCodecID codec, const BYTE *buffer, DWORD dwSize, REFERENCE_TIME rtStartInput, REFERENCE_TIME rtStopInput, BOOL bSwap, int nSamplesOffset) { HRESULT hr = S_OK; if (m_bFlushing) return S_FALSE; CMediaType mt = CreateBitstreamMediaType(codec, m_bsParser.m_dwSampleRate); if (FAILED(hr = ReconnectOutput(dwSize, mt))) { return hr; } IMediaSample *pOut; BYTE *pDataOut = nullptr; if (FAILED(GetDeliveryBuffer(&pOut, &pDataOut))) { return E_FAIL; } if (m_bResyncTimestamp && (rtStartInput != AV_NOPTS_VALUE || m_rtBitstreamCache != AV_NOPTS_VALUE)) { if (m_rtBitstreamCache != AV_NOPTS_VALUE) m_rtStart = m_rtBitstreamCache; else m_rtStart = rtStartInput; m_bResyncTimestamp = FALSE; } REFERENCE_TIME rtStart = m_rtStart, rtStop = AV_NOPTS_VALUE; REFERENCE_TIME rtOffset = (REFERENCE_TIME)round(DBL_SECOND_MULT * (double)nSamplesOffset / m_bsParser.m_dwSampleRate / m_dRate); double dDuration = DBL_SECOND_MULT * (double)m_bsParser.m_dwSamples / m_bsParser.m_dwSampleRate / m_dRate; m_dStartOffset += fmod(dDuration, 1.0); // Add rounded duration to rtStop rtStop = rtStart + (REFERENCE_TIME)(dDuration + 0.5); // and unrounded to m_rtStart.. m_rtStart += (REFERENCE_TIME)dDuration; // and accumulate error.. if (m_dStartOffset > 0.5) { m_rtStart++; m_dStartOffset -= 1.0; } REFERENCE_TIME rtJitter = 0; if (m_rtBitstreamCache != AV_NOPTS_VALUE) rtJitter = rtStart - m_rtBitstreamCache + rtOffset; m_faJitter.Sample(rtJitter); REFERENCE_TIME rtJitterMin = m_faJitter.AbsMinimum(); if (m_settings.AutoAVSync && abs(rtJitterMin) > m_JitterLimit) { DbgLog((LOG_TRACE, 10, L"::Deliver(): corrected A/V sync by %I64d", rtJitterMin)); m_rtStart -= rtJitterMin; rtStart -= rtJitterMin; m_faJitter.OffsetValues(-rtJitterMin); m_bDiscontinuity = TRUE; } #ifdef DEBUG DbgLog((LOG_CUSTOM5, 20, L"Bitstream Delivery, rtStart(calc): %I64d, rtStart(input): %I64d, duration: %I64d, offset: %I64d, diff: %I64d", rtStart, m_rtBitstreamCache, rtStop - rtStart, rtOffset, rtJitter)); if (m_faJitter.CurrentSample() == 0) { DbgLog((LOG_CUSTOM2, 20, L"Jitter Stats: min: %I64d - max: %I64d - avg: %I64d", rtJitterMin, m_faJitter.AbsMaximum(), m_faJitter.Average())); } #endif m_rtBitstreamCache = AV_NOPTS_VALUE; if (m_settings.AudioDelayEnabled) { REFERENCE_TIME rtDelay = (REFERENCE_TIME)((m_settings.AudioDelay * 10000i64) / m_dRate); rtStart += rtDelay; rtStop += rtDelay; } pOut->SetTime(&rtStart, &rtStop); pOut->SetMediaTime(nullptr, nullptr); pOut->SetPreroll(FALSE); pOut->SetDiscontinuity(m_bDiscontinuity); m_bDiscontinuity = FALSE; pOut->SetSyncPoint(TRUE); pOut->SetActualDataLength(dwSize); // byte-swap if needed if (bSwap) { lav_spdif_bswap_buf16((uint16_t *)pDataOut, (uint16_t *)buffer, dwSize >> 1); } else { memcpy(pDataOut, buffer, dwSize); } if (hr == S_OK) { hr = m_pOutput->GetConnected()->QueryAccept(&mt); if (hr == S_FALSE && m_nCodecId == AV_CODEC_ID_DTS && m_DTSBitstreamMode != DTS_Core) { DbgLog((LOG_TRACE, 1, L"DTS-HD Media Type failed with %0#.8x, trying fallback to DTS core", hr)); m_bForceDTSCore = TRUE; UpdateBitstreamContext(); goto done; } else if (hr == S_FALSE && m_settings.bBitstreamingFallback) { BitstreamFallbackToPCM(); goto done; } DbgLog((LOG_TRACE, 1, L"Sending new Media Type (QueryAccept: %0#.8x)", hr)); m_pOutput->SetMediaType(&mt); pOut->SetMediaType(&mt); } hr = m_pOutput->Deliver(pOut); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"::DeliverBitstream failed with code: %0#.8x", hr)); } done: SafeRelease(&pOut); return hr; } HRESULT CLAVAudio::BitstreamFallbackToPCM() { // fallback to decoding FreeBitstreamContext(); for (int i = 0; i < countof(lavf_bitstream_config); ++i) { if (lavf_bitstream_config[i].codec == m_nCodecId) { m_bBitstreamOverride[lavf_bitstream_config[i].config] = TRUE; } } m_bQueueResync = TRUE; return S_OK; } ================================================ FILE: decoder/LAVAudio/BitstreamMAT.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This code was inspired by the ffdshow-tryouts TaudioCodecBitstream module, licensed under GPL 2.0 */ #include "stdafx.h" #include "LAVAudio.h" #pragma warning(push) #pragma warning(disable : 4101) #pragma warning(disable : 5033) extern "C" { #include "libavformat/spdif.h" #define AVCODEC_X86_MATHOPS_H #include "libavcodec/get_bits.h" } #pragma warning(pop) #define MAT_BUFFER_SIZE (61440) #define MAT_BUFFER_LIMIT (MAT_BUFFER_SIZE - 24 /* MAT end code size */) #define MAT_POS_MIDDLE (30708 /* middle point*/ + 8 /* IEC header in front */) static const BYTE mat_start_code[20] = {0x07, 0x9E, 0x00, 0x03, 0x84, 0x01, 0x01, 0x01, 0x80, 0x00, 0x56, 0xA5, 0x3B, 0xF4, 0x81, 0x83, 0x49, 0x80, 0x77, 0xE0}; static const BYTE mat_middle_code[12] = {0xC3, 0xC1, 0x42, 0x49, 0x3B, 0xFA, 0x82, 0x83, 0x49, 0x80, 0x77, 0xE0}; static const BYTE mat_end_code[24] = {0xC3, 0xC2, 0xC0, 0xC4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x97, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; void CLAVAudio::MATWriteHeader() { ASSERT(m_bsOutput.GetCount() == 0); DWORD dwSize = BURST_HEADER_SIZE + sizeof(mat_start_code); // reserve size for the IEC header and the MAT start code m_bsOutput.SetSize(dwSize); BYTE *p = m_bsOutput.Ptr(); // IEC burst header AV_WB16(p + 0, SYNCWORD1); AV_WB16(p + 2, SYNCWORD2); AV_WB16(p + 4, IEC61937_TRUEHD); AV_WB16(p + 6, 61424); // MAT start code memcpy(p + BURST_HEADER_SIZE, mat_start_code, sizeof(mat_start_code)); // unless the start code falls into the padding, its considered part of the current MAT frame // Note that audio frames are not always aligned with MAT frames, so we might already have a partial frame at this // point m_TrueHDMATState.mat_framesize += dwSize; // The MAT metadata counts as padding, if we're scheduled to write any, which mean the start bytes should reduce any // further padding. if (m_TrueHDMATState.padding > 0) { // if the header fits into the padding of the last frame, just reduce the amount of needed padding if (m_TrueHDMATState.padding > dwSize) { m_TrueHDMATState.padding -= dwSize; m_TrueHDMATState.mat_framesize = 0; } else // otherwise, consume all padding and set the size of the next MAT frame to the remaining data { m_TrueHDMATState.mat_framesize = (dwSize - m_TrueHDMATState.padding); m_TrueHDMATState.padding = 0; } } } void CLAVAudio::MATWritePadding() { if (m_TrueHDMATState.padding > 0) { int remaining = MATFillDataBuffer(nullptr, m_TrueHDMATState.padding, true); // not all padding could be written to the buffer, write it later if (remaining >= 0) { m_TrueHDMATState.padding = remaining; m_TrueHDMATState.mat_framesize = 0; } else // more padding then requested was written, eg. there was a MAT middle/end marker that needed to be written { m_TrueHDMATState.padding = 0; m_TrueHDMATState.mat_framesize = -remaining; } } } void CLAVAudio::MATAppendData(const BYTE * const p, int size) { if (p) m_bsOutput.Append(p, size); else m_bsOutput.AppendZero(size); m_TrueHDMATState.mat_framesize += size; } int CLAVAudio::MATFillDataBuffer(const BYTE *const p, int size, bool padding) { ASSERT(p || padding); if (m_bsOutput.GetCount() >= MAT_BUFFER_LIMIT) return size; int remaining = size; // Write MAT middle marker, if needed // The MAT middle marker always needs to be in the exact same spot, any audio data will be split. // If we're currently writing padding, then the marker will be considered as padding data and reduce the amount of // padding still required. if (m_bsOutput.GetCount() <= MAT_POS_MIDDLE && m_bsOutput.GetCount() + size > MAT_POS_MIDDLE) { // write as much data before the middle code as we can int nBytesBefore = MAT_POS_MIDDLE - m_bsOutput.GetCount(); MATAppendData(p, nBytesBefore); remaining -= nBytesBefore; // write the MAT middle code MATAppendData(mat_middle_code, sizeof(mat_middle_code)); // if we're writing padding, deduct the size of the code from it if (padding) remaining -= sizeof(mat_middle_code); // write remaining data after the MAT marker if (remaining > 0) { return MATFillDataBuffer(p ? p + nBytesBefore : nullptr, remaining, padding); } return remaining; } // not enough room in the buffer to write all the data, write as much as we can and add the MAT footer if (m_bsOutput.GetCount() + size >= MAT_BUFFER_LIMIT) { // write as much data before the middle code as we can int nBytesBefore = MAT_BUFFER_LIMIT - m_bsOutput.GetCount(); MATAppendData(p, nBytesBefore); remaining -= nBytesBefore; // write the MAT end code MATAppendData(mat_end_code, sizeof(mat_end_code)); ASSERT(m_bsOutput.GetCount() == MAT_BUFFER_SIZE); // MAT markers don't displace padding, so reduce the amount of padding if (padding) remaining -= sizeof(mat_end_code); // any remaining data will be written in future calls return remaining; } MATAppendData(p, size); return 0; } void CLAVAudio::MATFlushPacket(HRESULT *hrDeliver) { if (m_bsOutput.GetCount() > 0) { ASSERT(m_bsOutput.GetCount() == 61440); // normal number of samples per frame uint16_t frame_samples = 40 << (m_TrueHDMATState.ratebits & 7); int nMATSamples = (frame_samples * 24); // Deliver MAT packet to the audio renderer *hrDeliver = DeliverBitstream(m_nCodecId, m_bsOutput.Ptr(), m_bsOutput.GetCount(), m_rtStartInputCache, m_rtStopInputCache, true, m_TrueHDMATState.nSamplesOffset); // we expect 24 frames per MAT frame, so calculate an offset from that // this is done after delivery, because it modifies the duration of the frame, eg. the start of the next frame if (nMATSamples != m_TrueHDMATState.nSamples) m_TrueHDMATState.nSamplesOffset += m_TrueHDMATState.nSamples - nMATSamples; m_bsOutput.SetSize(0); m_TrueHDMATState.nSamples = 0; } } static bool ParseTrueHDMajorSyncHeaders(const BYTE *p, int buffsize, int &ratebits, uint16_t &output_timing, bool &output_timing_present) { ASSERT(AV_RB32(p + 4) == 0xf8726fba); int length = (AV_RB16(p) & 0xfff) * 2; if (buffsize < 32) return false; // parse major sync and look for a restart header int major_sync_size = 28; if (p[29] & 1) { int extension_size = p[30] >> 4; major_sync_size += 2 + extension_size * 2; } GetBitContext gb; init_get_bits8(&gb, p + 4, buffsize - 4); skip_bits_long(&gb, 32); // format_sync // v(32) format_info ratebits = get_bits(&gb, 4); // ratebits skip_bits1(&gb); // 6ch_multichannel_type skip_bits1(&gb); // 8ch_multichannel_type skip_bits(&gb, 2); // reserved skip_bits(&gb, 2); // 2ch_presentation_channel_modifier skip_bits(&gb, 2); // 6ch_presentation_channel_modifier skip_bits(&gb, 5); // 6ch_presentation_channel_assignment skip_bits(&gb, 2); // 8ch_presentation_channel_modifier skip_bits(&gb, 13); // 8ch_presentation_channel_assignment skip_bits(&gb, 16); // signature skip_bits(&gb, 16); // flags skip_bits(&gb, 16); // reserved skip_bits1(&gb); // variable_rate skip_bits(&gb, 15); // peak_data_rate int num_substreams = get_bits(&gb, 4); skip_bits_long(&gb, 4 + (major_sync_size - 17) * 8); // substream directory for (int i = 0; i < num_substreams; i++) { int extra_substream_word = get_bits1(&gb); skip_bits1(&gb); // restart_nonexistent skip_bits1(&gb); // crc_present skip_bits1(&gb); // reserved skip_bits(&gb, 12); // substream_end_ptr if (extra_substream_word) skip_bits(&gb, 16); // drc_gain_update, drc_time_update, reserved } // substream segments for (int i = 0; i < num_substreams; i++) { if (get_bits1(&gb)) { // block_header_exists if (get_bits1(&gb)) { // restart_header_exists skip_bits(&gb, 14); // restart_sync_word output_timing = get_bits(&gb, 16); output_timing_present = true; // XXX: restart header } // XXX: Block header } // XXX: All blocks, all substreams? break; } return true; } HRESULT CLAVAudio::BitstreamTrueHD(const BYTE *p, int buffsize, HRESULT *hrDeliver) { // On a high level, a MAT frame consists of a sequence of padded TrueHD frames // The size of the padded frame can be determined from the frame time/sequence code in the frame header, // since it varies to accommodate spikes in bitrate. // In average all frames are always padded to 2560 bytes, so that 24 frames fit in one MAT frame, however // due to bitrate spikes single sync frames have been observed to use up to twice that size, in which // case they'll be preceded by smaller frames to keep the average bitrate constant. // A constant padding to 2560 bytes can work (this is how the ffmpeg spdifenc module works), however // high-bitrate streams can overshoot this size and therefor require proper handling of dynamic padding. uint16_t output_timing = 0; bool bOutputTimingPresent = false; // get the ratebits and output timing from the sync frame if (AV_RB32(p + 4) == 0xf8726fba) { if (ParseTrueHDMajorSyncHeaders(p, buffsize, m_TrueHDMATState.ratebits, output_timing, bOutputTimingPresent) == false) return E_FAIL; } else if (m_TrueHDMATState.prev_frametime_valid == false) { // only start streaming on a major sync frame m_rtBitstreamCache = AV_NOPTS_VALUE; m_TrueHDMATState.nSamplesOffset = 0; return S_FALSE; } uint16_t frame_time = AV_RB16(p + 2); uint32_t space_size = 0; uint16_t frame_samples = 40 << (m_TrueHDMATState.ratebits & 7); m_TrueHDMATState.output_timing += frame_samples; if (bOutputTimingPresent) { if (m_TrueHDMATState.output_timing_valid && (output_timing != m_TrueHDMATState.output_timing)) { DbgLog((LOG_TRACE, 10, _T("BitstreamTrueHD(): Detected a stream discontinuity, reseting framesize cache"))); m_TrueHDMATState.prev_frametime_valid = false; space_size = 40 * (64 >> (m_TrueHDMATState.ratebits & 7)); // the output timing is always one frame ahead for buffering reasons, so deduct one frame worth uint32_t prev_output = (uint16_t)(output_timing - frame_samples); if (prev_output < frame_time) // wrap around, output is always in front of frame time prev_output += UINT16_MAX; // get the offset of this frame, so we can compare to the previous frame, and determine the amount of padding that needs to be inserted int currentFrameOutputOffset = (prev_output - frame_time); // the previous offset should never be smaller then the incoming offset, or we will lack the reserved space ASSERT(m_TrueHDMATState.nOutputTimeOffset >= currentFrameOutputOffset); if (m_TrueHDMATState.nOutputTimeOffset >= currentFrameOutputOffset) m_TrueHDMATState.padding += (m_TrueHDMATState.nOutputTimeOffset - currentFrameOutputOffset) * (64 >> (m_TrueHDMATState.ratebits & 7)); DbgLog((LOG_TRACE, 10, _T("BitstreamTrueHD(): Carrying forward %d padding (offset %d - %d)"), m_TrueHDMATState.padding, m_TrueHDMATState.nOutputTimeOffset, currentFrameOutputOffset)); } m_TrueHDMATState.output_timing = output_timing; m_TrueHDMATState.output_timing_valid = true; } // compute final padded size for the previous frame, if any if (m_TrueHDMATState.prev_frametime_valid) space_size = uint16_t(frame_time - m_TrueHDMATState.prev_frametime) * (64 >> (m_TrueHDMATState.ratebits & 7)); // compute padding (ie. difference to the size of the previous frame) ASSERT(!m_TrueHDMATState.prev_frametime_valid || space_size >= m_TrueHDMATState.prev_mat_framesize); // if for some reason the space_size fails, align the actual frame size if (space_size < m_TrueHDMATState.prev_mat_framesize) space_size = FFALIGN(m_TrueHDMATState.prev_mat_framesize, (64 >> (m_TrueHDMATState.ratebits & 7))); m_TrueHDMATState.padding += (space_size - m_TrueHDMATState.prev_mat_framesize); // record the offset of frame time to output time, which is used to verify the size of the padding on discontinuities if (m_TrueHDMATState.output_timing_valid) { uint32_t prev_output = (uint16_t)(m_TrueHDMATState.output_timing - frame_samples); if (prev_output < frame_time) // wrap around, output is always in front of frame time prev_output += UINT16_MAX; m_TrueHDMATState.nOutputTimeOffset = (prev_output - frame_time); } // store frame time of the previous frame m_TrueHDMATState.prev_frametime = frame_time; m_TrueHDMATState.prev_frametime_valid = true; // Write the MAT header into the fresh buffer if (m_bsOutput.GetCount() == 0) { MATWriteHeader(); // initial header, don't count it for the frame size if (m_TrueHDMATState.init == false) { m_TrueHDMATState.init = true; m_TrueHDMATState.mat_framesize = 0; } } // write padding of the previous frame (if any) while (m_TrueHDMATState.padding > 0) { MATWritePadding(); ASSERT(m_TrueHDMATState.padding == 0 || m_bsOutput.GetCount() == MAT_BUFFER_SIZE); // Buffer is full, submit it if (m_bsOutput.GetCount() == MAT_BUFFER_SIZE) { MATFlushPacket(hrDeliver); // and setup a new buffer MATWriteHeader(); } } // count the number of samples in this frame m_TrueHDMATState.nSamples += frame_samples; // write actual audio data to the buffer int remaining = MATFillDataBuffer(p, buffsize); // not all data could be written, or the buffer is full if (remaining || m_bsOutput.GetCount() == MAT_BUFFER_SIZE) { // flush out old data MATFlushPacket(hrDeliver); if (remaining) { // .. setup a new buffer MATWriteHeader(); // and write the remaining data remaining = MATFillDataBuffer(p + (buffsize - remaining), remaining); ASSERT(remaining == 0); } } // store the size of the current MAT frame, so we can add padding later m_TrueHDMATState.prev_mat_framesize = m_TrueHDMATState.mat_framesize; m_TrueHDMATState.mat_framesize = 0; return S_OK; } ================================================ FILE: decoder/LAVAudio/BitstreamParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "BitstreamParser.h" #pragma warning(push) #pragma warning(disable : 4101) #pragma warning(disable : 5033) extern "C" { #define AVCODEC_X86_MATHOPS_H #include "libavcodec/ac3_parser_internal.h" } #pragma warning(pop) #include "parser/dts.h" CBitstreamParser::CBitstreamParser() { init_dts_parser((DTSParserContext **)&m_pParserContext); Reset(); } CBitstreamParser::~CBitstreamParser() { close_dts_parser((DTSParserContext **)&m_pParserContext); } void CBitstreamParser::Reset() { m_dwBlocks = 0; m_dwFrameSize = 0; m_dwSampleRate = 0; m_dwSamples = 0; m_bDTSHD = FALSE; memset(&m_DTSHeader, 0, sizeof(m_DTSHeader)); } HRESULT CBitstreamParser::Parse(AVCodecID codec, BYTE *pBuffer, DWORD dwSize) { switch (codec) { case AV_CODEC_ID_DTS: return ParseDTS(pBuffer, dwSize); case AV_CODEC_ID_AC3: case AV_CODEC_ID_EAC3: return ParseAC3(pBuffer, dwSize); case AV_CODEC_ID_TRUEHD: return ParseTrueHD(pBuffer, dwSize); } return S_OK; } HRESULT CBitstreamParser::ParseDTS(BYTE *pBuffer, DWORD dwSize) { int ret = parse_dts_header((DTSParserContext *)m_pParserContext, &m_DTSHeader, pBuffer, (unsigned)dwSize); if (ret < 0) return E_FAIL; m_bDTSHD = m_bDTSHD || m_DTSHeader.IsHD; m_dwBlocks = m_DTSHeader.Blocks; m_dwSampleRate = m_DTSHeader.SampleRate; m_dwFrameSize = m_DTSHeader.FrameSize; m_dwSamples = m_DTSHeader.SamplesPerBlock * m_dwBlocks; return S_OK; } HRESULT CBitstreamParser::ParseAC3(BYTE *pBuffer, DWORD dwSize) { AC3HeaderInfo hdr{}; AC3HeaderInfo *phdr = &hdr; if (avpriv_ac3_parse_header(&phdr, pBuffer, dwSize) >= 0) { m_dwSampleRate = hdr.sample_rate; // E-AC3 always combines 6 blocks, resulting in 1536 samples m_dwSamples = (hdr.bitstream_id > 10) ? (6 * 256) : (hdr.num_blocks * 256); } else { if (m_dwSampleRate == 0) // not seen a valid frame yet, error out return E_FAIL; } return S_OK; } HRESULT CBitstreamParser::ParseTrueHD(BYTE *pBuffer, DWORD dwSize) { if (AV_RB32(pBuffer + 4) == 0xf8726fba) { int nRatebits = pBuffer[8] >> 4; m_dwSampleRate = (nRatebits & 8 ? 44100 : 48000) << (nRatebits & 7); m_dwSamples = 24 * (40 << (nRatebits & 7)); } return S_OK; } ================================================ FILE: decoder/LAVAudio/BitstreamParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "parser/dts.h" struct GetBitContext; class CBitstreamParser { public: CBitstreamParser(); ~CBitstreamParser(); HRESULT Parse(AVCodecID codec, BYTE *pBuffer, DWORD dwSize); void Reset(); private: HRESULT ParseDTS(BYTE *pBuffer, DWORD dwSize); HRESULT ParseAC3(BYTE *pBuffer, DWORD dwSize); HRESULT ParseTrueHD(BYTE *pBuffer, DWORD dwSize); public: DWORD m_dwSampleRate = 0; DWORD m_dwBlocks = 0; DWORD m_dwFrameSize = 0; DWORD m_dwSamples = 0; BOOL m_bDTSHD = FALSE; DTSHeader m_DTSHeader; private: GetBitContext *m_gb = nullptr; void *m_pParserContext = nullptr; }; ================================================ FILE: decoder/LAVAudio/LAVAudio.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVAudio.h" #include "PostProcessor.h" #include #include #include "moreuuids.h" #include "DShowUtil.h" #include "IMediaSideData.h" #include "IMediaSideDataFFmpeg.h" #include "AudioSettingsProp.h" #include "registry.h" #include "resource.h" #include "DeCSS/DeCSSInputPin.h" #pragma warning(push) #pragma warning(disable : 4018) #pragma warning(disable : 4101) #pragma warning(disable : 4244) #pragma warning(disable : 5033) extern "C" { #define AVCODEC_X86_MATHOPS_H #include "libavformat/spdif.h" #include "libavcodec/flac_parse.h" #include "libavcodec/flac.h" #include "libavcodec/mpegaudiodecheader.h" extern int ff_vorbis_comment(AVFormatContext *ms, AVDictionary **m, const uint8_t *buf, int size, int parse_picture); extern void ff_rm_reorder_sipr_data(uint8_t *buf, int sub_packet_h, int framesize); __declspec(dllimport) extern const unsigned char ff_sipr_subpk_size[4]; }; #pragma warning(pop) #ifdef DEBUG #include "lavf_log.h" #endif static DWORD get_lav_channel_layout(AVChannelLayout * layout); extern HINSTANCE g_hInst; // Constructor CLAVAudio::CLAVAudio(LPUNKNOWN pUnk, HRESULT *phr) : CTransformFilter(NAME("lavc audio decoder"), 0, __uuidof(CLAVAudio)) { m_pInput = new CDeCSSTransformInputPin(TEXT("CDeCSSTransformInputPin"), this, phr, L"Input"); if (!m_pInput) { *phr = E_OUTOFMEMORY; } if (FAILED(*phr)) { return; } m_pOutput = new CTransformOutputPin(NAME("CTransformOutputPin"), this, phr, L"Output"); if (!m_pOutput) { *phr = E_OUTOFMEMORY; } if (FAILED(*phr)) { SAFE_DELETE(m_pInput); return; } LoadSettings(); InitBitstreaming(); #ifdef DEBUG DbgSetModuleLevel(LOG_CUSTOM1, DWORD_MAX); // FFMPEG messages use custom1 av_log_set_callback(lavf_log_callback); DbgSetModuleLevel(LOG_ERROR, DWORD_MAX); DbgSetModuleLevel(LOG_TRACE, DWORD_MAX); // DbgSetModuleLevel (LOG_CUSTOM2, DWORD_MAX); // Jitter statistics // DbgSetModuleLevel (LOG_CUSTOM5, DWORD_MAX); // Extensive timing options #else av_log_set_callback(nullptr); #endif } CLAVAudio::~CLAVAudio() { SAFE_DELETE(m_pTrayIcon); ffmpeg_shutdown(); ShutdownBitstreaming(); } STDMETHODIMP CLAVAudio::CreateTrayIcon() { CAutoLock cObjectLock(m_pLock); if (m_pTrayIcon) return E_UNEXPECTED; if (CBaseTrayIcon::ProcessBlackList()) return S_FALSE; m_pTrayIcon = new CBaseTrayIcon(this, TEXT(LAV_AUDIO), IDI_ICON1); return S_OK; } STDMETHODIMP CLAVAudio::JoinFilterGraph(IFilterGraph *pGraph, LPCWSTR pName) { CAutoLock cObjectLock(m_pLock); HRESULT hr = __super::JoinFilterGraph(pGraph, pName); if (pGraph && !m_pTrayIcon && m_settings.TrayIcon) { CreateTrayIcon(); } else if (!pGraph && m_pTrayIcon) { SAFE_DELETE(m_pTrayIcon); } return hr; } HRESULT CLAVAudio::LoadDefaults() { m_settings.TrayIcon = FALSE; m_settings.DRCEnabled = FALSE; m_settings.DRCLevel = 100; // Default all Codecs to enabled for (int i = 0; i < Codec_AudioNB; ++i) m_settings.bFormats[i] = TRUE; // Disable WMA codecs by default m_settings.bFormats[Codec_WMA2] = FALSE; m_settings.bFormats[Codec_WMAPRO] = FALSE; m_settings.bFormats[Codec_WMALL] = FALSE; // Default bitstreaming to disabled memset(m_settings.bBitstream, 0, sizeof(m_settings.bBitstream)); m_settings.DTSHDFraming = FALSE; m_settings.bBitstreamingFallback = TRUE; m_settings.AutoAVSync = TRUE; m_settings.ExpandMono = FALSE; m_settings.Expand61 = FALSE; m_settings.OutputStandardLayout = TRUE; m_settings.Output51Legacy = FALSE; m_settings.AllowRawSPDIF = FALSE; // Default all Sample Formats to enabled for (int i = 0; i < SampleFormat_NB; ++i) m_settings.bSampleFormats[i] = TRUE; m_settings.SampleConvertDither = TRUE; m_settings.AudioDelayEnabled = FALSE; m_settings.AudioDelay = 0; m_settings.MixingEnabled = FALSE; m_settings.MixingLayout = AV_CH_LAYOUT_STEREO; m_settings.MixingFlags = LAV_MIXING_FLAG_CLIP_PROTECTION; m_settings.MixingMode = MatrixEncoding_None; m_settings.MixingCenterLevel = 7071; m_settings.MixingSurroundLevel = 7071; m_settings.MixingLFELevel = 0; m_settings.SuppressFormatChanges = FALSE; return S_OK; } static const WCHAR *bitstreamingCodecs[Bitstream_NB] = {L"ac3", L"eac3", L"truehd", L"dts", L"dtshd"}; static const WCHAR *sampleFormats[SampleFormat_Bitstream] = {L"s16", L"s24", L"s32", L"u8", L"fp32"}; HRESULT CLAVAudio::LoadSettings() { LoadDefaults(); if (m_bRuntimeConfig) return S_FALSE; ReadSettings(HKEY_LOCAL_MACHINE); return ReadSettings(HKEY_CURRENT_USER); } HRESULT CLAVAudio::ReadSettings(HKEY rootKey) { HRESULT hr; DWORD dwVal; BOOL bFlag; BYTE *pBuf = nullptr; CRegistry reg = CRegistry(rootKey, LAVC_AUDIO_REGISTRY_KEY, hr, TRUE); if (SUCCEEDED(hr)) { bFlag = reg.ReadDWORD(L"TrayIcon", hr); if (SUCCEEDED(hr)) m_settings.TrayIcon = bFlag; bFlag = reg.ReadDWORD(L"DRCEnabled", hr); if (SUCCEEDED(hr)) m_settings.DRCEnabled = bFlag; dwVal = reg.ReadDWORD(L"DRCLevel", hr); if (SUCCEEDED(hr)) m_settings.DRCLevel = (int)dwVal; // Deprecated format storage pBuf = reg.ReadBinary(L"Formats", dwVal, hr); if (SUCCEEDED(hr)) { memcpy(&m_settings.bFormats, pBuf, min(dwVal, sizeof(m_settings.bFormats))); SAFE_CO_FREE(pBuf); } // Deprecated bitstreaming storage pBuf = reg.ReadBinary(L"Bitstreaming", dwVal, hr); if (SUCCEEDED(hr)) { memcpy(&m_settings.bBitstream, pBuf, min(dwVal, sizeof(m_settings.bBitstream))); SAFE_CO_FREE(pBuf); } bFlag = reg.ReadBOOL(L"DTSHDFraming", hr); if (SUCCEEDED(hr)) m_settings.DTSHDFraming = bFlag; bFlag = reg.ReadBOOL(L"BitstreamingFallback", hr); if (SUCCEEDED(hr)) m_settings.bBitstreamingFallback = bFlag; bFlag = reg.ReadBOOL(L"AutoAVSync", hr); if (SUCCEEDED(hr)) m_settings.AutoAVSync = bFlag; bFlag = reg.ReadBOOL(L"ExpandMono", hr); if (SUCCEEDED(hr)) m_settings.ExpandMono = bFlag; bFlag = reg.ReadBOOL(L"Expand61", hr); if (SUCCEEDED(hr)) m_settings.Expand61 = bFlag; bFlag = reg.ReadBOOL(L"OutputStandardLayout", hr); if (SUCCEEDED(hr)) m_settings.OutputStandardLayout = bFlag; bFlag = reg.ReadBOOL(L"Output51Legacy", hr); if (SUCCEEDED(hr)) m_settings.Output51Legacy = bFlag; bFlag = reg.ReadBOOL(L"Mixing", hr); if (SUCCEEDED(hr)) m_settings.MixingEnabled = bFlag; dwVal = reg.ReadDWORD(L"MixingLayout", hr); if (SUCCEEDED(hr)) m_settings.MixingLayout = dwVal; if (m_settings.MixingLayout == AV_CH_LAYOUT_5POINT1_BACK) m_settings.MixingLayout = AV_CH_LAYOUT_5POINT1; dwVal = reg.ReadDWORD(L"MixingFlags", hr); if (SUCCEEDED(hr)) m_settings.MixingFlags = dwVal; dwVal = reg.ReadDWORD(L"MixingMode", hr); if (SUCCEEDED(hr)) m_settings.MixingMode = dwVal; dwVal = reg.ReadDWORD(L"MixingCenterLevel", hr); if (SUCCEEDED(hr)) m_settings.MixingCenterLevel = dwVal; dwVal = reg.ReadDWORD(L"MixingSurroundLevel", hr); if (SUCCEEDED(hr)) m_settings.MixingSurroundLevel = dwVal; dwVal = reg.ReadDWORD(L"MixingLFELevel", hr); if (SUCCEEDED(hr)) m_settings.MixingLFELevel = dwVal; // Deprecated sample format storage pBuf = reg.ReadBinary(L"SampleFormats", dwVal, hr); if (SUCCEEDED(hr)) { memcpy(&m_settings.bSampleFormats, pBuf, min(dwVal, sizeof(m_settings.bSampleFormats))); SAFE_CO_FREE(pBuf); } bFlag = reg.ReadBOOL(L"AudioDelayEnabled", hr); if (SUCCEEDED(hr)) m_settings.AudioDelayEnabled = bFlag; dwVal = reg.ReadDWORD(L"AudioDelay", hr); if (SUCCEEDED(hr)) m_settings.AudioDelay = (int)dwVal; for (int i = 0; i < Bitstream_NB; ++i) { std::wstring key = std::wstring(L"Bitstreaming_") + std::wstring(bitstreamingCodecs[i]); bFlag = reg.ReadBOOL(key.c_str(), hr); if (SUCCEEDED(hr)) m_settings.bBitstream[i] = bFlag; } for (int i = 0; i < SampleFormat_Bitstream; ++i) { std::wstring key = std::wstring(L"SampleFormat_") + std::wstring(sampleFormats[i]); bFlag = reg.ReadBOOL(key.c_str(), hr); if (SUCCEEDED(hr)) m_settings.bSampleFormats[i] = bFlag; } bFlag = reg.ReadBOOL(L"SampleConvertDither", hr); if (SUCCEEDED(hr)) m_settings.SampleConvertDither = bFlag; } CRegistry regF = CRegistry(rootKey, LAVC_AUDIO_REGISTRY_KEY_FORMATS, hr, TRUE); if (SUCCEEDED(hr)) { for (int i = 0; i < Codec_AudioNB; ++i) { const codec_config_t *info = get_codec_config((LAVAudioCodec)i); ATL::CA2W name(info->name); bFlag = regF.ReadBOOL(name, hr); if (SUCCEEDED(hr)) m_settings.bFormats[i] = bFlag; } } return S_OK; } HRESULT CLAVAudio::SaveSettings() { if (m_bRuntimeConfig) return S_FALSE; HRESULT hr; CreateRegistryKey(HKEY_CURRENT_USER, LAVC_AUDIO_REGISTRY_KEY); CRegistry reg = CRegistry(HKEY_CURRENT_USER, LAVC_AUDIO_REGISTRY_KEY, hr); if (SUCCEEDED(hr)) { reg.WriteBOOL(L"TrayIcon", m_settings.TrayIcon); reg.WriteBOOL(L"DRCEnabled", m_settings.DRCEnabled); reg.WriteDWORD(L"DRCLevel", m_settings.DRCLevel); reg.WriteBOOL(L"DTSHDFraming", m_settings.DTSHDFraming); reg.WriteBOOL(L"BitstreamingFallback", m_settings.bBitstreamingFallback); reg.WriteBOOL(L"AutoAVSync", m_settings.AutoAVSync); reg.WriteBOOL(L"ExpandMono", m_settings.ExpandMono); reg.WriteBOOL(L"Expand61", m_settings.Expand61); reg.WriteBOOL(L"OutputStandardLayout", m_settings.OutputStandardLayout); reg.WriteBOOL(L"Output51Legacy", m_settings.Output51Legacy); reg.WriteBOOL(L"AudioDelayEnabled", m_settings.AudioDelayEnabled); reg.WriteDWORD(L"AudioDelay", m_settings.AudioDelay); reg.WriteBOOL(L"Mixing", m_settings.MixingEnabled); reg.WriteDWORD(L"MixingLayout", m_settings.MixingLayout); reg.WriteDWORD(L"MixingFlags", m_settings.MixingFlags); reg.WriteDWORD(L"MixingMode", m_settings.MixingMode); reg.WriteDWORD(L"MixingCenterLevel", m_settings.MixingCenterLevel); reg.WriteDWORD(L"MixingSurroundLevel", m_settings.MixingSurroundLevel); reg.WriteDWORD(L"MixingLFELevel", m_settings.MixingLFELevel); reg.DeleteKey(L"Formats"); CreateRegistryKey(HKEY_CURRENT_USER, LAVC_AUDIO_REGISTRY_KEY_FORMATS); CRegistry regF = CRegistry(HKEY_CURRENT_USER, LAVC_AUDIO_REGISTRY_KEY_FORMATS, hr); for (int i = 0; i < Codec_AudioNB; ++i) { const codec_config_t *info = get_codec_config((LAVAudioCodec)i); ATL::CA2W name(info->name); regF.WriteBOOL(name, m_settings.bFormats[i]); } reg.DeleteKey(L"Bitstreaming"); for (int i = 0; i < Bitstream_NB; ++i) { std::wstring key = std::wstring(L"Bitstreaming_") + std::wstring(bitstreamingCodecs[i]); reg.WriteBOOL(key.c_str(), m_settings.bBitstream[i]); } reg.DeleteKey(L"SampleFormats"); for (int i = 0; i < SampleFormat_Bitstream; ++i) { std::wstring key = std::wstring(L"SampleFormat_") + std::wstring(sampleFormats[i]); reg.WriteBOOL(key.c_str(), m_settings.bSampleFormats[i]); } reg.WriteBOOL(L"SampleConvertDither", m_settings.SampleConvertDither); } return S_OK; } void CLAVAudio::ffmpeg_shutdown() { m_pAVCodec = nullptr; if (m_pAVCtx) { av_freep(&m_pAVCtx->extradata); avcodec_free_context(&m_pAVCtx); } av_frame_free(&m_pFrame); av_packet_free(&m_pDecodePacket); if (m_pParser) { av_parser_close(m_pParser); m_pParser = nullptr; } if (m_swrContext) { swr_free(&m_swrContext); } FreeBitstreamContext(); m_nCodecId = AV_CODEC_ID_NONE; av_channel_layout_uninit(&m_DecodeLayout); av_channel_layout_uninit(&m_DecodeLayoutSanified); av_channel_layout_uninit(&m_SuppressLayout); av_channel_layout_uninit(&m_chRemixLayout); av_channel_layout_uninit(&m_chOverrideMixer); av_channel_layout_uninit(&m_MixingInputLayout); av_channel_layout_uninit(&m_ChannelMapOutputLayout); } // IUnknown STDMETHODIMP CLAVAudio::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; return QI(ISpecifyPropertyPages) QI(ISpecifyPropertyPages2) QI2(ILAVAudioSettings) QI2(ILAVAudioStatus) __super::NonDelegatingQueryInterface(riid, ppv); } // ISpecifyPropertyPages2 STDMETHODIMP CLAVAudio::GetPages(CAUUID *pPages) { CheckPointer(pPages, E_POINTER); BOOL bShowStatusPage = m_pInput && m_pInput->IsConnected(); pPages->cElems = bShowStatusPage ? 4 : 3; pPages->pElems = (GUID *)CoTaskMemAlloc(sizeof(GUID) * pPages->cElems); if (pPages->pElems == nullptr) { return E_OUTOFMEMORY; } pPages->pElems[0] = CLSID_LAVAudioSettingsProp; pPages->pElems[1] = CLSID_LAVAudioMixingProp; pPages->pElems[2] = CLSID_LAVAudioFormatsProp; if (bShowStatusPage) pPages->pElems[3] = CLSID_LAVAudioStatusProp; return S_OK; } STDMETHODIMP CLAVAudio::CreatePage(const GUID &guid, IPropertyPage **ppPage) { CheckPointer(ppPage, E_POINTER); HRESULT hr = S_OK; if (*ppPage != nullptr) return E_INVALIDARG; if (guid == CLSID_LAVAudioSettingsProp) *ppPage = new CLAVAudioSettingsProp(nullptr, &hr); else if (guid == CLSID_LAVAudioMixingProp) *ppPage = new CLAVAudioMixingProp(nullptr, &hr); else if (guid == CLSID_LAVAudioFormatsProp) *ppPage = new CLAVAudioFormatsProp(nullptr, &hr); else if (guid == CLSID_LAVAudioStatusProp) *ppPage = new CLAVAudioStatusProp(nullptr, &hr); if (SUCCEEDED(hr) && *ppPage) { (*ppPage)->AddRef(); return S_OK; } else { SAFE_DELETE(*ppPage); return E_FAIL; } } // ILAVAudioSettings HRESULT CLAVAudio::GetDRC(BOOL *pbDRCEnabled, int *piDRCLevel) { if (pbDRCEnabled) { *pbDRCEnabled = m_settings.DRCEnabled; } if (piDRCLevel) { *piDRCLevel = m_settings.DRCLevel; } return S_OK; } // ILAVAudioSettings HRESULT CLAVAudio::SetRuntimeConfig(BOOL bRuntimeConfig) { m_bRuntimeConfig = bRuntimeConfig; LoadSettings(); // Tray Icon is disabled by default SAFE_DELETE(m_pTrayIcon); return S_OK; } HRESULT CLAVAudio::SetDRC(BOOL bDRCEnabled, int fDRCLevel) { m_settings.DRCEnabled = bDRCEnabled; m_settings.DRCLevel = fDRCLevel; if (m_pAVCtx) { float fDRC = bDRCEnabled ? (float)fDRCLevel / 100.0f : 0.0f; av_opt_set_double(m_pAVCtx, "drc_scale", fDRC, AV_OPT_SEARCH_CHILDREN); } SaveSettings(); return S_OK; } BOOL CLAVAudio::GetFormatConfiguration(LAVAudioCodec aCodec) { if (aCodec < 0 || aCodec >= Codec_AudioNB) return FALSE; return m_settings.bFormats[aCodec]; } HRESULT CLAVAudio::SetFormatConfiguration(LAVAudioCodec aCodec, BOOL bEnabled) { if (aCodec < 0 || aCodec >= Codec_AudioNB) return E_FAIL; m_settings.bFormats[aCodec] = (bEnabled != 0); SaveSettings(); return S_OK; } BOOL CLAVAudio::GetBitstreamConfig(LAVBitstreamCodec bsCodec) { if (bsCodec < 0 || bsCodec >= Bitstream_NB) return FALSE; return m_settings.bBitstream[bsCodec]; } HRESULT CLAVAudio::SetBitstreamConfig(LAVBitstreamCodec bsCodec, BOOL bEnabled) { if (bsCodec >= Bitstream_NB) return E_FAIL; m_settings.bBitstream[bsCodec] = (bEnabled != 0); SaveSettings(); m_bBitStreamingSettingsChanged = TRUE; return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetDTSHDFraming() { return m_settings.DTSHDFraming; } STDMETHODIMP_(BOOL) CLAVAudio::GetBitstreamingFallback() { return m_settings.bBitstreamingFallback; } STDMETHODIMP CLAVAudio::SetDTSHDFraming(BOOL bHDFraming) { m_settings.DTSHDFraming = bHDFraming; SaveSettings(); if (m_nCodecId == AV_CODEC_ID_DTS) m_bBitStreamingSettingsChanged = TRUE; return S_OK; } STDMETHODIMP CLAVAudio::SetBitstreamingFallback(BOOL bBitstreamingFallback) { m_settings.bBitstreamingFallback = bBitstreamingFallback; SaveSettings(); return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetAutoAVSync() { return m_settings.AutoAVSync; } STDMETHODIMP CLAVAudio::SetAutoAVSync(BOOL bAutoSync) { m_settings.AutoAVSync = bAutoSync; SaveSettings(); return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetOutputStandardLayout() { return m_settings.OutputStandardLayout; } STDMETHODIMP CLAVAudio::SetOutputStandardLayout(BOOL bStdLayout) { m_settings.OutputStandardLayout = bStdLayout; SaveSettings(); return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetExpandMono() { return m_settings.ExpandMono; } STDMETHODIMP CLAVAudio::SetExpandMono(BOOL bExpandMono) { m_settings.ExpandMono = bExpandMono; SaveSettings(); return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetExpand61() { return m_settings.Expand61; } STDMETHODIMP CLAVAudio::SetExpand61(BOOL bExpand61) { m_settings.Expand61 = bExpand61; SaveSettings(); return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetAllowRawSPDIFInput() { return m_settings.AllowRawSPDIF; } STDMETHODIMP CLAVAudio::SetAllowRawSPDIFInput(BOOL bAllow) { m_settings.AllowRawSPDIF = bAllow; SaveSettings(); return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetSampleFormat(LAVAudioSampleFormat format) { if (format < 0 || format >= SampleFormat_NB) return FALSE; return m_settings.bSampleFormats[format]; } STDMETHODIMP CLAVAudio::SetSampleFormat(LAVAudioSampleFormat format, BOOL bEnabled) { if (format < 0 || format >= SampleFormat_NB) return E_FAIL; m_settings.bSampleFormats[format] = (bEnabled != 0); SaveSettings(); return S_OK; } STDMETHODIMP CLAVAudio::GetAudioDelay(BOOL *pbEnabled, int *pDelay) { if (pbEnabled) *pbEnabled = m_settings.AudioDelayEnabled; if (pDelay) *pDelay = m_settings.AudioDelay; return S_OK; } STDMETHODIMP CLAVAudio::SetAudioDelay(BOOL bEnabled, int delay) { m_settings.AudioDelayEnabled = bEnabled; m_settings.AudioDelay = delay; SaveSettings(); return S_OK; } STDMETHODIMP CLAVAudio::SetMixingEnabled(BOOL bEnabled) { m_settings.MixingEnabled = bEnabled; SaveSettings(); m_bMixingSettingsChanged = TRUE; return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetMixingEnabled() { return m_settings.MixingEnabled; } STDMETHODIMP CLAVAudio::SetMixingLayout(DWORD dwLayout) { m_settings.MixingLayout = dwLayout; SaveSettings(); m_bMixingSettingsChanged = TRUE; return S_OK; } STDMETHODIMP_(DWORD) CLAVAudio::GetMixingLayout() { return m_settings.MixingLayout; } STDMETHODIMP CLAVAudio::SetMixingFlags(DWORD dwFlags) { m_settings.MixingFlags = dwFlags; SaveSettings(); m_bMixingSettingsChanged = TRUE; return S_OK; } STDMETHODIMP_(DWORD) CLAVAudio::GetMixingFlags() { return m_settings.MixingFlags; } STDMETHODIMP CLAVAudio::SetMixingMode(LAVAudioMixingMode mixingMode) { m_settings.MixingMode = mixingMode; SaveSettings(); m_bMixingSettingsChanged = TRUE; return S_OK; } STDMETHODIMP_(LAVAudioMixingMode) CLAVAudio::GetMixingMode() { return (LAVAudioMixingMode)m_settings.MixingMode; } STDMETHODIMP CLAVAudio::SetMixingLevels(DWORD dwCenterLevel, DWORD dwSurroundLevel, DWORD dwLFELevel) { m_settings.MixingCenterLevel = dwCenterLevel; m_settings.MixingSurroundLevel = dwSurroundLevel; m_settings.MixingLFELevel = dwLFELevel; SaveSettings(); m_bMixingSettingsChanged = TRUE; return S_OK; } STDMETHODIMP CLAVAudio::GetMixingLevels(DWORD *dwCenterLevel, DWORD *dwSurroundLevel, DWORD *dwLFELevel) { if (dwCenterLevel) *dwCenterLevel = m_settings.MixingCenterLevel; if (dwSurroundLevel) *dwSurroundLevel = m_settings.MixingSurroundLevel; if (dwLFELevel) *dwLFELevel = m_settings.MixingLFELevel; return S_OK; } STDMETHODIMP CLAVAudio::SetTrayIcon(BOOL bEnabled) { m_settings.TrayIcon = bEnabled; // The tray icon is created if not yet done so, however its not removed on the fly // Removing the icon on the fly can cause deadlocks if the config is changed from the icons thread if (bEnabled && m_pGraph && !m_pTrayIcon) { CreateTrayIcon(); } return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVAudio::GetTrayIcon() { return m_settings.TrayIcon; } STDMETHODIMP CLAVAudio::SetSampleConvertDithering(BOOL bEnabled) { m_settings.SampleConvertDither = bEnabled; m_bMixingSettingsChanged = TRUE; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVAudio::GetSampleConvertDithering() { return m_settings.SampleConvertDither; } STDMETHODIMP CLAVAudio::SetSuppressFormatChanges(BOOL bEnabled) { m_settings.SuppressFormatChanges = bEnabled; return S_OK; } STDMETHODIMP_(BOOL) CLAVAudio::GetSuppressFormatChanges() { return m_settings.SuppressFormatChanges; } STDMETHODIMP CLAVAudio::SetOutput51LegacyLayout(BOOL b51Legacy) { m_settings.Output51Legacy = b51Legacy; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVAudio::GetOutput51LegacyLayout() { return m_settings.Output51Legacy; } // ILAVAudioStatus BOOL CLAVAudio::IsSampleFormatSupported(LAVAudioSampleFormat sfCheck) { return FALSE; } HRESULT CLAVAudio::GetDecodeDetails(const char **pCodec, const char **pDecodeFormat, int *pnChannels, int *pSampleRate, DWORD *pChannelMask) { if (!m_pInput || m_pInput->IsConnected() == FALSE || !m_pAVCtx) { return E_UNEXPECTED; } if (m_avBSContext) { if (pCodec) { const AVCodec *codec = avcodec_find_decoder(m_nCodecId); *pCodec = codec->name; } if (pnChannels) { *pnChannels = m_avBSContext->streams[0]->codecpar->ch_layout.nb_channels; } if (pSampleRate) { *pSampleRate = m_avBSContext->streams[0]->codecpar->sample_rate; } if (pDecodeFormat) { *pDecodeFormat = ""; } if (pChannelMask) { *pChannelMask = 0; } } else { if (pCodec) { if (m_pAVCodec) { if (m_nCodecId == AV_CODEC_ID_DTS && m_pAVCtx && m_pAVCtx->profile != AV_PROFILE_UNKNOWN) { static const char *DTSProfiles[] = {nullptr, nullptr, "dts", "dts-es", "dts 96/24", "dts-hd hra", "dts-hd ma", "dts express"}; int index = m_pAVCtx->profile / 10; if (index >= 0 && index < countof(DTSProfiles) && DTSProfiles[index]) *pCodec = DTSProfiles[index]; else *pCodec = "dts"; } else *pCodec = m_pAVCodec->name; } } if (pnChannels) { *pnChannels = m_pAVCtx->ch_layout.nb_channels; } if (pSampleRate) { *pSampleRate = m_pAVCtx->sample_rate; } if (pDecodeFormat) { if (IsActive()) *pDecodeFormat = get_sample_format_desc(m_DecodeFormat); else *pDecodeFormat = "Not Running"; } if (pChannelMask) { if (m_DecodeLayout.order == AV_CHANNEL_ORDER_NATIVE) *pChannelMask = (DWORD)m_DecodeLayout.u.mask; else *pChannelMask = 0; } } return S_OK; } HRESULT CLAVAudio::GetOutputDetails(const char **pOutputFormat, int *pnChannels, int *pSampleRate, DWORD *pChannelMask) { if (!m_pOutput || m_pOutput->IsConnected() == FALSE) { return E_UNEXPECTED; } if (m_avBSContext) { if (pOutputFormat) { *pOutputFormat = get_sample_format_desc(SampleFormat_Bitstream); } return S_FALSE; } if (pOutputFormat) { *pOutputFormat = get_sample_format_desc(m_OutputQueue.sfFormat); } if (pnChannels) { *pnChannels = m_OutputQueue.layout.nb_channels; } if (pSampleRate) { *pSampleRate = m_OutputQueue.dwSamplesPerSec; } if (pChannelMask) { if (m_OutputQueue.layout.order == AV_CHANNEL_ORDER_NATIVE) *pChannelMask = (DWORD)m_OutputQueue.layout.u.mask; else *pChannelMask = 0; } return S_OK; } HRESULT CLAVAudio::EnableVolumeStats() { DbgLog((LOG_TRACE, 1, L"Volume Statistics Enabled")); m_bVolumeStats = TRUE; return S_OK; } HRESULT CLAVAudio::DisableVolumeStats() { DbgLog((LOG_TRACE, 1, L"Volume Statistics Disabled")); m_bVolumeStats = FALSE; return S_OK; } HRESULT CLAVAudio::GetChannelVolumeAverage(WORD nChannel, float *pfDb) { CheckPointer(pfDb, E_POINTER); if (!m_pOutput || m_pOutput->IsConnected() == FALSE || !m_bVolumeStats || m_avBSContext) { return E_UNEXPECTED; } if (nChannel >= m_OutputQueue.layout.nb_channels || nChannel >= MAX_VOLUME_STAT_CHANNEL) { return E_INVALIDARG; } *pfDb = m_faVolume[nChannel].Average(); return S_OK; } // CTransformFilter HRESULT CLAVAudio::CheckInputType(const CMediaType *mtIn) { for (UINT i = 0; i < sudPinTypesInCount; i++) { if (*sudPinTypesIn[i].clsMajorType == mtIn->majortype && *sudPinTypesIn[i].clsMinorType == mtIn->subtype && (mtIn->formattype == FORMAT_WaveFormatEx || mtIn->formattype == FORMAT_WaveFormatExFFMPEG || mtIn->formattype == FORMAT_VorbisFormat2)) { return S_OK; } } if (m_settings.AllowRawSPDIF) { if (mtIn->majortype == MEDIATYPE_Audio && mtIn->formattype == FORMAT_WaveFormatEx && (mtIn->subtype == MEDIASUBTYPE_PCM || mtIn->subtype == MEDIASUBTYPE_IEEE_FLOAT || mtIn->subtype == MEDIASUBTYPE_DOLBY_AC3_SPDIF)) { return S_OK; } } return VFW_E_TYPE_NOT_ACCEPTED; } // Get the output media types HRESULT CLAVAudio::GetMediaType(int iPosition, CMediaType *pMediaType) { DbgLog((LOG_TRACE, 5, L"GetMediaType")); if (m_pInput->IsConnected() == FALSE || !((m_pAVCtx && m_pAVCodec) || m_avBSContext)) { return E_UNEXPECTED; } if (iPosition < 0) { return E_INVALIDARG; } if (m_avBSContext) { if (iPosition == 0) { *pMediaType = CreateBitstreamMediaType(m_nCodecId, m_pAVCtx->sample_rate, TRUE); return S_OK; } else { if (!m_settings.bBitstreamingFallback) return VFW_S_NO_MORE_ITEMS; iPosition--; } } const int nSamplesPerSec = m_pAVCtx->sample_rate; int nChannels = m_pAVCtx->ch_layout.nb_channels; DWORD dwChannelMask = get_lav_channel_layout(&m_pAVCtx->ch_layout); if (dwChannelMask == 0) dwChannelMask = get_channel_mask(nChannels); AVSampleFormat sample_fmt = m_pAVCtx->sample_fmt; if (sample_fmt == AV_SAMPLE_FMT_NONE) { int num_configs = 0; const enum AVSampleFormat *SampleFormats = NULL; int ret = avcodec_get_supported_config(m_pAVCtx, m_pAVCodec, AV_CODEC_CONFIG_SAMPLE_FORMAT, 0, (const void **)&SampleFormats, &num_configs); if (ret >= 0 && num_configs > 0 && SampleFormats) sample_fmt = SampleFormats[0]; } if (sample_fmt == AV_SAMPLE_FMT_NONE) sample_fmt = AV_SAMPLE_FMT_S32; // this gets mapped to S16/S24/S32 in get_lav_sample_fmt based on the bits per sample // Prefer bits_per_raw_sample if set, but if not, try to do a better guess with bits per coded sample int bits = m_pAVCtx->bits_per_raw_sample ? m_pAVCtx->bits_per_raw_sample : m_pAVCtx->bits_per_coded_sample; LAVAudioSampleFormat lav_sample_fmt = get_lav_sample_fmt(sample_fmt, bits); if (m_settings.MixingEnabled) { if (nChannels != av_popcount(m_settings.MixingLayout) && (nChannels > 2 || !(m_settings.MixingFlags & LAV_MIXING_FLAG_UNTOUCHED_STEREO))) { lav_sample_fmt = SampleFormat_FP32; bits = 32; dwChannelMask = m_settings.MixingLayout; nChannels = av_popcount(dwChannelMask); } else if (nChannels == 7 && m_settings.Expand61) { nChannels = 8; dwChannelMask = get_channel_mask(nChannels); } else if (nChannels == 1 && m_settings.ExpandMono) { nChannels = 2; dwChannelMask = get_channel_mask(nChannels); } } // possible format combinations: // 0: original // 1: 16-bit integer fallback // 2: alternate channel layout/count (5.1 back, or downmix to 8 channel) // 3: alternate channel layout, 16-bit // map to legacy 5.1 if user requested if (dwChannelMask == AV_CH_LAYOUT_5POINT1 && m_settings.Output51Legacy) dwChannelMask = AV_CH_LAYOUT_5POINT1_BACK; if (dwChannelMask == AV_CH_LAYOUT_5POINT1 && iPosition > 1 && iPosition < 4) dwChannelMask = AV_CH_LAYOUT_5POINT1_BACK; else if (nChannels > 8 && iPosition > 1 && iPosition < 4) // more then 8 channel, offer a downmix to 8 channel { nChannels = 8; dwChannelMask = AV_CH_LAYOUT_7POINT1; } else if (iPosition > 1) return VFW_S_NO_MORE_ITEMS; if (iPosition % 2) { lav_sample_fmt = SampleFormat_16; bits = 16; } else { lav_sample_fmt = GetBestAvailableSampleFormat(lav_sample_fmt, &bits, TRUE); } *pMediaType = CreateMediaType(lav_sample_fmt, nSamplesPerSec, nChannels, dwChannelMask, bits); return S_OK; } HRESULT CLAVAudio::ReconnectOutput(long cbBuffer, CMediaType &mt) { HRESULT hr = S_FALSE; IMemInputPin *pPin = nullptr; IMemAllocator *pAllocator = nullptr; CHECK_HR(hr = m_pOutput->GetConnected()->QueryInterface(&pPin)); if (FAILED(hr = pPin->GetAllocator(&pAllocator)) || !pAllocator) { goto done; } ALLOCATOR_PROPERTIES props, actual; CHECK_HR(hr = pAllocator->GetProperties(&props)); hr = S_FALSE; if (mt != m_pOutput->CurrentMediaType() || cbBuffer > props.cbBuffer) { DbgLog( (LOG_TRACE, 10, L"::ReconnectOutput(): Reconnecting output because media type or buffer size changed...")); if (cbBuffer > props.cbBuffer) { DbgLog((LOG_TRACE, 10, L"::ReconnectOutput(): -> Increasing buffer size")); props.cBuffers = 4; props.cbBuffer = cbBuffer * 3 / 2; if (FAILED(hr = m_pOutput->DeliverBeginFlush()) || FAILED(hr = m_pOutput->DeliverEndFlush()) || FAILED(hr = pAllocator->Decommit()) || FAILED(hr = pAllocator->SetProperties(&props, &actual)) || FAILED(hr = pAllocator->Commit())) { goto done; } if (props.cBuffers > actual.cBuffers || props.cbBuffer > actual.cbBuffer) { NotifyEvent(EC_ERRORABORT, hr, 0); hr = E_FAIL; goto done; } } hr = S_OK; } done: SafeRelease(&pPin); SafeRelease(&pAllocator); return hr; } CMediaType CLAVAudio::CreateMediaType(LAVAudioSampleFormat outputFormat, DWORD nSamplesPerSec, WORD nChannels, DWORD dwChannelMask, WORD wBitsPerSample) const { CMediaType mt; mt.majortype = MEDIATYPE_Audio; mt.subtype = (outputFormat == SampleFormat_FP32) ? MEDIASUBTYPE_IEEE_FLOAT : MEDIASUBTYPE_PCM; mt.formattype = FORMAT_WaveFormatEx; WAVEFORMATEXTENSIBLE wfex; memset(&wfex, 0, sizeof(wfex)); if (wBitsPerSample >> 3 > get_byte_per_sample(outputFormat)) { DbgLog((LOG_TRACE, 20, L"Invalid combination of sample format and bits per sample")); outputFormat = get_lav_sample_fmt(AV_SAMPLE_FMT_S32, wBitsPerSample); } WAVEFORMATEX *wfe = &wfex.Format; wfe->wFormatTag = (WORD)mt.subtype.Data1; wfe->nChannels = nChannels; wfe->nSamplesPerSec = nSamplesPerSec; wfe->wBitsPerSample = get_byte_per_sample(outputFormat) << 3; wfe->nBlockAlign = wfe->nChannels * wfe->wBitsPerSample / 8; wfe->nAvgBytesPerSec = wfe->nSamplesPerSec * wfe->nBlockAlign; BOOL bUseExtensible = FALSE; // non-standard mono/stereo if (dwChannelMask != 0 && (nChannels == 1 && dwChannelMask != KSAUDIO_SPEAKER_MONO || nChannels == 2 && dwChannelMask != KSAUDIO_SPEAKER_STEREO)) bUseExtensible = TRUE; else if (nChannels > 2) // more then two channels bUseExtensible = TRUE; else if (wfe->wBitsPerSample > 16 && outputFormat != SampleFormat_FP32) // high bitdepth integer bUseExtensible = TRUE; else if (wfe->nSamplesPerSec > 48000) // high sample rate bUseExtensible = TRUE; if (bUseExtensible) { wfex.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; wfex.Format.cbSize = sizeof(wfex) - sizeof(wfex.Format); wfex.dwChannelMask = dwChannelMask; if (wBitsPerSample > 0 && (outputFormat == SampleFormat_24 || outputFormat == SampleFormat_32)) { WORD wBpp = wBitsPerSample; if ((outputFormat == SampleFormat_24 && wBpp <= 16) || (outputFormat == SampleFormat_32 && wBpp < 24)) wBpp = 24; wfex.Samples.wValidBitsPerSample = wBpp; } else { wfex.Samples.wValidBitsPerSample = wfex.Format.wBitsPerSample; } wfex.SubFormat = mt.subtype; } mt.SetSampleSize(wfe->wBitsPerSample * wfe->nChannels / 8); mt.SetFormat((BYTE *)&wfex, sizeof(wfex.Format) + wfex.Format.cbSize); return mt; } // Check if the types are compatible HRESULT CLAVAudio::CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut) { // Check major types if (FAILED(CheckInputType(mtIn)) || mtOut->majortype != MEDIATYPE_Audio || (mtOut->subtype != MEDIASUBTYPE_PCM && mtOut->subtype != MEDIASUBTYPE_IEEE_FLOAT) || mtOut->formattype != FORMAT_WaveFormatEx) { return VFW_E_TYPE_NOT_ACCEPTED; } else { // Check for valid pcm settings, but only when output type is changing if (!m_avBSContext && m_pAVCtx && *mtOut != m_pOutput->CurrentMediaType()) { WAVEFORMATEX *wfex = (WAVEFORMATEX *)mtOut->pbFormat; if (wfex->nSamplesPerSec != m_pAVCtx->sample_rate) { return VFW_E_TYPE_NOT_ACCEPTED; } } } return S_OK; } HRESULT CLAVAudio::DecideBufferSize(IMemAllocator *pAllocator, ALLOCATOR_PROPERTIES *pProperties) { if (m_pInput->IsConnected() == FALSE) { return E_UNEXPECTED; } /*CMediaType& mt = m_pInput->CurrentMediaType(); WAVEFORMATEX* wfe = (WAVEFORMATEX*)mt.Format(); UNUSED_ALWAYS(wfe); */ pProperties->cBuffers = 4; // TODO: we should base this on the output media type pProperties->cbBuffer = LAV_AUDIO_BUFFER_SIZE; // 48KHz 6ch 32bps 100ms pProperties->cbAlign = 1; pProperties->cbPrefix = 0; HRESULT hr; ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAllocator->SetProperties(pProperties, &Actual))) { return hr; } return pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer ? E_FAIL : NOERROR; } HRESULT CLAVAudio::ffmpeg_init(AVCodecID codec, const void *format, const GUID format_type, DWORD formatlen) { CAutoLock lock(&m_csReceive); ffmpeg_shutdown(); DbgLog((LOG_TRACE, 10, L"::ffmpeg_init(): Initializing decoder for codec %S", avcodec_get_name(codec))); if (codec == AV_CODEC_ID_DTS || codec == AV_CODEC_ID_TRUEHD) { m_faJitter.SetNumSamples(256); m_JitterLimit = MAX_JITTER_DESYNC * 10; } else { m_faJitter.SetNumSamples(64); m_JitterLimit = MAX_JITTER_DESYNC; } // Fake codecs that are dependant in input bits per sample, mostly to handle QT PCM tracks if (codec == AV_CODEC_ID_PCM_QTRAW || codec == AV_CODEC_ID_PCM_SxxBE || codec == AV_CODEC_ID_PCM_SxxLE || codec == AV_CODEC_ID_PCM_UxxBE || codec == AV_CODEC_ID_PCM_UxxLE) { if (format_type == FORMAT_WaveFormatEx) { WAVEFORMATEX *wfein = (WAVEFORMATEX *)format; ASSERT(wfein->wBitsPerSample == 8 || wfein->wBitsPerSample == 16); switch (codec) { case AV_CODEC_ID_PCM_QTRAW: codec = wfein->wBitsPerSample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16BE; break; case AV_CODEC_ID_PCM_SxxBE: codec = wfein->wBitsPerSample == 8 ? AV_CODEC_ID_PCM_S8 : AV_CODEC_ID_PCM_S16BE; break; case AV_CODEC_ID_PCM_SxxLE: codec = wfein->wBitsPerSample == 8 ? AV_CODEC_ID_PCM_S8 : AV_CODEC_ID_PCM_S16LE; break; case AV_CODEC_ID_PCM_UxxBE: codec = wfein->wBitsPerSample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_U16BE; break; case AV_CODEC_ID_PCM_UxxLE: codec = wfein->wBitsPerSample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_U16LE; break; } } } // Special check for enabled PCM if (codec >= 0x10000 && codec < 0x12000 && codec != AV_CODEC_ID_PCM_BLURAY && codec != AV_CODEC_ID_PCM_DVD && !m_settings.bFormats[Codec_PCM]) return VFW_E_UNSUPPORTED_AUDIO; for (int i = 0; i < Codec_AudioNB; ++i) { const codec_config_t *config = get_codec_config((LAVAudioCodec)i); bool bMatched = false; for (int k = 0; k < config->nCodecs; ++k) { if (config->codecs[k] == codec) { bMatched = true; break; } } if (bMatched && !m_settings.bFormats[i]) { return VFW_E_UNSUPPORTED_AUDIO; } } // If the codec is bitstreaming, and enabled for it, go there now if (IsBitstreaming(codec)) { WAVEFORMATEX *wfe = (format_type == FORMAT_WaveFormatEx) ? (WAVEFORMATEX *)format : nullptr; if (wfe) CreateBitstreamContext(codec, wfe); } m_pAVCodec = nullptr; // Try codec overrides const char *codec_override = find_codec_override(codec); if (codec_override) m_pAVCodec = avcodec_find_decoder_by_name(codec_override); // Fallback to default if (!m_pAVCodec) m_pAVCodec = avcodec_find_decoder(codec); CheckPointer(m_pAVCodec, VFW_E_UNSUPPORTED_AUDIO); m_pAVCtx = avcodec_alloc_context3(m_pAVCodec); CheckPointer(m_pAVCtx, E_POINTER); if ((codec != AV_CODEC_ID_AAC || m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_MPEG_ADTS_AAC) && codec != AV_CODEC_ID_FLAC && codec != AV_CODEC_ID_COOK) m_pParser = av_parser_init(codec); if (codec == AV_CODEC_ID_OPUS) { m_pAVCtx->request_sample_fmt = AV_SAMPLE_FMT_FLT; } else if (codec == AV_CODEC_ID_ALAC) { m_pAVCtx->request_sample_fmt = AV_SAMPLE_FMT_S32P; } // We can only trust LAV Splitters LATM AAC header... BOOL bTrustExtraData = TRUE; if (codec == AV_CODEC_ID_AAC_LATM) { if (!(FilterInGraphSafe(m_pInput, CLSID_LAVSplitter) || FilterInGraphSafe(m_pInput, CLSID_LAVSplitterSource))) { bTrustExtraData = FALSE; } } DWORD nSamples, nBytesPerSec, nChannelMask; WORD nChannels, nBitsPerSample, nBlockAlign; audioFormatTypeHandler((BYTE *)format, &format_type, &nSamples, &nChannels, &nBitsPerSample, &nBlockAlign, &nBytesPerSec, &nChannelMask); size_t extralen = 0; getExtraData((BYTE *)format, &format_type, formatlen, nullptr, &extralen); m_pAVCtx->thread_count = 1; m_pAVCtx->thread_type = 0; m_pAVCtx->sample_rate = nSamples; m_pAVCtx->ch_layout.order = AV_CHANNEL_ORDER_UNSPEC; m_pAVCtx->ch_layout.nb_channels = nChannels; if (nChannelMask != 0 && av_popcount(nChannelMask) == nChannels) { av_channel_layout_uninit(&m_pAVCtx->ch_layout); av_channel_layout_from_mask(&m_pAVCtx->ch_layout, nChannelMask); } m_pAVCtx->bit_rate = nBytesPerSec << 3; m_pAVCtx->bits_per_coded_sample = nBitsPerSample; m_pAVCtx->block_align = nBlockAlign; m_pAVCtx->err_recognition = 0; m_pAVCtx->pkt_timebase.num = 1; m_pAVCtx->pkt_timebase.den = 10000000; memset(&m_raData, 0, sizeof(m_raData)); if (bTrustExtraData && extralen) { if (codec == AV_CODEC_ID_COOK || codec == AV_CODEC_ID_ATRAC3 || codec == AV_CODEC_ID_SIPR) { uint8_t *extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData((BYTE *)format, &format_type, formatlen, extra, nullptr); if (extra[0] == '.' && extra[1] == 'r' && extra[2] == 'a' && extra[3] == 0xfd) { HRESULT hr = ParseRealAudioHeader(extra, extralen); av_freep(&extra); if (FAILED(hr)) return hr; if (codec == AV_CODEC_ID_SIPR) { if (m_raData.flavor > 3) { DbgLog((LOG_TRACE, 10, L"-> Invalid SIPR flavor (%d)", m_raData.flavor)); return VFW_E_UNSUPPORTED_AUDIO; } m_pAVCtx->block_align = ff_sipr_subpk_size[m_raData.flavor]; } else if (codec == AV_CODEC_ID_COOK || codec == AV_CODEC_ID_ATRAC3) { m_pAVCtx->block_align = m_raData.sub_packet_size; } // Validate some settings if (m_raData.deint_id == MKBETAG('g', 'e', 'n', 'r')) { if (m_raData.sub_packet_size <= 0 || m_raData.sub_packet_size > m_raData.audio_framesize) return VFW_E_UNSUPPORTED_AUDIO; } } else { // Try without any processing? m_pAVCtx->extradata_size = (int)extralen; m_pAVCtx->extradata = extra; } } else { m_pAVCtx->extradata_size = (int)extralen; m_pAVCtx->extradata = (uint8_t *)av_mallocz(m_pAVCtx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData((BYTE *)format, &format_type, formatlen, m_pAVCtx->extradata, nullptr); } } m_nCodecId = codec; int ret = avcodec_open2(m_pAVCtx, m_pAVCodec, nullptr); if (ret >= 0) { m_pFrame = av_frame_alloc(); } else { return VFW_E_UNSUPPORTED_AUDIO; } // Set initial format for DTS based on the best guess if (codec == AV_CODEC_ID_DTS) { if (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_DTS_HD) { // HD with 16 or 24 bits is likely HD MA // everything else outputs float if (nBitsPerSample == 24) { m_pAVCtx->sample_fmt = AV_SAMPLE_FMT_S32P; m_pAVCtx->bits_per_raw_sample = 24; } else if (nBitsPerSample == 16) { m_pAVCtx->sample_fmt = AV_SAMPLE_FMT_S16P; m_pAVCtx->bits_per_raw_sample = 16; } else { m_pAVCtx->sample_fmt = AV_SAMPLE_FMT_FLTP; } } // Lossy is by default float output else { m_pAVCtx->sample_fmt = AV_SAMPLE_FMT_FLTP; } } // Parse VorbisComment entries from FLAC extradata to find the WAVEFORMATEXTENSIBLE_CHANNEL_MASK tag // This tag is used to store non-standard channel layouts in FLAC files, see LAV-8 / Issue 342 if (codec == AV_CODEC_ID_FLAC) { uint8_t *streaminfo; ret = ff_flac_is_extradata_valid(m_pAVCtx, &streaminfo); // full FLAC header if (ret && AV_RL32(m_pAVCtx->extradata) == MKTAG('f','L','a','C')) { AVDictionary *metadata = nullptr; int metadata_last = 0, metadata_type, metadata_size; uint8_t *header = m_pAVCtx->extradata + 4, *end = m_pAVCtx->extradata + m_pAVCtx->extradata_size; while (header + 4 < end && !metadata_last) { flac_parse_block_header(header, &metadata_last, &metadata_type, &metadata_size); header += 4; if (header + metadata_size > end) break; switch (metadata_type) { case FLAC_METADATA_TYPE_VORBIS_COMMENT: ff_vorbis_comment(nullptr, &metadata, header, metadata_size, 0); break; } header += metadata_size; } if (metadata) { AVDictionaryEntry *entry = av_dict_get(metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", nullptr, 0); if (entry && entry->value) { uint64_t channel_layout = strtol(entry->value, nullptr, 0); if (channel_layout && av_popcount64(channel_layout) == m_pAVCtx->ch_layout.nb_channels) { av_channel_layout_uninit(&m_pAVCtx->ch_layout); av_channel_layout_from_mask(&m_pAVCtx->ch_layout, channel_layout); } } av_dict_free(&metadata); } } } // Set Dynamic Range Compression float drc_scale = m_settings.DRCEnabled ? (float)m_settings.DRCLevel / 100.0f : 0.0f; ret = av_opt_set_double(m_pAVCtx, "drc_scale", drc_scale, AV_OPT_SEARCH_CHILDREN); // This could probably be a bit smarter.. if (codec == AV_CODEC_ID_PCM_BLURAY || codec == AV_CODEC_ID_PCM_DVD) { m_pAVCtx->bits_per_raw_sample = m_pAVCtx->bits_per_coded_sample; } // Some sanity checks if (m_pAVCtx->ch_layout.nb_channels > 64) { return VFW_E_UNSUPPORTED_AUDIO; } m_bFindDTSInPCM = (codec == AV_CODEC_ID_PCM_S16LE && m_settings.bFormats[Codec_DTS]); m_FallbackFormat = SampleFormat_None; av_channel_layout_uninit(&m_chOverrideMixer); av_channel_layout_uninit(&m_SuppressLayout); m_bMixingSettingsChanged = TRUE; m_bMPEGAudioResync = (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_MPEG1AudioPayload); return S_OK; } HRESULT CLAVAudio::SetMediaType(PIN_DIRECTION dir, const CMediaType *pmt) { DbgLog((LOG_TRACE, 5, L"SetMediaType -- %S", dir == PINDIR_INPUT ? "in" : "out")); if (dir == PINDIR_INPUT) { AVCodecID codec = AV_CODEC_ID_NONE; const void *format = pmt->Format(); GUID format_type = pmt->formattype; DWORD formatlen = pmt->cbFormat; // Override the format type if (pmt->subtype == MEDIASUBTYPE_FFMPEG_AUDIO && pmt->formattype == FORMAT_WaveFormatExFFMPEG) { WAVEFORMATEXFFMPEG *wfexff = (WAVEFORMATEXFFMPEG *)pmt->Format(); codec = (AVCodecID)wfexff->nCodecId; format = &wfexff->wfex; format_type = FORMAT_WaveFormatEx; formatlen -= sizeof(WAVEFORMATEXFFMPEG) - sizeof(WAVEFORMATEX); } else { codec = FindCodecId(pmt); } if (codec == AV_CODEC_ID_NONE) { if (m_settings.AllowRawSPDIF) { if (pmt->formattype == FORMAT_WaveFormatEx && pmt->subtype == MEDIASUBTYPE_PCM) { WAVEFORMATEX *wfex = (WAVEFORMATEX *)pmt->Format(); switch (wfex->wBitsPerSample) { case 8: codec = AV_CODEC_ID_PCM_U8; break; case 16: codec = AV_CODEC_ID_PCM_S16LE; break; case 24: codec = AV_CODEC_ID_PCM_S24LE; break; case 32: codec = AV_CODEC_ID_PCM_S32LE; break; } } else if (pmt->formattype == FORMAT_WaveFormatEx && pmt->subtype == MEDIASUBTYPE_IEEE_FLOAT) { codec = AV_CODEC_ID_PCM_F32LE; } else if (pmt->subtype == MEDIASUBTYPE_DOLBY_AC3_SPDIF) { codec = AV_CODEC_ID_AC3; } } if (codec == AV_CODEC_ID_NONE) return VFW_E_TYPE_NOT_ACCEPTED; } HRESULT hr = ffmpeg_init(codec, format, format_type, formatlen); if (FAILED(hr)) { return hr; } m_bDVDPlayback = (pmt->majortype == MEDIATYPE_DVD_ENCRYPTED_PACK || pmt->majortype == MEDIATYPE_MPEG2_PACK || pmt->majortype == MEDIATYPE_MPEG2_PES); } return __super::SetMediaType(dir, pmt); } HRESULT CLAVAudio::CheckConnect(PIN_DIRECTION dir, IPin *pPin) { DbgLog((LOG_TRACE, 5, L"CheckConnect -- %S", dir == PINDIR_INPUT ? "in" : "out")); if (dir == PINDIR_INPUT) { if (!m_bRuntimeConfig && CheckApplicationBlackList(LAVC_AUDIO_REGISTRY_KEY L"\\Blacklist")) return E_FAIL; // TODO: Check if the upstream source filter is LAVFSplitter, and store that somewhere // Validate that this is called before any media type negotiation } return __super::CheckConnect(dir, pPin); } HRESULT CLAVAudio::CompleteConnect(PIN_DIRECTION dir, IPin *pReceivePin) { DbgLog((LOG_TRACE, 5, L"CompleteConnect -- %S", dir == PINDIR_INPUT ? "in" : "out")); if (dir == PINDIR_OUTPUT) { // check that we connected with a bitstream type, or go back to decoding otherwise if (m_avBSContext && m_settings.bBitstreamingFallback) { CMediaType &mt = m_pOutput->CurrentMediaType(); WAVEFORMATEX *wfe = (WAVEFORMATEX *)mt.Format(); bool bPCM = false; // float is always PCM if (mt.subtype == MEDIASUBTYPE_IEEE_FLOAT || wfe->wFormatTag == WAVE_FORMAT_PCM) bPCM = true; else if (wfe->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)wfe; if (wfex->SubFormat == MEDIASUBTYPE_IEEE_FLOAT || wfex->SubFormat == MEDIASUBTYPE_PCM) bPCM = true; } if (bPCM) BitstreamFallbackToPCM(); } } return __super::CompleteConnect(dir, pReceivePin); } HRESULT CLAVAudio::EndOfStream() { DbgLog((LOG_TRACE, 10, L"CLAVAudio::EndOfStream()")); CAutoLock cAutoLock(&m_csReceive); // Flush the last data out of the parser ProcessBuffer(nullptr); ProcessBuffer(nullptr, TRUE); FlushOutput(TRUE); return __super::EndOfStream(); } HRESULT CLAVAudio::PerformFlush() { CAutoLock cAutoLock(&m_csReceive); m_buff.Clear(); FlushOutput(FALSE); FlushDecoder(); m_bsOutput.SetSize(0); m_rtStart = 0; m_bQueueResync = TRUE; m_bNeedSyncpoint = (m_raData.deint_id != 0); av_channel_layout_uninit(&m_SuppressLayout); m_bMPEGAudioResync = (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_MPEG1AudioPayload); memset(&m_TrueHDMATState, 0, sizeof(m_TrueHDMATState)); m_rtBitstreamCache = AV_NOPTS_VALUE; return S_OK; } HRESULT CLAVAudio::BeginFlush() { DbgLog((LOG_TRACE, 10, L"CLAVAudio::BeginFlush()")); m_bFlushing = TRUE; return __super::BeginFlush(); } HRESULT CLAVAudio::EndFlush() { DbgLog((LOG_TRACE, 10, L"CLAVAudio::EndFlush()")); CAutoLock cAutoLock(&m_csReceive); if (m_bDVDPlayback) PerformFlush(); HRESULT hr = __super::EndFlush(); m_bFlushing = FALSE; return hr; } HRESULT CLAVAudio::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { DbgLog((LOG_TRACE, 10, L"CLAVAudio::NewSegment() tStart: %I64d, tStop: %I64d, dRate: %.2f", tStart, tStop, dRate)); CAutoLock cAutoLock(&m_csReceive); PerformFlush(); if (dRate > 0.0) m_dRate = dRate; else m_dRate = 1.0; return __super::NewSegment(tStart, tStop, dRate); } HRESULT CLAVAudio::FlushDecoder() { if (m_bJustFlushed) return S_OK; if (m_pParser) { av_parser_close(m_pParser); m_pParser = av_parser_init(m_nCodecId); m_bUpdateTimeCache = TRUE; } if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) { avcodec_flush_buffers(m_pAVCtx); } m_bJustFlushed = TRUE; return S_OK; } HRESULT CLAVAudio::Receive(IMediaSample *pIn) { CAutoLock cAutoLock(&m_csReceive); HRESULT hr; AM_SAMPLE2_PROPERTIES const *pProps = m_pInput->SampleProps(); if (pProps->dwStreamId != AM_STREAM_MEDIA) { return m_pOutput->Deliver(pIn); } AM_MEDIA_TYPE *pmt; if (SUCCEEDED(pIn->GetMediaType(&pmt)) && pmt) { DbgLog((LOG_TRACE, 10, L"::Receive(): Input sample contained media type, dynamic format change...")); CMediaType mt(*pmt); m_pInput->SetMediaType(&mt); DeleteMediaType(pmt); pmt = nullptr; m_buff.Clear(); m_bQueueResync = TRUE; } if (m_bBitStreamingSettingsChanged) { m_bBitStreamingSettingsChanged = FALSE; UpdateBitstreamContext(); } if (!m_pAVCtx) { return E_FAIL; } BYTE *pDataIn = nullptr; if (FAILED(hr = pIn->GetPointer(&pDataIn))) { return hr; } long len = pIn->GetActualDataLength(); if (len < 0) { DbgLog((LOG_ERROR, 10, L"Invalid data length, aborting")); return E_FAIL; } else if (len == 0) { return S_OK; } (static_cast(m_pInput))->StripPacket(pDataIn, len); REFERENCE_TIME rtStart = _I64_MIN, rtStop = _I64_MIN; hr = pIn->GetTime(&rtStart, &rtStop); if ((pIn->IsDiscontinuity() == S_OK || (m_bNeedSyncpoint && pIn->IsSyncPoint() == S_OK))) { DbgLog((LOG_ERROR, 10, L"::Receive(): Discontinuity, flushing decoder..")); m_buff.Clear(); FlushOutput(FALSE); FlushDecoder(); m_bQueueResync = TRUE; m_bDiscontinuity = TRUE; if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L" -> Discontinuity without timestamp")); } if (m_bNeedSyncpoint && pIn->IsSyncPoint() == S_OK) { DbgLog((LOG_TRACE, 10, L"::Receive(): Got SyncPoint, resuming decoding....")); m_bNeedSyncpoint = FALSE; } } if (m_bQueueResync && SUCCEEDED(hr)) { DbgLog((LOG_TRACE, 10, L"Resync Request; old: %I64d; new: %I64d; buffer: %d", m_rtStart, rtStart, m_buff.GetCount())); FlushOutput(); if (m_rtStart != AV_NOPTS_VALUE && rtStart != m_rtStart) m_bDiscontinuity = TRUE; m_rtStart = rtStart; m_rtStartInputCache = AV_NOPTS_VALUE; m_rtBitstreamCache = AV_NOPTS_VALUE; m_dStartOffset = 0.0; m_bQueueResync = FALSE; m_bResyncTimestamp = TRUE; } m_bJustFlushed = FALSE; m_rtStartInput = SUCCEEDED(hr) ? rtStart : AV_NOPTS_VALUE; m_rtStopInput = (hr == S_OK) ? rtStop : AV_NOPTS_VALUE; DWORD bufflen = m_buff.GetCount(); // Hack to re-create the BD LPCM header because in the MPC-HC format its stripped off. CMediaType inMt(m_pInput->CurrentMediaType()); if (inMt.subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO && inMt.formattype == FORMAT_WaveFormatEx) { m_buff.SetSize(bufflen + 4); BYTE *buf = m_buff.Ptr() + bufflen; CreateBDLPCMHeader(buf, (WAVEFORMATEX_HDMV_LPCM *)inMt.pbFormat); bufflen = m_buff.GetCount(); } else if (inMt.subtype == MEDIASUBTYPE_DVD_LPCM_AUDIO && inMt.formattype == FORMAT_WaveFormatEx) { m_buff.SetSize(bufflen + 3); BYTE *buf = m_buff.Ptr() + bufflen; CreateDVDLPCMHeader(buf, (WAVEFORMATEX *)inMt.pbFormat); bufflen = m_buff.GetCount(); } // Ensure the size of the buffer doesn't overflow (its used as signed int in various places) if (bufflen > (INT_MAX - (DWORD)len)) { DbgLog((LOG_TRACE, 10, L"Too much audio buffered, aborting")); m_buff.Clear(); m_bQueueResync = TRUE; return E_FAIL; } m_buff.Allocate(bufflen + len + AV_INPUT_BUFFER_PADDING_SIZE); m_buff.Append(pDataIn, len); hr = ProcessBuffer(pIn); if (FAILED(hr)) return hr; return S_OK; } #define SAME_HEADER_MASK (0xffe00000 | (3 << 17) | (3 << 10) | (3 << 19)) static int check_mpegaudio_header(uint8_t *buf, uint32_t *retheader) { MPADecodeHeader sd; uint32_t header = AV_RB32(buf); if (avpriv_mpegaudio_decode_header(&sd, header) != 0) return -1; if (retheader) *retheader = header; return sd.frame_size; } HRESULT CLAVAudio::ResyncMPEGAudio() { uint8_t *buf = m_buff.Ptr(); int size = m_buff.GetCount(); for (int i = 0; i < (size - 3); i++) { uint32_t header, header2; int frame_size = check_mpegaudio_header(buf + i, &header); if (frame_size > 0 && (i + frame_size + 4) < size) { int ret = check_mpegaudio_header(buf + i + frame_size, &header2); if (ret >= 0 && (header & SAME_HEADER_MASK) == (header2 & SAME_HEADER_MASK)) { if (i > 0) { DbgLog((LOG_TRACE, 10, L"CLAVAudio::ResyncMPEGAudio(): Skipping %d bytes of junk", i)); m_buff.Consume(i); } return S_OK; } } } if (size > 64 * 1024) { DbgLog((LOG_TRACE, 10, L"CLAVAudio::ResyncMPEGAudio(): No matching headers found in 64kb of data, aborting search")); return S_OK; } return S_FALSE; } HRESULT CLAVAudio::ProcessBuffer(IMediaSample *pMediaSample, BOOL bEOF) { HRESULT hr = S_OK, hr2 = S_OK; int buffer_size = m_buff.GetCount(); BYTE *p = m_buff.Ptr(); int consumed = 0, consumed_header = 0; if (!bEOF) { if (m_bFindDTSInPCM) { int i = 0, count = 0; uint32_t state = -1; for (i = 0; i < buffer_size; ++i) { state = (state << 8) | p[i]; if ((state == DCA_MARKER_14B_LE && (i < buffer_size - 2) && (p[i + 1] & 0xF0) == 0xF0 && p[i + 2] == 0x07) || (state == DCA_MARKER_14B_BE && (i < buffer_size - 2) && p[i + 1] == 0x07 && (p[i + 2] & 0xF0) == 0xF0) || state == DCA_MARKER_RAW_LE || state == DCA_MARKER_RAW_BE) { count++; } } if (count >= 4) { DbgLog((LOG_TRACE, 10, L"::ProcessBuffer(): Detected %d DTS sync words in %d bytes of data, switching to DTS-in-WAV " L"decoding", count, buffer_size)); CMediaType mt = m_pInput->CurrentMediaType(); ffmpeg_init(AV_CODEC_ID_DTS, mt.Format(), *mt.FormatType(), mt.FormatLength()); m_bFindDTSInPCM = FALSE; } if (buffer_size > (16384 * (4 + count))) { m_bFindDTSInPCM = FALSE; } if (m_bFindDTSInPCM) { if (m_rtStartInputCache == AV_NOPTS_VALUE) m_rtStartInputCache = m_rtStartInput; return S_FALSE; } m_rtStartInput = m_rtStartInputCache; m_rtStartInputCache = AV_NOPTS_VALUE; } if (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_DOLBY_AC3_SPDIF) { if (buffer_size < BURST_HEADER_SIZE) return S_FALSE; uint16_t word1 = AV_RL16(p); uint16_t word2 = AV_RL16(p + 2); if (word1 == SYNCWORD1 && word2 == SYNCWORD2) { uint16_t type = AV_RL16(p + 4); int spdif_buffer_size = AV_RL16(p + 6) >> 3; p += BURST_HEADER_SIZE; if (spdif_buffer_size + BURST_HEADER_SIZE > buffer_size) { DbgLog((LOG_ERROR, 10, L"::ProcessBuffer(): SPDIF sample is too small (%d required, %d present)", spdif_buffer_size + BURST_HEADER_SIZE, buffer_size)); m_buff.Clear(); m_bQueueResync = TRUE; return S_FALSE; } buffer_size = spdif_buffer_size; // SPDIF is apparently big-endian coded lav_spdif_bswap_buf16((uint16_t *)p, (uint16_t *)p, buffer_size >> 1); // adjust buffer size to strip off spdif padding consumed_header = BURST_HEADER_SIZE; m_buff.SetSize(buffer_size + BURST_HEADER_SIZE); } } if (m_bMPEGAudioResync) { if (ResyncMPEGAudio() != S_OK) return S_FALSE; m_bMPEGAudioResync = FALSE; return ProcessBuffer(pMediaSample, FALSE); } } else { // In DTSinPCm mode, make sure the timestamps are correct, and process the remaining buffer if (m_bFindDTSInPCM) { m_rtStartInput = m_rtStartInputCache; m_rtStartInputCache = AV_NOPTS_VALUE; } // Otherwise, performa proper flush and stop working else { p = nullptr; buffer_size = -1; } } // If a bitstreaming context exists, we should bitstream if (m_avBSContext) { hr2 = Bitstream(p, buffer_size, consumed, &hr); if (FAILED(hr2)) { DbgLog((LOG_TRACE, 10, L"Invalid sample when bitstreaming!")); m_buff.Clear(); m_bQueueResync = TRUE; return S_FALSE; } else if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"::Bitstream indicates delivery failed")); } else if (hr2 == S_FALSE) { // DbgLog((LOG_TRACE, 10, L"::Bitstream returned S_FALSE")); hr = S_FALSE; } } else { // Decoding // Consume the buffer data hr2 = Decode(p, buffer_size, consumed, &hr, pMediaSample); // FAILED - throw away the data if (FAILED(hr2)) { DbgLog((LOG_TRACE, 10, L"Dropped invalid sample in ProcessBuffer")); m_buff.Clear(); m_bQueueResync = TRUE; return S_FALSE; } else if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"::Decode indicates delivery failed")); } else if (hr2 == S_FALSE) { // DbgLog((LOG_TRACE, 10, L"::Decode returned S_FALSE")); hr = S_FALSE; } } if (bEOF || consumed <= 0) { return hr; } // Determine actual buffer consumption consumed = consumed_header + min(consumed, buffer_size); // Remove the consumed data from the buffer m_buff.Consume(consumed); return hr; } static DWORD get_lav_channel_layout(AVChannelLayout *layout) { if (layout->order != AV_CHANNEL_ORDER_NATIVE) return 0; uint64_t mask = layout->u.mask; if (mask > DWORD_MAX) { if (mask & AV_CH_WIDE_LEFT) mask = (mask & ~AV_CH_WIDE_LEFT) | AV_CH_FRONT_LEFT_OF_CENTER; if (mask & AV_CH_WIDE_RIGHT) mask = (mask & ~AV_CH_WIDE_RIGHT) | AV_CH_FRONT_RIGHT_OF_CENTER; if (mask & AV_CH_SURROUND_DIRECT_LEFT) mask = (mask & ~AV_CH_SURROUND_DIRECT_LEFT) | AV_CH_SIDE_LEFT; if (mask & AV_CH_SURROUND_DIRECT_RIGHT) mask = (mask & ~AV_CH_SURROUND_DIRECT_RIGHT) | AV_CH_SIDE_RIGHT; } // sanity check if (av_popcount64(mask) != layout->nb_channels || mask > DWORD_MAX) return 0; return (DWORD)mask; } HRESULT CLAVAudio::Decode(const BYTE *pDataBuffer, int buffsize, int &consumed, HRESULT *hrDeliver, IMediaSample *pMediaSample) { int got_frame = 0; BYTE *tmpProcessBuf = nullptr; HRESULT hr = S_FALSE; BOOL bFlush = (pDataBuffer == nullptr); if (m_pDecodePacket == nullptr) m_pDecodePacket = av_packet_alloc(); const MediaSideDataFFMpeg *pFFSideData = nullptr; if (!bFlush && (m_raData.deint_id == MKBETAG('g', 'e', 'n', 'r') || m_raData.deint_id == MKBETAG('s', 'i', 'p', 'r'))) { int w = m_raData.audio_framesize; int h = m_raData.sub_packet_h; int sps = m_raData.sub_packet_size; int len = w * h; if (buffsize >= len) { tmpProcessBuf = (BYTE *)av_mallocz(len + AV_INPUT_BUFFER_PADDING_SIZE); // "genr" deinterleaving is used for COOK and ATRAC if (m_raData.deint_id == MKBETAG('g', 'e', 'n', 'r')) { const BYTE *srcBuf = pDataBuffer; for (int y = 0; y < h; y++) { for (int x = 0, w2 = w / sps; x < w2; x++) { memcpy(tmpProcessBuf + sps * (h * x + ((h + 1) / 2) * (y & 1) + (y >> 1)), srcBuf, sps); srcBuf += sps; } } // "sipr" deinterleaving is used for ... SIPR } else if (m_raData.deint_id == MKBETAG('s', 'i', 'p', 'r')) { memcpy(tmpProcessBuf, pDataBuffer, len); ff_rm_reorder_sipr_data(tmpProcessBuf, h, w); } pDataBuffer = tmpProcessBuf; buffsize = len; m_rtStartInput = m_rtStartInputCache; m_rtStartInputCache = AV_NOPTS_VALUE; } else { if (m_rtStartInputCache == AV_NOPTS_VALUE) m_rtStartInputCache = m_rtStartInput; return S_FALSE; } } #ifdef DEBUG else if (!bFlush && m_raData.deint_id) { const char *deint = (const char *)&m_raData.deint_id; DbgLog((LOG_TRACE, 10, L"::Decode(): Unsupported deinterleaving algorithm '%c%c%c%c'", deint[3], deint[2], deint[1], deint[0])); } #endif if (pMediaSample) { IMediaSideData *pSideData = nullptr; if (SUCCEEDED(pMediaSample->QueryInterface(&pSideData))) { size_t nFFSideDataSize = 0; if (FAILED( pSideData->GetSideData(IID_MediaSideDataFFMpeg, (const BYTE **)&pFFSideData, &nFFSideDataSize)) || nFFSideDataSize != sizeof(MediaSideDataFFMpeg)) { pFFSideData = nullptr; } SafeRelease(&pSideData); } } consumed = 0; while (buffsize > 0 || bFlush) { got_frame = 0; if (bFlush) buffsize = 0; if (m_pParser) { BYTE *pOut = nullptr; int pOut_size = 0; int used_bytes = av_parser_parse2(m_pParser, m_pAVCtx, &pOut, &pOut_size, pDataBuffer, buffsize, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (used_bytes < 0) { DbgLog((LOG_TRACE, 50, L"::Decode() - audio parsing failed (ret: %d)", -used_bytes)); goto fail; } else if (used_bytes == 0 && pOut_size == 0) { DbgLog((LOG_TRACE, 50, L"::Decode() - could not process buffer, starving?")); break; } // Timestamp cache to compensate for one frame delay the parser might introduce, in case the frames were // already perfectly sliced apart If we used more (or equal) bytes then was output again, we encountered a // new frame, update timestamps if (used_bytes >= pOut_size && m_bUpdateTimeCache) { m_rtStartInputCache = m_rtStartInput; m_rtStopInputCache = m_rtStopInput; m_rtStartInput = m_rtStopInput = AV_NOPTS_VALUE; m_bUpdateTimeCache = FALSE; } if (!bFlush && used_bytes > 0) { buffsize -= used_bytes; pDataBuffer += used_bytes; consumed += used_bytes; } if (pOut_size > 0) { m_pDecodePacket->data = pOut; m_pDecodePacket->size = pOut_size; m_pDecodePacket->dts = m_rtStartInputCache; m_pDecodePacket->pts = m_rtStartInputCache; m_pDecodePacket->time_base = m_pAVCtx->pkt_timebase; CopyMediaSideDataFF(m_pDecodePacket, &pFFSideData); int ret2 = avcodec_send_packet(m_pAVCtx, m_pDecodePacket); // decoder wants us to drain it first if (ret2 == AVERROR(EAGAIN)) { DecodeReceive(hrDeliver); ret2 = avcodec_send_packet(m_pAVCtx, m_pDecodePacket); } if (ret2 < 0) { DbgLog((LOG_TRACE, 50, L"::Decode() - decoding failed despite successful parsing")); m_bQueueResync = TRUE; av_packet_unref(m_pDecodePacket); continue; } m_rtStartInputCache = AV_NOPTS_VALUE; m_bUpdateTimeCache = TRUE; hr = DecodeReceive(hrDeliver); } else { continue; } } else if (bFlush) { hr = S_FALSE; break; } else { m_pDecodePacket->data = (uint8_t *)pDataBuffer; m_pDecodePacket->size = buffsize; m_pDecodePacket->dts = m_rtStartInput; m_pDecodePacket->pts = m_rtStartInput; m_pDecodePacket->time_base = m_pAVCtx->pkt_timebase; CopyMediaSideDataFF(m_pDecodePacket, &pFFSideData); int ret2 = avcodec_send_packet(m_pAVCtx, m_pDecodePacket); // decoder wants us to drain it first if (ret2 == AVERROR(EAGAIN)) { DecodeReceive(hrDeliver); ret2 = avcodec_send_packet(m_pAVCtx, m_pDecodePacket); } if (ret2 < 0) { av_packet_unref(m_pDecodePacket); goto fail; } if (!bFlush) { pDataBuffer += buffsize; consumed += buffsize; buffsize = 0; } m_rtStartInput = AV_NOPTS_VALUE; hr = DecodeReceive(hrDeliver); } av_packet_unref(m_pDecodePacket); } av_free(tmpProcessBuf); return hr; fail: av_free(tmpProcessBuf); return E_FAIL; } HRESULT CLAVAudio::DecodeReceive(HRESULT *hrDeliver) { BufferDetails out; while (1) { int ret = avcodec_receive_frame(m_pAVCtx, m_pFrame); if (ret == AVERROR(EAGAIN)) return S_OK; else if (ret < 0) return E_FAIL; // Send current input time to the delivery function out.rtStart = m_pFrame->pts; // Channel re-mapping and sample format conversion ASSERT(m_pFrame->nb_samples > 0); av_channel_layout_copy(&out.layout, &m_pFrame->ch_layout); out.dwSamplesPerSec = m_pAVCtx->sample_rate; if (out.layout.order == AV_CHANNEL_ORDER_UNSPEC) { DWORD dwMask = get_channel_mask(out.layout.nb_channels); if (dwMask > 0) av_channel_layout_from_mask(&out.layout, dwMask); } out.nSamples = m_pFrame->nb_samples; DWORD dwPCMSize = out.nSamples * out.layout.nb_channels * av_get_bytes_per_sample(m_pAVCtx->sample_fmt); DWORD dwPCMSizeAligned = FFALIGN(out.nSamples, 32) * out.layout.nb_channels * av_get_bytes_per_sample(m_pAVCtx->sample_fmt); if (m_pFrame->decode_error_flags & FF_DECODE_ERROR_INVALID_BITSTREAM) { if (av_channel_layout_compare(&m_DecodeLayout, &out.layout) != 0) { DbgLog((LOG_TRACE, 50, L"::Decode() - Corrupted audio frame with channel layout change, dropping.")); av_frame_unref(m_pFrame); continue; } } switch (m_pAVCtx->sample_fmt) { case AV_SAMPLE_FMT_U8: out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->Append(m_pFrame->data[0], dwPCMSize); out.sfFormat = SampleFormat_U8; break; case AV_SAMPLE_FMT_S16: out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->Append(m_pFrame->data[0], dwPCMSize); out.sfFormat = SampleFormat_16; break; case AV_SAMPLE_FMT_S32: out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->Append(m_pFrame->data[0], dwPCMSize); out.sfFormat = SampleFormat_32; out.wBitsPerSample = m_pAVCtx->bits_per_raw_sample; break; case AV_SAMPLE_FMT_FLT: out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->Append(m_pFrame->data[0], dwPCMSize); out.sfFormat = SampleFormat_FP32; break; case AV_SAMPLE_FMT_DBL: { out.bBuffer->Allocate(dwPCMSizeAligned / 2); out.bBuffer->SetSize(dwPCMSize / 2); float *pDataOut = (float *)(out.bBuffer->Ptr()); for (size_t i = 0; i < out.nSamples; ++i) { for (int ch = 0; ch < out.layout.nb_channels; ++ch) { *pDataOut = (float)((double *)m_pFrame->data[0])[ch + i * m_pAVCtx->ch_layout.nb_channels]; pDataOut++; } } } out.sfFormat = SampleFormat_FP32; break; // Planar Formats case AV_SAMPLE_FMT_U8P: { out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->SetSize(dwPCMSize); uint8_t *pOut = (uint8_t *)(out.bBuffer->Ptr()); for (size_t i = 0; i < out.nSamples; ++i) { for (int ch = 0; ch < out.layout.nb_channels; ++ch) { *pOut++ = ((uint8_t *)m_pFrame->extended_data[ch])[i]; } } } out.sfFormat = SampleFormat_U8; break; case AV_SAMPLE_FMT_S16P: { out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->SetSize(dwPCMSize); int16_t *pOut = (int16_t *)(out.bBuffer->Ptr()); for (size_t i = 0; i < out.nSamples; ++i) { for (int ch = 0; ch < out.layout.nb_channels; ++ch) { *pOut++ = ((int16_t *)m_pFrame->extended_data[ch])[i]; } } } out.sfFormat = SampleFormat_16; break; case AV_SAMPLE_FMT_S32P: { out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->SetSize(dwPCMSize); int32_t *pOut = (int32_t *)(out.bBuffer->Ptr()); for (size_t i = 0; i < out.nSamples; ++i) { for (int ch = 0; ch < out.layout.nb_channels; ++ch) { *pOut++ = ((int32_t *)m_pFrame->extended_data[ch])[i]; } } } out.sfFormat = SampleFormat_32; out.wBitsPerSample = m_pAVCtx->bits_per_raw_sample; break; case AV_SAMPLE_FMT_FLTP: { out.bBuffer->Allocate(dwPCMSizeAligned); out.bBuffer->SetSize(dwPCMSize); float *pOut = (float *)(out.bBuffer->Ptr()); for (size_t i = 0; i < out.nSamples; ++i) { for (int ch = 0; ch < out.layout.nb_channels; ++ch) { *pOut++ = ((float *)m_pFrame->extended_data[ch])[i]; } } } out.sfFormat = SampleFormat_FP32; break; case AV_SAMPLE_FMT_DBLP: { out.bBuffer->Allocate(dwPCMSizeAligned / 2); out.bBuffer->SetSize(dwPCMSize / 2); float *pOut = (float *)(out.bBuffer->Ptr()); for (size_t i = 0; i < out.nSamples; ++i) { for (int ch = 0; ch < out.layout.nb_channels; ++ch) { *pOut++ = (float)((double *)m_pFrame->extended_data[ch])[i]; } } } out.sfFormat = SampleFormat_FP32; break; default: assert(FALSE); break; } av_frame_unref(m_pFrame); m_DecodeFormat = out.sfFormat == SampleFormat_32 && out.wBitsPerSample > 0 && out.wBitsPerSample <= 24 ? (out.wBitsPerSample <= 16 ? SampleFormat_16 : SampleFormat_24) : out.sfFormat; av_channel_layout_copy(&m_DecodeLayout, &out.layout); if (SUCCEEDED(PostProcess(&out))) { *hrDeliver = QueueOutput(out); if (FAILED(*hrDeliver)) { return S_FALSE; } } } return S_OK; } HRESULT CLAVAudio::GetDeliveryBuffer(IMediaSample **pSample, BYTE **pData) { HRESULT hr; *pData = nullptr; if (FAILED(hr = m_pOutput->GetDeliveryBuffer(pSample, nullptr, nullptr, 0)) || FAILED(hr = (*pSample)->GetPointer(pData))) { return hr; } AM_MEDIA_TYPE *pmt = nullptr; if (SUCCEEDED((*pSample)->GetMediaType(&pmt)) && pmt) { CMediaType mt = *pmt; m_pOutput->SetMediaType(&mt); DeleteMediaType(pmt); pmt = nullptr; } return S_OK; } HRESULT CLAVAudio::QueueOutput(BufferDetails &buffer) { HRESULT hr = S_OK; if (av_channel_layout_compare(&m_OutputQueue.layout, &buffer.layout) != 0 || m_OutputQueue.sfFormat != buffer.sfFormat || m_OutputQueue.dwSamplesPerSec != buffer.dwSamplesPerSec || m_OutputQueue.wBitsPerSample != buffer.wBitsPerSample) { if (m_OutputQueue.nSamples > 0) FlushOutput(); m_OutputQueue.sfFormat = buffer.sfFormat; av_channel_layout_copy(&m_OutputQueue.layout, &buffer.layout); m_OutputQueue.dwSamplesPerSec = buffer.dwSamplesPerSec; m_OutputQueue.wBitsPerSample = buffer.wBitsPerSample; } if (m_OutputQueue.nSamples == 0) m_OutputQueue.rtStart = buffer.rtStart; else if (m_OutputQueue.rtStart == AV_NOPTS_VALUE && buffer.rtStart != AV_NOPTS_VALUE) m_OutputQueue.rtStart = buffer.rtStart - (REFERENCE_TIME)((double)m_OutputQueue.nSamples / m_OutputQueue.dwSamplesPerSec * 10000000.0); // Try to retain the buffer, if possible if (m_OutputQueue.nSamples == 0) { FFSWAP(GrowableArray *, m_OutputQueue.bBuffer, buffer.bBuffer); } else { m_OutputQueue.bBuffer->Append(buffer.bBuffer); } m_OutputQueue.nSamples += buffer.nSamples; buffer.bBuffer->SetSize(0); buffer.nSamples = 0; // Length of the current sample double dDuration = (double)m_OutputQueue.nSamples / m_OutputQueue.dwSamplesPerSec * 10000000.0; double dOffset = fmod(dDuration, 1.0); // Don't exceed the buffer if (dDuration >= PCM_BUFFER_MAX_DURATION || (dDuration >= PCM_BUFFER_MIN_DURATION && dOffset <= FLT_EPSILON)) { hr = FlushOutput(); } return hr; } HRESULT CLAVAudio::FlushOutput(BOOL bDeliver) { CAutoLock cAutoLock(&m_csReceive); HRESULT hr = S_OK; if (bDeliver && m_OutputQueue.nSamples > 0) hr = Deliver(m_OutputQueue); // Clear Queue m_OutputQueue.nSamples = 0; m_OutputQueue.bBuffer->SetSize(0); m_OutputQueue.rtStart = AV_NOPTS_VALUE; return hr; } HRESULT CLAVAudio::Deliver(BufferDetails &buffer) { HRESULT hr = S_OK; if (m_bFlushing) return S_FALSE; CMediaType mt = CreateMediaType(buffer.sfFormat, buffer.dwSamplesPerSec, buffer.layout.nb_channels, (DWORD)buffer.layout.u.mask, buffer.wBitsPerSample); WAVEFORMATEX *wfe = (WAVEFORMATEX *)mt.Format(); long cbBuffer = buffer.nSamples * wfe->nBlockAlign; if (FAILED(hr = ReconnectOutput(cbBuffer, mt))) { return hr; } IMediaSample *pOut; BYTE *pDataOut = nullptr; if (FAILED(GetDeliveryBuffer(&pOut, &pDataOut))) { return E_FAIL; } if (m_bResyncTimestamp && buffer.rtStart != AV_NOPTS_VALUE) { m_rtStart = buffer.rtStart; m_bResyncTimestamp = FALSE; } // Length of the current sample double dDuration = (double)buffer.nSamples / buffer.dwSamplesPerSec * DBL_SECOND_MULT / m_dRate; m_dStartOffset += fmod(dDuration, 1.0); // Delivery Timestamps REFERENCE_TIME rtStart = m_rtStart, rtStop = m_rtStart + (REFERENCE_TIME)(dDuration + 0.5); // Compute next start time m_rtStart += (REFERENCE_TIME)dDuration; // If the offset reaches one (100ns), add it to the next frame if (m_dStartOffset > 0.5) { m_rtStart++; m_dStartOffset -= 1.0; } if (buffer.rtStart != AV_NOPTS_VALUE) { REFERENCE_TIME rtJitter = rtStart - buffer.rtStart; m_faJitter.Sample(rtJitter); REFERENCE_TIME rtJitterMin = m_faJitter.AbsMinimum(); if (m_settings.AutoAVSync && abs(rtJitterMin) > m_JitterLimit) { DbgLog((LOG_TRACE, 10, L"::Deliver(): corrected A/V sync by %I64d", rtJitterMin)); m_rtStart -= rtJitterMin; rtStart -= rtJitterMin; rtStop -= rtJitterMin; m_faJitter.OffsetValues(-rtJitterMin); m_bDiscontinuity = TRUE; } #ifdef DEBUG if (m_faJitter.CurrentSample() == 0) { DbgLog((LOG_CUSTOM2, 20, L"Jitter Stats: min: %I64d - max: %I64d - avg: %I64d", rtJitterMin, m_faJitter.AbsMaximum(), m_faJitter.Average())); } #endif DbgLog((LOG_CUSTOM5, 20, L"PCM Delivery, rtStart(calc): %I64d, rtStart(input): %I64d, sample duration: %I64d, diff: %I64d", rtStart, buffer.rtStart, rtStop - rtStart, rtJitter)); } else { DbgLog((LOG_CUSTOM5, 20, L"PCM Delivery, rtStart(calc): %I64d, rtStart(input): N/A, sample duration: %I64d, diff: N/A", rtStart, rtStop - rtStart)); } if (rtStart < 0) { goto done; } if (hr == S_OK) { retry_qa: hr = m_pOutput->GetConnected()->QueryAccept(&mt); DbgLog((LOG_TRACE, 1, L"Sending new Media Type (QueryAccept: %0#.8x)", hr)); if (hr != S_OK) { if (buffer.sfFormat != SampleFormat_16) { mt = CreateMediaType(SampleFormat_16, buffer.dwSamplesPerSec, buffer.layout.nb_channels, (DWORD)buffer.layout.u.mask, 16); hr = m_pOutput->GetConnected()->QueryAccept(&mt); if (hr == S_OK) { DbgLog((LOG_TRACE, 1, L"-> 16-bit fallback type accepted")); m_FallbackFormat = SampleFormat_16; PerformAVRProcessing(&buffer); } } // Try 5.1 back fallback format if (buffer.layout.u.mask == AV_CH_LAYOUT_5POINT1) { DbgLog((LOG_TRACE, 1, L"-> Trying to fallback to 5.1 back")); buffer.layout.u.mask = AV_CH_LAYOUT_5POINT1_BACK; mt = CreateMediaType(buffer.sfFormat, buffer.dwSamplesPerSec, buffer.layout.nb_channels, (DWORD)buffer.layout.u.mask, buffer.wBitsPerSample); goto retry_qa; } // more then 8 channel, try 7.1 fallback format if (buffer.layout.nb_channels > 8) { DbgLog((LOG_TRACE, 1, L"-> Trying to fallback to 7.1 (have more then 8 channel)")); mt = CreateMediaType(buffer.sfFormat, buffer.dwSamplesPerSec, 8, (DWORD)AV_CH_LAYOUT_7POINT1, buffer.wBitsPerSample); hr = m_pOutput->GetConnected()->QueryAccept(&mt); if (hr != S_OK) { mt = CreateMediaType(SampleFormat_16, buffer.dwSamplesPerSec, 8, AV_CH_LAYOUT_7POINT1, 16); hr = m_pOutput->GetConnected()->QueryAccept(&mt); if (hr == S_OK) m_FallbackFormat = SampleFormat_16; } if (hr == S_OK) { DbgLog((LOG_TRACE, 1, L"-> Override Mixing to layout to 7.1")); av_channel_layout_uninit(&m_chOverrideMixer); av_channel_layout_from_mask(&m_chOverrideMixer, AV_CH_LAYOUT_7POINT1); m_bMixingSettingsChanged = TRUE; // Mix to the new layout PerformAVRProcessing(&buffer); } } // If a 16-bit fallback isn't enough, try to retain current channel layout as well if (hr != S_OK) { WAVEFORMATEX *wfeCurrent = (WAVEFORMATEX *)m_pOutput->CurrentMediaType().Format(); WORD wChannels = wfeCurrent->nChannels; DWORD dwChannelMask = 0; if (wfeCurrent->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)wfeCurrent; dwChannelMask = wfex->dwChannelMask; } else { dwChannelMask = get_channel_mask(wChannels); } if (buffer.layout.nb_channels != wfeCurrent->nChannels || buffer.layout.u.mask != dwChannelMask) { mt = CreateMediaType(buffer.sfFormat, buffer.dwSamplesPerSec, wChannels, dwChannelMask, buffer.wBitsPerSample); hr = m_pOutput->GetConnected()->QueryAccept(&mt); if (hr != S_OK) { mt = CreateMediaType(SampleFormat_16, buffer.dwSamplesPerSec, wChannels, dwChannelMask, 16); hr = m_pOutput->GetConnected()->QueryAccept(&mt); if (hr == S_OK) m_FallbackFormat = SampleFormat_16; } if (hr == S_OK) { DbgLog((LOG_TRACE, 1, L"-> Override Mixing to layout 0x%x", dwChannelMask)); av_channel_layout_uninit(&m_chOverrideMixer); av_channel_layout_from_mask(&m_chOverrideMixer, dwChannelMask); m_bMixingSettingsChanged = TRUE; // Mix to the new layout PerformAVRProcessing(&buffer); } } } } m_pOutput->SetMediaType(&mt); pOut->SetMediaType(&mt); } if (m_settings.AudioDelayEnabled) { REFERENCE_TIME rtDelay = (REFERENCE_TIME)((m_settings.AudioDelay * 10000i64) / m_dRate); rtStart += rtDelay; rtStop += rtDelay; } pOut->SetTime(&rtStart, &rtStop); pOut->SetMediaTime(nullptr, nullptr); pOut->SetPreroll(FALSE); pOut->SetDiscontinuity(m_bDiscontinuity); m_bDiscontinuity = FALSE; pOut->SetSyncPoint(TRUE); pOut->SetActualDataLength(buffer.bBuffer->GetCount()); memcpy(pDataOut, buffer.bBuffer->Ptr(), buffer.bBuffer->GetCount()); hr = m_pOutput->Deliver(pOut); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"::Deliver failed with code: %0#.8x", hr)); } done: SafeRelease(&pOut); return hr; } HRESULT CLAVAudio::BreakConnect(PIN_DIRECTION dir) { if (dir == PINDIR_INPUT) { ffmpeg_shutdown(); } return __super::BreakConnect(dir); } ================================================ FILE: decoder/LAVAudio/LAVAudio.def ================================================ ; LAVAudio.def ; declares the exports LIBRARY "LAVAudio.ax" EXPORTS DllGetClassObject PRIVATE DllCanUnloadNow PRIVATE DllRegisterServer PRIVATE DllUnregisterServer PRIVATE OpenConfiguration PRIVATE ================================================ FILE: decoder/LAVAudio/LAVAudio.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "LAVAudioSettings.h" #include "FloatingAverage.h" #include "Media.h" #include "BitstreamParser.h" #include "PostProcessor.h" #include "ISpecifyPropertyPages2.h" #include "BaseTrayIcon.h" //////////////////// Configuration ////////////////////////// // Buffer Size for decoded PCM: 1s of 192kHz 32-bit with 8 channels // 192000 (Samples) * 4 (Bytes per Sample) * 8 (channels) #define LAV_AUDIO_BUFFER_SIZE 6144000 // Maximum Durations (in reference time) // 10ms (DTS has 10.6667 ms samples, don't want to queue them up) #define PCM_BUFFER_MAX_DURATION 100000 // 6ms #define PCM_BUFFER_MIN_DURATION 60000 // Maximum desync that we attribute to jitter before re-syncing (10ms) #define MAX_JITTER_DESYNC 100000i64 #define MAX_VOLUME_STAT_CHANNEL 8 //////////////////// End Configuration ////////////////////// #define AV_CODEC_ID_PCM_SxxBE (AVCodecID)0x19001 #define AV_CODEC_ID_PCM_SxxLE (AVCodecID)0x19002 #define AV_CODEC_ID_PCM_UxxBE (AVCodecID)0x19003 #define AV_CODEC_ID_PCM_UxxLE (AVCodecID)0x19004 #define AV_CODEC_ID_PCM_QTRAW (AVCodecID)0x19005 #define LAVC_AUDIO_REGISTRY_KEY L"Software\\LAV\\Audio" #define LAVC_AUDIO_REGISTRY_KEY_FORMATS L"Software\\LAV\\Audio\\Formats" #define LAVC_AUDIO_LOG_FILE L"LAVAudio.txt" struct WAVEFORMATEX_HDMV_LPCM; struct BufferDetails { GrowableArray *bBuffer = nullptr; // PCM Buffer LAVAudioSampleFormat sfFormat = SampleFormat_16; // Sample Format WORD wBitsPerSample = 0; // Bits per sample DWORD dwSamplesPerSec = 0; // Samples per second unsigned nSamples = 0; // Samples in the buffer (every sample is sizeof(sfFormat) * nChannels in the buffer) AVChannelLayout layout{}; REFERENCE_TIME rtStart = AV_NOPTS_VALUE; // Start Time of the buffer BOOL bPlanar = FALSE; // Planar (not used) BufferDetails() { bBuffer = new GrowableArray(); }; ~BufferDetails() { delete bBuffer; av_channel_layout_uninit(&layout); } }; class __declspec(uuid("E8E73B6B-4CB3-44A4-BE99-4F7BCB96E491")) CLAVAudio : public CTransformFilter , public ISpecifyPropertyPages2 , public ILAVAudioSettings , public ILAVAudioStatus { public: CLAVAudio(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVAudio(); // IUnknown DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // ISpecifyPropertyPages2 STDMETHODIMP GetPages(CAUUID *pPages); STDMETHODIMP CreatePage(const GUID &guid, IPropertyPage **ppPage); // ILAVAudioSettings STDMETHODIMP SetRuntimeConfig(BOOL bRuntimeConfig); STDMETHODIMP GetDRC(BOOL *pbDRCEnabled, int *piDRCLevel); STDMETHODIMP SetDRC(BOOL bDRCEnabled, int iDRCLevel); STDMETHODIMP_(BOOL) GetFormatConfiguration(LAVAudioCodec aCodec); STDMETHODIMP SetFormatConfiguration(LAVAudioCodec aCodec, BOOL bEnabled); STDMETHODIMP_(BOOL) GetBitstreamConfig(LAVBitstreamCodec bsCodec); STDMETHODIMP SetBitstreamConfig(LAVBitstreamCodec bsCodec, BOOL bEnabled); STDMETHODIMP_(BOOL) GetDTSHDFraming(); STDMETHODIMP SetDTSHDFraming(BOOL bHDFraming); STDMETHODIMP_(BOOL) GetBitstreamingFallback(); STDMETHODIMP SetBitstreamingFallback(BOOL bBitstreamingFallback); STDMETHODIMP_(BOOL) GetAutoAVSync(); STDMETHODIMP SetAutoAVSync(BOOL bAutoSync); STDMETHODIMP_(BOOL) GetOutputStandardLayout(); STDMETHODIMP SetOutputStandardLayout(BOOL bStdLayout); STDMETHODIMP_(BOOL) GetExpandMono(); STDMETHODIMP SetExpandMono(BOOL bExpandMono); STDMETHODIMP_(BOOL) GetExpand61(); STDMETHODIMP SetExpand61(BOOL bExpand61); STDMETHODIMP_(BOOL) GetAllowRawSPDIFInput(); STDMETHODIMP SetAllowRawSPDIFInput(BOOL bAllow); STDMETHODIMP_(BOOL) GetSampleFormat(LAVAudioSampleFormat format); STDMETHODIMP SetSampleFormat(LAVAudioSampleFormat format, BOOL bEnabled); STDMETHODIMP GetAudioDelay(BOOL *pbEnabled, int *pDelay); STDMETHODIMP SetAudioDelay(BOOL bEnabled, int delay); STDMETHODIMP SetMixingEnabled(BOOL bEnabled); STDMETHODIMP_(BOOL) GetMixingEnabled(); STDMETHODIMP SetMixingLayout(DWORD dwLayout); STDMETHODIMP_(DWORD) GetMixingLayout(); STDMETHODIMP SetMixingFlags(DWORD dwFlags); STDMETHODIMP_(DWORD) GetMixingFlags(); STDMETHODIMP SetMixingMode(LAVAudioMixingMode mixingMode); STDMETHODIMP_(LAVAudioMixingMode) GetMixingMode(); STDMETHODIMP SetMixingLevels(DWORD dwCenterLevel, DWORD dwSurroundLevel, DWORD dwLFELevel); STDMETHODIMP GetMixingLevels(DWORD *dwCenterLevel, DWORD *dwSurroundLevel, DWORD *dwLFELevel); STDMETHODIMP SetTrayIcon(BOOL bEnabled); STDMETHODIMP_(BOOL) GetTrayIcon(); STDMETHODIMP SetSampleConvertDithering(BOOL bEnabled); STDMETHODIMP_(BOOL) GetSampleConvertDithering(); STDMETHODIMP SetSuppressFormatChanges(BOOL bEnabled); STDMETHODIMP_(BOOL) GetSuppressFormatChanges(); STDMETHODIMP SetOutput51LegacyLayout(BOOL b51Legacy); STDMETHODIMP_(BOOL) GetOutput51LegacyLayout(); // ILAVAudioStatus STDMETHODIMP_(BOOL) IsSampleFormatSupported(LAVAudioSampleFormat sfCheck); STDMETHODIMP GetDecodeDetails(const char **pCodec, const char **pDecodeFormat, int *pnChannels, int *pSampleRate, DWORD *pChannelMask); STDMETHODIMP GetOutputDetails(const char **pOutputFormat, int *pnChannels, int *pSampleRate, DWORD *pChannelMask); STDMETHODIMP EnableVolumeStats(); STDMETHODIMP DisableVolumeStats(); STDMETHODIMP GetChannelVolumeAverage(WORD nChannel, float *pfDb); // CTransformFilter HRESULT CheckInputType(const CMediaType *mtIn); HRESULT CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut); HRESULT DecideBufferSize(IMemAllocator *pAllocator, ALLOCATOR_PROPERTIES *pprop); HRESULT GetMediaType(int iPosition, CMediaType *pMediaType); HRESULT Receive(IMediaSample *pIn); STDMETHODIMP JoinFilterGraph(IFilterGraph *pGraph, LPCWSTR pName); // Optional Overrides HRESULT CheckConnect(PIN_DIRECTION dir, IPin *pPin); HRESULT CompleteConnect(PIN_DIRECTION dir, IPin *pReceivePin); HRESULT SetMediaType(PIN_DIRECTION dir, const CMediaType *pmt); HRESULT EndOfStream(); HRESULT BeginFlush(); HRESULT EndFlush(); HRESULT NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); HRESULT BreakConnect(PIN_DIRECTION Dir); public: // Pin Configuration const static AMOVIESETUP_MEDIATYPE sudPinTypesIn[]; const static UINT sudPinTypesInCount; const static AMOVIESETUP_MEDIATYPE sudPinTypesOut[]; const static UINT sudPinTypesOutCount; private: enum DTSBitstreamMode { DTS_Core, DTS_HDMA, DTS_HDHR }; HRESULT LoadDefaults(); HRESULT ReadSettings(HKEY rootKey); HRESULT LoadSettings(); HRESULT SaveSettings(); STDMETHODIMP CreateTrayIcon(); HRESULT ffmpeg_init(AVCodecID codec, const void *format, GUID format_type, DWORD formatlen); void ffmpeg_shutdown(); CMediaType CreateMediaType(LAVAudioSampleFormat outputFormat, DWORD nSamplesPerSec, WORD nChannels, DWORD dwChannelMask, WORD wBitsPerSample = 0) const; HRESULT ReconnectOutput(long cbBuffer, CMediaType &mt); HRESULT ProcessBuffer(IMediaSample *pMediaSample, BOOL bEOF = FALSE); HRESULT Decode(const BYTE *p, int buffsize, int &consumed, HRESULT *hrDeliver, IMediaSample *pMediaSample); HRESULT DecodeReceive(HRESULT *hrDeliver); HRESULT PostProcess(BufferDetails *buffer); HRESULT GetDeliveryBuffer(IMediaSample **pSample, BYTE **pData); HRESULT QueueOutput(BufferDetails &buffer); HRESULT FlushOutput(BOOL bDeliver = TRUE); HRESULT FlushDecoder(); HRESULT PerformFlush(); HRESULT Deliver(BufferDetails &buffer); void CreateBDLPCMHeader(BYTE *pBuf, const WAVEFORMATEX_HDMV_LPCM *wfex_lpcm) const; void CreateDVDLPCMHeader(BYTE *pBuf, const WAVEFORMATEX *wfex) const; HRESULT ParseRealAudioHeader(const BYTE *extra, const size_t extralen); HRESULT ResyncMPEGAudio(); void UpdateVolumeStats(const BufferDetails &buffer); BOOL IsBitstreaming(AVCodecID codec); HRESULT InitBitstreaming(); HRESULT ShutdownBitstreaming(); static int BSWriteBuffer(void *opaque, const uint8_t *buf, int buf_size); HRESULT CreateBitstreamContext(AVCodecID codec, WAVEFORMATEX *wfe); HRESULT UpdateBitstreamContext(); HRESULT FreeBitstreamContext(); HRESULT BitstreamFallbackToPCM(); HRESULT Bitstream(const BYTE *p, int buffsize, int &consumed, HRESULT *hrDeliver); HRESULT DeliverBitstream(AVCodecID codec, const BYTE *buffer, DWORD dwSize, REFERENCE_TIME rtStartInput, REFERENCE_TIME rtStopInput, BOOL bSwap = false, int nSamplesOffset = 0); HRESULT BitstreamTrueHD(const BYTE *p, int buffsize, HRESULT *hrDeliver); void MATWriteHeader(); void MATWritePadding(); void MATAppendData(const BYTE * const p, int size); int MATFillDataBuffer(const BYTE * const p, int size, bool padding = false); void MATFlushPacket(HRESULT *hrDeliver); CMediaType CreateBitstreamMediaType(AVCodecID codec, DWORD dwSampleRate, BOOL bDTSHDOverride = FALSE); void ActivateDTSHDMuxing(); DTSBitstreamMode GetDTSHDBitstreamMode(); HRESULT CheckChannelLayoutConformity(AVChannelLayout *layout); HRESULT Create51Conformity(DWORD dwLayout); HRESULT Create61Conformity(DWORD dwLayout); HRESULT Create71Conformity(DWORD dwLayout); LAVAudioSampleFormat GetBestAvailableSampleFormat(LAVAudioSampleFormat inFormat, int *bits = NULL, BOOL bNoFallback = FALSE); HRESULT Truncate32Buffer(BufferDetails *buffer); HRESULT PadTo32(BufferDetails *buffer); HRESULT PerformAVRProcessing(BufferDetails *buffer); private: AVCodecID m_nCodecId = AV_CODEC_ID_NONE; const AVCodec *m_pAVCodec = nullptr; AVCodecContext *m_pAVCtx = nullptr; AVCodecParserContext *m_pParser = nullptr; AVFrame *m_pFrame = nullptr; BOOL m_bFlushing = FALSE; BOOL m_bDiscontinuity = FALSE; REFERENCE_TIME m_rtStart = 0; double m_dStartOffset = 0.0; double m_dRate = 1.0; REFERENCE_TIME m_rtStartInput = AV_NOPTS_VALUE; // rtStart of the current input package REFERENCE_TIME m_rtStopInput = AV_NOPTS_VALUE; // rtStop of the current input package REFERENCE_TIME m_rtStartInputCache = AV_NOPTS_VALUE; // rtStart of the last input package REFERENCE_TIME m_rtStopInputCache = AV_NOPTS_VALUE; // rtStop of the last input package REFERENCE_TIME m_rtBitstreamCache = AV_NOPTS_VALUE; // Bitstreaming time cache BOOL m_bUpdateTimeCache = TRUE; GrowableArray m_buff; // Input Buffer LAVAudioSampleFormat m_DecodeFormat = SampleFormat_16; LAVAudioSampleFormat m_MixingInputFormat = SampleFormat_None; LAVAudioSampleFormat m_FallbackFormat = SampleFormat_None; AVChannelLayout m_chOverrideMixer{}; SwrContext *m_swrContext = nullptr; LAVAudioSampleFormat m_sfRemixFormat = SampleFormat_None; AVChannelLayout m_chRemixLayout{}; BOOL m_bAVResampleFailed = FALSE; BOOL m_bMixingSettingsChanged = FALSE; // Settings struct AudioSettings { BOOL TrayIcon; BOOL DRCEnabled; int DRCLevel; BOOL bFormats[Codec_AudioNB]; BOOL bBitstream[Bitstream_NB]; BOOL DTSHDFraming; BOOL bBitstreamingFallback; BOOL AutoAVSync; BOOL ExpandMono; BOOL Expand61; BOOL OutputStandardLayout; BOOL Output51Legacy; BOOL AllowRawSPDIF; BOOL bSampleFormats[SampleFormat_NB]; BOOL SampleConvertDither; BOOL AudioDelayEnabled; int AudioDelay; BOOL MixingEnabled; DWORD MixingLayout; DWORD MixingFlags; DWORD MixingMode; DWORD MixingCenterLevel; DWORD MixingSurroundLevel; DWORD MixingLFELevel; BOOL SuppressFormatChanges; } m_settings; BOOL m_bRuntimeConfig = FALSE; BOOL m_bVolumeStats = FALSE; // Volume Stats gathering enabled FloatingAverage m_faVolume[MAX_VOLUME_STAT_CHANNEL]; // Floating Average for volume (8 channels) BOOL m_bQueueResync = FALSE; BOOL m_bResyncTimestamp = FALSE; BOOL m_bNeedSyncpoint = FALSE; BOOL m_bJustFlushed = TRUE; BufferDetails m_OutputQueue; AVIOContext *m_avioBitstream = nullptr; AVFormatContext *m_avBSContext = nullptr; GrowableArray m_bsOutput; BOOL m_bBitStreamingSettingsChanged = FALSE; BOOL m_bBitstreamOverride[Bitstream_NB] = {FALSE}; DTSBitstreamMode m_DTSBitstreamMode = DTS_Core; BOOL m_bForceDTSCore = FALSE; CBitstreamParser m_bsParser; BOOL m_bFindDTSInPCM = FALSE; BOOL m_bDVDPlayback = FALSE; BOOL m_bMPEGAudioResync = FALSE; FloatingAverage m_faJitter{50}; REFERENCE_TIME m_JitterLimit = MAX_JITTER_DESYNC; AVChannelLayout m_DecodeLayout{}; AVChannelLayout m_DecodeLayoutSanified{}; AVChannelLayout m_MixingInputLayout{}; BOOL m_bChannelMappingRequired = FALSE; AVChannelLayout m_SuppressLayout{}; ExtendedChannelMap m_ChannelMap; AVChannelLayout m_ChannelMapOutputLayout{}; AVPacket *m_pDecodePacket = nullptr; AVPacket *m_pBitstreamPacket = nullptr; // TrueHD Bitstreaming struct { bool init = false; int ratebits = 0; uint16_t output_timing = 0; BOOL output_timing_valid = FALSE; uint16_t prev_frametime = 0; BOOL prev_frametime_valid = FALSE; uint32_t mat_framesize = 0; uint32_t prev_mat_framesize = 0; DWORD padding = 0; DWORD nSamples = 0; int nSamplesOffset = 0; int nOutputTimeOffset = 0; } m_TrueHDMATState; struct { int flavor; int coded_frame_size; int audio_framesize; int sub_packet_h; int sub_packet_size; unsigned int deint_id; } m_raData; CBaseTrayIcon *m_pTrayIcon = nullptr; }; ================================================ FILE: decoder/LAVAudio/LAVAudio.manifest ================================================ ================================================ FILE: decoder/LAVAudio/LAVAudio.rc ================================================ // Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_ICON1 ICON "..\\..\\resources\\blue.ico" #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""winres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" "LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\r\n" "#pragma code_page(1252)\r\n" "#include ""LAVAudio.rc2"" // non-Microsoft Visual C++ edited resources\r\n" "#endif\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_PROPPAGE_AUDIO_SETTINGS DIALOGEX 0, 0, 369, 234 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN GROUPBOX "Dynamic Range Compression",IDC_DRC_BOX,7,7,196,40 CONTROL "Apply DRC on formats that support it (AC3, EAC3)",IDC_DRC, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,17,177,10 CONTROL "",IDC_DRC_LEVEL,"msctls_trackbar32",TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,50,30,100,12 LTEXT "Level: ",IDC_LBL_DRC_LEVEL,15,30,28,8 LTEXT "100%",IDC_DRC_LEVEL_TEXT,150,30,20,8,0,WS_EX_RIGHT GROUPBOX "Bitstreaming (S/PDIF, HDMI)",IDC_BITSTREAMING,7,50,196,98 LTEXT "Formats",IDC_BS_FORMATS,12,60,122,8 CONTROL "Dolby Digital (AC-3)",IDC_BS_AC3,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,20,72,79,10 CONTROL "Dolby Digital Plus (E-AC3)",IDC_BS_EAC3,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,20,86,97,10 CONTROL "Dolby TrueHD",IDC_BS_TRUEHD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,20,100,60,10 CONTROL "DTS",IDC_BS_DTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,130,72,29,10 CONTROL "DTS-HD",IDC_BS_DTSHD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,130,86,41,10 LTEXT "Options",IDC_BS_OPTIONS,12,112,26,8 CONTROL "Force max DTS-HD rate (not recommended)",IDC_BS_DTSHD_FRAMING, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,20,123,151,10 CONTROL "Fallback to PCM if Bitstreaming is not supported",IDC_BS_FALLBACK, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,20,135,161,10 GROUPBOX "Options",IDC_OPTIONS,7,149,196,65 CONTROL "Auto A/V Sync correction",IDC_AUTO_AVSYNC,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,160,96,10 CONTROL "Convert Output to Standard Channel Layouts",IDC_STANDARD_CH_LAYOUT, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,174,162,10 CONTROL "Expand Mono to Stereo",IDC_EXPAND_MONO,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,188,91,10 CONTROL "Expand 6.1 to 7.1",IDC_EXPAND61,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,118,188,74,10 CONTROL "Use Legacy 5.1 channel layout",IDC_OUTPUT51_LEGACY, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,202,162,10 LTEXT "LAV Audio Decoder x.xx",IDC_LAVAUDIO_FOOTER,209,221,149,8,0,WS_EX_RIGHT GROUPBOX "Output Formats",IDC_OUTPUT_FORMATS,207,59,151,132 LTEXT "Select which output formats are available.\nThe best format is used automatically.",IDC_LBL_OUTPUTFORMATS,213,70,140,22 CONTROL "16-bit Integer",IDC_OUT_S16,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,216,91,61,10 CONTROL "24-bit Integer",IDC_OUT_S24,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,286,91,61,10 CONTROL "32-bit Integer",IDC_OUT_S32,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,216,107,61,10 CONTROL "32-bit Floating-point",IDC_OUT_FP32,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,216,123,81,10 CONTROL "8-bit Integer",IDC_OUT_U8,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,286,107,54,10 CONTROL "Use Dithering for 16-bit Output",IDC_OUT_S16_DITHER, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,216,139,125,10 LTEXT "Enabling all formats will allow untouched / bitexact output. Only if a format is not compatible with your hard- or software it should be disabled.",IDC_LBL_OUTNOTE,213,152,140,37 GROUPBOX "Audio Delay",IDC_GROUP_DELAY,207,7,151,50 CONTROL "Enable Audio Delay",IDC_DELAY_ENABLED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,214,20,113,10 LTEXT "Delay (in ms):",IDC_STATIC,213,37,47,8 EDITTEXT IDC_DELAY,261,35,46,13,ES_AUTOHSCROLL,WS_EX_RIGHT CONTROL "",IDC_DELAYSPIN,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_HOTTRACK,305,35,11,13 CONTROL "Enable System Tray Icon", IDC_TRAYICON, "Button", BS_AUTOCHECKBOX | WS_TABSTOP, 7, 219, 192, 10 END IDD_PROPPAGE_AUDIO_MIXING DIALOGEX 0, 0, 369, 215 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN GROUPBOX "Mixer",IDC_LBL_MIXING,7,7,214,112 CONTROL "Enable Mixing",IDC_MIXING,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,14,19,59,10 LTEXT "Output Speaker Configuration:",IDC_LBL_OUTPUT_SPEAKERS,15,32,100,8 COMBOBOX IDC_OUTPUT_SPEAKERS,121,30,90,30,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP GROUPBOX "Settings",IDC_MIX_SETTINGS,225,7,133,56 CONTROL "Don't mix Stereo sources",IDC_UNTOUCHED_STEREO,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,235,19,100,10 CONTROL "Normalize Matrix",IDC_NORMALIZE_MATRIX,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,235,33,100,10 CONTROL "Clipping Protection",IDC_CLIP_PROTECTION,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,235,47,100,10 GROUPBOX "Matrix Encoding",IDC_MIXING_MODE,225,67,133,51 CONTROL "None",IDC_MIXMODE_NORMAL,"Button",BS_AUTORADIOBUTTON,235,79,116,10 CONTROL "Dolby Pro Logic",IDC_MIXMODE_DOLBY,"Button",BS_AUTORADIOBUTTON,235,91,116,10 CONTROL "Dolby Pro Logic II",IDC_MIXMODE_DPL2,"Button",BS_AUTORADIOBUTTON,235,103,116,10 LTEXT "Center Mix Level",IDC_LBL_CENTER_LEVEL,12,50,54,8 CONTROL "",IDC_MIX_LEVEL_CENTER,"msctls_trackbar32",TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,72,47,130,15 LTEXT "0.00",IDC_MIX_LEVEL_CENTER_TEXT,202,50,16,8 LTEXT "Surround Mix Level",IDC_LBL_SURROUND_LEVEL,12,65,62,8 CONTROL "",IDC_MIX_LEVEL_SURROUND,"msctls_trackbar32",TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,72,62,130,15 LTEXT "0.00",IDC_MIX_LEVEL_SURROUND_TEXT,202,65,16,8 LTEXT "LFE Mix Level",IDC_LBL_LFE_LEVEL,12,80,44,8 CONTROL "",IDC_MIX_LEVEL_LFE,"msctls_trackbar32",TBS_BOTH | TBS_NOTICKS | WS_TABSTOP,72,77,130,15 LTEXT "0.00",IDC_MIX_LEVEL_LFE_TEXT,202,80,16,8 LTEXT "The mixing levels control the volume of the individual channels when being mixed with other channels into a downmix.",IDC_LBL_MIXING_LEVEL,12,97,200,18 END IDD_PROPPAGE_FORMATS DIALOGEX 0, 0, 369, 234 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN LTEXT "Here you can select which formats LAV Audio should decode.\nBecause LAV Audio supports a wide range of (rare) formats, not all are listed here.\nIf you need to configure a specific format which is not listed, submit a ticket asking for the option.",IDC_LBL_FORMATS,8,10,333,30 CONTROL "",IDC_CODECS,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,40,351,185 END IDD_PROPPAGE_STATUS DIALOGEX 0, 0, 214, 156 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN GROUPBOX "Input",IDC_INPUT_STATUS,7,7,98,61 LTEXT "Codec:",IDC_LBL_INPUT_CODEC,12,18,44,8 LTEXT "Channel:",IDC_LBL_INPUT_CHANNEL,12,30,44,8 LTEXT "Sample Rate:",IDC_LBL_INPUT_SAMPLERATE,12,42,44,8 LTEXT "Format:",IDC_LBL_INPUT_FORMAT,12,54,44,8 LTEXT "",IDC_INPUT_CODEC,58,18,45,8 LTEXT "",IDC_INPUT_CHANNEL,58,30,45,8 LTEXT "",IDC_INPUT_SAMPLERATE,58,42,45,8 LTEXT "",IDC_INPUT_FORMAT,58,54,45,8 GROUPBOX "Output",IDC_OUTPUT_STATUS,109,7,98,61 LTEXT "Codec:",IDC_LBL_OUTPUT_CODEC,114,18,44,8 LTEXT "Channel:",IDC_LBL_OUTPUT_CHANNEL,114,30,44,8 LTEXT "Sample Rate:",IDC_LBL_OUTPUT_SAMPLERATE,114,42,44,8 LTEXT "Format:",IDC_LBL_OUTPUT_FORMAT,114,54,44,8 LTEXT "",IDC_OUTPUT_CODEC,160,18,45,8 LTEXT "",IDC_OUTPUT_CHANNEL,160,30,45,8 LTEXT "",IDC_OUTPUT_SAMPLERATE,160,42,45,8 LTEXT "",IDC_OUTPUT_FORMAT,160,54,45,8 GROUPBOX "Channel Output",IDC_VOLUME,7,71,200,77 CONTROL "",IDC_VOLUME1,"msctls_progress32",PBS_VERTICAL | WS_BORDER,14,84,12,45 CONTROL "",IDC_VOLUME2,"msctls_progress32",PBS_VERTICAL | WS_BORDER,39,84,12,45 CONTROL "",IDC_VOLUME3,"msctls_progress32",PBS_VERTICAL | WS_BORDER,64,84,12,45 CONTROL "",IDC_VOLUME4,"msctls_progress32",PBS_VERTICAL | WS_BORDER,89,84,12,45 CONTROL "",IDC_VOLUME5,"msctls_progress32",PBS_VERTICAL | WS_BORDER,114,84,12,45 CONTROL "",IDC_VOLUME6,"msctls_progress32",PBS_VERTICAL | WS_BORDER,139,84,12,45 CONTROL "",IDC_VOLUME7,"msctls_progress32",PBS_VERTICAL | WS_BORDER,164,84,12,45 CONTROL "",IDC_VOLUME8,"msctls_progress32",PBS_VERTICAL | WS_BORDER,189,84,12,45 CTEXT "L",IDC_VOLUME1_DESC,9,132,21,8 CTEXT "R",IDC_VOLUME2_DESC,34,132,21,8 CTEXT "C",IDC_VOLUME3_DESC,59,132,21,8 CTEXT "LFE",IDC_VOLUME4_DESC,84,132,21,8 CTEXT "BL",IDC_VOLUME5_DESC,109,132,21,8 CTEXT "BR",IDC_VOLUME6_DESC,134,132,21,8 CTEXT "SL",IDC_VOLUME7_DESC,159,132,21,8 CTEXT "SR",IDC_VOLUME8_DESC,184,132,21,8 END ///////////////////////////////////////////////////////////////////////////// // // DESIGNINFO // #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO BEGIN IDD_PROPPAGE_AUDIO_SETTINGS, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 358 TOPMARGIN, 7 BOTTOMMARGIN, 229 END IDD_PROPPAGE_AUDIO_MIXING, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 358 TOPMARGIN, 7 BOTTOMMARGIN, 210 END IDD_PROPPAGE_FORMATS, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 358 TOPMARGIN, 7 BOTTOMMARGIN, 210 END IDD_PROPPAGE_STATUS, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 207 TOPMARGIN, 7 BOTTOMMARGIN, 148 END END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // String Table // STRINGTABLE BEGIN IDS_SETTINGS "Audio Settings" IDS_STATUS "Status" IDS_FORMATS "Formats" IDS_MIXER "Mixing" END #endif // English (United States) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #include "LAVAudio.rc2" // non-Microsoft Visual C++ edited resources #endif ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ================================================ FILE: decoder/LAVAudio/LAVAudio.rc2 ================================================ // // LAVAudio.rc2 - resources Microsoft Visual C++ does not edit directly // #ifdef APSTUDIO_INVOKED #error This file is not editable by Microsoft Visual C++ #endif //APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // Add manually edited resources here... ///////////////////////////////////////////////////////////////////////////// #include "resource.h" #include "..\..\common\includes\version.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources ///////////////////////////////////////////////////////////////////////////// // Neutral (Sys. Default) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION LAV_VERSION_TAG PRODUCTVERSION LAV_VERSION_TAG FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", "1f0.de - Hendrik Leppkes" VALUE "FileDescription", "LAV Audio Decoder - DirectShow Audio Decoder" VALUE "FileVersion", LAV_VERSION_STR VALUE "InternalName", "LAVAudio.ax" VALUE "LegalCopyright", "Copyright (C) 2010-2021 Hendrik Leppkes" VALUE "OriginalFilename", "LAVAudio.ax" VALUE "ProductName", "LAV Audio Decoder" VALUE "ProductVersion", LAV_VERSION_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif ================================================ FILE: decoder/LAVAudio/LAVAudio.vcxproj ================================================  Debug Win32 Debug x64 Release Win32 Release x64 {12154C64-9136-4C21-92FA-665008C6FD27} Win32Proj LAVAudio DynamicLibrary true Unicode DynamicLibrary false true Unicode .ax $(SolutionDir)bin_$(PlatformName)d\ .ax $(SolutionDir)bin_$(PlatformName)\$(ProjectName)\ Build WIN32;_DEBUG;_WINDOWS;_USRDLL;LAVAUDIO_EXPORTS;%(PreprocessorDefinitions) advapi32.lib;ole32.lib;winmm.lib;user32.lib;oleaut32.lib;shell32.lib;Shlwapi.lib;Comctl32.lib;version.lib;avformat-lav.lib;avutil-lav.lib;avcodec-lav.lib;swresample-lav.lib LAVAudio.def $(ProjectDir)\$(ProjectName).manifest %(AdditionalManifestFiles) WIN32;NDEBUG;_WINDOWS;_USRDLL;LAVAUDIO_EXPORTS;%(PreprocessorDefinitions) advapi32.lib;ole32.lib;winmm.lib;user32.lib;oleaut32.lib;shell32.lib;Shlwapi.lib;Comctl32.lib;version.lib;avformat-lav.lib;avutil-lav.lib;avcodec-lav.lib;swresample-lav.lib LAVAudio.def copy "$(TargetDir)\$(TargetName)$(TargetExt)" "$(OutDir).." $(OutDir)..\$(TargetFileName) $(TargetDir)\$(TargetName)$(TargetExt) $(ProjectDir)\$(ProjectName).manifest %(AdditionalManifestFiles) NotUsing Create RC {e8a3f6fa-ae1c-4c8e-a0b6-9c8480324eaa} {0a058024-41f4-4509-97d2-803a1806ce86} ================================================ FILE: decoder/LAVAudio/LAVAudio.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {5d05f06d-934e-4454-a2e6-07c4aebe26c6} {322b942d-d30d-4738-abf1-3934ed971b11} Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files\parser Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files\parser Header Files\parser Header Files Header Files Resource Files Resource Files Resource Files Resource Files ================================================ FILE: decoder/LAVAudio/Media.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVAudio.h" #include #include #include #include "moreuuids.h" extern "C" { #include "libavutil/intreadwrite.h" }; typedef struct { const CLSID *clsMinorType; const enum AVCodecID nFFCodec; } FFMPEG_SUBTYPE_MAP; // clang-format off // Map Media Subtype <> FFMPEG Codec Id static const FFMPEG_SUBTYPE_MAP lavc_audio_codecs[] = { // AAC { &MEDIASUBTYPE_AAC, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_LATM_AAC, AV_CODEC_ID_AAC_LATM }, { &MEDIASUBTYPE_MPEG_LOAS, AV_CODEC_ID_AAC_LATM }, { &MEDIASUBTYPE_MP4A, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_mp4a, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_AAC_ADTS, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_MPEG_ADTS_AAC,AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_MPEG_RAW_AAC, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_MPEG_HEAAC, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_ALS, AV_CODEC_ID_MP4ALS }, // Dolby { &MEDIASUBTYPE_DOLBY_AC3, AV_CODEC_ID_AC3 }, { &MEDIASUBTYPE_DOLBY_DDPLUS, AV_CODEC_ID_EAC3 }, { &MEDIASUBTYPE_DOLBY_DDPLUS_ARCSOFT, AV_CODEC_ID_EAC3 }, { &MEDIASUBTYPE_DOLBY_TRUEHD, AV_CODEC_ID_TRUEHD }, { &MEDIASUBTYPE_WAVE_DOLBY_AC3, AV_CODEC_ID_AC3 }, // DTS { &MEDIASUBTYPE_DTS, AV_CODEC_ID_DTS }, { &MEDIASUBTYPE_DTS_HD, AV_CODEC_ID_DTS }, { &MEDIASUBTYPE_WAVE_DTS, AV_CODEC_ID_DTS }, // MPEG Audio { &MEDIASUBTYPE_MPEG1Packet, AV_CODEC_ID_MP1 }, { &MEDIASUBTYPE_MPEG1Payload, AV_CODEC_ID_MP1 }, { &MEDIASUBTYPE_MPEG1AudioPayload, AV_CODEC_ID_MP1 }, { &MEDIASUBTYPE_MPEG2_AUDIO, AV_CODEC_ID_MP2 }, { &MEDIASUBTYPE_MP3, AV_CODEC_ID_MP3 }, // FLAC { &MEDIASUBTYPE_FLAC, AV_CODEC_ID_FLAC }, { &MEDIASUBTYPE_FLAC_FRAMED, AV_CODEC_ID_FLAC }, // Ogg Vorbis { &MEDIASUBTYPE_Vorbis2, AV_CODEC_ID_VORBIS }, // Other Lossless formats { &MEDIASUBTYPE_TTA1, AV_CODEC_ID_TTA }, { &MEDIASUBTYPE_WAVPACK4, AV_CODEC_ID_WAVPACK }, { &MEDIASUBTYPE_MLP, AV_CODEC_ID_MLP }, { &MEDIASUBTYPE_ALAC, AV_CODEC_ID_ALAC }, { &MEDIASUBTYPE_TAK, AV_CODEC_ID_TAK }, { &MEDIASUBTYPE_AES3, AV_CODEC_ID_S302M }, // BluRay LPCM { &MEDIASUBTYPE_DVD_LPCM_AUDIO, AV_CODEC_ID_PCM_DVD }, { &MEDIASUBTYPE_BD_LPCM_AUDIO, AV_CODEC_ID_PCM_BLURAY }, { &MEDIASUBTYPE_HDMV_LPCM_AUDIO, AV_CODEC_ID_PCM_BLURAY }, // MPC-HC MPEG Splitter type with header stripped off // QT PCM { &MEDIASUBTYPE_PCM_NONE, AV_CODEC_ID_PCM_QTRAW}, { &MEDIASUBTYPE_PCM_RAW, AV_CODEC_ID_PCM_QTRAW}, { &MEDIASUBTYPE_PCM_TWOS, AV_CODEC_ID_PCM_SxxBE}, { &MEDIASUBTYPE_PCM_SOWT, AV_CODEC_ID_PCM_SxxLE}, { &MEDIASUBTYPE_PCM_IN24, AV_CODEC_ID_PCM_S24BE}, { &MEDIASUBTYPE_PCM_IN32, AV_CODEC_ID_PCM_S32BE}, { &MEDIASUBTYPE_PCM_FL32, AV_CODEC_ID_PCM_F32BE}, { &MEDIASUBTYPE_PCM_FL64, AV_CODEC_ID_PCM_F64BE}, { &MEDIASUBTYPE_PCM_IN24_le, AV_CODEC_ID_PCM_S24LE}, { &MEDIASUBTYPE_PCM_IN32_le, AV_CODEC_ID_PCM_S32LE}, { &MEDIASUBTYPE_PCM_FL32_le, AV_CODEC_ID_PCM_F32LE}, { &MEDIASUBTYPE_PCM_FL64_le, AV_CODEC_ID_PCM_F64LE}, // WMV { &MEDIASUBTYPE_MSAUDIO1, AV_CODEC_ID_WMAV1 }, { &MEDIASUBTYPE_WMAUDIO2, AV_CODEC_ID_WMAV2 }, { &MEDIASUBTYPE_WMAUDIO3, AV_CODEC_ID_WMAPRO }, { &MEDIASUBTYPE_WMAUDIO_LOSSLESS, AV_CODEC_ID_WMALOSSLESS }, // RealMedia Audio { &MEDIASUBTYPE_COOK, AV_CODEC_ID_COOK }, { &MEDIASUBTYPE_RAAC, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_RACP, AV_CODEC_ID_AAC }, { &MEDIASUBTYPE_SIPR, AV_CODEC_ID_SIPR }, { &MEDIASUBTYPE_SIPR_WAVE, AV_CODEC_ID_SIPR }, { &MEDIASUBTYPE_DNET, AV_CODEC_ID_AC3 }, { &MEDIASUBTYPE_28_8, AV_CODEC_ID_RA_288 }, { &MEDIASUBTYPE_14_4, AV_CODEC_ID_RA_144 }, { &MEDIASUBTYPE_RALF, AV_CODEC_ID_RALF }, // Misc { &MEDIASUBTYPE_SPEEX, AV_CODEC_ID_SPEEX }, { &MEDIASUBTYPE_OPUS, AV_CODEC_ID_OPUS }, { &MEDIASUBTYPE_OPUS_OLD, AV_CODEC_ID_OPUS }, { &MEDIASUBTYPE_SAMR, AV_CODEC_ID_AMR_NB }, { &MEDIASUBTYPE_NELLYMOSER, AV_CODEC_ID_NELLYMOSER }, { &MEDIASUBTYPE_ALAW, AV_CODEC_ID_PCM_ALAW }, { &MEDIASUBTYPE_MULAW, AV_CODEC_ID_PCM_MULAW }, { &MEDIASUBTYPE_MSGSM610, AV_CODEC_ID_GSM_MS }, { &MEDIASUBTYPE_ADPCM_MS, AV_CODEC_ID_ADPCM_MS }, { &MEDIASUBTYPE_TRUESPEECH, AV_CODEC_ID_TRUESPEECH }, { &MEDIASUBTYPE_QDM2, AV_CODEC_ID_QDM2 }, { &MEDIASUBTYPE_VOXWARE_RT29, AV_CODEC_ID_METASOUND }, { &MEDIASUBTYPE_ATRAC3, AV_CODEC_ID_ATRAC3 }, { &MEDIASUBTYPE_ATRC, AV_CODEC_ID_ATRAC3 }, { &MEDIASUBTYPE_ATRAC3P, AV_CODEC_ID_ATRAC3P }, { &MEDIASUBTYPE_IMA_WAV, AV_CODEC_ID_ADPCM_IMA_WAV }, { &MEDIASUBTYPE_G726, AV_CODEC_ID_ADPCM_G726 }, { &MEDIASUBTYPE_729A, AV_CODEC_ID_G729 }, { &MEDIASUBTYPE_G729, AV_CODEC_ID_G729 }, { &MEDIASUBTYPE_IMC, AV_CODEC_ID_IMC }, // Special LAVFSplitter interface { &MEDIASUBTYPE_FFMPEG_AUDIO, AV_CODEC_ID_NONE }, }; // Define Input Media Types const AMOVIESETUP_MEDIATYPE CLAVAudio::sudPinTypesIn[] = { // DVD Types { &MEDIATYPE_DVD_ENCRYPTED_PACK, &MEDIASUBTYPE_MPEG2_AUDIO }, { &MEDIATYPE_MPEG2_PACK, &MEDIASUBTYPE_MPEG2_AUDIO }, { &MEDIATYPE_MPEG2_PES, &MEDIASUBTYPE_MPEG2_AUDIO }, { &MEDIATYPE_DVD_ENCRYPTED_PACK, &MEDIASUBTYPE_DOLBY_AC3 }, { &MEDIATYPE_MPEG2_PACK, &MEDIASUBTYPE_DOLBY_AC3 }, { &MEDIATYPE_MPEG2_PES, &MEDIASUBTYPE_DOLBY_AC3 }, { &MEDIATYPE_DVD_ENCRYPTED_PACK, &MEDIASUBTYPE_DTS }, { &MEDIATYPE_MPEG2_PACK, &MEDIASUBTYPE_DTS }, { &MEDIATYPE_MPEG2_PES, &MEDIASUBTYPE_DTS }, { &MEDIATYPE_DVD_ENCRYPTED_PACK, &MEDIASUBTYPE_DVD_LPCM_AUDIO }, { &MEDIATYPE_MPEG2_PACK, &MEDIASUBTYPE_DVD_LPCM_AUDIO }, { &MEDIATYPE_MPEG2_PES, &MEDIASUBTYPE_DVD_LPCM_AUDIO }, // AAC { &MEDIATYPE_Audio, &MEDIASUBTYPE_AAC }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_LATM_AAC }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG_LOAS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MP4A }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_mp4a }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_AAC_ADTS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG_ADTS_AAC}, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG_RAW_AAC }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG_HEAAC }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_ALS }, // Dolby { &MEDIATYPE_Audio, &MEDIASUBTYPE_DOLBY_AC3 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_DOLBY_DDPLUS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_DOLBY_DDPLUS_ARCSOFT }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_DOLBY_TRUEHD }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_WAVE_DOLBY_AC3 }, // DTS { &MEDIATYPE_Audio, &MEDIASUBTYPE_DTS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_WAVE_DTS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_DTS_HD }, // MPEG Audio { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG1Packet }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG1Payload }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG1AudioPayload }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MPEG2_AUDIO }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MP3 }, // FLAC { &MEDIATYPE_Audio, &MEDIASUBTYPE_FLAC, }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_FLAC_FRAMED }, // Ogg Vorbis { &MEDIATYPE_Audio, &MEDIASUBTYPE_Vorbis2 }, // Other Lossless formats { &MEDIATYPE_Audio, &MEDIASUBTYPE_TTA1 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_WAVPACK4 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MLP }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_ALAC }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_TAK }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_AES3 }, // BluRay LPCM { &MEDIATYPE_Audio, &MEDIASUBTYPE_DVD_LPCM_AUDIO }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_BD_LPCM_AUDIO }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_HDMV_LPCM_AUDIO }, // MPC-HC MPEG Splitter type with header stripped off // QT PCM { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_NONE }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_RAW }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_TWOS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_SOWT }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_IN24 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_IN32 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_FL32 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_FL64 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_IN24_le }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_IN32_le }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_FL32_le }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM_FL64_le }, // WMV { &MEDIATYPE_Audio, &MEDIASUBTYPE_MSAUDIO1 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_WMAUDIO2 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_WMAUDIO3 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_WMAUDIO_LOSSLESS }, // RealMedia Audio { &MEDIATYPE_Audio, &MEDIASUBTYPE_COOK }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_RAAC }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_RACP }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_SIPR }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_SIPR_WAVE }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_DNET }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_28_8 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_14_4 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_RALF }, // Misc { &MEDIATYPE_Audio, &MEDIASUBTYPE_SPEEX }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_OPUS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_OPUS_OLD }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_SAMR }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_NELLYMOSER }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_ALAW }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MULAW }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_MSGSM610 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_ADPCM_MS }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_TRUESPEECH }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_QDM2, }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_VOXWARE_RT29 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_ATRAC3 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_ATRC }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_ATRAC3P }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_IMA_WAV }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_G726 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_729A }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_G729 }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_IMC }, // Special LAVFSplitter interface { &MEDIATYPE_Audio, &MEDIASUBTYPE_FFMPEG_AUDIO }, }; const UINT CLAVAudio::sudPinTypesInCount = countof(CLAVAudio::sudPinTypesIn); // Define Output Media Types const AMOVIESETUP_MEDIATYPE CLAVAudio::sudPinTypesOut[] = { { &MEDIATYPE_Audio, &MEDIASUBTYPE_PCM }, { &MEDIATYPE_Audio, &MEDIASUBTYPE_IEEE_FLOAT }, }; const UINT CLAVAudio::sudPinTypesOutCount = countof(CLAVAudio::sudPinTypesOut); // clang-format on // Crawl the lavc_audio_codecs array for the proper codec AVCodecID FindCodecId(const CMediaType *mt) { for (int i = 0; i < countof(lavc_audio_codecs); ++i) { if (mt->subtype == *lavc_audio_codecs[i].clsMinorType) { return lavc_audio_codecs[i].nFFCodec; } } return AV_CODEC_ID_NONE; } static const struct s_ffmpeg_codec_overrides { AVCodecID codec; const char *override; } ffmpeg_codec_overrides[] = { {AV_CODEC_ID_MP1, "mp1float"}, {AV_CODEC_ID_MP2, "mp2float"}, {AV_CODEC_ID_MP3, "mp3float"}, {AV_CODEC_ID_AMR_NB, "libopencore_amrnb"}, {AV_CODEC_ID_AMR_WB, "libopencore_amrwb"}, }; const char *find_codec_override(AVCodecID codec) { for (int i = 0; i < countof(ffmpeg_codec_overrides); ++i) { if (ffmpeg_codec_overrides[i].codec == codec) return ffmpeg_codec_overrides[i].override; } return nullptr; } // Default Channel to Speaker Map static const scmap_t m_scmap_default[] = { // FL FR FC LFe BL BR FLC FRC {1, KSAUDIO_SPEAKER_MONO}, // Mono M1, 0 {2, KSAUDIO_SPEAKER_STEREO}, // Stereo FL, FR {3, KSAUDIO_SPEAKER_3POINT0}, // 3/0 FL, FR, FC {4, KSAUDIO_SPEAKER_3POINT1}, // 3/1 FL, FR, FC, Surround {5, KSAUDIO_SPEAKER_5POINT0}, // 3/2 FL, FR, FC, BL, BR {6, KSAUDIO_SPEAKER_5POINT1_SURROUND}, // 3/2+LFe FL, FR, FC, SL, SR, LFe {7, KSAUDIO_SPEAKER_7POINT0}, // 3/4 FL, FR, FC, BL, Bls, Brs, BR {8, KSAUDIO_SPEAKER_7POINT1_SURROUND}, // 3/4+LFe FL, FR, FC, BL, BR, SL, SR, LFe }; DWORD get_channel_mask(int num_channels) { if (num_channels < 1 || num_channels > 8) return 0; return m_scmap_default[num_channels - 1].dwChannelMask; } static const char *sample_format_strings[] = {"16bit Integer", "24bit Integer", "32bit Integer", "8bit Integer", "32bit Float", "Bitstreaming"}; const char *get_sample_format_desc(LAVAudioSampleFormat sfFormat) { return sample_format_strings[sfFormat]; } const char *get_sample_format_desc(CMediaType &mt) { LAVAudioSampleFormat format; if (mt.subtype == MEDIASUBTYPE_IEEE_FLOAT) { format = SampleFormat_FP32; } else { WAVEFORMATEX *wfout = (WAVEFORMATEX *)mt.Format(); switch (wfout->wBitsPerSample) { case 8: format = SampleFormat_U8; break; case 16: format = SampleFormat_16; break; case 24: format = SampleFormat_24; break; case 32: format = SampleFormat_32; break; default: ASSERT(false); } } return get_sample_format_desc(format); } BYTE get_byte_per_sample(LAVAudioSampleFormat sfFormat) { switch (sfFormat) { case SampleFormat_U8: return 1; case SampleFormat_16: return 2; case SampleFormat_24: return 3; case SampleFormat_32: case SampleFormat_FP32: return 4; } return 0; } LAVAudioSampleFormat get_lav_sample_fmt(AVSampleFormat sample_fmt, int bits) { LAVAudioSampleFormat lav_sample_fmt; switch (sample_fmt) { case AV_SAMPLE_FMT_S16: case AV_SAMPLE_FMT_S16P: case AV_SAMPLE_FMT_S32: case AV_SAMPLE_FMT_S32P: if (bits > 24 || (!bits && (sample_fmt == AV_SAMPLE_FMT_S32 || sample_fmt == AV_SAMPLE_FMT_S32P))) lav_sample_fmt = SampleFormat_32; else if (bits > 16) lav_sample_fmt = SampleFormat_24; else lav_sample_fmt = SampleFormat_16; break; case AV_SAMPLE_FMT_DBL: case AV_SAMPLE_FMT_DBLP: case AV_SAMPLE_FMT_FLT: case AV_SAMPLE_FMT_FLTP: lav_sample_fmt = SampleFormat_FP32; break; case AV_SAMPLE_FMT_U8: case AV_SAMPLE_FMT_U8P: lav_sample_fmt = SampleFormat_U8; break; default: lav_sample_fmt = SampleFormat_16; break; } return lav_sample_fmt; } AVSampleFormat get_ff_sample_fmt(LAVAudioSampleFormat sample_fmt) { AVSampleFormat ff_sample_fmt; switch (sample_fmt) { case SampleFormat_16: ff_sample_fmt = AV_SAMPLE_FMT_S16; break; case SampleFormat_24: case SampleFormat_32: ff_sample_fmt = AV_SAMPLE_FMT_S32; break; case SampleFormat_FP32: ff_sample_fmt = AV_SAMPLE_FMT_FLT; break; case SampleFormat_U8: ff_sample_fmt = AV_SAMPLE_FMT_U8; break; default: assert(0); break; } return ff_sample_fmt; } static BYTE get_lpcm_sample_rate_index(int sample_rate) { switch (sample_rate) { case 48000: return 1; case 96000: return 4; case 192000: return 5; } return 0; } static BYTE get_lpcm_bit_per_sample_index(int bit_per_sample) { switch (bit_per_sample) { case 16: return 1; case 20: return 2; case 24: return 3; } return 0; } void CLAVAudio::CreateBDLPCMHeader(BYTE *const pBuf, const WAVEFORMATEX_HDMV_LPCM *const wfex_lpcm) const { const BYTE channel_conf = (wfex_lpcm->cbSize >= 1) ? wfex_lpcm->channel_conf : 0; pBuf[0] = 0; pBuf[1] = 0; pBuf[2] = ((channel_conf) << 4) | (get_lpcm_sample_rate_index(wfex_lpcm->nSamplesPerSec) & 0x0f); pBuf[3] = get_lpcm_bit_per_sample_index(wfex_lpcm->wBitsPerSample) << 6; } static BYTE get_dvdlpcm_sample_rate_index(int sample_rate) { switch (sample_rate) { case 48000: return 0; case 96000: return 1; case 44100: return 2; case 32000: return 3; } return 0; } void CLAVAudio::CreateDVDLPCMHeader(BYTE *const pBuf, const WAVEFORMATEX *const wfex) const { pBuf[0] = 0; pBuf[1] = (((wfex->wBitsPerSample - 16) / 4) << 6) | (get_dvdlpcm_sample_rate_index(wfex->nSamplesPerSec) << 4) | ((wfex->nChannels - 1) & 7); pBuf[2] = 0; } HRESULT CLAVAudio::ParseRealAudioHeader(const BYTE *extra, const size_t extralen) { const uint8_t *fmt = extra + 4; uint16_t version = AV_RB16(fmt); fmt += 2; if (version == 3) { DbgLog((LOG_TRACE, 10, L"RealAudio Header version 3 unsupported")); return VFW_E_UNSUPPORTED_AUDIO; } else if (version == 4 || version == 5 && extralen > 50) { // main format block fmt += 2; // word - unused (always 0) fmt += 4; // byte[4] - .ra4/.ra5 signature fmt += 4; // dword - unknown fmt += 2; // word - Version2 fmt += 4; // dword - header size m_raData.flavor = AV_RB16(fmt); fmt += 2; // word - codec flavor m_raData.coded_frame_size = AV_RB32(fmt); fmt += 4; // dword - coded frame size fmt += 12; // byte[12] - unknown m_raData.sub_packet_h = AV_RB16(fmt); fmt += 2; // word - sub packet h m_raData.audio_framesize = m_pAVCtx->block_align = AV_RB16(fmt); fmt += 2; // word - frame size m_raData.sub_packet_size = AV_RB16(fmt); fmt += 2; // word - subpacket size fmt += 2; // word - unknown // 6 Unknown bytes in ver 5 if (version == 5) fmt += 6; // Audio format block fmt += 8; // Tag info in v4 if (version == 4) { int len = *fmt++; m_raData.deint_id = AV_RB32(fmt); fmt += len; len = *fmt++; fmt += len; } else if (version == 5) { m_raData.deint_id = AV_RB32(fmt); fmt += 4; fmt += 4; } fmt += 3; if (version == 5) fmt++; size_t ra_extralen = min((size_t)((extra + extralen) - (fmt + 4)), AV_RB32(fmt)); if (ra_extralen > 0) { m_pAVCtx->extradata_size = (int)ra_extralen; m_pAVCtx->extradata = (uint8_t *)av_mallocz(ra_extralen + AV_INPUT_BUFFER_PADDING_SIZE); memcpy(m_pAVCtx->extradata, fmt + 4, ra_extralen); } } else { DbgLog((LOG_TRACE, 10, L"Unknown RealAudio Header version: %d", version)); return VFW_E_UNSUPPORTED_AUDIO; } return S_OK; } // Gets a sample from the buffer for processing // The sample is returned as a floating point, with either single or double precision, depending on the template type // DO NOT USE WITH AN INTEGER TYPE - only double and float are allowed template T get_sample_from_buffer(const BYTE *const pBuffer, LAVAudioSampleFormat sfFormat) { T fSample = 0.0; switch (sfFormat) { case SampleFormat_U8: fSample = (T)(*(uint8_t *)pBuffer); fSample = (fSample + INT8_MIN) / INT8_MAX; break; case SampleFormat_16: fSample = (T)(*(int16_t *)pBuffer); fSample /= INT16_MAX; break; case SampleFormat_24: fSample += pBuffer[0] << 8; fSample += pBuffer[1] << 16; fSample += pBuffer[2] << 24; fSample /= INT32_MAX; break; case SampleFormat_32: fSample = (T)(*(int32_t *)pBuffer); fSample /= INT32_MAX; break; case SampleFormat_FP32: fSample = (T) * (float *)pBuffer; break; } return fSample; } // This function calculates the Root mean square (RMS) of all samples in the buffer, // converts the result into a reference dB value, and adds it to the volume floating average void CLAVAudio::UpdateVolumeStats(const BufferDetails &buffer) { const BYTE bSampleSize = get_byte_per_sample(buffer.sfFormat); const DWORD dwSamplesPerChannel = buffer.nSamples; const BYTE *pBuffer = buffer.bBuffer->Ptr(); float *const fChAvg = (float *)calloc(buffer.layout.nb_channels, sizeof(float)); for (DWORD i = 0; i < dwSamplesPerChannel; ++i) { for (WORD ch = 0; ch < buffer.layout.nb_channels; ++ch) { const float fSample = get_sample_from_buffer(pBuffer, buffer.sfFormat); fChAvg[ch] += fSample * fSample; pBuffer += bSampleSize; } } for (int ch = 0; ch < min(buffer.layout.nb_channels, MAX_VOLUME_STAT_CHANNEL); ++ch) { if (fChAvg[ch] > FLT_EPSILON) { const float fAvgSqrt = sqrtf(fChAvg[ch] / dwSamplesPerChannel); const float fDb = 20.0f * log10f(fAvgSqrt); m_faVolume[ch].Sample(fDb); } else { m_faVolume[ch].Sample(-100.0f); } } free(fChAvg); } #define MAX_SPEAKER_LAYOUT 18 // Get the channel index for the given speaker flag // First channel starts at index 0 WORD get_channel_from_flag(DWORD dwMask, DWORD dwFlag) { WORD nChannel = 0; for (int i = 0; i < MAX_SPEAKER_LAYOUT; i++) { DWORD flag = 1 << i; if (dwMask & flag) { if (dwFlag == flag) break; else nChannel++; } } return nChannel; } // Get the speaker flag for the given channel in the mask // First channel starts at index 0 DWORD get_flag_from_channel(DWORD dwMask, WORD wChannel) { WORD nChannel = 0; for (int i = 0; i < MAX_SPEAKER_LAYOUT; i++) { DWORD flag = 1 << i; if (dwMask & flag) { if (nChannel == wChannel) return flag; else nChannel++; } } return 0; } static const char *channel_short_descs[] = {"L", "R", "C", "LFE", "BL", "BR", "FLC", "FRC", "BC", "SL", "SR", "TC", "TFL", "TFC", "TFR", "TBL", "TBC", "TBR"}; const char *get_channel_desc(DWORD dwFlag) { for (int i = 0; i < MAX_SPEAKER_LAYOUT; i++) { DWORD flag = 1 << i; if (flag & dwFlag) { return channel_short_descs[i]; } } return "-"; } // Strings will be filled in eventually. // AV_CODEC_ID_NONE means there is some special handling going on. // Order is Important, has to be the same as the CC Enum // Also, the order is used for storage in the Registry // clang-format off static codec_config_t m_codec_config[] = { { 2, { AV_CODEC_ID_AAC, AV_CODEC_ID_AAC_LATM }}, // CC_AAC { 1, { AV_CODEC_ID_AC3 }}, // CC_AC3 { 1, { AV_CODEC_ID_EAC3 }}, // CC_EAC3 { 1, { AV_CODEC_ID_DTS }, "dts", "DTS Coherent Acoustics (DTS, DTS-HD)"}, // CC_DTS { 2, { AV_CODEC_ID_MP2, AV_CODEC_ID_MP1 }}, // CC_MP2 { 1, { AV_CODEC_ID_MP3 }}, // CC_MP3 { 2, { AV_CODEC_ID_TRUEHD, AV_CODEC_ID_MLP }}, // CC_TRUEHD { 1, { AV_CODEC_ID_FLAC }}, // CC_FLAC { 1, { AV_CODEC_ID_VORBIS }}, // CC_VORBIS { 2, { AV_CODEC_ID_PCM_BLURAY, AV_CODEC_ID_PCM_DVD }, "lpcm", "Linear PCM (BluRay & DVD)"}, // CC_LPCM { 1, { AV_CODEC_ID_NONE }, "pcm", "Raw PCM Types (including QT PCM)" }, // CC_LPCM { 1, { AV_CODEC_ID_WAVPACK }}, // CC_WAVPACK { 1, { AV_CODEC_ID_TTA }}, // CC_TTA { 2, { AV_CODEC_ID_WMAV2, AV_CODEC_ID_WMAV1 }, "wma", "Windows Media Audio 1/2"}, // CC_WMA2 { 1, { AV_CODEC_ID_WMAPRO }}, // CC_WMAPRO { 1, { AV_CODEC_ID_COOK }}, // CC_COOK { 4, { AV_CODEC_ID_SIPR, AV_CODEC_ID_RA_144, AV_CODEC_ID_RA_288, AV_CODEC_ID_RALF }, "realaudio", "Real Audio (SIPR, RALF, 14.4 28.8)" }, // CC_REAL { 1, { AV_CODEC_ID_WMALOSSLESS }}, // CC_WMALL { 1, { AV_CODEC_ID_ALAC }}, // CC_ALAC { 1, { AV_CODEC_ID_OPUS }, "opus", "Opus Audio Codec"}, // CC_OPUS { 2, { AV_CODEC_ID_AMR_NB, AV_CODEC_ID_AMR_WB }, "amr", "AMR-NB/WB (Adaptive Multi-Rate NarrowBand/WideBand)" }, // CC_AMR { 1, { AV_CODEC_ID_NELLYMOSER }}, // CC_Nellymoser { 4, { AV_CODEC_ID_PCM_ALAW, AV_CODEC_ID_PCM_MULAW, AV_CODEC_ID_GSM_MS, AV_CODEC_ID_ADPCM_MS }, "mspcm", "Microsoft PCM (A-Law, muLaw, MS-GSM, MS ADPCM)" }, // CC_MSPCM { 1, { AV_CODEC_ID_TRUESPEECH }}, // CC_Truespeech { 1, { AV_CODEC_ID_TAK }}, // CC_TAK { 3, { AV_CODEC_ID_ATRAC1, AV_CODEC_ID_ATRAC3, AV_CODEC_ID_ATRAC3P }, "atrac", "ATRAC (Adaptive TRansform Acoustic Coding)"}, // CC_ATRAC { 3, { AV_CODEC_ID_ADPCM_IMA_WAV, AV_CODEC_ID_ADPCM_G726, AV_CODEC_ID_G729 }, "adpcm", "ADPCM (adaptive differential pcm)"}, // CC_ADPCM { 1, { AV_CODEC_ID_IMC }}, // CC_IMC }; // clang-format on const codec_config_t *get_codec_config(LAVAudioCodec codec) { codec_config_t *config = &m_codec_config[codec]; const AVCodec *avcodec = avcodec_find_decoder(config->codecs[0]); if (avcodec) { if (!config->name) { config->name = avcodec->name; } if (!config->description) { config->description = avcodec->long_name; } } return &m_codec_config[codec]; } static LAVAudioSampleFormat sampleFormatMapping[5][5] = { {SampleFormat_16, SampleFormat_24, SampleFormat_FP32, SampleFormat_32, SampleFormat_U8}, // SampleFormat_16 {SampleFormat_24, SampleFormat_FP32, SampleFormat_32, SampleFormat_16, SampleFormat_U8}, // SampleFormat_24 {SampleFormat_32, SampleFormat_FP32, SampleFormat_24, SampleFormat_16, SampleFormat_U8}, // SampleFormat_32 {SampleFormat_U8, SampleFormat_16, SampleFormat_24, SampleFormat_FP32, SampleFormat_32}, // SampleFormat_U8 {SampleFormat_FP32, SampleFormat_24, SampleFormat_32, SampleFormat_16, SampleFormat_U8}, // SampleFormat_FP32 }; LAVAudioSampleFormat CLAVAudio::GetBestAvailableSampleFormat(LAVAudioSampleFormat inFormat, int *bits, BOOL bNoFallback) { ASSERT(inFormat >= 0 && inFormat < SampleFormat_Bitstream); if (m_FallbackFormat != SampleFormat_None && !bNoFallback) return m_FallbackFormat; LAVAudioSampleFormat outFormat = sampleFormatMapping[inFormat][0]; for (int i = 0; i < 5; i++) { if (GetSampleFormat(sampleFormatMapping[inFormat][i])) { outFormat = sampleFormatMapping[inFormat][i]; break; } } if (bits && outFormat != inFormat) *bits = get_byte_per_sample(outFormat) << 3; return outFormat; } // Copy of ff_spdif_bswap_buf16, which sadly is a private symbol void lav_spdif_bswap_buf16(uint16_t *dst, const uint16_t *src, int w) { int i; for (i = 0; i + 8 <= w; i += 8) { dst[i + 0] = av_bswap16(src[i + 0]); dst[i + 1] = av_bswap16(src[i + 1]); dst[i + 2] = av_bswap16(src[i + 2]); dst[i + 3] = av_bswap16(src[i + 3]); dst[i + 4] = av_bswap16(src[i + 4]); dst[i + 5] = av_bswap16(src[i + 5]); dst[i + 6] = av_bswap16(src[i + 6]); dst[i + 7] = av_bswap16(src[i + 7]); } for (; i < w; i++) dst[i + 0] = av_bswap16(src[i + 0]); } ================================================ FILE: decoder/LAVAudio/Media.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #define DBL_SECOND_MULT 10000000.0 #define RT_SECOND_MULT 10000000LL #define INT24_MAX 8388607i32 #define INT24_MIN (-8388607i32 - 1) #define LAV_CH_LAYOUT_5POINT1_BC (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY | AV_CH_BACK_CENTER) #define LAV_CH_LAYOUT_5POINT1_WIDE \ (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY | AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER) #define LAV_CH_LAYOUT_7POINT1_EXTRAWIDE (LAV_CH_LAYOUT_5POINT1_WIDE | AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT) struct scmap_t { WORD nChannels; DWORD dwChannelMask; }; #define MAX_NUM_CC_CODECS 5 struct codec_config_t { int nCodecs; AVCodecID codecs[MAX_NUM_CC_CODECS]; const char *name; const char *description; }; const codec_config_t *get_codec_config(LAVAudioCodec codec); AVCodecID FindCodecId(const CMediaType *mt); const char *find_codec_override(AVCodecID codec); DWORD get_channel_mask(int num_channels); const char *get_sample_format_desc(LAVAudioSampleFormat sfFormat); const char *get_sample_format_desc(CMediaType &mt); BYTE get_byte_per_sample(LAVAudioSampleFormat sfFormat); LAVAudioSampleFormat get_lav_sample_fmt(AVSampleFormat sample_fmt, int bits = 0); AVSampleFormat get_ff_sample_fmt(LAVAudioSampleFormat sample_fmt); WORD get_channel_from_flag(DWORD dwMask, DWORD dwFlag); DWORD get_flag_from_channel(DWORD dwMask, WORD wChannel); const char *get_channel_desc(DWORD dwFlag); // Gets a sample from the buffer for processing // The sample is returned as a floating point, with either single or double precision, depending on the template type // DO NOT USE WITH AN INTEGER TYPE - only double and float are allowed template T get_sample_from_buffer(const BYTE *pBuffer, LAVAudioSampleFormat sfFormat); void lav_spdif_bswap_buf16(uint16_t *dst, const uint16_t *src, int w); ================================================ FILE: decoder/LAVAudio/PostProcessor.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "PostProcessor.h" #include "LAVAudio.h" #include "Media.h" extern "C" { #include "libavutil/intreadwrite.h" }; // PCM Volume Adjustment Factors, both for integer and float math // entries start at 2 channel mixing, half volume static int pcm_volume_adjust_integer[7] = {362, 443, 512, 572, 627, 677, 724}; static float pcm_volume_adjust_float[7] = {1.41421356f, 1.73205081f, 2.00000000f, 2.23606798f, 2.44948974f, 2.64575131f, 2.82842712f}; // SCALE_CA helper macro for SampleCopyAdjust #define SCALE_CA(sample, iFactor, factor) \ { \ if (iFactor > 0) \ { \ sample *= factor; \ sample >>= 8; \ } \ else \ { \ sample <<= 8; \ sample /= factor; \ } \ } // // Helper Function that reads one sample from pIn, applys the scale specified by iFactor, and writes it to pOut // static inline void SampleCopyAdjust(BYTE *pOut, const BYTE *pIn, int iFactor, LAVAudioSampleFormat sfSampleFormat) { ASSERT(abs(iFactor) > 1 && abs(iFactor) <= 8); const int factorIndex = abs(iFactor) - 2; switch (sfSampleFormat) { case SampleFormat_U8: { uint8_t *pOutSample = pOut; int32_t sample = *pIn + INT8_MIN; SCALE_CA(sample, iFactor, pcm_volume_adjust_integer[factorIndex]); *pOutSample = av_clip_uint8(sample - INT8_MIN); } break; case SampleFormat_16: { int16_t *pOutSample = (int16_t *)pOut; int32_t sample = *((int16_t *)pIn); SCALE_CA(sample, iFactor, pcm_volume_adjust_integer[factorIndex]); *pOutSample = av_clip_int16(sample); } break; case SampleFormat_24: { int32_t sample = (pIn[0] << 8) + (pIn[1] << 16) + (pIn[2] << 24); sample >>= 8; SCALE_CA(sample, iFactor, pcm_volume_adjust_integer[factorIndex]); sample = av_clip(sample, INT24_MIN, INT24_MAX); pOut[0] = sample & 0xff; pOut[1] = (sample >> 8) & 0xff; pOut[2] = (sample >> 16) & 0xff; } break; case SampleFormat_32: { int32_t *pOutSample = (int32_t *)pOut; int64_t sample = *((int32_t *)pIn); SCALE_CA(sample, iFactor, pcm_volume_adjust_integer[factorIndex]); *pOutSample = av_clipl_int32(sample); } break; case SampleFormat_FP32: { float *pOutSample = (float *)pOut; float sample = *((float *)pIn); if (iFactor > 0) { sample *= pcm_volume_adjust_float[factorIndex]; } else { sample /= pcm_volume_adjust_float[factorIndex]; } *pOutSample = av_clipf(sample, -1.0f, 1.0f); } break; default: ASSERT(0); break; } } // // Writes one sample of silence into the buffer // static inline void Silence(BYTE *pBuffer, LAVAudioSampleFormat sfSampleFormat) { switch (sfSampleFormat) { case SampleFormat_16: case SampleFormat_24: case SampleFormat_32: case SampleFormat_FP32: memset(pBuffer, 0, get_byte_per_sample(sfSampleFormat)); break; case SampleFormat_U8: *pBuffer = 128U; break; default: ASSERT(0); } } // // Extended Channel Remapping Processor // // This function can process a PCM buffer of any sample format, and remap the channels // into any arbitrary layout and channel count. // // The samples are copied byte-by-byte, without any conversion or loss. // // The ExtendedChannelMap is assumed to always have at least uOutChannels valid entries. // Its layout is in output format: // Map[0] is the first output channel, and should contain the index in the source stream (or -1 for silence) // Map[1] is the second output channel // // Source channels can be applied multiple times to the Destination, but multiple Source channels cannot be merged into one channel. // Note that when copying one source channel into multiple destinations, you always want to reduce its volume. // You can either do this in a second step, or use the factor documented below // // Examples: // 5.1 Input Buffer, following map will extract the Center channel, and return it as Mono: // uOutChannels == 1; map = {2} // // Mono Input Buffer, Convert to Stereo // uOutChannels == 2; map = {0, 0} // // Additionally, a factor can be applied to all PCM samples // // For optimization, the factor cannot be freely specified. // Factors -1, 0, 1 are ignored. // A Factor of 2 doubles the volume, 3 trippled, etc. // A Factor of -2 will produce half volume, -3 one third, etc. // The limit is a factor of 8/-8 // // Otherwise, see ChannelMapping HRESULT ExtendedChannelMapping(BufferDetails *pcm, const unsigned uOutChannels, const ExtendedChannelMap extMap) { #ifdef DEBUG ASSERT(pcm && pcm->bBuffer); ASSERT(uOutChannels > 0 && uOutChannels <= 8); for (unsigned idx = 0; idx < uOutChannels; ++idx) { ASSERT(extMap[idx].idx >= -1 && extMap[idx].idx < pcm->layout.nb_channels); } #endif // Sample Size const unsigned uSampleSize = get_byte_per_sample(pcm->sfFormat); // New Output Buffer GrowableArray *out = new GrowableArray(); out->SetSize(uOutChannels * pcm->nSamples * uSampleSize); const BYTE *pIn = pcm->bBuffer->Ptr(); BYTE *pOut = out->Ptr(); for (unsigned i = 0; i < pcm->nSamples; ++i) { for (unsigned ch = 0; ch < uOutChannels; ++ch) { if (extMap[ch].idx >= 0) { if (!extMap[ch].factor || abs(extMap[ch].factor) == 1) memcpy(pOut, pIn + (extMap[ch].idx * uSampleSize), uSampleSize); else SampleCopyAdjust(pOut, pIn + (extMap[ch].idx * uSampleSize), extMap[ch].factor, pcm->sfFormat); } else Silence(pOut, pcm->sfFormat); pOut += uSampleSize; } pIn += uSampleSize * pcm->layout.nb_channels; } // Apply changes to buffer delete pcm->bBuffer; pcm->bBuffer = out; av_channel_layout_uninit(&pcm->layout); pcm->layout.order = AV_CHANNEL_ORDER_UNSPEC; pcm->layout.nb_channels = uOutChannels; return S_OK; } #define CHL_CONTAINS_ALL(l, m) (((l) & (m)) == (m)) #define CHL_ALL_OR_NONE(l, m) (((l) & (m)) == (m) || ((l) & (m)) == 0) HRESULT CLAVAudio::CheckChannelLayoutConformity(AVChannelLayout * layout) { int channels = layout->nb_channels; if (layout->order != AV_CHANNEL_ORDER_NATIVE) { DbgLog((LOG_ERROR, 10, L"::CheckChannelLayoutConformity(): Only native channel orders are supported")); goto noprocessing; } if (layout->u.mask > INT32_MAX) { DbgLog((LOG_ERROR, 10, L"::CheckChannelLayoutConformity(): Layout channels above 32-bit are not handled (mask: 0x%llx)", layout->u.mask)); goto noprocessing; } DWORD dwMask = (DWORD)layout->u.mask; // We require multi-channel and at least containing stereo if (!CHL_CONTAINS_ALL(dwMask, AV_CH_LAYOUT_STEREO) || channels == 2) goto noprocessing; // We do not know what to do with "top" channels if (dwMask & (AV_CH_TOP_CENTER | AV_CH_TOP_FRONT_LEFT | AV_CH_TOP_FRONT_CENTER | AV_CH_TOP_FRONT_RIGHT | AV_CH_TOP_BACK_LEFT | AV_CH_TOP_BACK_CENTER | AV_CH_TOP_BACK_RIGHT)) { DbgLog((LOG_ERROR, 10, L"::CheckChannelLayoutConformity(): Layout with top channels is not supported (mask: 0x%x)", dwMask)); goto noprocessing; } // We need either both surround channels, or none. One of a type is not supported if (!CHL_ALL_OR_NONE(dwMask, AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT) || !CHL_ALL_OR_NONE(dwMask, AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT) || !CHL_ALL_OR_NONE(dwMask, AV_CH_FRONT_LEFT_OF_CENTER | AV_CH_FRONT_RIGHT_OF_CENTER)) { DbgLog( (LOG_ERROR, 10, L"::CheckChannelLayoutConformity(): Layout with only one surround channel is not supported (mask: 0x%x)", dwMask)); goto noprocessing; } // No need to process full 5.1/6.1 layouts, or any 8 channel layouts if (dwMask == AV_CH_LAYOUT_5POINT1 || dwMask == AV_CH_LAYOUT_5POINT1_BACK || dwMask == AV_CH_LAYOUT_6POINT1_BACK || channels == 8) { DbgLog((LOG_TRACE, 10, L"::CheckChannelLayoutConformity(): Layout is already a default layout (mask: 0x%x)", dwMask)); goto noprocessing; } // Check 5.1 channels if (CHL_CONTAINS_ALL(AV_CH_LAYOUT_5POINT1, dwMask) /* 5.1 with side channels */ || CHL_CONTAINS_ALL(AV_CH_LAYOUT_5POINT1_BACK, dwMask) /* 5.1 with back channels */ || CHL_CONTAINS_ALL(LAV_CH_LAYOUT_5POINT1_WIDE, dwMask) /* 5.1 with side-front channels */ || CHL_CONTAINS_ALL(LAV_CH_LAYOUT_5POINT1_BC, dwMask)) /* 3/1/x layouts, front channels with a back center */ return Create51Conformity(dwMask); // Check 6.1 channels (5.1 layouts + Back Center) if (CHL_CONTAINS_ALL(AV_CH_LAYOUT_6POINT1, dwMask) /* 6.1 with side channels */ || CHL_CONTAINS_ALL(AV_CH_LAYOUT_6POINT1_BACK, dwMask) /* 6.1 with back channels */ || CHL_CONTAINS_ALL(LAV_CH_LAYOUT_5POINT1_WIDE | AV_CH_BACK_CENTER, dwMask)) /* 6.1 with side-front channels */ return Create61Conformity(dwMask); // Check 7.1 channels if (CHL_CONTAINS_ALL(AV_CH_LAYOUT_7POINT1, dwMask) /* 7.1 with side+back channels */ || CHL_CONTAINS_ALL(AV_CH_LAYOUT_7POINT1_WIDE, dwMask) /* 7.1 with front-side+back channels */ || CHL_CONTAINS_ALL(LAV_CH_LAYOUT_7POINT1_EXTRAWIDE, dwMask)) /* 7.1 with front-side+side channels */ return Create71Conformity(dwMask); noprocessing: m_bChannelMappingRequired = FALSE; return S_FALSE; } HRESULT CLAVAudio::Create51Conformity(DWORD dwLayout) { DbgLog((LOG_TRACE, 10, L"::Create51Conformity(): Creating 5.1 default layout (mask: 0x%x)", dwLayout)); int ch = 0; ExtChMapClear(&m_ChannelMap); // All layouts we support have to contain L/R ExtChMapSet(&m_ChannelMap, 0, ch++, 0); ExtChMapSet(&m_ChannelMap, 1, ch++, 0); // Center channel if (dwLayout & AV_CH_FRONT_CENTER) ExtChMapSet(&m_ChannelMap, 2, ch++, 0); // LFE if (dwLayout & AV_CH_LOW_FREQUENCY) ExtChMapSet(&m_ChannelMap, 3, ch++, 0); // Back/Side if (dwLayout & (AV_CH_SIDE_LEFT | AV_CH_BACK_LEFT | AV_CH_FRONT_LEFT_OF_CENTER)) { ExtChMapSet(&m_ChannelMap, 4, ch++, 0); ExtChMapSet(&m_ChannelMap, 5, ch++, 0); // Back Center } else if (dwLayout & AV_CH_BACK_CENTER) { ExtChMapSet(&m_ChannelMap, 4, ch, -2); ExtChMapSet(&m_ChannelMap, 5, ch++, -2); } m_bChannelMappingRequired = TRUE; av_channel_layout_uninit(&m_ChannelMapOutputLayout); av_channel_layout_from_mask(&m_ChannelMapOutputLayout, AV_CH_LAYOUT_5POINT1); return S_OK; } HRESULT CLAVAudio::Create61Conformity(DWORD dwLayout) { if (m_settings.Expand61) { DbgLog((LOG_TRACE, 10, L"::Create61Conformity(): Expanding to 7.1")); return Create71Conformity(dwLayout); } DbgLog((LOG_TRACE, 10, L"::Create61Conformity(): Creating 6.1 default layout (mask: 0x%x)", dwLayout)); int ch = 0; ExtChMapClear(&m_ChannelMap); // All layouts we support have to contain L/R ExtChMapSet(&m_ChannelMap, 0, ch++, 0); ExtChMapSet(&m_ChannelMap, 1, ch++, 0); // Center channel if (dwLayout & AV_CH_FRONT_CENTER) ExtChMapSet(&m_ChannelMap, 2, ch++, 0); // LFE if (dwLayout & AV_CH_LOW_FREQUENCY) ExtChMapSet(&m_ChannelMap, 3, ch++, 0); // Back channels, if before BC if (dwLayout & (AV_CH_BACK_LEFT | AV_CH_FRONT_LEFT_OF_CENTER)) { DbgLog((LOG_TRACE, 10, L"::Create61Conformity(): Using surround channels *before* BC")); ExtChMapSet(&m_ChannelMap, 4, ch++, 0); ExtChMapSet(&m_ChannelMap, 5, ch++, 0); } // Back Center if (dwLayout & AV_CH_BACK_CENTER) ExtChMapSet(&m_ChannelMap, 6, ch++, 0); // Back channels, if after BC if (dwLayout & AV_CH_SIDE_LEFT) { DbgLog((LOG_TRACE, 10, L"::Create61Conformity(): Using surround channels *after* BC")); ExtChMapSet(&m_ChannelMap, 4, ch++, 0); ExtChMapSet(&m_ChannelMap, 5, ch++, 0); } m_bChannelMappingRequired = TRUE; av_channel_layout_uninit(&m_ChannelMapOutputLayout); av_channel_layout_from_mask(&m_ChannelMapOutputLayout, AV_CH_LAYOUT_6POINT1_BACK); return S_OK; } HRESULT CLAVAudio::Create71Conformity(DWORD dwLayout) { DbgLog((LOG_TRACE, 10, L"::Create71Conformity(): Creating 7.1 default layout (mask: 0x%x)", dwLayout)); int ch = 0; ExtChMapClear(&m_ChannelMap); // All layouts we support have to contain L/R ExtChMapSet(&m_ChannelMap, 0, ch++, 0); ExtChMapSet(&m_ChannelMap, 1, ch++, 0); // Center channel if (dwLayout & AV_CH_FRONT_CENTER) ExtChMapSet(&m_ChannelMap, 2, ch++, 0); // LFE if (dwLayout & AV_CH_LOW_FREQUENCY) ExtChMapSet(&m_ChannelMap, 3, ch++, 0); // Back channels if (dwLayout & AV_CH_BACK_CENTER) { DbgLog((LOG_TRACE, 10, L"::Create71Conformity(): Usign BC to fill back channels")); if (dwLayout & AV_CH_SIDE_LEFT) { DbgLog((LOG_TRACE, 10, L"::Create71Conformity(): Using BC before side-surround channels")); ExtChMapSet(&m_ChannelMap, 4, ch, -2); ExtChMapSet(&m_ChannelMap, 5, ch++, -2); ExtChMapSet(&m_ChannelMap, 6, ch++, 0); ExtChMapSet(&m_ChannelMap, 7, ch++, 0); } else { DbgLog((LOG_TRACE, 10, L"::Create71Conformity(): Using BC after side-surround channels")); ExtChMapSet(&m_ChannelMap, 6, ch++, 0); ExtChMapSet(&m_ChannelMap, 7, ch++, 0); ExtChMapSet(&m_ChannelMap, 4, ch, -2); ExtChMapSet(&m_ChannelMap, 5, ch++, -2); } } else { DbgLog((LOG_TRACE, 10, L"::Create71Conformity(): Using original 4 surround channels")); ExtChMapSet(&m_ChannelMap, 4, ch++, 0); ExtChMapSet(&m_ChannelMap, 5, ch++, 0); ExtChMapSet(&m_ChannelMap, 6, ch++, 0); ExtChMapSet(&m_ChannelMap, 7, ch++, 0); } m_bChannelMappingRequired = TRUE; av_channel_layout_uninit(&m_ChannelMapOutputLayout); av_channel_layout_from_mask(&m_ChannelMapOutputLayout, AV_CH_LAYOUT_7POINT1); return S_OK; } HRESULT CLAVAudio::PadTo32(BufferDetails *buffer) { ASSERT(buffer->sfFormat == SampleFormat_24); const DWORD size = (buffer->nSamples * buffer->layout.nb_channels) * 4; GrowableArray *pcmOut = new GrowableArray(); pcmOut->SetSize(size); const BYTE *pDataIn = buffer->bBuffer->Ptr(); BYTE *pDataOut = pcmOut->Ptr(); for (unsigned int i = 0; i < buffer->nSamples; ++i) { for (int ch = 0; ch < buffer->layout.nb_channels; ++ch) { AV_WL32(pDataOut, AV_RL24(pDataIn) << 8); pDataOut += 4; pDataIn += 3; } } delete buffer->bBuffer; buffer->bBuffer = pcmOut; buffer->sfFormat = SampleFormat_32; buffer->wBitsPerSample = 24; return S_OK; } HRESULT CLAVAudio::Truncate32Buffer(BufferDetails *buffer) { ASSERT(buffer->sfFormat == SampleFormat_32 && buffer->wBitsPerSample <= 24); // Determine the bytes per sample to keep. Cut a 16-bit sample to 24 if 16-bit is disabled for some reason const int bytes_per_sample = buffer->wBitsPerSample <= 16 && GetSampleFormat(SampleFormat_16) ? 2 : 3; if (bytes_per_sample == 3 && !GetSampleFormat(SampleFormat_24)) return S_FALSE; const int skip = 4 - bytes_per_sample; const DWORD size = (buffer->nSamples * buffer->layout.nb_channels) * bytes_per_sample; GrowableArray *pcmOut = new GrowableArray(); pcmOut->SetSize(size); const BYTE *pDataIn = buffer->bBuffer->Ptr(); BYTE *pDataOut = pcmOut->Ptr(); pDataIn += skip; for (unsigned int i = 0; i < buffer->nSamples; ++i) { for (int ch = 0; ch < buffer->layout.nb_channels; ++ch) { memcpy(pDataOut, pDataIn, bytes_per_sample); pDataOut += bytes_per_sample; pDataIn += 4; } } delete buffer->bBuffer; buffer->bBuffer = pcmOut; buffer->sfFormat = bytes_per_sample == 3 ? SampleFormat_24 : SampleFormat_16; return S_OK; } HRESULT CLAVAudio::PerformAVRProcessing(BufferDetails *buffer) { int ret = 0; AVChannelLayout chMixingLayout{}; if (av_channel_layout_check(&m_chOverrideMixer) != 0) { av_channel_layout_copy(&chMixingLayout, &m_chOverrideMixer); } else if (m_settings.MixingEnabled) { av_channel_layout_from_mask(&chMixingLayout, m_settings.MixingLayout); } else { av_channel_layout_copy(&chMixingLayout, &buffer->layout); } // No mixing stereo, if the user doesn't want it if (buffer->layout.nb_channels <= 2 && (m_settings.MixingFlags & LAV_MIXING_FLAG_UNTOUCHED_STEREO)) { av_channel_layout_uninit(&chMixingLayout); av_channel_layout_copy(&chMixingLayout, &buffer->layout); } LAVAudioSampleFormat outputFormat = av_channel_layout_compare(&buffer->layout, &chMixingLayout) != 0 ? GetBestAvailableSampleFormat(SampleFormat_FP32) : GetBestAvailableSampleFormat(buffer->sfFormat); // Short Circuit some processing if (av_channel_layout_compare(&buffer->layout, &chMixingLayout) == 0 && !buffer->bPlanar) { if (buffer->sfFormat == SampleFormat_24 && outputFormat == SampleFormat_32) { PadTo32(buffer); return S_OK; } else if (buffer->sfFormat == SampleFormat_32 && outputFormat == SampleFormat_24) { buffer->wBitsPerSample = 24; Truncate32Buffer(buffer); return S_OK; } } // Sadly, we need to convert this, avresample has no 24-bit mode if (buffer->sfFormat == SampleFormat_24) { PadTo32(buffer); } if (av_channel_layout_compare(&buffer->layout, &m_MixingInputLayout) != 0 || (!m_swrContext && !m_bAVResampleFailed) || m_bMixingSettingsChanged || av_channel_layout_compare(&m_chRemixLayout, &chMixingLayout) != 0 || outputFormat != m_sfRemixFormat || buffer->sfFormat != m_MixingInputFormat) { m_bAVResampleFailed = FALSE; m_bMixingSettingsChanged = FALSE; if (m_swrContext) { swr_free(&m_swrContext); } av_channel_layout_copy(&m_MixingInputLayout, &buffer->layout); av_channel_layout_copy(&m_chRemixLayout, &chMixingLayout); m_MixingInputFormat = buffer->sfFormat; m_sfRemixFormat = outputFormat; swr_alloc_set_opts2(&m_swrContext, &chMixingLayout, get_ff_sample_fmt(m_sfRemixFormat), buffer->dwSamplesPerSec, &buffer->layout, get_ff_sample_fmt(buffer->sfFormat), buffer->dwSamplesPerSec, 0, NULL); av_opt_set_int(m_swrContext, "dither_method", m_settings.SampleConvertDither ? SWR_DITHER_TRIANGULAR_HIGHPASS : SWR_DITHER_NONE, 0); // Setup mixing properties, if needed if (av_channel_layout_compare(&buffer->layout, &chMixingLayout) != 0) { ASSERT(chMixingLayout.order == AV_CHANNEL_ORDER_NATIVE); BOOL bNormalize = !!(m_settings.MixingFlags & LAV_MIXING_FLAG_NORMALIZE_MATRIX); BOOL bClipProtection = !!(m_settings.MixingFlags & LAV_MIXING_FLAG_CLIP_PROTECTION); av_opt_set_int(m_swrContext, "clip_protection", !bNormalize && bClipProtection, 0); av_opt_set_int(m_swrContext, "internal_sample_fmt", AV_SAMPLE_FMT_FLTP, 0); // setup matrix parameters const double center_mix_level = (double)m_settings.MixingCenterLevel / 10000.0; const double surround_mix_level = (double)m_settings.MixingSurroundLevel / 10000.0; const double lfe_mix_level = (double)m_settings.MixingLFELevel / 10000.0 / (chMixingLayout.u.mask == AV_CH_LAYOUT_MONO ? 1.0 : M_SQRT1_2); av_opt_set_double(m_swrContext, "center_mix_level", center_mix_level, 0); av_opt_set_double(m_swrContext, "surround_mix_level", surround_mix_level, 0); av_opt_set_double(m_swrContext, "lfe_mix_level", lfe_mix_level, 0); av_opt_set_double(m_swrContext, "rematrix_maxval", bNormalize ? 1.0 : 0.0, 0); av_opt_set_int(m_swrContext, "matrix_encoding", (AVMatrixEncoding)m_settings.MixingMode, 0); } // Open Resample Context ret = swr_init(m_swrContext); if (ret < 0) { DbgLog((LOG_ERROR, 10, L"swr_init failed")); goto setuperr; } } if (!m_swrContext) { DbgLog((LOG_ERROR, 10, L"swresample context missing?")); goto setuperr; } av_channel_layout_uninit(&chMixingLayout); LAVAudioSampleFormat bufferFormat = (m_sfRemixFormat == SampleFormat_24) ? SampleFormat_32 : m_sfRemixFormat; // avresample always outputs 32-bit GrowableArray *pcmOut = new GrowableArray(); pcmOut->Allocate(FFALIGN(buffer->nSamples, 32) * m_chRemixLayout.nb_channels * get_byte_per_sample(bufferFormat)); BYTE *pOut = pcmOut->Ptr(); BYTE *pIn = buffer->bBuffer->Ptr(); ret = swr_convert(m_swrContext, &pOut, pcmOut->GetAllocated(), (const uint8_t **)&pIn, buffer->nSamples); if (ret < 0) { DbgLog((LOG_ERROR, 10, L"swr_convert failed")); delete pcmOut; return S_FALSE; } delete buffer->bBuffer; buffer->bBuffer = pcmOut; av_channel_layout_copy(&buffer->layout, &m_chRemixLayout); buffer->sfFormat = bufferFormat; buffer->wBitsPerSample = get_byte_per_sample(m_sfRemixFormat) << 3; buffer->bBuffer->SetSize(buffer->layout.nb_channels * buffer->nSamples * get_byte_per_sample(buffer->sfFormat)); return S_OK; setuperr: swr_free(&m_swrContext); m_bAVResampleFailed = TRUE; av_channel_layout_uninit(&chMixingLayout); return E_FAIL; } HRESULT CLAVAudio::PostProcess(BufferDetails *buffer) { // Validate channel mask if (buffer->layout.order == AV_CHANNEL_ORDER_UNSPEC || (buffer->layout.order == AV_CHANNEL_ORDER_NATIVE && buffer->layout.u.mask == 0) || (buffer->layout.order != AV_CHANNEL_ORDER_UNSPEC && buffer->layout.order != AV_CHANNEL_ORDER_NATIVE)) { int layout_channels = buffer->layout.nb_channels; av_channel_layout_uninit(&buffer->layout); DWORD dwMask = get_channel_mask(layout_channels); if (dwMask) { av_channel_layout_from_mask(&buffer->layout, dwMask); } else { buffer->layout.order = AV_CHANNEL_ORDER_UNSPEC; buffer->layout.nb_channels = layout_channels; } } if (m_settings.SuppressFormatChanges) { if (av_channel_layout_check(&m_SuppressLayout) == 0) { av_channel_layout_copy(&m_SuppressLayout, &buffer->layout); } else { if (av_channel_layout_compare(&buffer->layout, &m_SuppressLayout) != 0 && buffer->layout.nb_channels <= m_SuppressLayout.nb_channels) { // only warn once if (av_channel_layout_compare(&m_chOverrideMixer, &m_SuppressLayout) != 0) { DbgLog((LOG_TRACE, 10, L"Channel Format change suppressed")); av_channel_layout_copy(&m_chOverrideMixer, &m_SuppressLayout); } } else if (buffer->layout.nb_channels > m_SuppressLayout.nb_channels) { DbgLog((LOG_TRACE, 10, L"Channel count increased, allowing change")); av_channel_layout_uninit(&m_chOverrideMixer); av_channel_layout_copy(&m_SuppressLayout, &buffer->layout); } } } ASSERT(buffer->layout.order == AV_CHANNEL_ORDER_NATIVE || buffer->layout.order == AV_CHANNEL_ORDER_UNSPEC); BOOL bOverrideMixing = av_channel_layout_check(&m_chOverrideMixer) != 0; // determine the layout we're mixing to AVChannelLayout chMixingLayout{}; if (bOverrideMixing) av_channel_layout_copy(&chMixingLayout, &m_chOverrideMixer); else if (m_settings.MixingEnabled) av_channel_layout_from_mask(&chMixingLayout, m_settings.MixingLayout); BOOL bMixing = (m_settings.MixingEnabled || bOverrideMixing) && av_channel_layout_compare(&buffer->layout, &chMixingLayout) != 0; LAVAudioSampleFormat outputFormat = GetBestAvailableSampleFormat(buffer->sfFormat); // Perform conversion to layout and sample format, if required if (bMixing || outputFormat != buffer->sfFormat) { PerformAVRProcessing(buffer); } // Remap to standard configurations, if requested (not in combination with mixing) if (!bMixing && m_settings.OutputStandardLayout) { if (av_channel_layout_compare(&buffer->layout, &m_DecodeLayoutSanified) != 0) { av_channel_layout_copy(&m_DecodeLayoutSanified, &buffer->layout); CheckChannelLayoutConformity(&buffer->layout); } if (m_bChannelMappingRequired) { ExtendedChannelMapping(buffer, m_ChannelMapOutputLayout.nb_channels, m_ChannelMap); av_channel_layout_copy(&buffer->layout, &m_ChannelMapOutputLayout); } } // Map to the requested 5.1 layout if (m_settings.Output51Legacy && buffer->layout.u.mask == AV_CH_LAYOUT_5POINT1) buffer->layout.u.mask = AV_CH_LAYOUT_5POINT1_BACK; else if (!m_settings.Output51Legacy && buffer->layout.u.mask == AV_CH_LAYOUT_5POINT1_BACK) buffer->layout.u.mask = AV_CH_LAYOUT_5POINT1; // Check if current output uses back layout, and keep it active in that case if (buffer->layout.u.mask == AV_CH_LAYOUT_5POINT1) { WAVEFORMATEX *wfe = (WAVEFORMATEX *)m_pOutput->CurrentMediaType().Format(); if (wfe->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)wfe; if (wfex->dwChannelMask == AV_CH_LAYOUT_5POINT1_BACK) buffer->layout.u.mask = AV_CH_LAYOUT_5POINT1_BACK; } } // Mono -> Stereo expansion if (buffer->layout.nb_channels == 1 && m_settings.ExpandMono) { ExtendedChannelMap map = {{0, -2}, {0, -2}}; ExtendedChannelMapping(buffer, 2, map); av_channel_layout_uninit(&buffer->layout); av_channel_layout_default(&buffer->layout, 2); } // 6.1 -> 7.1 expansion if (m_settings.Expand61) { if (buffer->layout.u.mask == AV_CH_LAYOUT_6POINT1_BACK) { ExtendedChannelMap map = {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {6, -2}, {6, -2}, {4, 0}, {5, 0}}; ExtendedChannelMapping(buffer, 8, map); buffer->layout.u.mask = AV_CH_LAYOUT_7POINT1; } else if (buffer->layout.u.mask == AV_CH_LAYOUT_6POINT1) { ExtendedChannelMap map = {{0, 0}, {1, 0}, {2, 0}, {3, 0}, {4, -2}, {4, -2}, {5, 0}, {6, 0}}; ExtendedChannelMapping(buffer, 8, map); buffer->layout.u.mask = AV_CH_LAYOUT_7POINT1; } } if (m_bVolumeStats) { UpdateVolumeStats(*buffer); } // Truncate 24-in-32 to real 24 if (buffer->sfFormat == SampleFormat_32 && buffer->wBitsPerSample && buffer->wBitsPerSample <= 24) { Truncate32Buffer(buffer); } av_channel_layout_uninit(&chMixingLayout); return S_OK; } ================================================ FILE: decoder/LAVAudio/PostProcessor.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once struct BufferDetails; typedef struct ExtendedChannelMap_s { int idx; int factor; } ExtendedChannelMap[8]; inline void ExtChMapSet(ExtendedChannelMap *map, int ch, int idx, int factor) { (*map)[ch].idx = idx; (*map)[ch].factor = factor; } inline void ExtChMapClear(ExtendedChannelMap *map) { for (unsigned i = 0; i < 8; ++i) { (*map)[i].idx = -1; (*map)[i].factor = 0; } } HRESULT ExtendedChannelMapping(BufferDetails *pcm, unsigned uOutChannels, const ExtendedChannelMap extMap); ================================================ FILE: decoder/LAVAudio/dllmain.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Based on the SampleParser Template by GDCL // -------------------------------------------------------------------------------- // Copyright (c) GDCL 2004. All Rights Reserved. // You are free to re-use this as the basis for your own filter development, // provided you retain this copyright notice in the source. // http://www.gdcl.co.uk // -------------------------------------------------------------------------------- #include "stdafx.h" // Initialize the GUIDs #include #include #include "LAVAudio.h" #include "AudioSettingsProp.h" #include "moreuuids.h" #include "IMediaSideDataFFmpeg.h" #include "registry.h" // --- COM factory table and registration code -------------- const AMOVIESETUP_PIN sudpPinsAudioDec[] = {{L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, CLAVAudio::sudPinTypesInCount, CLAVAudio::sudPinTypesIn}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, CLAVAudio::sudPinTypesOutCount, CLAVAudio::sudPinTypesOut}}; const AMOVIESETUP_FILTER sudFilterReg = {&__uuidof(CLAVAudio), // filter clsid L"LAV Audio Decoder", // filter name MERIT_PREFERRED + 3, // merit countof(sudpPinsAudioDec), sudpPinsAudioDec, CLSID_LegacyAmFilterCategory}; // --- COM factory table and registration code -------------- // DirectShow base class COM factory requires this table, // declaring all the COM objects in this DLL CFactoryTemplate g_Templates[] = { // one entry for each CoCreate-able object {sudFilterReg.strName, sudFilterReg.clsID, CreateInstance, nullptr, &sudFilterReg}, // This entry is for the property page. {L"LAV Audio Properties", &CLSID_LAVAudioSettingsProp, CreateInstance, nullptr, nullptr}, {L"LAV Audio Mixer", &CLSID_LAVAudioMixingProp, CreateInstance, nullptr, nullptr}, {L"LAV Audio Format Settings", &CLSID_LAVAudioFormatsProp, CreateInstance, nullptr, nullptr}, {L"LAV Audio Status", &CLSID_LAVAudioStatusProp, CreateInstance, nullptr, nullptr}}; int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); // self-registration entrypoint STDAPI DllRegisterServer() { // base classes will handle registration using the factory template table return AMovieDllRegisterServer2(true); } STDAPI DllUnregisterServer() { // base classes will handle de-registration using the factory template table return AMovieDllRegisterServer2(false); } // if we declare the correct C runtime entrypoint and then forward it to the DShow base // classes we will be sure that both the C/C++ runtimes and the base classes are initialized // correctly extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD dwReason, LPVOID lpReserved) { return DllEntryPoint(reinterpret_cast(hDllHandle), dwReason, lpReserved); } void CALLBACK OpenConfiguration(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) { HRESULT hr = S_OK; CUnknown *pInstance = CreateInstance(nullptr, &hr); IBaseFilter *pFilter = nullptr; pInstance->NonDelegatingQueryInterface(IID_IBaseFilter, (void **)&pFilter); if (pFilter) { pFilter->AddRef(); CBaseDSPropPage::ShowPropPageDialog(pFilter); } delete pInstance; } ================================================ FILE: decoder/LAVAudio/parser/dts.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #define __STDC_CONSTANT_MACROS // Exclude inline asm from being included #define AVCODEC_X86_MATHOPS_H extern "C" { #pragma warning(push) #pragma warning(disable : 4101) #pragma warning(disable : 4244) #pragma warning(disable : 4305) #pragma warning(disable : 5033) #include "libavcodec/avcodec.h" #include "libavcodec/get_bits.h" #include "libavcodec/dca_sample_rate_tab.h" #pragma warning(pop) extern int avpriv_dca_convert_bitstream(const uint8_t *src, int src_size, uint8_t *dst, int max_size); }; #include "dts.h" #include "parser.h" #include struct DTSParserContext { GetBitContext *gb; }; int init_dts_parser(DTSParserContext **pContext) { if (!pContext) return -1; *pContext = (DTSParserContext *)malloc(sizeof(DTSParserContext)); if (*pContext == nullptr) return -1; memset(*pContext, 0, sizeof(DTSParserContext)); (*pContext)->gb = new GetBitContext(); return 0; } int close_dts_parser(DTSParserContext **pContext) { if (!pContext) return -1; delete (*pContext)->gb; free(*pContext); *pContext = nullptr; return 0; } static int parse_dts_xch_header(DTSParserContext *pContext, DTSHeader *pHeader, const uint8_t *pBuffer, unsigned uSize) { GetBitContext *gb = pContext->gb; init_get_bits(gb, pBuffer, uSize << 3); get_bits(gb, 32); /* DCA_XCH_MARKER */ get_bits(gb, 10); /* XCh Frame Size */ pHeader->XChChannelLayout = get_bits(gb, 4); /* Extension Channel Arrangement */ return 0; } static int parse_dts_xch_hd_header(DTSParserContext *pContext, DTSHeader *pHeader, const uint8_t *pBuffer, unsigned uSize) { GetBitContext *gb = pContext->gb; init_get_bits(gb, pBuffer, uSize << 3); /* Huh? */ pHeader->XChChannelLayout = 1; return 0; } static int parse_dts_xxch_header(DTSParserContext *pContext, DTSHeader *pHeader, const uint8_t *pBuffer, unsigned uSize) { GetBitContext *gb = pContext->gb; init_get_bits(gb, pBuffer, uSize << 3); get_bits(gb, 32); /* DCA_XXCH_MARKER */ get_bits(gb, 8); /* ? */ pHeader->XChChannelLayout = get_bits(gb, 2); /* Channels Added? */ get_bits(gb, 6); /* ? */ return 0; } static int parse_dts_xxch_hd_header(DTSParserContext *pContext, DTSHeader *pHeader, const uint8_t *pBuffer, unsigned uSize) { GetBitContext *gb = pContext->gb; init_get_bits(gb, pBuffer, uSize << 3); get_bits(gb, 32); /* DCA_XXCH_MARKER */ get_bits(gb, 8); /* ? */ pHeader->XChChannelLayout = get_bits(gb, 2); /* Channels Added? */ get_bits(gb, 6); /* ? */ return 0; } static int parse_dts_hd_header(DTSParserContext *pContext, DTSHeader *pHeader, const uint8_t *pBuffer, unsigned uSize) { GetBitContext *gb = pContext->gb; init_get_bits(gb, pBuffer, uSize << 3); unsigned NumAudio = 1; unsigned NumAssets = 1; get_bits(gb, 32); /* DCA_HD_MARKER */ get_bits(gb, 8); /* Unknown */ unsigned SubIdx = get_bits(gb, 2); /* Substream Index */ unsigned blownUp = get_bits(gb, 1); /* Blown Up Header */ if (blownUp) { get_bits(gb, 12); /* Header Size */ get_bits(gb, 20); /* HD Size */ } else { get_bits(gb, 8); /* Header Size */ get_bits(gb, 16); /* HD Size */ } unsigned staticFields = get_bits(gb, 1); /* Static fields present */ if (staticFields) { std::vector ActiveExSSMasks; get_bits(gb, 2); /* Reference clock code */ get_bits(gb, 3); /* ExSS frame duration code */ if (get_bits(gb, 1)) /* Timestamp flag */ get_bits(gb, 36); /* Timestamp */ NumAudio = get_bits(gb, 3) + 1; /* Num audio present */ NumAssets = get_bits(gb, 3) + 1; /* Num assets */ for (uint8_t Pos = 0; Pos < NumAudio; Pos++) { uint32_t mask = get_bits(gb, SubIdx + 1); /* Active ExSS masks */ ActiveExSSMasks.push_back(mask); } for (uint8_t Pos = 0; Pos < NumAudio; Pos++) for (uint8_t Pos2 = 0; Pos2 < SubIdx + 1; Pos2 += 2) if (ActiveExSSMasks[Pos] % 2) get_bits(gb, 8); /* Active ExSS masks 2 */ if (get_bits(gb, 1)) { /* Mix Metadata Flag */ get_bits(gb, 2); /* Mix Metadata Adjustment Level */ unsigned bits = get_bits(gb, 2); /* Bits4Mix Mask */ bits = 4 + bits * 4; unsigned num = get_bits(gb, 2) + 1; /* Num Configs */ for (uint8_t Pos = 0; Pos < num; Pos++) get_bits(gb, bits); /* Mix Out Ch Mask */ } } /* END: Static Fields */ // Sizes for (uint8_t Pos = 0; Pos < NumAssets; Pos++) { if (blownUp) { get_bits(gb, 20); /* Size */ } else { get_bits(gb, 16); /* Size */ } } for (uint8_t Pos = 0; Pos < NumAssets; Pos++) { get_bits(gb, 9); /* Asset Size */ get_bits(gb, 3); /* Asset Descriptor Data */ if (staticFields) { if (get_bits(gb, 1)) /* Asset type descriptor present */ get_bits(gb, 4); /* Asset type descriptor */ if (get_bits(gb, 1)) /* Language descriptor present */ get_bits(gb, 24); /* Language descriptor */ if (get_bits(gb, 1)) { /* Info text present */ unsigned bytes = get_bits(gb, 10) + 1; /* Info text size */ for (unsigned Pos = 0; Pos < bytes; Pos++) get_bits(gb, 8); /* Info Text */ } get_bits(gb, 5); /* Bit Resolution */ get_bits(gb, 4); /* Maximum Sample Rate */ pHeader->HDTotalChannels = get_bits(gb, 8) + 1; /* Total Number of Channels */ if (get_bits(gb, 1)) { /* 1 to 1 speaker map present */ unsigned SpeakerActivityMaskBits = 0, SpeakerRemapSetsCount; if (pHeader->HDTotalChannels > 2) get_bits(gb, 1); /* Embedded stereo flag */ if (pHeader->HDTotalChannels > 6) get_bits(gb, 1); /* Embedded 6 channels flag */ if (get_bits(gb, 1)) { /* Speaker Mask Flag */ SpeakerActivityMaskBits = get_bits(gb, 2); /* Speaker mask bits */ SpeakerActivityMaskBits = 4 + SpeakerActivityMaskBits * 4; pHeader->HDSpeakerMask = get_bits(gb, SpeakerActivityMaskBits); /* Speaker activity Mask */ } SpeakerRemapSetsCount = get_bits(gb, 3); /* Speaker remap sets count */ for (uint8_t Pos = 0; Pos < SpeakerRemapSetsCount; Pos++) get_bits(gb, SpeakerActivityMaskBits); /* Standard Speaker Layout mask */ /* unfinished for (uint8_t Pos = 0; Pos < SpeakerRemapSetsCount; Pos++) get_bits(gb, 5); /* NumDecCh4Remap */ } } } return 0; } int parse_dts_header(DTSParserContext *pContext, DTSHeader *pHeader, uint8_t *pBuffer, unsigned uSize) { if (!pContext) return -1; if (!pHeader) return -1; unsigned ExtDescriptor = 0, ExtCoding = 0; uint8_t dts_buffer[32 + AV_INPUT_BUFFER_PADDING_SIZE] = {0}; int ret = avpriv_dca_convert_bitstream(pBuffer, uSize, dts_buffer, 32); bool is16be = (AV_RB32(pBuffer) == DCA_MARKER_RAW_BE); /* Parse Core Header */ if (ret >= 0) { pHeader->HasCore = 1; GetBitContext *gb = pContext->gb; init_get_bits(gb, dts_buffer, 32 << 3); skip_bits_long(gb, 32); /* Sync code */ skip_bits1(gb); /* Frame type */ pHeader->SamplesPerBlock = get_bits(gb, 5) + 1; /* Samples deficit */ pHeader->CRCPresent = get_bits1(gb); /* CRC present */ pHeader->Blocks = get_bits(gb, 7) + 1; /* Number of Blocks */ pHeader->FrameSize = get_bits(gb, 14) + 1; /* Primary (core) Frame Size */ pHeader->ChannelLayout = get_bits(gb, 6); /* Channel configuration */ unsigned sample_index = get_bits(gb, 4); /* Sample frequency index */ pHeader->SampleRate = ff_dca_sample_rates[sample_index]; skip_bits(gb, 5); /* Bitrate index */ skip_bits1(gb); /* Down mix */ skip_bits1(gb); /* Dynamic range */ skip_bits1(gb); /* Time stamp */ skip_bits1(gb); /* Auxiliary data */ skip_bits1(gb); /* HDCD */ ExtDescriptor = get_bits(gb, 3); /* External descriptor */ ExtCoding = get_bits1(gb); /* Extended coding */ skip_bits1(gb); /* ASPF */ pHeader->LFE = get_bits(gb, 2); /* LFE */ skip_bits1(gb); /* Predictor History */ if (pHeader->CRCPresent) skip_bits(gb, 16); /* CRC */ skip_bits1(gb); /* Multirate Interpolator */ skip_bits(gb, 4); /* Encoder Software Revision */ skip_bits(gb, 2); /* Copy history */ pHeader->ES = get_bits1(gb); /* ES */ skip_bits(gb, 2); /* PCMR (source PCM resolution) */ skip_bits1(gb); /* SUMF (Front Sum/Difference Flag) */ skip_bits1(gb); /* SUMS (Surround Sum/Difference Flag) */ skip_bits(gb, 4); /* Dialog Normalization Parameter or Unspecified (dependent on encoder version) */ // Check some basic validity if (uSize < pHeader->FrameSize) return -1; } else { pHeader->HasCore = 0; } if (pHeader->HasCore && !is16be) return 0; // DTS-HD parsing const uint8_t *pHD = nullptr; if (pHeader->HasCore) { // If we have a core, only search after the normal buffer if (uSize > (pHeader->FrameSize + 4)) { // at least 4 bytes extra, could probably insert a minimal size of a HD header, but so what pHD = find_marker32_position(pBuffer + pHeader->FrameSize, uSize - pHeader->FrameSize, DCA_HD_MARKER); } } else { pHD = find_marker32_position(pBuffer, uSize, DCA_HD_MARKER); } if (pHD) { pHeader->IsHD = 1; size_t remaining = uSize - (pHD - pBuffer); parse_dts_hd_header(pContext, pHeader, pHD, (unsigned)remaining); const uint8_t *pXChHD = find_marker32_position(pHD, remaining, DCA_XCH_MARKER); if (pXChHD) { size_t remaining = uSize - (pXChHD - pBuffer); parse_dts_xch_hd_header(pContext, pHeader, pXChHD, (unsigned)remaining); } const uint8_t *pXXChHD = find_marker32_position(pHD, remaining, DCA_XXCH_MARKER); if (pXXChHD) { size_t remaining = uSize - (pXXChHD - pBuffer); parse_dts_xxch_hd_header(pContext, pHeader, pXXChHD, (unsigned)remaining); } } // Handle DTS extensions if (ExtCoding) { size_t coreSize = pHD ? (pHD - pBuffer) : uSize; if (ExtDescriptor == 0 || ExtDescriptor == 3) { const uint8_t *pXCh = find_marker32_position(pBuffer, coreSize, DCA_XCH_MARKER); if (pXCh) { size_t remaining = coreSize - (pXCh - pBuffer); parse_dts_xch_header(pContext, pHeader, pXCh, (unsigned)remaining); } } if (ExtDescriptor == 6) { const uint8_t *pXXCh = find_marker32_position(pBuffer, coreSize, DCA_XXCH_MARKER); if (pXXCh) { size_t remaining = coreSize - (pXXCh - pBuffer); parse_dts_xxch_header(pContext, pHeader, pXXCh, (unsigned)remaining); } } } return 0; } ================================================ FILE: decoder/LAVAudio/parser/dts.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "parser.h" /** DCA syncwords */ #define DCA_MARKER_RAW_BE 0x7FFE8001 #define DCA_MARKER_RAW_LE 0xFE7F0180 #define DCA_MARKER_14B_BE 0x1FFFE800 #define DCA_MARKER_14B_LE 0xFF1F00E8 /** DCA-HD specific block starts with this marker. */ #define DCA_HD_MARKER 0x64582025 /** DCA extension blocks */ #define DCA_XCH_MARKER 0x5a5a5a5a #define DCA_XXCH_MARKER 0x47004A03 struct DTSParserContext; struct DTSHeader { unsigned HasCore; unsigned CRCPresent; unsigned SamplesPerBlock; unsigned Blocks; unsigned FrameSize; unsigned ChannelLayout; unsigned SampleRate; unsigned LFE; // Extensions unsigned ES; unsigned XChChannelLayout; unsigned IsHD; unsigned HDTotalChannels; unsigned HDSpeakerMask; }; int init_dts_parser(DTSParserContext **pContext); int close_dts_parser(DTSParserContext **pContext); int parse_dts_header(DTSParserContext *pContext, DTSHeader *pHeader, uint8_t *pBuffer, unsigned uSize); ================================================ FILE: decoder/LAVAudio/parser/parser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once static inline const uint8_t *find_marker32_position(const uint8_t *pBuffer, size_t uBufSize, uint32_t marker) { uint32_t state = 0; for (size_t i = 0; i < uBufSize; ++i) { state = (state << 8) | pBuffer[i]; if (state == marker) { return pBuffer + (i - 3); } } return nullptr; } ================================================ FILE: decoder/LAVAudio/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by LAVAudio.rc // #define IDD_PROPPAGE_AUDIO_SETTINGS 9 #define IDD_PROPPAGE_AUDIO_MIXING 10 #define IDD_PROPPAGE_FORMATS 11 #define IDD_PROPPAGE_STATUS 12 #define IDS_SETTINGS 101 #define IDS_STATUS 102 #define IDS_FORMATS 103 #define IDI_ICON1 104 #define IDS_MIXER 105 #define IDC_INPUT_STATUS 1013 #define IDC_OUTPUT_STATUS 1026 #define IDC_DRC 1034 #define IDC_DRC_LEVEL 1035 #define IDC_DRC_BOX 1036 #define IDC_DRC_LEVEL_TEXT 1037 #define IDC_LBL_DRC_LEVEL 1038 #define IDC_VOLUME 1039 #define IDC_VOLUME1 1040 #define IDC_VOLUME2 1041 #define IDC_VOLUME3 1042 #define IDC_VOLUME4 1043 #define IDC_VOLUME5 1044 #define IDC_VOLUME6 1045 #define IDC_VOLUME7 1046 #define IDC_VOLUME8 1047 #define IDC_VOLUME1_DESC 1048 #define IDC_VOLUME2_DESC 1049 #define IDC_VOLUME3_DESC 1050 #define IDC_VOLUME4_DESC 1051 #define IDC_VOLUME5_DESC 1052 #define IDC_VOLUME6_DESC 1053 #define IDC_VOLUME7_DESC 1054 #define IDC_VOLUME8_DESC 1055 #define IDC_CODECS 1056 #define IDC_CODECS_NONE 1059 #define IDC_LAVAUDIO_FOOTER 1060 #define IDC_BITSTREAMING 1061 #define IDC_BS_AC3 1062 #define IDC_BS_EAC3 1063 #define IDC_BS_TRUEHD 1064 #define IDC_BS_DTS 1065 #define IDC_BS_DTSHD 1066 #define IDC_BS_FORMATS 1067 #define IDC_BS_DTSHD_FRAMING 1068 #define IDC_BS_OPTIONS 1069 #define IDC_OPTIONS 1070 #define IDC_AUTO_AVSYNC 1071 #define IDC_LBL_INPUT_CODEC 1072 #define IDC_LBL_INPUT_CHANNEL 1073 #define IDC_LBL_INPUT_SAMPLERATE 1074 #define IDC_LBL_INPUT_FORMAT 1075 #define IDC_INPUT_SAMPLERATE 1076 #define IDC_INPUT_CODEC 1077 #define IDC_INPUT_CHANNEL 1078 #define IDC_INPUT_FORMAT 1079 #define IDC_LBL_OUTPUT_CODEC 1080 #define IDC_LBL_OUTPUT_CHANNEL 1081 #define IDC_LBL_OUTPUT_SAMPLERATE 1082 #define IDC_LBL_OUTPUT_FORMAT 1083 #define IDC_OUTPUT_SAMPLERATE 1084 #define IDC_OUTPUT_CODEC 1085 #define IDC_OUTPUT_CHANNEL 1086 #define IDC_OUTPUT_FORMAT 1087 #define IDC_STANDARD_CH_LAYOUT 1088 #define IDC_EXPAND_MONO 1089 #define IDC_EXPAND61 1090 #define IDC_OUTPUT_FORMATS 1091 #define IDC_LBL_OUTPUTFORMATS 1092 #define IDC_OUT_S16 1093 #define IDC_OUT_S24 1094 #define IDC_OUT_S32 1095 #define IDC_OUT_FP32 1096 #define IDC_OUT_U8 1097 #define IDC_LBL_OUTNOTE 1098 #define IDC_GROUP_DELAY 1099 #define IDC_DELAY_ENABLED 1100 #define IDC_DELAY 1101 #define IDC_DELAYSPIN 1102 #define IDC_LBL_FORMATS 1103 #define IDC_MIXING 1104 #define IDC_MIXER 1105 #define IDC_DOWNMIX 1106 #define IDC_OUTPUT_SPEAKERS 1108 #define IDC_UNTOUCHED_STEREO 1109 #define IDC_MIX_SETTINGS 1110 #define IDC_LBL_OUTPUT_SPEAKERS 1111 #define IDC_LBL_MIXING 1112 #define IDC_NORMALIZE_MATRIX 1113 #define IDC_CLIP_PROTECTION 1114 #define IDC_MIXING_MODE 1115 #define IDC_MIXMODE_NORMAL 1116 #define IDC_MIXMODE_DOLBY 1117 #define IDC_MIXMODE_DPL2 1118 #define IDC_MIX_LEVEL_CENTER 1121 #define IDC_MIX_LEVEL_SURROUND 1122 #define IDC_MIX_LEVEL_LFE 1123 #define IDC_LBL_CENTER_LEVEL 1124 #define IDC_LBL_SURROUND_LEVEL 1125 #define IDC_LBL_LFE_LEVEL 1126 #define IDC_MIX_LEVEL_CENTER_TEXT 1127 #define IDC_MIX_LEVEL_SURROUND_TEXT 1128 #define IDC_MIX_LEVEL_LFE_TEXT 1129 #define IDC_LBL_MIXING_LEVEL 1130 #define IDC_TRAYICON 1131 #define IDC_OUT_S16_DITHER 1132 #define IDC_OUTPUT51_LEGACY 1133 #define IDC_BS_FALLBACK 1135 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 106 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1134 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: decoder/LAVAudio/stdafx.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Pre-compiled header #include "stdafx.h" ================================================ FILE: decoder/LAVAudio/stdafx.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // pre-compiled header #pragma once // Support for Version 6.0 styles #pragma comment( \ linker, \ "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #include "common_defines.h" // include headers #include #include #include #include #pragma warning(push) #pragma warning(disable : 4244) extern "C" { #define __STDC_CONSTANT_MACROS #include "libavformat/avformat.h" #include "libavcodec/avcodec.h" #include "libavutil/opt.h" #include "libavutil/intreadwrite.h" #include "libswresample/swresample.h" } #pragma warning(pop) #include "streams.h" #include "DShowUtil.h" #include "growarray.h" ================================================ FILE: decoder/LAVVideo/CCOutputPin.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "CCOutputPin.h" #include "LAVVideo.h" CCCOutputPin::CCCOutputPin(TCHAR *pObjectName, CLAVVideo *pFilter, CCritSec *pcsFilter, HRESULT *phr, LPWSTR pName) : CBaseOutputPin(pObjectName, pFilter, pcsFilter, phr, pName) { m_CCmt.SetType(&MEDIATYPE_DTVCCData); m_CCmt.SetSubtype(&IID_MediaSideDataEIA608CC); m_CCmt.SetFormatType(&FORMAT_None); m_CCmt.SetVariableSize(); m_CCmt.SetSampleSize(4096); } CCCOutputPin::~CCCOutputPin() { } HRESULT CCCOutputPin::Active(void) { return __super::Active(); } STDMETHODIMP CCCOutputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); return __super::NonDelegatingQueryInterface(riid, ppv); } HRESULT CCCOutputPin::DecideBufferSize(IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *pProperties) { CheckPointer(pAlloc, E_POINTER); CheckPointer(pProperties, E_POINTER); HRESULT hr = S_OK; pProperties->cBuffers = max(pProperties->cBuffers, 1); pProperties->cbBuffer = max((ULONG)pProperties->cbBuffer, 4096); // Sanity checks ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAlloc->SetProperties(pProperties, &Actual))) return hr; if (Actual.cbBuffer < pProperties->cbBuffer) return E_FAIL; ASSERT(Actual.cBuffers >= pProperties->cBuffers); return S_OK; } HRESULT CCCOutputPin::CheckMediaType(const CMediaType *pmt) { if (*pmt == m_CCmt) return S_OK; return E_INVALIDARG; } HRESULT CCCOutputPin::GetMediaType(int iPosition, CMediaType *pmt) { if (iPosition < 0 || iPosition > 0) return E_INVALIDARG; *pmt = m_CCmt; return S_OK; } STDMETHODIMP CCCOutputPin::DeliverCCData(BYTE *pDataIn, size_t size, REFERENCE_TIME rtTime) { HRESULT hr; IMediaSample *pSample = nullptr; CHECK_HR(hr = GetDeliveryBuffer(&pSample, nullptr, nullptr, 0)); // Resize buffer if it is too small // This can cause a playback hick-up, we should avoid this if possible by setting a big enough buffer size if (size > (size_t)pSample->GetSize()) { SafeRelease(&pSample); ALLOCATOR_PROPERTIES props, actual; CHECK_HR(hr = m_pAllocator->GetProperties(&props)); // Give us 2 times the requested size, so we don't resize every time props.cbBuffer = (long)(size * 2); if (props.cBuffers > 1) { CHECK_HR(hr = __super::DeliverBeginFlush()); CHECK_HR(hr = __super::DeliverEndFlush()); } CHECK_HR(hr = m_pAllocator->Decommit()); CHECK_HR(hr = m_pAllocator->SetProperties(&props, &actual)); CHECK_HR(hr = m_pAllocator->Commit()); CHECK_HR(hr = GetDeliveryBuffer(&pSample, nullptr, nullptr, 0)); } // Fill the sample BYTE *pData = nullptr; if (FAILED(hr = pSample->GetPointer(&pData)) || !pData) goto done; memcpy(pData, pDataIn, size); // set properties CHECK_HR(hr = pSample->SetActualDataLength((long)size)); CHECK_HR(hr = pSample->SetTime(rtTime != AV_NOPTS_VALUE ? &rtTime : nullptr, rtTime != AV_NOPTS_VALUE ? &rtTime : nullptr)); CHECK_HR(hr = pSample->SetMediaTime(nullptr, nullptr)); // Deliver CHECK_HR(hr = Deliver(pSample)); done: SafeRelease(&pSample); return hr; } ================================================ FILE: decoder/LAVVideo/CCOutputPin.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class CLAVVideo; class CCCOutputPin : public CBaseOutputPin { public: CCCOutputPin(TCHAR *pObjectName, CLAVVideo *pFilter, CCritSec *pcsFilter, HRESULT *phr, LPWSTR pName); virtual ~CCCOutputPin(); // IUnknown DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // CBasePin virtual HRESULT CheckMediaType(const CMediaType *pmt); virtual HRESULT GetMediaType(int iPosition, CMediaType *pmt); virtual HRESULT Active(void); // CBaseOutputPin virtual HRESULT DecideBufferSize(IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *ppropInputRequest); // CCOutputPin STDMETHODIMP DeliverCCData(BYTE *pData, size_t size, REFERENCE_TIME rtTime); private: CMediaType m_CCmt; }; ================================================ FILE: decoder/LAVVideo/DecodeManager.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "DecodeManager.h" #include "LAVVideo.h" #include CDecodeManager::CDecodeManager(CLAVVideo *pLAVVideo) : m_pLAVVideo(pLAVVideo) { WCHAR fileName[1024]; GetModuleFileName(nullptr, fileName, 1024); m_processName = PathFindFileName(fileName); } CDecodeManager::~CDecodeManager(void) { Close(); } STDMETHODIMP CDecodeManager::Close() { CAutoLock decoderLock(this); SAFE_DELETE(m_pDecoder); FreeSideDataCache(); return S_OK; } #define HWFORMAT_ENABLED \ ((codec == AV_CODEC_ID_H264 && m_pLAVVideo->GetHWAccelCodec(HWCodec_H264)) || \ ((codec == AV_CODEC_ID_VC1 || codec == AV_CODEC_ID_WMV3) && m_pLAVVideo->GetHWAccelCodec(HWCodec_VC1)) || \ ((codec == AV_CODEC_ID_MPEG2VIDEO || codec == AV_CODEC_ID_MPEG1VIDEO) && \ m_pLAVVideo->GetHWAccelCodec(HWCodec_MPEG2)) || \ (codec == AV_CODEC_ID_MPEG4 && m_pLAVVideo->GetHWAccelCodec(HWCodec_MPEG4)) || \ (codec == AV_CODEC_ID_HEVC && m_pLAVVideo->GetHWAccelCodec(HWCodec_HEVC)) || \ (codec == AV_CODEC_ID_VP9 && m_pLAVVideo->GetHWAccelCodec(HWCodec_VP9)) || \ (codec == AV_CODEC_ID_AV1 && m_pLAVVideo->GetHWAccelCodec(HWCodec_AV1))) #define HWRESOLUTION_ENABLED \ ((pBMI->biHeight <= 576 && pBMI->biWidth <= 1024 && m_pLAVVideo->GetHWAccelResolutionFlags() & LAVHWResFlag_SD) || \ ((pBMI->biHeight > 576 || pBMI->biWidth > 1024) && pBMI->biHeight <= 1200 && pBMI->biWidth <= 1920 && \ m_pLAVVideo->GetHWAccelResolutionFlags() & LAVHWResFlag_HD) || \ ((pBMI->biHeight > 1200 || pBMI->biWidth > 1920) && m_pLAVVideo->GetHWAccelResolutionFlags() & LAVHWResFlag_UHD)) ILAVDecoder *CDecodeManager::CreateHWAccelDecoder(LAVHWAccel hwAccel) { ILAVDecoder *pDecoder = nullptr; if (hwAccel == HWAccel_CUDA) pDecoder = CreateDecoderCUVID(); else if (hwAccel == HWAccel_QuickSync) pDecoder = CreateDecoderQuickSync(); else if (hwAccel == HWAccel_DXVA2CopyBack) pDecoder = CreateDecoderDXVA2(); else if (hwAccel == HWAccel_DXVA2Native) pDecoder = CreateDecoderDXVA2Native(); else if (hwAccel == HWAccel_D3D11) pDecoder = CreateDecoderD3D11(); return pDecoder; } STDMETHODIMP CDecodeManager::CreateSideDataCache(const MediaSideDataFFMpeg* pSideData) { FreeSideDataCache(); if (pSideData && pSideData->side_data_elems > 0) { m_SideDataCache.side_data = (AVPacketSideData *)av_calloc(pSideData->side_data_elems, sizeof(*m_SideDataCache.side_data)); if (m_SideDataCache.side_data == nullptr) return E_OUTOFMEMORY; for (int i = 0; i < pSideData->side_data_elems; i++) { const AVPacketSideData *src_sd = &pSideData->side_data[i]; AVPacketSideData *dst_sd = &m_SideDataCache.side_data[i]; dst_sd->data = (uint8_t *)av_memdup(src_sd->data, src_sd->size); if (!dst_sd->data) return E_OUTOFMEMORY; dst_sd->type = src_sd->type; dst_sd->size = src_sd->size; m_SideDataCache.side_data_elems++; } } return S_OK; } void CDecodeManager::FreeSideDataCache() { av_packet_side_data_free(&m_SideDataCache.side_data, &m_SideDataCache.side_data_elems); } STDMETHODIMP CDecodeManager::CreateDecoder(const CMediaType *pmt, AVCodecID codec, const MediaSideDataFFMpeg *pSideData) { CAutoLock decoderLock(this); DbgLog( (LOG_TRACE, 10, L"CDecodeThread::CreateDecoder(): Creating new decoder for codec %S", avcodec_get_name(codec))); HRESULT hr = S_OK; BOOL bWMV9 = FALSE; BOOL bHWDecBlackList = _wcsicmp(m_processName.c_str(), L"dllhost.exe") == 0 || _wcsicmp(m_processName.c_str(), L"explorer.exe") == 0 || _wcsicmp(m_processName.c_str(), L"ReClockHelper.dll") == 0; DbgLog((LOG_TRACE, 10, L"-> Process is %s, blacklist: %d", m_processName.c_str(), bHWDecBlackList)); BITMAPINFOHEADER *pBMI = nullptr; videoFormatTypeHandler(*pmt, &pBMI); CreateSideDataCache(pSideData); // disable HW for DVD decoding if (m_pLAVVideo->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) bHWDecBlackList = true; // Try reusing the current HW decoder if (m_pDecoder && m_bHWDecoder && !bHWDecBlackList && !m_bHWDecoderFailed && HWFORMAT_ENABLED && HWRESOLUTION_ENABLED) { DbgLog((LOG_TRACE, 10, L"-> Trying to re-use old HW Decoder")); hr = m_pDecoder->InitDecoder(codec, pmt, &m_SideDataCache); goto done; } SAFE_DELETE(m_pDecoder); LAVHWAccel hwAccel = m_pLAVVideo->GetHWAccel(); if (!bHWDecBlackList && hwAccel != HWAccel_None && !m_bHWDecoderFailed && HWFORMAT_ENABLED && HWRESOLUTION_ENABLED) { DbgLog((LOG_TRACE, 10, L"-> Trying Hardware Codec %d", hwAccel)); m_pDecoder = CreateHWAccelDecoder(hwAccel); m_bHWDecoder = TRUE; } softwaredec: // Fallback for software if (!m_pDecoder) { DbgLog((LOG_TRACE, 10, L"-> No HW Codec, using Software")); m_bHWDecoder = FALSE; if (m_pLAVVideo->GetUseMSWMV9Decoder() && (codec == AV_CODEC_ID_VC1 || codec == AV_CODEC_ID_WMV3) && !m_bWMV9Failed) { m_pDecoder = CreateDecoderWMV9MFT(); bWMV9 = TRUE; } else if (codec == AV_CODEC_ID_H264_MVC) { m_pDecoder = CreateDecoderMSDKMVC(); } else m_pDecoder = CreateDecoderAVCodec(); } DbgLog((LOG_TRACE, 10, L"-> Created Codec '%s'", m_pDecoder->GetDecoderName())); hr = m_pDecoder->InitInterfaces(static_cast(m_pLAVVideo), static_cast(m_pLAVVideo)); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Init Interfaces failed (hr: 0x%x)", hr)); goto done; } hr = m_pDecoder->InitDecoder(codec, pmt, pSideData); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Init Decoder failed (hr: 0x%x)", hr)); goto done; } done: if (FAILED(hr)) { SAFE_DELETE(m_pDecoder); if (m_bHWDecoder) { DbgLog((LOG_TRACE, 10, L"-> Hardware decoder failed to initialize, re-trying with software...")); m_bHWDecoderFailed = TRUE; goto softwaredec; } if (bWMV9) { DbgLog((LOG_TRACE, 10, L"-> WMV9 MFT decoder failed, trying avcodec instead...")); m_bWMV9Failed = TRUE; bWMV9 = FALSE; goto softwaredec; } return hr; } m_Codec = codec; return hr; } STDMETHODIMP CDecodeManager::Decode(IMediaSample *pSample) { CAutoLock decoderLock(this); HRESULT hr = S_OK; if (!m_pDecoder) return E_UNEXPECTED; hr = m_pDecoder->Decode(pSample); // If a hardware decoder indicates a hard failure, we switch back to software // This is used to indicate incompatible media if (FAILED(hr) && m_bHWDecoder) { DbgLog((LOG_TRACE, 10, L"CDecodeManager::Decode(): Hardware decoder indicates failure, switching back to software")); m_bHWDecoderFailed = TRUE; // If we're disabling DXVA2 Native decoding, we need to release resources now if (wcscmp(m_pDecoder->GetDecoderName(), L"dxva2n") == 0 || wcscmp(m_pDecoder->GetDecoderName(), L"d3d11 native") == 0) { m_pLAVVideo->ReleaseAllDXVAResources(); m_pLAVVideo->GetOutputPin()->GetConnected()->BeginFlush(); m_pLAVVideo->GetOutputPin()->GetConnected()->EndFlush(); // TODO: further decoding still fails when DXVA2-Native fails mid-decoding, since we can't inform the // renderer about no longer delivering DXVA surfaces } CMediaType &mt = m_pLAVVideo->GetInputMediaType(); hr = CreateDecoder(&mt, m_Codec, &m_SideDataCache); if (SUCCEEDED(hr)) { hr = m_pDecoder->Decode(pSample); } } return S_OK; } STDMETHODIMP CDecodeManager::Flush() { CAutoLock decoderLock(this); if (!m_pDecoder) return E_UNEXPECTED; return m_pDecoder->Flush(); } STDMETHODIMP CDecodeManager::EndOfStream() { CAutoLock decoderLock(this); if (!m_pDecoder) return E_UNEXPECTED; return m_pDecoder->EndOfStream(); } STDMETHODIMP CDecodeManager::InitAllocator(IMemAllocator **ppAlloc) { CAutoLock decoderLock(this); if (!m_pDecoder) return E_UNEXPECTED; return m_pDecoder->InitAllocator(ppAlloc); } STDMETHODIMP CDecodeManager::PostConnect(IPin *pPin) { CAutoLock decoderLock(this); HRESULT hr = S_OK; if (m_pDecoder) { hr = m_pDecoder->PostConnect(pPin); if (FAILED(hr)) { m_bHWDecoderFailed = TRUE; CMediaType &mt = m_pLAVVideo->GetInputMediaType(); hr = CreateDecoder(&mt, m_Codec, &m_SideDataCache); } } return hr; } STDMETHODIMP CDecodeManager::BreakConnect() { CAutoLock decoderLock(this); if (!m_pDecoder) return E_UNEXPECTED; return m_pDecoder->BreakConnect(); } ================================================ FILE: decoder/LAVVideo/DecodeManager.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "decoders/ILAVDecoder.h" #include "SynchronizedQueue.h" #include "IMediaSideDataFFmpeg.h" class CLAVVideo; class CDecodeManager : protected CCritSec { public: CDecodeManager(CLAVVideo *pLAVVideo); ~CDecodeManager(); static ILAVDecoder *CreateHWAccelDecoder(LAVHWAccel hwAccel); // Decoder management STDMETHODIMP CreateDecoder(const CMediaType *pmt, AVCodecID codec, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP Close(); // Media control STDMETHODIMP Decode(IMediaSample *pSample); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); // Allocator/memory management STDMETHODIMP InitAllocator(IMemAllocator **ppAlloc); STDMETHODIMP PostConnect(IPin *pPin); STDMETHODIMP BreakConnect(); // HWAccel Query STDMETHODIMP_(BOOL) IsHWDecoderActive() { return m_bHWDecoder; } STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName) { return m_pDecoder ? m_pDecoder->GetHWAccelActiveDevice(pstrDeviceName) : E_UNEXPECTED; } // ILAVDecoder (partial) STDMETHODIMP_(const WCHAR *) GetDecoderName() { return m_pDecoder ? m_pDecoder->GetDecoderName() : nullptr; } STDMETHODIMP_(long) GetBufferCount(long *pMaxBuffers) { return m_pDecoder ? m_pDecoder->GetBufferCount(pMaxBuffers) : 4; } STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess) { return m_pDecoder ? m_pDecoder->IsInterlaced(bAllowGuess) : TRUE; } STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { if (m_pDecoder == NULL) { if (pPix) *pPix = LAVPixFmt_None; if (pBpp) *pBpp = 8; if (pPixSoftware) *pPixSoftware = LAVPixFmt_None; return S_FALSE; } return m_pDecoder->GetPixelFormat(pPix, pBpp, pPixSoftware); } STDMETHODIMP_(REFERENCE_TIME) GetFrameDuration() { ASSERT(m_pDecoder); return m_pDecoder->GetFrameDuration(); } STDMETHODIMP HasThreadSafeBuffers() { return m_pDecoder ? m_pDecoder->HasThreadSafeBuffers() : S_FALSE; } STDMETHODIMP SetDirectOutput(BOOL bDirect) { return m_pDecoder ? m_pDecoder->SetDirectOutput(bDirect) : S_FALSE; } private: STDMETHODIMP CreateSideDataCache(const MediaSideDataFFMpeg *pSideData); void FreeSideDataCache(); private: CLAVVideo *m_pLAVVideo = nullptr; ILAVDecoder *m_pDecoder = nullptr; AVCodecID m_Codec = AV_CODEC_ID_NONE; MediaSideDataFFMpeg m_SideDataCache{}; BOOL m_bHWDecoder = FALSE; BOOL m_bHWDecoderFailed = FALSE; BOOL m_bWMV9Failed = FALSE; std::wstring m_processName; }; ================================================ FILE: decoder/LAVVideo/Filtering.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVVideo.h" static void lav_free_lavframe(void *opaque, uint8_t *data) { LAVFrame *frame = (LAVFrame *)opaque; FreeLAVFrameBuffers(frame); SAFE_CO_FREE(opaque); } static void lav_unref_frame(void *opaque, uint8_t *data) { AVBufferRef *buf = (AVBufferRef *)opaque; av_buffer_unref(&buf); } static void avfilter_free_lav_buffer(LAVFrame *pFrame) { av_frame_free((AVFrame **)&pFrame->priv_data); } HRESULT CLAVVideo::Filter(LAVFrame *pFrame) { int ret = 0; BOOL bFlush = pFrame->flags & LAV_FRAME_FLAG_FLUSH; if (m_Decoder.IsInterlaced(FALSE) && m_settings.DeintMode != DeintMode_Disable && m_settings.SWDeintMode != SWDeintMode_None && ((bFlush && m_pFilterGraph) || pFrame->format == LAVPixFmt_YUV420 || pFrame->format == LAVPixFmt_YUV422 || pFrame->format == LAVPixFmt_NV12)) { AVPixelFormat ff_pixfmt = (pFrame->format == LAVPixFmt_YUV420) ? AV_PIX_FMT_YUV420P : (pFrame->format == LAVPixFmt_YUV422) ? AV_PIX_FMT_YUV422P : AV_PIX_FMT_NV12; if (!bFlush && (!m_pFilterGraph || pFrame->format != m_filterPixFmt || pFrame->width != m_filterWidth || pFrame->height != m_filterHeight)) { DbgLog((LOG_TRACE, 10, L":Filter()(init) Initializing software deinterlacing filter...")); if (m_pFilterGraph) { avfilter_graph_free(&m_pFilterGraph); m_pFilterBufferSrc = nullptr; m_pFilterBufferSink = nullptr; } m_filterPixFmt = pFrame->format; m_filterWidth = pFrame->width; m_filterHeight = pFrame->height; char args[512]; const AVFilter *buffersrc = avfilter_get_by_name("buffer"); const AVFilter *buffersink = avfilter_get_by_name("buffersink"); AVFilterInOut *outputs = avfilter_inout_alloc(); AVFilterInOut *inputs = avfilter_inout_alloc(); m_pFilterGraph = avfilter_graph_alloc(); av_opt_set(m_pFilterGraph, "thread_type", "slice", AV_OPT_SEARCH_CHILDREN); av_opt_set_int(m_pFilterGraph, "threads", FFMAX(1, av_cpu_count() / 2), AV_OPT_SEARCH_CHILDREN); // 0/0 is not a valid value for avfilter, make sure it doesn't happen AVRational aspect_ratio = pFrame->aspect_ratio; if (aspect_ratio.num == 0 || aspect_ratio.den == 0) aspect_ratio = {0, 1}; _snprintf_s(args, sizeof(args), "video_size=%dx%d:pix_fmt=%s:time_base=1/10000000:pixel_aspect=%d/%d", pFrame->width, pFrame->height, av_get_pix_fmt_name(ff_pixfmt), pFrame->aspect_ratio.num, pFrame->aspect_ratio.den); ret = avfilter_graph_create_filter(&m_pFilterBufferSrc, buffersrc, "in", args, nullptr, m_pFilterGraph); if (ret < 0) { DbgLog((LOG_TRACE, 10, L"::Filter()(init) Creating the input buffer filter failed with code %d", ret)); avfilter_graph_free(&m_pFilterGraph); goto deliver; } _snprintf_s(args, sizeof(args), "pixel_formats=%s", (ff_pixfmt == AV_PIX_FMT_NV12) ? "nv12,yuv420p" : av_get_pix_fmt_name(ff_pixfmt)); ret = avfilter_graph_create_filter(&m_pFilterBufferSink, buffersink, "out", args, nullptr, m_pFilterGraph); if (ret < 0) { DbgLog((LOG_TRACE, 10, L"::Filter()(init) Creating the buffer sink filter failed with code %d", ret)); avfilter_free(m_pFilterBufferSrc); m_pFilterBufferSrc = nullptr; avfilter_graph_free(&m_pFilterGraph); goto deliver; } /* Endpoints for the filter graph. */ outputs->name = av_strdup("in"); outputs->filter_ctx = m_pFilterBufferSrc; outputs->pad_idx = 0; outputs->next = nullptr; inputs->name = av_strdup("out"); inputs->filter_ctx = m_pFilterBufferSink; inputs->pad_idx = 0; inputs->next = nullptr; if (m_settings.SWDeintMode == SWDeintMode_YADIF) _snprintf_s(args, sizeof(args), "yadif=mode=%s:parity=auto:deint=interlaced", (m_settings.SWDeintOutput == DeintOutput_FramePerField) ? "send_field" : "send_frame"); else if (m_settings.SWDeintMode == SWDeintMode_W3FDIF_Simple) _snprintf_s(args, sizeof(args), "w3fdif=filter=simple:deint=interlaced:mode=%s:parity=auto", (m_settings.SWDeintOutput == DeintOutput_FramePerField) ? "field" : "frame"); else if (m_settings.SWDeintMode == SWDeintMode_W3FDIF_Complex) _snprintf_s(args, sizeof(args), "w3fdif=filter=complex:deint=interlaced:mode=%s:parity=auto", (m_settings.SWDeintOutput == DeintOutput_FramePerField) ? "field" : "frame"); else if (m_settings.SWDeintMode == SWDeintMode_BWDIF) _snprintf_s(args, sizeof(args), "bwdif=mode=%s:parity=auto:deint=interlaced", (m_settings.SWDeintOutput == DeintOutput_FramePerField) ? "send_field" : "send_frame"); else ASSERT(0); if ((ret = avfilter_graph_parse_ptr(m_pFilterGraph, args, &inputs, &outputs, nullptr)) < 0) { DbgLog((LOG_TRACE, 10, L"::Filter()(init) Parsing the graph failed with code %d", ret)); avfilter_graph_free(&m_pFilterGraph); goto deliver; } if ((ret = avfilter_graph_config(m_pFilterGraph, nullptr)) < 0) { DbgLog((LOG_TRACE, 10, L"::Filter()(init) Configuring the graph failed with code %d", ret)); avfilter_graph_free(&m_pFilterGraph); goto deliver; } DbgLog((LOG_TRACE, 10, L":Filter()(init) avfilter Initialization complete")); } if (!m_pFilterGraph) goto deliver; if (pFrame->direct) { HRESULT hr = DeDirectFrame(pFrame, true); if (FAILED(hr)) { ReleaseFrame(&pFrame); return hr; } } AVFrame *in_frame = nullptr; BOOL refcountedFrame = (m_Decoder.HasThreadSafeBuffers() == S_OK); // When flushing, we feed a NULL frame if (!bFlush) { in_frame = av_frame_alloc(); for (int i = 0; i < 4; i++) { in_frame->data[i] = pFrame->data[i]; in_frame->linesize[i] = (int)pFrame->stride[i]; } in_frame->width = pFrame->width; in_frame->height = pFrame->height; in_frame->format = ff_pixfmt; in_frame->pts = pFrame->rtStart; in_frame->flags |= pFrame->interlaced ? AV_FRAME_FLAG_INTERLACED : 0; in_frame->flags |= pFrame->tff ? AV_FRAME_FLAG_TOP_FIELD_FIRST : 0; in_frame->sample_aspect_ratio = pFrame->aspect_ratio; if (refcountedFrame) { AVBufferRef *pFrameBuf = av_buffer_create(nullptr, 0, lav_free_lavframe, pFrame, 0); const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get((AVPixelFormat)in_frame->format); int planes = (in_frame->format == AV_PIX_FMT_NV12) ? 2 : desc->nb_components; for (int i = 0; i < planes; i++) { int h_shift = (i == 1 || i == 2) ? desc->log2_chroma_h : 0; int plane_size = (in_frame->height >> h_shift) * in_frame->linesize[i]; AVBufferRef *planeRef = av_buffer_ref(pFrameBuf); in_frame->buf[i] = av_buffer_create(in_frame->data[i], plane_size, lav_unref_frame, planeRef, AV_BUFFER_FLAG_READONLY); } av_buffer_unref(&pFrameBuf); } m_FilterPrevFrame = *pFrame; memset(m_FilterPrevFrame.data, 0, sizeof(m_FilterPrevFrame.data)); m_FilterPrevFrame.destruct = nullptr; } else { if (!m_FilterPrevFrame.height) // if height is not set, the frame is most likely not valid return S_OK; *pFrame = m_FilterPrevFrame; } if ((ret = av_buffersrc_write_frame(m_pFilterBufferSrc, in_frame)) < 0) { av_frame_free(&in_frame); goto deliver; } BOOL bFramePerField = (m_settings.SWDeintMode != SWDeintMode_None && m_settings.SWDeintOutput == DeintOutput_FramePerField); AVFrame *out_frame = av_frame_alloc(); HRESULT hrDeliver = S_OK; while (SUCCEEDED(hrDeliver) && (av_buffersink_get_frame(m_pFilterBufferSink, out_frame) >= 0)) { LAVFrame *outFrame = nullptr; AllocateFrame(&outFrame); REFERENCE_TIME rtDuration = pFrame->rtStop - pFrame->rtStart; if (bFramePerField) rtDuration >>= 1; // Copy most settings over outFrame->format = (out_frame->format == AV_PIX_FMT_YUV420P) ? LAVPixFmt_YUV420 : (out_frame->format == AV_PIX_FMT_YUV422P) ? LAVPixFmt_YUV422 : LAVPixFmt_NV12; outFrame->sw_format = outFrame->format; outFrame->bpp = pFrame->bpp; outFrame->ext_format = pFrame->ext_format; outFrame->avgFrameDuration = pFrame->avgFrameDuration; outFrame->flags = pFrame->flags; outFrame->width = out_frame->width; outFrame->height = out_frame->height; outFrame->aspect_ratio = out_frame->sample_aspect_ratio; outFrame->tff = !!(out_frame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST); REFERENCE_TIME pts = av_rescale(out_frame->pts, m_pFilterBufferSink->inputs[0]->time_base.num * 10000000LL, m_pFilterBufferSink->inputs[0]->time_base.den); outFrame->rtStart = pts; outFrame->rtStop = pts + rtDuration; if (bFramePerField) { if (outFrame->avgFrameDuration != AV_NOPTS_VALUE) outFrame->avgFrameDuration /= 2; } for (int i = 0; i < 4; i++) { outFrame->data[i] = out_frame->data[i]; outFrame->stride[i] = out_frame->linesize[i]; } outFrame->destruct = avfilter_free_lav_buffer; outFrame->priv_data = av_frame_alloc(); av_frame_move_ref((AVFrame *)outFrame->priv_data, out_frame); hrDeliver = DeliverToRenderer(outFrame); } if (!refcountedFrame) ReleaseFrame(&pFrame); av_frame_free(&in_frame); av_frame_free(&out_frame); // We EOF'ed the graph, need to close it if (bFlush) { if (m_pFilterGraph) { avfilter_graph_free(&m_pFilterGraph); m_pFilterBufferSrc = nullptr; m_pFilterBufferSink = nullptr; } } return S_OK; } else { m_filterPixFmt = LAVPixFmt_None; deliver: return DeliverToRenderer(pFrame); } } ================================================ FILE: decoder/LAVVideo/LAVPixFmtConverter.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVPixFmtConverter.h" #include "Media.h" #include "decoders/ILAVDecoder.h" #include #include "moreuuids.h" #include #include "rand_sse.h" /* * Availability of custom high-quality converters * x = formatter available, - = fallback using swscale * 1 = up to 14-bit only * in/out YV12 NV12 YV16 YUY2 UYVY YV24 AYUV P010 P210 v210 Y410 v410 P016 * P216 Y416 RGB24 RGB32 YUV420 x x - x x - - - - - * - - - - - x x YUV420bX x x - x1 x1 - - x * - - - - x - - x x YUV422 - - x x x - * - - - - - - - - - x x YUV422bX - - x x * x - - - x - - - - x - x x YUV444 - - * - - - x x - - - - - - - - x x * YUV444bX - - - - - x x - - - x - - - x * x x NV12 x x - x x - - - - - - - - * - - x x P010 - x - - - - - x - - - * - x - - x x YUY2 - - - - - - - - - * - - - - - - - - RGB24 - - - - - - - * - - - - - - - - x - RGB32 - - - - - * - - - - - - - - - - - x ARGB32 - - - * - - - - - - - - - - - - - x RGB48 - - - * - - - - - - - - - - - - x x * * Every processing path has a swscale fallback (even those with a "-" above), every combination of input/output is * possible, just not optimized (ugly and/or slow) */ typedef struct { LAVPixelFormat in_pix_fmt; int maxbpp; LAVOutPixFmts lav_pix_fmts[LAVOutPixFmt_NB + 1]; } LAV_INOUT_PIXFMT_MAP; #define PIXOUT_420_8 LAVOutPixFmt_NV12, LAVOutPixFmt_YV12 #define PIXOUT_422_8 LAVOutPixFmt_YUY2, LAVOutPixFmt_UYVY, LAVOutPixFmt_YV16 #define PIXOUT_444_8 LAVOutPixFmt_YV24, LAVOutPixFmt_AYUV #define PIXOUT_RGB_8 LAVOutPixFmt_RGB32, LAVOutPixFmt_RGB24 #define PIXOUT_420_10 LAVOutPixFmt_P010 #define PIXOUT_422_10 LAVOutPixFmt_P210, LAVOutPixFmt_v210 #define PIXOUT_444_10 LAVOutPixFmt_Y410, LAVOutPixFmt_v410 #define PIXOUT_420_16 LAVOutPixFmt_P016 #define PIXOUT_422_16 LAVOutPixFmt_P216 #define PIXOUT_444_16 LAVOutPixFmt_Y416 #define PIXOUT_RGB_16 LAVOutPixFmt_RGB48 // clang-format off static LAV_INOUT_PIXFMT_MAP lav_pixfmt_map[] = { // Default { LAVPixFmt_None, 8, { PIXOUT_420_8, PIXOUT_420_10, PIXOUT_420_16, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, // 4:2:0 { LAVPixFmt_YUV420, 8, { PIXOUT_420_8, PIXOUT_420_10, PIXOUT_420_16, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_NV12, 8, { PIXOUT_420_8, PIXOUT_420_10, PIXOUT_420_16, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_P016, 10, { PIXOUT_420_10, PIXOUT_420_16, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_P016, 16, { PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_YUV420bX, 10, { PIXOUT_420_10, PIXOUT_420_16, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_YUV420bX, 16, { PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, // 4:2:2 { LAVPixFmt_YUV422, 8, { PIXOUT_422_8, PIXOUT_422_10, PIXOUT_422_16, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_YUY2, 8, { PIXOUT_422_8, PIXOUT_422_10, PIXOUT_422_16, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_YUV422bX, 10, { PIXOUT_422_10, PIXOUT_422_16, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_YUV422bX, 16, { PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_Y216, 10, { PIXOUT_422_10, PIXOUT_422_16, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_Y216, 16, { PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, // 4:4:4 { LAVPixFmt_YUV444, 8, { PIXOUT_444_8, PIXOUT_444_10, PIXOUT_444_16, PIXOUT_RGB_16, PIXOUT_RGB_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_YUV444bX, 10, { PIXOUT_444_10, PIXOUT_444_16, PIXOUT_444_8, PIXOUT_RGB_16, PIXOUT_RGB_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_YUV444bX, 16, { PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_RGB_16, PIXOUT_RGB_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_AYUV, 8, { LAVOutPixFmt_AYUV, LAVOutPixFmt_YV24, PIXOUT_444_10, PIXOUT_444_16, PIXOUT_RGB_16, PIXOUT_RGB_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_Y410, 10, { PIXOUT_444_10, PIXOUT_444_16, PIXOUT_444_8, PIXOUT_RGB_16, PIXOUT_RGB_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_Y416, 16, { PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_RGB_16, PIXOUT_RGB_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, // RGB { LAVPixFmt_RGB24, 8, { LAVOutPixFmt_RGB24, LAVOutPixFmt_RGB32, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_RGB32, 8, { PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_ARGB32, 8, { PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_RGB48, 8, { PIXOUT_RGB_16, PIXOUT_RGB_8, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8 } }, { LAVPixFmt_DXVA2, 8, { PIXOUT_420_8, PIXOUT_420_10, PIXOUT_420_16, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_RGB_16 } }, { LAVPixFmt_DXVA2, 10, { PIXOUT_420_10, PIXOUT_420_16, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_DXVA2, 16, { PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_D3D11, 8, { PIXOUT_420_8, PIXOUT_420_10, PIXOUT_420_16, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8, PIXOUT_RGB_16 } }, { LAVPixFmt_D3D11, 10, { PIXOUT_420_10, PIXOUT_420_16, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, { LAVPixFmt_D3D11, 16, { PIXOUT_420_16, PIXOUT_420_10, PIXOUT_420_8, PIXOUT_422_16, PIXOUT_422_10, PIXOUT_422_8, PIXOUT_RGB_8, PIXOUT_RGB_16, PIXOUT_444_16, PIXOUT_444_10, PIXOUT_444_8 } }, }; LAVOutPixFmtDesc lav_pixfmt_desc[] = { { MEDIASUBTYPE_YV12, 12, 1, 3, { 1, 2, 2 }, { 1, 2, 2 } }, // YV12 { MEDIASUBTYPE_NV12, 12, 1, 2, { 1, 2 }, { 1, 1 } }, // NV12 { MEDIASUBTYPE_YUY2, 16, 2, 0, { 1 }, { 1 } }, // YUY2 (packed) { MEDIASUBTYPE_UYVY, 16, 2, 0, { 1 }, { 1 } }, // UYVY (packed) { MEDIASUBTYPE_AYUV, 32, 4, 0, { 1 }, { 1 } }, // AYUV (packed) { MEDIASUBTYPE_P010, 24, 2, 2, { 1, 2 }, { 1, 1 } }, // P010 { MEDIASUBTYPE_P210, 32, 2, 2, { 1, 1 }, { 1, 1 } }, // P210 { MEDIASUBTYPE_Y410, 32, 4, 0, { 1 }, { 1 } }, // Y410 (packed) { MEDIASUBTYPE_P016, 24, 2, 2, { 1, 2 }, { 1, 1 } }, // P016 { MEDIASUBTYPE_P216, 32, 2, 2, { 1, 1 }, { 1, 1 } }, // P216 { MEDIASUBTYPE_Y416, 64, 8, 0, { 1 }, { 1 } }, // Y416 (packed) { MEDIASUBTYPE_RGB32, 32, 4, 0, { 1 }, { 1 } }, // RGB32 { MEDIASUBTYPE_RGB24, 24, 3, 0, { 1 }, { 1 } }, // RGB24 { FOURCCMap('012v'), 24, 4, 0, { 1 }, { 1 } }, // v210 (packed) { FOURCCMap('014v'), 32, 4, 0, { 1 }, { 1 } }, // v410 (packed) { MEDIASUBTYPE_YV16, 16, 1, 3, { 1, 1, 1 }, { 1, 2, 2 } }, // YV16 { MEDIASUBTYPE_YV24, 24, 1, 3, { 1, 1, 1 }, { 1, 1, 1 } }, // YV24 { FOURCCMap('0BGR'), 48, 6, 0, { 1 }, { 1 } }, // RGB48 }; // clang-format on static LAV_INOUT_PIXFMT_MAP *lookupFormatMap(LAVPixelFormat informat, int bpp, BOOL bFallbackToDefault = TRUE) { for (int i = 0; i < countof(lav_pixfmt_map); ++i) { if (lav_pixfmt_map[i].in_pix_fmt == informat && bpp <= lav_pixfmt_map[i].maxbpp) { return &lav_pixfmt_map[i]; } } if (bFallbackToDefault) return &lav_pixfmt_map[0]; return nullptr; } CLAVPixFmtConverter::CLAVPixFmtConverter() { convert = &CLAVPixFmtConverter::convert_generic; convert_direct = nullptr; m_NumThreads = min(8, max(1, av_cpu_count() / 2)); ZeroMemory(&m_ColorProps, sizeof(m_ColorProps)); } CLAVPixFmtConverter::~CLAVPixFmtConverter() { DestroySWScale(); av_freep(&m_pAlignedBuffer); } LAVOutPixFmts CLAVPixFmtConverter::GetOutputBySubtype(const GUID *guid) { for (int i = 0; i < countof(lav_pixfmt_desc); ++i) { if (lav_pixfmt_desc[i].subtype == *guid) { return (LAVOutPixFmts)i; } } return LAVOutPixFmt_None; } int CLAVPixFmtConverter::GetFilteredFormatCount() { LAV_INOUT_PIXFMT_MAP *pixFmtMap = lookupFormatMap(m_InputPixFmt, m_InBpp); int count = 0; for (int i = 0; i < LAVOutPixFmt_NB; ++i) { if (m_pSettings->GetPixelFormat(pixFmtMap->lav_pix_fmts[i])) count++; } if (count == 0) count = LAVOutPixFmt_NB; return count; } LAVOutPixFmts CLAVPixFmtConverter::GetFilteredFormat(int index) { LAV_INOUT_PIXFMT_MAP *pixFmtMap = lookupFormatMap(m_InputPixFmt, m_InBpp); int actualIndex = -1; for (int i = 0; i < LAVOutPixFmt_NB; ++i) { if (m_pSettings->GetPixelFormat(pixFmtMap->lav_pix_fmts[i])) actualIndex++; if (index == actualIndex) return pixFmtMap->lav_pix_fmts[i]; } // If no format is enabled, we use the fallback formats to avoid catastrophic failure if (index >= LAVOutPixFmt_NB) index = 0; return lav_pixfmt_map[0].lav_pix_fmts[index]; } LAVOutPixFmts CLAVPixFmtConverter::GetPreferredOutput() { return GetFilteredFormat(0); } int CLAVPixFmtConverter::GetNumMediaTypes() { return GetFilteredFormatCount(); } void CLAVPixFmtConverter::GetMediaType(CMediaType *mt, int index, LONG biWidth, LONG biHeight, DWORD dwAspectX, DWORD dwAspectY, REFERENCE_TIME rtAvgTime, BOOL bInterlaced, BOOL bVIH1) { if (index < 0 || index >= GetFilteredFormatCount()) index = 0; LAVOutPixFmts pixFmt = GetFilteredFormat(index); GUID guid = lav_pixfmt_desc[pixFmt].subtype; mt->SetType(&MEDIATYPE_Video); mt->SetSubtype(&guid); BITMAPINFOHEADER *pBIH = nullptr; if (bVIH1) { mt->SetFormatType(&FORMAT_VideoInfo); VIDEOINFOHEADER *vih = (VIDEOINFOHEADER *)mt->ReallocFormatBuffer(sizeof(VIDEOINFOHEADER)); memset(vih, 0, sizeof(VIDEOINFOHEADER)); vih->rcSource.right = vih->rcTarget.right = biWidth; vih->rcSource.bottom = vih->rcTarget.bottom = abs(biHeight); vih->AvgTimePerFrame = rtAvgTime; pBIH = &vih->bmiHeader; } else { mt->SetFormatType(&FORMAT_VideoInfo2); VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)mt->ReallocFormatBuffer(sizeof(VIDEOINFOHEADER2)); memset(vih2, 0, sizeof(VIDEOINFOHEADER2)); // Validate the Aspect Ratio - an AR of 0 crashes VMR-9 if (dwAspectX == 0 || dwAspectY == 0) { dwAspectX = biWidth; dwAspectY = abs(biHeight); } // Always reduce the AR to the smalles fraction int dwX = 0, dwY = 0; av_reduce(&dwX, &dwY, dwAspectX, dwAspectY, max(dwAspectX, dwAspectY)); vih2->rcSource.right = vih2->rcTarget.right = biWidth; vih2->rcSource.bottom = vih2->rcTarget.bottom = abs(biHeight); vih2->AvgTimePerFrame = rtAvgTime; vih2->dwPictAspectRatioX = dwX; vih2->dwPictAspectRatioY = dwY; if (bInterlaced) vih2->dwInterlaceFlags = AMINTERLACE_IsInterlaced | AMINTERLACE_DisplayModeBobOrWeave; pBIH = &vih2->bmiHeader; } pBIH->biSize = sizeof(BITMAPINFOHEADER); pBIH->biWidth = biWidth; pBIH->biHeight = biHeight; pBIH->biBitCount = lav_pixfmt_desc[pixFmt].bpp; pBIH->biPlanes = 1; pBIH->biSizeImage = GetImageSize(biWidth, abs(biHeight), pixFmt); pBIH->biCompression = guid.Data1; if (guid == MEDIASUBTYPE_RGB32 || guid == MEDIASUBTYPE_RGB24) { pBIH->biCompression = BI_RGB; } // Correct implied stride for v210 if (guid == FOURCCMap('012v')) { pBIH->biWidth = FFALIGN(biWidth, 48); } mt->SetSampleSize(pBIH->biSizeImage); mt->SetTemporalCompression(0); } DWORD CLAVPixFmtConverter::GetImageSize(int width, int height, LAVOutPixFmts pixFmt) { if (pixFmt == LAVOutPixFmt_None) pixFmt = m_OutputPixFmt; if (pixFmt == LAVOutPixFmt_None) { ASSERT(0); // Safe value that should work for all pixel formats, just in case this happens return width * height * 16; } if (pixFmt == LAVOutPixFmt_v210) return ((width + 47) / 48) * 128 * height; else { return (width * height * lav_pixfmt_desc[pixFmt].bpp) >> 3; } } BOOL CLAVPixFmtConverter::IsAllowedSubtype(const GUID *guid) { for (int i = 0; i < GetFilteredFormatCount(); ++i) { if (lav_pixfmt_desc[GetFilteredFormat(i)].subtype == *guid) return TRUE; } return FALSE; } void CLAVPixFmtConverter::SelectConvertFunction() { m_RequiredAlignment = 16; m_bRGBConverter = FALSE; convert = nullptr; int cpu = av_get_cpu_flags(); if (m_OutputPixFmt == LAVOutPixFmt_v210 || m_OutputPixFmt == LAVOutPixFmt_v410) { // We assume that every filter that understands v210 will also properly handle it m_RequiredAlignment = 0; } else if ((m_OutputPixFmt == LAVOutPixFmt_RGB32 && (m_InputPixFmt == LAVPixFmt_RGB32 || m_InputPixFmt == LAVPixFmt_ARGB32)) || (m_OutputPixFmt == LAVOutPixFmt_RGB24 && m_InputPixFmt == LAVPixFmt_RGB24) || (m_OutputPixFmt == LAVOutPixFmt_RGB48 && m_InputPixFmt == LAVPixFmt_RGB48) || (m_OutputPixFmt == LAVOutPixFmt_YUY2 && m_InputPixFmt == LAVPixFmt_YUY2) || (m_OutputPixFmt == LAVOutPixFmt_AYUV && m_InputPixFmt == LAVPixFmt_AYUV) || (m_OutputPixFmt == LAVOutPixFmt_Y410 && m_InputPixFmt == LAVPixFmt_Y410) || (m_OutputPixFmt == LAVOutPixFmt_Y416 && m_InputPixFmt == LAVPixFmt_Y416) || (m_OutputPixFmt == LAVOutPixFmt_NV12 && m_InputPixFmt == LAVPixFmt_NV12) || ((m_OutputPixFmt == LAVOutPixFmt_P010 || m_OutputPixFmt == LAVOutPixFmt_P016) && m_InputPixFmt == LAVPixFmt_P016)) { if (cpu & AV_CPU_FLAG_SSE2) convert = &CLAVPixFmtConverter::plane_copy_sse2; else convert = &CLAVPixFmtConverter::plane_copy; m_RequiredAlignment = 0; } else if (m_InputPixFmt == LAVPixFmt_RGB48 && m_OutputPixFmt == LAVOutPixFmt_RGB32 && (cpu & AV_CPU_FLAG_SSSE3)) { convert = &CLAVPixFmtConverter::convert_rgb48_rgb32_ssse3; } else if (cpu & AV_CPU_FLAG_SSE2) { if (m_OutputPixFmt == LAVOutPixFmt_AYUV && m_InputPixFmt == LAVPixFmt_YUV444bX) { convert = &CLAVPixFmtConverter::convert_yuv444_ayuv_dither_le; } else if (m_OutputPixFmt == LAVOutPixFmt_AYUV && m_InputPixFmt == LAVPixFmt_YUV444) { convert = &CLAVPixFmtConverter::convert_yuv444_ayuv; } else if (m_OutputPixFmt == LAVOutPixFmt_Y410 && m_InputPixFmt == LAVPixFmt_YUV444bX && m_InBpp <= 10) { convert = &CLAVPixFmtConverter::convert_yuv444_y410; } else if (((m_OutputPixFmt == LAVOutPixFmt_YV12 || m_OutputPixFmt == LAVOutPixFmt_NV12) && m_InputPixFmt == LAVPixFmt_YUV420bX) || (m_OutputPixFmt == LAVOutPixFmt_YV16 && m_InputPixFmt == LAVPixFmt_YUV422bX) || (m_OutputPixFmt == LAVOutPixFmt_YV24 && m_InputPixFmt == LAVPixFmt_YUV444bX)) { if (m_OutputPixFmt == LAVOutPixFmt_NV12) { convert = &CLAVPixFmtConverter::convert_yuv_yv_nv12_dither_le; } else { convert = &CLAVPixFmtConverter::convert_yuv_yv_nv12_dither_le; } m_RequiredAlignment = 32; } else if (((m_OutputPixFmt == LAVOutPixFmt_P010 || m_OutputPixFmt == LAVOutPixFmt_P016) && m_InputPixFmt == LAVPixFmt_YUV420bX) || ((m_OutputPixFmt == LAVOutPixFmt_P210 || m_OutputPixFmt == LAVOutPixFmt_P216) && m_InputPixFmt == LAVPixFmt_YUV422bX)) { convert = &CLAVPixFmtConverter::convert_yuv420_px1x_le; } else if (m_OutputPixFmt == LAVOutPixFmt_NV12 && m_InputPixFmt == LAVPixFmt_YUV420) { convert = &CLAVPixFmtConverter::convert_yuv420_nv12; m_RequiredAlignment = 32; } else if (m_OutputPixFmt == LAVOutPixFmt_YUY2 && m_InputPixFmt == LAVPixFmt_YUV422) { convert = &CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy<0>; m_RequiredAlignment = 32; } else if (m_OutputPixFmt == LAVOutPixFmt_UYVY && m_InputPixFmt == LAVPixFmt_YUV422) { convert = &CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy<1>; m_RequiredAlignment = 32; } else if ((m_OutputPixFmt == LAVOutPixFmt_RGB32 || m_OutputPixFmt == LAVOutPixFmt_RGB24) && (m_InputPixFmt == LAVPixFmt_YUV420 || m_InputPixFmt == LAVPixFmt_YUV420bX || m_InputPixFmt == LAVPixFmt_YUV422 || m_InputPixFmt == LAVPixFmt_YUV422bX || m_InputPixFmt == LAVPixFmt_YUV444 || m_InputPixFmt == LAVPixFmt_YUV444bX || m_InputPixFmt == LAVPixFmt_NV12 || m_InputPixFmt == LAVPixFmt_P016)) { convert = &CLAVPixFmtConverter::convert_yuv_rgb; if (m_OutputPixFmt == LAVOutPixFmt_RGB32) { m_RequiredAlignment = 4; } m_bRGBConverter = TRUE; } else if (m_OutputPixFmt == LAVOutPixFmt_YV12 && m_InputPixFmt == LAVPixFmt_NV12) { convert = &CLAVPixFmtConverter::convert_nv12_yv12; m_RequiredAlignment = 32; } else if ((m_OutputPixFmt == LAVOutPixFmt_YUY2 || m_OutputPixFmt == LAVOutPixFmt_UYVY) && (m_InputPixFmt == LAVPixFmt_YUV420 || m_InputPixFmt == LAVPixFmt_NV12 || m_InputPixFmt == LAVPixFmt_YUV420bX) && m_InBpp <= 14) { if (m_OutputPixFmt == LAVOutPixFmt_YUY2) { convert = &CLAVPixFmtConverter::convert_yuv420_yuy2<0>; } else { convert = &CLAVPixFmtConverter::convert_yuv420_yuy2<1>; } m_RequiredAlignment = 8; // Pixel alignment of 8 guarantees a byte alignment of 16 } else if ((m_OutputPixFmt == LAVOutPixFmt_YUY2 || m_OutputPixFmt == LAVOutPixFmt_UYVY) && m_InputPixFmt == LAVPixFmt_YUV422bX) { if (m_OutputPixFmt == LAVOutPixFmt_YUY2) { convert = &CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy_dither_le<0>; } else { convert = &CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy_dither_le<1>; } m_RequiredAlignment = 8; // Pixel alignment of 8 guarantees a byte alignment of 16 } else if ((m_OutputPixFmt == LAVOutPixFmt_YV12 && m_InputPixFmt == LAVPixFmt_YUV420) || (m_OutputPixFmt == LAVOutPixFmt_YV16 && m_InputPixFmt == LAVPixFmt_YUV422) || (m_OutputPixFmt == LAVOutPixFmt_YV24 && m_InputPixFmt == LAVPixFmt_YUV444)) { convert = &CLAVPixFmtConverter::convert_yuv_yv; m_RequiredAlignment = 0; } else if (m_InputPixFmt == LAVPixFmt_RGB48 && (m_OutputPixFmt == LAVOutPixFmt_RGB24 || m_OutputPixFmt == LAVOutPixFmt_RGB32)) { if (m_OutputPixFmt == LAVOutPixFmt_RGB32) convert = &CLAVPixFmtConverter::convert_rgb48_rgb<1>; else convert = &CLAVPixFmtConverter::convert_rgb48_rgb<0>; } else if (m_InputPixFmt == LAVPixFmt_P016 && m_OutputPixFmt == LAVOutPixFmt_NV12) { convert = &CLAVPixFmtConverter::convert_p010_nv12_sse2; } else if (m_InputPixFmt == LAVPixFmt_Y216 && (m_OutputPixFmt == LAVOutPixFmt_P210 || m_OutputPixFmt == LAVOutPixFmt_P216) && (cpu & AV_CPU_FLAG_SSE4)) { convert = &CLAVPixFmtConverter::convert_y210_p210_sse4; m_RequiredAlignment = 4; // alignment of four pixel gives us a byte alignment of 16, the absolute minimum requirement } else if (m_InputPixFmt == LAVPixFmt_YUY2 && m_OutputPixFmt == LAVOutPixFmt_YV16) { convert = &CLAVPixFmtConverter::convert_yuy2_yv16_sse2; } } if (convert == nullptr) { convert = &CLAVPixFmtConverter::convert_generic; } SelectConvertFunctionDirect(); } void CLAVPixFmtConverter::SelectConvertFunctionDirect() { convert_direct = nullptr; m_bDirectMode = FALSE; int cpu = av_get_cpu_flags(); if ((m_InputPixFmt == LAVPixFmt_NV12 && m_OutputPixFmt == LAVOutPixFmt_NV12) || (m_InputPixFmt == LAVPixFmt_P016 && (m_OutputPixFmt == LAVOutPixFmt_P010 || m_OutputPixFmt == LAVOutPixFmt_P016))) { if (cpu & AV_CPU_FLAG_SSE4) convert_direct = &CLAVPixFmtConverter::plane_copy_direct_nv12_sse4; else if (cpu & AV_CPU_FLAG_SSE2) convert_direct = &CLAVPixFmtConverter::plane_copy_sse2; else convert_direct = &CLAVPixFmtConverter::plane_copy; } else if ((m_InputPixFmt == LAVPixFmt_YUY2 && m_OutputPixFmt == LAVOutPixFmt_YUY2) || (m_InputPixFmt == LAVPixFmt_AYUV && m_OutputPixFmt == LAVOutPixFmt_AYUV) || (m_InputPixFmt == LAVPixFmt_Y410 && m_OutputPixFmt == LAVOutPixFmt_Y410) || (m_InputPixFmt == LAVPixFmt_Y416 && m_OutputPixFmt == LAVOutPixFmt_Y416)) { if (cpu & AV_CPU_FLAG_SSE4) convert_direct = &CLAVPixFmtConverter::plane_copy_direct_sse4; else if (cpu & AV_CPU_FLAG_SSE2) convert_direct = &CLAVPixFmtConverter::plane_copy_sse2; else convert_direct = &CLAVPixFmtConverter::plane_copy; } else if (m_InputPixFmt == LAVPixFmt_P016 && m_OutputPixFmt == LAVOutPixFmt_NV12) { if (cpu & AV_CPU_FLAG_SSE4) convert_direct = &CLAVPixFmtConverter::convert_p010_nv12_direct_sse4; else if (cpu & AV_CPU_FLAG_SSE2) convert_direct = &CLAVPixFmtConverter::convert_p010_nv12_sse2; } else if (m_InputPixFmt == LAVPixFmt_NV12 && m_OutputPixFmt == LAVOutPixFmt_YV12) { if (cpu & AV_CPU_FLAG_SSE4) convert_direct = &CLAVPixFmtConverter::convert_nv12_yv12_direct_sse4; else if (cpu & AV_CPU_FLAG_SSE2) convert_direct = &CLAVPixFmtConverter::convert_nv12_yv12; } else if (m_InputPixFmt == LAVPixFmt_Y216 && (m_OutputPixFmt == LAVOutPixFmt_P210 || m_OutputPixFmt == LAVOutPixFmt_P216)) { if (cpu & AV_CPU_FLAG_SSE4) convert_direct = &CLAVPixFmtConverter::convert_y210_p210_direct_sse4; } else if (m_InputPixFmt == LAVPixFmt_YUY2 && m_OutputPixFmt == LAVOutPixFmt_YV16) { if (cpu & AV_CPU_FLAG_SSE4) convert_direct = &CLAVPixFmtConverter::convert_yuy2_yv16_direct_sse4; else if (cpu & AV_CPU_FLAG_SSE2) convert_direct = &CLAVPixFmtConverter::convert_yuy2_yv16_sse2; } if (convert_direct != nullptr) m_bDirectMode = TRUE; } HRESULT CLAVPixFmtConverter::Convert(const BYTE *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst, int width, int height, ptrdiff_t dstStride, int planeHeight) { uint8_t *out = dst; ptrdiff_t outStride = dstStride, i; planeHeight = max(height, planeHeight); // Check if we have proper pixel alignment and the dst memory is actually aligned if (m_RequiredAlignment && (FFALIGN(dstStride, m_RequiredAlignment) != dstStride || ((uintptr_t)dst % 16u))) { outStride = FFALIGN(dstStride, m_RequiredAlignment); size_t requiredSize = (outStride * planeHeight * lav_pixfmt_desc[m_OutputPixFmt].bpp) >> 3; if (requiredSize > m_nAlignedBufferSize || !m_pAlignedBuffer) { DbgLog((LOG_TRACE, 10, L"::Convert(): Conversion requires a bigger stride (need: %d, have: %d), allocating buffer...", outStride, dstStride)); av_freep(&m_pAlignedBuffer); m_pAlignedBuffer = (uint8_t *)av_malloc(requiredSize + AV_INPUT_BUFFER_PADDING_SIZE); if (!m_pAlignedBuffer) { return E_FAIL; } m_nAlignedBufferSize = requiredSize; } out = m_pAlignedBuffer; } uint8_t *dstArray[4] = {0}; ptrdiff_t dstStrideArray[4] = {0}; ptrdiff_t byteStride = outStride * lav_pixfmt_desc[m_OutputPixFmt].codedbytes; dstArray[0] = out; dstStrideArray[0] = byteStride; for (i = 1; i < lav_pixfmt_desc[m_OutputPixFmt].planes; ++i) { dstArray[i] = dstArray[i - 1] + dstStrideArray[i - 1] * (planeHeight / lav_pixfmt_desc[m_OutputPixFmt].planeHeight[i - 1]); dstStrideArray[i] = byteStride / lav_pixfmt_desc[m_OutputPixFmt].planeWidth[i]; } HRESULT hr = (this->*convert)(src, srcStride, dstArray, dstStrideArray, width, height, m_InputPixFmt, m_InBpp, m_OutputPixFmt); if (out != dst) { ChangeStride(out, outStride, dst, dstStride, width, height, planeHeight, m_OutputPixFmt); } return hr; } BOOL CLAVPixFmtConverter::IsDirectModeSupported(uintptr_t dst, ptrdiff_t stride) { const int stride_align = ((m_OutputPixFmt == LAVOutPixFmt_YV12 || m_OutputPixFmt == LAVOutPixFmt_YV16) ? 32 : 16); if (FFALIGN(stride, stride_align) != stride || (dst % 16u)) return false; return m_bDirectMode; } HRESULT CLAVPixFmtConverter::ConvertDirect(LAVFrame *pFrame, uint8_t *dst, int width, int height, ptrdiff_t dstStride, int planeHeight) { HRESULT hr = S_OK; planeHeight = max(height, planeHeight); ASSERT(pFrame->direct && pFrame->direct_lock && pFrame->direct_unlock); LAVDirectBuffer buffer{}; if (pFrame->direct_lock(pFrame, &buffer)) { uint8_t *dstArray[4] = {0}; ptrdiff_t dstStrideArray[4] = {0}; ptrdiff_t byteStride = dstStride * lav_pixfmt_desc[m_OutputPixFmt].codedbytes; dstArray[0] = dst; dstStrideArray[0] = byteStride; for (int i = 1; i < lav_pixfmt_desc[m_OutputPixFmt].planes; ++i) { dstArray[i] = dstArray[i - 1] + dstStrideArray[i - 1] * (planeHeight / lav_pixfmt_desc[m_OutputPixFmt].planeHeight[i - 1]); dstStrideArray[i] = byteStride / lav_pixfmt_desc[m_OutputPixFmt].planeWidth[i]; } hr = (this->*convert_direct)(buffer.data, buffer.stride, dstArray, dstStrideArray, width, height, m_InputPixFmt, m_InBpp, m_OutputPixFmt); pFrame->direct_unlock(pFrame); } return hr; } void CLAVPixFmtConverter::ChangeStride(const uint8_t *src, ptrdiff_t srcStride, uint8_t *dst, ptrdiff_t dstStride, int width, int height, int planeHeight, LAVOutPixFmts format) { LAVOutPixFmtDesc desc = lav_pixfmt_desc[format]; int line = 0; // Copy first plane const size_t widthBytes = width * desc.codedbytes; const ptrdiff_t srcStrideBytes = srcStride * desc.codedbytes; const ptrdiff_t dstStrideBytes = dstStride * desc.codedbytes; for (line = 0; line < height; ++line) { memcpy(dst, src, widthBytes); src += srcStrideBytes; dst += dstStrideBytes; } dst += (planeHeight - height) * dstStrideBytes; for (int plane = 1; plane < desc.planes; ++plane) { const size_t planeWidth = widthBytes / desc.planeWidth[plane]; const int activePlaneHeight = height / desc.planeHeight[plane]; const int totalPlaneHeight = planeHeight / desc.planeHeight[plane]; const ptrdiff_t srcPlaneStride = srcStrideBytes / desc.planeWidth[plane]; const ptrdiff_t dstPlaneStride = dstStrideBytes / desc.planeWidth[plane]; for (line = 0; line < activePlaneHeight; ++line) { memcpy(dst, src, planeWidth); src += srcPlaneStride; dst += dstPlaneStride; } dst += (totalPlaneHeight - activePlaneHeight) * dstPlaneStride; } } const uint16_t *CLAVPixFmtConverter::GetRandomDitherCoeffs(int height, int coeffs, int bits, int line) { if (m_pSettings->GetDitherMode() != LAVDither_Random) return nullptr; int totalWidth = 8 * coeffs; if (!m_pRandomDithers || totalWidth > m_ditherWidth || height > m_ditherHeight || bits != m_ditherBits) { if (m_pRandomDithers) _aligned_free(m_pRandomDithers); m_pRandomDithers = nullptr; m_ditherWidth = totalWidth; m_ditherHeight = height; m_ditherBits = bits; m_pRandomDithers = (uint16_t *)_aligned_malloc(m_ditherWidth * m_ditherHeight * 2, 16); if (m_pRandomDithers == nullptr) return nullptr; #ifdef DEBUG LARGE_INTEGER frequency, start, end; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&start); DbgLog((LOG_TRACE, 10, L"Creating dither matrix")); #endif // Seed random number generator time_t seed = time(nullptr); seed >>= 1; srand_sse((unsigned int)seed); bits = (1 << bits); for (int i = 0; i < m_ditherHeight; i++) { uint16_t *ditherline = m_pRandomDithers + (m_ditherWidth * i); for (int j = 0; j < m_ditherWidth; j += 4) { int rnds[4]; rand_sse(rnds); ditherline[j + 0] = rnds[0] % bits; ditherline[j + 1] = rnds[1] % bits; ditherline[j + 2] = rnds[2] % bits; ditherline[j + 3] = rnds[3] % bits; } } #ifdef DEBUG QueryPerformanceCounter(&end); double diff = (end.QuadPart - start.QuadPart) * 1000.0 / frequency.QuadPart; DbgLog((LOG_TRACE, 10, L"Finished creating dither matrix (took %2.3fms)", diff)); #endif } if (line < 0 || line >= m_ditherHeight) line = rand() % m_ditherHeight; return &m_pRandomDithers[line * m_ditherWidth]; } ================================================ FILE: decoder/LAVVideo/LAVPixFmtConverter.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "LAVVideoSettings.h" #include "decoders/ILAVDecoder.h" #include #define CONV_FUNC_PARAMS \ (const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], const ptrdiff_t dstStride[4], \ int width, int height, LAVPixelFormat inputFormat, int bpp, LAVOutPixFmts outputFormat) #define DECLARE_CONV_FUNC(name) HRESULT name CONV_FUNC_PARAMS #define DECLARE_CONV_FUNC_IMPL(name) DECLARE_CONV_FUNC(CLAVPixFmtConverter::name) // Important, when adding new pixel formats, they need to be added in LAVPixFmtConverter.cpp as well to the format // descriptors typedef struct { GUID subtype; int bpp; int codedbytes; int planes; int planeHeight[4]; int planeWidth[4]; } LAVOutPixFmtDesc; typedef struct _RGBCoeffs { __m128i Ysub; __m128i CbCr_center; __m128i rgb_add; __m128i cy; __m128i cR_Cr; __m128i cG_Cb_cG_Cr; __m128i cB_Cb; } RGBCoeffs; typedef int(__stdcall *YUVRGBConversionFunc)(const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV, uint8_t *dst, int width, int height, ptrdiff_t srcStrideY, ptrdiff_t srcStrideUV, ptrdiff_t dstStride, ptrdiff_t sliceYStart, ptrdiff_t sliceYEnd, const RGBCoeffs *coeffs, const uint16_t *dithers); extern LAVOutPixFmtDesc lav_pixfmt_desc[]; class CLAVPixFmtConverter { public: CLAVPixFmtConverter(); ~CLAVPixFmtConverter(); void SetSettings(ILAVVideoSettings *pSettings) { m_pSettings = pSettings; } BOOL SetInputFmt(enum LAVPixelFormat pixfmt, int bpp) { ASSERT(pixfmt != LAVPixFmt_None && pixfmt != LAVPixFmt_D3D11 && pixfmt != LAVPixFmt_DXVA2); if (m_InputPixFmt != pixfmt || m_InBpp != bpp) { m_InputPixFmt = pixfmt; m_InBpp = bpp; DestroySWScale(); SelectConvertFunction(); return TRUE; } return FALSE; } HRESULT SetOutputPixFmt(enum LAVOutPixFmts pix_fmt) { m_OutputPixFmt = pix_fmt; DestroySWScale(); SelectConvertFunction(); return S_OK; } LAVOutPixFmts GetOutputBySubtype(const GUID *guid); LAVOutPixFmts GetPreferredOutput(); LAVOutPixFmts GetOutputPixFmt() { return m_OutputPixFmt; } void SetColorProps(DXVA2_ExtendedFormat props, int RGBOutputRange) { if (props.value != m_ColorProps.value || swsOutputRange != RGBOutputRange) { DestroySWScale(); m_ColorProps = props; swsOutputRange = RGBOutputRange; } } int GetNumMediaTypes(); void GetMediaType(CMediaType *mt, int index, LONG biWidth, LONG biHeight, DWORD dwAspectX, DWORD dwAspectY, REFERENCE_TIME rtAvgTime, BOOL bInterlaced = TRUE, BOOL bVIH1 = FALSE); BOOL IsAllowedSubtype(const GUID *guid); HRESULT Convert(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst, int width, int height, ptrdiff_t dstStride, int planeHeight); HRESULT ConvertDirect(LAVFrame *pFrame, uint8_t *dst, int width, int height, ptrdiff_t dstStride, int planeHeight); BOOL IsRGBConverterActive() { return m_bRGBConverter; } BOOL IsDirectModeSupported(uintptr_t dst, ptrdiff_t stride); DWORD GetImageSize(int width, int height, LAVOutPixFmts pixFmt = LAVOutPixFmt_None); private: AVPixelFormat GetFFInput() { return getFFPixelFormatFromLAV(m_InputPixFmt, m_InBpp); } int GetFilteredFormatCount(); LAVOutPixFmts GetFilteredFormat(int index); void SelectConvertFunction(); void SelectConvertFunctionDirect(); // Helper functions for convert_generic HRESULT swscale_scale(enum AVPixelFormat srcPix, enum AVPixelFormat dstPix, const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4], LAVOutPixFmtDesc pixFmtDesc, bool swapPlanes12 = false); HRESULT ConvertTo422Packed(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4]); HRESULT ConvertToAYUV(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4]); HRESULT ConvertToPX1X(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4], int chromaVertical); HRESULT ConvertToY410(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4]); HRESULT ConvertToY416(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4]); HRESULT ConvertTov210(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4]); HRESULT ConvertTov410(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[4], int width, int height, const ptrdiff_t dstStride[4]); void DestroySWScale() { if (m_pSwsContext) sws_freeContext(m_pSwsContext); m_pSwsContext = nullptr; if (m_rgbCoeffs) _aligned_free(m_rgbCoeffs); m_rgbCoeffs = nullptr; if (m_pRandomDithers) _aligned_free(m_pRandomDithers); m_pRandomDithers = nullptr; }; SwsContext *GetSWSContext(int width, int height, enum AVPixelFormat srcPix, enum AVPixelFormat dstPix, int flags); void ChangeStride(const uint8_t *src, ptrdiff_t srcStride, uint8_t *dst, ptrdiff_t dstStride, int width, int height, int planeHeight, LAVOutPixFmts format); typedef HRESULT(CLAVPixFmtConverter::*ConverterFn) CONV_FUNC_PARAMS; // Conversion function pointer ConverterFn convert; ConverterFn convert_direct; // Pixel Implementations DECLARE_CONV_FUNC(convert_generic); DECLARE_CONV_FUNC(plane_copy); DECLARE_CONV_FUNC(plane_copy_sse2); DECLARE_CONV_FUNC(convert_yuv444_ayuv); DECLARE_CONV_FUNC(convert_yuv444_ayuv_dither_le); DECLARE_CONV_FUNC(convert_yuv444_y410); DECLARE_CONV_FUNC(convert_yuv420_px1x_le); DECLARE_CONV_FUNC(convert_yuv420_nv12); DECLARE_CONV_FUNC(convert_yuv_yv); DECLARE_CONV_FUNC(convert_nv12_yv12); DECLARE_CONV_FUNC(convert_p010_nv12_sse2); DECLARE_CONV_FUNC(convert_y210_p210_sse4); template DECLARE_CONV_FUNC(convert_yuv420_yuy2); template DECLARE_CONV_FUNC(convert_yuv422_yuy2_uyvy); template DECLARE_CONV_FUNC(convert_yuv422_yuy2_uyvy_dither_le); template DECLARE_CONV_FUNC(convert_yuv_yv_nv12_dither_le); DECLARE_CONV_FUNC(convert_rgb48_rgb32_ssse3); template DECLARE_CONV_FUNC(convert_rgb48_rgb); DECLARE_CONV_FUNC(plane_copy_direct_sse4); DECLARE_CONV_FUNC(plane_copy_direct_nv12_sse4); DECLARE_CONV_FUNC(convert_nv12_yv12_direct_sse4); DECLARE_CONV_FUNC(convert_p010_nv12_direct_sse4); DECLARE_CONV_FUNC(convert_y210_p210_direct_sse4); DECLARE_CONV_FUNC(convert_yuy2_yv16_sse2); DECLARE_CONV_FUNC(convert_yuy2_yv16_direct_sse4); DECLARE_CONV_FUNC(convert_yuv_rgb); const RGBCoeffs *getRGBCoeffs(int width, int height); void InitRGBConvDispatcher(); const uint16_t *GetRandomDitherCoeffs(int height, int coeffs, int bits, int line); private: LAVPixelFormat m_InputPixFmt = LAVPixFmt_None; LAVOutPixFmts m_OutputPixFmt = LAVOutPixFmt_YV12; int m_InBpp = 0; BOOL m_bDirectMode = false; int swsWidth = 0; int swsHeight = 0; int swsOutputRange = 0; DXVA2_ExtendedFormat m_ColorProps; ptrdiff_t m_RequiredAlignment = 0; SwsContext *m_pSwsContext = nullptr; size_t m_nAlignedBufferSize = 0; uint8_t *m_pAlignedBuffer = nullptr; int m_NumThreads = 1; ILAVVideoSettings *m_pSettings = nullptr; RGBCoeffs *m_rgbCoeffs = nullptr; BOOL m_bRGBConverter = FALSE; BOOL m_bRGBConvInit = FALSE; // [out32][dithermode][ycgco][format][shift] YUVRGBConversionFunc m_RGBConvFuncs[2][2][2][LAVPixFmt_NB][9]; uint16_t *m_pRandomDithers = nullptr; int m_ditherWidth = 0; int m_ditherHeight = 0; int m_ditherBits = 0; }; ================================================ FILE: decoder/LAVVideo/LAVVideo.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVVideo.h" #include "VideoSettingsProp.h" #include "Media.h" #include #include "VideoInputPin.h" #include "VideoOutputPin.h" #include "moreuuids.h" #include "registry.h" #include "resource.h" #include "IMediaSample3D.h" #include "IMediaSideDataFFmpeg.h" #include #include "parsers/VC1HeaderParser.h" #include "parsers/MPEG2HeaderParser.h" #include #include #include #pragma warning(disable : 4355) CLAVVideo::CLAVVideo(LPUNKNOWN pUnk, HRESULT *phr) : CTransformFilter(NAME("LAV Video Decoder"), 0, __uuidof(CLAVVideo)) , m_Decoder(this) { *phr = S_OK; m_pInput = new CVideoInputPin(TEXT("CVideoInputPin"), this, phr, L"Input"); ASSERT(SUCCEEDED(*phr)); m_pOutput = new CVideoOutputPin(TEXT("CVideoOutputPin"), this, phr, L"Output"); ASSERT(SUCCEEDED(*phr)); memset(&m_LAVPinInfo, 0, sizeof(m_LAVPinInfo)); memset(&m_FilterPrevFrame, 0, sizeof(m_FilterPrevFrame)); memset(&m_SideData, 0, sizeof(m_SideData)); LoadSettings(); m_PixFmtConverter.SetSettings(this); #ifdef DEBUG DbgSetModuleLevel(LOG_TRACE, DWORD_MAX); DbgSetModuleLevel(LOG_ERROR, DWORD_MAX); DbgSetModuleLevel(LOG_CUSTOM1, DWORD_MAX); // FFMPEG messages use custom1 #endif } CLAVVideo::~CLAVVideo() { SAFE_DELETE(m_pTrayIcon); ReleaseLastSequenceFrame(); m_Decoder.Close(); if (m_pFilterGraph) avfilter_graph_free(&m_pFilterGraph); m_pFilterBufferSrc = nullptr; m_pFilterBufferSink = nullptr; if (m_SubtitleConsumer) m_SubtitleConsumer->DisconnectProvider(); SafeRelease(&m_SubtitleConsumer); SAFE_DELETE(m_pSubtitleInput); SAFE_DELETE(m_pCCOutputPin); } HRESULT CLAVVideo::CreateTrayIcon() { CAutoLock cObjectLock(m_pLock); if (m_pTrayIcon) return E_UNEXPECTED; if (CBaseTrayIcon::ProcessBlackList()) return S_FALSE; m_pTrayIcon = new CBaseTrayIcon(this, TEXT(LAV_VIDEO), IDI_ICON1); return S_OK; } STDMETHODIMP CLAVVideo::JoinFilterGraph(IFilterGraph *pGraph, LPCWSTR pName) { CAutoLock cObjectLock(m_pLock); HRESULT hr = __super::JoinFilterGraph(pGraph, pName); if (pGraph && !m_pTrayIcon && m_settings.TrayIcon) { CreateTrayIcon(); } else if (!pGraph && m_pTrayIcon) { SAFE_DELETE(m_pTrayIcon); } return hr; } HRESULT CLAVVideo::LoadDefaults() { m_settings.TrayIcon = FALSE; // Set Defaults m_settings.StreamAR = 2; m_settings.NumThreads = 0; m_settings.DeintFieldOrder = DeintFieldOrder_Auto; m_settings.DeintMode = DeintMode_Auto; m_settings.RGBRange = 2; // Full range default for (int i = 0; i < Codec_VideoNB; ++i) m_settings.bFormats[i] = TRUE; m_settings.bFormats[Codec_RV12] = FALSE; m_settings.bFormats[Codec_QPEG] = FALSE; m_settings.bFormats[Codec_MSRLE] = FALSE; m_settings.bDVDVideo = TRUE; m_settings.bMSWMV9DMO = TRUE; // Raw formats, off by default m_settings.bFormats[Codec_v210] = FALSE; for (int i = 0; i < LAVOutPixFmt_NB; ++i) m_settings.bPixFmts[i] = TRUE; m_settings.bPixFmts[LAVOutPixFmt_YV16] = FALSE; m_settings.bPixFmts[LAVOutPixFmt_AYUV] = FALSE; m_settings.HWAccel = HWAccel_None; for (int i = 0; i < HWCodec_NB; ++i) m_settings.bHWFormats[i] = TRUE; m_settings.bHWFormats[HWCodec_MPEG4] = FALSE; m_settings.bHWFormats[HWCodec_H264MVC] = FALSE; m_settings.HWAccelResFlags = LAVHWResFlag_SD | LAVHWResFlag_HD | LAVHWResFlag_UHD; m_settings.HWAccelCUVIDXVA = TRUE; m_settings.HWDeintMode = HWDeintMode_Weave; m_settings.HWDeintOutput = DeintOutput_FramePerField; m_settings.SWDeintMode = SWDeintMode_None; m_settings.SWDeintOutput = DeintOutput_FramePerField; m_settings.DitherMode = LAVDither_Random; m_settings.HWAccelDeviceDXVA2 = LAVHWACCEL_DEVICE_DEFAULT; m_settings.HWAccelDeviceDXVA2Desc = 0; m_settings.HWAccelDeviceD3D11 = LAVHWACCEL_DEVICE_DEFAULT; m_settings.HWAccelDeviceD3D11Desc = 0; m_settings.bH264MVCOverride = TRUE; m_settings.bCCOutputPinEnabled = FALSE; return S_OK; } static const WCHAR *pixFmtSettingsMap[LAVOutPixFmt_NB] = {L"yv12", L"nv12", L"yuy2", L"uyvy", L"ayuv", L"p010", L"p210", L"y410", L"p016", L"p216", L"y416", L"rgb32", L"rgb24", L"v210", L"v410", L"yv16", L"yv24", L"rgb48"}; HRESULT CLAVVideo::LoadSettings() { LoadDefaults(); if (m_bRuntimeConfig) return S_FALSE; ReadSettings(HKEY_LOCAL_MACHINE); return ReadSettings(HKEY_CURRENT_USER); } HRESULT CLAVVideo::ReadSettings(HKEY rootKey) { HRESULT hr; BOOL bFlag; DWORD dwVal; CRegistry reg = CRegistry(rootKey, LAVC_VIDEO_REGISTRY_KEY, hr, TRUE); if (SUCCEEDED(hr)) { bFlag = reg.ReadBOOL(L"TrayIcon", hr); if (SUCCEEDED(hr)) m_settings.TrayIcon = bFlag; dwVal = reg.ReadDWORD(L"StreamAR", hr); if (SUCCEEDED(hr)) m_settings.StreamAR = dwVal; dwVal = reg.ReadDWORD(L"NumThreads", hr); if (SUCCEEDED(hr)) m_settings.NumThreads = dwVal; dwVal = reg.ReadDWORD(L"DeintFieldOrder", hr); if (SUCCEEDED(hr)) m_settings.DeintFieldOrder = dwVal; // Load deprecated deint flags and convert them bFlag = reg.ReadBOOL(L"DeintAggressive", hr); if (SUCCEEDED(hr) && bFlag) m_settings.DeintMode = DeintMode_Aggressive; bFlag = reg.ReadBOOL(L"DeintForce", hr); if (SUCCEEDED(hr) && bFlag) m_settings.DeintMode = DeintMode_Force; bFlag = reg.ReadBOOL(L"DeintTreatAsProgressive", hr); if (SUCCEEDED(hr) && bFlag) m_settings.DeintMode = DeintMode_Disable; dwVal = reg.ReadDWORD(L"DeintMode", hr); if (SUCCEEDED(hr)) m_settings.DeintMode = (LAVDeintMode)dwVal; dwVal = reg.ReadDWORD(L"RGBRange", hr); if (SUCCEEDED(hr)) m_settings.RGBRange = dwVal; dwVal = reg.ReadDWORD(L"SWDeintMode", hr); if (SUCCEEDED(hr)) m_settings.SWDeintMode = dwVal; dwVal = reg.ReadDWORD(L"SWDeintOutput", hr); if (SUCCEEDED(hr)) m_settings.SWDeintOutput = dwVal; dwVal = reg.ReadDWORD(L"DitherMode", hr); if (SUCCEEDED(hr)) m_settings.DitherMode = dwVal; bFlag = reg.ReadBOOL(L"DVDVideo", hr); if (SUCCEEDED(hr)) m_settings.bDVDVideo = bFlag; bFlag = reg.ReadBOOL(L"MSWMV9DMO", hr); if (SUCCEEDED(hr)) m_settings.bMSWMV9DMO = bFlag; } CRegistry regF = CRegistry(rootKey, LAVC_VIDEO_REGISTRY_KEY_FORMATS, hr, TRUE); if (SUCCEEDED(hr)) { for (int i = 0; i < Codec_VideoNB; ++i) { const codec_config_t *info = get_codec_config((LAVVideoCodec)i); ATL::CA2W name(info->name); bFlag = regF.ReadBOOL(name, hr); if (SUCCEEDED(hr)) m_settings.bFormats[i] = bFlag; } } CRegistry regP = CRegistry(rootKey, LAVC_VIDEO_REGISTRY_KEY_OUTPUT, hr, TRUE); if (SUCCEEDED(hr)) { for (int i = 0; i < LAVOutPixFmt_NB; ++i) { bFlag = regP.ReadBOOL(pixFmtSettingsMap[i], hr); if (SUCCEEDED(hr)) m_settings.bPixFmts[i] = bFlag; } // Force disable, for future use m_settings.bPixFmts[LAVOutPixFmt_YV16] = FALSE; } CRegistry regHW = CRegistry(rootKey, LAVC_VIDEO_REGISTRY_KEY_HWACCEL, hr, TRUE); if (SUCCEEDED(hr)) { dwVal = regHW.ReadDWORD(L"HWAccel", hr); if (SUCCEEDED(hr)) m_settings.HWAccel = dwVal; bFlag = regHW.ReadBOOL(L"h264", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_H264] = bFlag; bFlag = regHW.ReadBOOL(L"vc1", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_VC1] = bFlag; bFlag = regHW.ReadBOOL(L"mpeg2", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_MPEG2] = bFlag; bFlag = regHW.ReadBOOL(L"mpeg4", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_MPEG4] = bFlag; bFlag = regHW.ReadBOOL(L"hevc", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_HEVC] = bFlag; bFlag = regHW.ReadBOOL(L"vp9", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_VP9] = bFlag; bFlag = regHW.ReadBOOL(L"h264mvc", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_H264MVC] = bFlag; bFlag = regHW.ReadBOOL(L"av1", hr); if (SUCCEEDED(hr)) m_settings.bHWFormats[HWCodec_AV1] = bFlag; dwVal = regHW.ReadDWORD(L"HWResFlags", hr); if (SUCCEEDED(hr)) m_settings.HWAccelResFlags = dwVal; dwVal = regHW.ReadDWORD(L"HWDeintMode", hr); if (SUCCEEDED(hr)) m_settings.HWDeintMode = dwVal; dwVal = regHW.ReadDWORD(L"HWDeintOutput", hr); if (SUCCEEDED(hr)) m_settings.HWDeintOutput = dwVal; dwVal = regHW.ReadDWORD(L"HWAccelDeviceDXVA2", hr); if (SUCCEEDED(hr)) m_settings.HWAccelDeviceDXVA2 = dwVal; dwVal = regHW.ReadDWORD(L"HWAccelDeviceDXVA2Desc", hr); if (SUCCEEDED(hr)) m_settings.HWAccelDeviceDXVA2Desc = dwVal; dwVal = regHW.ReadDWORD(L"HWAccelDeviceD3D11", hr); if (SUCCEEDED(hr)) m_settings.HWAccelDeviceD3D11 = dwVal; dwVal = regHW.ReadDWORD(L"HWAccelDeviceD3D11Desc", hr); if (SUCCEEDED(hr)) m_settings.HWAccelDeviceD3D11Desc = dwVal; bFlag = regHW.ReadBOOL(L"HWAccelCUVIDXVA", hr); if (SUCCEEDED(hr)) m_settings.HWAccelCUVIDXVA = bFlag; } return S_OK; } HRESULT CLAVVideo::SaveSettings() { if (m_bRuntimeConfig) return S_FALSE; HRESULT hr; CreateRegistryKey(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY); CRegistry reg = CRegistry(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY, hr); if (SUCCEEDED(hr)) { reg.WriteBOOL(L"TrayIcon", m_settings.TrayIcon); reg.WriteDWORD(L"StreamAR", m_settings.StreamAR); reg.WriteDWORD(L"NumThreads", m_settings.NumThreads); reg.WriteDWORD(L"DeintFieldOrder", m_settings.DeintFieldOrder); reg.WriteDWORD(L"DeintMode", m_settings.DeintMode); reg.WriteDWORD(L"RGBRange", m_settings.RGBRange); CreateRegistryKey(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY_FORMATS); CRegistry regF = CRegistry(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY_FORMATS, hr); for (int i = 0; i < Codec_VideoNB; ++i) { const codec_config_t *info = get_codec_config((LAVVideoCodec)i); ATL::CA2W name(info->name); regF.WriteBOOL(name, m_settings.bFormats[i]); } reg.WriteBOOL(L"DVDVideo", m_settings.bDVDVideo); reg.WriteBOOL(L"MSWMV9DMO", m_settings.bMSWMV9DMO); CreateRegistryKey(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY_OUTPUT); CRegistry regP = CRegistry(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY_OUTPUT, hr); for (int i = 0; i < LAVOutPixFmt_NB; ++i) { regP.WriteBOOL(pixFmtSettingsMap[i], m_settings.bPixFmts[i]); } CreateRegistryKey(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY_HWACCEL); CRegistry regHW = CRegistry(HKEY_CURRENT_USER, LAVC_VIDEO_REGISTRY_KEY_HWACCEL, hr); regHW.WriteDWORD(L"HWAccel", m_settings.HWAccel); regHW.WriteBOOL(L"h264", m_settings.bHWFormats[HWCodec_H264]); regHW.WriteBOOL(L"vc1", m_settings.bHWFormats[HWCodec_VC1]); regHW.WriteBOOL(L"mpeg2", m_settings.bHWFormats[HWCodec_MPEG2]); regHW.WriteBOOL(L"mpeg4", m_settings.bHWFormats[HWCodec_MPEG4]); regHW.WriteBOOL(L"hevc", m_settings.bHWFormats[HWCodec_HEVC]); regHW.WriteBOOL(L"vp9", m_settings.bHWFormats[HWCodec_VP9]); regHW.WriteBOOL(L"h264mvc", m_settings.bHWFormats[HWCodec_H264MVC]); regHW.WriteBOOL(L"av1", m_settings.bHWFormats[HWCodec_AV1]); regHW.WriteDWORD(L"HWResFlags", m_settings.HWAccelResFlags); regHW.WriteDWORD(L"HWDeintMode", m_settings.HWDeintMode); regHW.WriteDWORD(L"HWDeintOutput", m_settings.HWDeintOutput); regHW.WriteDWORD(L"HWAccelDeviceDXVA2", m_settings.HWAccelDeviceDXVA2); regHW.WriteDWORD(L"HWAccelDeviceDXVA2Desc", m_settings.HWAccelDeviceDXVA2Desc); regHW.WriteDWORD(L"HWAccelDeviceD3D11", m_settings.HWAccelDeviceD3D11); regHW.WriteDWORD(L"HWAccelDeviceD3D11Desc", m_settings.HWAccelDeviceD3D11Desc); regHW.WriteBOOL(L"HWAccelCUVIDXVA", m_settings.HWAccelCUVIDXVA); reg.WriteDWORD(L"SWDeintMode", m_settings.SWDeintMode); reg.WriteDWORD(L"SWDeintOutput", m_settings.SWDeintOutput); reg.WriteDWORD(L"DitherMode", m_settings.DitherMode); reg.DeleteKey(L"DeintAggressive"); reg.DeleteKey(L"DeintForce"); reg.DeleteKey(L"DeintTreatAsProgressive"); } return S_OK; } // IUnknown STDMETHODIMP CLAVVideo::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; return QI(ISpecifyPropertyPages) QI(ISpecifyPropertyPages2) QI(IPropertyBag) QI2(ILAVVideoSettings) QI2(ILAVVideoStatus) __super::NonDelegatingQueryInterface(riid, ppv); } // ISpecifyPropertyPages2 STDMETHODIMP CLAVVideo::GetPages(CAUUID *pPages) { CheckPointer(pPages, E_POINTER); pPages->cElems = 2; pPages->pElems = (GUID *)CoTaskMemAlloc(sizeof(GUID) * pPages->cElems); if (pPages->pElems == nullptr) { return E_OUTOFMEMORY; } pPages->pElems[0] = CLSID_LAVVideoSettingsProp; pPages->pElems[1] = CLSID_LAVVideoFormatsProp; return S_OK; } STDMETHODIMP CLAVVideo::CreatePage(const GUID &guid, IPropertyPage **ppPage) { CheckPointer(ppPage, E_POINTER); HRESULT hr = S_OK; if (*ppPage != nullptr) return E_INVALIDARG; if (guid == CLSID_LAVVideoSettingsProp) *ppPage = new CLAVVideoSettingsProp(nullptr, &hr); else if (guid == CLSID_LAVVideoFormatsProp) *ppPage = new CLAVVideoFormatsProp(nullptr, &hr); if (SUCCEEDED(hr) && *ppPage) { (*ppPage)->AddRef(); return S_OK; } else { SAFE_DELETE(*ppPage); return E_FAIL; } } STDMETHODIMP_(LPWSTR) CLAVVideo::GetFileExtension() { if (m_strExtension.empty()) { m_strExtension = L""; IFileSourceFilter *pSource = nullptr; if (SUCCEEDED(FindIntefaceInGraph(m_pInput, IID_IFileSourceFilter, (void **)&pSource))) { LPOLESTR pwszFile = nullptr; if (SUCCEEDED(pSource->GetCurFile(&pwszFile, nullptr)) && pwszFile) { LPWSTR pwszExtension = PathFindExtensionW(pwszFile); m_strExtension = std::wstring(pwszExtension); CoTaskMemFree(pwszFile); } SafeRelease(&pSource); } } size_t len = m_strExtension.size() + 1; LPWSTR pszExtension = (LPWSTR)CoTaskMemAlloc(sizeof(WCHAR) * len); if (!pszExtension) return nullptr; wcscpy_s(pszExtension, len, m_strExtension.c_str()); return pszExtension; } // CTransformFilter int CLAVVideo::GetPinCount() { int nCount = 2; if (m_pSubtitleInput) nCount++; if (m_pCCOutputPin) nCount++; return nCount; } CBasePin *CLAVVideo::GetPin(int n) { if (n >= 2) { if (m_pSubtitleInput && n == 2) return m_pSubtitleInput; else if ((m_pSubtitleInput && n == 3) || (!m_pSubtitleInput && n == 2)) return m_pCCOutputPin; } return __super::GetPin(n); } HRESULT CLAVVideo::CheckInputType(const CMediaType *mtIn) { for (UINT i = 0; i < sudPinTypesInCount; i++) { if (*sudPinTypesIn[i].clsMajorType == mtIn->majortype && *sudPinTypesIn[i].clsMinorType == mtIn->subtype && (mtIn->formattype == FORMAT_VideoInfo || mtIn->formattype == FORMAT_VideoInfo2 || mtIn->formattype == FORMAT_MPEGVideo || mtIn->formattype == FORMAT_MPEG2Video)) { return S_OK; } } return VFW_E_TYPE_NOT_ACCEPTED; } // Check if the types are compatible HRESULT CLAVVideo::CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut) { DbgLog((LOG_TRACE, 10, L"::CheckTransform()")); if (SUCCEEDED(CheckInputType(mtIn)) && mtOut->majortype == MEDIATYPE_Video) { if (m_PixFmtConverter.IsAllowedSubtype(&mtOut->subtype)) { return S_OK; } } return VFW_E_TYPE_NOT_ACCEPTED; } HRESULT CLAVVideo::DecideBufferSize(IMemAllocator *pAllocator, ALLOCATOR_PROPERTIES *pProperties) { DbgLog((LOG_TRACE, 10, L"::DecideBufferSize()")); if (m_pInput->IsConnected() == FALSE) { return E_UNEXPECTED; } BITMAPINFOHEADER *pBIH = nullptr; CMediaType &mtOut = m_pOutput->CurrentMediaType(); videoFormatTypeHandler(mtOut, &pBIH); // try to honor the requested number of downstream buffers, but cap at the decoders maximum long decoderBuffersMax = LONG_MAX; long decoderBuffs = m_Decoder.GetBufferCount(&decoderBuffersMax); long downstreamBuffers = pProperties->cBuffers; pProperties->cBuffers = min(max(pProperties->cBuffers, 2) + decoderBuffs, decoderBuffersMax); pProperties->cbBuffer = pBIH ? pBIH->biSizeImage : 3110400; pProperties->cbAlign = 1; pProperties->cbPrefix = 0; DbgLog((LOG_TRACE, 10, L" -> Downstream wants %d buffers, decoder wants %d, for a total of: %d", downstreamBuffers, decoderBuffs, pProperties->cBuffers)); HRESULT hr; ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAllocator->SetProperties(pProperties, &Actual))) { return hr; } return pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer ? E_FAIL : S_OK; } HRESULT CLAVVideo::GetMediaType(int iPosition, CMediaType *pMediaType) { DbgLog((LOG_TRACE, 10, L"::GetMediaType(): position: %d", iPosition)); if (m_pInput->IsConnected() == FALSE) { return E_UNEXPECTED; } if (iPosition < 0) { return E_INVALIDARG; } if (iPosition >= (m_PixFmtConverter.GetNumMediaTypes() * 2)) { return VFW_S_NO_MORE_ITEMS; } int index = iPosition / 2; BOOL bVIH1 = iPosition % 2; CMediaType &mtIn = m_pInput->CurrentMediaType(); BITMAPINFOHEADER *pBIH = nullptr; REFERENCE_TIME rtAvgTime = 0; DWORD dwAspectX = 0, dwAspectY = 0; videoFormatTypeHandler(mtIn.Format(), mtIn.FormatType(), &pBIH, &rtAvgTime, &dwAspectX, &dwAspectY); // Adjust for deinterlacing if (m_Decoder.IsInterlaced(FALSE) && m_settings.DeintMode != DeintMode_Disable) { BOOL bFramePerField = (m_settings.SWDeintMode != SWDeintMode_None && m_settings.SWDeintOutput == DeintOutput_FramePerField); if (bFramePerField) rtAvgTime /= 2; } m_PixFmtConverter.GetMediaType(pMediaType, index, pBIH->biWidth, pBIH->biHeight, dwAspectX, dwAspectY, rtAvgTime, IsInterlacedOutput(), bVIH1); return S_OK; } BOOL CLAVVideo::IsInterlacedOutput() { return (m_settings.SWDeintMode == SWDeintMode_None || m_filterPixFmt == LAVPixFmt_None) && m_Decoder.IsInterlaced(TRUE) && !(m_settings.DeintMode == DeintMode_Disable); } static const LPWSTR stream_ar_blacklist[] = { L".mkv", L".webm", L".mp4", L".mov", L".m4v", }; HRESULT CLAVVideo::CreateDecoder(const CMediaType *pmt) { DbgLog((LOG_TRACE, 10, L"::CreateDecoder(): Creating new decoder...")); HRESULT hr = S_OK; AVCodecID codec = FindCodecId(pmt); if (codec == AV_CODEC_ID_NONE) { return VFW_E_TYPE_NOT_ACCEPTED; } // Check if codec is activated for (int i = 0; i < Codec_VideoNB; ++i) { const codec_config_t *config = get_codec_config((LAVVideoCodec)i); bool bMatched = false; for (int k = 0; k < config->nCodecs; ++k) { if (config->codecs[k] == codec) { bMatched = true; break; } } if (bMatched && !m_settings.bFormats[i]) { DbgLog((LOG_TRACE, 10, L"-> Codec is disabled")); return VFW_E_TYPE_NOT_ACCEPTED; } } if (codec == AV_CODEC_ID_H264_MVC && !m_settings.bH264MVCOverride) { DbgLog((LOG_TRACE, 10, L"-> H.264 MVC override, refusing")); return VFW_E_TYPE_NOT_ACCEPTED; } ILAVPinInfo *pPinInfo = nullptr; hr = FindPinIntefaceInGraph(m_pInput, IID_ILAVPinInfo, (void **)&pPinInfo); if (SUCCEEDED(hr)) { memset(&m_LAVPinInfo, 0, sizeof(m_LAVPinInfo)); m_LAVPinInfoValid = TRUE; m_LAVPinInfo.flags = pPinInfo->GetStreamFlags(); m_LAVPinInfo.pix_fmt = (AVPixelFormat)pPinInfo->GetPixelFormat(); m_LAVPinInfo.has_b_frames = pPinInfo->GetHasBFrames(); SafeRelease(&pPinInfo); } else { m_LAVPinInfoValid = FALSE; } // Clear old sidedata memset(&m_SideData, 0, sizeof(m_SideData)); // Read and store stream-level sidedata IMediaSideData *pPinSideData = nullptr; MediaSideDataFFMpeg *pSideDataFFmpeg = nullptr; hr = FindPinIntefaceInGraph(m_pInput, __uuidof(IMediaSideData), (void **)&pPinSideData); if (SUCCEEDED(hr)) { size_t size = 0; hr = pPinSideData->GetSideData(IID_MediaSideDataFFMpeg, (const BYTE **)&pSideDataFFmpeg, &size); if (SUCCEEDED(hr) && size == sizeof(MediaSideDataFFMpeg)) { for (int i = 0; i < pSideDataFFmpeg->side_data_elems; i++) { AVPacketSideData *sd = &pSideDataFFmpeg->side_data[i]; // Display Mastering metadata, including color info if (sd->type == AV_PKT_DATA_MASTERING_DISPLAY_METADATA && sd->size == sizeof(AVMasteringDisplayMetadata)) { m_SideData.Mastering = *(AVMasteringDisplayMetadata *)sd->data; } else if (sd->type == AV_PKT_DATA_CONTENT_LIGHT_LEVEL && sd->size == sizeof(AVContentLightMetadata)) { m_SideData.ContentLight = *(AVContentLightMetadata *)sd->data; } else if (sd->type == AV_PKT_DATA_X264_BUILD && sd->size == 4 && codec == AV_CODEC_ID_H264) { SetX264Build(*(int *)sd->data); } } } SafeRelease(&pPinSideData); } m_dwDecodeFlags = 0; LPWSTR pszExtension = GetFileExtension(); if (pszExtension) { DbgLog((LOG_TRACE, 10, L"-> File extension: %s", pszExtension)); for (int i = 0; i < countof(stream_ar_blacklist); i++) { if (_wcsicmp(stream_ar_blacklist[i], pszExtension) == 0) { m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_STREAMAR_BLACKLIST; break; } } if (m_dwDecodeFlags & LAV_VIDEO_DEC_FLAG_STREAMAR_BLACKLIST) { // MPC-HC MP4 Splitter fails at Container AR if (FilterInGraph(PINDIR_INPUT, CLSID_MPCHCMP4Splitter) || FilterInGraph(PINDIR_INPUT, CLSID_MPCHCMP4SplitterSource)) { m_dwDecodeFlags &= ~LAV_VIDEO_DEC_FLAG_STREAMAR_BLACKLIST; } } } BOOL bSageVC1Hack = (codec == AV_CODEC_ID_VC1) && FilterInGraph(PINDIR_INPUT, CLSID_SageTVMpegDeMux); // Certain filters send VC-1 in PTS instead of DTS, so list them here // Usually, these are MPEG systems. BOOL bVC1DTS = (codec == AV_CODEC_ID_VC1) && !(FilterInGraph(PINDIR_INPUT, CLSID_MPCHCMPEGSplitter) || FilterInGraph(PINDIR_INPUT, CLSID_MPCHCMPEGSplitterSource) || FilterInGraph(PINDIR_INPUT, CLSID_MPBDReader) || bSageVC1Hack); BOOL bH2645IsAVI = ((codec == AV_CODEC_ID_H264 || codec == AV_CODEC_ID_HEVC) && (!m_LAVPinInfoValid && pszExtension && _wcsicmp(pszExtension, L".avi") == 0)); BOOL bLAVSplitter = FilterInGraph(PINDIR_INPUT, CLSID_LAVSplitterSource) || FilterInGraph(PINDIR_INPUT, CLSID_LAVSplitter); BOOL bDVDPlayback = (pmt->majortype == MEDIATYPE_DVD_ENCRYPTED_PACK || pmt->majortype == MEDIATYPE_MPEG2_PACK || pmt->majortype == MEDIATYPE_MPEG2_PES); BOOL bTheoraMPCHCOgg = (codec == AV_CODEC_ID_THEORA || codec == AV_CODEC_ID_VP3) && (FilterInGraph(PINDIR_INPUT, CLSID_MPCHCOggSplitter) || FilterInGraph(PINDIR_INPUT, CLSID_MPCHCOggSource)); if (bDVDPlayback && !m_settings.bDVDVideo) { DbgLog((LOG_TRACE, 10, L"-> DVD Video support is disabled")); return VFW_E_TYPE_NOT_ACCEPTED; } if (m_LAVPinInfoValid && (m_LAVPinInfo.flags & LAV_STREAM_FLAG_ONLY_DTS)) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_ONLY_DTS; if (bVC1DTS) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_ONLY_DTS; if (bH2645IsAVI) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_ONLY_DTS; if (bLAVSplitter) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_LAVSPLITTER; if (bDVDPlayback) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_DVD; if (bTheoraMPCHCOgg) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_NO_MT; if (bSageVC1Hack) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_SAGE_HACK; if (m_LAVPinInfoValid && (m_LAVPinInfo.flags & LAV_STREAM_FLAG_LIVE)) m_dwDecodeFlags |= LAV_VIDEO_DEC_FLAG_LIVE; SAFE_CO_FREE(pszExtension); hr = m_Decoder.CreateDecoder(pmt, codec, pSideDataFFmpeg); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Decoder creation failed")); goto done; } // Get avg time per frame videoFormatTypeHandler(pmt->Format(), pmt->FormatType(), nullptr, &m_rtAvgTimePerFrame); LAVPixelFormat pix, sw_pixfmt; int bpp; m_Decoder.GetPixelFormat(&pix, &bpp, &sw_pixfmt); // Set input on the converter, and force negotiation if needed if (m_PixFmtConverter.SetInputFmt(sw_pixfmt, bpp) && m_pOutput->IsConnected()) m_bForceFormatNegotiation = TRUE; if (pix == LAVPixFmt_YUV420 || pix == LAVPixFmt_YUV422 || pix == LAVPixFmt_NV12) m_filterPixFmt = pix; if (m_settings.bCCOutputPinEnabled && !bDVDPlayback && (codec == AV_CODEC_ID_MPEG2VIDEO || codec == AV_CODEC_ID_H264)) { if (m_pCCOutputPin == nullptr && CBaseFilter::IsStopped()) m_pCCOutputPin = new CCCOutputPin(TEXT("CCCOutputPin"), this, &m_csFilter, &hr, L"~CC Output"); } done: return SUCCEEDED(hr) ? S_OK : VFW_E_TYPE_NOT_ACCEPTED; } HRESULT CLAVVideo::CheckDirectMode() { LAVPixelFormat pix; int bpp; m_Decoder.GetPixelFormat(&pix, &bpp, nullptr); GUID outputSubtype = m_pOutput->CurrentMediaType().subtype; BOOL bDirect = (pix == LAVPixFmt_NV12 || pix == LAVPixFmt_P016 || pix == LAVPixFmt_YUY2 || pix == LAVPixFmt_Y216 || pix == LAVPixFmt_AYUV || pix == LAVPixFmt_Y410 || pix == LAVPixFmt_Y416); if (pix == LAVPixFmt_NV12 && m_Decoder.IsInterlaced(FALSE) && m_settings.SWDeintMode != SWDeintMode_None) bDirect = FALSE; else if (pix == LAVPixFmt_NV12 && outputSubtype != MEDIASUBTYPE_NV12 && outputSubtype != MEDIASUBTYPE_YV12) bDirect = FALSE; else if (pix == LAVPixFmt_P016 && outputSubtype != MEDIASUBTYPE_P010 && outputSubtype != MEDIASUBTYPE_P016 && outputSubtype != MEDIASUBTYPE_NV12) bDirect = FALSE; else if (pix == LAVPixFmt_YUY2 && outputSubtype != MEDIASUBTYPE_YUY2 && outputSubtype != MEDIASUBTYPE_YV16) bDirect = FALSE; else if (pix == LAVPixFmt_Y216 && outputSubtype != MEDIASUBTYPE_P210 && outputSubtype != MEDIASUBTYPE_P216) bDirect = FALSE; else if (pix == LAVPixFmt_AYUV && outputSubtype != MEDIASUBTYPE_AYUV) bDirect = FALSE; else if (pix == LAVPixFmt_Y410 && outputSubtype != MEDIASUBTYPE_Y410) bDirect = FALSE; else if (pix == LAVPixFmt_Y416 && outputSubtype != MEDIASUBTYPE_Y416) bDirect = FALSE; else if (m_SubtitleConsumer && m_SubtitleConsumer->HasProvider()) bDirect = FALSE; m_Decoder.SetDirectOutput(bDirect); return S_OK; } HRESULT CLAVVideo::SetMediaType(PIN_DIRECTION dir, const CMediaType *pmt) { HRESULT hr = S_OK; DbgLog((LOG_TRACE, 5, L"SetMediaType -- %S", dir == PINDIR_INPUT ? "in" : "out")); if (dir == PINDIR_INPUT) { hr = CreateDecoder(pmt); if (FAILED(hr)) { return hr; } m_bForceInputAR = TRUE; } else if (dir == PINDIR_OUTPUT) { m_PixFmtConverter.SetOutputPixFmt(m_PixFmtConverter.GetOutputBySubtype(pmt->Subtype())); } return __super::SetMediaType(dir, pmt); } HRESULT CLAVVideo::EndOfStream() { DbgLog((LOG_TRACE, 1, L"EndOfStream, flushing decoder")); CAutoLock cAutoLock(&m_csReceive); m_Decoder.EndOfStream(); Filter(GetFlushFrame()); if (m_pCCOutputPin) m_pCCOutputPin->DeliverEndOfStream(); DbgLog((LOG_TRACE, 1, L"EndOfStream finished, decoder flushed")); return __super::EndOfStream(); } HRESULT CLAVVideo::EndOfSegment() { DbgLog((LOG_TRACE, 1, L"EndOfSegment, flushing decoder")); CAutoLock cAutoLock(&m_csReceive); m_Decoder.EndOfStream(); Filter(GetFlushFrame()); // Forward the EndOfSegment call downstream if (m_pOutput != NULL && m_pOutput->IsConnected()) { IPin *pConnected = m_pOutput->GetConnected(); IPinSegmentEx *pPinSegmentEx = NULL; if (pConnected->QueryInterface(&pPinSegmentEx) == S_OK) { pPinSegmentEx->EndOfSegment(); } SafeRelease(&pPinSegmentEx); } return S_OK; } HRESULT CLAVVideo::BeginFlush() { DbgLog((LOG_TRACE, 1, L"::BeginFlush")); m_bFlushing = TRUE; if (m_pCCOutputPin) m_pCCOutputPin->DeliverBeginFlush(); return __super::BeginFlush(); } HRESULT CLAVVideo::EndFlush() { DbgLog((LOG_TRACE, 1, L"::EndFlush")); CAutoLock cAutoLock(&m_csReceive); ReleaseLastSequenceFrame(); if (m_dwDecodeFlags & LAV_VIDEO_DEC_FLAG_DVD) { PerformFlush(); } HRESULT hr = __super::EndFlush(); if (m_pCCOutputPin) m_pCCOutputPin->DeliverEndFlush(); m_bFlushing = FALSE; return hr; } HRESULT CLAVVideo::ReleaseLastSequenceFrame() { // Release DXVA2 frames hold in the last sequence frame if (m_pLastSequenceFrame && m_pLastSequenceFrame->format == LAVPixFmt_DXVA2) { IMediaSample *pSample = (IMediaSample *)m_pLastSequenceFrame->data[0]; IDirect3DSurface9 *pSurface = (IDirect3DSurface9 *)m_pLastSequenceFrame->data[3]; SafeRelease(&pSample); SafeRelease(&pSurface); } else if (m_pLastSequenceFrame && m_pLastSequenceFrame->format == LAVPixFmt_D3D11) { // TODO D3D11 } ReleaseFrame(&m_pLastSequenceFrame); return S_OK; } HRESULT CLAVVideo::PerformFlush() { CAutoLock cAutoLock(&m_csReceive); ReleaseLastSequenceFrame(); m_Decoder.Flush(); m_bInDVDMenu = FALSE; if (m_pFilterGraph) avfilter_graph_free(&m_pFilterGraph); m_rtPrevStart = m_rtPrevStop = 0; memset(&m_FilterPrevFrame, 0, sizeof(m_FilterPrevFrame)); return S_OK; } HRESULT CLAVVideo::NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { DbgLog((LOG_TRACE, 1, L"::NewSegment - %I64d / %I64d", tStart, tStop)); PerformFlush(); if (m_pCCOutputPin) m_pCCOutputPin->DeliverNewSegment(tStart, tStop, dRate); return __super::NewSegment(tStart, tStop, dRate); } HRESULT CLAVVideo::CheckConnect(PIN_DIRECTION dir, IPin *pPin) { if (dir == PINDIR_INPUT) { if (!m_bRuntimeConfig && CheckApplicationBlackList(LAVC_VIDEO_REGISTRY_KEY L"\\Blacklist")) return E_FAIL; if (FilterInGraphSafe(pPin, CLSID_LAVVideo, TRUE)) { DbgLog((LOG_TRACE, 10, L"CLAVVideo::CheckConnect(): LAVVideo is already in this graph branch, aborting.")); return E_FAIL; } } else if (dir == PINDIR_OUTPUT) { // Get the filter we're connecting to IBaseFilter *pFilter = GetFilterFromPin(pPin); CLSID guidFilter = GUID_NULL; if (pFilter != nullptr) { if (FAILED(pFilter->GetClassID(&guidFilter))) guidFilter = GUID_NULL; SafeRelease(&pFilter); } // Don't allow connection to the AVI Decompressor, it doesn't support a variety of our output formats properly if (guidFilter == CLSID_AVIDec) return VFW_E_TYPE_NOT_ACCEPTED; } return __super::CheckConnect(dir, pPin); } HRESULT CLAVVideo::BreakConnect(PIN_DIRECTION dir) { DbgLog((LOG_TRACE, 10, L"::BreakConnect")); if (dir == PINDIR_INPUT) { if (m_pFilterGraph) avfilter_graph_free(&m_pFilterGraph); m_Decoder.Close(); m_X264Build = -1; } else if (dir == PINDIR_OUTPUT) { m_Decoder.BreakConnect(); } return __super::BreakConnect(dir); } HRESULT CLAVVideo::CompleteConnect(PIN_DIRECTION dir, IPin *pReceivePin) { DbgLog((LOG_TRACE, 10, L"::CompleteConnect")); HRESULT hr = S_OK; if (dir == PINDIR_OUTPUT) { BOOL bFailNonDXVA = false; // Fail P010 software connections before Windows 10 Creators Update (presumably it was fixed before Creators // already, but this is definitely a safe known condition) if (!IsWindows10BuildOrNewer(15063) && (m_pOutput->CurrentMediaType().subtype == MEDIASUBTYPE_P010 || m_pOutput->CurrentMediaType().subtype == MEDIASUBTYPE_P016)) { // Check if we're connecting to EVR IBaseFilter *pFilter = GetFilterFromPin(pReceivePin); if (pFilter != nullptr) { CLSID guid; if (SUCCEEDED(pFilter->GetClassID(&guid))) { DbgLog((LOG_TRACE, 10, L"-> Connecting P010/P016 to %s", WStringFromGUID(guid).c_str())); bFailNonDXVA = (guid == CLSID_EnhancedVideoRenderer || guid == CLSID_VideoMixingRenderer9 || guid == CLSID_VideoMixingRenderer); } SafeRelease(&pFilter); } } hr = m_Decoder.PostConnect(pReceivePin); if (SUCCEEDED(hr)) { if (bFailNonDXVA) { LAVPixelFormat fmt; m_Decoder.GetPixelFormat(&fmt, nullptr, nullptr); if (fmt != LAVPixFmt_DXVA2) { DbgLog((LOG_TRACE, 10, L"-> Non-DXVA2 Connection rejected on this renderer and subtype")); return VFW_E_TYPE_NOT_ACCEPTED; } } CheckDirectMode(); } } else if (dir == PINDIR_INPUT) { if (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_MPEG2_VIDEO && !m_pSubtitleInput && (m_dwDecodeFlags & LAV_VIDEO_DEC_FLAG_DVD)) { m_pSubtitleInput = new CLAVVideoSubtitleInputPin(TEXT("CLAVVideoSubtitleInputPin"), this, &m_csFilter, &hr, L"Subtitle Input"); ASSERT(SUCCEEDED(hr)); m_SubtitleConsumer = new CLAVSubtitleConsumer(this); m_SubtitleConsumer->AddRef(); m_pSubtitleInput->SetSubtitleConsumer(m_SubtitleConsumer); BITMAPINFOHEADER *pBIH = nullptr; videoFormatTypeHandler(m_pInput->CurrentMediaType(), &pBIH); if (pBIH) { m_SubtitleConsumer->SetVideoSize(pBIH->biWidth, pBIH->biHeight); } } } return hr; } HRESULT CLAVVideo::StartStreaming() { CAutoLock cAutoLock(&m_csReceive); if (m_pSubtitleInput) { bool bFoundConsumer = false; ISubRenderConsumer *pSubConsumer = nullptr; if (SUCCEEDED(FindIntefaceInGraph(m_pOutput, __uuidof(ISubRenderConsumer), (void **)&pSubConsumer))) { int nc = 0; LPWSTR strName = nullptr, strVersion = nullptr; pSubConsumer->GetString("name", &strName, &nc); pSubConsumer->GetString("version", &strVersion, &nc); DbgLog((LOG_TRACE, 10, L"CLAVVideo::StartStreaming():: Found ISubRenderConsumer (%s %s)", strName, strVersion)); // only support madVR for now, and only recent versions (anything before 0.89.10 crashes) if (strName && strVersion) { if (wcscmp(strName, L"madVR") == 0) { int major, minor, build, rev; if (swscanf_s(strVersion, L"%d.%d.%d.%d", &major, &minor, &build, &rev) == 4) { if (major > 0 || (major == 0 && (minor > 89 || (minor == 89 && build >= 10)))) bFoundConsumer = true; } } else if (wcscmp(strName, L"JRVR") == 0) { bFoundConsumer = true; } } if (bFoundConsumer) { m_pSubtitleInput->SetSubtitleConsumer(pSubConsumer); SafeRelease(&m_SubtitleConsumer); } SafeRelease(&pSubConsumer); } if (bFoundConsumer == false) { if (m_SubtitleConsumer == nullptr) { m_SubtitleConsumer = new CLAVSubtitleConsumer(this); m_SubtitleConsumer->AddRef(); BITMAPINFOHEADER *pBIH = nullptr; videoFormatTypeHandler(m_pInput->CurrentMediaType(), &pBIH); if (pBIH) { m_SubtitleConsumer->SetVideoSize(pBIH->biWidth, pBIH->biHeight); } } m_pSubtitleInput->SetSubtitleConsumer(m_SubtitleConsumer); } } return S_OK; } STDMETHODIMP CLAVVideo::Stop() { // Get the receiver lock and prevent frame delivery { CAutoLock lck3(&m_csReceive); m_bFlushing = TRUE; } // actually perform the stop HRESULT hr = __super::Stop(); // unblock delivery again, if we continue receiving frames m_bFlushing = FALSE; return hr; } HRESULT CLAVVideo::GetDeliveryBuffer(IMediaSample **ppOut, int width, int height, AVRational ar, DXVA2_ExtendedFormat dxvaExtFlags, REFERENCE_TIME avgFrameDuration) { CheckPointer(ppOut, E_POINTER); HRESULT hr; if (FAILED(hr = ReconnectOutput(width, height, ar, dxvaExtFlags, avgFrameDuration))) { return hr; } if (FAILED(hr = m_pOutput->GetDeliveryBuffer(ppOut, nullptr, nullptr, 0))) { return hr; } CheckPointer(*ppOut, E_UNEXPECTED); AM_MEDIA_TYPE *pmt = nullptr; if (SUCCEEDED((*ppOut)->GetMediaType(&pmt)) && pmt) { CMediaType &outMt = m_pOutput->CurrentMediaType(); BITMAPINFOHEADER *pBMINew = nullptr; videoFormatTypeHandler(pmt->pbFormat, &pmt->formattype, &pBMINew); #ifdef DEBUG BITMAPINFOHEADER *pBMIOld = nullptr; videoFormatTypeHandler(outMt.pbFormat, &outMt.formattype, &pBMIOld); RECT rcTarget = {0}; if (pmt->formattype == FORMAT_VideoInfo2) { rcTarget = ((VIDEOINFOHEADER2 *)pmt->pbFormat)->rcTarget; } else if (pmt->formattype == FORMAT_VideoInfo) { rcTarget = ((VIDEOINFOHEADER *)pmt->pbFormat)->rcTarget; } DbgLog((LOG_TRACE, 10, L"::GetDeliveryBuffer(): Sample contains new media type from downstream filter..")); DbgLog((LOG_TRACE, 10, L"-> Width changed from %d to %d (target: %d)", pBMIOld->biWidth, pBMINew->biWidth, rcTarget.right)); #endif if (pBMINew->biWidth < width) { DbgLog((LOG_TRACE, 10, L" -> Renderer is trying to shrink the output window, failing!")); (*ppOut)->Release(); (*ppOut) = nullptr; DeleteMediaType(pmt); return E_FAIL; } if (pmt->formattype == FORMAT_VideoInfo2 && outMt.formattype == FORMAT_VideoInfo2 && m_bDXVAExtFormatSupport) { VIDEOINFOHEADER2 *vih2Current = (VIDEOINFOHEADER2 *)outMt.pbFormat; VIDEOINFOHEADER2 *vih2New = (VIDEOINFOHEADER2 *)pmt->pbFormat; if (vih2Current->dwControlFlags && vih2Current->dwControlFlags != vih2New->dwControlFlags) { m_bDXVAExtFormatSupport = FALSE; DbgLog((LOG_TRACE, 10, L"-> Disabled DXVA2ExtFormat Support, because renderer changed our value.")); } } // Check image size DWORD lSampleSize = m_PixFmtConverter.GetImageSize(pBMINew->biWidth, abs(pBMINew->biHeight)); if (lSampleSize != pBMINew->biSizeImage) { DbgLog((LOG_TRACE, 10, L"-> biSizeImage does not match our calculated sample size, correcting")); pBMINew->biSizeImage = lSampleSize; pmt->lSampleSize = lSampleSize; m_bSendMediaType = TRUE; } CMediaType mt = *pmt; m_pOutput->SetMediaType(&mt); DeleteMediaType(pmt); pmt = nullptr; } (*ppOut)->SetDiscontinuity(FALSE); (*ppOut)->SetSyncPoint(TRUE); return S_OK; } HRESULT CLAVVideo::ReconnectOutput(int width, int height, AVRational ar, DXVA2_ExtendedFormat dxvaExtFlags, REFERENCE_TIME avgFrameDuration, BOOL bDXVA) { CMediaType mt = m_pOutput->CurrentMediaType(); HRESULT hr = S_FALSE; BOOL bNeedReconnect = FALSE; int timeout = 100; DWORD dwAspectX = 0, dwAspectY = 0; RECT rcTargetOld = {0}; LONG biWidthOld = 0; // HACK: 1280 is the value when only chroma location is set to MPEG2, do not bother to send this information, as its // the same for basically every clip. if ((dxvaExtFlags.value & ~0xff) != 0 && (dxvaExtFlags.value & ~0xff) != 1280) dxvaExtFlags.SampleFormat = AMCONTROL_USED | AMCONTROL_COLORINFO_PRESENT; else dxvaExtFlags.value = 0; if (m_bMadVR == -1) m_bMadVR = FilterInGraph(PINDIR_OUTPUT, CLSID_madVR); if (m_bJRVR == -1) m_bJRVR = !m_bMadVR && FilterInGraph(PINDIR_OUTPUT, CLSID_JRVR); if (m_bOverlayMixer == -1) { m_bOverlayMixer = !m_bMadVR && FilterInGraph(PINDIR_OUTPUT, CLSID_OverlayMixer); if (m_bOverlayMixer) m_bDXVAExtFormatSupport = 0; } // Determine Interlaced flags // - madVR handles the flags properly, so properly indicate forced deint, adaptive deint and progressive // - The OverlayMixer fails at interlaced support, so completely disable interlaced flags for it BOOL bInterlaced = IsInterlacedOutput(); DWORD dwInterlacedFlags = 0; if (m_bMadVR || m_bJRVR) { if (bInterlaced && m_settings.DeintMode == DeintMode_Force) { dwInterlacedFlags = AMINTERLACE_IsInterlaced | AMINTERLACE_DisplayModeBobOnly; } else if (bInterlaced) { dwInterlacedFlags = AMINTERLACE_IsInterlaced | AMINTERLACE_DisplayModeBobOrWeave; } else { dwInterlacedFlags = 0; } } else if (!m_bOverlayMixer) { dwInterlacedFlags = bInterlaced ? AMINTERLACE_IsInterlaced | AMINTERLACE_DisplayModeBobOrWeave : 0; } // Remove custom matrix settings, which are not understood upstream if (dxvaExtFlags.VideoTransferMatrix == 6) { dxvaExtFlags.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601; } else if (dxvaExtFlags.VideoTransferMatrix > 5 && !(m_bMadVR || m_bJRVR)) { dxvaExtFlags.VideoTransferMatrix = DXVA2_VideoTransferMatrix_Unknown; } // madVR doesn't understand HLG yet, fallback to BT.709, which makes use of the backwards-compatible nature of HLG // Value 16 was used for ST2084 by madVR, which results in a terrible experience with HLG videos otherwise // TODO: remove once madVR learns HLG if (dxvaExtFlags.VideoTransferFunction == 16 && m_bMadVR) { dxvaExtFlags.VideoTransferFunction = DXVA2_VideoTransFunc_709; } if (mt.formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER *vih = (VIDEOINFOHEADER *)mt.Format(); if (avgFrameDuration == AV_NOPTS_VALUE) avgFrameDuration = vih->AvgTimePerFrame; bNeedReconnect = (vih->rcTarget.right != width || vih->rcTarget.bottom != height || abs(vih->AvgTimePerFrame - avgFrameDuration) > 10); } else if (mt.formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)mt.Format(); if (avgFrameDuration == AV_NOPTS_VALUE) avgFrameDuration = vih2->AvgTimePerFrame; DWORD dwARX, dwARY; videoFormatTypeHandler(m_pInput->CurrentMediaType().Format(), m_pInput->CurrentMediaType().FormatType(), nullptr, nullptr, &dwARX, &dwARY); int num = ar.num, den = ar.den; BOOL bStreamAR = (m_settings.StreamAR == 1) || (m_settings.StreamAR == 2 && (!(m_dwDecodeFlags & LAV_VIDEO_DEC_FLAG_STREAMAR_BLACKLIST) || !(dwARX && dwARY))); if (!bStreamAR || num == 0 || den == 0) { if (m_bForceInputAR && dwARX && dwARY) { num = dwARX; den = dwARY; } else { num = vih2->dwPictAspectRatioX; den = vih2->dwPictAspectRatioY; } m_bForceInputAR = FALSE; } dwAspectX = num; dwAspectY = den; // Disallow switching to non-interlaced mediatype for most renderers, as it causes dropped frames without real // advantages if (!m_bMadVR && vih2->dwInterlaceFlags) dwInterlacedFlags = vih2->dwInterlaceFlags; bNeedReconnect = (vih2->rcTarget.right != width || vih2->rcTarget.bottom != height || vih2->dwPictAspectRatioX != num || vih2->dwPictAspectRatioY != den || abs(vih2->AvgTimePerFrame - avgFrameDuration) > 10 || (m_bDXVAExtFormatSupport && vih2->dwControlFlags != dxvaExtFlags.value) || (vih2->dwInterlaceFlags != dwInterlacedFlags)); } if (!bNeedReconnect && bDXVA) { BITMAPINFOHEADER *pBMI = nullptr; videoFormatTypeHandler(mt.Format(), mt.FormatType(), &pBMI); bNeedReconnect = (pBMI->biCompression != mmioFOURCC('d', 'x', 'v', 'a')); } if (bNeedReconnect) { DbgLog((LOG_TRACE, 10, L"::ReconnectOutput(): Performing reconnect")); BITMAPINFOHEADER *pBIH = nullptr; if (mt.formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER *vih = (VIDEOINFOHEADER *)mt.Format(); rcTargetOld = vih->rcTarget; DbgLog((LOG_TRACE, 10, L"Using VIH, Format dump:")); DbgLog((LOG_TRACE, 10, L"-> width: %d -> %d", vih->rcTarget.right, width)); DbgLog((LOG_TRACE, 10, L"-> height: %d -> %d", vih->rcTarget.bottom, height)); DbgLog((LOG_TRACE, 10, L"-> FPS: %I64d -> %I64d", vih->AvgTimePerFrame, avgFrameDuration)); SetRect(&vih->rcSource, 0, 0, width, height); SetRect(&vih->rcTarget, 0, 0, width, height); vih->AvgTimePerFrame = avgFrameDuration; pBIH = &vih->bmiHeader; } else if (mt.formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)mt.Format(); rcTargetOld = vih2->rcTarget; DbgLog((LOG_TRACE, 10, L"Using VIH2, Format dump:")); DbgLog((LOG_TRACE, 10, L"-> width: %d -> %d", vih2->rcTarget.right, width)); DbgLog((LOG_TRACE, 10, L"-> height: %d -> %d", vih2->rcTarget.bottom, height)); DbgLog((LOG_TRACE, 10, L"-> AR: %d:%d -> %d:%d", vih2->dwPictAspectRatioX, vih2->dwPictAspectRatioY, dwAspectX, dwAspectY)); DbgLog((LOG_TRACE, 10, L"-> FPS: %I64d -> %I64d", vih2->AvgTimePerFrame, avgFrameDuration)); DbgLog((LOG_TRACE, 10, L"-> interlaced: 0x%0.8x -> 0x%0.8x", vih2->dwInterlaceFlags, dwInterlacedFlags)); DbgLog((LOG_TRACE, 10, L"-> flags: 0x%0.8x -> 0x%0.8x", vih2->dwControlFlags, m_bDXVAExtFormatSupport ? dxvaExtFlags.value : vih2->dwControlFlags)); vih2->dwPictAspectRatioX = dwAspectX; vih2->dwPictAspectRatioY = dwAspectY; SetRect(&vih2->rcSource, 0, 0, width, height); SetRect(&vih2->rcTarget, 0, 0, width, height); vih2->AvgTimePerFrame = avgFrameDuration; vih2->dwInterlaceFlags = dwInterlacedFlags; if (m_bDXVAExtFormatSupport) vih2->dwControlFlags = dxvaExtFlags.value; pBIH = &vih2->bmiHeader; } DWORD oldSizeImage = pBIH->biSizeImage; biWidthOld = pBIH->biWidth; pBIH->biWidth = width; pBIH->biHeight = pBIH->biHeight < 0 ? -height : height; pBIH->biSizeImage = m_PixFmtConverter.GetImageSize(width, height); if (bDXVA) pBIH->biCompression = mmioFOURCC('d', 'x', 'v', 'a'); if (mt.subtype == FOURCCMap('012v')) { pBIH->biWidth = FFALIGN(width, 48); } HRESULT hrQA = m_pOutput->GetConnected()->QueryAccept(&mt); if (bDXVA) { m_bSendMediaType = TRUE; m_pOutput->SetMediaType(&mt); } else { receiveconnection: hr = m_pOutput->GetConnected()->ReceiveConnection(m_pOutput, &mt); if (SUCCEEDED(hr)) { IMediaSample *pOut = nullptr; if (SUCCEEDED(hr = m_pOutput->GetDeliveryBuffer(&pOut, nullptr, nullptr, 0)) && pOut) { AM_MEDIA_TYPE *pmt = nullptr; if (SUCCEEDED(pOut->GetMediaType(&pmt)) && pmt) { CMediaType newmt = *pmt; videoFormatTypeHandler(newmt.Format(), newmt.FormatType(), &pBIH); DbgLog((LOG_TRACE, 10, L"-> New MediaType negotiated; actual width: %d - renderer requests: %ld", width, pBIH->biWidth)); if (pBIH->biWidth < width) { DbgLog((LOG_ERROR, 10, L"-> Renderer requests width smaller than image width, failing..")); DeleteMediaType(pmt); pOut->Release(); return E_FAIL; } // Check image size DWORD lSampleSize = m_PixFmtConverter.GetImageSize(pBIH->biWidth, abs(pBIH->biHeight)); if (lSampleSize != pBIH->biSizeImage) { DbgLog((LOG_TRACE, 10, L"-> biSizeImage does not match our calculated sample size, correcting")); pBIH->biSizeImage = lSampleSize; newmt.SetSampleSize(lSampleSize); m_bSendMediaType = TRUE; } // Store media type m_pOutput->SetMediaType(&newmt); m_bSendMediaType = TRUE; if (newmt.formattype == FORMAT_VideoInfo2 && mt.formattype == FORMAT_VideoInfo2 && m_bDXVAExtFormatSupport) { VIDEOINFOHEADER2 *vih2New = (VIDEOINFOHEADER2 *)newmt.pbFormat; if (dxvaExtFlags.value && dxvaExtFlags.value != vih2New->dwControlFlags) { m_bDXVAExtFormatSupport = FALSE; DbgLog((LOG_TRACE, 10, L"-> Disabled DXVA2ExtFormat Support, because renderer changed our value.")); } } DeleteMediaType(pmt); } else { // No Stride Request? We're ok with that, too! // The overlay mixer doesn't ask for a stride, but it needs one anyway // It'll provide a buffer just in the right size, so we can calculate this here. if (m_bOverlayMixer) { long size = pOut->GetSize(); pBIH->biWidth = size / abs(pBIH->biHeight) * 8 / pBIH->biBitCount; } DbgLog((LOG_TRACE, 10, L"-> We did not get a stride request, using width %d for stride", pBIH->biWidth)); m_bSendMediaType = TRUE; m_pOutput->SetMediaType(&mt); } pOut->Release(); } } else if (hr == VFW_E_BUFFERS_OUTSTANDING && timeout != -1) { if (timeout > 0) { DbgLog((LOG_TRACE, 10, L"-> Buffers outstanding, retrying in 10ms..")); Sleep(10); timeout -= 10; } else { DbgLog((LOG_TRACE, 10, L"-> Buffers outstanding, timeout reached, flushing..")); m_pOutput->DeliverBeginFlush(); m_pOutput->DeliverEndFlush(); timeout = -1; } goto receiveconnection; } else if (hrQA == S_OK) { DbgLog((LOG_TRACE, 10, L"-> Downstream accepts new format, but cannot reconnect dynamically...")); if (pBIH->biSizeImage > oldSizeImage) { DbgLog((LOG_TRACE, 10, L"-> But, we need a bigger buffer, try to adapt allocator manually")); IMemInputPin *pMemPin = nullptr; if (SUCCEEDED(hr = m_pOutput->GetConnected()->QueryInterface(&pMemPin)) && pMemPin) { IMemAllocator *pMemAllocator = nullptr; if (SUCCEEDED(hr = pMemPin->GetAllocator(&pMemAllocator)) && pMemAllocator) { ALLOCATOR_PROPERTIES props, actual; hr = pMemAllocator->GetProperties(&props); hr = pMemAllocator->Decommit(); props.cbBuffer = pBIH->biSizeImage; hr = pMemAllocator->SetProperties(&props, &actual); hr = pMemAllocator->Commit(); SafeRelease(&pMemAllocator); } } SafeRelease(&pMemPin); } else { // Check if there was a stride before.. if (rcTargetOld.right && biWidthOld > rcTargetOld.right && biWidthOld > pBIH->biWidth) { // If we had a stride before, the filter is apparently stride aware // Try to make it easier by keeping the old stride around pBIH->biWidth = biWidthOld; } } m_pOutput->SetMediaType(&mt); m_bSendMediaType = TRUE; } else { DbgLog((LOG_TRACE, 10, L"-> Receive Connection failed (hr: %x); QueryAccept: %x", hr, hrQA)); } } if (bNeedReconnect && !bDXVA) NotifyEvent(EC_VIDEO_SIZE_CHANGED, MAKELPARAM(width, height), 0); hr = S_OK; CheckDirectMode(); } return hr; } HRESULT CLAVVideo::NegotiatePixelFormat(CMediaType &outMt, int width, int height) { DbgLog((LOG_TRACE, 10, L"::NegotiatePixelFormat()")); HRESULT hr = S_OK; int i = 0; int timeout = 100; DWORD dwAspectX, dwAspectY; REFERENCE_TIME rtAvg; BOOL bVIH1 = (outMt.formattype == FORMAT_VideoInfo); videoFormatTypeHandler(outMt.Format(), outMt.FormatType(), nullptr, &rtAvg, &dwAspectX, &dwAspectY); CMediaType mt; for (i = 0; i < m_PixFmtConverter.GetNumMediaTypes(); ++i) { m_PixFmtConverter.GetMediaType(&mt, i, width, height, dwAspectX, dwAspectY, rtAvg, IsInterlacedOutput(), bVIH1); // hr = m_pOutput->GetConnected()->QueryAccept(&mt); receiveconnection: hr = m_pOutput->GetConnected()->ReceiveConnection(m_pOutput, &mt); if (hr == S_OK) { DbgLog((LOG_TRACE, 10, L"::NegotiatePixelFormat(): Filter accepted format with index %d", i)); m_pOutput->SetMediaType(&mt); hr = S_OK; goto done; } else if (hr == VFW_E_BUFFERS_OUTSTANDING && timeout != -1) { if (timeout > 0) { DbgLog((LOG_TRACE, 10, L"-> Buffers outstanding, retrying in 10ms..")); Sleep(10); timeout -= 10; } else { DbgLog((LOG_TRACE, 10, L"-> Buffers outstanding, timeout reached, flushing..")); m_pOutput->DeliverBeginFlush(); m_pOutput->DeliverEndFlush(); timeout = -1; } goto receiveconnection; } } DbgLog((LOG_ERROR, 10, L"::NegotiatePixelFormat(): Unable to agree on a pixel format")); hr = E_FAIL; done: FreeMediaType(mt); return hr; } HRESULT CLAVVideo::Receive(IMediaSample *pIn) { CAutoLock cAutoLock(&m_csReceive); HRESULT hr = S_OK; AM_SAMPLE2_PROPERTIES const *pProps = m_pInput->SampleProps(); if (pProps->dwStreamId != AM_STREAM_MEDIA) { return m_pOutput->Deliver(pIn); } AM_MEDIA_TYPE *pmt = nullptr; if (SUCCEEDED(pIn->GetMediaType(&pmt)) && pmt) { CMediaType mt = *pmt; DeleteMediaType(pmt); if (mt != m_pInput->CurrentMediaType() || !(m_dwDecodeFlags & LAV_VIDEO_DEC_FLAG_DVD)) { DbgLog((LOG_TRACE, 10, L"::Receive(): Input sample contained media type, dynamic format change...")); m_Decoder.EndOfStream(); hr = m_pInput->SetMediaType(&mt); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"::Receive(): Setting new media type failed...")); return hr; } } } m_hrDeliver = S_OK; // Skip over empty packets if (pIn->GetActualDataLength() == 0) { return S_OK; } hr = m_Decoder.Decode(pIn); if (FAILED(hr)) return hr; if (FAILED(m_hrDeliver)) return m_hrDeliver; return S_OK; } // ILAVVideoCallback STDMETHODIMP CLAVVideo::AllocateFrame(LAVFrame **ppFrame) { CheckPointer(ppFrame, E_POINTER); *ppFrame = (LAVFrame *)CoTaskMemAlloc(sizeof(LAVFrame)); if (!*ppFrame) { return E_OUTOFMEMORY; } // Initialize with zero ZeroMemory(*ppFrame, sizeof(LAVFrame)); // Set some defaults (*ppFrame)->sw_format = LAVPixFmt_None; (*ppFrame)->bpp = 8; (*ppFrame)->rtStart = AV_NOPTS_VALUE; (*ppFrame)->rtStop = AV_NOPTS_VALUE; (*ppFrame)->aspect_ratio = {0, 1}; (*ppFrame)->frame_type = '?'; return S_OK; } STDMETHODIMP CLAVVideo::ReleaseFrame(LAVFrame **ppFrame) { CheckPointer(ppFrame, E_POINTER); // Allow *ppFrame to be NULL already if (*ppFrame) { FreeLAVFrameBuffers(*ppFrame); SAFE_CO_FREE(*ppFrame); } return S_OK; } HRESULT CLAVVideo::DeDirectFrame(LAVFrame *pFrame, bool bDisableDirectMode) { if (!pFrame->direct) return S_FALSE; ASSERT(pFrame->direct_lock && pFrame->direct_unlock); LAVPixFmtDesc desc = getPixelFormatDesc(pFrame->format); LAVFrame tmpFrame = *pFrame; pFrame->destruct = nullptr; pFrame->priv_data = nullptr; pFrame->direct = false; pFrame->direct_lock = nullptr; pFrame->direct_unlock = nullptr; memset(pFrame->data, 0, sizeof(pFrame->data)); // sidedata remains on the main frame tmpFrame.side_data = nullptr; tmpFrame.side_data_count = 0; LAVDirectBuffer buffer; if (tmpFrame.direct_lock(&tmpFrame, &buffer)) { HRESULT hr = AllocLAVFrameBuffers(pFrame, buffer.stride[0] / desc.codedbytes); if (FAILED(hr)) { tmpFrame.direct_unlock(&tmpFrame); FreeLAVFrameBuffers(&tmpFrame); return hr; } // use slow copy, this should only be used extremely rarely memcpy(pFrame->data[0], buffer.data[0], pFrame->height * buffer.stride[0]); for (int i = 1; i < desc.planes; i++) memcpy(pFrame->data[i], buffer.data[i], (pFrame->height / desc.planeHeight[i]) * buffer.stride[i]); tmpFrame.direct_unlock(&tmpFrame); } else { // fallack, alloc anyway so nothing blows up HRESULT hr = AllocLAVFrameBuffers(pFrame); if (FAILED(hr)) { FreeLAVFrameBuffers(&tmpFrame); return hr; } } FreeLAVFrameBuffers(&tmpFrame); if (bDisableDirectMode) m_Decoder.SetDirectOutput(false); return S_OK; } STDMETHODIMP_(LAVFrame *) CLAVVideo::GetFlushFrame() { LAVFrame *pFlushFrame = nullptr; AllocateFrame(&pFlushFrame); pFlushFrame->flags |= LAV_FRAME_FLAG_FLUSH; pFlushFrame->rtStart = INT64_MAX; pFlushFrame->rtStop = INT64_MAX; return pFlushFrame; } STDMETHODIMP CLAVVideo::Deliver(LAVFrame *pFrame) { // Out-of-sequence flush event to get all frames delivered, // only triggered by decoders when they are already "empty" // so no need to flush the decoder here if (pFrame->flags & LAV_FRAME_FLAG_FLUSH) { DbgLog((LOG_TRACE, 10, L"Decoder triggered a flush...")); Filter(GetFlushFrame()); ReleaseFrame(&pFrame); return S_FALSE; } if (m_bFlushing) { ReleaseFrame(&pFrame); return S_FALSE; } if (ValidateLAVFrameBuffers(pFrame) == false) { ReleaseFrame(&pFrame); return S_FALSE; } if (pFrame->rtStart == AV_NOPTS_VALUE) { pFrame->rtStart = m_rtPrevStop; pFrame->rtStop = AV_NOPTS_VALUE; } if (pFrame->rtStop == AV_NOPTS_VALUE) { REFERENCE_TIME duration = 0; CMediaType &mt = m_pOutput->CurrentMediaType(); videoFormatTypeHandler(mt.Format(), mt.FormatType(), nullptr, &duration, nullptr, nullptr); REFERENCE_TIME decoderDuration = m_Decoder.GetFrameDuration(); if (pFrame->avgFrameDuration && pFrame->avgFrameDuration != AV_NOPTS_VALUE) { duration = pFrame->avgFrameDuration; } else if (!duration && decoderDuration) { duration = decoderDuration; } else if (!duration) { duration = 1; } pFrame->rtStop = pFrame->rtStart + (duration * (pFrame->repeat ? 3 : 2) / 2); } #if defined(DEBUG) && DEBUG_FRAME_TIMINGS DbgLog((LOG_TRACE, 10, L"Frame, rtStart: %I64d, dur: %I64d, diff: %I64d, key: %d, type: %C, repeat: %d, interlaced: %d, tff: %d", pFrame->rtStart, pFrame->rtStop - pFrame->rtStart, pFrame->rtStart - m_rtPrevStart, pFrame->key_frame, pFrame->frame_type, pFrame->repeat, pFrame->interlaced, pFrame->tff)); #endif m_rtPrevStart = pFrame->rtStart; m_rtPrevStop = pFrame->rtStop; if (!pFrame->avgFrameDuration || pFrame->avgFrameDuration == AV_NOPTS_VALUE) pFrame->avgFrameDuration = m_rtAvgTimePerFrame; else m_rtAvgTimePerFrame = pFrame->avgFrameDuration; if (pFrame->rtStart < 0) { ReleaseFrame(&pFrame); return S_OK; } // Only perform filtering if we have to. // DXVA Native generally can't be filtered, and the only filtering we currently support is software deinterlacing if (pFrame->format == LAVPixFmt_DXVA2 || pFrame->format == LAVPixFmt_D3D11 || !(m_Decoder.IsInterlaced(FALSE) && m_settings.SWDeintMode != SWDeintMode_None) || pFrame->flags & LAV_FRAME_FLAG_REDRAW) { return DeliverToRenderer(pFrame); } else { Filter(pFrame); } return S_OK; } HRESULT CLAVVideo::DeliverToRenderer(LAVFrame *pFrame) { HRESULT hr = S_OK; // This should never get here, but better check if (pFrame->flags & LAV_FRAME_FLAG_FLUSH) { ReleaseFrame(&pFrame); return S_FALSE; } if (!(pFrame->flags & LAV_FRAME_FLAG_REDRAW)) { // Release the old End-of-Sequence frame, this ensures any "normal" frame will clear the stored EOS frame if (pFrame->format != LAVPixFmt_DXVA2 && pFrame->format != LAVPixFmt_D3D11) { ReleaseFrame(&m_pLastSequenceFrame); if ((pFrame->flags & LAV_FRAME_FLAG_END_OF_SEQUENCE || m_bInDVDMenu)) { if (pFrame->direct) { hr = DeDirectFrame(pFrame, false); if (FAILED(hr)) { ReleaseFrame(&pFrame); return hr; } } CopyLAVFrame(pFrame, &m_pLastSequenceFrame); } } else if (pFrame->format == LAVPixFmt_DXVA2) { if ((pFrame->flags & LAV_FRAME_FLAG_END_OF_SEQUENCE || m_bInDVDMenu)) { if (!m_pLastSequenceFrame) { hr = AllocateFrame(&m_pLastSequenceFrame); if (SUCCEEDED(hr)) { m_pLastSequenceFrame->format = LAVPixFmt_DXVA2; hr = GetD3DBuffer(m_pLastSequenceFrame); if (FAILED(hr)) { ReleaseFrame(&m_pLastSequenceFrame); } } } if (m_pLastSequenceFrame && m_pLastSequenceFrame->data[0] && m_pLastSequenceFrame->data[3]) { BYTE *data0 = m_pLastSequenceFrame->data[0], *data3 = m_pLastSequenceFrame->data[3]; *m_pLastSequenceFrame = *pFrame; m_pLastSequenceFrame->data[0] = data0; m_pLastSequenceFrame->data[3] = data3; // Be careful not to accidentally copy the destructor of the original frame, that would end up being // bad m_pLastSequenceFrame->destruct = nullptr; m_pLastSequenceFrame->priv_data = nullptr; // don't copy side data m_pLastSequenceFrame->side_data = nullptr; m_pLastSequenceFrame->side_data_count = 0; IDirect3DSurface9 *pSurface = (IDirect3DSurface9 *)m_pLastSequenceFrame->data[3]; IDirect3DDevice9 *pDevice = nullptr; hr = pSurface->GetDevice(&pDevice); if (SUCCEEDED(hr)) { hr = pDevice->StretchRect((IDirect3DSurface9 *)pFrame->data[3], nullptr, pSurface, nullptr, D3DTEXF_NONE); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"::Decode(): Copying DXVA2 surface failed")); } SafeRelease(&pDevice); } } } } else if (pFrame->format == LAVPixFmt_D3D11) { // TODO D3D11 } } if (m_bFlushing) { ReleaseFrame(&pFrame); return S_FALSE; } // Process stream-level sidedata and attach it to the frame if necessary if (m_SideData.Mastering.has_colorspace) { // preserve HLG setting, as the container can often indicate the corresponding SDR format if (pFrame->ext_format.VideoTransferFunction == MFVideoTransFunc_HLG) m_SideData.Mastering.color_trc = AVCOL_TRC_ARIB_STD_B67; fillDXVAExtFormat(pFrame->ext_format, m_SideData.Mastering.color_range - 1, m_SideData.Mastering.color_primaries, m_SideData.Mastering.colorspace, m_SideData.Mastering.color_trc, m_SideData.Mastering.chroma_location, false); } if (m_SideData.Mastering.has_luminance || m_SideData.Mastering.has_primaries) { MediaSideDataHDR *hdr = nullptr; // Check if HDR data already exists if (pFrame->side_data && pFrame->side_data_count) { for (int i = 0; i < pFrame->side_data_count; i++) { if (pFrame->side_data[i].guidType == IID_MediaSideDataHDR) { hdr = (MediaSideDataHDR *)pFrame->side_data[i].data; break; } } } if (hdr == nullptr) hdr = (MediaSideDataHDR *)AddLAVFrameSideData(pFrame, IID_MediaSideDataHDR, sizeof(MediaSideDataHDR)); processFFHDRData(hdr, &m_SideData.Mastering); } if (m_SideData.ContentLight.MaxCLL && m_SideData.ContentLight.MaxFALL) { MediaSideDataHDRContentLightLevel *hdr = nullptr; // Check if data already exists if (pFrame->side_data && pFrame->side_data_count) { for (int i = 0; i < pFrame->side_data_count; i++) { if (pFrame->side_data[i].guidType == IID_MediaSideDataHDRContentLightLevel) { hdr = (MediaSideDataHDRContentLightLevel *)pFrame->side_data[i].data; break; } } } if (hdr == nullptr) hdr = (MediaSideDataHDRContentLightLevel *)AddLAVFrameSideData( pFrame, IID_MediaSideDataHDRContentLightLevel, sizeof(MediaSideDataHDRContentLightLevel)); hdr->MaxCLL = m_SideData.ContentLight.MaxCLL; hdr->MaxFALL = m_SideData.ContentLight.MaxFALL; } // Collect width/height int width = pFrame->width; int height = pFrame->height; if (width == 1920 && height == 1088) { height = 1080; } if (m_PixFmtConverter.SetInputFmt(pFrame->sw_format, pFrame->bpp) || m_bForceFormatNegotiation) { DbgLog((LOG_TRACE, 10, L"::Decode(): Changed input pixel format to %d (%d bpp, hw: %d)", pFrame->sw_format, pFrame->bpp, (pFrame->format != pFrame->sw_format))); CMediaType &mt = m_pOutput->CurrentMediaType(); if (m_PixFmtConverter.GetOutputBySubtype(mt.Subtype()) != m_PixFmtConverter.GetPreferredOutput()) { NegotiatePixelFormat(mt, width, height); } m_bForceFormatNegotiation = FALSE; } m_PixFmtConverter.SetColorProps(pFrame->ext_format, m_settings.RGBRange); // Update flags for cases where the converter can change the nominal range if (m_PixFmtConverter.IsRGBConverterActive()) { if (m_settings.RGBRange != 0) pFrame->ext_format.NominalRange = m_settings.RGBRange == 1 ? DXVA2_NominalRange_16_235 : DXVA2_NominalRange_0_255; else if (pFrame->ext_format.NominalRange == DXVA2_NominalRange_Unknown) pFrame->ext_format.NominalRange = DXVA2_NominalRange_16_235; } else if (m_PixFmtConverter.GetOutputPixFmt() == LAVOutPixFmt_RGB32 || m_PixFmtConverter.GetOutputPixFmt() == LAVOutPixFmt_RGB24 || m_PixFmtConverter.GetOutputPixFmt() == LAVOutPixFmt_RGB48) { pFrame->ext_format.NominalRange = DXVA2_NominalRange_0_255; } // Check if we are doing RGB output BOOL bRGBOut = (m_PixFmtConverter.GetOutputPixFmt() == LAVOutPixFmt_RGB24 || m_PixFmtConverter.GetOutputPixFmt() == LAVOutPixFmt_RGB32); // And blend subtitles if we're on YUV output before blending (because the output YUV formats are more complicated // to handle) if (m_SubtitleConsumer && m_SubtitleConsumer->HasProvider()) { m_SubtitleConsumer->SetVideoSize(width, height); m_SubtitleConsumer->RequestFrame(pFrame->rtStart, pFrame->rtStop); if (!bRGBOut) { if (pFrame->direct) { hr = DeDirectFrame(pFrame, true); if (FAILED(hr)) { ReleaseFrame(&pFrame); return hr; } } m_SubtitleConsumer->ProcessFrame(pFrame); } } // Grab a media sample, and start assembling the data for it. IMediaSample *pSampleOut = nullptr; BYTE *pDataOut = nullptr; REFERENCE_TIME avgDuration = pFrame->avgFrameDuration; if (avgDuration == 0) avgDuration = AV_NOPTS_VALUE; if (pFrame->format == LAVPixFmt_DXVA2 || pFrame->format == LAVPixFmt_D3D11) { pSampleOut = (IMediaSample *)pFrame->data[0]; // Addref the sample if we need to. If its coming from the decoder, it should be addref'ed, // but if its a copy from the subtitle engine, then it should not be addref'ed. if (!(pFrame->flags & LAV_FRAME_FLAG_DXVA_NOADDREF)) pSampleOut->AddRef(); ReconnectOutput(width, height, pFrame->aspect_ratio, pFrame->ext_format, avgDuration, TRUE); } else { if (FAILED(hr = GetDeliveryBuffer(&pSampleOut, width, height, pFrame->aspect_ratio, pFrame->ext_format, avgDuration)) || FAILED(hr = pSampleOut->GetPointer(&pDataOut)) || pDataOut == nullptr) { SafeRelease(&pSampleOut); ReleaseFrame(&pFrame); return hr; } } CMediaType &mt = m_pOutput->CurrentMediaType(); BITMAPINFOHEADER *pBIH = nullptr; videoFormatTypeHandler(mt.Format(), mt.FormatType(), &pBIH); // Set side data on the media sample if (pFrame->side_data_count) { IMediaSideData *pMediaSideData = nullptr; if (SUCCEEDED(hr = pSampleOut->QueryInterface(&pMediaSideData))) { for (int i = 0; i < pFrame->side_data_count; i++) { if (pFrame->side_data[i].guidType != IID_MediaSideDataEIA608CC) pMediaSideData->SetSideData(pFrame->side_data[i].guidType, pFrame->side_data[i].data, pFrame->side_data[i].size); } SafeRelease(&pMediaSideData); } if (m_pCCOutputPin && m_pCCOutputPin->IsConnected()) { size_t sCC = 0; BYTE *CC = GetLAVFrameSideData(pFrame, IID_MediaSideDataEIA608CC, &sCC); if (CC && sCC) { m_pCCOutputPin->DeliverCCData(CC, sCC, pFrame->rtStart); } } } if (pFrame->flags & (LAV_FRAME_FLAG_END_OF_SEQUENCE | LAV_FRAME_FLAG_REDRAW)) { IMediaSideData *pMediaSideData = nullptr; if (SUCCEEDED(hr = pSampleOut->QueryInterface(&pMediaSideData))) { DWORD dwControlFlags = MediaSideDataControlFlags_EndOfSequence; pMediaSideData->SetSideData(IID_MediaSideDataControlFlags, (const BYTE *)&dwControlFlags, sizeof(dwControlFlags)); SafeRelease(&pMediaSideData); } } if (pFrame->format != LAVPixFmt_DXVA2 && pFrame->format != LAVPixFmt_D3D11) { long required = m_PixFmtConverter.GetImageSize(pBIH->biWidth, abs(pBIH->biHeight)); long lSampleSize = pSampleOut->GetSize(); if (lSampleSize < required) { DbgLog( (LOG_ERROR, 10, L"::Decode(): Buffer is too small! Actual: %d, Required: %d", lSampleSize, required)); SafeRelease(&pSampleOut); ReleaseFrame(&pFrame); return E_FAIL; } pSampleOut->SetActualDataLength(required); #if defined(DEBUG) && DEBUG_PIXELCONV_TIMINGS LARGE_INTEGER frequency, start, end; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&start); #endif if (pFrame->direct && !m_PixFmtConverter.IsDirectModeSupported((uintptr_t)pDataOut, pBIH->biWidth)) { DeDirectFrame(pFrame, true); } if (pFrame->direct) m_PixFmtConverter.ConvertDirect(pFrame, pDataOut, width, height, pBIH->biWidth, abs(pBIH->biHeight)); else m_PixFmtConverter.Convert(pFrame->data, pFrame->stride, pDataOut, width, height, pBIH->biWidth, abs(pBIH->biHeight)); #if defined(DEBUG) && DEBUG_PIXELCONV_TIMINGS QueryPerformanceCounter(&end); double diff = (end.QuadPart - start.QuadPart) * 1000.0 / frequency.QuadPart; m_pixFmtTimingAvg.Sample(diff); DbgLog((LOG_TRACE, 10, L"Pixel Mapping took %2.3fms in avg", m_pixFmtTimingAvg.Average())); #endif // Write the second view into IMediaSample3D, if available if (pFrame->flags & LAV_FRAME_FLAG_MVC) { IMediaSample3D *pSample3D = nullptr; if (SUCCEEDED(hr = pSampleOut->QueryInterface(&pSample3D))) { BYTE *pDataOut3D = nullptr; if (SUCCEEDED(pSample3D->Enable3D()) && SUCCEEDED(pSample3D->GetPointer3D(&pDataOut3D))) { m_PixFmtConverter.Convert(pFrame->stereo, pFrame->stride, pDataOut3D, width, height, pBIH->biWidth, abs(pBIH->biHeight)); } SafeRelease(&pSample3D); } } // Once we're done with the old frame, release its buffers // This does not release the frame yet, just free its buffers FreeLAVFrameBuffers(pFrame); // .. and if we do RGB conversion, blend after the conversion, for improved quality if (bRGBOut && m_SubtitleConsumer && m_SubtitleConsumer->HasProvider()) { int strideBytes = pBIH->biWidth; LAVPixelFormat pixFmt; if (m_PixFmtConverter.GetOutputPixFmt() == LAVOutPixFmt_RGB32) { pixFmt = LAVPixFmt_RGB32; strideBytes *= 4; } else { pixFmt = LAVPixFmt_RGB24; strideBytes *= 3; } // We need to supply a LAV Frame to the subtitle API // So update it with the appropriate settings pFrame->data[0] = pDataOut; pFrame->stride[0] = strideBytes; pFrame->format = pixFmt; pFrame->sw_format = pixFmt; pFrame->bpp = 8; pFrame->flags |= LAV_FRAME_FLAG_BUFFER_MODIFY; m_SubtitleConsumer->ProcessFrame(pFrame); } if ((mt.subtype == MEDIASUBTYPE_RGB32 || mt.subtype == MEDIASUBTYPE_RGB24) && pBIH->biHeight > 0) { int bpp = (mt.subtype == MEDIASUBTYPE_RGB32) ? 4 : 3; flip_plane(pDataOut, pBIH->biWidth * bpp, height); } } BOOL bSizeChanged = FALSE; if (m_bSendMediaType) { AM_MEDIA_TYPE *sendmt = CreateMediaType(&mt); pSampleOut->SetMediaType(sendmt); DeleteMediaType(sendmt); m_bSendMediaType = FALSE; if (pFrame->format == LAVPixFmt_DXVA2 || pFrame->format == LAVPixFmt_D3D11) bSizeChanged = TRUE; } // Handle DVD playback rate.. if (GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) { CVideoInputPin *pPin = dynamic_cast(m_pInput); AM_SimpleRateChange pinRate = pPin->GetDVDRateChange(); if (abs(pinRate.Rate) != m_DVDRate.Rate) { DbgLog((LOG_TRACE, 10, L"DVD Rate changed to: %d", pinRate.Rate)); m_DVDRate.Rate = abs(pinRate.Rate); m_DVDRate.StartTime = pFrame->rtStart; } if (m_DVDRate.StartTime != AV_NOPTS_VALUE && m_DVDRate.Rate != 10000) { pFrame->rtStart = m_DVDRate.StartTime + (pFrame->rtStart - m_DVDRate.StartTime) * m_DVDRate.Rate / 10000; pFrame->rtStop = m_DVDRate.StartTime + (pFrame->rtStop - m_DVDRate.StartTime) * m_DVDRate.Rate / 10000; } } // Set frame timings.. pSampleOut->SetTime(&pFrame->rtStart, &pFrame->rtStop); pSampleOut->SetMediaTime(nullptr, nullptr); // And frame flags.. SetFrameFlags(pSampleOut, pFrame); // Release frame before delivery, so it can be re-used by the decoder (if required) ReleaseFrame(&pFrame); hr = m_pOutput->Deliver(pSampleOut); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"::Decode(): Deliver failed with hr: %x", hr)); m_hrDeliver = hr; } if (bSizeChanged) NotifyEvent(EC_VIDEO_SIZE_CHANGED, MAKELPARAM(pBIH->biWidth, abs(pBIH->biHeight)), 0); SafeRelease(&pSampleOut); return hr; } HRESULT CLAVVideo::GetD3DBuffer(LAVFrame *pFrame) { CheckPointer(pFrame, E_POINTER); IMediaSample *pSample = nullptr; HRESULT hr = m_pOutput->GetDeliveryBuffer(&pSample, nullptr, nullptr, 0); if (SUCCEEDED(hr)) { IMFGetService *pService = nullptr; hr = pSample->QueryInterface(&pService); if (SUCCEEDED(hr)) { IDirect3DSurface9 *pSurface = nullptr; hr = pService->GetService(MR_BUFFER_SERVICE, __uuidof(IDirect3DSurface9), (LPVOID *)&pSurface); if (SUCCEEDED(hr)) { pFrame->data[0] = (BYTE *)pSample; pFrame->data[3] = (BYTE *)pSurface; } SafeRelease(&pService); } } return hr; } HRESULT CLAVVideo::RedrawStillImage() { IMediaControl *pMC = nullptr; if (m_pGraph->QueryInterface(&pMC) == S_OK && pMC) { OAFilterState state = State_Stopped; pMC->GetState(0, &state); SafeRelease(&pMC); if (state != State_Running) { DbgLog((LOG_TRACE, 10, L"CLAVVideo::RedrawStillImage(): Redraw ignored, graph is not running.")); return S_FALSE; } } if (m_pLastSequenceFrame) { CAutoLock lock(&m_csReceive); // Since a delivery call can clear the stored sequence frame, we need a second check here // Because only after we obtained the receive lock, we are in charge.. if (!m_pLastSequenceFrame) return S_FALSE; DbgLog((LOG_TRACE, 10, L"CLAVVideo::RedrawStillImage(): Redrawing still image")); LAVFrame *pFrame = nullptr; if (m_pLastSequenceFrame->format == LAVPixFmt_DXVA2) { HRESULT hr = AllocateFrame(&pFrame); if (FAILED(hr)) return hr; *pFrame = *m_pLastSequenceFrame; hr = GetD3DBuffer(pFrame); if (SUCCEEDED(hr)) { IMediaSample *pSample = (IMediaSample *)pFrame->data[0]; IDirect3DSurface9 *pSurface = (IDirect3DSurface9 *)pFrame->data[3]; pSample->SetTime(&m_pLastSequenceFrame->rtStart, &m_pLastSequenceFrame->rtStop); IDirect3DDevice9 *pDevice = nullptr; if (SUCCEEDED(pSurface->GetDevice(&pDevice))) { hr = pDevice->StretchRect((IDirect3DSurface9 *)m_pLastSequenceFrame->data[3], nullptr, pSurface, nullptr, D3DTEXF_NONE); if (SUCCEEDED(hr)) { pFrame->flags |= LAV_FRAME_FLAG_REDRAW | LAV_FRAME_FLAG_BUFFER_MODIFY; hr = Deliver(pFrame); } SafeRelease(&pDevice); } SafeRelease(&pSurface); SafeRelease(&pSample); } return hr; } else if (m_pLastSequenceFrame->format == LAVPixFmt_D3D11) { // TODO D3D11 } else { LAVFrame *pFrame = nullptr; HRESULT hr = CopyLAVFrame(m_pLastSequenceFrame, &pFrame); if (FAILED(hr)) return hr; pFrame->flags |= LAV_FRAME_FLAG_REDRAW; return Deliver(pFrame); } return S_FALSE; } return S_FALSE; } HRESULT CLAVVideo::SetFrameFlags(IMediaSample *pMS, LAVFrame *pFrame) { HRESULT hr = S_OK; IMediaSample2 *pMS2 = nullptr; if (SUCCEEDED(hr = pMS->QueryInterface(&pMS2))) { AM_SAMPLE2_PROPERTIES props; if (SUCCEEDED(pMS2->GetProperties(sizeof(props), (BYTE *)&props))) { props.dwTypeSpecificFlags &= ~0x7f; if (!pFrame->interlaced) props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; if (pFrame->tff) props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST; if (pFrame->repeat) props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_REPEAT_FIELD; pMS2->SetProperties(sizeof(props), (BYTE *)&props); } } SafeRelease(&pMS2); return hr; } STDMETHODIMP CLAVVideo::Read(LPCOLESTR pszPropName, VARIANT *pVar, IErrorLog *pErrorLog) { CheckPointer(pszPropName, E_INVALIDARG); CheckPointer(pVar, E_INVALIDARG); if (_wcsicmp(pszPropName, L"STEREOSCOPIC3D") == 0) { const WCHAR *pszDecoder = GetActiveDecoderName(); bool bMVC = pszDecoder && wcscmp(pszDecoder, L"msdk mvc") == 0; VariantClear(pVar); pVar->vt = VT_BSTR; pVar->bstrVal = SysAllocString(bMVC ? L"1" : L"0"); return S_OK; } return E_INVALIDARG; } STDMETHODIMP_(BOOL) CLAVVideo::HasDynamicInputAllocator() { return dynamic_cast(m_pInput)->HasDynamicAllocator(); } // ILAVVideoSettings STDMETHODIMP CLAVVideo::SetRuntimeConfig(BOOL bRuntimeConfig) { m_bRuntimeConfig = bRuntimeConfig; LoadSettings(); // Tray Icon is disabled by default SAFE_DELETE(m_pTrayIcon); return S_OK; } STDMETHODIMP CLAVVideo::SetFormatConfiguration(LAVVideoCodec vCodec, BOOL bEnabled) { if (vCodec < 0 || vCodec >= Codec_VideoNB) return E_FAIL; m_settings.bFormats[vCodec] = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetFormatConfiguration(LAVVideoCodec vCodec) { if (vCodec < 0 || vCodec >= Codec_VideoNB) return FALSE; return m_settings.bFormats[vCodec]; } STDMETHODIMP CLAVVideo::SetNumThreads(DWORD dwNum) { m_settings.NumThreads = dwNum; return SaveSettings(); } STDMETHODIMP_(DWORD) CLAVVideo::GetNumThreads() { return m_settings.NumThreads; } STDMETHODIMP CLAVVideo::SetStreamAR(DWORD bStreamAR) { m_settings.StreamAR = bStreamAR; return SaveSettings(); } STDMETHODIMP_(DWORD) CLAVVideo::GetStreamAR() { return m_settings.StreamAR; } STDMETHODIMP CLAVVideo::SetDeintFieldOrder(LAVDeintFieldOrder order) { m_settings.DeintFieldOrder = order; return SaveSettings(); } STDMETHODIMP_(LAVDeintFieldOrder) CLAVVideo::GetDeintFieldOrder() { return (LAVDeintFieldOrder)m_settings.DeintFieldOrder; } STDMETHODIMP CLAVVideo::SetDeintAggressive(BOOL bAggressive) { if (m_settings.DeintMode == DeintMode_Auto && bAggressive) m_settings.DeintMode = DeintMode_Aggressive; else if (m_settings.DeintMode == DeintMode_Aggressive && !bAggressive) m_settings.DeintMode = DeintMode_Auto; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetDeintAggressive() { return (m_settings.DeintMode == DeintMode_Aggressive); } STDMETHODIMP CLAVVideo::SetDeintForce(BOOL bForce) { if ((m_settings.DeintMode == DeintMode_Auto || m_settings.DeintMode == DeintMode_Aggressive) && bForce) m_settings.DeintMode = DeintMode_Force; else if (m_settings.DeintMode == DeintMode_Force && !bForce) m_settings.DeintMode = DeintMode_Auto; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetDeintForce() { return (m_settings.DeintMode == DeintMode_Force); } STDMETHODIMP CLAVVideo::SetPixelFormat(LAVOutPixFmts pixFmt, BOOL bEnabled) { if (pixFmt < 0 || pixFmt >= LAVOutPixFmt_NB) return E_FAIL; m_settings.bPixFmts[pixFmt] = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetPixelFormat(LAVOutPixFmts pixFmt) { if (pixFmt < 0 || pixFmt >= LAVOutPixFmt_NB) return FALSE; return m_settings.bPixFmts[pixFmt]; } STDMETHODIMP CLAVVideo::SetRGBOutputRange(DWORD dwRange) { m_settings.RGBRange = dwRange; return SaveSettings(); } STDMETHODIMP_(DWORD) CLAVVideo::GetRGBOutputRange() { return m_settings.RGBRange; } STDMETHODIMP_(DWORD) CLAVVideo::CheckHWAccelSupport(LAVHWAccel hwAccel) { if (hwAccel == m_settings.HWAccel && m_Decoder.IsHWDecoderActive()) return 2; HRESULT hr = E_FAIL; ILAVDecoder *pDecoder = CDecodeManager::CreateHWAccelDecoder(hwAccel); if (pDecoder) { hr = pDecoder->InitInterfaces(this, this); if (SUCCEEDED(hr)) { hr = pDecoder->Check(); } SAFE_DELETE(pDecoder); } return SUCCEEDED(hr) ? 1 : 0; } STDMETHODIMP CLAVVideo::SetHWAccel(LAVHWAccel hwAccel) { m_settings.HWAccel = hwAccel; return SaveSettings(); } STDMETHODIMP_(LAVHWAccel) CLAVVideo::GetHWAccel() { return (LAVHWAccel)m_settings.HWAccel; } STDMETHODIMP CLAVVideo::SetHWAccelCodec(LAVVideoHWCodec hwAccelCodec, BOOL bEnabled) { if (hwAccelCodec < 0 || hwAccelCodec >= HWCodec_NB) return E_FAIL; m_settings.bHWFormats[hwAccelCodec] = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetHWAccelCodec(LAVVideoHWCodec hwAccelCodec) { if (hwAccelCodec < 0 || hwAccelCodec >= HWCodec_NB) return FALSE; return m_settings.bHWFormats[hwAccelCodec]; } STDMETHODIMP CLAVVideo::SetHWAccelDeintMode(LAVHWDeintModes deintMode) { m_settings.HWDeintMode = deintMode; return SaveSettings(); } STDMETHODIMP_(LAVHWDeintModes) CLAVVideo::GetHWAccelDeintMode() { return (LAVHWDeintModes)m_settings.HWDeintMode; } STDMETHODIMP CLAVVideo::SetHWAccelDeintOutput(LAVDeintOutput deintOutput) { m_settings.HWDeintOutput = deintOutput; return SaveSettings(); } STDMETHODIMP_(LAVDeintOutput) CLAVVideo::GetHWAccelDeintOutput() { return (LAVDeintOutput)m_settings.HWDeintOutput; } STDMETHODIMP CLAVVideo::SetHWAccelDeintHQ(BOOL bHQ) { m_settings.HWAccelCUVIDXVA = bHQ; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetHWAccelDeintHQ() { return m_settings.HWAccelCUVIDXVA; } STDMETHODIMP CLAVVideo::SetSWDeintMode(LAVSWDeintModes deintMode) { m_settings.SWDeintMode = deintMode; return SaveSettings(); } STDMETHODIMP_(LAVSWDeintModes) CLAVVideo::GetSWDeintMode() { return (LAVSWDeintModes)m_settings.SWDeintMode; } STDMETHODIMP CLAVVideo::SetSWDeintOutput(LAVDeintOutput deintOutput) { m_settings.SWDeintOutput = deintOutput; return SaveSettings(); } STDMETHODIMP_(LAVDeintOutput) CLAVVideo::GetSWDeintOutput() { return (LAVDeintOutput)m_settings.SWDeintOutput; } STDMETHODIMP CLAVVideo::SetDeintTreatAsProgressive(BOOL bEnabled) { m_settings.DeintMode = bEnabled ? DeintMode_Disable : DeintMode_Auto; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetDeintTreatAsProgressive() { return (m_settings.DeintMode == DeintMode_Disable); } STDMETHODIMP CLAVVideo::SetDitherMode(LAVDitherMode ditherMode) { m_settings.DitherMode = ditherMode; return SaveSettings(); } STDMETHODIMP_(LAVDitherMode) CLAVVideo::GetDitherMode() { return (LAVDitherMode)m_settings.DitherMode; } STDMETHODIMP CLAVVideo::SetUseMSWMV9Decoder(BOOL bEnabled) { m_settings.bMSWMV9DMO = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetUseMSWMV9Decoder() { return m_settings.bMSWMV9DMO; } STDMETHODIMP CLAVVideo::SetDVDVideoSupport(BOOL bEnabled) { m_settings.bDVDVideo = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetDVDVideoSupport() { return m_settings.bDVDVideo; } STDMETHODIMP CLAVVideo::SetHWAccelResolutionFlags(DWORD dwResFlags) { m_settings.HWAccelResFlags = dwResFlags; return SaveSettings(); } STDMETHODIMP_(DWORD) CLAVVideo::GetHWAccelResolutionFlags() { return m_settings.HWAccelResFlags; } STDMETHODIMP CLAVVideo::SetTrayIcon(BOOL bEnabled) { m_settings.TrayIcon = bEnabled; // The tray icon is created if not yet done so, however its not removed on the fly // Removing the icon on the fly can cause deadlocks if the config is changed from the icons thread if (bEnabled && m_pGraph && !m_pTrayIcon) { CreateTrayIcon(); } return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVVideo::GetTrayIcon() { return m_settings.TrayIcon; } STDMETHODIMP CLAVVideo::SetDeinterlacingMode(LAVDeintMode deintMode) { m_settings.DeintMode = deintMode; return SaveSettings(); } STDMETHODIMP_(LAVDeintMode) CLAVVideo::GetDeinterlacingMode() { return m_settings.DeintMode; } STDMETHODIMP CLAVVideo::SetGPUDeviceIndex(DWORD dwDevice) { m_dwGPUDeviceIndex = dwDevice; return S_OK; } STDMETHODIMP_(DWORD) CLAVVideo::GetHWAccelNumDevices(LAVHWAccel hwAccel) { HRESULT hr = S_OK; ILAVDecoder *pDecoder = CDecodeManager::CreateHWAccelDecoder(hwAccel); DWORD dwDevices = 0; if (pDecoder) { hr = pDecoder->InitInterfaces(this, this); if (SUCCEEDED(hr)) { dwDevices = pDecoder->GetHWAccelNumDevices(); } SAFE_DELETE(pDecoder); } return dwDevices; } STDMETHODIMP CLAVVideo::GetHWAccelDeviceInfo(LAVHWAccel hwAccel, DWORD dwIndex, BSTR *pstrDeviceName, DWORD *pdwDeviceIdentifier) { HRESULT hr = E_NOINTERFACE; ILAVDecoder *pDecoder = CDecodeManager::CreateHWAccelDecoder(hwAccel); if (pDecoder) { hr = pDecoder->InitInterfaces(this, this); if (SUCCEEDED(hr)) { hr = pDecoder->GetHWAccelDeviceInfo(dwIndex, pstrDeviceName, pdwDeviceIdentifier); } SAFE_DELETE(pDecoder); } return hr; } STDMETHODIMP_(DWORD) CLAVVideo::GetHWAccelDeviceIndex(LAVHWAccel hwAccel, DWORD *pdwDeviceIdentifier) { HRESULT hr = S_OK; if (hwAccel == HWAccel_DXVA2CopyBack) { DWORD dwDeviceIndex = m_settings.HWAccelDeviceDXVA2; DWORD dwDeviceId = m_settings.HWAccelDeviceDXVA2Desc; // verify the values and re-match them to adapters appropriately if (dwDeviceIndex != LAVHWACCEL_DEVICE_DEFAULT && dwDeviceId != 0) { hr = VerifyD3D9Device(dwDeviceIndex, dwDeviceId); if (FAILED(hr)) { dwDeviceIndex = LAVHWACCEL_DEVICE_DEFAULT; dwDeviceId = 0; } } if (pdwDeviceIdentifier) *pdwDeviceIdentifier = dwDeviceId; return dwDeviceIndex; } else if (hwAccel == HWAccel_D3D11) { DWORD dwDeviceIndex = m_settings.HWAccelDeviceD3D11; DWORD dwDeviceId = m_settings.HWAccelDeviceD3D11Desc; // verify the values and re-match them to adapters appropriately if (dwDeviceIndex != LAVHWACCEL_DEVICE_DEFAULT && dwDeviceId != 0) { hr = VerifyD3D11Device(dwDeviceIndex, dwDeviceId); if (FAILED(hr)) { dwDeviceIndex = LAVHWACCEL_DEVICE_DEFAULT; dwDeviceId = 0; } } if (pdwDeviceIdentifier) *pdwDeviceIdentifier = dwDeviceId; return dwDeviceIndex; } if (pdwDeviceIdentifier) *pdwDeviceIdentifier = 0; return LAVHWACCEL_DEVICE_DEFAULT; } STDMETHODIMP CLAVVideo::SetHWAccelDeviceIndex(LAVHWAccel hwAccel, DWORD dwIndex, DWORD dwDeviceIdentifier) { HRESULT hr = S_OK; if (dwIndex != LAVHWACCEL_DEVICE_DEFAULT && dwDeviceIdentifier == 0 && !m_bRuntimeConfig) hr = GetHWAccelDeviceInfo(hwAccel, dwIndex, nullptr, &dwDeviceIdentifier); if (SUCCEEDED(hr)) { if (hwAccel == HWAccel_DXVA2CopyBack) { m_settings.HWAccelDeviceDXVA2 = dwIndex; m_settings.HWAccelDeviceDXVA2Desc = dwDeviceIdentifier; } else if (hwAccel == HWAccel_D3D11) { m_settings.HWAccelDeviceD3D11 = dwIndex; m_settings.HWAccelDeviceD3D11Desc = dwDeviceIdentifier; } return SaveSettings(); } else { return E_INVALIDARG; } } STDMETHODIMP CLAVVideo::SetH264MVCDecodingOverride(BOOL bEnabled) { m_settings.bH264MVCOverride = bEnabled; return S_OK; } STDMETHODIMP CLAVVideo::SetEnableCCOutputPin(BOOL bEnabled) { m_settings.bCCOutputPinEnabled = bEnabled; return S_OK; } STDMETHODIMP CLAVVideo::GetHWAccelActiveDevice(BSTR *pstrDeviceName) { return m_Decoder.GetHWAccelActiveDevice(pstrDeviceName); } ================================================ FILE: decoder/LAVVideo/LAVVideo.def ================================================ ; LAVVideo.def ; declares the exports LIBRARY "LAVVideo.ax" EXPORTS DllGetClassObject PRIVATE DllCanUnloadNow PRIVATE DllRegisterServer PRIVATE DllUnregisterServer PRIVATE OpenConfiguration PRIVATE ================================================ FILE: decoder/LAVVideo/LAVVideo.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "decoders/ILAVDecoder.h" #include "DecodeManager.h" #include "ILAVPinInfo.h" #include "LAVPixFmtConverter.h" #include "LAVVideoSettings.h" #include "FloatingAverage.h" #include "ISpecifyPropertyPages2.h" #include "SynchronizedQueue.h" #include "subtitles/LAVSubtitleConsumer.h" #include "subtitles/LAVVideoSubtitleInputPin.h" #include "CCOutputPin.h" #include "BaseTrayIcon.h" #include "IMediaSideData.h" extern "C" { #include "libavutil/mastering_display_metadata.h" }; #define LAVC_VIDEO_REGISTRY_KEY L"Software\\LAV\\Video" #define LAVC_VIDEO_REGISTRY_KEY_FORMATS L"Software\\LAV\\Video\\Formats" #define LAVC_VIDEO_REGISTRY_KEY_OUTPUT L"Software\\LAV\\Video\\Output" #define LAVC_VIDEO_REGISTRY_KEY_HWACCEL L"Software\\LAV\\Video\\HWAccel" #define LAVC_VIDEO_LOG_FILE L"LAVVideo.txt" #define DEBUG_FRAME_TIMINGS 0 #define DEBUG_PIXELCONV_TIMINGS 0 typedef struct { REFERENCE_TIME rtStart; REFERENCE_TIME rtStop; } TimingCache; class __declspec(uuid("EE30215D-164F-4A92-A4EB-9D4C13390F9F")) CLAVVideo : public CTransformFilter , public ISpecifyPropertyPages2 , public ILAVVideoSettings , public ILAVVideoStatus , public ILAVVideoCallback , public IPropertyBag { public: CLAVVideo(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVVideo(); // IUnknown DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // ISpecifyPropertyPages2 STDMETHODIMP GetPages(CAUUID *pPages); STDMETHODIMP CreatePage(const GUID &guid, IPropertyPage **ppPage); // ILAVVideoSettings STDMETHODIMP SetRuntimeConfig(BOOL bRuntimeConfig); STDMETHODIMP SetFormatConfiguration(LAVVideoCodec vCodec, BOOL bEnabled); STDMETHODIMP_(BOOL) GetFormatConfiguration(LAVVideoCodec vCodec); STDMETHODIMP SetNumThreads(DWORD dwNum); STDMETHODIMP_(DWORD) GetNumThreads(); STDMETHODIMP SetStreamAR(DWORD bStreamAR); STDMETHODIMP_(DWORD) GetStreamAR(); STDMETHODIMP SetPixelFormat(LAVOutPixFmts pixFmt, BOOL bEnabled); STDMETHODIMP_(BOOL) GetPixelFormat(LAVOutPixFmts pixFmt); STDMETHODIMP SetRGBOutputRange(DWORD dwRange); STDMETHODIMP_(DWORD) GetRGBOutputRange(); STDMETHODIMP SetDeintFieldOrder(LAVDeintFieldOrder fieldOrder); STDMETHODIMP_(LAVDeintFieldOrder) GetDeintFieldOrder(); STDMETHODIMP SetDeintForce(BOOL bForce); STDMETHODIMP_(BOOL) GetDeintForce(); STDMETHODIMP SetDeintAggressive(BOOL bAggressive); STDMETHODIMP_(BOOL) GetDeintAggressive(); STDMETHODIMP_(DWORD) CheckHWAccelSupport(LAVHWAccel hwAccel); STDMETHODIMP SetHWAccel(LAVHWAccel hwAccel); STDMETHODIMP_(LAVHWAccel) GetHWAccel(); STDMETHODIMP SetHWAccelCodec(LAVVideoHWCodec hwAccelCodec, BOOL bEnabled); STDMETHODIMP_(BOOL) GetHWAccelCodec(LAVVideoHWCodec hwAccelCodec); STDMETHODIMP SetHWAccelDeintMode(LAVHWDeintModes deintMode); STDMETHODIMP_(LAVHWDeintModes) GetHWAccelDeintMode(); STDMETHODIMP SetHWAccelDeintOutput(LAVDeintOutput deintOutput); STDMETHODIMP_(LAVDeintOutput) GetHWAccelDeintOutput(); STDMETHODIMP SetHWAccelDeintHQ(BOOL bHQ); STDMETHODIMP_(BOOL) GetHWAccelDeintHQ(); STDMETHODIMP SetSWDeintMode(LAVSWDeintModes deintMode); STDMETHODIMP_(LAVSWDeintModes) GetSWDeintMode(); STDMETHODIMP SetSWDeintOutput(LAVDeintOutput deintOutput); STDMETHODIMP_(LAVDeintOutput) GetSWDeintOutput(); STDMETHODIMP SetDeintTreatAsProgressive(BOOL bEnabled); STDMETHODIMP_(BOOL) GetDeintTreatAsProgressive(); STDMETHODIMP SetDitherMode(LAVDitherMode ditherMode); STDMETHODIMP_(LAVDitherMode) GetDitherMode(); STDMETHODIMP SetUseMSWMV9Decoder(BOOL bEnabled); STDMETHODIMP_(BOOL) GetUseMSWMV9Decoder(); STDMETHODIMP SetDVDVideoSupport(BOOL bEnabled); STDMETHODIMP_(BOOL) GetDVDVideoSupport(); STDMETHODIMP SetHWAccelResolutionFlags(DWORD dwResFlags); STDMETHODIMP_(DWORD) GetHWAccelResolutionFlags(); STDMETHODIMP SetTrayIcon(BOOL bEnabled); STDMETHODIMP_(BOOL) GetTrayIcon(); STDMETHODIMP SetDeinterlacingMode(LAVDeintMode deintMode); STDMETHODIMP_(LAVDeintMode) GetDeinterlacingMode(); STDMETHODIMP SetGPUDeviceIndex(DWORD dwDevice); STDMETHODIMP_(DWORD) GetHWAccelNumDevices(LAVHWAccel hwAccel); STDMETHODIMP GetHWAccelDeviceInfo(LAVHWAccel hwAccel, DWORD dwIndex, BSTR *pstrDeviceName, DWORD *pdwDeviceIdentifier); STDMETHODIMP_(DWORD) GetHWAccelDeviceIndex(LAVHWAccel hwAccel, DWORD *pdwDeviceIdentifier); STDMETHODIMP SetHWAccelDeviceIndex(LAVHWAccel hwAccel, DWORD dwIndex, DWORD dwDeviceIdentifier); STDMETHODIMP SetH264MVCDecodingOverride(BOOL bEnabled); STDMETHODIMP SetEnableCCOutputPin(BOOL bEnabled); // ILAVVideoStatus STDMETHODIMP_(const WCHAR *) GetActiveDecoderName() { return m_Decoder.GetDecoderName(); } STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName); // CTransformFilter STDMETHODIMP Stop(); HRESULT CheckInputType(const CMediaType *mtIn); HRESULT CheckTransform(const CMediaType *mtIn, const CMediaType *mtOut); HRESULT DecideBufferSize(IMemAllocator *pAllocator, ALLOCATOR_PROPERTIES *pprop); HRESULT GetMediaType(int iPosition, CMediaType *pMediaType); HRESULT SetMediaType(PIN_DIRECTION dir, const CMediaType *pmt); HRESULT EndOfStream(); HRESULT BeginFlush(); HRESULT EndFlush(); HRESULT NewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); HRESULT Receive(IMediaSample *pIn); HRESULT CheckConnect(PIN_DIRECTION dir, IPin *pPin); HRESULT BreakConnect(PIN_DIRECTION dir); HRESULT CompleteConnect(PIN_DIRECTION dir, IPin *pReceivePin); HRESULT StartStreaming(); int GetPinCount(); CBasePin *GetPin(int n); STDMETHODIMP JoinFilterGraph(IFilterGraph *pGraph, LPCWSTR pName); // IPinSegmentEx HRESULT EndOfSegment(); // ILAVVideoCallback STDMETHODIMP AllocateFrame(LAVFrame **ppFrame); STDMETHODIMP ReleaseFrame(LAVFrame **ppFrame); STDMETHODIMP Deliver(LAVFrame *pFrame); STDMETHODIMP_(LPWSTR) GetFileExtension(); STDMETHODIMP_(BOOL) FilterInGraph(PIN_DIRECTION dir, const GUID &clsid) { if (dir == PINDIR_INPUT) return FilterInGraphSafe(m_pInput, clsid); else return FilterInGraphSafe(m_pOutput, clsid); } STDMETHODIMP_(DWORD) GetDecodeFlags() { return m_dwDecodeFlags; } STDMETHODIMP_(CMediaType &) GetInputMediaType() { return m_pInput->CurrentMediaType(); } STDMETHODIMP GetLAVPinInfo(LAVPinInfo &info) { if (m_LAVPinInfoValid) { info = m_LAVPinInfo; return S_OK; } return E_FAIL; } STDMETHODIMP_(CBasePin *) GetOutputPin() { return m_pOutput; } STDMETHODIMP_(CMediaType &) GetOutputMediaType() { return m_pOutput->CurrentMediaType(); } STDMETHODIMP DVDStripPacket(BYTE *&p, long &len) { static_cast(m_pInput)->StripPacket(p, len); return S_OK; } STDMETHODIMP_(LAVFrame *) GetFlushFrame(); STDMETHODIMP ReleaseAllDXVAResources() { ReleaseLastSequenceFrame(); return S_OK; } STDMETHODIMP_(DWORD) GetGPUDeviceIndex() { return m_dwGPUDeviceIndex; } STDMETHODIMP_(BOOL) HasDynamicInputAllocator(); STDMETHODIMP SetX264Build(int nBuild) { m_X264Build = nBuild; return S_OK; } STDMETHODIMP_(int) GetX264Build() { return m_X264Build; } // IPropertyBag STDMETHODIMP Read(LPCOLESTR pszPropName, VARIANT *pVar, IErrorLog *pErrorLog); STDMETHODIMP Write(LPCOLESTR pszPropName, VARIANT *pVar) { return E_NOTIMPL; } public: // Pin Configuration const static AMOVIESETUP_MEDIATYPE sudPinTypesIn[]; const static UINT sudPinTypesInCount; const static AMOVIESETUP_MEDIATYPE sudPinTypesOut[]; const static UINT sudPinTypesOutCount; private: HRESULT LoadDefaults(); HRESULT ReadSettings(HKEY rootKey); HRESULT LoadSettings(); HRESULT SaveSettings(); HRESULT CreateTrayIcon(); HRESULT CreateDecoder(const CMediaType *pmt); HRESULT GetDeliveryBuffer(IMediaSample **ppOut, int width, int height, AVRational ar, DXVA2_ExtendedFormat dxvaExtFormat, REFERENCE_TIME avgFrameDuration); HRESULT ReconnectOutput(int width, int height, AVRational ar, DXVA2_ExtendedFormat dxvaExtFlags, REFERENCE_TIME avgFrameDuration, BOOL bDXVA = FALSE); HRESULT SetFrameFlags(IMediaSample *pMS, LAVFrame *pFrame); HRESULT NegotiatePixelFormat(CMediaType &mt, int width, int height); BOOL IsInterlacedOutput(); HRESULT CheckDirectMode(); HRESULT DeDirectFrame(LAVFrame *pFrame, bool bDisableDirectMode = true); HRESULT Filter(LAVFrame *pFrame); HRESULT DeliverToRenderer(LAVFrame *pFrame); HRESULT PerformFlush(); HRESULT ReleaseLastSequenceFrame(); HRESULT GetD3DBuffer(LAVFrame *pFrame); HRESULT RedrawStillImage(); HRESULT SetInDVDMenu(bool menu) { m_bInDVDMenu = menu; return S_OK; } private: friend class CVideoInputPin; friend class CVideoOutputPin; friend class CDecodeManager; friend class CLAVSubtitleProvider; friend class CLAVSubtitleConsumer; CDecodeManager m_Decoder; REFERENCE_TIME m_rtPrevStart = 0; REFERENCE_TIME m_rtPrevStop = 0; REFERENCE_TIME m_rtAvgTimePerFrame = AV_NOPTS_VALUE; BOOL m_bForceInputAR = FALSE; BOOL m_bSendMediaType = FALSE; BOOL m_bFlushing = FALSE; BOOL m_bForceFormatNegotiation = FALSE; HRESULT m_hrDeliver = S_OK; CLAVPixFmtConverter m_PixFmtConverter; std::wstring m_strExtension; BOOL m_bDXVAExtFormatSupport = TRUE; DWORD m_bMadVR = -1; DWORD m_bJRVR = -1; DWORD m_bOverlayMixer = -1; DWORD m_dwDecodeFlags = 0; BOOL m_bInDVDMenu = FALSE; AVFilterGraph *m_pFilterGraph = nullptr; AVFilterContext *m_pFilterBufferSrc = nullptr; AVFilterContext *m_pFilterBufferSink = nullptr; LAVPixelFormat m_filterPixFmt = LAVPixFmt_None; int m_filterWidth = 0; int m_filterHeight = 0; LAVFrame m_FilterPrevFrame; BOOL m_LAVPinInfoValid = FALSE; LAVPinInfo m_LAVPinInfo; int m_X264Build = -1; struct { AVMasteringDisplayMetadata Mastering; AVContentLightMetadata ContentLight; } m_SideData; CLAVVideoSubtitleInputPin *m_pSubtitleInput = nullptr; CLAVSubtitleConsumer *m_SubtitleConsumer = nullptr; CCCOutputPin *m_pCCOutputPin = nullptr; LAVFrame *m_pLastSequenceFrame = nullptr; AM_SimpleRateChange m_DVDRate = AM_SimpleRateChange{AV_NOPTS_VALUE, 10000}; BOOL m_bRuntimeConfig = FALSE; struct VideoSettings { BOOL TrayIcon; DWORD StreamAR; DWORD NumThreads; BOOL bFormats[Codec_VideoNB]; BOOL bMSWMV9DMO; BOOL bPixFmts[LAVOutPixFmt_NB]; DWORD RGBRange; DWORD HWAccel; BOOL bHWFormats[HWCodec_NB]; DWORD HWAccelResFlags; BOOL HWAccelCUVIDXVA; DWORD HWDeintMode; DWORD HWDeintOutput; DWORD DeintFieldOrder; LAVDeintMode DeintMode; DWORD SWDeintMode; DWORD SWDeintOutput; DWORD DitherMode; BOOL bDVDVideo; DWORD HWAccelDeviceDXVA2; DWORD HWAccelDeviceDXVA2Desc; DWORD HWAccelDeviceD3D11; DWORD HWAccelDeviceD3D11Desc; BOOL bH264MVCOverride; BOOL bCCOutputPinEnabled; } m_settings; DWORD m_dwGPUDeviceIndex = DWORD_MAX; CBaseTrayIcon *m_pTrayIcon = nullptr; #ifdef DEBUG FloatingAverage m_pixFmtTimingAvg; #endif }; ================================================ FILE: decoder/LAVVideo/LAVVideo.manifest ================================================ ================================================ FILE: decoder/LAVVideo/LAVVideo.rc ================================================ // Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_ICON1 ICON "..\\..\\resources\\red.ico" #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""winres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" "LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\r\n" "#pragma code_page(1252)\r\n" "#include ""LAVVideo.rc2"" // non-Microsoft Visual C++ edited resources\r\n" "#endif\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_PROPPAGE_VIDEO_SETTINGS DIALOGEX 0, 0, 415, 295 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN GROUPBOX "Settings",IDC_VIDEO_SETTINGS,7,7,140,132 LTEXT "Threads for Multi-Threading",IDC_LBL_MULTITHREAD,14,20,91,8 COMBOBOX IDC_THREADS,15,30,75,200,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP CONTROL "Use Stream Aspect Ratio",IDC_STREAMAR,"Button",BS_AUTO3STATE | WS_TABSTOP,15,50,100,10 LTEXT "Settings for Interlaced Video Streams",IDC_DEINT_SETTINGS,12,64,131,8 LTEXT "Field Order",IDC_LBL_DEINT_FIELDORDER,14,76,79,8 COMBOBOX IDC_DEINT_FIELDORDER,15,87,110,100,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP LTEXT "Deinterlacing Mode",IDC_LBL_DEINT_MODE,14,106,79,8 COMBOBOX IDC_DEINT_MODE,15,116,110,100,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP GROUPBOX "Output Formats",IDC_OUTPUT_FORMATS,7,143,226,131 LTEXT "8-bit",IDC_OUT_8BIT,38,154,32,8 LTEXT "10-bit",IDC_OUT_10BIT,115,154,32,8 LTEXT "16-bit",IDC_OUT_16BIT,191,154,24,8 LTEXT "4:2:0",IDC_OUT_420,14,164,20,8 CONTROL "NV12",IDC_OUT_NV12,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,38,164,32,10 CONTROL "YV12",IDC_OUT_YV12,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,78,164,32,10 CONTROL "P010",IDC_OUT_P010,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,115,164,32,10 CONTROL "P016",IDC_OUT_P016,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,191,164,32,10 LTEXT "4:2:2",IDC_OUT_422,14,178,20,8 CONTROL "YUY2",IDC_OUT_YUY2,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,38,178,32,10 CONTROL "UYVY",IDC_OUT_UYVY,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,78,178,32,10 CONTROL "P210",IDC_OUT_P210,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,115,178,32,10 CONTROL "v210",IDC_OUT_V210,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,151,178,32,10 CONTROL "P216",IDC_OUT_P216,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,191,178,32,10 LTEXT "4:4:4",IDC_OUT_444,14,193,20,8 CONTROL "YV24",IDC_OUT_YV24,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,38,193,32,10 CONTROL "AYUV",IDC_OUT_AYUV,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,78,193,32,10 CONTROL "Y410",IDC_OUT_Y410,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,115,193,32,10 CONTROL "v410",IDC_OUT_V410,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,151,193,32,10 CONTROL "Y416",IDC_OUT_Y416,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,191,193,32,10 LTEXT "RGB",IDC_OUT_RGB,14,207,20,8 CONTROL "RGB32",IDC_OUT_RGB32,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,38,207,40,10 CONTROL "RGB24",IDC_OUT_RGB24,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,78,207,40,10 CONTROL "RGB48",IDC_OUT_RGB48,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,191,207,40,10 LTEXT "RGB Output levels (for YUV -> RGB conversion)",IDC_LBL_RGBOUT,14,223,188,8 CONTROL "TV (16-235)",IDC_RGBOUT_TV,"Button",BS_AUTORADIOBUTTON,19,234,50,10 CONTROL "PC (0-255)",IDC_RGBOUT_PC,"Button",BS_AUTORADIOBUTTON,71,234,46,10 CONTROL "Untouched (as input)",IDC_RGBOUT_AUTO,"Button",BS_AUTORADIOBUTTON,120,234,80,10 LTEXT "Dithering Mode",IDC_STATIC,14,247,188,8 CONTROL "Ordered Dithering",IDC_DITHER_ORDERED,"Button",BS_AUTORADIOBUTTON | WS_GROUP,19,258,92,10 CONTROL "Random Dithering",IDC_DITHER_RANDOM,"Button",BS_AUTORADIOBUTTON,120,258,90,10 GROUPBOX "Hardware Acceleration",IDC_HWACCEL_SETTINGS,151,7,253,132 LTEXT "Hardware Decoder to use:",IDC_LBL_HWACCEL,157,17,107,8 COMBOBOX IDC_HWACCEL,160,28,85,100,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP LTEXT "N/A",IDC_HWACCEL_AVAIL,247,31,20,8 LTEXT "Active Decoder: ",IDC_STATIC,157,46,56,8 LTEXT "",IDC_ACTIVE_DECODER,213,46,55,8 LTEXT "Resolutions",IDC_LBL_HWRESOLUTIONS,271,17,47,8 CONTROL "SD",IDC_HWRES_SD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,274,27,32,10 CONTROL "HD",IDC_HWRES_HD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,315,27,32,10 CONTROL "UHD (4K)",IDC_HWRES_UHD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,356,27,43,10 LTEXT "Codecs for HW Decoding",IDC_LBL_HWCODECS,271,42,80,8 CONTROL "H.264",IDC_HWACCEL_H264,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,274,53,39,10 CONTROL "HEVC",IDC_HWACCEL_HEVC,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,315,53,39,10 CONTROL "VC-1",IDC_HWACCEL_VC1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,356,53,39,10 CONTROL "MPEG-2",IDC_HWACCEL_MPEG2,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,274,67,39,10 CONTROL "MPEG-4",IDC_HWACCEL_MPEG4,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,356,67,39,10 CONTROL "VP9",IDC_HWACCEL_VP9,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,274,81,39,10 CONTROL "AV1",IDC_HWACCEL_AV1,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,315,81,39,10 CONTROL "H.264 MVC",IDC_HWACCEL_H264MVC,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,356,81,46,10 LTEXT "Active Hardware Accelerator:",IDC_LBL_HWACCEL_DEVICE,157,62,110,8 LTEXT "",IDC_HWACCEL_DEVICE,160,72,105,8 LTEXT "Hardware Device to use:",IDC_LBL_HWACCEL_DEVICE_SELECT,157,87,105,8 COMBOBOX IDC_HWACCEL_DEVICE_SELECT,160,98,235,30,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP LTEXT "The selected Hardware Decoder does not support using a specific device.",IDC_LBL_HWACCEL_DEVICE_HINT,160,115,235,18 CONTROL "Enable CUVID DXVA processing", IDC_HWACCEL_CUVID_DXVA, "Button", BS_AUTOCHECKBOX | WS_TABSTOP, 160,125,139,10 GROUPBOX "Hardware/GPU Deinterlacing (CUVID/QS only)",IDC_GROUP_HWDEINT,237,143,167,52 CONTROL "Enable Adaptive HW Deinterlacing",IDC_HWDEINT_ENABLE, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,244,155,139,10 LTEXT "Output Mode",IDC_LBL_HWDEINT_MODE,243,167,62,8 CONTROL "25p/30p (Film)",IDC_HWDEINT_OUT_FILM,"Button",BS_AUTORADIOBUTTON | WS_GROUP,247,180,58,10 CONTROL "50p/60p (Video)",IDC_HWDEINT_OUT_VIDEO,"Button",BS_AUTORADIOBUTTON,315,180,62,10 GROUPBOX "Software Deinterlacing",IDC_SWDEINT,237,197,167,67 LTEXT "Algorithm",IDC_LBL_SWDEINT_ALGO,243,208,100,11 COMBOBOX IDC_SWDEINT_MODE,246,220,140,100,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP LTEXT "Output Mode",IDC_LBL_SWDEINT_MODE,243,237,100,11 CONTROL "25p/30p (Film)",IDC_SWDEINT_OUT_FILM,"Button",BS_AUTORADIOBUTTON | WS_GROUP,247,248,58,10 CONTROL "50p/60p (Video)",IDC_SWDEINT_OUT_VIDEO,"Button",BS_AUTORADIOBUTTON,315,248,62,10 CONTROL "Enable System Tray Icon",IDC_TRAYICON,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,280,192,10 LTEXT "LAV Video Decoder x.xx",IDC_LAVVIDEO_FOOTER,248,282,156,8,0,WS_EX_RIGHT END IDD_PROPPAGE_FORMATS DIALOGEX 0, 0, 405, 250 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN LTEXT "Select which formats LAV Video should decode:",IDC_LBL_FORMATS,8,10,378,10 CONTROL "",IDC_CODECS,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,20,387,193 CONTROL "Use Microsoft WMV9 MFT decoder for WMV3 and VC-1",IDC_CODECS_MSWMVDMO, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,230,352,10 CONTROL "Enable DVD Video support",IDC_DVD_VIDEO,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,217,313,10 END ///////////////////////////////////////////////////////////////////////////// // // DESIGNINFO // #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO BEGIN IDD_PROPPAGE_VIDEO_SETTINGS, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 404 TOPMARGIN, 7 BOTTOMMARGIN, 290 END IDD_PROPPAGE_FORMATS, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 394 TOPMARGIN, 7 BOTTOMMARGIN, 243 END END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // AFX_DIALOG_LAYOUT // IDD_PROPPAGE_VIDEO_SETTINGS AFX_DIALOG_LAYOUT BEGIN 0 END ///////////////////////////////////////////////////////////////////////////// // // String Table // STRINGTABLE BEGIN IDS_SETTINGS "Video Settings" IDS_FORMATS "Formats" IDS_FIELDORDER_AUTO "Auto" IDS_FIELDORDER_TOP "Top-Field First" IDS_FIELDORDER_BOTTOM "Bottom-Field First" IDS_DEINTMODE_AUTO "Auto" IDS_DEINTMODE_AGGRESSIVE "Aggressive" IDS_DEINTMODE_FORCE "Force" IDS_DEINTMODE_DISABLE "Disabled (Progressive)" END #endif // English (United States) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #include "LAVVideo.rc2" // non-Microsoft Visual C++ edited resources #endif ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ================================================ FILE: decoder/LAVVideo/LAVVideo.rc2 ================================================ // // LAVVideo.rc2 - resources Microsoft Visual C++ does not edit directly // #ifdef APSTUDIO_INVOKED #error This file is not editable by Microsoft Visual C++ #endif //APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // Add manually edited resources here... ///////////////////////////////////////////////////////////////////////////// #include "resource.h" #include "..\..\common\includes\version.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources ///////////////////////////////////////////////////////////////////////////// // Neutral (Sys. Default) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION LAV_VERSION_TAG PRODUCTVERSION LAV_VERSION_TAG FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", "1f0.de - Hendrik Leppkes" VALUE "FileDescription", "LAV Video Decoder - DirectShow Video Decoder" VALUE "FileVersion", LAV_VERSION_STR VALUE "InternalName", "LAVVideo.ax" VALUE "LegalCopyright", "Copyright (C) 2010-2021 Hendrik Leppkes" VALUE "OriginalFilename", "LAVVideo.ax" VALUE "ProductName", "LAV Video Decoder" VALUE "ProductVersion", LAV_VERSION_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif ================================================ FILE: decoder/LAVVideo/LAVVideo.vcxproj ================================================  Debug Win32 Debug x64 Release Win32 Release x64 {D29ADED3-086B-46A8-9455-97EFF6B14775} Win32Proj LAVVideo DynamicLibrary true Unicode DynamicLibrary false true Unicode .ax $(SolutionDir)bin_$(PlatformName)d\ .ax $(SolutionDir)bin_$(PlatformName)\$(ProjectName)\ Build WIN32;_DEBUG;_WINDOWS;_USRDLL;LAVVIDEO_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories);$(SolutionDir)qsdecoder;$(ProjectDir)decoders\mvc\include advapi32.lib;ole32.lib;gdi32.lib;winmm.lib;user32.lib;oleaut32.lib;shell32.lib;Shlwapi.lib;Comctl32.lib;d3d9.lib;mfuuid.lib;dmoguids.lib;avutil-lav.lib;avcodec-lav.lib;swscale-lav.lib;avfilter-lav.lib;libmfx.lib LAVVideo.def $(ProjectDir)decoders\mvc\lib32;%(AdditionalLibraryDirectories) $(ProjectDir)decoders\mvc\lib64;%(AdditionalLibraryDirectories) libcmt.lib $(ProjectDir)\$(ProjectName).manifest %(AdditionalManifestFiles) WIN32;NDEBUG;_WINDOWS;_USRDLL;LAVVIDEO_EXPORTS;%(PreprocessorDefinitions) %(AdditionalIncludeDirectories);$(SolutionDir)qsdecoder;$(ProjectDir)decoders\mvc\include advapi32.lib;ole32.lib;gdi32.lib;winmm.lib;user32.lib;oleaut32.lib;shell32.lib;Shlwapi.lib;Comctl32.lib;d3d9.lib;mfuuid.lib;dmoguids.lib;avutil-lav.lib;avcodec-lav.lib;swscale-lav.lib;avfilter-lav.lib;libmfx.lib LAVVideo.def $(ProjectDir)decoders\mvc\lib32;%(AdditionalLibraryDirectories) $(ProjectDir)decoders\mvc\lib64;%(AdditionalLibraryDirectories) copy "$(TargetDir)\$(TargetName)$(TargetExt)" "$(OutDir).." $(OutDir)..\$(TargetFileName) $(TargetDir)\$(TargetName)$(TargetExt) $(ProjectDir)\$(ProjectName).manifest %(AdditionalManifestFiles) Create {e8a3f6fa-ae1c-4c8e-a0b6-9c8480324eaa} {0a058024-41f4-4509-97d2-803a1806ce86} ================================================ FILE: decoder/LAVVideo/LAVVideo.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {30aabf4d-c49c-4299-82a6-eda004fc7b22} {a78d7ea2-1b41-4d14-bcbc-7367aee8f548} {785bf298-6050-43e0-81d0-54dd1389be17} {4b09de39-e456-4b36-98fa-aba7f24526bd} {e2f0f0cd-c474-4ba2-aa2e-dd8e689907e7} {c5cd3602-30d6-48ff-8100-230758b36fb4} {2417dd22-d693-40ad-a3f7-a6e3b4e22b9d} {d3bbf10b-cfb1-45d9-8cb4-6323349e6b22} {fb30ec43-26d9-4ea0-950b-4a055654a2e6} {edcd1461-a03c-4080-84ef-a1e5d2e4f2b4} {313fee8a-af36-434b-9ac0-808a14d70bb0} {aa256837-6553-43d3-bdf9-bce2e149fb21} {5bef8a26-ba3d-4eb9-aa69-0bfaf1c6a433} Source Files Source Files Source Files Source Files Source Files Source Files Source Files\parsers Source Files\parsers Source Files\pixconv Source Files\pixconv Source Files\pixconv Source Files\pixconv Source Files\pixconv Source Files\pixconv Source Files\decoders Source Files\decoders Source Files\decoders Source Files\parsers Source Files\pixconv Source Files Source Files\decoders Source Files\decoders Source Files Source Files\decoders\dxva2 Source Files\subtitles Source Files\subtitles Source Files\subtitles Source Files\subtitles Source Files\subtitles\blend Source Files\subtitles Source Files Source Files\pixconv Source Files\decoders Source Files\parsers Source Files\parsers Source Files\pixconv Source Files\decoders Source Files Source Files\decoders\dxva2 Source Files\decoders Source Files\decoders\d3d11 Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files\parsers Header Files\parsers Header Files\pixconv Header Files\pixconv Header Files\decoders Header Files\decoders Header Files\decoders Header Files\decoders Header Files\parsers Header Files\decoders Header Files\decoders Header Files Header Files\decoders\dxva2 Header Files\subtitles Header Files\subtitles Header Files\subtitles Header Files\subtitles Header Files\subtitles Header Files\subtitles Header Files Header Files\decoders Header Files\parsers Header Files\parsers Header Files\decoders Header Files Header Files\decoders\dxva2 Header Files\decoders Header Files\decoders\d3d11 Header Files Header Files Header Files Header Files Header Files\decoders\d3d11 Resource Files Resource Files Resource Files Resource Files ================================================ FILE: decoder/LAVVideo/Media.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVVideo.h" #include "Media.h" #include #include #include "moreuuids.h" typedef struct { const CLSID *clsMinorType; const enum AVCodecID nFFCodec; } FFMPEG_SUBTYPE_MAP; // clang-format off // Map Media Subtype <> FFMPEG Codec Id static const FFMPEG_SUBTYPE_MAP lavc_video_codecs[] = { // H264 { &MEDIASUBTYPE_H264, AV_CODEC_ID_H264 }, { &MEDIASUBTYPE_h264, AV_CODEC_ID_H264 }, { &MEDIASUBTYPE_X264, AV_CODEC_ID_H264 }, { &MEDIASUBTYPE_x264, AV_CODEC_ID_H264 }, { &MEDIASUBTYPE_AVC1, AV_CODEC_ID_H264 }, { &MEDIASUBTYPE_avc1, AV_CODEC_ID_H264 }, { &MEDIASUBTYPE_CCV1, AV_CODEC_ID_H264 }, // Used by Haali Splitter { &MEDIASUBTYPE_H264_bis, AV_CODEC_ID_H264}, // MainConcept specific { &MEDIASUBTYPE_AMVC, AV_CODEC_ID_H264_MVC }, { &MEDIASUBTYPE_MVC1, AV_CODEC_ID_H264_MVC }, // HEVC { &MEDIASUBTYPE_HEVC, AV_CODEC_ID_HEVC }, { &MEDIASUBTYPE_HVC1, AV_CODEC_ID_HEVC }, { &MEDIASUBTYPE_HM10, AV_CODEC_ID_HEVC }, { &MEDIASUBTYPE_H265, AV_CODEC_ID_HEVC }, // VVC { &MEDIASUBTYPE_VVC1, AV_CODEC_ID_VVC }, // MPEG1/2 { &MEDIASUBTYPE_MPEG1Payload, AV_CODEC_ID_MPEG1VIDEO }, { &MEDIASUBTYPE_MPEG1Video, AV_CODEC_ID_MPEG1VIDEO }, { &MEDIASUBTYPE_MPEG2_VIDEO, AV_CODEC_ID_MPEG2VIDEO }, // MJPEG { &MEDIASUBTYPE_MJPG, AV_CODEC_ID_MJPEG }, { &MEDIASUBTYPE_QTJpeg, AV_CODEC_ID_MJPEG }, { &MEDIASUBTYPE_MJPA, AV_CODEC_ID_MJPEG }, { &MEDIASUBTYPE_MJPB, AV_CODEC_ID_MJPEGB }, { &MEDIASUBTYPE_MJPGB, AV_CODEC_ID_MJPEGB }, { &MEDIASUBTYPE_LJPG, AV_CODEC_ID_JPEGLS }, { &MEDIASUBTYPE_JPGL, AV_CODEC_ID_JPEGLS }, { &MEDIASUBTYPE_MJLS, AV_CODEC_ID_JPEGLS }, // VC-1 { &MEDIASUBTYPE_WVC1, AV_CODEC_ID_VC1 }, { &MEDIASUBTYPE_wvc1, AV_CODEC_ID_VC1 }, { &MEDIASUBTYPE_WMVA, AV_CODEC_ID_VC1 }, { &MEDIASUBTYPE_wmva, AV_CODEC_ID_VC1 }, { &MEDIASUBTYPE_WVP2, AV_CODEC_ID_VC1IMAGE }, { &MEDIASUBTYPE_wvp2, AV_CODEC_ID_VC1IMAGE }, // WMV { &MEDIASUBTYPE_WMV1, AV_CODEC_ID_WMV1 }, { &MEDIASUBTYPE_wmv1, AV_CODEC_ID_WMV1 }, { &MEDIASUBTYPE_WMV2, AV_CODEC_ID_WMV2 }, { &MEDIASUBTYPE_wmv2, AV_CODEC_ID_WMV2 }, { &MEDIASUBTYPE_2VMW, AV_CODEC_ID_WMV2 }, { &MEDIASUBTYPE_WMV3, AV_CODEC_ID_WMV3 }, { &MEDIASUBTYPE_wmv3, AV_CODEC_ID_WMV3 }, { &MEDIASUBTYPE_WMVP, AV_CODEC_ID_WMV3IMAGE }, { &MEDIASUBTYPE_wmvp, AV_CODEC_ID_WMV3IMAGE }, // VP7/8/9 { &MEDIASUBTYPE_VP70, AV_CODEC_ID_VP7 }, { &MEDIASUBTYPE_VP80, AV_CODEC_ID_VP8 }, { &MEDIASUBTYPE_VP90, AV_CODEC_ID_VP9 }, // AV1 { &MEDIASUBTYPE_AV01, AV_CODEC_ID_AV1 }, // MPEG4 ASP { &MEDIASUBTYPE_XVID, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_xvid, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_DIVX, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_divx, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_Divx, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_DX50, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_dx50, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_MP4V, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_mp4v, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_M4S2, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_m4s2, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_MP4S, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_mp4s, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_FMP4, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_3IVX, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_3ivx, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_3IV1, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_3iv1, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_3IV2, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_3iv2, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_BLZ0, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_GEOV, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_SEDG, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_SMP4, AV_CODEC_ID_MPEG4 }, { &MEDIASUBTYPE_DXGM, AV_CODEC_ID_MPEG4 }, // MS-MPEG4 { &MEDIASUBTYPE_MPG4, AV_CODEC_ID_MSMPEG4V1 }, { &MEDIASUBTYPE_mpg4, AV_CODEC_ID_MSMPEG4V1 }, { &MEDIASUBTYPE_MP41, AV_CODEC_ID_MSMPEG4V1 }, { &MEDIASUBTYPE_mp41, AV_CODEC_ID_MSMPEG4V1 }, { &MEDIASUBTYPE_DIV1, AV_CODEC_ID_MSMPEG4V1 }, { &MEDIASUBTYPE_div1, AV_CODEC_ID_MSMPEG4V1 }, { &MEDIASUBTYPE_MP42, AV_CODEC_ID_MSMPEG4V2 }, { &MEDIASUBTYPE_mp42, AV_CODEC_ID_MSMPEG4V2 }, { &MEDIASUBTYPE_DIV2, AV_CODEC_ID_MSMPEG4V2 }, { &MEDIASUBTYPE_div2, AV_CODEC_ID_MSMPEG4V2 }, { &MEDIASUBTYPE_MP43, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_mp43, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_DIV3, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_div3, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_MPG3, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_mpg3, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_DIV4, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_div4, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_DIV5, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_div5, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_DIV6, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_div6, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_DVX3, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_dvx3, AV_CODEC_ID_MSMPEG4V3 }, { &MEDIASUBTYPE_3IVD, AV_CODEC_ID_MSMPEG4V3 }, // Flash { &MEDIASUBTYPE_FLV1, AV_CODEC_ID_FLV1 }, { &MEDIASUBTYPE_flv1, AV_CODEC_ID_FLV1 }, { &MEDIASUBTYPE_VP60, AV_CODEC_ID_VP6 }, { &MEDIASUBTYPE_vp60, AV_CODEC_ID_VP6 }, { &MEDIASUBTYPE_VP61, AV_CODEC_ID_VP6 }, { &MEDIASUBTYPE_vp61, AV_CODEC_ID_VP6 }, { &MEDIASUBTYPE_VP62, AV_CODEC_ID_VP6 }, { &MEDIASUBTYPE_vp62, AV_CODEC_ID_VP6 }, { &MEDIASUBTYPE_VP6A, AV_CODEC_ID_VP6A }, { &MEDIASUBTYPE_vp6a, AV_CODEC_ID_VP6A }, { &MEDIASUBTYPE_VP6F, AV_CODEC_ID_VP6F }, { &MEDIASUBTYPE_vp6f, AV_CODEC_ID_VP6F }, { &MEDIASUBTYPE_FLV4, AV_CODEC_ID_VP6F }, { &MEDIASUBTYPE_flv4, AV_CODEC_ID_VP6F }, { &MEDIASUBTYPE_FSV1, AV_CODEC_ID_FLASHSV }, // Real { &MEDIASUBTYPE_RV10, AV_CODEC_ID_RV10 }, { &MEDIASUBTYPE_RV20, AV_CODEC_ID_RV20 }, { &MEDIASUBTYPE_RV30, AV_CODEC_ID_RV30 }, { &MEDIASUBTYPE_RV40, AV_CODEC_ID_RV40 }, // DV Video { &MEDIASUBTYPE_dvsd, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVSD, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_CDVH, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_CDVC, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_CDV5, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_dv25, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DV25, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_dv50, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DV50, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVCP, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DV5P, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DV5N, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVPP, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVC, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVH1, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVH2, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVH3, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVH4, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVH5, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVH6, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVHQ, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_DVHP, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_AVdv, AV_CODEC_ID_DVVIDEO }, { &MEDIASUBTYPE_AVd1, AV_CODEC_ID_DVVIDEO }, // JPEG 2000 { &MEDIASUBTYPE_mjp2, AV_CODEC_ID_JPEG2000 }, { &MEDIASUBTYPE_MJ2C, AV_CODEC_ID_JPEG2000 }, { &MEDIASUBTYPE_LJ2C, AV_CODEC_ID_JPEG2000 }, { &MEDIASUBTYPE_LJ2K, AV_CODEC_ID_JPEG2000 }, { &MEDIASUBTYPE_IPJ2, AV_CODEC_ID_JPEG2000 }, // Misc Formats { &MEDIASUBTYPE_SVQ1, AV_CODEC_ID_SVQ1 }, { &MEDIASUBTYPE_SVQ3, AV_CODEC_ID_SVQ3 }, { &MEDIASUBTYPE_H261, AV_CODEC_ID_H261 }, { &MEDIASUBTYPE_h261, AV_CODEC_ID_H261 }, { &MEDIASUBTYPE_H263, AV_CODEC_ID_H263 }, { &MEDIASUBTYPE_h263, AV_CODEC_ID_H263 }, { &MEDIASUBTYPE_S263, AV_CODEC_ID_H263 }, { &MEDIASUBTYPE_s263, AV_CODEC_ID_H263 }, { &MEDIASUBTYPE_I263, AV_CODEC_ID_H263I }, { &MEDIASUBTYPE_i263, AV_CODEC_ID_H263I }, { &MEDIASUBTYPE_THEORA, AV_CODEC_ID_THEORA }, { &MEDIASUBTYPE_theora, AV_CODEC_ID_THEORA }, { &MEDIASUBTYPE_TSCC, AV_CODEC_ID_TSCC }, { &MEDIASUBTYPE_TSC2, AV_CODEC_ID_TSCC2 }, { &MEDIASUBTYPE_IV50, AV_CODEC_ID_INDEO5 }, { &MEDIASUBTYPE_IV41, AV_CODEC_ID_INDEO4 }, { &MEDIASUBTYPE_IV31, AV_CODEC_ID_INDEO3 }, { &MEDIASUBTYPE_IV32, AV_CODEC_ID_INDEO3 }, { &MEDIASUBTYPE_RT21, AV_CODEC_ID_INDEO2 }, { &MEDIASUBTYPE_FPS1, AV_CODEC_ID_FRAPS }, { &MEDIASUBTYPE_HuffYUV, AV_CODEC_ID_HUFFYUV }, { &MEDIASUBTYPE_Lagarith, AV_CODEC_ID_LAGARITH }, { &MEDIASUBTYPE_CVID, AV_CODEC_ID_CINEPAK }, { &MEDIASUBTYPE_QTRle, AV_CODEC_ID_QTRLE }, { &MEDIASUBTYPE_VP30, AV_CODEC_ID_VP3 }, { &MEDIASUBTYPE_VP31, AV_CODEC_ID_VP3 }, { &MEDIASUBTYPE_VP40, AV_CODEC_ID_VP4 }, { &MEDIASUBTYPE_CSCD, AV_CODEC_ID_CSCD }, { &MEDIASUBTYPE_QPEG, AV_CODEC_ID_QPEG }, { &MEDIASUBTYPE_QP10, AV_CODEC_ID_QPEG }, { &MEDIASUBTYPE_QP11, AV_CODEC_ID_QPEG }, { &MEDIASUBTYPE_MSZH, AV_CODEC_ID_MSZH }, { &MEDIASUBTYPE_ZLIB, AV_CODEC_ID_ZLIB }, { &MEDIASUBTYPE_QTRpza, AV_CODEC_ID_RPZA }, { &MEDIASUBTYPE_PCM, AV_CODEC_ID_MSRLE }, // Yeah, PCM. Its the same FourCC as used by MS-RLE { &MEDIASUBTYPE_apch, AV_CODEC_ID_PRORES }, { &MEDIASUBTYPE_apcn, AV_CODEC_ID_PRORES }, { &MEDIASUBTYPE_apcs, AV_CODEC_ID_PRORES }, { &MEDIASUBTYPE_apco, AV_CODEC_ID_PRORES }, { &MEDIASUBTYPE_ap4h, AV_CODEC_ID_PRORES }, { &MEDIASUBTYPE_ap4x, AV_CODEC_ID_PRORES }, { &MEDIASUBTYPE_ULRA, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_ULRG, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_ULY0, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_ULY2, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_ULY4, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UQY2, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UQRG, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UQRA, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_ULH0, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_ULH2, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_ULH4, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UMY2, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UMH2, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UMY4, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UMH4, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UMRG, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_UMRA, AV_CODEC_ID_UTVIDEO }, { &MEDIASUBTYPE_AMVV, AV_CODEC_ID_AMV }, { &MEDIASUBTYPE_AMVF, AV_CODEC_ID_AMV }, { &MEDIASUBTYPE_DiracVideo, AV_CODEC_ID_DIRAC }, { &MEDIASUBTYPE_DRAC, AV_CODEC_ID_DIRAC }, { &MEDIASUBTYPE_AVdn, AV_CODEC_ID_DNXHD }, { &MEDIASUBTYPE_AVdh, AV_CODEC_ID_DNXHD }, { &MEDIASUBTYPE_CRAM, AV_CODEC_ID_MSVIDEO1 }, { &MEDIASUBTYPE_MSVC, AV_CODEC_ID_MSVIDEO1 }, { &MEDIASUBTYPE_WHAM, AV_CODEC_ID_MSVIDEO1 }, { &MEDIASUBTYPE_8BPS, AV_CODEC_ID_8BPS }, { &MEDIASUBTYPE_LOCO, AV_CODEC_ID_LOCO }, { &MEDIASUBTYPE_ZMBV, AV_CODEC_ID_ZMBV }, { &MEDIASUBTYPE_VCR1, AV_CODEC_ID_VCR1 }, { &MEDIASUBTYPE_AASC, AV_CODEC_ID_AASC }, { &MEDIASUBTYPE_SNOW, AV_CODEC_ID_SNOW }, { &MEDIASUBTYPE_FFV1, AV_CODEC_ID_FFV1 }, { &MEDIASUBTYPE_FFVH, AV_CODEC_ID_FFVHUFF }, { &MEDIASUBTYPE_VMNC, AV_CODEC_ID_VMNC }, { &MEDIASUBTYPE_FLIC, AV_CODEC_ID_FLIC }, //{ &MEDIASUBTYPE_G2M2, AV_CODEC_ID_G2M }, //{ &MEDIASUBTYPE_G2M3, AV_CODEC_ID_G2M }, { &MEDIASUBTYPE_G2M4, AV_CODEC_ID_G2M }, { &MEDIASUBTYPE_G2M5, AV_CODEC_ID_G2M }, { &MEDIASUBTYPE_icod, AV_CODEC_ID_AIC }, { &MEDIASUBTYPE_DUCK, AV_CODEC_ID_TRUEMOTION1 }, { &MEDIASUBTYPE_TM20, AV_CODEC_ID_TRUEMOTION2 }, { &MEDIASUBTYPE_CFHD, AV_CODEC_ID_CFHD }, { &MEDIASUBTYPE_MAGY, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_M8RG, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_M8RA, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_M8G0, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_M8Y0, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_M8Y2, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_M8Y4, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_M8YA, AV_CODEC_ID_MAGICYUV }, { &MEDIASUBTYPE_FICV, AV_CODEC_ID_FIC }, { &MEDIASUBTYPE_QTSmc, AV_CODEC_ID_SMC }, { &MEDIASUBTYPE_smc, AV_CODEC_ID_SMC }, { &MEDIASUBTYPE_VIXL, AV_CODEC_ID_VIXL }, { &MEDIASUBTYPE_ULTI, AV_CODEC_ID_ULTI }, { &MEDIASUBTYPE_WNV1, AV_CODEC_ID_WNV1 }, { &MEDIASUBTYPE_CYUV, AV_CODEC_ID_CYUV }, { &MEDIASUBTYPE_AVS1, AV_CODEC_ID_ASV1 }, { &MEDIASUBTYPE_AVS2, AV_CODEC_ID_ASV2 }, { &MEDIASUBTYPE_AVRn, AV_CODEC_ID_AVRN }, { &MEDIASUBTYPE_SP5X, AV_CODEC_ID_SP5X }, { &MEDIASUBTYPE_SP54, AV_CODEC_ID_SP5X }, { &MEDIASUBTYPE_Hap1, AV_CODEC_ID_HAP }, { &MEDIASUBTYPE_Hap5, AV_CODEC_ID_HAP }, { &MEDIASUBTYPE_HapY, AV_CODEC_ID_HAP }, { &MEDIASUBTYPE_DXD3, AV_CODEC_ID_DXV }, { &MEDIASUBTYPE_DXDI, AV_CODEC_ID_DXV }, { &MEDIASUBTYPE_ARBC, AV_CODEC_ID_ARBC }, { &MEDIASUBTYPE_KGV1, AV_CODEC_ID_KGV1 }, { &MEDIASUBTYPE_APV1, AV_CODEC_ID_APV }, // Game Formats { &MEDIASUBTYPE_BIKI, AV_CODEC_ID_BINKVIDEO }, { &MEDIASUBTYPE_BIKB, AV_CODEC_ID_BINKVIDEO }, { &MEDIASUBTYPE_BIKf, AV_CODEC_ID_BINKVIDEO }, { &MEDIASUBTYPE_SMK2, AV_CODEC_ID_SMACKVIDEO }, { &MEDIASUBTYPE_SMK4, AV_CODEC_ID_SMACKVIDEO }, { &MEDIASUBTYPE_THPV, AV_CODEC_ID_THP }, { &MEDIASUBTYPE_ROQV, AV_CODEC_ID_ROQ }, // Image Formats { &MEDIASUBTYPE_PNG, AV_CODEC_ID_PNG }, { &MEDIASUBTYPE_TIFF, AV_CODEC_ID_TIFF }, { &MEDIASUBTYPE_BMP, AV_CODEC_ID_BMP }, { &MEDIASUBTYPE_GIF, AV_CODEC_ID_GIF }, { &MEDIASUBTYPE_TGA, AV_CODEC_ID_TARGA }, { &MEDIASUBTYPE_WEBP, AV_CODEC_ID_WEBP }, // Special raw formats { &MEDIASUBTYPE_v210, AV_CODEC_ID_V210 }, { &MEDIASUBTYPE_v410, AV_CODEC_ID_V410 }, { &MEDIASUBTYPE_LAV_RAWVIDEO, AV_CODEC_ID_RAWVIDEO }, }; // Define Input Media Types const AMOVIESETUP_MEDIATYPE CLAVVideo::sudPinTypesIn[] = { // H264 { &MEDIATYPE_Video, &MEDIASUBTYPE_H264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_h264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_X264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_x264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_avc1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CCV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_H264_bis }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AMVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MVC1 }, // HEVC { &MEDIATYPE_Video, &MEDIASUBTYPE_HEVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HM10 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_H265 }, // VVC { &MEDIATYPE_Video, &MEDIASUBTYPE_VVC1 }, // MPEG1/2 { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Payload }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Video }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG2_VIDEO }, { &MEDIATYPE_DVD_ENCRYPTED_PACK, &MEDIASUBTYPE_MPEG2_VIDEO }, { &MEDIATYPE_MPEG2_PACK, &MEDIASUBTYPE_MPEG2_VIDEO }, { &MEDIATYPE_MPEG2_PES, &MEDIASUBTYPE_MPEG2_VIDEO }, // MJPEG { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTJpeg }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPB }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPGB }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LJPG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_JPGL }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJLS }, // VC-1 { &MEDIATYPE_Video, &MEDIASUBTYPE_WVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wvc1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMVA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmva }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WVP2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wvp2 }, // WMV { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_2VMW }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMVP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmvp }, // VP7/8/9 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP70 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP80 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP90 }, // AV1 { &MEDIATYPE_Video, &MEDIASUBTYPE_AV01 }, // MPEG4 ASP { &MEDIATYPE_Video, &MEDIASUBTYPE_XVID }, { &MEDIATYPE_Video, &MEDIASUBTYPE_xvid }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIVX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_divx }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Divx }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DX50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dx50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP4V }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp4v }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M4S2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_m4s2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP4S }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp4s }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IVX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3ivx }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3iv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3iv2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BLZ0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_GEOV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SEDG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DXGM }, // MS-MPEG4 { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mpg4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP42 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp42 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP43 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp43 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mpg3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVX3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvx3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IVD }, // Flash { &MEDIATYPE_Video, &MEDIASUBTYPE_FLV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_flv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP60 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp60 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP61 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp61 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP62 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp62 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP6A }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp6a }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP6F }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp6f }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FLV4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_flv4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FSV1 }, // Real { &MEDIATYPE_Video, &MEDIASUBTYPE_RV10 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV20 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV30 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV40 }, // DV Video { &MEDIATYPE_Video, &MEDIASUBTYPE_dvsd }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVSD }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CDVH }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CDVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CDV5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dv25 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DV25 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dv50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DV50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVCP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DV5P }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DV5N }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVPP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVHQ }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVHP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdv }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVd1 }, // JPEG 2000 { &MEDIATYPE_Video, &MEDIASUBTYPE_mjp2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJ2C }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LJ2C }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LJ2K }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IPJ2 }, // Misc Formats { &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_H261 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_h261 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_H263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_h263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_S263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_s263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_I263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_i263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_THEORA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_theora }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TSCC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TSC2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV31 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV32 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RT21 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FPS1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HuffYUV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Lagarith }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CVID }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTRle }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP30 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP31 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP40 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CSCD }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QPEG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QP10 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QP11 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSZH }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ZLIB }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTRpza }, { &MEDIATYPE_Video, &MEDIASUBTYPE_PCM }, // Yeah, PCM. Its the same FourCC as used by MS-RLE { &MEDIATYPE_Video, &MEDIASUBTYPE_apch }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apcn }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apcs }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apco }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap4h }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap4x }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULY0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULY4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UQY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UQRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UQRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULH0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULH4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMY4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMH4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AMVV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AMVF }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DiracVideo }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DRAC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdn }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdh }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CRAM }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WHAM }, { &MEDIATYPE_Video, &MEDIASUBTYPE_8BPS }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LOCO }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ZMBV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VCR1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AASC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SNOW }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFVH }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VMNC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FLIC }, //{ &MEDIATYPE_Video, &MEDIASUBTYPE_G2M2 }, //{ &MEDIATYPE_Video, &MEDIASUBTYPE_G2M3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_icod }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DUCK }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TM20 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CFHD }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MAGY }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M8RG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M8RA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M8G0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M8Y0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M8Y2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M8Y4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M8YA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FICV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTSmc }, { &MEDIATYPE_Video, &MEDIASUBTYPE_smc, }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VIXL }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ULTI }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WNV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CYUV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVS1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVS2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVRn }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SP5X }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SP54 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Hap1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Hap5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HapY }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DXD3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DXDI }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ARBC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_KGV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_APV1 }, // Game Formats { &MEDIATYPE_Video, &MEDIASUBTYPE_BIKI }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BIKB }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BIKf }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SMK2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SMK4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_THPV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ROQV }, // Image Formats { &MEDIATYPE_Video, &MEDIASUBTYPE_PNG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TIFF }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BMP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_GIF }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TGA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WEBP }, // Special raw formats { &MEDIATYPE_Video, &MEDIASUBTYPE_v210 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_v410 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LAV_RAWVIDEO }, }; const UINT CLAVVideo::sudPinTypesInCount = countof(CLAVVideo::sudPinTypesIn); // Define Output Media Types const AMOVIESETUP_MEDIATYPE CLAVVideo::sudPinTypesOut[] = { { &MEDIATYPE_Video, &MEDIASUBTYPE_YV12 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_NV12 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YUY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UYVY }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RGB32 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RGB24 }, }; const UINT CLAVVideo::sudPinTypesOutCount = countof(CLAVVideo::sudPinTypesOut); // Crawl the lavc_video_codecs array for the proper codec AVCodecID FindCodecId(const CMediaType *mt) { for (int i = 0; i < countof(lavc_video_codecs); ++i) { if (mt->subtype == *lavc_video_codecs[i].clsMinorType) { return lavc_video_codecs[i].nFFCodec; } } return AV_CODEC_ID_NONE; } // Strings will be filled in eventually. // AV_CODEC_ID_NONE means there is some special handling going on. // Order is Important, has to be the same as the CC Enum // Also, the order is used for storage in the Registry static codec_config_t m_codec_config[] = { { 1, { AV_CODEC_ID_H264 }}, // Codec_H264 { 2, { AV_CODEC_ID_VC1, AV_CODEC_ID_VC1IMAGE }}, // Codec_VC1 { 1, { AV_CODEC_ID_MPEG1VIDEO }, "mpeg1"}, // Codec_MPEG1 { 1, { AV_CODEC_ID_MPEG2VIDEO }, "mpeg2"}, // Codec_MPEG2 { 1, { AV_CODEC_ID_MPEG4 }}, // Codec_MPEG4 { 3, { AV_CODEC_ID_MSMPEG4V1, AV_CODEC_ID_MSMPEG4V2, AV_CODEC_ID_MSMPEG4V3 }, "msmpeg4", "MS-MPEG-4 (DIVX3)" }, // Codec_MSMPEG4 { 1, { AV_CODEC_ID_VP8 }}, // Codec_VP8 { 2, { AV_CODEC_ID_WMV3, AV_CODEC_ID_WMV3IMAGE }}, // Codec_WMV3 { 2, { AV_CODEC_ID_WMV1, AV_CODEC_ID_WMV2 }, "wmv12", "Windows Media Video 7/8" }, // Codec_WMV12 { 3, { AV_CODEC_ID_MJPEG, AV_CODEC_ID_MJPEGB, AV_CODEC_ID_AMV }}, // Codec_MJPEG { 2, { AV_CODEC_ID_THEORA, AV_CODEC_ID_VP3 }}, // Codec_Theora { 2, { AV_CODEC_ID_FLV1, AV_CODEC_ID_FLASHSV }, "flash", "Flash Video (FLV1, FSV1)"}, // Codec_FLV1 { 3, { AV_CODEC_ID_VP6, AV_CODEC_ID_VP6A, AV_CODEC_ID_VP6F }}, // Codec_VP6 { 2, { AV_CODEC_ID_SVQ1, AV_CODEC_ID_SVQ3 }, "svq", "SVQ 1 / SVQ 3"}, // Codec_SVQ { 1, { AV_CODEC_ID_H261 }}, // Codec_H261 { 2, { AV_CODEC_ID_H263, AV_CODEC_ID_H263I }}, // Codec_H263 { 3, { AV_CODEC_ID_INDEO3, AV_CODEC_ID_INDEO4, AV_CODEC_ID_INDEO5 }, "indeo", "Intel Indeo 3/4/5"}, // Codec_Indeo { 2, { AV_CODEC_ID_TSCC, AV_CODEC_ID_TSCC2 }}, // Codec_TSCC { 1, { AV_CODEC_ID_FRAPS }}, // Codec_Fraps { 2, { AV_CODEC_ID_HUFFYUV, AV_CODEC_ID_FFVHUFF }}, // Codec_HuffYUV { 1, { AV_CODEC_ID_QTRLE }}, // Codec_QTRle { 1, { AV_CODEC_ID_DVVIDEO }}, // Codec_DV { 1, { AV_CODEC_ID_BINKVIDEO }, "bink"}, // Codec_Bink { 1, { AV_CODEC_ID_SMACKVIDEO }}, // Codec_Smacker { 2, { AV_CODEC_ID_RV10, AV_CODEC_ID_RV20 }, "rv12", "RealVideo 1/2" }, // Codev_RV12 { 2, { AV_CODEC_ID_RV30, AV_CODEC_ID_RV40 }, "rv34", "RealVideo 3/4" }, // Codec_RV34 { 1, { AV_CODEC_ID_LAGARITH }}, // Codec_Lagarith { 1, { AV_CODEC_ID_CINEPAK }}, // Codec_Cinepak { 1, { AV_CODEC_ID_CSCD }}, // Codec_Camstudio { 1, { AV_CODEC_ID_QPEG }}, // Codec_QPEG { 2, { AV_CODEC_ID_ZLIB, AV_CODEC_ID_MSZH }, "zlib", "ZLIB/MSZH lossless" }, // Codec_ZLIB { 1, { AV_CODEC_ID_RPZA }}, // Codec_QTRpza { 1, { AV_CODEC_ID_PNG }}, // Codec_PNG { 2, { AV_CODEC_ID_MSRLE, AV_CODEC_ID_AASC }}, // Codec_MSRLE { 1, { AV_CODEC_ID_PRORES }}, // Codec_ProRes { 1, { AV_CODEC_ID_UTVIDEO }}, // Codec_UtVideo { 1, { AV_CODEC_ID_DIRAC }}, // Codec_Dirac { 1, { AV_CODEC_ID_DNXHD }}, // Codec_DNxHD { 1, { AV_CODEC_ID_MSVIDEO1 }}, // Codec_MSVideo1 { 1, { AV_CODEC_ID_8BPS }}, // Codec_8BPS { 1, { AV_CODEC_ID_LOCO }}, // Codec_LOCO { 1, { AV_CODEC_ID_ZMBV }}, // Codec_ZMBV { 1, { AV_CODEC_ID_VCR1 }}, // Codec_VCR1 { 1, { AV_CODEC_ID_SNOW }}, // Codec_Snow { 1, { AV_CODEC_ID_FFV1 }}, // Codec_FFV1 { 2, { AV_CODEC_ID_V210, AV_CODEC_ID_V410 }, "v210/v410", "v210/v410 uncompressed"}, // Codec_v210 { 1, { AV_CODEC_ID_JPEG2000 }}, // Codec_JPEG2000 { 1, { AV_CODEC_ID_VMNC }}, // Codec_VMNC { 1, { AV_CODEC_ID_FLIC }}, // Codec_FLIC { 1, { AV_CODEC_ID_G2M }}, // Codec_G2M { 1, { AV_CODEC_ID_AIC }, "icod", "Apple Intermediate Codec (ICOD)"}, // Codec_ICOD { 1, { AV_CODEC_ID_THP }}, // Codec_THP { 1, { AV_CODEC_ID_HEVC }}, // Codec_HEVC { 1, { AV_CODEC_ID_VP9 }}, // Codec_VP9 { 2, { AV_CODEC_ID_TRUEMOTION1, AV_CODEC_ID_TRUEMOTION2 }, "truemotion", "Duck TrueMotion 1/2"}, // Codec_TrueMotion { 1, { AV_CODEC_ID_VP7 }}, // Codec_VP7 { 1, { AV_CODEC_ID_H264_MVC }, "h264mvc", "H.264 MVC 3D" }, // Codec_H264MVC { 1, { AV_CODEC_ID_CFHD }}, // Codec_CineformHD { 1, { AV_CODEC_ID_MAGICYUV }}, // Codec_MagicYUV { 1, { AV_CODEC_ID_AV1 }}, // Codec_AV1 { 1, { AV_CODEC_ID_VVC }}, // Codec_VVC { 1, { AV_CODEC_ID_VP4 }}, // Codec_VP4 { 1, { AV_CODEC_ID_FIC }}, // Codec_FIC { 1, { AV_CODEC_ID_APV }}, // Codec_APV }; // clang-format off const codec_config_t *get_codec_config(LAVVideoCodec codec) { codec_config_t *config = &m_codec_config[codec]; const AVCodecDescriptor *desc = avcodec_descriptor_get(config->codecs[0]); if (desc) { if (!config->name) { config->name = desc->name; } if (!config->description) { config->description = desc->long_name; } } return &m_codec_config[codec]; } int flip_plane(BYTE *buffer, int stride, int height) { BYTE *line_buffer = (BYTE *)av_malloc(stride); BYTE *cur_front = buffer; BYTE *cur_back = buffer + (stride * (height - 1)); height /= 2; for (int i = 0; i < height; i++) { memcpy(line_buffer, cur_front, stride); memcpy(cur_front, cur_back, stride); memcpy(cur_back, line_buffer, stride); cur_front += stride; cur_back -= stride; } av_freep(&line_buffer); return 0; } void fillDXVAExtFormat(DXVA2_ExtendedFormat &fmt, int range, int primaries, int matrix, int transfer, int chroma_sample_location, bool bClear) { if (bClear) fmt.value = 0; if (range != -1) fmt.NominalRange = range ? DXVA2_NominalRange_0_255 : DXVA2_NominalRange_16_235; // Color Primaries switch(primaries) { case AVCOL_PRI_BT709: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709; break; case AVCOL_PRI_BT470M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysM; break; case AVCOL_PRI_BT470BG: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysBG; break; case AVCOL_PRI_SMPTE170M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE170M; break; case AVCOL_PRI_SMPTE240M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE240M; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_PRI_BT2020: fmt.VideoPrimaries = MFVideoPrimaries_BT2020; break; case AVCOL_PRI_SMPTE428: fmt.VideoPrimaries = MFVideoPrimaries_XYZ; break; case AVCOL_PRI_SMPTE431: fmt.VideoPrimaries = MFVideoPrimaries_DCI_P3; break; } // Color Space / Transfer Matrix switch (matrix) { case AVCOL_SPC_BT709: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT709; break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601; break; case AVCOL_SPC_SMPTE240M: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_SMPTE240M; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_SPC_BT2020_CL: case AVCOL_SPC_BT2020_NCL: fmt.VideoTransferMatrix = MFVideoTransferMatrix_BT2020_10; break; // Custom values, not official standard, but understood by madVR case AVCOL_SPC_FCC: fmt.VideoTransferMatrix = (DXVA2_VideoTransferMatrix)6; break; case AVCOL_SPC_YCGCO: fmt.VideoTransferMatrix = (DXVA2_VideoTransferMatrix)7; break; } // Color Transfer Function switch(transfer) { case AVCOL_TRC_BT709: case AVCOL_TRC_SMPTE170M: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_709; break; case AVCOL_TRC_BT2020_10: case AVCOL_TRC_BT2020_12: fmt.VideoTransferFunction = (matrix == AVCOL_SPC_BT2020_CL) ? MFVideoTransFunc_2020_const : MFVideoTransFunc_2020; break; case AVCOL_TRC_GAMMA22: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_22; break; case AVCOL_TRC_GAMMA28: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_28; break; case AVCOL_TRC_SMPTE240M: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_240M; break; case AVCOL_TRC_LINEAR: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_10; break; case AVCOL_TRC_LOG: fmt.VideoTransferFunction = MFVideoTransFunc_Log_100; break; case AVCOL_TRC_LOG_SQRT: fmt.VideoTransferFunction = MFVideoTransFunc_Log_316; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_TRC_SMPTEST2084: fmt.VideoTransferFunction = MFVideoTransFunc_2084; break; case AVCOL_TRC_ARIB_STD_B67: fmt.VideoTransferFunction = MFVideoTransFunc_HLG; break; } // Chroma location switch (chroma_sample_location) { case AVCHROMA_LOC_LEFT: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG2; break; case AVCHROMA_LOC_CENTER: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG1; break; case AVCHROMA_LOC_TOPLEFT: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_Cosited; break; } } void processFFHDRData(MediaSideDataHDR *sd, AVMasteringDisplayMetadata *ff) { if (!sd || !ff) return; // avcodec exports the display primaries in RGB order, we export them in GBR if (ff->has_primaries) { sd->display_primaries_x[0] = av_q2d(ff->display_primaries[1][0]); sd->display_primaries_y[0] = av_q2d(ff->display_primaries[1][1]); sd->display_primaries_x[1] = av_q2d(ff->display_primaries[2][0]); sd->display_primaries_y[1] = av_q2d(ff->display_primaries[2][1]); sd->display_primaries_x[2] = av_q2d(ff->display_primaries[0][0]); sd->display_primaries_y[2] = av_q2d(ff->display_primaries[0][1]); sd->white_point_x = av_q2d(ff->white_point[0]); sd->white_point_y = av_q2d(ff->white_point[1]); } if (ff->has_luminance) { sd->max_display_mastering_luminance = av_q2d(ff->max_luminance); sd->min_display_mastering_luminance = av_q2d(ff->min_luminance); } } void processFFHDR10PlusData(MediaSideDataHDR10Plus *sd, AVDynamicHDRPlus *ff, int width, int height) { if (!sd || !ff) return; if (ff->num_windows > 3) return; sd->num_windows = ff->num_windows; for (int i = 0; i < ff->num_windows; i++) { sd->windows[i].upper_left_corner_x = (int)av_q2d(ff->params[i].window_upper_left_corner_x) * (width - 1); sd->windows[i].upper_left_corner_y = (int)av_q2d(ff->params[i].window_upper_left_corner_y) * (height - 1); sd->windows[i].lower_right_corner_x = (int)av_q2d(ff->params[i].window_lower_right_corner_x) * (width - 1); sd->windows[i].lower_right_corner_y = (int)av_q2d(ff->params[i].window_lower_right_corner_y) * (height - 1); sd->windows[i].center_of_ellipse_x = ff->params[i].center_of_ellipse_x; sd->windows[i].center_of_ellipse_y = ff->params[i].center_of_ellipse_y; sd->windows[i].rotation_angle = ff->params[i].rotation_angle; sd->windows[i].semimajor_axis_internal_ellipse = ff->params[i].semimajor_axis_internal_ellipse; sd->windows[i].semimajor_axis_external_ellipse = ff->params[i].semimajor_axis_external_ellipse; sd->windows[i].semiminor_axis_external_ellipse = ff->params[i].semiminor_axis_external_ellipse; sd->windows[i].overlap_process_option = ff->params[i].overlap_process_option; for (int k = 0; k < 3; k++) sd->windows[i].maxscl[k] = av_q2d(ff->params[i].maxscl[k]); sd->windows[i].average_maxrgb = av_q2d(ff->params[i].average_maxrgb); sd->windows[i].num_distribution_maxrgb_percentiles = ff->params[i].num_distribution_maxrgb_percentiles; for (int k = 0; k < ff->params[i].num_distribution_maxrgb_percentiles; k++) { sd->windows[i].distribution_maxrgb_percentiles[k].percentage = ff->params[i].distribution_maxrgb[k].percentage; sd->windows[i].distribution_maxrgb_percentiles[k].percentile = av_q2d(ff->params[i].distribution_maxrgb[k].percentile); } sd->windows[i].fraction_bright_pixels = av_q2d(ff->params[i].fraction_bright_pixels); sd->windows[i].tone_mapping_flag = ff->params[i].tone_mapping_flag; if (sd->windows[i].tone_mapping_flag) { sd->windows[i].knee_point_x = av_q2d(ff->params[i].knee_point_x); sd->windows[i].knee_point_y = av_q2d(ff->params[i].knee_point_y); sd->windows[i].num_bezier_curve_anchors = ff->params[i].num_bezier_curve_anchors; for (int k = 0; k < ff->params[i].num_bezier_curve_anchors; k++) sd->windows[i].bezier_curve_anchors[k] = av_q2d(ff->params[i].bezier_curve_anchors[k]); } sd->windows[i].color_saturation_mapping_flag = ff->params[i].color_saturation_mapping_flag; if (sd->windows[i].color_saturation_mapping_flag) sd->windows[i].color_saturation_weight = av_q2d(ff->params[i].color_saturation_weight); } sd->targeted_system_display_maximum_luminance = av_q2d(ff->targeted_system_display_maximum_luminance); sd->targeted_system_display_actual_peak_luminance_flag = ff->targeted_system_display_actual_peak_luminance_flag; sd->num_rows_targeted_system_display_actual_peak_luminance = ff->num_rows_targeted_system_display_actual_peak_luminance; sd->num_cols_targeted_system_display_actual_peak_luminance = ff->num_cols_targeted_system_display_actual_peak_luminance; for (int i = 0; i < ff->num_rows_targeted_system_display_actual_peak_luminance; i++) for (int j = 0; j < ff->num_cols_targeted_system_display_actual_peak_luminance; j++) sd->targeted_system_display_actual_peak_luminance[i][j] = av_q2d(ff->targeted_system_display_actual_peak_luminance[i][j]); sd->mastering_display_actual_peak_luminance_flag = ff->mastering_display_actual_peak_luminance_flag; sd->num_rows_mastering_display_actual_peak_luminance = ff->num_rows_mastering_display_actual_peak_luminance; sd->num_cols_mastering_display_actual_peak_luminance = ff->num_cols_mastering_display_actual_peak_luminance; for (int i = 0; i < ff->num_rows_mastering_display_actual_peak_luminance; i++) for (int j = 0; j < ff->num_cols_mastering_display_actual_peak_luminance; j++) sd->mastering_display_actual_peak_luminance[i][j] = av_q2d(ff->mastering_display_actual_peak_luminance[i][j]); } void processFFDOVIData(MediaSideDataDOVIMetadata* sd, const AVDOVIMetadata* ff) { const AVDOVIRpuDataHeader *header = av_dovi_get_header(ff); const AVDOVIDataMapping *mapping = av_dovi_get_mapping(ff); const AVDOVIColorMetadata *color = av_dovi_get_color(ff); #define RPU_HDR(name) sd->Header.##name = header->##name; #define RPU_MAP(name) sd->Mapping.##name = mapping->##name; #define RPU_COLOR(name) sd->ColorMetadata.##name = color->##name; RPU_HDR(rpu_type); RPU_HDR(rpu_format); RPU_HDR(vdr_rpu_profile); RPU_HDR(vdr_rpu_level); RPU_HDR(chroma_resampling_explicit_filter_flag); RPU_HDR(coef_data_type); RPU_HDR(coef_log2_denom); RPU_HDR(vdr_rpu_normalized_idc); RPU_HDR(bl_video_full_range_flag); RPU_HDR(bl_bit_depth); RPU_HDR(el_bit_depth); RPU_HDR(vdr_bit_depth); RPU_HDR(spatial_resampling_filter_flag); RPU_HDR(el_spatial_resampling_filter_flag); RPU_HDR(disable_residual_flag); RPU_MAP(vdr_rpu_id); RPU_MAP(mapping_color_space); RPU_MAP(mapping_chroma_format_idc); for (int i = 0; i < 3; i++) { sd->Mapping.curves[i].num_pivots = mapping->curves[i].num_pivots; for (int j = 0; j < AV_DOVI_MAX_PIECES + 1; j++) sd->Mapping.curves[i].pivots[j] = mapping->curves[i].pivots[j]; for (int j = 0; j < AV_DOVI_MAX_PIECES; j++) { sd->Mapping.curves[i].mapping_idc[j] = mapping->curves[i].mapping_idc[j]; // poly sd->Mapping.curves[i].poly_order[j] = mapping->curves[i].poly_order[j]; sd->Mapping.curves[i].poly_coef[j][0] = mapping->curves[i].poly_coef[j][0]; sd->Mapping.curves[i].poly_coef[j][1] = mapping->curves[i].poly_coef[j][1]; sd->Mapping.curves[i].poly_coef[j][2] = mapping->curves[i].poly_coef[j][2]; // mmr sd->Mapping.curves[i].mmr_order[j] = mapping->curves[i].mmr_order[j]; sd->Mapping.curves[i].mmr_constant[j] = mapping->curves[i].mmr_constant[j]; for (int k = 0; k < 3; k++) for (int l = 0; l < 7; l++) sd->Mapping.curves[i].mmr_coef[j][k][l] = mapping->curves[i].mmr_coef[j][k][l]; } } RPU_MAP(nlq_method_idc); RPU_MAP(num_x_partitions); RPU_MAP(num_y_partitions); for (int i = 0; i < 3; i++) { sd->Mapping.nlq[i].nlq_offset = mapping->nlq[i].nlq_offset; sd->Mapping.nlq[i].vdr_in_max = mapping->nlq[i].vdr_in_max; sd->Mapping.nlq[i].linear_deadzone_slope = mapping->nlq[i].linear_deadzone_slope; sd->Mapping.nlq[i].linear_deadzone_threshold = mapping->nlq[i].linear_deadzone_threshold; } RPU_COLOR(dm_metadata_id); RPU_COLOR(scene_refresh_flag); for (int i = 0; i < 9; i++) { sd->ColorMetadata.ycc_to_rgb_matrix[i] = av_q2d(color->ycc_to_rgb_matrix[i]); sd->ColorMetadata.rgb_to_lms_matrix[i] = av_q2d(color->rgb_to_lms_matrix[i]); } for (int i = 0; i < 3; i++) { sd->ColorMetadata.ycc_to_rgb_offset[i] = av_q2d(color->ycc_to_rgb_offset[i]); } RPU_COLOR(signal_eotf); RPU_COLOR(signal_eotf_param0); RPU_COLOR(signal_eotf_param1); RPU_COLOR(signal_eotf_param2); RPU_COLOR(signal_bit_depth); RPU_COLOR(signal_color_space); RPU_COLOR(signal_chroma_format); RPU_COLOR(signal_full_range_flag); RPU_COLOR(source_min_pq); RPU_COLOR(source_max_pq); RPU_COLOR(source_diagonal); #undef RPU_HDR #undef RPU_MAP #undef RPU_COLOR int LAVExtIdx = 0; for (int i = 0; i < ff->num_ext_blocks; i++) { AVDOVIDmData *ext = av_dovi_get_ext(ff, i); auto lavext = &sd->Extensions[LAVExtIdx]; lavext->level = ext->level; switch (ext->level) { case 1: lavext->Level1.min_pq = ext->l1.min_pq; lavext->Level1.max_pq = ext->l1.max_pq; lavext->Level1.avg_pq = ext->l1.avg_pq; break; case 2: lavext->Level2.target_max_pq = ext->l2.target_max_pq; lavext->Level2.trim_slope = ext->l2.trim_slope; lavext->Level2.trim_offset = ext->l2.trim_offset; lavext->Level2.trim_power = ext->l2.trim_power; lavext->Level2.trim_chroma_weight = ext->l2.trim_chroma_weight; lavext->Level2.trim_saturation_gain = ext->l2.trim_saturation_gain; lavext->Level2.ms_weight = ext->l2.ms_weight; break; case 3: lavext->Level3.min_pq_offset = ext->l3.min_pq_offset; lavext->Level3.max_pq_offset = ext->l3.max_pq_offset; lavext->Level3.avg_pq_offset = ext->l3.avg_pq_offset; break; case 4: lavext->Level4.anchor_pq = ext->l4.anchor_pq; lavext->Level4.anchor_power = ext->l4.anchor_power; break; case 5: lavext->Level5.left_offset = ext->l5.left_offset; lavext->Level5.right_offset = ext->l5.right_offset; lavext->Level5.top_offset = ext->l5.top_offset; lavext->Level5.bottom_offset = ext->l5.bottom_offset; break; case 6: lavext->Level6.max_luminance = ext->l6.max_luminance; lavext->Level6.min_luminance = ext->l6.min_luminance; lavext->Level6.max_cll = ext->l6.max_cll; lavext->Level6.max_fall = ext->l6.max_fall; break; case 8: lavext->Level8.target_display_index = ext->l8.target_display_index; lavext->Level8.trim_slope = ext->l8.trim_slope; lavext->Level8.trim_offset = ext->l8.trim_offset; lavext->Level8.trim_power = ext->l8.trim_power; lavext->Level8.trim_chroma_weight = ext->l8.trim_chroma_weight; lavext->Level8.trim_saturation_gain = ext->l8.trim_saturation_gain; lavext->Level8.ms_weight = ext->l8.ms_weight; lavext->Level8.target_mid_contrast = ext->l8.target_mid_contrast; lavext->Level8.clip_trim = ext->l8.clip_trim; for (int j = 0; j < 6; j++) { lavext->Level8.saturation_vector_field[j] = ext->l8.saturation_vector_field[j]; lavext->Level8.hue_vector_field[j] = ext->l8.hue_vector_field[j]; } break; case 9: lavext->Level9.source_primary_index = ext->l9.source_primary_index; lavext->Level9.white_point_x = av_q2d(ext->l9.source_display_primaries.wp.x); lavext->Level9.white_point_y = av_q2d(ext->l9.source_display_primaries.wp.y); lavext->Level9.display_primaries_x[0] = av_q2d(ext->l9.source_display_primaries.prim.r.x); lavext->Level9.display_primaries_x[1] = av_q2d(ext->l9.source_display_primaries.prim.g.x); lavext->Level9.display_primaries_x[2] = av_q2d(ext->l9.source_display_primaries.prim.b.x); lavext->Level9.display_primaries_y[0] = av_q2d(ext->l9.source_display_primaries.prim.r.y); lavext->Level9.display_primaries_y[1] = av_q2d(ext->l9.source_display_primaries.prim.g.y); lavext->Level9.display_primaries_y[2] = av_q2d(ext->l9.source_display_primaries.prim.b.y); break; case 10: lavext->Level10.target_display_index = ext->l10.target_display_index; lavext->Level10.target_max_pq = ext->l10.target_max_pq; lavext->Level10.target_min_pq = ext->l10.target_min_pq; lavext->Level10.target_primary_index = ext->l10.target_primary_index; lavext->Level10.white_point_x = av_q2d(ext->l10.target_display_primaries.wp.x); lavext->Level10.white_point_y = av_q2d(ext->l10.target_display_primaries.wp.y); lavext->Level10.display_primaries_x[0] = av_q2d(ext->l10.target_display_primaries.prim.r.x); lavext->Level10.display_primaries_x[1] = av_q2d(ext->l10.target_display_primaries.prim.g.x); lavext->Level10.display_primaries_x[2] = av_q2d(ext->l10.target_display_primaries.prim.b.x); lavext->Level10.display_primaries_y[0] = av_q2d(ext->l10.target_display_primaries.prim.r.y); lavext->Level10.display_primaries_y[1] = av_q2d(ext->l10.target_display_primaries.prim.g.y); lavext->Level10.display_primaries_y[2] = av_q2d(ext->l10.target_display_primaries.prim.b.y); break; case 11: lavext->Level11.content_type = ext->l11.content_type; lavext->Level11.whitepoint = ext->l11.whitepoint; lavext->Level11.reference_mode_flag = ext->l11.reference_mode_flag; break; case 254: lavext->Level254.dm_mode = ext->l254.dm_mode; lavext->Level254.dm_version_index = ext->l254.dm_version_index; break; default: lavext->level = 0; /* reset level, unknown/not implemented extension */ break; } /* if the block is valid/recognized, go to the next one */ if (lavext->level > 0) LAVExtIdx++; /* only 32 blocks are allowed, sanity check here */ if (LAVExtIdx >= LAV_DOVI_MAX_EXTENSIONS) break; } } extern "C" const uint8_t *avpriv_find_start_code(const uint8_t *p, const uint8_t *end, uint32_t *state); int CheckForSequenceMarkers(AVCodecID codec, const uint8_t *buf, long len, uint32_t *state, const uint8_t **pos) { int status = 0; if (buf && len > 0) { const uint8_t *p = buf, *end = buf + len; if (codec == AV_CODEC_ID_MPEG2VIDEO) { while (p < end) { p = avpriv_find_start_code(p, end, state); if (*state == 0x000001b7) { DbgLog((LOG_TRACE, 50, L"Found SEQ_END_CODE at %p (end: %p)", p, end)); status |= STATE_EOS_FOUND; if (pos) *pos = p; return status; } else if (*state == 0x000001b8) { status |= STATE_GOP_FOUND; } } } return status; } return status; } int sws_scale2(struct SwsContext *c, const uint8_t *const srcSlice[], const ptrdiff_t srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const ptrdiff_t dstStride[]) { if (!c) return -1; int srcStride2[4]; int dstStride2[4]; for (int i = 0; i < 4; i++) { srcStride2[i] = (int)srcStride[i]; dstStride2[i] = (int)dstStride[i]; } return sws_scale(c, srcSlice, srcStride2, srcSliceY, srcSliceH, dst, dstStride2); } ================================================ FILE: decoder/LAVVideo/Media.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "IMediaSideData.h" #include "libavutil/mastering_display_metadata.h" #include "libavutil/hdr_dynamic_metadata.h" #include "libavutil/dovi_meta.h" AVCodecID FindCodecId(const CMediaType *mt); int getThreadFlags(AVCodecID codecId); #define MAX_NUM_CC_CODECS 3 struct codec_config_t { int nCodecs; AVCodecID codecs[MAX_NUM_CC_CODECS]; const char *name; const char *description; }; const codec_config_t *get_codec_config(LAVVideoCodec codec); int flip_plane(BYTE *buffer, int stride, int height); void fillDXVAExtFormat(DXVA2_ExtendedFormat &fmt, int range, int primaries, int matrix, int transfer, int chroma_sample_location = 0, bool bClear = true); void processFFHDRData(MediaSideDataHDR *sd, AVMasteringDisplayMetadata *ff); void processFFHDR10PlusData(MediaSideDataHDR10Plus *sd, AVDynamicHDRPlus *ff, int width, int height); void processFFDOVIData(MediaSideDataDOVIMetadata *sd, const AVDOVIMetadata *ff); #define STATE_NOT_FOUND 0 #define STATE_EOS_FOUND 1 #define STATE_GOP_FOUND 2 int CheckForSequenceMarkers(AVCodecID codec, const uint8_t *buf, long len, uint32_t *state, const uint8_t **pos = nullptr); int sws_scale2(struct SwsContext *c, const uint8_t *const srcSlice[], const ptrdiff_t srcStride[], int srcSliceY, int srcSliceH, uint8_t *const dst[], const ptrdiff_t dstStride[]); ================================================ FILE: decoder/LAVVideo/VideoInputPin.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "VideoInputPin.h" #include "ILAVDynamicAllocator.h" CVideoInputPin::CVideoInputPin(TCHAR *pObjectName, CLAVVideo *pFilter, HRESULT *phr, LPWSTR pName) : CDeCSSTransformInputPin(pObjectName, pFilter, phr, pName) , m_pLAVVideo(pFilter) { } STDMETHODIMP CVideoInputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); return QI(IPinSegmentEx) __super::NonDelegatingQueryInterface(riid, ppv); } STDMETHODIMP CVideoInputPin::NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly) { HRESULT hr = __super::NotifyAllocator(pAllocator, bReadOnly); m_bDynamicAllocator = FALSE; if (SUCCEEDED(hr) && pAllocator) { ILAVDynamicAllocator *pDynamicAllocator = nullptr; if (SUCCEEDED(pAllocator->QueryInterface(&pDynamicAllocator))) { m_bDynamicAllocator = pDynamicAllocator->IsDynamicAllocator(); } SafeRelease(&pDynamicAllocator); } return hr; } STDMETHODIMP CVideoInputPin::EndOfSegment() { CAutoLock lck(&m_pLAVVideo->m_csReceive); HRESULT hr = CheckStreaming(); if (S_OK == hr) { hr = m_pLAVVideo->EndOfSegment(); } return hr; } // IKsPropertySet STDMETHODIMP CVideoInputPin::Set(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength) { if (PropSet != AM_KSPROPSETID_TSRateChange) { return __super::Set(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength); } switch (Id) { case AM_RATE_SimpleRateChange: { AM_SimpleRateChange *p = (AM_SimpleRateChange *)pPropertyData; if (!m_CorrectTS) { return E_PROP_ID_UNSUPPORTED; } CAutoLock cAutoLock(&m_csRateLock); m_ratechange = *p; } break; case AM_RATE_UseRateVersion: { WORD *p = (WORD *)pPropertyData; if (*p > 0x0101) { return E_PROP_ID_UNSUPPORTED; } } break; case AM_RATE_CorrectTS: { LONG *p = (LONG *)pPropertyData; m_CorrectTS = *p; } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CVideoInputPin::Get(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength, ULONG *pBytesReturned) { if (PropSet != AM_KSPROPSETID_TSRateChange) { return __super::Get(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength, pBytesReturned); } switch (Id) { case AM_RATE_SimpleRateChange: { AM_SimpleRateChange *p = (AM_SimpleRateChange *)pPropertyData; CAutoLock cAutoLock(&m_csRateLock); *p = m_ratechange; *pBytesReturned = sizeof(AM_SimpleRateChange); } break; case AM_RATE_MaxFullDataRate: { AM_MaxFullDataRate *p = (AM_MaxFullDataRate *)pPropertyData; *p = 2 * 10000; *pBytesReturned = sizeof(AM_MaxFullDataRate); } break; case AM_RATE_QueryFullFrameRate: { AM_QueryRate *p = (AM_QueryRate *)pPropertyData; p->lMaxForwardFullFrame = 2 * 10000; p->lMaxReverseFullFrame = 0; *pBytesReturned = sizeof(AM_QueryRate); } break; case AM_RATE_QueryLastRateSegPTS: { // REFERENCE_TIME* p = (REFERENCE_TIME*)pPropertyData; return E_PROP_ID_UNSUPPORTED; } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CVideoInputPin::QuerySupported(REFGUID PropSet, ULONG Id, ULONG *pTypeSupport) { if (PropSet != AM_KSPROPSETID_TSRateChange) { return __super::QuerySupported(PropSet, Id, pTypeSupport); } switch (Id) { case AM_RATE_SimpleRateChange: *pTypeSupport = KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET; break; case AM_RATE_MaxFullDataRate: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_UseRateVersion: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_RATE_QueryFullFrameRate: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_QueryLastRateSegPTS: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_CorrectTS: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } ================================================ FILE: decoder/LAVVideo/VideoInputPin.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DeCSS/DeCSSInputPin.h" #include "LAVVideo.h" #include "IPinSegmentEx.h" class CVideoInputPin : public CDeCSSTransformInputPin , public IPinSegmentEx { public: CVideoInputPin(TCHAR *pObjectName, CLAVVideo *pFilter, HRESULT *phr, LPWSTR pName); // CUnknown DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // IMemInputPin STDMETHODIMP NotifyAllocator(IMemAllocator *pAllocator, BOOL bReadOnly); // IPinSegmentEx STDMETHODIMP EndOfSegment(); // IKsPropertySet STDMETHODIMP Set(REFGUID PropSet, ULONG Id, LPVOID InstanceData, ULONG InstanceLength, LPVOID PropertyData, ULONG DataLength); STDMETHODIMP Get(REFGUID PropSet, ULONG Id, LPVOID InstanceData, ULONG InstanceLength, LPVOID PropertyData, ULONG DataLength, ULONG *pBytesReturned); STDMETHODIMP QuerySupported(REFGUID PropSet, ULONG Id, ULONG *pTypeSupport); AM_SimpleRateChange GetDVDRateChange() { CAutoLock cAutoLock(&m_csRateLock); return m_ratechange; } BOOL HasDynamicAllocator() { return m_bDynamicAllocator; } private: CLAVVideo *m_pLAVVideo = nullptr; CCritSec m_csRateLock; int m_CorrectTS = 0; AM_SimpleRateChange m_ratechange = AM_SimpleRateChange{AV_NOPTS_VALUE, 10000}; BOOL m_bDynamicAllocator = FALSE; }; ================================================ FILE: decoder/LAVVideo/VideoOutputPin.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVVideo.h" #include "VideoOutputPin.h" CVideoOutputPin::CVideoOutputPin(LPCTSTR pObjectName, CLAVVideo *pFilter, HRESULT *phr, LPCWSTR pName) : CTransformOutputPin(pObjectName, (CTransformFilter *)pFilter, phr, pName) , m_pFilter(pFilter) { } CVideoOutputPin::~CVideoOutputPin() { } HRESULT CVideoOutputPin::InitAllocator(IMemAllocator **ppAlloc) { HRESULT hr = S_FALSE; hr = m_pFilter->m_Decoder.InitAllocator(ppAlloc); if (hr != S_OK) hr = __super::InitAllocator(ppAlloc); return hr; } ================================================ FILE: decoder/LAVVideo/VideoOutputPin.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class CVideoOutputPin : public CTransformOutputPin { public: CVideoOutputPin(LPCTSTR pObjectName, CLAVVideo *pFilter, HRESULT *phr, LPCWSTR pName); virtual ~CVideoOutputPin(); HRESULT InitAllocator(IMemAllocator **ppAlloc); private: CLAVVideo *m_pFilter = nullptr; }; ================================================ FILE: decoder/LAVVideo/VideoSettingsProp.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "VideoSettingsProp.h" #include "Media.h" #include #include "resource.h" #include "version.h" CLAVVideoSettingsProp::CLAVVideoSettingsProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVVideoProp"), pUnk, IDD_PROPPAGE_VIDEO_SETTINGS, IDS_SETTINGS) { } CLAVVideoSettingsProp::~CLAVVideoSettingsProp() { } HRESULT CLAVVideoSettingsProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pVideoSettings == nullptr); HRESULT hr = pUnk->QueryInterface(&m_pVideoSettings); if (FAILED(hr)) return hr; hr = pUnk->QueryInterface(&m_pVideoStatus); if (FAILED(hr)) return hr; return S_OK; } HRESULT CLAVVideoSettingsProp::OnDisconnect() { SafeRelease(&m_pVideoSettings); SafeRelease(&m_pVideoStatus); return S_OK; } HRESULT CLAVVideoSettingsProp::OnApplyChanges() { ASSERT(m_pVideoSettings != nullptr); ASSERT(m_pVideoStatus != nullptr); HRESULT hr = S_OK; BOOL bFlag; DWORD dwVal; dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_STREAMAR, BM_GETCHECK, 0, 0); m_pVideoSettings->SetStreamAR(dwVal); dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_THREADS, CB_GETCURSEL, 0, 0); m_pVideoSettings->SetNumThreads(dwVal); dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_DEINT_FIELDORDER, CB_GETCURSEL, 0, 0); m_pVideoSettings->SetDeintFieldOrder((LAVDeintFieldOrder)dwVal); dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_DEINT_MODE, CB_GETCURSEL, 0, 0); m_pVideoSettings->SetDeinterlacingMode((LAVDeintMode)dwVal); m_bPixFmts[LAVOutPixFmt_YV12] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_YV12, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_NV12] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_NV12, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_P010] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_P010, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_P016] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_P016, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_YUY2] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_YUY2, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_UYVY] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_UYVY, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_P210] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_P210, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_v210] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_V210, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_P216] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_P216, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_YV24] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_YV24, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_AYUV] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_AYUV, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_Y410] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_Y410, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_v410] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_V410, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_Y416] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_Y416, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_RGB32] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_RGB32, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_RGB24] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_RGB24, BM_GETCHECK, 0, 0); m_bPixFmts[LAVOutPixFmt_RGB48] = (BOOL)SendDlgItemMessage(m_Dlg, IDC_OUT_RGB48, BM_GETCHECK, 0, 0); for (int i = 0; i < LAVOutPixFmt_NB; ++i) { m_pVideoSettings->SetPixelFormat((LAVOutPixFmts)i, m_bPixFmts[i]); } BOOL bRGBAuto = (BOOL)SendDlgItemMessage(m_Dlg, IDC_RGBOUT_AUTO, BM_GETCHECK, 0, 0); BOOL bRGBTV = (BOOL)SendDlgItemMessage(m_Dlg, IDC_RGBOUT_TV, BM_GETCHECK, 0, 0); BOOL bRGBPC = (BOOL)SendDlgItemMessage(m_Dlg, IDC_RGBOUT_PC, BM_GETCHECK, 0, 0); m_pVideoSettings->SetRGBOutputRange(bRGBAuto ? 0 : bRGBTV ? 1 : 2); LRESULT retVal = SendDlgItemMessage(m_Dlg, IDC_HWACCEL, CB_GETCURSEL, 0, 0); dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_HWACCEL, CB_GETITEMDATA, retVal, 0); m_pVideoSettings->SetHWAccel((LAVHWAccel)dwVal); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_H264, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_H264, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_VC1, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_VC1, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_MPEG2, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_MPEG2, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_MPEG4, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_MPEG4, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_HEVC, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_HEVC, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_VP9, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_VP9, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_AV1, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_AV1, bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_H264MVC, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelCodec(HWCodec_H264MVC, bFlag); DWORD dwHWResFlags = 0; bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWRES_SD, BM_GETCHECK, 0, 0); if (bFlag) dwHWResFlags |= LAVHWResFlag_SD; bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWRES_HD, BM_GETCHECK, 0, 0); if (bFlag) dwHWResFlags |= LAVHWResFlag_HD; bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWRES_UHD, BM_GETCHECK, 0, 0); if (bFlag) dwHWResFlags |= LAVHWResFlag_UHD; m_pVideoSettings->SetHWAccelResolutionFlags(dwHWResFlags); dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_DEVICE_SELECT, CB_GETCURSEL, 0, 0); if (dwVal == 0) dwVal = LAVHWACCEL_DEVICE_DEFAULT; else dwVal--; m_pVideoSettings->SetHWAccelDeviceIndex(m_pVideoSettings->GetHWAccel(), dwVal, 0); BOOL bHWAccelCUVIDDXVA = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_CUVID_DXVA, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelDeintHQ(bHWAccelCUVIDDXVA); BOOL bHWDeint = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWDEINT_ENABLE, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelDeintMode(bHWDeint ? HWDeintMode_Hardware : HWDeintMode_Weave); BOOL bFilm = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWDEINT_OUT_FILM, BM_GETCHECK, 0, 0); // BOOL bVideo = (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWDEINT_OUT_VIDEO, BM_GETCHECK, 0, 0); m_pVideoSettings->SetHWAccelDeintOutput(bFilm ? DeintOutput_FramePer2Field : DeintOutput_FramePerField); dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_GETCURSEL, 0, 0); m_pVideoSettings->SetSWDeintMode((LAVSWDeintModes)dwVal); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SWDEINT_OUT_FILM, BM_GETCHECK, 0, 0); // BOOL bVideo = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SWDEINT_OUT_VIDEO, BM_GETCHECK, 0, 0); m_pVideoSettings->SetSWDeintOutput(bFlag ? DeintOutput_FramePer2Field : DeintOutput_FramePerField); BOOL bOrdered = (BOOL)SendDlgItemMessage(m_Dlg, IDC_DITHER_ORDERED, BM_GETCHECK, 0, 0); BOOL bRandom = (BOOL)SendDlgItemMessage(m_Dlg, IDC_DITHER_RANDOM, BM_GETCHECK, 0, 0); m_pVideoSettings->SetDitherMode(bOrdered ? LAVDither_Ordered : LAVDither_Random); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_GETCHECK, 0, 0); m_pVideoSettings->SetTrayIcon(bFlag); LoadData(); return hr; } static void AddComboBoxEntryWithData(HWND hwnd, int nIDDlgItem, WCHAR *pszText, UINT Data) { // add the entry LRESULT ret = SendDlgItemMessage(hwnd, nIDDlgItem, CB_ADDSTRING, 0, (LPARAM)pszText); if (ret < 0) return; // set its data SendDlgItemMessage(hwnd, nIDDlgItem, CB_SETITEMDATA, ret, Data); } static void SelectComboBoxItemByValue(HWND hwnd, int nIDDlgItem, UINT Data) { LRESULT count = SendDlgItemMessage(hwnd, nIDDlgItem, CB_GETCOUNT, 0, 0); for (int i = 0; i < count; i++) { LRESULT ItemData = SendDlgItemMessage(hwnd, nIDDlgItem, CB_GETITEMDATA, i, 0); if (ItemData == Data) { SendDlgItemMessage(hwnd, nIDDlgItem, CB_SETCURSEL, i, 0); break; } } } HRESULT CLAVVideoSettingsProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pVideoSettings != nullptr); const WCHAR *version = TEXT(LAV_VIDEO) L" " TEXT(LAV_VERSION_STR); SendDlgItemMessage(m_Dlg, IDC_LAVVIDEO_FOOTER, WM_SETTEXT, 0, (LPARAM)version); WCHAR stringBuffer[512] = L"Auto"; // Init the Combo Box SendDlgItemMessage(m_Dlg, IDC_THREADS, CB_RESETCONTENT, 0, 0); SendDlgItemMessage(m_Dlg, IDC_THREADS, CB_ADDSTRING, 0, (LPARAM)stringBuffer); for (unsigned i = 1; i <= 32; ++i) { swprintf_s(stringBuffer, L"%d", i); SendDlgItemMessage(m_Dlg, IDC_THREADS, CB_ADDSTRING, 0, (LPARAM)stringBuffer); } addHint(IDC_THREADS, L"Enable Multi-Threading for codecs that support it.\nAuto will automatically use the maximum " L"number of threads suitable for your CPU. Using 1 thread disables multi-threading.\n\nMT " L"decoding is supported for H264, MPEG2, MPEG4, VP8, VP3/Theora, DV and HuffYUV"); addHint(IDC_STREAMAR, L"Checked - Stream AR will be used.\nUnchecked - Frame AR will not be used.\nIndeterminate " L"(Auto) - Stream AR will not be used on files with a container AR (recommended)."); WCHAR hwAccelNone[] = L"None"; WCHAR hwAccelCUDA[] = L"NVIDIA CUVID (old)"; WCHAR hwAccelQuickSync[] = L"Intel\xae QuickSync (old)"; WCHAR hwAccelDXVA2CB[] = L"DXVA2 (copy-back)"; WCHAR hwAccelDXVA2N[] = L"DXVA2 (native)"; WCHAR hwAccelD3D11[] = L"D3D11"; AddComboBoxEntryWithData(m_Dlg, IDC_HWACCEL, hwAccelNone, HWAccel_None); AddComboBoxEntryWithData(m_Dlg, IDC_HWACCEL, hwAccelDXVA2CB, HWAccel_DXVA2CopyBack); AddComboBoxEntryWithData(m_Dlg, IDC_HWACCEL, hwAccelDXVA2N, HWAccel_DXVA2Native); AddComboBoxEntryWithData(m_Dlg, IDC_HWACCEL, hwAccelD3D11, HWAccel_D3D11); AddComboBoxEntryWithData(m_Dlg, IDC_HWACCEL, hwAccelCUDA, HWAccel_CUDA); AddComboBoxEntryWithData(m_Dlg, IDC_HWACCEL, hwAccelQuickSync, HWAccel_QuickSync); // Init the fieldorder Combo Box SendDlgItemMessage(m_Dlg, IDC_DEINT_FIELDORDER, CB_RESETCONTENT, 0, 0); WideStringFromResource(stringBuffer, IDS_FIELDORDER_AUTO); SendDlgItemMessage(m_Dlg, IDC_DEINT_FIELDORDER, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_FIELDORDER_TOP); SendDlgItemMessage(m_Dlg, IDC_DEINT_FIELDORDER, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_FIELDORDER_BOTTOM); SendDlgItemMessage(m_Dlg, IDC_DEINT_FIELDORDER, CB_ADDSTRING, 0, (LPARAM)stringBuffer); // Deint Mode combo box SendDlgItemMessage(m_Dlg, IDC_DEINT_MODE, CB_RESETCONTENT, 0, 0); WideStringFromResource(stringBuffer, IDS_DEINTMODE_AUTO); SendDlgItemMessage(m_Dlg, IDC_DEINT_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_DEINTMODE_AGGRESSIVE); SendDlgItemMessage(m_Dlg, IDC_DEINT_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_DEINTMODE_FORCE); SendDlgItemMessage(m_Dlg, IDC_DEINT_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_DEINTMODE_DISABLE); SendDlgItemMessage(m_Dlg, IDC_DEINT_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); // SW Deint Mode WCHAR swdeintNone[] = L"No Software Deinterlacing"; WCHAR swdeintYADIF[] = L"YADIF"; WCHAR swdeintW3FDIFS[] = L"Weston Three Field (Simple)"; WCHAR swdeintW3FDIFC[] = L"Weston Three Field (Complex)"; WCHAR swdeintBWDIF[] = L"BobWeaver (bwdif)"; SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_ADDSTRING, 0, (LPARAM)swdeintNone); SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_ADDSTRING, 0, (LPARAM)swdeintYADIF); SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_ADDSTRING, 0, (LPARAM)swdeintW3FDIFS); SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_ADDSTRING, 0, (LPARAM)swdeintW3FDIFC); SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_ADDSTRING, 0, (LPARAM)swdeintBWDIF); addHint(IDC_HWACCEL_MPEG4, L"EXPERIMENTAL! The MPEG4-ASP decoder is known to be unstable! Use at your own peril!"); addHint(IDC_HWACCEL_H264MVC, L"Intel GPU only.\nMVC acceleration is not supported on other graphics cards."); addHint(IDC_HWACCEL_CUVID_DXVA, L"Enable DXVA video processing for CUVID decoding, enables hybrid decoding and can " L"affect deinterlacing quality.\n\nNote: Using DXVA2-CopyBack is recommended for " L"hybrid decoding instead of using CUVID in DXVA mode."); addHint(IDC_HWRES_SD, L"Use Hardware Decoding for Standard-definition content (DVD, SDTV)\n\nThis affects all " L"videos with a resolution less than 1024x576 (DVD resolution)"); addHint(IDC_HWRES_HD, L"Use Hardware Decoding for High-definition content (Blu-ray, HDTV)\n\nAffects all videos " L"above SD resolution, up to Full-HD, 1920x1200"); addHint(IDC_HWRES_UHD, L"Use Hardware Decoding for Ultra-high-definition content (4K, UHDTV)\n\nAffects all videos above HD " L"resolution. Note that not all hardware supports decoding 4K/UHD content. On AMD GPUs, 4K support is very " L"fragile, and may even cause crashes or BSODs, use at your own risk."); addHint(IDC_DEINT_MODE, L"Controls how interlaced material is handled.\n\nAuto: Frame flags are used to determine content " L"type.\nAggressive: All frames in an interlaced streams are handled interlaced.\nForce: All frames are " L"handles as interlaced.\nDisabled: All frames are handled as progressive."); addHint(IDC_HWDEINT_OUT_FILM, L"Deinterlace in \"Film\" Mode.\nFor every pair of interlaced fields, one frame will " L"be created, resulting in 25/30 fps."); addHint(IDC_HWDEINT_OUT_VIDEO, L"Deinterlace in \"Video\" Mode. (Recommended)\nFor every interlaced field, one " L"frame will be created, resulting in 50/60 fps."); addHint(IDC_DITHER_ORDERED, L"Ordered Dithering uses a static pattern, resulting in very smooth and regular " L"pattern. However, in some cases the regular pattern can be visible and distracting."); addHint(IDC_DITHER_RANDOM, L"Random Dithering uses random noise to dither the video frames. This has the advantage of not creating " L"any visible pattern, at the downside of increasing the noise floor slightly."); hr = LoadData(); if (SUCCEEDED(hr)) { SendDlgItemMessage(m_Dlg, IDC_THREADS, CB_SETCURSEL, m_dwNumThreads, 0); SendDlgItemMessage(m_Dlg, IDC_STREAMAR, BM_SETCHECK, m_StreamAR, 0); SendDlgItemMessage(m_Dlg, IDC_DEINT_FIELDORDER, CB_SETCURSEL, m_DeintFieldOrder, 0); SendDlgItemMessage(m_Dlg, IDC_DEINT_MODE, CB_SETCURSEL, m_DeintMode, 0); SendDlgItemMessage(m_Dlg, IDC_OUT_YV12, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_YV12], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_NV12, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_NV12], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_P010, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_P010], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_P016, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_P016], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_YUY2, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_YUY2], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_UYVY, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_UYVY], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_P210, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_P210], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_V210, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_v210], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_P216, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_P216], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_YV24, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_YV24], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_AYUV, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_AYUV], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_Y410, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_Y410], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_V410, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_v410], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_Y416, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_Y416], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_RGB32, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_RGB32], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_RGB24, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_RGB24], 0); SendDlgItemMessage(m_Dlg, IDC_OUT_RGB48, BM_SETCHECK, m_bPixFmts[LAVOutPixFmt_RGB48], 0); SendDlgItemMessage(m_Dlg, IDC_RGBOUT_AUTO, BM_SETCHECK, (m_dwRGBOutput == 0), 0); SendDlgItemMessage(m_Dlg, IDC_RGBOUT_TV, BM_SETCHECK, (m_dwRGBOutput == 1), 0); SendDlgItemMessage(m_Dlg, IDC_RGBOUT_PC, BM_SETCHECK, (m_dwRGBOutput == 2), 0); SelectComboBoxItemByValue(m_Dlg, IDC_HWACCEL, m_HWAccel); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_H264, BM_SETCHECK, m_HWAccelCodecs[HWCodec_H264], 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_VC1, BM_SETCHECK, m_HWAccelCodecs[HWCodec_VC1], 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_MPEG2, BM_SETCHECK, m_HWAccelCodecs[HWCodec_MPEG2], 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_MPEG4, BM_SETCHECK, m_HWAccelCodecs[HWCodec_MPEG4], 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_HEVC, BM_SETCHECK, m_HWAccelCodecs[HWCodec_HEVC], 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_VP9, BM_SETCHECK, m_HWAccelCodecs[HWCodec_VP9], 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_AV1, BM_SETCHECK, m_HWAccelCodecs[HWCodec_AV1], 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_H264MVC, BM_SETCHECK, m_HWAccelCodecs[HWCodec_H264MVC], 0); SendDlgItemMessage(m_Dlg, IDC_HWRES_SD, BM_SETCHECK, !!(m_HWRes & LAVHWResFlag_SD), 0); SendDlgItemMessage(m_Dlg, IDC_HWRES_HD, BM_SETCHECK, !!(m_HWRes & LAVHWResFlag_HD), 0); SendDlgItemMessage(m_Dlg, IDC_HWRES_UHD, BM_SETCHECK, !!(m_HWRes & LAVHWResFlag_UHD), 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_CUVID_DXVA, BM_SETCHECK, m_HWAccelCUVIDDXVA, 0); SendDlgItemMessage(m_Dlg, IDC_HWDEINT_ENABLE, BM_SETCHECK, (m_HWDeintAlgo == HWDeintMode_Hardware), 0); SendDlgItemMessage(m_Dlg, IDC_HWDEINT_OUT_FILM, BM_SETCHECK, (m_HWDeintOutMode == DeintOutput_FramePer2Field), 0); SendDlgItemMessage(m_Dlg, IDC_HWDEINT_OUT_VIDEO, BM_SETCHECK, (m_HWDeintOutMode == DeintOutput_FramePerField), 0); SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_SETCURSEL, m_SWDeint, 0); SendDlgItemMessage(m_Dlg, IDC_SWDEINT_OUT_FILM, BM_SETCHECK, (m_SWDeintOutMode == DeintOutput_FramePer2Field), 0); SendDlgItemMessage(m_Dlg, IDC_SWDEINT_OUT_VIDEO, BM_SETCHECK, (m_SWDeintOutMode == DeintOutput_FramePerField), 0); SendDlgItemMessage(m_Dlg, IDC_DITHER_ORDERED, BM_SETCHECK, (m_DitherMode == LAVDither_Ordered), 0); SendDlgItemMessage(m_Dlg, IDC_DITHER_RANDOM, BM_SETCHECK, (m_DitherMode == LAVDither_Random), 0); SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_SETCHECK, m_TrayIcon, 0); UpdateHWOptions(); UpdateYADIFOptions(); } const WCHAR *decoder = m_pVideoStatus->GetActiveDecoderName(); SendDlgItemMessage(m_Dlg, IDC_ACTIVE_DECODER, WM_SETTEXT, 0, (LPARAM)(decoder ? decoder : L"")); BSTR bstrHWDevice = nullptr; if (SUCCEEDED(m_pVideoStatus->GetHWAccelActiveDevice(&bstrHWDevice))) { SendDlgItemMessage(m_Dlg, IDC_HWACCEL_DEVICE, WM_SETTEXT, 0, (LPARAM)bstrHWDevice); SysFreeString(bstrHWDevice); } else { SendDlgItemMessage(m_Dlg, IDC_HWACCEL_DEVICE, WM_SETTEXT, 0, (LPARAM)L""); } return hr; } HRESULT CLAVVideoSettingsProp::UpdateHWOptions() { LRESULT lValue = SendDlgItemMessage(m_Dlg, IDC_HWACCEL, CB_GETCURSEL, 0, 0); LAVHWAccel hwAccel = (LAVHWAccel)SendDlgItemMessage(m_Dlg, IDC_HWACCEL, CB_GETITEMDATA, lValue, 0); DWORD dwSupport = m_pVideoSettings->CheckHWAccelSupport(hwAccel); BOOL bEnabled = (hwAccel != HWAccel_None) && dwSupport; BOOL bHWDeint = bEnabled && (hwAccel == HWAccel_CUDA || hwAccel == HWAccel_QuickSync); BOOL bHWDeintEnabled = bHWDeint && (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWDEINT_ENABLE, BM_GETCHECK, 0, 0); BOOL bCUDAOnly = bEnabled && (hwAccel == HWAccel_CUDA); BOOL bDVD = bEnabled && (BOOL)SendDlgItemMessage(m_Dlg, IDC_HWACCEL_MPEG2, BM_GETCHECK, 0, 0); BOOL bHEVC = bEnabled && (hwAccel != HWAccel_QuickSync); BOOL bVP9 = bEnabled && (hwAccel != HWAccel_QuickSync); BOOL bAV1 = bEnabled && (hwAccel != HWAccel_QuickSync) && (hwAccel != HWAccel_CUDA); ShowWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_CUVID_DXVA), (hwAccel == HWAccel_CUDA && !IsWindows10OrNewer()) ? SW_SHOW : SW_HIDE); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_H264), bEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_VC1), bEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_MPEG2), bEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_MPEG4), bCUDAOnly); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_HEVC), bHEVC); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_VP9), bVP9); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_AV1), bAV1); EnableWindow(GetDlgItem(m_Dlg, IDC_HWRES_SD), bEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWRES_HD), bEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWRES_UHD), bEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWDEINT_ENABLE), bHWDeint); EnableWindow(GetDlgItem(m_Dlg, IDC_LBL_HWDEINT_MODE), bHWDeintEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWDEINT_OUT_FILM), bHWDeintEnabled); EnableWindow(GetDlgItem(m_Dlg, IDC_HWDEINT_OUT_VIDEO), bHWDeintEnabled); WCHAR hwAccelEmpty[] = L""; WCHAR hwAccelUnavailable[] = L"N/A"; WCHAR hwAccelAvailable[] = L"OK"; SendDlgItemMessage( m_Dlg, IDC_HWACCEL_AVAIL, WM_SETTEXT, 0, (LPARAM)(hwAccel == HWAccel_None ? hwAccelEmpty : dwSupport == 0 ? hwAccelUnavailable : hwAccelAvailable)); const WCHAR hwHintNoDeviceChoice[] = L"The selected Hardware Decoder does not support using a specific device."; const WCHAR hwHintDXVA2Display[] = L"DXVA2 requires an active display for GPUs to be available.\nNote that GPUs " L"are listed once for each connected display."; const WCHAR hwHintD3D11NotSupported[] = L"D3D11 requires Windows 8 or newer, and is not supported on this OS."; const WCHAR hwHintD3D11DeviceHint[] = L"Selecting a specific device for D3D11 disables Native mode and forces " L"Copy-Back, use Automatic for the best performance."; SendDlgItemMessage(m_Dlg, IDC_HWACCEL_DEVICE_SELECT, CB_RESETCONTENT, 0, 0); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_DEVICE_SELECT, CB_ADDSTRING, 0, (hwAccel == HWAccel_D3D11) ? (LPARAM)L"Automatic (Native)" : (LPARAM)L"Automatic"); DWORD dwnDevices = m_pVideoSettings->GetHWAccelNumDevices(hwAccel); for (DWORD dwDevice = 0; dwDevice < dwnDevices; dwDevice++) { BSTR bstrDeviceName = nullptr; HRESULT hr = m_pVideoSettings->GetHWAccelDeviceInfo(hwAccel, dwDevice, &bstrDeviceName, NULL); if (SUCCEEDED(hr)) { SendDlgItemMessage(m_Dlg, IDC_HWACCEL_DEVICE_SELECT, CB_ADDSTRING, 0, (LPARAM)bstrDeviceName); SysFreeString(bstrDeviceName); } } if (hwAccel == HWAccel_D3D11 && !IsWindows8OrNewer()) { m_HWDeviceIndex = 0; dwnDevices = 0; SendDlgItemMessage(m_Dlg, IDC_LBL_HWACCEL_DEVICE_HINT, WM_SETTEXT, 0, (LPARAM)hwHintD3D11NotSupported); } else if (dwnDevices == 0) { m_HWDeviceIndex = 0; SendDlgItemMessage(m_Dlg, IDC_LBL_HWACCEL_DEVICE_HINT, WM_SETTEXT, 0, (LPARAM)hwHintNoDeviceChoice); } else { DWORD dwDeviceId = 0; m_HWDeviceIndex = m_pVideoSettings->GetHWAccelDeviceIndex(hwAccel, &dwDeviceId); if (m_HWDeviceIndex == LAVHWACCEL_DEVICE_DEFAULT) m_HWDeviceIndex = 0; else m_HWDeviceIndex++; if (hwAccel == HWAccel_DXVA2CopyBack) SendDlgItemMessage(m_Dlg, IDC_LBL_HWACCEL_DEVICE_HINT, WM_SETTEXT, 0, (LPARAM)hwHintDXVA2Display); else if (hwAccel == HWAccel_D3D11) SendDlgItemMessage(m_Dlg, IDC_LBL_HWACCEL_DEVICE_HINT, WM_SETTEXT, 0, (LPARAM)hwHintD3D11DeviceHint); else SendDlgItemMessage(m_Dlg, IDC_LBL_HWACCEL_DEVICE_HINT, WM_SETTEXT, 0, (LPARAM)L""); } EnableWindow(GetDlgItem(m_Dlg, IDC_LBL_HWACCEL_DEVICE_SELECT), (dwnDevices > 0)); EnableWindow(GetDlgItem(m_Dlg, IDC_HWACCEL_DEVICE_SELECT), (dwnDevices > 0)); SendDlgItemMessage(m_Dlg, IDC_HWACCEL_DEVICE_SELECT, CB_SETCURSEL, m_HWDeviceIndex, 0); return S_OK; } HRESULT CLAVVideoSettingsProp::UpdateYADIFOptions() { DWORD dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_SWDEINT_MODE, CB_GETCURSEL, 0, 0); EnableWindow(GetDlgItem(m_Dlg, IDC_LBL_SWDEINT_MODE), (dwVal != SWDeintMode_None)); EnableWindow(GetDlgItem(m_Dlg, IDC_SWDEINT_OUT_FILM), (dwVal != SWDeintMode_None)); EnableWindow(GetDlgItem(m_Dlg, IDC_SWDEINT_OUT_VIDEO), (dwVal != SWDeintMode_None)); return S_OK; } HRESULT CLAVVideoSettingsProp::LoadData() { HRESULT hr = S_OK; m_dwNumThreads = m_pVideoSettings->GetNumThreads(); m_StreamAR = m_pVideoSettings->GetStreamAR(); m_DeintFieldOrder = m_pVideoSettings->GetDeintFieldOrder(); m_DeintMode = m_pVideoSettings->GetDeinterlacingMode(); m_dwRGBOutput = m_pVideoSettings->GetRGBOutputRange(); for (int i = 0; i < LAVOutPixFmt_NB; ++i) { m_bPixFmts[i] = m_pVideoSettings->GetPixelFormat((LAVOutPixFmts)i); } m_HWAccel = m_pVideoSettings->GetHWAccel(); for (int i = 0; i < HWCodec_NB; ++i) { m_HWAccelCodecs[i] = m_pVideoSettings->GetHWAccelCodec((LAVVideoHWCodec)i); } m_HWRes = m_pVideoSettings->GetHWAccelResolutionFlags(); m_HWAccelCUVIDDXVA = m_pVideoSettings->GetHWAccelDeintHQ(); m_HWDeintAlgo = m_pVideoSettings->GetHWAccelDeintMode(); m_HWDeintOutMode = m_pVideoSettings->GetHWAccelDeintOutput(); m_SWDeint = m_pVideoSettings->GetSWDeintMode(); m_SWDeintOutMode = m_pVideoSettings->GetSWDeintOutput(); m_DitherMode = m_pVideoSettings->GetDitherMode(); m_TrayIcon = m_pVideoSettings->GetTrayIcon(); return hr; } INT_PTR CLAVVideoSettingsProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT lValue; BOOL bValue; switch (uMsg) { case WM_COMMAND: if (LOWORD(wParam) == IDC_STREAMAR && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != m_StreamAR) { SetDirty(); } } else if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_THREADS) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETCURSEL, 0, 0); if (lValue != m_dwNumThreads) { SetDirty(); } } else if (LOWORD(wParam) == IDC_DEINT_FIELDORDER && HIWORD(wParam) == CBN_SELCHANGE) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETCURSEL, 0, 0); if (lValue != m_DeintFieldOrder) { SetDirty(); } } else if (LOWORD(wParam) == IDC_DEINT_MODE && HIWORD(wParam) == CBN_SELCHANGE) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETCURSEL, 0, 0); if (lValue != m_DeintMode) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_YV12 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_YV12]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_NV12 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_NV12]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_P010 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_P010]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_P016 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_P016]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_YUY2 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_YUY2]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_UYVY && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_UYVY]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_P210 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_P210]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_V210 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_v210]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_P216 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_P216]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_YV24 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_YV24]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_AYUV && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_AYUV]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_Y410 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_Y410]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_V410 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_v410]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_Y416 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_Y416]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_RGB32 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_RGB32]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_RGB24 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_RGB24]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_OUT_RGB48 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bPixFmts[LAVOutPixFmt_RGB48]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_RGBOUT_AUTO && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_dwRGBOutput == 0)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_RGBOUT_TV && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_dwRGBOutput == 1)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_RGBOUT_PC && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_dwRGBOutput == 2)) { SetDirty(); } } else if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_HWACCEL) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETCURSEL, 0, 0); lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETITEMDATA, lValue, 0); if (lValue != m_HWAccel) { SetDirty(); } UpdateHWOptions(); } else if (LOWORD(wParam) == IDC_HWACCEL_H264 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_H264]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWACCEL_VC1 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_VC1]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWACCEL_MPEG2 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_MPEG2]) { SetDirty(); } UpdateHWOptions(); } else if (LOWORD(wParam) == IDC_HWACCEL_MPEG4 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_MPEG4]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWACCEL_HEVC && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_HEVC]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWACCEL_VP9 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_VP9]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWACCEL_AV1 && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_AV1]) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWACCEL_H264MVC && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCodecs[HWCodec_H264MVC]) { SetDirty(); } } else if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_HWACCEL_DEVICE_SELECT) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETCURSEL, 0, 0); if (lValue != m_HWDeviceIndex) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWACCEL_CUVID_DXVA && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_HWAccelCUVIDDXVA) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWDEINT_ENABLE && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != (m_HWDeintAlgo == HWDeintMode_Hardware)) { SetDirty(); } UpdateHWOptions(); } else if (LOWORD(wParam) == IDC_HWDEINT_OUT_FILM && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != (m_HWDeintOutMode == DeintOutput_FramePer2Field)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWDEINT_OUT_VIDEO && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != (m_HWDeintOutMode == DeintOutput_FramePerField)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_SWDEINT_OUT_FILM && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != (m_SWDeintOutMode == DeintOutput_FramePer2Field)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_SWDEINT_OUT_VIDEO && HIWORD(wParam) == BN_CLICKED) { bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != (m_SWDeintOutMode == DeintOutput_FramePerField)) { SetDirty(); } } else if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_SWDEINT_MODE) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), CB_GETCURSEL, 0, 0); if (lValue != m_SWDeint) { SetDirty(); } UpdateYADIFOptions(); } else if (LOWORD(wParam) == IDC_DITHER_ORDERED && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_DitherMode == LAVDither_Ordered)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_DITHER_RANDOM && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != (m_DitherMode == LAVDither_Random)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWRES_SD && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue == !(m_HWRes & LAVHWResFlag_SD)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWRES_HD && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue == !(m_HWRes & LAVHWResFlag_HD)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_HWRES_UHD && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue == !(m_HWRes & LAVHWResFlag_UHD)) { SetDirty(); } } else if (LOWORD(wParam) == IDC_TRAYICON && HIWORD(wParam) == BN_CLICKED) { lValue = SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (lValue != m_TrayIcon) { SetDirty(); } } break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// // Format Configurations CLAVVideoFormatsProp::CLAVVideoFormatsProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVVideoFormats"), pUnk, IDD_PROPPAGE_FORMATS, IDS_FORMATS) { } CLAVVideoFormatsProp::~CLAVVideoFormatsProp() { } HRESULT CLAVVideoFormatsProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pVideoSettings == nullptr); return pUnk->QueryInterface(&m_pVideoSettings); } HRESULT CLAVVideoFormatsProp::OnDisconnect() { SafeRelease(&m_pVideoSettings); return S_OK; } HRESULT CLAVVideoFormatsProp::OnApplyChanges() { ASSERT(m_pVideoSettings != nullptr); HRESULT hr = S_OK; HWND hlv = GetDlgItem(m_Dlg, IDC_CODECS); // Get checked state BOOL bFlag; for (int nItem = 0; nItem < ListView_GetItemCount(hlv); nItem++) { bFlag = ListView_GetCheckState(hlv, nItem); m_pVideoSettings->SetFormatConfiguration((LAVVideoCodec)nItem, bFlag); } bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_CODECS_MSWMVDMO, BM_GETCHECK, 0, 0); m_pVideoSettings->SetUseMSWMV9Decoder(bFlag); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_DVD_VIDEO, BM_GETCHECK, 0, 0); m_pVideoSettings->SetDVDVideoSupport(bFlag); LoadData(); return hr; } HRESULT CLAVVideoFormatsProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES | ICC_LISTVIEW_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pVideoSettings != nullptr); // Setup ListView control for format configuration SendDlgItemMessage(m_Dlg, IDC_CODECS, CCM_DPISCALE, TRUE, 0); HWND hlv = GetDlgItem(m_Dlg, IDC_CODECS); ListView_SetExtendedListViewStyle(hlv, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); int nCol = 1; LVCOLUMN lvc = {LVCF_WIDTH, 0, 20, 0}; ListView_InsertColumn(hlv, 0, &lvc); ListView_AddCol(hlv, nCol, 85, L"Codec", false); ListView_AddCol(hlv, nCol, 400, L"Description", false); ListView_DeleteAllItems(hlv); ListView_SetItemCount(hlv, Codec_VideoNB); // Create entries for the formats LVITEM lvi; memset(&lvi, 0, sizeof(lvi)); lvi.mask = LVIF_TEXT | LVIF_PARAM; int nItem = 0; for (nItem = 0; nItem < Codec_VideoNB; ++nItem) { const codec_config_t *config = get_codec_config((LAVVideoCodec)nItem); // Create main entry lvi.iItem = nItem + 1; ListView_InsertItem(hlv, &lvi); // Set sub item texts ATL::CA2W name(config->name); ListView_SetItemText(hlv, nItem, 1, (LPWSTR)name); ATL::CA2W desc(config->description); ListView_SetItemText(hlv, nItem, 2, (LPWSTR)desc); } hr = LoadData(); if (SUCCEEDED(hr)) { // Set checked state for (nItem = 0; nItem < ListView_GetItemCount(hlv); nItem++) { ListView_SetCheckState(hlv, nItem, m_bFormats[nItem]); } } SendDlgItemMessage(m_Dlg, IDC_CODECS_MSWMVDMO, BM_SETCHECK, m_bWMVDMO, 0); SendDlgItemMessage(m_Dlg, IDC_DVD_VIDEO, BM_SETCHECK, m_bDVD, 0); return hr; } HRESULT CLAVVideoFormatsProp::LoadData() { HRESULT hr = S_OK; for (unsigned i = 0; i < Codec_VideoNB; ++i) m_bFormats[i] = m_pVideoSettings->GetFormatConfiguration((LAVVideoCodec)i) != 0; m_bWMVDMO = m_pVideoSettings->GetUseMSWMV9Decoder(); m_bDVD = m_pVideoSettings->GetDVDVideoSupport(); return hr; } INT_PTR CLAVVideoFormatsProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_COMMAND: if (LOWORD(wParam) == IDC_CODECS_MSWMVDMO && HIWORD(wParam) == BN_CLICKED) { BOOL bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bWMVDMO) { SetDirty(); } } else if (LOWORD(wParam) == IDC_DVD_VIDEO && HIWORD(wParam) == BN_CLICKED) { BOOL bValue = (BOOL)SendDlgItemMessage(m_Dlg, LOWORD(wParam), BM_GETCHECK, 0, 0); if (bValue != m_bDVD) { SetDirty(); } } break; case WM_NOTIFY: NMHDR *hdr = (LPNMHDR)lParam; if (hdr->idFrom == IDC_CODECS) { switch (hdr->code) { case LVN_ITEMCHANGED: LPNMLISTVIEW nmlv = (LPNMLISTVIEW)lParam; BOOL check = ListView_GetCheckState(hdr->hwndFrom, nmlv->iItem); if (check != m_bFormats[nmlv->iItem]) { SetDirty(); } return TRUE; } } break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } ================================================ FILE: decoder/LAVVideo/VideoSettingsProp.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "LAVVideoSettings.h" #include "BaseDSPropPage.h" #include "Media.h" // {278407C2-558C-4BED-83A0-B6FA454200BD} DEFINE_GUID(CLSID_LAVVideoSettingsProp, 0x278407c2, 0x558c, 0x4bed, 0x83, 0xa0, 0xb6, 0xfa, 0x45, 0x42, 0x0, 0xbd); // {2D4D6F88-8B41-40A2-B297-3D722816648B} DEFINE_GUID(CLSID_LAVVideoFormatsProp, 0x2d4d6f88, 0x8b41, 0x40a2, 0xb2, 0x97, 0x3d, 0x72, 0x28, 0x16, 0x64, 0x8b); class CLAVVideoSettingsProp : public CBaseDSPropPage { public: CLAVVideoSettingsProp(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVVideoSettingsProp(); HRESULT OnActivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); HRESULT OnApplyChanges(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: HRESULT LoadData(); HRESULT UpdateHWOptions(); HRESULT UpdateYADIFOptions(); void SetDirty() { m_bDirty = TRUE; if (m_pPageSite) { m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY); } } private: ILAVVideoSettings *m_pVideoSettings = nullptr; ILAVVideoStatus *m_pVideoStatus = nullptr; DWORD m_dwNumThreads; DWORD m_StreamAR; DWORD m_DeintFieldOrder; LAVDeintMode m_DeintMode; DWORD m_dwRGBOutput; BOOL m_bPixFmts[LAVOutPixFmt_NB]; DWORD m_HWAccel; BOOL m_HWAccelCodecs[HWCodec_NB]; BOOL m_HWAccelCUVIDDXVA; DWORD m_HWRes; DWORD m_HWDeviceIndex; DWORD m_HWDeintAlgo; DWORD m_HWDeintOutMode; LAVSWDeintModes m_SWDeint; DWORD m_SWDeintOutMode; DWORD m_DitherMode; BOOL m_TrayIcon; }; class CLAVVideoFormatsProp : public CBaseDSPropPage { public: CLAVVideoFormatsProp(LPUNKNOWN pUnk, HRESULT *phr); ~CLAVVideoFormatsProp(); HRESULT OnActivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); HRESULT OnApplyChanges(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: HRESULT LoadData(); void SetDirty() { m_bDirty = TRUE; if (m_pPageSite) { m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY); } } private: ILAVVideoSettings *m_pVideoSettings = nullptr; BOOL m_bFormats[Codec_VideoNB]; BOOL m_bWMVDMO; BOOL m_bDVD; }; ================================================ FILE: decoder/LAVVideo/decoders/DecBase.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "ILAVDecoder.h" #include "DeCSS/DeCSSInputPin.h" class CDecBase : public ILAVDecoder { public: CDecBase(void) {} virtual ~CDecBase(void) {} STDMETHOD(Init)() PURE; STDMETHOD(Decode) (const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample) PURE; // ILAVDecoder STDMETHODIMP InitInterfaces(ILAVVideoSettings *pSettings, ILAVVideoCallback *pCallback) { m_pSettings = pSettings; m_pCallback = pCallback; return Init(); } STDMETHODIMP Check() { return S_FALSE; } STDMETHODIMP_(REFERENCE_TIME) GetFrameDuration() { return 0; } STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess) { return TRUE; } STDMETHODIMP InitAllocator(IMemAllocator **ppAlloc) { return E_NOTIMPL; } STDMETHODIMP PostConnect(IPin *pPin) { return S_FALSE; } STDMETHODIMP BreakConnect() { return S_FALSE; } STDMETHODIMP_(long) GetBufferCount(long *pMaxBuffers = nullptr) { return 2; } STDMETHODIMP HasThreadSafeBuffers() { return S_FALSE; } STDMETHODIMP SetDirectOutput(BOOL bDirect) { return S_FALSE; } STDMETHODIMP_(DWORD) GetHWAccelNumDevices() { return 0; } STDMETHODIMP GetHWAccelDeviceInfo(DWORD dwIndex, BSTR *pstrDeviceName, DWORD *dwDeviceIdentifier) { return E_UNEXPECTED; } STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName) { return E_UNEXPECTED; } STDMETHODIMP Decode(IMediaSample *pSample) { HRESULT hr; // Retrieve buffer BYTE *pData = nullptr; if (FAILED(hr = pSample->GetPointer(&pData))) { return hr; } // Retrieve timestamps REFERENCE_TIME rtStart, rtStop; hr = pSample->GetTime(&rtStart, &rtStop); if (FAILED(hr)) { rtStart = rtStop = AV_NOPTS_VALUE; } else if (hr == VFW_S_NO_STOP_TIME || rtStop - 1 <= rtStart) { rtStop = AV_NOPTS_VALUE; } // DVD Stripping long nSize = pSample->GetActualDataLength(); m_pCallback->DVDStripPacket(pData, nSize); if (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_SAGE_HACK) { FFSWAP(REFERENCE_TIME, rtStart, m_rtTimestampBuffer); rtStop = AV_NOPTS_VALUE; } return Decode(pData, nSize, rtStart, rtStop, pSample->IsSyncPoint() == S_OK, pSample->IsDiscontinuity() == S_OK, pSample); } STDMETHODIMP Flush() { m_rtTimestampBuffer = 0; m_MpegParserState = (uint32_t)-1; return S_OK; }; protected: // Convenience wrapper around m_pCallback inline HRESULT Deliver(LAVFrame *pFrame) { return m_pCallback->Deliver(pFrame); } inline HRESULT AllocateFrame(LAVFrame **ppFrame) { return m_pCallback->AllocateFrame(ppFrame); } inline HRESULT ReleaseFrame(LAVFrame **ppFrame) { return m_pCallback->ReleaseFrame(ppFrame); } protected: ILAVVideoSettings *m_pSettings = nullptr; ILAVVideoCallback *m_pCallback = nullptr; REFERENCE_TIME m_rtTimestampBuffer = AV_NOPTS_VALUE; uint32_t m_MpegParserState = (uint32_t)-1; }; ================================================ FILE: decoder/LAVVideo/decoders/ILAVDecoder.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "LAVVideoSettings.h" #include "ILAVPinInfo.h" /** * List of internally used pixel formats * * Note for high bit-depth formats: * All bX (9-16 bit) formats always use 2 bytes, are little-endian, and the values are right-aligned. * That means that there are leading zero-bits, and not trailing like in DirectShow * The actual number of valid bits is stored in the LAVFrame */ // clang-format off typedef enum LAVPixelFormat { LAVPixFmt_None = -1, /* planar YUV */ LAVPixFmt_YUV420, ///< YUV 4:2:0, 8 bit LAVPixFmt_YUV420bX, ///< YUV 4:2:0, 9-16 bit LAVPixFmt_YUV422, ///< YUV 4:2:2, 8 bit LAVPixFmt_YUV422bX, ///< YUV 4:2:2, 9-16 bit LAVPixFmt_YUV444, ///< YUV 4:4:4, 8 bit LAVPixFmt_YUV444bX, ///< YUV 4:4:4, 9-16 bit /* packed/half-packed YUV */ LAVPixFmt_NV12, ///< YUV 4:2:0, U/V interleaved LAVPixFmt_YUY2, ///< YUV 4:2:2, packed, YUYV order LAVPixFmt_P016, ///< YUV 4:2:0, 10 to 16-bit, U/V interleaved, MSB aligned /* RGB */ LAVPixFmt_RGB24, ///< RGB24, in BGR order LAVPixFmt_RGB32, ///< RGB32, in BGRA order (A is invalid and should be 0xFF) LAVPixFmt_ARGB32, ///< ARGB32, in BGRA order LAVPixFmt_RGB48, ///< RGB48, in RGB order (16-bit per pixel) /* HW formats */ LAVPixFmt_AYUV, ///< AYUV, 4:4:4 8-bit LAVPixFmt_Y410, ///< Y410, 4:4:4 10-bit packed into 32-bit, AVYU order (A is 2 bit) LAVPixFmt_Y416, ///< Y416, 4:4:4 16-bit, AVYU order LAVPixFmt_Y216, ///< Y210/Y216, 4:2:2, 10 to 16-bit packed into 64-bit, Y0/U/Y1/V LAVPixFmt_HWFormats, LAVPixFmt_DXVA2 = LAVPixFmt_HWFormats, ///< DXVA2 Surface LAVPixFmt_D3D11, ///< D3D11 Surface LAVPixFmt_NB, ///< number of formats } LAVPixelFormat; // clang-format on /** * Structure describing a pixel format */ typedef struct LAVPixFmtDesc { int codedbytes; ///< coded byte per pixel in one plane (for packed and multibyte formats) int planes; ///< number of planes int planeWidth[4]; ///< log2 width factor int planeHeight[4]; ///< log2 height factor } LAVPixFmtDesc; /** * Get the Pixel Format Descriptor for the given format */ LAVPixFmtDesc getPixelFormatDesc(LAVPixelFormat pixFmt); /** * Map the LAV Pixel Format to a FFMpeg pixel format (for swscale, etc) */ AVPixelFormat getFFPixelFormatFromLAV(LAVPixelFormat pixFmt, int bpp); typedef struct LAVDirectBuffer { BYTE *data[4]; ///< pointer to the picture planes ptrdiff_t stride[4]; ///< stride of the planes (in bytes) UINT Width, Height; ///< width/height of the locked texture } LAVDirectBuffer; typedef struct LAVFrameSideData { GUID guidType; ///< type of the side data BYTE *data; ///< side data size_t size; ///< size } LAVFrameSideData; /** * A Video Frame * * Allocated by the decoder and passed through the processing chain. * * The Decoder should allocate frames by using ILAVVideoCallback::AllocateFrame() * Frames need to be free'd with ILAVVideoCallback::ReleaseFrame() * * FIXME: Right now the avcodec decoder always reuses the buffers the next time its called! * NYI: Some Post-Processing filters will require to hang on to frames longer then the normal delivery process. * NYI: That means that the image buffers should not be re-used unless "destruct" released them. */ typedef struct LAVFrame { int width; ///< width of the frame (in pixel) int height; ///< height of the frame (in pixel) BYTE *data[4]; ///< pointer to the picture planes BYTE *stereo[4]; ///< pointer to the second view picture planes ptrdiff_t stride[4]; ///< stride of the planes (in bytes) LAVPixelFormat format; ///< pixel format of the frame LAVPixelFormat sw_format; int bpp; ///< bits per pixel, only meaningful for YUV420bX, YUV422bX or YUV444bX REFERENCE_TIME rtStart; ///< start time of the frame. unset if AV_NOPTS_VALUE REFERENCE_TIME rtStop; ///< stop time of the frame. unset if AV_NOPTS_VALUE int repeat; ///< repeat frame flag, signals how much the frame should be delayed AVRational aspect_ratio; ///< display aspect ratio (unset/invalid if either num or den is 0) REFERENCE_TIME avgFrameDuration; ///< frame duration used for the media type to indicate fps (AV_NOPTS_VALUE or 0 = ///< use from input pin) DXVA2_ExtendedFormat ext_format; ///< extended format flags (critical uses: indicate progressive/interlaced, ///< indicate limited/full range) int key_frame; ///< frame is a key frame (field is not mandatory) int interlaced; ///< frame is interlaced int tff; ///< top field is first char frame_type; ///< frame type char (I/P/B/?) int flags; ///< frame flags #define LAV_FRAME_FLAG_BUFFER_MODIFY 0x00000001 #define LAV_FRAME_FLAG_END_OF_SEQUENCE 0x00000002 #define LAV_FRAME_FLAG_FLUSH 0x00000004 #define LAV_FRAME_FLAG_REDRAW 0x00000008 #define LAV_FRAME_FLAG_DXVA_NOADDREF 0x00000010 #define LAV_FRAME_FLAG_MVC 0x00000020 LAVFrameSideData *side_data; int side_data_count; /* destruct function to free any buffers being held by this frame (may be null) */ void (*destruct)(struct LAVFrame *); void *priv_data; ///< private data from the decoder (mostly for destruct) bool direct; bool (*direct_lock)(struct LAVFrame *, struct LAVDirectBuffer *); void (*direct_unlock)(struct LAVFrame *); } LAVFrame; /** * Allocate buffers for the LAVFrame "data" element to fit the pixfmt with the given stride * * This method also fills the stride argument in the LAVFrame properly. * Its required that width/height and format are already set on the frame. * * @param pFrame Frame to fill * @param stride stride to use (in pixel). If 0, a stride will be computed to fill usual alignment rules * @return HRESULT */ HRESULT AllocLAVFrameBuffers(LAVFrame *pFrame, ptrdiff_t stride = 0); /** * Destruct a LAV Frame, freeing its data pointers */ HRESULT FreeLAVFrameBuffers(LAVFrame *pFrame); /** * Copy a LAV Frame, including a memcpy of the data */ HRESULT CopyLAVFrame(LAVFrame *pSrc, LAVFrame **ppDst); /** * Copy the buffers in the LAV Frame, calling destruct on the old buffers. * * Usually useful to release decoder-specific buffers, and move to memory buffers */ HRESULT CopyLAVFrameInPlace(LAVFrame *pFrame); /** * Add Side Data to the frame and return a pointer to it */ BYTE *AddLAVFrameSideData(LAVFrame *pFrame, GUID guidType, size_t size); /** * Get a side data entry from the frame by its type */ BYTE *GetLAVFrameSideData(LAVFrame *pFrame, GUID guidType, size_t *pSize); /** * Validate that the frame has the correct number of allocated buffers */ bool ValidateLAVFrameBuffers(LAVFrame *pFrame); typedef struct LAVPinInfo { DWORD flags; ///< Flags that describe the video content (see ILAVPinInfo.h for valid values) AVPixelFormat pix_fmt; ///< The pixel format used int has_b_frames; } LAVPinInfo; /** * Interface into the LAV Video core for the decoder implementations * This interface offers all required functions to properly communicate with the core */ interface ILAVVideoCallback { /** * Allocate and initialize a new frame * * @param ppFrame variable to receive the frame * @return HRESULT */ STDMETHOD(AllocateFrame)(LAVFrame * *ppFrame) PURE; /** * Destruct and release frame * This function calls the "destruct" function on the frame, and releases it afterwards * * @param ppFrame variable of the frame, will be nulled * @return HRESULT */ STDMETHOD(ReleaseFrame)(LAVFrame * *ppFrame) PURE; /** * Deliver the frame * The decoder gives up control of the frame at this point, and hands it over to the processing chain * * @param pFrame frame to deliver * @return HRESULT */ STDMETHOD(Deliver)(LAVFrame * pFrame) PURE; /** * Get the extension of the currently loaded file * * @result WCHAR string to the extension. Callers needs to free the memory with CoTaskMemFree */ STDMETHOD_(LPWSTR, GetFileExtension)() PURE; /** * Get Decode Flags * * @return flags */ STDMETHOD_(DWORD, GetDecodeFlags)() PURE; #define LAV_VIDEO_DEC_FLAG_STREAMAR_BLACKLIST 0x00000001 #define LAV_VIDEO_DEC_FLAG_ONLY_DTS 0x00000002 #define LAV_VIDEO_DEC_FLAG_LAVSPLITTER 0x00000008 #define LAV_VIDEO_DEC_FLAG_DVD 0x00000010 #define LAV_VIDEO_DEC_FLAG_NO_MT 0x00000020 #define LAV_VIDEO_DEC_FLAG_SAGE_HACK 0x00000040 #define LAV_VIDEO_DEC_FLAG_LIVE 0x00000080 /** * Get the input media type * * @result media type */ STDMETHOD_(CMediaType &, GetInputMediaType)() PURE; /** * Query the LAVPinInfo */ STDMETHOD(GetLAVPinInfo)(LAVPinInfo & info) PURE; /** * Get a reference to the output pin */ STDMETHOD_(CBasePin *, GetOutputPin)() PURE; /** * Get the output media type * * @result media type */ STDMETHOD_(CMediaType &, GetOutputMediaType)() PURE; /** * Strip the packet for DVD decoding */ STDMETHOD(DVDStripPacket)(BYTE * &p, long &len) PURE; /** * Get a Dummy frame used for flusing */ STDMETHOD_(LAVFrame *, GetFlushFrame)() PURE; /** * Ask the decoder to release all DXVA resources */ STDMETHOD(ReleaseAllDXVAResources)() PURE; /** * Get the index of the GPU device to be used for HW decoding, DWORD_MAX if not set */ STDMETHOD_(DWORD, GetGPUDeviceIndex)() PURE; /** * Check if the input is using a dynamic allocator */ STDMETHOD_(BOOL, HasDynamicInputAllocator)() PURE; /** * Set the x264 build info */ STDMETHOD(SetX264Build)(int nBuild) PURE; /** * Get the x264 build info */ STDMETHOD_(int, GetX264Build)() PURE; }; /** * Decoder interface * * Every decoder needs to implement this to interface with the LAV Video core */ interface ILAVDecoder { /** * Virtual destructor */ virtual ~ILAVDecoder(void){}; /** * Initialize interfaces with the LAV Video core * This function should also be used to create all interfaces with external DLLs * * @param pSettings reference to the settings interface * @param pCallback reference to the callback interface * @return S_OK on success, error code if this decoder is lacking an external support dll */ STDMETHOD(InitInterfaces)(ILAVVideoSettings * pSettings, ILAVVideoCallback * pCallback) PURE; /** * Check if the decoder is functional */ STDMETHOD(Check)() PURE; /** * Initialize the codec to decode a stream specified by codec and pmt. * * @param codec Codec Id * @param pmt DirectShow Media Type * @return S_OK on success, an error code otherwise */ STDMETHOD(InitDecoder)(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) PURE; /** * Decode a frame. * * @param pSample Media Sample to decode * @return S_OK if decoding was successful, S_FALSE if no frame could be extracted, an error code if the decoder is * not compatible with the bitstream * * Note: When returning an actual error code, the filter will switch to the fallback software decoder! This should * only be used for catastrophic failures, like trying to decode a unsupported format on a hardware decoder. */ STDMETHOD(Decode)(IMediaSample * pSample) PURE; /** * Flush the decoder after a seek. * The decoder should discard any remaining data. * * @return unused */ STDMETHOD(Flush)() PURE; /** * End of Stream * The decoder is asked to output any buffered frames for immediate delivery * * @return unused */ STDMETHOD(EndOfStream)() PURE; /** * Query the decoder for the current pixel format * Mostly used by the media type creation logic before playback starts * * @return the pixel format used in the decoding process */ STDMETHOD(GetPixelFormat)(LAVPixelFormat * pPix, int *pBpp, LAVPixelFormat *pPixSoftware) PURE; /** * Get the frame duration. * * This function is not mandatory, and if you cannot provide any specific duration, return 0. */ STDMETHOD_(REFERENCE_TIME, GetFrameDuration)() PURE; /** * Query whether the format can potentially be interlaced. * This function should return false if the format can 100% not be interlaced, and true if it can be interlaced (but * also progressive). */ STDMETHOD_(BOOL, IsInterlaced)(BOOL bAllowGuess) PURE; /** * Allows the decoder to handle an allocator. * Used by DXVA2 decoding */ STDMETHOD(InitAllocator)(IMemAllocator * *ppAlloc) PURE; /** * Function called after connection is established, with the pin as argument */ STDMETHOD(PostConnect)(IPin * pPin) PURE; /** * Notify the decoder the output connection was broken */ STDMETHOD(BreakConnect)() PURE; /** * Get the number of sample buffers optimal for this decoder */ STDMETHOD_(long, GetBufferCount)(long *pMaxBuffers = nullptr) PURE; /** * Get the name of the decoder */ STDMETHOD_(const WCHAR *, GetDecoderName)() PURE; /** * Get whether the decoder outputs thread-safe buffers */ STDMETHOD(HasThreadSafeBuffers)() PURE; /** * Toggle direct frame output mode for hardware decoders */ STDMETHOD(SetDirectOutput)(BOOL bDirect) PURE; /** * Get the number of available hw accel devices */ STDMETHOD_(DWORD, GetHWAccelNumDevices)() PURE; /** * Get information about a hwaccel device */ STDMETHOD(GetHWAccelDeviceInfo)(DWORD dwIndex, BSTR * pstrDeviceName, DWORD * dwDeviceIdentifier) PURE; /** * Get the description of the currently active hwaccel device */ STDMETHOD(GetHWAccelActiveDevice)(BSTR * pstrDeviceName) PURE; }; /** * Decoder creation functions * * They are listed here so that including their header files is not required */ ILAVDecoder *CreateDecoderAVCodec(); ILAVDecoder *CreateDecoderWMV9MFT(); ILAVDecoder *CreateDecoderCUVID(); ILAVDecoder *CreateDecoderQuickSync(); ILAVDecoder *CreateDecoderDXVA2(); ILAVDecoder *CreateDecoderDXVA2Native(); ILAVDecoder *CreateDecoderD3D11(); ILAVDecoder *CreateDecoderMSDKMVC(); HRESULT VerifyD3D9Device(DWORD &dwIndex, DWORD dwDeviceId); HRESULT VerifyD3D11Device(DWORD &dwIndex, DWORD dwDeviceId); ================================================ FILE: decoder/LAVVideo/decoders/avcodec.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "avcodec.h" #include "moreuuids.h" #include "parsers/MPEG2HeaderParser.h" #include "parsers/H264SequenceParser.h" #include "parsers/VC1HeaderParser.h" #include "Media.h" #include "IMediaSideData.h" #include "IMediaSideDataFFmpeg.h" #include "ByteParser.h" #ifdef DEBUG #include "lavf_log.h" #endif extern "C" { #include "libavutil/pixdesc.h" #include "libavutil/mastering_display_metadata.h" #include "libavutil/hdr_dynamic_metadata.h" #include "libavutil/dovi_meta.h" }; //////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////// ILAVDecoder *CreateDecoderAVCodec() { return new CDecAvcodec(); } //////////////////////////////////////////////////////////////////////////////// // Create DXVA2 Extended Flags from a AVFrame and AVCodecContext //////////////////////////////////////////////////////////////////////////////// static DXVA2_ExtendedFormat GetDXVA2ExtendedFlags(AVFrame *frame) { DXVA2_ExtendedFormat fmt; ZeroMemory(&fmt, sizeof(fmt)); fillDXVAExtFormat(fmt, -1, frame->color_primaries, frame->colorspace, frame->color_trc, frame->chroma_location); if (frame->format == AV_PIX_FMT_XYZ12LE || frame->format == AV_PIX_FMT_XYZ12BE) fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709; // Color Range, 0-255 or 16-235 BOOL ffFullRange = (frame->color_range == AVCOL_RANGE_JPEG) || frame->format == AV_PIX_FMT_YUVJ420P || frame->format == AV_PIX_FMT_YUVJ422P || frame->format == AV_PIX_FMT_YUVJ444P || frame->format == AV_PIX_FMT_YUVJ440P || frame->format == AV_PIX_FMT_YUVJ411P; fmt.NominalRange = ffFullRange ? DXVA2_NominalRange_0_255 : (frame->color_range == AVCOL_RANGE_MPEG) ? DXVA2_NominalRange_16_235 : DXVA2_NominalRange_Unknown; return fmt; } //////////////////////////////////////////////////////////////////////////////// // avcodec -> LAV codec mappings //////////////////////////////////////////////////////////////////////////////// // This mapping table should contain all pixel formats, except hardware formats (VDPAU, XVMC, DXVA, etc) // A format that is not listed will be converted to YUV420 static struct PixelFormatMapping { AVPixelFormat ffpixfmt; LAVPixelFormat lavpixfmt; BOOL conversion; int bpp; } ff_pix_map[] = { {AV_PIX_FMT_YUV420P, LAVPixFmt_YUV420, FALSE}, {AV_PIX_FMT_YUYV422, LAVPixFmt_YUY2, FALSE}, {AV_PIX_FMT_BGR24, LAVPixFmt_RGB24, FALSE}, {AV_PIX_FMT_YUV422P, LAVPixFmt_YUV422, FALSE}, {AV_PIX_FMT_YUV444P, LAVPixFmt_YUV444, FALSE}, {AV_PIX_FMT_YUVJ420P, LAVPixFmt_YUV420, FALSE}, {AV_PIX_FMT_YUVJ422P, LAVPixFmt_YUV422, FALSE}, {AV_PIX_FMT_YUVJ444P, LAVPixFmt_YUV444, FALSE}, {AV_PIX_FMT_NV12, LAVPixFmt_NV12, FALSE}, {AV_PIX_FMT_NV21, LAVPixFmt_NV12, TRUE}, {AV_PIX_FMT_BGRA, LAVPixFmt_ARGB32, FALSE}, {AV_PIX_FMT_RGB48LE, LAVPixFmt_RGB48, FALSE}, {AV_PIX_FMT_YUV420P16LE, LAVPixFmt_YUV420bX, FALSE, 16}, {AV_PIX_FMT_YUV420P16BE, LAVPixFmt_YUV420bX, TRUE, 16}, {AV_PIX_FMT_YUV422P16LE, LAVPixFmt_YUV422bX, FALSE, 16}, {AV_PIX_FMT_YUV422P16BE, LAVPixFmt_YUV422bX, TRUE, 16}, {AV_PIX_FMT_YUV444P16LE, LAVPixFmt_YUV444bX, FALSE, 16}, {AV_PIX_FMT_YUV444P16BE, LAVPixFmt_YUV444bX, TRUE, 16}, {AV_PIX_FMT_YUV420P9BE, LAVPixFmt_YUV420bX, TRUE, 9}, {AV_PIX_FMT_YUV420P9LE, LAVPixFmt_YUV420bX, FALSE, 9}, {AV_PIX_FMT_YUV420P10BE, LAVPixFmt_YUV420bX, TRUE, 10}, {AV_PIX_FMT_YUV420P10LE, LAVPixFmt_YUV420bX, FALSE, 10}, {AV_PIX_FMT_YUV422P10BE, LAVPixFmt_YUV422bX, TRUE, 10}, {AV_PIX_FMT_YUV422P10LE, LAVPixFmt_YUV422bX, FALSE, 10}, {AV_PIX_FMT_YUV444P9BE, LAVPixFmt_YUV444bX, TRUE, 9}, {AV_PIX_FMT_YUV444P9LE, LAVPixFmt_YUV444bX, FALSE, 9}, {AV_PIX_FMT_YUV444P10BE, LAVPixFmt_YUV444bX, TRUE, 10}, {AV_PIX_FMT_YUV444P10LE, LAVPixFmt_YUV444bX, FALSE, 10}, {AV_PIX_FMT_YUV422P9BE, LAVPixFmt_YUV422bX, TRUE, 9}, {AV_PIX_FMT_YUV422P9LE, LAVPixFmt_YUV422bX, FALSE, 9}, {AV_PIX_FMT_YUVA420P9BE, LAVPixFmt_YUV420bX, TRUE, 9}, {AV_PIX_FMT_YUVA420P9LE, LAVPixFmt_YUV420bX, FALSE, 9}, {AV_PIX_FMT_YUVA422P9BE, LAVPixFmt_YUV422bX, TRUE, 9}, {AV_PIX_FMT_YUVA422P9LE, LAVPixFmt_YUV422bX, FALSE, 9}, {AV_PIX_FMT_YUVA444P9BE, LAVPixFmt_YUV444bX, TRUE, 9}, {AV_PIX_FMT_YUVA444P9LE, LAVPixFmt_YUV444bX, FALSE, 9}, {AV_PIX_FMT_YUVA420P10BE, LAVPixFmt_YUV420bX, TRUE, 10}, {AV_PIX_FMT_YUVA420P10LE, LAVPixFmt_YUV420bX, FALSE, 10}, {AV_PIX_FMT_YUVA422P10BE, LAVPixFmt_YUV422bX, TRUE, 10}, {AV_PIX_FMT_YUVA422P10LE, LAVPixFmt_YUV422bX, FALSE, 10}, {AV_PIX_FMT_YUVA444P10BE, LAVPixFmt_YUV444bX, TRUE, 10}, {AV_PIX_FMT_YUVA444P10LE, LAVPixFmt_YUV444bX, FALSE, 10}, {AV_PIX_FMT_YUVA420P16BE, LAVPixFmt_YUV420bX, TRUE, 16}, {AV_PIX_FMT_YUVA420P16LE, LAVPixFmt_YUV420bX, FALSE, 16}, {AV_PIX_FMT_YUVA422P16BE, LAVPixFmt_YUV422bX, TRUE, 16}, {AV_PIX_FMT_YUVA422P16LE, LAVPixFmt_YUV422bX, FALSE, 16}, {AV_PIX_FMT_YUVA444P16BE, LAVPixFmt_YUV444bX, TRUE, 16}, {AV_PIX_FMT_YUVA444P16LE, LAVPixFmt_YUV444bX, FALSE, 16}, {AV_PIX_FMT_BGR0, LAVPixFmt_RGB32, FALSE}, {AV_PIX_FMT_YUV420P12BE, LAVPixFmt_YUV420bX, TRUE, 12}, {AV_PIX_FMT_YUV420P12LE, LAVPixFmt_YUV420bX, FALSE, 12}, {AV_PIX_FMT_YUV420P14BE, LAVPixFmt_YUV420bX, TRUE, 14}, {AV_PIX_FMT_YUV420P14LE, LAVPixFmt_YUV420bX, FALSE, 14}, {AV_PIX_FMT_YUV422P12BE, LAVPixFmt_YUV422bX, TRUE, 12}, {AV_PIX_FMT_YUV422P12LE, LAVPixFmt_YUV422bX, FALSE, 12}, {AV_PIX_FMT_YUV422P14BE, LAVPixFmt_YUV422bX, TRUE, 14}, {AV_PIX_FMT_YUV422P14LE, LAVPixFmt_YUV422bX, FALSE, 14}, {AV_PIX_FMT_YUV444P12BE, LAVPixFmt_YUV444bX, TRUE, 12}, {AV_PIX_FMT_YUV444P12LE, LAVPixFmt_YUV444bX, FALSE, 12}, {AV_PIX_FMT_YUV444P14BE, LAVPixFmt_YUV444bX, TRUE, 14}, {AV_PIX_FMT_YUV444P14LE, LAVPixFmt_YUV444bX, FALSE, 14}, {AV_PIX_FMT_P010LE, LAVPixFmt_P016, FALSE, 10}, {AV_PIX_FMT_P010BE, LAVPixFmt_P016, TRUE, 10}, {AV_PIX_FMT_P016LE, LAVPixFmt_P016, FALSE, 16}, {AV_PIX_FMT_P016BE, LAVPixFmt_P016, TRUE, 16}, {AV_PIX_FMT_YUVA422P12BE, LAVPixFmt_YUV422bX, TRUE, 12}, {AV_PIX_FMT_YUVA422P12LE, LAVPixFmt_YUV422bX, FALSE, 12}, {AV_PIX_FMT_YUVA444P12BE, LAVPixFmt_YUV444bX, TRUE, 12}, {AV_PIX_FMT_YUVA444P12LE, LAVPixFmt_YUV444bX, FALSE, 12}, {AV_PIX_FMT_Y210BE, LAVPixFmt_Y216, TRUE, 10}, {AV_PIX_FMT_Y210LE, LAVPixFmt_Y216, FALSE, 10}, {AV_PIX_FMT_VUYA, LAVPixFmt_AYUV, FALSE}, {AV_PIX_FMT_VUYX, LAVPixFmt_AYUV, FALSE}, {AV_PIX_FMT_P012LE, LAVPixFmt_P016, FALSE, 12}, {AV_PIX_FMT_P012BE, LAVPixFmt_P016, TRUE, 12}, {AV_PIX_FMT_Y212BE, LAVPixFmt_Y216, TRUE, 12}, {AV_PIX_FMT_Y212LE, LAVPixFmt_Y216, FALSE, 12}, {AV_PIX_FMT_XV30BE, LAVPixFmt_Y410, TRUE, 10}, {AV_PIX_FMT_XV30LE, LAVPixFmt_Y410, FALSE, 10}, {AV_PIX_FMT_XV48BE, LAVPixFmt_Y416, TRUE, 10}, {AV_PIX_FMT_XV48LE, LAVPixFmt_Y416, FALSE, 10}, {AV_PIX_FMT_Y216BE, LAVPixFmt_Y216, TRUE, 16}, {AV_PIX_FMT_Y216LE, LAVPixFmt_Y216, FALSE, 16}, {AV_PIX_FMT_DXVA2_VLD, LAVPixFmt_DXVA2, FALSE}, {AV_PIX_FMT_D3D11, LAVPixFmt_D3D11, FALSE}, }; static AVCodecID ff_interlace_capable[] = {AV_CODEC_ID_DNXHD, AV_CODEC_ID_DVVIDEO, AV_CODEC_ID_FRWU, AV_CODEC_ID_MJPEG, AV_CODEC_ID_MPEG4, AV_CODEC_ID_MPEG2VIDEO, AV_CODEC_ID_H264, AV_CODEC_ID_VC1, AV_CODEC_ID_PNG, AV_CODEC_ID_PRORES, AV_CODEC_ID_RAWVIDEO, AV_CODEC_ID_UTVIDEO}; static struct PixelFormatMapping getPixFmtMapping(AVPixelFormat pixfmt) { const PixelFormatMapping def = {pixfmt, LAVPixFmt_YUV420, TRUE, 8}; PixelFormatMapping result = { AV_PIX_FMT_NONE }; for (int i = 0; i < countof(ff_pix_map); i++) { if (ff_pix_map[i].ffpixfmt == pixfmt) { result = ff_pix_map[i]; break; } } // use a heuristic if there was no perfect match if (result.ffpixfmt == AV_PIX_FMT_NONE) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pixfmt); if (desc == nullptr) { result = def; } else { // RGB formats (or PAL) if (desc->flags & (AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_PAL)) { if (desc->comp[0].depth > 8) result = {pixfmt, LAVPixFmt_RGB48, TRUE}; else result = {pixfmt, LAVPixFmt_RGB32, TRUE}; } else { // 420 and 410 (and gray) if ((desc->log2_chroma_w && desc->log2_chroma_h) || desc->nb_components == 1) { if (desc->comp[0].depth > 8) result = {pixfmt, LAVPixFmt_YUV420bX, TRUE, desc->comp[0].depth}; else result = {pixfmt, LAVPixFmt_YUV420, TRUE}; } else if (desc->log2_chroma_w) // 422 and 411 { if (desc->comp[0].depth > 8) result = {pixfmt, LAVPixFmt_YUV422bX, TRUE, desc->comp[0].depth}; else result = {pixfmt, LAVPixFmt_YUV422, TRUE}; } else // 444 and others { if (desc->comp[0].depth > 8) result = {pixfmt, LAVPixFmt_YUV444bX, TRUE, desc->comp[0].depth}; else result = {pixfmt, LAVPixFmt_YUV444, TRUE}; } } } } if (result.lavpixfmt != LAVPixFmt_YUV420bX && result.lavpixfmt != LAVPixFmt_YUV422bX && result.lavpixfmt != LAVPixFmt_YUV444bX && result.lavpixfmt != LAVPixFmt_P016 && result.lavpixfmt != LAVPixFmt_Y216) result.bpp = 8; return result; } //////////////////////////////////////////////////////////////////////////////// // AVCodec decoder implementation //////////////////////////////////////////////////////////////////////////////// CDecAvcodec::CDecAvcodec(void) : CDecBase() { } CDecAvcodec::~CDecAvcodec(void) { DestroyDecoder(); } // ILAVDecoder STDMETHODIMP CDecAvcodec::Init() { #ifdef DEBUG DbgSetModuleLevel(LOG_CUSTOM1, DWORD_MAX); // FFMPEG messages use custom1 av_log_set_callback(lavf_log_callback); #else av_log_set_callback(nullptr); #endif return S_OK; } STDMETHODIMP CDecAvcodec::InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) { DestroyDecoder(); DbgLog((LOG_TRACE, 10, L"Initializing ffmpeg for codec %S", avcodec_get_name(codec))); BITMAPINFOHEADER *pBMI = nullptr; videoFormatTypeHandler((const BYTE *)pmt->Format(), pmt->FormatType(), &pBMI); if (codec == AV_CODEC_ID_AV1 && IsHardwareAccelerator()) { m_pAVCodec = avcodec_find_decoder_by_name("av1"); } else { m_pAVCodec = avcodec_find_decoder(codec); } CheckPointer(m_pAVCodec, VFW_E_UNSUPPORTED_VIDEO); m_pAVCtx = avcodec_alloc_context3(m_pAVCodec); CheckPointer(m_pAVCtx, E_POINTER); DWORD dwDecFlags = m_pCallback->GetDecodeFlags(); // Use parsing for mpeg1/2 at all times, or H264/HEVC when its not from LAV Splitter if (codec == AV_CODEC_ID_MPEG1VIDEO || codec == AV_CODEC_ID_MPEG2VIDEO || (!(dwDecFlags & LAV_VIDEO_DEC_FLAG_LAVSPLITTER) && (pmt->subtype == MEDIASUBTYPE_H264 || pmt->subtype == MEDIASUBTYPE_h264 || pmt->subtype == MEDIASUBTYPE_X264 || pmt->subtype == MEDIASUBTYPE_x264 || pmt->subtype == MEDIASUBTYPE_H264_bis || pmt->subtype == MEDIASUBTYPE_HEVC || pmt->subtype == MEDIASUBTYPE_H265))) { m_pParser = av_parser_init(codec); } LONG biRealWidth = pBMI->biWidth, biRealHeight = pBMI->biHeight; if (pmt->formattype == FORMAT_VideoInfo || pmt->formattype == FORMAT_MPEGVideo) { VIDEOINFOHEADER *vih = (VIDEOINFOHEADER *)pmt->Format(); if (vih->rcTarget.right != 0 && vih->rcTarget.bottom != 0) { biRealWidth = vih->rcTarget.right; biRealHeight = vih->rcTarget.bottom; } } else if (pmt->formattype == FORMAT_VideoInfo2 || pmt->formattype == FORMAT_MPEG2Video) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)pmt->Format(); if (vih2->rcTarget.right != 0 && vih2->rcTarget.bottom != 0) { biRealWidth = vih2->rcTarget.right; biRealHeight = vih2->rcTarget.bottom; } } m_pAVCtx->codec_id = codec; m_pAVCtx->codec_tag = pBMI->biCompression; m_pAVCtx->coded_width = pBMI->biWidth; m_pAVCtx->coded_height = abs(pBMI->biHeight); m_pAVCtx->bits_per_coded_sample = pBMI->biBitCount; m_pAVCtx->err_recognition = 0; m_pAVCtx->workaround_bugs = FF_BUG_AUTODETECT; // Setup threading // Thread Count. 0 = auto detect int thread_count = m_pSettings->GetNumThreads(); if (thread_count == 0) { thread_count = av_cpu_count(); } m_pAVCtx->thread_count = max(1, min(thread_count, AVCODEC_MAX_THREADS)); if (dwDecFlags & LAV_VIDEO_DEC_FLAG_NO_MT || codec == AV_CODEC_ID_MPEG4) { m_pAVCtx->thread_count = 1; } m_pFrame = av_frame_alloc(); CheckPointer(m_pFrame, E_POINTER); // Process Extradata size_t extralen = 0; getExtraData(*pmt, nullptr, &extralen); BOOL bH264avc = FALSE; if (pmt->formattype == FORMAT_MPEG2Video && (m_pAVCtx->codec_tag == MAKEFOURCC('a', 'v', 'c', '1') || m_pAVCtx->codec_tag == MAKEFOURCC('A', 'V', 'C', '1') || m_pAVCtx->codec_tag == MAKEFOURCC('C', 'C', 'V', '1'))) { // Reconstruct AVC1 extradata format DbgLog((LOG_TRACE, 10, L"-> Processing AVC1 extradata of %d bytes", extralen)); MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->Format(); extralen += 7; BYTE *extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); extra[0] = 1; extra[1] = (BYTE)mp2vi->dwProfile; extra[2] = 0; extra[3] = (BYTE)mp2vi->dwLevel; extra[4] = (BYTE)(mp2vi->dwFlags ? mp2vi->dwFlags : 4) - 1; // only process extradata if available uint8_t ps_count = 0; if (extralen > 7) { // Actually copy the metadata into our new buffer size_t actual_len; getExtraData(*pmt, extra + 6, &actual_len); // Count the number of SPS/PPS in them and set the length // We'll put them all into one block and add a second block with 0 elements afterwards // The parsing logic does not care what type they are, it just expects 2 blocks. BYTE *p = extra + 6, *end = extra + 6 + actual_len; BOOL bSPS = FALSE, bPPS = FALSE; while (p + 1 < end) { unsigned len = (((unsigned)p[0] << 8) | p[1]) + 2; if (p + len > end) { break; } if ((p[2] & 0x1F) == 7) bSPS = TRUE; if ((p[2] & 0x1F) == 8) bPPS = TRUE; ps_count++; p += len; } } extra[5] = ps_count; extra[extralen - 1] = 0; bH264avc = TRUE; m_pAVCtx->extradata = extra; m_pAVCtx->extradata_size = (int)extralen; } else if (extralen > 0) { DbgLog((LOG_TRACE, 10, L"-> Processing extradata of %d bytes", extralen)); BYTE *extra = nullptr; if (pmt->subtype == MEDIASUBTYPE_LAV_RAWVIDEO) { if (extralen < sizeof(m_pAVCtx->pix_fmt)) { DbgLog((LOG_TRACE, 10, L"-> LAV RAW Video extradata is missing..")); } else { extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData(*pmt, extra, nullptr); m_pAVCtx->pix_fmt = *(AVPixelFormat *)extra; extralen -= sizeof(AVPixelFormat); memmove(extra, extra + sizeof(AVPixelFormat), extralen); } } else if (codec == AV_CODEC_ID_VP9) { // read custom vpcC headers if (extralen >= 16) { extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData(*pmt, extra, nullptr); if (AV_RB32(extra) == MKBETAG('v', 'p', 'c', 'C') && AV_RB8(extra + 4) == 1) { m_pAVCtx->profile = AV_RB8(extra + 8); m_pAVCtx->color_primaries = (AVColorPrimaries)AV_RB8(extra + 11); m_pAVCtx->color_trc = (AVColorTransferCharacteristic)AV_RB8(extra + 12); m_pAVCtx->colorspace = (AVColorSpace)AV_RB8(extra + 13); int bitdepth = AV_RB8(extra + 10) >> 4; if (m_pAVCtx->profile == 2 && bitdepth == 10) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P10; } else if (m_pAVCtx->profile == 2 && bitdepth == 12) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P12; } } av_freep(&extra); extralen = 0; } } else if (codec == AV_CODEC_ID_AV1) { extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData(*pmt, extra, nullptr); // ISOBMFF start marker, invalid in OBU syntax if (extralen >= 4 && extra[0] == 0x81) { CByteParser av1(extra, extralen); av1.BitSkip(8); m_pAVCtx->profile = av1.BitRead(3); av1.BitSkip(5); // level idx av1.BitSkip(1); // tier int high_bitdepth = av1.BitRead(1); int twelve_bit = av1.BitRead(1); int monochrome = av1.BitRead(1); int chroma_x = av1.BitRead(1); int chroma_y = av1.BitRead(1); av1.BitSkip(2); // chroma sample position // determine pixel format if (m_pAVCtx->profile == AV_PROFILE_AV1_MAIN) { if (!monochrome) { if (chroma_x && chroma_y) { if (!high_bitdepth) m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P; else if (!twelve_bit) m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P10; else m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P12; } else if (chroma_x && !chroma_y) { if (!high_bitdepth) m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P; else if (!twelve_bit) m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P10; else m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P12; } else if (!chroma_x && !chroma_y) { if (!high_bitdepth) m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV444P; else if (!twelve_bit) m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV444P10; else m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV444P12; } } else { if (!high_bitdepth) m_pAVCtx->pix_fmt = AV_PIX_FMT_GRAY8; else if (!twelve_bit) m_pAVCtx->pix_fmt = AV_PIX_FMT_GRAY10; else m_pAVCtx->pix_fmt = AV_PIX_FMT_GRAY12; } } } } else { // Just copy extradata for other formats extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData(*pmt, extra, nullptr); } // Hack to discard invalid MP4 metadata with AnnexB style video if (codec == AV_CODEC_ID_H264 && !bH264avc && extra && extra[0] == 1) { av_freep(&extra); extralen = 0; } m_pAVCtx->extradata = extra; m_pAVCtx->extradata_size = (int)extralen; } else { if (codec == AV_CODEC_ID_VP6 || codec == AV_CODEC_ID_VP6A || codec == AV_CODEC_ID_VP6F) { int cropH = pBMI->biWidth - biRealWidth; int cropV = pBMI->biHeight - biRealHeight; if (cropH >= 0 && cropH <= 0x0f && cropV >= 0 && cropV <= 0x0f) { m_pAVCtx->extradata = (uint8_t *)av_mallocz(1 + AV_INPUT_BUFFER_PADDING_SIZE); m_pAVCtx->extradata_size = 1; m_pAVCtx->extradata[0] = (cropH << 4) | cropV; } } } m_CurrentThread = 0; m_rtStartCache = AV_NOPTS_VALUE; LAVPinInfo lavPinInfo = {0}; BOOL bLAVInfoValid = SUCCEEDED(m_pCallback->GetLAVPinInfo(lavPinInfo)); m_bInputPadded = (dwDecFlags & LAV_VIDEO_DEC_FLAG_LAVSPLITTER); // Setup codec-specific timing logic // MPEG-4 with VideoInfo/2 is from AVI, and only DTS if (codec == AV_CODEC_ID_MPEG4 && pmt->formattype != FORMAT_MPEG2Video) dwDecFlags |= LAV_VIDEO_DEC_FLAG_ONLY_DTS; // RealVideo is only DTS if (codec == AV_CODEC_ID_RV10 || codec == AV_CODEC_ID_RV20 || codec == AV_CODEC_ID_RV30 || codec == AV_CODEC_ID_RV40) dwDecFlags |= LAV_VIDEO_DEC_FLAG_ONLY_DTS; // H.264 without B frames should use reordering for proper delay handling if (codec == AV_CODEC_ID_H264 && bLAVInfoValid && lavPinInfo.has_b_frames == 0) { dwDecFlags &= ~LAV_VIDEO_DEC_FLAG_ONLY_DTS; } // Use ffmpegs logic to reorder timestamps // This is required for all codecs which use frame re-ordering or frame-threaded decoding (unless they specifically // use DTS timestamps, ie. H264 in AVI) m_bFFReordering = !(dwDecFlags & LAV_VIDEO_DEC_FLAG_ONLY_DTS) && (m_pAVCodec->capabilities & (AV_CODEC_CAP_DELAY | AV_CODEC_CAP_FRAME_THREADS)); // Stop time is unreliable, drop it and calculate it m_bCalculateStopTime = (codec == AV_CODEC_ID_H264 || codec == AV_CODEC_ID_DIRAC || (codec == AV_CODEC_ID_MPEG4 && pmt->formattype == FORMAT_MPEG2Video) || (codec == AV_CODEC_ID_VC1 && !(dwDecFlags & LAV_VIDEO_DEC_FLAG_ONLY_DTS))); // Real Video content has some odd timestamps // LAV Splitter does them allright with RV30/RV40, everything else screws them up m_bRVDropBFrameTimings = (codec == AV_CODEC_ID_RV10 || codec == AV_CODEC_ID_RV20 || ((codec == AV_CODEC_ID_RV30 || codec == AV_CODEC_ID_RV40) && (!(dwDecFlags & LAV_VIDEO_DEC_FLAG_LAVSPLITTER) || (bLAVInfoValid && (lavPinInfo.flags & LAV_STREAM_FLAG_RV34_MKV))))); // Enable B-Frame delay handling m_bBFrameDelay = !m_bFFReordering && !m_bRVDropBFrameTimings; m_bWaitingForKeyFrame = TRUE; m_bResumeAtKeyFrame = codec == AV_CODEC_ID_MPEG2VIDEO || codec == AV_CODEC_ID_VC1 || codec == AV_CODEC_ID_VC1IMAGE || codec == AV_CODEC_ID_WMV3 || codec == AV_CODEC_ID_WMV3IMAGE || codec == AV_CODEC_ID_RV30 || codec == AV_CODEC_ID_RV40 || codec == AV_CODEC_ID_VP3 || codec == AV_CODEC_ID_THEORA || codec == AV_CODEC_ID_MPEG4; m_bHasPalette = m_pAVCtx->bits_per_coded_sample <= 8 && m_pAVCtx->extradata_size && !(dwDecFlags & LAV_VIDEO_DEC_FLAG_LAVSPLITTER) && (codec == AV_CODEC_ID_MSVIDEO1 || codec == AV_CODEC_ID_MSRLE || codec == AV_CODEC_ID_CINEPAK || codec == AV_CODEC_ID_8BPS || codec == AV_CODEC_ID_QPEG || codec == AV_CODEC_ID_QTRLE || codec == AV_CODEC_ID_TSCC); if (FAILED(AdditionaDecoderInit())) { return E_FAIL; } if (bLAVInfoValid) { // Use strict decoding with LAV Splitter and non-live sources if (codec == AV_CODEC_ID_H264 && !(dwDecFlags & LAV_VIDEO_DEC_FLAG_LIVE) && m_bFFReordering && !m_pAVCtx->hwaccel_context) { m_pAVCtx->strict_std_compliance = FF_COMPLIANCE_STRICT; } // Try to set the has_b_frames info if available else if (lavPinInfo.has_b_frames >= 0) { DbgLog((LOG_TRACE, 10, L"-> Setting has_b_frames to %d", lavPinInfo.has_b_frames)); m_pAVCtx->has_b_frames = lavPinInfo.has_b_frames; // Set H264 to at least 2 B-Frames, which is the most common for broadcasts if (codec == AV_CODEC_ID_H264 && m_pAVCtx->has_b_frames == 1) m_pAVCtx->has_b_frames = 2; } } // side data if (pSideData && pSideData->side_data_elems > 0) { m_pAVCtx->coded_side_data =(AVPacketSideData *)av_calloc(pSideData->side_data_elems, sizeof(*pSideData->side_data)); if (m_pAVCtx->coded_side_data == nullptr) return E_OUTOFMEMORY; for (int i = 0; i < pSideData->side_data_elems; i++) { const AVPacketSideData *src_sd = &pSideData->side_data[i]; AVPacketSideData *dst_sd = &m_pAVCtx->coded_side_data[i]; dst_sd->data = (uint8_t *)av_memdup(src_sd->data, src_sd->size); if (!dst_sd->data) return E_OUTOFMEMORY; dst_sd->type = src_sd->type; dst_sd->size = src_sd->size; m_pAVCtx->nb_coded_side_data++; } } // codec-specific options AVDictionary *options = nullptr; // workaround for old/broken x264 streams int nX264Build = m_pCallback->GetX264Build(); if (codec == AV_CODEC_ID_H264 && nX264Build != -1) { av_dict_set_int(&options, "x264_build", nX264Build, 0); } // Open the decoder m_bInInit = TRUE; int ret = avcodec_open2(m_pAVCtx, m_pAVCodec, &options); m_bInInit = FALSE; // the dict now contains all options that could not be applied if (options) { av_dict_free(&options); } if (ret >= 0) { DbgLog((LOG_TRACE, 10, L"-> ffmpeg codec opened successfully (ret: %d)", ret)); m_nCodecId = codec; } else { DbgLog((LOG_TRACE, 10, L"-> ffmpeg codec failed to open (ret: %d)", ret)); DestroyDecoder(); return VFW_E_UNSUPPORTED_VIDEO; } m_iInterlaced = 0; for (int i = 0; i < countof(ff_interlace_capable); i++) { if (codec == ff_interlace_capable[i]) { m_iInterlaced = -1; break; } } // Detect chroma and interlaced if (m_pAVCtx->extradata && m_pAVCtx->extradata_size) { if (codec == AV_CODEC_ID_MPEG2VIDEO) { CMPEG2HeaderParser mpeg2Parser(m_pAVCtx->extradata, m_pAVCtx->extradata_size); if (mpeg2Parser.hdr.valid) { if (mpeg2Parser.hdr.chroma < 2) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P; } else if (mpeg2Parser.hdr.chroma == 2) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P; } m_iInterlaced = mpeg2Parser.hdr.interlaced; } } else if (codec == AV_CODEC_ID_H264) { CH264SequenceParser h264parser; if (bH264avc) h264parser.ParseNALs(m_pAVCtx->extradata + 6, m_pAVCtx->extradata_size - 6, 2); else h264parser.ParseNALs(m_pAVCtx->extradata, m_pAVCtx->extradata_size, 0); if (h264parser.sps.valid) m_iInterlaced = h264parser.sps.interlaced; } else if (codec == AV_CODEC_ID_VC1) { CVC1HeaderParser vc1parser(m_pAVCtx->extradata, m_pAVCtx->extradata_size); if (vc1parser.hdr.valid) m_iInterlaced = (vc1parser.hdr.interlaced ? -1 : 0); } } if (codec == AV_CODEC_ID_DNXHD) m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P10; else if (codec == AV_CODEC_ID_FRAPS) m_pAVCtx->pix_fmt = AV_PIX_FMT_BGR24; if (bLAVInfoValid && lavPinInfo.pix_fmt != AV_PIX_FMT_NONE && codec != AV_CODEC_ID_FRAPS) { if (m_pAVCtx->pix_fmt != AV_PIX_FMT_DXVA2_VLD && m_pAVCtx->pix_fmt != AV_PIX_FMT_D3D11) m_pAVCtx->pix_fmt = lavPinInfo.pix_fmt; if (m_pAVCtx->sw_pix_fmt == AV_PIX_FMT_NONE) m_pAVCtx->sw_pix_fmt = lavPinInfo.pix_fmt; } // Ensure software pixfmt is set, so hardware accels can use it immediately if (m_pAVCtx->sw_pix_fmt == AV_PIX_FMT_NONE && m_pAVCtx->pix_fmt != AV_PIX_FMT_DXVA2_VLD && m_pAVCtx->pix_fmt != AV_PIX_FMT_D3D11) m_pAVCtx->sw_pix_fmt = m_pAVCtx->pix_fmt; DbgLog((LOG_TRACE, 10, L"AVCodec init successfull. interlaced: %d", m_iInterlaced)); return S_OK; } STDMETHODIMP CDecAvcodec::DestroyDecoder() { m_pAVCodec = nullptr; if (m_pParser) { av_parser_close(m_pParser); m_pParser = nullptr; } if (m_pAVCtx) { if (m_pAVCtx->codec_id == AV_CODEC_ID_H264) { int64_t x264build = -1; if (av_opt_get_int(m_pAVCtx->priv_data, "x264_build", 0, &x264build) >= 0) m_pCallback->SetX264Build((int)x264build); } av_freep(&m_pAVCtx->hwaccel_context); av_freep(&m_pAVCtx->extradata); avcodec_free_context(&m_pAVCtx); } av_frame_free(&m_pFrame); av_freep(&m_pFFBuffer); m_nFFBufferSize = 0; if (m_pSwsContext) { sws_freeContext(m_pSwsContext); m_pSwsContext = nullptr; } m_nCodecId = AV_CODEC_ID_NONE; return S_OK; } static void lav_avframe_free(LAVFrame *frame) { ASSERT(frame->priv_data); av_frame_free((AVFrame **)&frame->priv_data); } static void avpacket_mediasample_free(void *opaque, uint8_t *buffer) { IMediaSample *pSample = (IMediaSample *)opaque; SafeRelease(&pSample); } STDMETHODIMP CDecAvcodec::FillAVPacketData(AVPacket *avpkt, const uint8_t *buffer, int buflen, IMediaSample *pSample, bool bRefCounting) { if (m_bInputPadded && (m_pParser == nullptr)) { avpkt->data = (uint8_t *)buffer; avpkt->size = buflen; if (pSample && bRefCounting && m_pCallback->HasDynamicInputAllocator()) { avpkt->buf = av_buffer_create(avpkt->data, avpkt->size, avpacket_mediasample_free, pSample, AV_BUFFER_FLAG_READONLY); if (!avpkt->buf) { return E_OUTOFMEMORY; } pSample->AddRef(); } } else { // create fresh packet if (av_new_packet(avpkt, buflen) < 0) return E_OUTOFMEMORY; // copy data over memcpy(avpkt->data, buffer, buflen); } // copy side-data from input sample if (pSample) { IMediaSideData *pSideData = nullptr; if (SUCCEEDED(pSample->QueryInterface(&pSideData))) { size_t nFFSideDataSize = 0; const MediaSideDataFFMpeg *pFFSideData = nullptr; if (FAILED( pSideData->GetSideData(IID_MediaSideDataFFMpeg, (const BYTE **)&pFFSideData, &nFFSideDataSize)) || nFFSideDataSize != sizeof(MediaSideDataFFMpeg)) { pFFSideData = nullptr; } SafeRelease(&pSideData); CopyMediaSideDataFF(avpkt, &pFFSideData); } } return S_OK; } STDMETHODIMP CDecAvcodec::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample) { CheckPointer(m_pAVCtx, E_UNEXPECTED); // Put timestamps into the buffers if appropriate if (m_pAVCtx->active_thread_type & FF_THREAD_FRAME) { if (!m_bFFReordering) { m_tcThreadBuffer[m_CurrentThread].rtStart = rtStartIn; m_tcThreadBuffer[m_CurrentThread].rtStop = rtStopIn; } m_CurrentThread = (m_CurrentThread + 1) % m_pAVCtx->thread_count; } else if (m_bBFrameDelay) { m_tcBFrameDelay[m_nBFramePos].rtStart = rtStartIn; m_tcBFrameDelay[m_nBFramePos].rtStop = rtStopIn; m_nBFramePos = !m_nBFramePos; } // if we have a parser, it'll handle calling the decode function if (m_pParser) { return ParsePacket(buffer, buflen, rtStartIn, rtStopIn, pSample); } else { // Flush the decoder if appropriate if (buffer == nullptr) { return DecodePacket(nullptr, AV_NOPTS_VALUE, AV_NOPTS_VALUE); } // build an AVPacket AVPacket *avpkt = av_packet_alloc(); // set data pointers if (FAILED(FillAVPacketData(avpkt, buffer, buflen, pSample, true))) { return E_OUTOFMEMORY; } // timestamps avpkt->pts = rtStartIn; if (rtStartIn != AV_NOPTS_VALUE && rtStopIn != AV_NOPTS_VALUE) avpkt->duration = (int)(rtStopIn - rtStartIn); // flags avpkt->flags = bSyncPoint ? AV_PKT_FLAG_KEY : 0; // perform decoding HRESULT hr = DecodePacket(avpkt, rtStartIn, rtStopIn); // free packet after av_packet_free(&avpkt); // forward decoding failures, should only happen when a hardware decoder fails if (FAILED(hr)) { return hr; } } return S_OK; } STDMETHODIMP CDecAvcodec::ParsePacket(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, IMediaSample *pSample) { BOOL bFlush = (buffer == NULL); int used_bytes = 0; uint8_t *pDataBuffer = (uint8_t *)buffer; HRESULT hr = S_OK; // re-allocate with padding, if needed if (m_bInputPadded == false && buflen > 0) { // re-allocate buffer to have enough space BYTE *pBuf = (BYTE *)av_fast_realloc(m_pFFBuffer, &m_nFFBufferSize, buflen + AV_INPUT_BUFFER_PADDING_SIZE); if (!pBuf) return E_FAIL; m_pFFBuffer = pBuf; // copy data to buffer memcpy(m_pFFBuffer, buffer, buflen); memset(m_pFFBuffer + buflen, 0, AV_INPUT_BUFFER_PADDING_SIZE); pDataBuffer = m_pFFBuffer; } // loop over the data buffer until the parser has consumed all data while (buflen > 0 || bFlush) { REFERENCE_TIME rtStart = rtStartIn, rtStop = rtStopIn; uint8_t *pOutBuffer = nullptr; int pOutLen = 0; used_bytes = av_parser_parse2(m_pParser, m_pAVCtx, &pOutBuffer, &pOutLen, pDataBuffer, buflen, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (used_bytes == 0 && pOutLen == 0 && !bFlush) { DbgLog((LOG_TRACE, 50, L"::Decode() - could not process buffer, starving?")); break; } else if (used_bytes > 0) { buflen -= used_bytes; pDataBuffer += used_bytes; } // Update start time cache // If more data was read then output, update the cache (incomplete frame) // If output is bigger, a frame was completed, update the actual rtStart with the cached value, and then // overwrite the cache if (used_bytes > pOutLen) { if (rtStartIn != AV_NOPTS_VALUE) m_rtStartCache = rtStartIn; } else if (used_bytes == pOutLen || ((used_bytes + 9) == pOutLen)) { // Why +9 above? // Well, apparently there are some broken MKV muxers that like to mux the MPEG-2 PICTURE_START_CODE block // (which is 9 bytes) in the package with the previous frame This would cause the frame timestamps to be // delayed by one frame exactly, and cause timestamp reordering to go wrong. So instead of failing on those // samples, lets just assume that 9 bytes are that case exactly. m_rtStartCache = rtStartIn = AV_NOPTS_VALUE; } else if (pOutLen > used_bytes) { rtStart = m_rtStartCache; m_rtStartCache = rtStartIn; // The value was used once, don't use it for multiple frames, that ends up in weird timings rtStartIn = AV_NOPTS_VALUE; } // decode any parsed data if (pOutLen > 0) { AVPacket *avpkt = av_packet_alloc(); // set data pointers if (FAILED(FillAVPacketData(avpkt, pOutBuffer, pOutLen, pSample, false))) { return E_OUTOFMEMORY; } // timestamp avpkt->pts = rtStart; // decode the parsed packet hr = DecodePacket(avpkt, rtStart, rtStop); // and free it after av_packet_free(&avpkt); if (FAILED(hr)) { return hr; } } // or perform a flush at the end else if (bFlush) { hr = DecodePacket(nullptr, AV_NOPTS_VALUE, AV_NOPTS_VALUE); if (FAILED(hr)) { return hr; } break; } } return S_OK; } STDMETHODIMP CDecAvcodec::DecodePacket(AVPacket *avpkt, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn) { int ret = 0; BOOL bEndOfSequence = FALSE; BOOL bDeliverFirst = FALSE; REFERENCE_TIME rtStart = rtStartIn, rtStop = rtStopIn; // packet pre-processing if (avpkt) { // EOS/GOP detection for mpeg2 video streams if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) { int state = CheckForSequenceMarkers(m_nCodecId, avpkt->data, avpkt->size, &m_MpegParserState); if (state & STATE_EOS_FOUND) { bEndOfSequence = TRUE; } if (state & STATE_GOP_FOUND && m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) { m_bWaitingForKeyFrame = FALSE; } } // Check for VP8 keyframes if (m_nCodecId == AV_CODEC_ID_VP8 && m_bWaitingForKeyFrame) { if (!(avpkt->data[0] & 1)) { DbgLog((LOG_TRACE, 10, L"::Decode(): Found VP8 key-frame, resuming decoding")); m_bWaitingForKeyFrame = FALSE; } else { return S_OK; } } else if (m_nCodecId == AV_CODEC_ID_VP9 && m_bWaitingForKeyFrame) { CByteParser VP9Header(avpkt->data, avpkt->size); // check vp9 frame marker if (VP9Header.BitRead(2) != 0x2) return E_FAIL; int profile = VP9Header.BitRead(1) | (VP9Header.BitRead(1) << 1); if (profile == 3) profile += VP9Header.BitRead(1); if (VP9Header.BitRead(1) == 0 && VP9Header.BitRead(1) == 0) { DbgLog((LOG_TRACE, 10, L"::Decode(): Found VP9 key-frame, resuming decoding")); m_bWaitingForKeyFrame = FALSE; } else { return S_OK; } } // Add a palette from extradata, if any if (m_bHasPalette) { m_bHasPalette = FALSE; uint32_t *pal = (uint32_t *)av_packet_new_side_data(avpkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); int pal_size = FFMIN((1 << m_pAVCtx->bits_per_coded_sample) << 2, m_pAVCtx->extradata_size); uint8_t *pal_src = m_pAVCtx->extradata + m_pAVCtx->extradata_size - pal_size; for (int i = 0; i < pal_size / 4; i++) pal[i] = 0xFF << 24 | AV_RL32(pal_src + 4 * i); } } send_packet: // send packet to the decoder ret = avcodec_send_packet(m_pAVCtx, avpkt); if (ret < 0) { // Check if post-decoding checks failed if (FAILED(PostDecode())) { return E_FAIL; } if (ret == AVERROR(EAGAIN)) { if (bDeliverFirst) { DbgLog((LOG_ERROR, 10, L"::Decode(): repeated packet submission to the decoder failed")); ASSERT(0); return E_FAIL; } bDeliverFirst = TRUE; } else return S_FALSE; } else { bDeliverFirst = FALSE; } // loop over available frames while (1) { ret = avcodec_receive_frame(m_pAVCtx, m_pFrame); if (FAILED(PostDecode())) { av_frame_unref(m_pFrame); return E_FAIL; } // Decoding of this frame failed ... oh well! if (ret < 0 && ret != AVERROR(EAGAIN)) { av_frame_unref(m_pFrame); return S_FALSE; } // Judge frame usability // This determines if a frame is artifact free and can be delivered. if (m_bResumeAtKeyFrame && m_bWaitingForKeyFrame && ret >= 0) { if (m_pFrame->flags & AV_FRAME_FLAG_KEY) { DbgLog((LOG_TRACE, 50, L"::Decode() - Found Key-Frame, resuming decoding at %I64d", m_pFrame->pts)); m_bWaitingForKeyFrame = FALSE; } else { ret = AVERROR(EAGAIN); } } // Handle B-frame delay for frame threading codecs if ((m_pAVCtx->active_thread_type & FF_THREAD_FRAME) && m_bBFrameDelay) { m_tcBFrameDelay[m_nBFramePos] = m_tcThreadBuffer[m_CurrentThread]; m_nBFramePos = !m_nBFramePos; } // no frame was decoded, bail out here if (ret < 0 || !m_pFrame->data[0]) { av_frame_unref(m_pFrame); break; } /////////////////////////////////////////////////////////////////////////////////////////////// // Determine the proper timestamps for the frame, based on different possible flags. /////////////////////////////////////////////////////////////////////////////////////////////// if (m_bFFReordering) { rtStart = m_pFrame->pts; if (m_pFrame->duration) rtStop = m_pFrame->pts + m_pFrame->duration; else rtStop = AV_NOPTS_VALUE; } else if (m_bBFrameDelay && m_pAVCtx->has_b_frames) { rtStart = m_tcBFrameDelay[m_nBFramePos].rtStart; rtStop = m_tcBFrameDelay[m_nBFramePos].rtStop; } else if (m_pAVCtx->active_thread_type & FF_THREAD_FRAME) { unsigned index = m_CurrentThread; rtStart = m_tcThreadBuffer[index].rtStart; rtStop = m_tcThreadBuffer[index].rtStop; } if (m_bRVDropBFrameTimings && m_pFrame->pict_type == AV_PICTURE_TYPE_B) { rtStart = AV_NOPTS_VALUE; } if (m_bCalculateStopTime) rtStop = AV_NOPTS_VALUE; /////////////////////////////////////////////////////////////////////////////////////////////// // All required values collected, deliver the frame /////////////////////////////////////////////////////////////////////////////////////////////// LAVFrame *pOutFrame = nullptr; AllocateFrame(&pOutFrame); AVRational display_aspect_ratio; int64_t num = (int64_t)m_pFrame->sample_aspect_ratio.num * m_pFrame->width; int64_t den = (int64_t)m_pFrame->sample_aspect_ratio.den * m_pFrame->height; av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den, num, den, INT_MAX); pOutFrame->width = m_pFrame->width; pOutFrame->height = m_pFrame->height; pOutFrame->aspect_ratio = display_aspect_ratio; pOutFrame->repeat = m_pFrame->repeat_pict; pOutFrame->key_frame = !!(m_pFrame->flags & AV_FRAME_FLAG_KEY); pOutFrame->frame_type = av_get_picture_type_char(m_pFrame->pict_type); pOutFrame->ext_format = GetDXVA2ExtendedFlags(m_pFrame); if ((m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) && m_pFrame->repeat_pict) m_nSoftTelecine = 2; else if (m_nSoftTelecine > 0) m_nSoftTelecine--; if ((m_pFrame->flags & AV_FRAME_FLAG_INTERLACED) || (!m_pAVCtx->progressive_sequence && (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO))) { if (!m_nSoftTelecine) m_iInterlaced = 1; } else if (m_pAVCtx->progressive_sequence) m_iInterlaced = 0; // Don't apply aggressive deinterlacing to content that looks soft-telecined, as it would destroy the content bool bAggressiveFlag = (m_iInterlaced == 1 && m_pSettings->GetDeinterlacingMode() == DeintMode_Aggressive) && !m_nSoftTelecine; pOutFrame->interlaced = ((m_pFrame->flags & AV_FRAME_FLAG_INTERLACED) || bAggressiveFlag || m_pSettings->GetDeinterlacingMode() == DeintMode_Force) && !(m_pSettings->GetDeinterlacingMode() == DeintMode_Disable); LAVDeintFieldOrder fo = m_pSettings->GetDeintFieldOrder(); pOutFrame->tff = (fo == DeintFieldOrder_Auto) ? !!(m_pFrame->flags & AV_FRAME_FLAG_TOP_FIELD_FIRST) : (fo == DeintFieldOrder_TopFieldFirst); pOutFrame->rtStart = rtStart; pOutFrame->rtStop = rtStop; PixelFormatMapping map = getPixFmtMapping((AVPixelFormat)m_pFrame->format); pOutFrame->format = map.lavpixfmt; pOutFrame->sw_format = pOutFrame->format; pOutFrame->bpp = map.bpp; if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_MPEG1VIDEO) pOutFrame->avgFrameDuration = GetFrameDuration(); AVFrameSideData *sdHDR = av_frame_get_side_data(m_pFrame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA); if (sdHDR) { if (sdHDR->size == sizeof(AVMasteringDisplayMetadata)) { AVMasteringDisplayMetadata *metadata = (AVMasteringDisplayMetadata *)sdHDR->data; MediaSideDataHDR *hdr = (MediaSideDataHDR *)AddLAVFrameSideData(pOutFrame, IID_MediaSideDataHDR, sizeof(MediaSideDataHDR)); processFFHDRData(hdr, metadata); } else { DbgLog((LOG_TRACE, 10, L"::Decode(): Found HDR data of an unexpected size (%d)", sdHDR->size)); } } AVFrameSideData *sdHDRContentLightLevel = av_frame_get_side_data(m_pFrame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL); if (sdHDRContentLightLevel) { if (sdHDRContentLightLevel->size == sizeof(AVContentLightMetadata)) { AVContentLightMetadata *metadata = (AVContentLightMetadata *)sdHDRContentLightLevel->data; MediaSideDataHDRContentLightLevel *hdr = (MediaSideDataHDRContentLightLevel *)AddLAVFrameSideData( pOutFrame, IID_MediaSideDataHDRContentLightLevel, sizeof(MediaSideDataHDRContentLightLevel)); hdr->MaxCLL = metadata->MaxCLL; hdr->MaxFALL = metadata->MaxFALL; } else { DbgLog((LOG_TRACE, 10, L"::Decode(): Found HDR Light Level data of an unexpected size (%d)", sdHDRContentLightLevel->size)); } } AVFrameSideData *sdHDR10Plus = av_frame_get_side_data(m_pFrame, AV_FRAME_DATA_DYNAMIC_HDR_PLUS); if (sdHDR10Plus) { if (sdHDR10Plus->size == sizeof(AVDynamicHDRPlus)) { AVDynamicHDRPlus *metadata = (AVDynamicHDRPlus *)sdHDR10Plus->data; MediaSideDataHDR10Plus *hdr = (MediaSideDataHDR10Plus *)AddLAVFrameSideData( pOutFrame, IID_MediaSideDataHDR10Plus, sizeof(MediaSideDataHDR10Plus)); processFFHDR10PlusData(hdr, metadata, m_pFrame->width, m_pFrame->height); } else { DbgLog((LOG_TRACE, 10, L"::Decode(): Found HDR10+ data of an unexpected size (%d)", sdHDR10Plus->size)); } } AVFrameSideData *sdDOVI = av_frame_get_side_data(m_pFrame, AV_FRAME_DATA_DOVI_METADATA); if (sdDOVI) { AVDOVIMetadata *metadata = (AVDOVIMetadata *)sdDOVI->data; MediaSideDataDOVIMetadata *hdr = (MediaSideDataDOVIMetadata *)AddLAVFrameSideData( pOutFrame, IID_MediaSideDataDOVIMetadataV2, sizeof(MediaSideDataDOVIMetadata)); processFFDOVIData(hdr, metadata); #pragma warning(push) #pragma warning(disable: 4996) // legacy format without extensions BYTE *hdrLegacy = (BYTE *)AddLAVFrameSideData( pOutFrame, IID_MediaSideDataDOVIMetadata, offsetof(MediaSideDataDOVIMetadata, Extensions)); memcpy(hdrLegacy, hdr, offsetof(MediaSideDataDOVIMetadata, Extensions)); #pragma warning(pop) } AVFrameSideData *sdDOVIRPU = av_frame_get_side_data(m_pFrame, AV_FRAME_DATA_DOVI_RPU_BUFFER); if (sdDOVIRPU) { BYTE *pDVRPU = AddLAVFrameSideData(pOutFrame, IID_MediaSideDataDOVIRPU, sdDOVIRPU->size); memcpy(pDVRPU, sdDOVIRPU->data, sdDOVIRPU->size); } AVFrameSideData *sdCC = av_frame_get_side_data(m_pFrame, AV_FRAME_DATA_A53_CC); if (sdCC) { BYTE *CC = AddLAVFrameSideData(pOutFrame, IID_MediaSideDataEIA608CC, sdCC->size); memcpy(CC, sdCC->data, sdCC->size); } if (map.conversion) { ConvertPixFmt(m_pFrame, pOutFrame); } else { AVFrame *pFrameRef = av_frame_alloc(); av_frame_ref(pFrameRef, m_pFrame); for (int i = 0; i < 4; i++) { pOutFrame->data[i] = pFrameRef->data[i]; pOutFrame->stride[i] = pFrameRef->linesize[i]; } pOutFrame->priv_data = pFrameRef; pOutFrame->destruct = lav_avframe_free; // Check alignment on rawvideo, which can be off depending on the source file if (m_nCodecId == AV_CODEC_ID_RAWVIDEO) { for (int i = 0; i < 4; i++) { if ((intptr_t)pOutFrame->data[i] % 16u || pOutFrame->stride[i] % 16u) { // copy the frame, its not aligned properly and would crash later CopyLAVFrameInPlace(pOutFrame); break; } } } } if (bEndOfSequence) pOutFrame->flags |= LAV_FRAME_FLAG_END_OF_SEQUENCE; if (pOutFrame->format == LAVPixFmt_DXVA2) { pOutFrame->data[0] = m_pFrame->data[4]; HandleDXVA2Frame(pOutFrame); } else if (pOutFrame->format == LAVPixFmt_D3D11) { HandleDXVA2Frame(pOutFrame); } else { Deliver(pOutFrame); } if (bEndOfSequence) { bEndOfSequence = FALSE; if (pOutFrame->format == LAVPixFmt_DXVA2 || pOutFrame->format == LAVPixFmt_D3D11) { HandleDXVA2Frame(m_pCallback->GetFlushFrame()); } else { Deliver(m_pCallback->GetFlushFrame()); } } // increase thread count when flushing if (avpkt == nullptr) { m_CurrentThread = (m_CurrentThread + 1) % m_pAVCtx->thread_count; } av_frame_unref(m_pFrame); } // repeat sending the packet to the decoder if it failed first if (bDeliverFirst) { goto send_packet; } return S_OK; } STDMETHODIMP CDecAvcodec::Flush() { if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) { avcodec_flush_buffers(m_pAVCtx); } if (m_pParser) { av_parser_close(m_pParser); m_pParser = av_parser_init(m_nCodecId); } m_CurrentThread = 0; m_rtStartCache = AV_NOPTS_VALUE; m_bWaitingForKeyFrame = TRUE; m_nSoftTelecine = 0; m_nBFramePos = 0; m_tcBFrameDelay[0].rtStart = m_tcBFrameDelay[0].rtStop = AV_NOPTS_VALUE; m_tcBFrameDelay[1].rtStart = m_tcBFrameDelay[1].rtStop = AV_NOPTS_VALUE; if (!(m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) && (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO)) { CDecAvcodec::InitDecoder(m_nCodecId, &m_pCallback->GetInputMediaType(), nullptr); } return __super::Flush(); } STDMETHODIMP CDecAvcodec::EndOfStream() { Decode(nullptr, 0, AV_NOPTS_VALUE, AV_NOPTS_VALUE, FALSE, FALSE, nullptr); return S_OK; } STDMETHODIMP CDecAvcodec::GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { AVPixelFormat pixfmt = m_pAVCtx ? m_pAVCtx->pix_fmt : AV_PIX_FMT_NONE; PixelFormatMapping mapping = getPixFmtMapping(pixfmt); if (pPix) *pPix = mapping.lavpixfmt; if (pBpp) *pBpp = mapping.bpp; if (pPixSoftware) *pPixSoftware = mapping.lavpixfmt; return S_OK; } STDMETHODIMP CDecAvcodec::ConvertPixFmt(AVFrame *pFrame, LAVFrame *pOutFrame) { // Allocate the buffers to write into HRESULT hr = AllocLAVFrameBuffers(pOutFrame); if (FAILED(hr)) return hr; // Map to swscale compatible format AVPixelFormat dstFormat = getFFPixelFormatFromLAV(pOutFrame->format, pOutFrame->bpp); // Get a context m_pSwsContext = sws_getCachedContext(m_pSwsContext, pFrame->width, pFrame->height, (AVPixelFormat)pFrame->format, pFrame->width, pFrame->height, dstFormat, SWS_BILINEAR | SWS_FULL_CHR_H_INT | SWS_PRINT_INFO, nullptr, nullptr, nullptr); ptrdiff_t linesize[4]; for (int i = 0; i < 4; i++) linesize[i] = pFrame->linesize[i]; // Perform conversion sws_scale2(m_pSwsContext, pFrame->data, linesize, 0, pFrame->height, pOutFrame->data, pOutFrame->stride); return S_OK; } STDMETHODIMP_(REFERENCE_TIME) CDecAvcodec::GetFrameDuration() { if (m_pAVCtx->framerate.den && m_pAVCtx->framerate.num) return (REF_SECOND_MULT * m_pAVCtx->framerate.den / m_pAVCtx->framerate.num); if (m_pAVCtx->time_base.den && m_pAVCtx->time_base.num) return (REF_SECOND_MULT * m_pAVCtx->time_base.num / m_pAVCtx->time_base.den) * ((m_pAVCtx->codec_descriptor && m_pAVCtx->codec_descriptor->props & AV_CODEC_PROP_FIELDS) ? 2 : 1); return 0; } STDMETHODIMP_(BOOL) CDecAvcodec::IsInterlaced(BOOL bAllowGuess) { return (bAllowGuess && m_iInterlaced) || (m_iInterlaced > 0) || m_pSettings->GetDeinterlacingMode() == DeintMode_Force; } ================================================ FILE: decoder/LAVVideo/decoders/avcodec.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DecBase.h" #include #define AVCODEC_MAX_THREADS 32 typedef struct { REFERENCE_TIME rtStart; REFERENCE_TIME rtStop; } TimingCache; class CDecAvcodec : public CDecBase { public: CDecAvcodec(void); virtual ~CDecAvcodec(void); // ILAVDecoder STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware); STDMETHODIMP_(REFERENCE_TIME) GetFrameDuration(); STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess); STDMETHODIMP_(const WCHAR *) GetDecoderName() { return L"avcodec"; } STDMETHODIMP HasThreadSafeBuffers() { return S_OK; } // CDecBase STDMETHODIMP Init(); protected: virtual HRESULT AdditionaDecoderInit() { return S_FALSE; } virtual HRESULT PostDecode() { return S_FALSE; } virtual HRESULT HandleDXVA2Frame(LAVFrame *pFrame) { return S_FALSE; } virtual BOOL IsHardwareAccelerator() { return FALSE; } STDMETHODIMP DestroyDecoder(); STDMETHODIMP FillAVPacketData(AVPacket *avpkt, const BYTE *buffer, int buflen, IMediaSample *pSample, bool bRefCounting); STDMETHODIMP DecodePacket(AVPacket *avpkt, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn); STDMETHODIMP ParsePacket(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, IMediaSample *pSample); private: STDMETHODIMP ConvertPixFmt(AVFrame *pFrame, LAVFrame *pOutFrame); protected: AVCodecContext *m_pAVCtx = nullptr; AVFrame *m_pFrame = nullptr; AVCodecID m_nCodecId = AV_CODEC_ID_NONE; BOOL m_bInInit = FALSE; private: const AVCodec *m_pAVCodec = nullptr; AVCodecParserContext *m_pParser = nullptr; BYTE *m_pFFBuffer = nullptr; unsigned int m_nFFBufferSize = 0; SwsContext *m_pSwsContext = nullptr; BOOL m_bHasPalette = FALSE; // Timing settings BOOL m_bFFReordering = FALSE; BOOL m_bCalculateStopTime = FALSE; BOOL m_bRVDropBFrameTimings = FALSE; BOOL m_bInputPadded = FALSE; BOOL m_bBFrameDelay = TRUE; TimingCache m_tcBFrameDelay[2]; int m_nBFramePos = 0; TimingCache m_tcThreadBuffer[AVCODEC_MAX_THREADS]; int m_CurrentThread = 0; REFERENCE_TIME m_rtStartCache = AV_NOPTS_VALUE; BOOL m_bResumeAtKeyFrame = FALSE; BOOL m_bWaitingForKeyFrame = FALSE; int m_iInterlaced = -1; int m_nSoftTelecine = 0; }; ================================================ FILE: decoder/LAVVideo/decoders/cuvid/dynlink_cuda.h ================================================ /* * Copyright 1993-2015 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ #ifndef __cuda_h__ #define __cuda_h__ /** * CUDA API version support */ #include "dynlink_cuda_cuda.h" #endif //__cuda_h__ ================================================ FILE: decoder/LAVVideo/decoders/cuvid/dynlink_cuda_cuda.h ================================================ /* * Copyright 1993-2015 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ #ifndef __cuda_cuda_h__ #define __cuda_cuda_h__ #include #ifndef __CUDA_API_VERSION #define __CUDA_API_VERSION 4000 #endif /** * \defgroup CUDA_DRIVER CUDA Driver API * * This section describes the low-level CUDA driver application programming * interface. * * @{ */ /** * \defgroup CUDA_TYPES Data types used by CUDA driver * @{ */ /** * CUDA API version number */ #define CUDA_VERSION 4000 /* 4.0 */ #ifdef __cplusplus extern "C" { #endif /** * CUDA device pointer */ #if __CUDA_API_VERSION >= 3020 #if defined(__x86_64) || defined(AMD64) || defined(_M_AMD64) || defined(__aarch64__) typedef unsigned long long CUdeviceptr; #else typedef unsigned int CUdeviceptr; #endif #endif /* __CUDA_API_VERSION >= 3020 */ typedef int CUdevice; /**< CUDA device */ typedef struct CUctx_st *CUcontext; /**< CUDA context */ typedef struct CUmod_st *CUmodule; /**< CUDA module */ typedef struct CUfunc_st *CUfunction; /**< CUDA function */ typedef struct CUarray_st *CUarray; /**< CUDA array */ typedef struct CUtexref_st *CUtexref; /**< CUDA texture reference */ typedef struct CUsurfref_st *CUsurfref; /**< CUDA surface reference */ typedef struct CUevent_st *CUevent; /**< CUDA event */ typedef struct CUstream_st *CUstream; /**< CUDA stream */ typedef struct CUgraphicsResource_st *CUgraphicsResource; /**< CUDA graphics interop resource */ typedef struct CUuuid_st /**< CUDA definition of UUID */ { char bytes[16]; } CUuuid; /** * Context creation flags */ typedef enum CUctx_flags_enum { CU_CTX_SCHED_AUTO = 0x00, /**< Automatic scheduling */ CU_CTX_SCHED_SPIN = 0x01, /**< Set spin as default scheduling */ CU_CTX_SCHED_YIELD = 0x02, /**< Set yield as default scheduling */ CU_CTX_SCHED_BLOCKING_SYNC = 0x04, /**< Set blocking synchronization as default scheduling */ CU_CTX_BLOCKING_SYNC = 0x04, /**< Set blocking synchronization as default scheduling \deprecated */ CU_CTX_MAP_HOST = 0x08, /**< Support mapped pinned allocations */ CU_CTX_LMEM_RESIZE_TO_MAX = 0x10, /**< Keep local memory allocation after launch */ #if __CUDA_API_VERSION < 4000 CU_CTX_SCHED_MASK = 0x03, CU_CTX_FLAGS_MASK = 0x1f #else CU_CTX_SCHED_MASK = 0x07, CU_CTX_PRIMARY = 0x20, /**< Initialize and return the primary context */ CU_CTX_FLAGS_MASK = 0x3f #endif } CUctx_flags; /** * Event creation flags */ typedef enum CUevent_flags_enum { CU_EVENT_DEFAULT = 0, /**< Default event flag */ CU_EVENT_BLOCKING_SYNC = 1, /**< Event uses blocking synchronization */ CU_EVENT_DISABLE_TIMING = 2 /**< Event will not record timing data */ } CUevent_flags; /** * Array formats */ typedef enum CUarray_format_enum { CU_AD_FORMAT_UNSIGNED_INT8 = 0x01, /**< Unsigned 8-bit integers */ CU_AD_FORMAT_UNSIGNED_INT16 = 0x02, /**< Unsigned 16-bit integers */ CU_AD_FORMAT_UNSIGNED_INT32 = 0x03, /**< Unsigned 32-bit integers */ CU_AD_FORMAT_SIGNED_INT8 = 0x08, /**< Signed 8-bit integers */ CU_AD_FORMAT_SIGNED_INT16 = 0x09, /**< Signed 16-bit integers */ CU_AD_FORMAT_SIGNED_INT32 = 0x0a, /**< Signed 32-bit integers */ CU_AD_FORMAT_HALF = 0x10, /**< 16-bit floating point */ CU_AD_FORMAT_FLOAT = 0x20 /**< 32-bit floating point */ } CUarray_format; /** * Texture reference addressing modes */ typedef enum CUaddress_mode_enum { CU_TR_ADDRESS_MODE_WRAP = 0, /**< Wrapping address mode */ CU_TR_ADDRESS_MODE_CLAMP = 1, /**< Clamp to edge address mode */ CU_TR_ADDRESS_MODE_MIRROR = 2, /**< Mirror address mode */ CU_TR_ADDRESS_MODE_BORDER = 3 /**< Border address mode */ } CUaddress_mode; /** * Texture reference filtering modes */ typedef enum CUfilter_mode_enum { CU_TR_FILTER_MODE_POINT = 0, /**< Point filter mode */ CU_TR_FILTER_MODE_LINEAR = 1 /**< Linear filter mode */ } CUfilter_mode; /** * Device properties */ typedef enum CUdevice_attribute_enum { CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1, /**< Maximum number of threads per block */ CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = 2, /**< Maximum block dimension X */ CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = 3, /**< Maximum block dimension Y */ CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = 4, /**< Maximum block dimension Z */ CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 5, /**< Maximum grid dimension X */ CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = 6, /**< Maximum grid dimension Y */ CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = 7, /**< Maximum grid dimension Z */ CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK = 8, /**< Maximum shared memory available per block in bytes */ CU_DEVICE_ATTRIBUTE_SHARED_MEMORY_PER_BLOCK = 8, /**< Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK */ CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY = 9, /**< Memory available on device for __constant__ variables in a CUDA C kernel in bytes */ CU_DEVICE_ATTRIBUTE_WARP_SIZE = 10, /**< Warp size in threads */ CU_DEVICE_ATTRIBUTE_MAX_PITCH = 11, /**< Maximum pitch in bytes allowed by memory copies */ CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK = 12, /**< Maximum number of 32-bit registers available per block */ CU_DEVICE_ATTRIBUTE_REGISTERS_PER_BLOCK = 12, /**< Deprecated, use CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK */ CU_DEVICE_ATTRIBUTE_CLOCK_RATE = 13, /**< Peak clock frequency in kilohertz */ CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT = 14, /**< Alignment requirement for textures */ CU_DEVICE_ATTRIBUTE_GPU_OVERLAP = 15, /**< Device can possibly copy memory and execute a kernel concurrently */ CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16, /**< Number of multiprocessors on device */ CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT = 17, /**< Specifies whether there is a run time limit on kernels */ CU_DEVICE_ATTRIBUTE_INTEGRATED = 18, /**< Device is integrated with host memory */ CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY = 19, /**< Device can map host memory into CUDA address space */ CU_DEVICE_ATTRIBUTE_COMPUTE_MODE = 20, /**< Compute mode (See ::CUcomputemode for details) */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_WIDTH = 21, /**< Maximum 1D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_WIDTH = 22, /**< Maximum 2D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_HEIGHT = 23, /**< Maximum 2D texture height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_WIDTH = 24, /**< Maximum 3D texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_HEIGHT = 25, /**< Maximum 3D texture height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE3D_DEPTH = 26, /**< Maximum 3D texture depth */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_WIDTH = 27, /**< Maximum texture array width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_HEIGHT = 28, /**< Maximum texture array height */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES = 29, /**< Maximum slices in a texture array */ CU_DEVICE_ATTRIBUTE_SURFACE_ALIGNMENT = 30, /**< Alignment requirement for surfaces */ CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS = 31, /**< Device can possibly execute multiple kernels concurrently */ CU_DEVICE_ATTRIBUTE_ECC_ENABLED = 32, /**< Device has ECC support enabled */ CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = 33, /**< PCI bus ID of the device */ CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = 34, /**< PCI device ID of the device */ CU_DEVICE_ATTRIBUTE_TCC_DRIVER = 35 /**< Device is using TCC driver model */ #if __CUDA_API_VERSION >= 4000 , CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE = 36, /**< Peak memory clock frequency in kilohertz */ CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH = 37, /**< Global memory bus width in bits */ CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE = 38, /**< Size of L2 cache in bytes */ CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR = 39, /**< Maximum resident threads per multiprocessor */ CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT = 40, /**< Number of asynchronous engines */ CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING = 41, /**< Device uses shares a unified address space with the host */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_WIDTH = 42, /**< Maximum 1D layered texture width */ CU_DEVICE_ATTRIBUTE_MAXIMUM_TEXTURE1D_LAYERED_LAYERS = 43 /**< Maximum layers in a 1D layered texture */ #endif } CUdevice_attribute; /** * Legacy device properties */ typedef struct CUdevprop_st { int maxThreadsPerBlock; /**< Maximum number of threads per block */ int maxThreadsDim[3]; /**< Maximum size of each dimension of a block */ int maxGridSize[3]; /**< Maximum size of each dimension of a grid */ int sharedMemPerBlock; /**< Shared memory available per block in bytes */ int totalConstantMemory; /**< Constant memory available on device in bytes */ int SIMDWidth; /**< Warp size in threads */ int memPitch; /**< Maximum pitch in bytes allowed by memory copies */ int regsPerBlock; /**< 32-bit registers available per block */ int clockRate; /**< Clock frequency in kilohertz */ int textureAlign; /**< Alignment requirement for textures */ } CUdevprop; /** * Function properties */ typedef enum CUfunction_attribute_enum { /** * The maximum number of threads per block, beyond which a launch of the * function would fail. This number depends on both the function and the * device on which the function is currently loaded. */ CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 0, /** * The size in bytes of statically-allocated shared memory required by * this function. This does not include dynamically-allocated shared * memory requested by the user at runtime. */ CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = 1, /** * The size in bytes of user-allocated constant memory required by this * function. */ CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = 2, /** * The size in bytes of local memory used by each thread of this function. */ CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = 3, /** * The number of registers used by each thread of this function. */ CU_FUNC_ATTRIBUTE_NUM_REGS = 4, /** * The PTX virtual architecture version for which the function was * compiled. This value is the major PTX version * 10 + the minor PTX * version, so a PTX version 1.3 function would return the value 13. * Note that this may return the undefined value of 0 for cubins * compiled prior to CUDA 3.0. */ CU_FUNC_ATTRIBUTE_PTX_VERSION = 5, /** * The binary architecture version for which the function was compiled. * This value is the major binary version * 10 + the minor binary version, * so a binary version 1.3 function would return the value 13. Note that * this will return a value of 10 for legacy cubins that do not have a * properly-encoded binary architecture version. */ CU_FUNC_ATTRIBUTE_BINARY_VERSION = 6, CU_FUNC_ATTRIBUTE_MAX } CUfunction_attribute; /** * Function cache configurations */ typedef enum CUfunc_cache_enum { CU_FUNC_CACHE_PREFER_NONE = 0x00, /**< no preference for shared memory or L1 (default) */ CU_FUNC_CACHE_PREFER_SHARED = 0x01, /**< prefer larger shared memory and smaller L1 cache */ CU_FUNC_CACHE_PREFER_L1 = 0x02 /**< prefer larger L1 cache and smaller shared memory */ } CUfunc_cache; /** * Memory types */ typedef enum CUmemorytype_enum { CU_MEMORYTYPE_HOST = 0x01, /**< Host memory */ CU_MEMORYTYPE_DEVICE = 0x02, /**< Device memory */ CU_MEMORYTYPE_ARRAY = 0x03 /**< Array memory */ #if __CUDA_API_VERSION >= 4000 , CU_MEMORYTYPE_UNIFIED = 0x04 /**< Unified device or host memory */ #endif } CUmemorytype; /** * Compute Modes */ typedef enum CUcomputemode_enum { CU_COMPUTEMODE_DEFAULT = 0, /**< Default compute mode (Multiple contexts allowed per device) */ CU_COMPUTEMODE_EXCLUSIVE = 1, /**< Compute-exclusive-thread mode (Only one context used by a single thread can be present on this device at a time) */ CU_COMPUTEMODE_PROHIBITED = 2 /**< Compute-prohibited mode (No contexts can be created on this device at this time) */ #if __CUDA_API_VERSION >= 4000 , CU_COMPUTEMODE_EXCLUSIVE_PROCESS = 3 /**< Compute-exclusive-process mode (Only one context used by a single process can be present on this device at a time) */ #endif } CUcomputemode; /** * Online compiler options */ typedef enum CUjit_option_enum { /** * Max number of registers that a thread may use.\n * Option type: unsigned int */ CU_JIT_MAX_REGISTERS = 0, /** * IN: Specifies minimum number of threads per block to target compilation * for\n * OUT: Returns the number of threads the compiler actually targeted. * This restricts the resource utilization fo the compiler (e.g. max * registers) such that a block with the given number of threads should be * able to launch based on register limitations. Note, this option does not * currently take into account any other resource limitations, such as * shared memory utilization.\n * Option type: unsigned int */ CU_JIT_THREADS_PER_BLOCK, /** * Returns a float value in the option of the wall clock time, in * milliseconds, spent creating the cubin\n * Option type: float */ CU_JIT_WALL_TIME, /** * Pointer to a buffer in which to print any log messsages from PTXAS * that are informational in nature (the buffer size is specified via * option ::CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES) \n * Option type: char* */ CU_JIT_INFO_LOG_BUFFER, /** * IN: Log buffer size in bytes. Log messages will be capped at this size * (including null terminator)\n * OUT: Amount of log buffer filled with messages\n * Option type: unsigned int */ CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES, /** * Pointer to a buffer in which to print any log messages from PTXAS that * reflect errors (the buffer size is specified via option * ::CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES)\n * Option type: char* */ CU_JIT_ERROR_LOG_BUFFER, /** * IN: Log buffer size in bytes. Log messages will be capped at this size * (including null terminator)\n * OUT: Amount of log buffer filled with messages\n * Option type: unsigned int */ CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, /** * Level of optimizations to apply to generated code (0 - 4), with 4 * being the default and highest level of optimizations.\n * Option type: unsigned int */ CU_JIT_OPTIMIZATION_LEVEL, /** * No option value required. Determines the target based on the current * attached context (default)\n * Option type: No option value needed */ CU_JIT_TARGET_FROM_CUCONTEXT, /** * Target is chosen based on supplied ::CUjit_target_enum.\n * Option type: unsigned int for enumerated type ::CUjit_target_enum */ CU_JIT_TARGET, /** * Specifies choice of fallback strategy if matching cubin is not found. * Choice is based on supplied ::CUjit_fallback_enum.\n * Option type: unsigned int for enumerated type ::CUjit_fallback_enum */ CU_JIT_FALLBACK_STRATEGY } CUjit_option; /** * Online compilation targets */ typedef enum CUjit_target_enum { CU_TARGET_COMPUTE_10 = 0, /**< Compute device class 1.0 */ CU_TARGET_COMPUTE_11, /**< Compute device class 1.1 */ CU_TARGET_COMPUTE_12, /**< Compute device class 1.2 */ CU_TARGET_COMPUTE_13, /**< Compute device class 1.3 */ CU_TARGET_COMPUTE_20, /**< Compute device class 2.0 */ CU_TARGET_COMPUTE_21 /**< Compute device class 2.1 */ } CUjit_target; /** * Cubin matching fallback strategies */ typedef enum CUjit_fallback_enum { CU_PREFER_PTX = 0, /**< Prefer to compile ptx */ CU_PREFER_BINARY /**< Prefer to fall back to compatible binary code */ } CUjit_fallback; /** * Flags to register a graphics resource */ typedef enum CUgraphicsRegisterFlags_enum { CU_GRAPHICS_REGISTER_FLAGS_NONE = 0x00, CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY = 0x01, CU_GRAPHICS_REGISTER_FLAGS_WRITE_DISCARD = 0x02, CU_GRAPHICS_REGISTER_FLAGS_SURFACE_LDST = 0x04 } CUgraphicsRegisterFlags; /** * Flags for mapping and unmapping interop resources */ typedef enum CUgraphicsMapResourceFlags_enum { CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE = 0x00, CU_GRAPHICS_MAP_RESOURCE_FLAGS_READ_ONLY = 0x01, CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD = 0x02 } CUgraphicsMapResourceFlags; /** * Array indices for cube faces */ typedef enum CUarray_cubemap_face_enum { CU_CUBEMAP_FACE_POSITIVE_X = 0x00, /**< Positive X face of cubemap */ CU_CUBEMAP_FACE_NEGATIVE_X = 0x01, /**< Negative X face of cubemap */ CU_CUBEMAP_FACE_POSITIVE_Y = 0x02, /**< Positive Y face of cubemap */ CU_CUBEMAP_FACE_NEGATIVE_Y = 0x03, /**< Negative Y face of cubemap */ CU_CUBEMAP_FACE_POSITIVE_Z = 0x04, /**< Positive Z face of cubemap */ CU_CUBEMAP_FACE_NEGATIVE_Z = 0x05 /**< Negative Z face of cubemap */ } CUarray_cubemap_face; /** * Limits */ typedef enum CUlimit_enum { CU_LIMIT_STACK_SIZE = 0x00, /**< GPU thread stack size */ CU_LIMIT_PRINTF_FIFO_SIZE = 0x01, /**< GPU printf FIFO size */ CU_LIMIT_MALLOC_HEAP_SIZE = 0x02 /**< GPU malloc heap size */ } CUlimit; /** * Error codes */ typedef enum cudaError_enum { /** * The API call returned with no errors. In the case of query calls, this * can also mean that the operation being queried is complete (see * ::cuEventQuery() and ::cuStreamQuery()). */ CUDA_SUCCESS = 0, /** * This indicates that one or more of the parameters passed to the API call * is not within an acceptable range of values. */ CUDA_ERROR_INVALID_VALUE = 1, /** * The API call failed because it was unable to allocate enough memory to * perform the requested operation. */ CUDA_ERROR_OUT_OF_MEMORY = 2, /** * This indicates that the CUDA driver has not been initialized with * ::cuInit() or that initialization has failed. */ CUDA_ERROR_NOT_INITIALIZED = 3, /** * This indicates that the CUDA driver is in the process of shutting down. */ CUDA_ERROR_DEINITIALIZED = 4, /** * This indicates profiling APIs are called while application is running * in visual profiler mode. */ CUDA_ERROR_PROFILER_DISABLED = 5, /** * This indicates profiling has not been initialized for this context. * Call cuProfilerInitialize() to resolve this. */ CUDA_ERROR_PROFILER_NOT_INITIALIZED = 6, /** * This indicates profiler has already been started and probably * cuProfilerStart() is incorrectly called. */ CUDA_ERROR_PROFILER_ALREADY_STARTED = 7, /** * This indicates profiler has already been stopped and probably * cuProfilerStop() is incorrectly called. */ CUDA_ERROR_PROFILER_ALREADY_STOPPED = 8, /** * This indicates that no CUDA-capable devices were detected by the installed * CUDA driver. */ CUDA_ERROR_NO_DEVICE = 100, /** * This indicates that the device ordinal supplied by the user does not * correspond to a valid CUDA device. */ CUDA_ERROR_INVALID_DEVICE = 101, /** * This indicates that the device kernel image is invalid. This can also * indicate an invalid CUDA module. */ CUDA_ERROR_INVALID_IMAGE = 200, /** * This most frequently indicates that there is no context bound to the * current thread. This can also be returned if the context passed to an * API call is not a valid handle (such as a context that has had * ::cuCtxDestroy() invoked on it). This can also be returned if a user * mixes different API versions (i.e. 3010 context with 3020 API calls). * See ::cuCtxGetApiVersion() for more details. */ CUDA_ERROR_INVALID_CONTEXT = 201, /** * This indicated that the context being supplied as a parameter to the * API call was already the active context. * \deprecated * This error return is deprecated as of CUDA 3.2. It is no longer an * error to attempt to push the active context via ::cuCtxPushCurrent(). */ CUDA_ERROR_CONTEXT_ALREADY_CURRENT = 202, /** * This indicates that a map or register operation has failed. */ CUDA_ERROR_MAP_FAILED = 205, /** * This indicates that an unmap or unregister operation has failed. */ CUDA_ERROR_UNMAP_FAILED = 206, /** * This indicates that the specified array is currently mapped and thus * cannot be destroyed. */ CUDA_ERROR_ARRAY_IS_MAPPED = 207, /** * This indicates that the resource is already mapped. */ CUDA_ERROR_ALREADY_MAPPED = 208, /** * This indicates that there is no kernel image available that is suitable * for the device. This can occur when a user specifies code generation * options for a particular CUDA source file that do not include the * corresponding device configuration. */ CUDA_ERROR_NO_BINARY_FOR_GPU = 209, /** * This indicates that a resource has already been acquired. */ CUDA_ERROR_ALREADY_ACQUIRED = 210, /** * This indicates that a resource is not mapped. */ CUDA_ERROR_NOT_MAPPED = 211, /** * This indicates that a mapped resource is not available for access as an * array. */ CUDA_ERROR_NOT_MAPPED_AS_ARRAY = 212, /** * This indicates that a mapped resource is not available for access as a * pointer. */ CUDA_ERROR_NOT_MAPPED_AS_POINTER = 213, /** * This indicates that an uncorrectable ECC error was detected during * execution. */ CUDA_ERROR_ECC_UNCORRECTABLE = 214, /** * This indicates that the ::CUlimit passed to the API call is not * supported by the active device. */ CUDA_ERROR_UNSUPPORTED_LIMIT = 215, /** * This indicates that the ::CUcontext passed to the API call can * only be bound to a single CPU thread at a time but is already * bound to a CPU thread. */ CUDA_ERROR_CONTEXT_ALREADY_IN_USE = 216, /** * This indicates that the device kernel source is invalid. */ CUDA_ERROR_INVALID_SOURCE = 300, /** * This indicates that the file specified was not found. */ CUDA_ERROR_FILE_NOT_FOUND = 301, /** * This indicates that a link to a shared object failed to resolve. */ CUDA_ERROR_SHARED_OBJECT_SYMBOL_NOT_FOUND = 302, /** * This indicates that initialization of a shared object failed. */ CUDA_ERROR_SHARED_OBJECT_INIT_FAILED = 303, /** * This indicates that an OS call failed. */ CUDA_ERROR_OPERATING_SYSTEM = 304, /** * This indicates that a resource handle passed to the API call was not * valid. Resource handles are opaque types like ::CUstream and ::CUevent. */ CUDA_ERROR_INVALID_HANDLE = 400, /** * This indicates that a named symbol was not found. Examples of symbols * are global/constant variable names, texture names, and surface names. */ CUDA_ERROR_NOT_FOUND = 500, /** * This indicates that asynchronous operations issued previously have not * completed yet. This result is not actually an error, but must be indicated * differently than ::CUDA_SUCCESS (which indicates completion). Calls that * may return this value include ::cuEventQuery() and ::cuStreamQuery(). */ CUDA_ERROR_NOT_READY = 600, /** * An exception occurred on the device while executing a kernel. Common * causes include dereferencing an invalid device pointer and accessing * out of bounds shared memory. The context cannot be used, so it must * be destroyed (and a new one should be created). All existing device * memory allocations from this context are invalid and must be * reconstructed if the program is to continue using CUDA. */ CUDA_ERROR_LAUNCH_FAILED = 700, /** * This indicates that a launch did not occur because it did not have * appropriate resources. This error usually indicates that the user has * attempted to pass too many arguments to the device kernel, or the * kernel launch specifies too many threads for the kernel's register * count. Passing arguments of the wrong size (i.e. a 64-bit pointer * when a 32-bit int is expected) is equivalent to passing too many * arguments and can also result in this error. */ CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES = 701, /** * This indicates that the device kernel took too long to execute. This can * only occur if timeouts are enabled - see the device attribute * ::CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT for more information. The * context cannot be used (and must be destroyed similar to * ::CUDA_ERROR_LAUNCH_FAILED). All existing device memory allocations from * this context are invalid and must be reconstructed if the program is to * continue using CUDA. */ CUDA_ERROR_LAUNCH_TIMEOUT = 702, /** * This error indicates a kernel launch that uses an incompatible texturing * mode. */ CUDA_ERROR_LAUNCH_INCOMPATIBLE_TEXTURING = 703, /** * This error indicates that a call to ::cuCtxEnablePeerAccess() is * trying to re-enable peer access to a context which has already * had peer access to it enabled. */ CUDA_ERROR_PEER_ACCESS_ALREADY_ENABLED = 704, /** * This error indicates that a call to ::cuMemPeerRegister is trying to * register memory from a context which has not had peer access * enabled yet via ::cuCtxEnablePeerAccess(), or that * ::cuCtxDisablePeerAccess() is trying to disable peer access * which has not been enabled yet. */ CUDA_ERROR_PEER_ACCESS_NOT_ENABLED = 705, /** * This error indicates that a call to ::cuMemPeerRegister is trying to * register already-registered memory. */ CUDA_ERROR_PEER_MEMORY_ALREADY_REGISTERED = 706, /** * This error indicates that a call to ::cuMemPeerUnregister is trying to * unregister memory that has not been registered. */ CUDA_ERROR_PEER_MEMORY_NOT_REGISTERED = 707, /** * This error indicates that ::cuCtxCreate was called with the flag * ::CU_CTX_PRIMARY on a device which already has initialized its * primary context. */ CUDA_ERROR_PRIMARY_CONTEXT_ACTIVE = 708, /** * This error indicates that the context current to the calling thread * has been destroyed using ::cuCtxDestroy, or is a primary context which * has not yet been initialized. */ CUDA_ERROR_CONTEXT_IS_DESTROYED = 709, /** * This indicates that an unknown internal error has occurred. */ CUDA_ERROR_UNKNOWN = 999 } CUresult; #if __CUDA_API_VERSION >= 4000 /** * If set, host memory is portable between CUDA contexts. * Flag for ::cuMemHostAlloc() */ #define CU_MEMHOSTALLOC_PORTABLE 0x01 /** * If set, host memory is mapped into CUDA address space and * ::cuMemHostGetDevicePointer() may be called on the host pointer. * Flag for ::cuMemHostAlloc() */ #define CU_MEMHOSTALLOC_DEVICEMAP 0x02 /** * If set, host memory is allocated as write-combined - fast to write, * faster to DMA, slow to read except via SSE4 streaming load instruction * (MOVNTDQA). * Flag for ::cuMemHostAlloc() */ #define CU_MEMHOSTALLOC_WRITECOMBINED 0x04 /** * If set, host memory is portable between CUDA contexts. * Flag for ::cuMemHostRegister() */ #define CU_MEMHOSTREGISTER_PORTABLE 0x01 /** * If set, host memory is mapped into CUDA address space and * ::cuMemHostGetDevicePointer() may be called on the host pointer. * Flag for ::cuMemHostRegister() */ #define CU_MEMHOSTREGISTER_DEVICEMAP 0x02 /** * If set, peer memory is mapped into CUDA address space and * ::cuMemPeerGetDevicePointer() may be called on the host pointer. * Flag for ::cuMemPeerRegister() */ #define CU_MEMPEERREGISTER_DEVICEMAP 0x02 #endif #if __CUDA_API_VERSION >= 3020 /** * 2D memory copy parameters */ typedef struct CUDA_MEMCPY2D_st { size_t srcXInBytes; /**< Source X in bytes */ size_t srcY; /**< Source Y */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ size_t srcPitch; /**< Source pitch (ignored when src is array) */ size_t dstXInBytes; /**< Destination X in bytes */ size_t dstY; /**< Destination Y */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ size_t dstPitch; /**< Destination pitch (ignored when dst is array) */ size_t WidthInBytes; /**< Width of 2D memory copy in bytes */ size_t Height; /**< Height of 2D memory copy */ } CUDA_MEMCPY2D; /** * 3D memory copy parameters */ typedef struct CUDA_MEMCPY3D_st { size_t srcXInBytes; /**< Source X in bytes */ size_t srcY; /**< Source Y */ size_t srcZ; /**< Source Z */ size_t srcLOD; /**< Source LOD */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ void *reserved0; /**< Must be NULL */ size_t srcPitch; /**< Source pitch (ignored when src is array) */ size_t srcHeight; /**< Source height (ignored when src is array; may be 0 if Depth==1) */ size_t dstXInBytes; /**< Destination X in bytes */ size_t dstY; /**< Destination Y */ size_t dstZ; /**< Destination Z */ size_t dstLOD; /**< Destination LOD */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ void *reserved1; /**< Must be NULL */ size_t dstPitch; /**< Destination pitch (ignored when dst is array) */ size_t dstHeight; /**< Destination height (ignored when dst is array; may be 0 if Depth==1) */ size_t WidthInBytes; /**< Width of 3D memory copy in bytes */ size_t Height; /**< Height of 3D memory copy */ size_t Depth; /**< Depth of 3D memory copy */ } CUDA_MEMCPY3D; /** * 3D memory cross-context copy parameters */ typedef struct CUDA_MEMCPY3D_PEER_st { size_t srcXInBytes; /**< Source X in bytes */ size_t srcY; /**< Source Y */ size_t srcZ; /**< Source Z */ size_t srcLOD; /**< Source LOD */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ CUcontext srcContext; /**< Source context (ignored with srcMemoryType is ::CU_MEMORYTYPE_ARRAY) */ size_t srcPitch; /**< Source pitch (ignored when src is array) */ size_t srcHeight; /**< Source height (ignored when src is array; may be 0 if Depth==1) */ size_t dstXInBytes; /**< Destination X in bytes */ size_t dstY; /**< Destination Y */ size_t dstZ; /**< Destination Z */ size_t dstLOD; /**< Destination LOD */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ CUcontext dstContext; /**< Destination context (ignored with dstMemoryType is ::CU_MEMORYTYPE_ARRAY) */ size_t dstPitch; /**< Destination pitch (ignored when dst is array) */ size_t dstHeight; /**< Destination height (ignored when dst is array; may be 0 if Depth==1) */ size_t WidthInBytes; /**< Width of 3D memory copy in bytes */ size_t Height; /**< Height of 3D memory copy */ size_t Depth; /**< Depth of 3D memory copy */ } CUDA_MEMCPY3D_PEER; /** * Array descriptor */ typedef struct CUDA_ARRAY_DESCRIPTOR_st { size_t Width; /**< Width of array */ size_t Height; /**< Height of array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ } CUDA_ARRAY_DESCRIPTOR; /** * 3D array descriptor */ typedef struct CUDA_ARRAY3D_DESCRIPTOR_st { size_t Width; /**< Width of 3D array */ size_t Height; /**< Height of 3D array */ size_t Depth; /**< Depth of 3D array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ unsigned int Flags; /**< Flags */ } CUDA_ARRAY3D_DESCRIPTOR; #endif /* __CUDA_API_VERSION >= 3020 */ /** * If set, the CUDA array is a collection of layers, where each layer is either a 1D * or a 2D array and the Depth member of CUDA_ARRAY3D_DESCRIPTOR specifies the number * of layers, not the depth of a 3D array. */ #define CUDA_ARRAY3D_LAYERED 0x01 /** * Deprecated, use CUDA_ARRAY3D_LAYERED */ #define CUDA_ARRAY3D_2DARRAY 0x01 /** * This flag must be set in order to bind a surface reference * to the CUDA array */ #define CUDA_ARRAY3D_SURFACE_LDST 0x02 /** * Override the texref format with a format inferred from the array. * Flag for ::cuTexRefSetArray() */ #define CU_TRSA_OVERRIDE_FORMAT 0x01 /** * Read the texture as integers rather than promoting the values to floats * in the range [0,1]. * Flag for ::cuTexRefSetFlags() */ #define CU_TRSF_READ_AS_INTEGER 0x01 /** * Use normalized texture coordinates in the range [0,1) instead of [0,dim). * Flag for ::cuTexRefSetFlags() */ #define CU_TRSF_NORMALIZED_COORDINATES 0x02 /** * Perform sRGB->linear conversion during texture read. * Flag for ::cuTexRefSetFlags() */ #define CU_TRSF_SRGB 0x10 /** * End of array terminator for the \p extra parameter to * ::cuLaunchKernel */ #define CU_LAUNCH_PARAM_END ((void*)0x00) /** * Indicator that the next value in the \p extra parameter to * ::cuLaunchKernel will be a pointer to a buffer containing all kernel * parameters used for launching kernel \p f. This buffer needs to * honor all alignment/padding requirements of the individual parameters. * If ::CU_LAUNCH_PARAM_BUFFER_SIZE is not also specified in the * \p extra array, then ::CU_LAUNCH_PARAM_BUFFER_POINTER will have no * effect. */ #define CU_LAUNCH_PARAM_BUFFER_POINTER ((void*)0x01) /** * Indicator that the next value in the \p extra parameter to * ::cuLaunchKernel will be a pointer to a size_t which contains the * size of the buffer specified with ::CU_LAUNCH_PARAM_BUFFER_POINTER. * It is required that ::CU_LAUNCH_PARAM_BUFFER_POINTER also be specified * in the \p extra array if the value associated with * ::CU_LAUNCH_PARAM_BUFFER_SIZE is not zero. */ #define CU_LAUNCH_PARAM_BUFFER_SIZE ((void*)0x02) /** * For texture references loaded into the module, use default texunit from * texture reference. */ #define CU_PARAM_TR_DEFAULT -1 /** * CUDA API made obselete at API version 3020 */ #if defined(__CUDA_API_VERSION_INTERNAL) #define CUdeviceptr CUdeviceptr_v1 #define CUDA_MEMCPY2D_st CUDA_MEMCPY2D_v1_st #define CUDA_MEMCPY2D CUDA_MEMCPY2D_v1 #define CUDA_MEMCPY3D_st CUDA_MEMCPY3D_v1_st #define CUDA_MEMCPY3D CUDA_MEMCPY3D_v1 #define CUDA_ARRAY_DESCRIPTOR_st CUDA_ARRAY_DESCRIPTOR_v1_st #define CUDA_ARRAY_DESCRIPTOR CUDA_ARRAY_DESCRIPTOR_v1 #define CUDA_ARRAY3D_DESCRIPTOR_st CUDA_ARRAY3D_DESCRIPTOR_v1_st #define CUDA_ARRAY3D_DESCRIPTOR CUDA_ARRAY3D_DESCRIPTOR_v1 #endif /* CUDA_FORCE_LEGACY32_INTERNAL */ #if defined(__CUDA_API_VERSION_INTERNAL) || __CUDA_API_VERSION < 3020 typedef unsigned int CUdeviceptr; typedef struct CUDA_MEMCPY2D_st { unsigned int srcXInBytes; /**< Source X in bytes */ unsigned int srcY; /**< Source Y */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ unsigned int srcPitch; /**< Source pitch (ignored when src is array) */ unsigned int dstXInBytes; /**< Destination X in bytes */ unsigned int dstY; /**< Destination Y */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ unsigned int dstPitch; /**< Destination pitch (ignored when dst is array) */ unsigned int WidthInBytes; /**< Width of 2D memory copy in bytes */ unsigned int Height; /**< Height of 2D memory copy */ } CUDA_MEMCPY2D; typedef struct CUDA_MEMCPY3D_st { unsigned int srcXInBytes; /**< Source X in bytes */ unsigned int srcY; /**< Source Y */ unsigned int srcZ; /**< Source Z */ unsigned int srcLOD; /**< Source LOD */ CUmemorytype srcMemoryType; /**< Source memory type (host, device, array) */ const void *srcHost; /**< Source host pointer */ CUdeviceptr srcDevice; /**< Source device pointer */ CUarray srcArray; /**< Source array reference */ void *reserved0; /**< Must be NULL */ unsigned int srcPitch; /**< Source pitch (ignored when src is array) */ unsigned int srcHeight; /**< Source height (ignored when src is array; may be 0 if Depth==1) */ unsigned int dstXInBytes; /**< Destination X in bytes */ unsigned int dstY; /**< Destination Y */ unsigned int dstZ; /**< Destination Z */ unsigned int dstLOD; /**< Destination LOD */ CUmemorytype dstMemoryType; /**< Destination memory type (host, device, array) */ void *dstHost; /**< Destination host pointer */ CUdeviceptr dstDevice; /**< Destination device pointer */ CUarray dstArray; /**< Destination array reference */ void *reserved1; /**< Must be NULL */ unsigned int dstPitch; /**< Destination pitch (ignored when dst is array) */ unsigned int dstHeight; /**< Destination height (ignored when dst is array; may be 0 if Depth==1) */ unsigned int WidthInBytes; /**< Width of 3D memory copy in bytes */ unsigned int Height; /**< Height of 3D memory copy */ unsigned int Depth; /**< Depth of 3D memory copy */ } CUDA_MEMCPY3D; typedef struct CUDA_ARRAY_DESCRIPTOR_st { unsigned int Width; /**< Width of array */ unsigned int Height; /**< Height of array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ } CUDA_ARRAY_DESCRIPTOR; typedef struct CUDA_ARRAY3D_DESCRIPTOR_st { unsigned int Width; /**< Width of 3D array */ unsigned int Height; /**< Height of 3D array */ unsigned int Depth; /**< Depth of 3D array */ CUarray_format Format; /**< Array format */ unsigned int NumChannels; /**< Channels per array element */ unsigned int Flags; /**< Flags */ } CUDA_ARRAY3D_DESCRIPTOR; #endif /* (__CUDA_API_VERSION_INTERNAL) || __CUDA_API_VERSION < 3020 */ /* * If set, the CUDA array contains an array of 2D slices * and the Depth member of CUDA_ARRAY3D_DESCRIPTOR specifies * the number of slices, not the depth of a 3D array. */ #define CUDA_ARRAY3D_2DARRAY 0x01 /** * This flag must be set in order to bind a surface reference * to the CUDA array */ #define CUDA_ARRAY3D_SURFACE_LDST 0x02 /** * Override the texref format with a format inferred from the array. * Flag for ::cuTexRefSetArray() */ #define CU_TRSA_OVERRIDE_FORMAT 0x01 /** * Read the texture as integers rather than promoting the values to floats * in the range [0,1]. * Flag for ::cuTexRefSetFlags() */ #define CU_TRSF_READ_AS_INTEGER 0x01 /** * Use normalized texture coordinates in the range [0,1) instead of [0,dim). * Flag for ::cuTexRefSetFlags() */ #define CU_TRSF_NORMALIZED_COORDINATES 0x02 /** * Perform sRGB->linear conversion during texture read. * Flag for ::cuTexRefSetFlags() */ #define CU_TRSF_SRGB 0x10 /** * For texture references loaded into the module, use default texunit from * texture reference. */ #define CU_PARAM_TR_DEFAULT -1 /** @} */ /* END CUDA_TYPES */ #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #define CUDAAPI __stdcall #else #define CUDAAPI #endif /** * \defgroup CUDA_INITIALIZE Initialization * * This section describes the initialization functions of the low-level CUDA * driver application programming interface. * * @{ */ /********************************* ** Initialization *********************************/ typedef CUresult CUDAAPI tcuInit(unsigned int Flags); /********************************* ** Driver Version Query *********************************/ typedef CUresult CUDAAPI tcuDriverGetVersion(int *driverVersion); /************************************ ** ** Device management ** ***********************************/ typedef CUresult CUDAAPI tcuDeviceGet(CUdevice *device, int ordinal); typedef CUresult CUDAAPI tcuDeviceGetCount(int *count); typedef CUresult CUDAAPI tcuDeviceGetName(char *name, int len, CUdevice dev); typedef CUresult CUDAAPI tcuDeviceComputeCapability(int *major, int *minor, CUdevice dev); #if __CUDA_API_VERSION >= 3020 typedef CUresult CUDAAPI tcuDeviceTotalMem(size_t *bytes, CUdevice dev); #else typedef CUresult CUDAAPI tcuDeviceTotalMem(unsigned int *bytes, CUdevice dev); #endif typedef CUresult CUDAAPI tcuDeviceGetProperties(CUdevprop *prop, CUdevice dev); typedef CUresult CUDAAPI tcuDeviceGetAttribute(int *pi, CUdevice_attribute attrib, CUdevice dev); /************************************ ** ** Context management ** ***********************************/ typedef CUresult CUDAAPI tcuCtxCreate(CUcontext *pctx, unsigned int flags, CUdevice dev); typedef CUresult CUDAAPI tcuCtxDestroy(CUcontext ctx); typedef CUresult CUDAAPI tcuCtxAttach(CUcontext *pctx, unsigned int flags); typedef CUresult CUDAAPI tcuCtxDetach(CUcontext ctx); typedef CUresult CUDAAPI tcuCtxPushCurrent(CUcontext ctx); typedef CUresult CUDAAPI tcuCtxPopCurrent(CUcontext *pctx); typedef CUresult CUDAAPI tcuCtxSetCurrent(CUcontext ctx); typedef CUresult CUDAAPI tcuCtxGetCurrent(CUcontext *pctx); typedef CUresult CUDAAPI tcuCtxGetDevice(CUdevice *device); typedef CUresult CUDAAPI tcuCtxSynchronize(void); /************************************ ** ** Module management ** ***********************************/ typedef CUresult CUDAAPI tcuModuleLoad(CUmodule *module, const char *fname); typedef CUresult CUDAAPI tcuModuleLoadData(CUmodule *module, const void *image); typedef CUresult CUDAAPI tcuModuleLoadDataEx(CUmodule *module, const void *image, unsigned int numOptions, CUjit_option *options, void **optionValues); typedef CUresult CUDAAPI tcuModuleLoadFatBinary(CUmodule *module, const void *fatCubin); typedef CUresult CUDAAPI tcuModuleUnload(CUmodule hmod); typedef CUresult CUDAAPI tcuModuleGetFunction(CUfunction *hfunc, CUmodule hmod, const char *name); #if __CUDA_API_VERSION >= 3020 typedef CUresult CUDAAPI tcuModuleGetGlobal(CUdeviceptr *dptr, size_t *bytes, CUmodule hmod, const char *name); #else typedef CUresult CUDAAPI tcuModuleGetGlobal(CUdeviceptr *dptr, unsigned int *bytes, CUmodule hmod, const char *name); #endif typedef CUresult CUDAAPI tcuModuleGetTexRef(CUtexref *pTexRef, CUmodule hmod, const char *name); typedef CUresult CUDAAPI tcuModuleGetSurfRef(CUsurfref *pSurfRef, CUmodule hmod, const char *name); /************************************ ** ** Memory management ** ***********************************/ #if __CUDA_API_VERSION >= 3020 typedef CUresult CUDAAPI tcuMemGetInfo(size_t *free, size_t *total); typedef CUresult CUDAAPI tcuMemAlloc(CUdeviceptr *dptr, size_t bytesize); typedef CUresult CUDAAPI tcuMemGetAddressRange(CUdeviceptr *pbase, size_t *psize, CUdeviceptr dptr); typedef CUresult CUDAAPI tcuMemAllocPitch(CUdeviceptr *dptr, size_t *pPitch, size_t WidthInBytes, size_t Height, // size of biggest r/w to be performed by kernels on this memory // 4, 8 or 16 bytes unsigned int ElementSizeBytes ); #else typedef CUresult CUDAAPI tcuMemGetInfo(unsigned int *free, unsigned int *total); typedef CUresult CUDAAPI tcuMemAlloc(CUdeviceptr *dptr, unsigned int bytesize); typedef CUresult CUDAAPI tcuMemGetAddressRange(CUdeviceptr *pbase, unsigned int *psize, CUdeviceptr dptr); typedef CUresult CUDAAPI tcuMemAllocPitch(CUdeviceptr *dptr, unsigned int *pPitch, unsigned int WidthInBytes, unsigned int Height, // size of biggest r/w to be performed by kernels on this memory // 4, 8 or 16 bytes unsigned int ElementSizeBytes ); #endif typedef CUresult CUDAAPI tcuMemFree(CUdeviceptr dptr); #if __CUDA_API_VERSION >= 3020 typedef CUresult CUDAAPI tcuMemAllocHost(void **pp, size_t bytesize); #else typedef CUresult CUDAAPI tcuMemAllocHost(void **pp, unsigned int bytesize); #endif typedef CUresult CUDAAPI tcuMemFreeHost(void *p); typedef CUresult CUDAAPI tcuMemHostAlloc(void **pp, size_t bytesize, unsigned int Flags); typedef CUresult CUDAAPI tcuMemHostGetDevicePointer(CUdeviceptr *pdptr, void *p, unsigned int Flags); typedef CUresult CUDAAPI tcuMemHostGetFlags(unsigned int *pFlags, void *p); typedef CUresult CUDAAPI tcuMemHostRegister(void *p, size_t bytesize, unsigned int Flags); typedef CUresult CUDAAPI tcuMemHostUnregister(void *p);; typedef CUresult CUDAAPI tcuMemcpy(CUdeviceptr dst, CUdeviceptr src, size_t ByteCount); typedef CUresult CUDAAPI tcuMemcpyPeer(CUdeviceptr dstDevice, CUcontext dstContext, CUdeviceptr srcDevice, CUcontext srcContext, size_t ByteCount); /************************************ ** ** Synchronous Memcpy ** ** Intra-device memcpy's done with these functions may execute in parallel with the CPU, ** but if host memory is involved, they wait until the copy is done before returning. ** ***********************************/ // 1D functions #if __CUDA_API_VERSION >= 3020 // system <-> device memory typedef CUresult CUDAAPI tcuMemcpyHtoD(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount); typedef CUresult CUDAAPI tcuMemcpyDtoH(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount); // device <-> device memory typedef CUresult CUDAAPI tcuMemcpyDtoD(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount); // device <-> array memory typedef CUresult CUDAAPI tcuMemcpyDtoA(CUarray dstArray, size_t dstOffset, CUdeviceptr srcDevice, size_t ByteCount); typedef CUresult CUDAAPI tcuMemcpyAtoD(CUdeviceptr dstDevice, CUarray srcArray, size_t srcOffset, size_t ByteCount); // system <-> array memory typedef CUresult CUDAAPI tcuMemcpyHtoA(CUarray dstArray, size_t dstOffset, const void *srcHost, size_t ByteCount); typedef CUresult CUDAAPI tcuMemcpyAtoH(void *dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount); // array <-> array memory typedef CUresult CUDAAPI tcuMemcpyAtoA(CUarray dstArray, size_t dstOffset, CUarray srcArray, size_t srcOffset, size_t ByteCount); #else // system <-> device memory typedef CUresult CUDAAPI tcuMemcpyHtoD(CUdeviceptr dstDevice, const void *srcHost, unsigned int ByteCount); typedef CUresult CUDAAPI tcuMemcpyDtoH(void *dstHost, CUdeviceptr srcDevice, unsigned int ByteCount); // device <-> device memory typedef CUresult CUDAAPI tcuMemcpyDtoD(CUdeviceptr dstDevice, CUdeviceptr srcDevice, unsigned int ByteCount); // device <-> array memory typedef CUresult CUDAAPI tcuMemcpyDtoA(CUarray dstArray, unsigned int dstOffset, CUdeviceptr srcDevice, unsigned int ByteCount); typedef CUresult CUDAAPI tcuMemcpyAtoD(CUdeviceptr dstDevice, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount); // system <-> array memory typedef CUresult CUDAAPI tcuMemcpyHtoA(CUarray dstArray, unsigned int dstOffset, const void *srcHost, unsigned int ByteCount); typedef CUresult CUDAAPI tcuMemcpyAtoH(void *dstHost, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount); // array <-> array memory typedef CUresult CUDAAPI tcuMemcpyAtoA(CUarray dstArray, unsigned int dstOffset, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount); #endif // 2D memcpy typedef CUresult CUDAAPI tcuMemcpy2D(const CUDA_MEMCPY2D *pCopy); typedef CUresult CUDAAPI tcuMemcpy2DUnaligned(const CUDA_MEMCPY2D *pCopy); // 3D memcpy typedef CUresult CUDAAPI tcuMemcpy3D(const CUDA_MEMCPY3D *pCopy); /************************************ ** ** Asynchronous Memcpy ** ** Any host memory involved must be DMA'able (e.g., allocated with cuMemAllocHost). ** memcpy's done with these functions execute in parallel with the CPU and, if ** the hardware is available, may execute in parallel with the GPU. ** Asynchronous memcpy must be accompanied by appropriate stream synchronization. ** ***********************************/ // 1D functions #if __CUDA_API_VERSION >= 3020 // system <-> device memory typedef CUresult CUDAAPI tcuMemcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost, size_t ByteCount, CUstream hStream); typedef CUresult CUDAAPI tcuMemcpyDtoHAsync(void *dstHost, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream); // device <-> device memory typedef CUresult CUDAAPI tcuMemcpyDtoDAsync(CUdeviceptr dstDevice, CUdeviceptr srcDevice, size_t ByteCount, CUstream hStream); // system <-> array memory typedef CUresult CUDAAPI tcuMemcpyHtoAAsync(CUarray dstArray, size_t dstOffset, const void *srcHost, size_t ByteCount, CUstream hStream); typedef CUresult CUDAAPI tcuMemcpyAtoHAsync(void *dstHost, CUarray srcArray, size_t srcOffset, size_t ByteCount, CUstream hStream); #else // system <-> device memory typedef CUresult CUDAAPI tcuMemcpyHtoDAsync(CUdeviceptr dstDevice, const void *srcHost, unsigned int ByteCount, CUstream hStream); typedef CUresult CUDAAPI tcuMemcpyDtoHAsync(void *dstHost, CUdeviceptr srcDevice, unsigned int ByteCount, CUstream hStream); // device <-> device memory typedef CUresult CUDAAPI tcuMemcpyDtoDAsync(CUdeviceptr dstDevice, CUdeviceptr srcDevice, unsigned int ByteCount, CUstream hStream); // system <-> array memory typedef CUresult CUDAAPI tcuMemcpyHtoAAsync(CUarray dstArray, unsigned int dstOffset, const void *srcHost, unsigned int ByteCount, CUstream hStream); typedef CUresult CUDAAPI tcuMemcpyAtoHAsync(void *dstHost, CUarray srcArray, unsigned int srcOffset, unsigned int ByteCount, CUstream hStream); #endif // 2D memcpy typedef CUresult CUDAAPI tcuMemcpy2DAsync(const CUDA_MEMCPY2D *pCopy, CUstream hStream); // 3D memcpy typedef CUresult CUDAAPI tcuMemcpy3DAsync(const CUDA_MEMCPY3D *pCopy, CUstream hStream); /************************************ ** ** Memset ** ***********************************/ #if __CUDA_API_VERSION >= 3020 typedef CUresult CUDAAPI tcuMemsetD8(CUdeviceptr dstDevice, unsigned char uc, size_t N); typedef CUresult CUDAAPI tcuMemsetD16(CUdeviceptr dstDevice, unsigned short us, size_t N); typedef CUresult CUDAAPI tcuMemsetD32(CUdeviceptr dstDevice, unsigned int ui, size_t N); typedef CUresult CUDAAPI tcuMemsetD2D8(CUdeviceptr dstDevice, unsigned int dstPitch, unsigned char uc, size_t Width, size_t Height); typedef CUresult CUDAAPI tcuMemsetD2D16(CUdeviceptr dstDevice, unsigned int dstPitch, unsigned short us, size_t Width, size_t Height); typedef CUresult CUDAAPI tcuMemsetD2D32(CUdeviceptr dstDevice, unsigned int dstPitch, unsigned int ui, size_t Width, size_t Height); #else typedef CUresult CUDAAPI tcuMemsetD8(CUdeviceptr dstDevice, unsigned char uc, unsigned int N); typedef CUresult CUDAAPI tcuMemsetD16(CUdeviceptr dstDevice, unsigned short us, unsigned int N); typedef CUresult CUDAAPI tcuMemsetD32(CUdeviceptr dstDevice, unsigned int ui, unsigned int N); typedef CUresult CUDAAPI tcuMemsetD2D8(CUdeviceptr dstDevice, unsigned int dstPitch, unsigned char uc, unsigned int Width, unsigned int Height); typedef CUresult CUDAAPI tcuMemsetD2D16(CUdeviceptr dstDevice, unsigned int dstPitch, unsigned short us, unsigned int Width, unsigned int Height); typedef CUresult CUDAAPI tcuMemsetD2D32(CUdeviceptr dstDevice, unsigned int dstPitch, unsigned int ui, unsigned int Width, unsigned int Height); #endif /************************************ ** ** Function management ** ***********************************/ typedef CUresult CUDAAPI tcuFuncSetBlockShape(CUfunction hfunc, int x, int y, int z); typedef CUresult CUDAAPI tcuFuncSetSharedSize(CUfunction hfunc, unsigned int bytes); typedef CUresult CUDAAPI tcuFuncGetAttribute(int *pi, CUfunction_attribute attrib, CUfunction hfunc); typedef CUresult CUDAAPI tcuFuncSetCacheConfig(CUfunction hfunc, CUfunc_cache config); typedef CUresult CUDAAPI tcuLaunchKernel(CUfunction f, unsigned int gridDimX, unsigned int gridDimY, unsigned int gridDimZ, unsigned int blockDimX, unsigned int blockDimY, unsigned int blockDimZ, unsigned int sharedMemBytes, CUstream hStream, void **kernelParams, void **extra); /************************************ ** ** Array management ** ***********************************/ typedef CUresult CUDAAPI tcuArrayCreate(CUarray *pHandle, const CUDA_ARRAY_DESCRIPTOR *pAllocateArray); typedef CUresult CUDAAPI tcuArrayGetDescriptor(CUDA_ARRAY_DESCRIPTOR *pArrayDescriptor, CUarray hArray); typedef CUresult CUDAAPI tcuArrayDestroy(CUarray hArray); typedef CUresult CUDAAPI tcuArray3DCreate(CUarray *pHandle, const CUDA_ARRAY3D_DESCRIPTOR *pAllocateArray); typedef CUresult CUDAAPI tcuArray3DGetDescriptor(CUDA_ARRAY3D_DESCRIPTOR *pArrayDescriptor, CUarray hArray); /************************************ ** ** Texture reference management ** ***********************************/ typedef CUresult CUDAAPI tcuTexRefCreate(CUtexref *pTexRef); typedef CUresult CUDAAPI tcuTexRefDestroy(CUtexref hTexRef); typedef CUresult CUDAAPI tcuTexRefSetArray(CUtexref hTexRef, CUarray hArray, unsigned int Flags); #if __CUDA_API_VERSION >= 3020 typedef CUresult CUDAAPI tcuTexRefSetAddress(size_t *ByteOffset, CUtexref hTexRef, CUdeviceptr dptr, size_t bytes); typedef CUresult CUDAAPI tcuTexRefSetAddress2D(CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR *desc, CUdeviceptr dptr, size_t Pitch); #else typedef CUresult CUDAAPI tcuTexRefSetAddress(unsigned int *ByteOffset, CUtexref hTexRef, CUdeviceptr dptr, unsigned int bytes); typedef CUresult CUDAAPI tcuTexRefSetAddress2D(CUtexref hTexRef, const CUDA_ARRAY_DESCRIPTOR *desc, CUdeviceptr dptr, unsigned int Pitch); #endif typedef CUresult CUDAAPI tcuTexRefSetFormat(CUtexref hTexRef, CUarray_format fmt, int NumPackedComponents); typedef CUresult CUDAAPI tcuTexRefSetAddressMode(CUtexref hTexRef, int dim, CUaddress_mode am); typedef CUresult CUDAAPI tcuTexRefSetFilterMode(CUtexref hTexRef, CUfilter_mode fm); typedef CUresult CUDAAPI tcuTexRefSetFlags(CUtexref hTexRef, unsigned int Flags); typedef CUresult CUDAAPI tcuTexRefGetAddress(CUdeviceptr *pdptr, CUtexref hTexRef); typedef CUresult CUDAAPI tcuTexRefGetArray(CUarray *phArray, CUtexref hTexRef); typedef CUresult CUDAAPI tcuTexRefGetAddressMode(CUaddress_mode *pam, CUtexref hTexRef, int dim); typedef CUresult CUDAAPI tcuTexRefGetFilterMode(CUfilter_mode *pfm, CUtexref hTexRef); typedef CUresult CUDAAPI tcuTexRefGetFormat(CUarray_format *pFormat, int *pNumChannels, CUtexref hTexRef); typedef CUresult CUDAAPI tcuTexRefGetFlags(unsigned int *pFlags, CUtexref hTexRef); /************************************ ** ** Surface reference management ** ***********************************/ typedef CUresult CUDAAPI tcuSurfRefSetArray(CUsurfref hSurfRef, CUarray hArray, unsigned int Flags); typedef CUresult CUDAAPI tcuSurfRefGetArray(CUarray *phArray, CUsurfref hSurfRef); /************************************ ** ** Parameter management ** ***********************************/ typedef CUresult CUDAAPI tcuParamSetSize(CUfunction hfunc, unsigned int numbytes); typedef CUresult CUDAAPI tcuParamSeti(CUfunction hfunc, int offset, unsigned int value); typedef CUresult CUDAAPI tcuParamSetf(CUfunction hfunc, int offset, float value); typedef CUresult CUDAAPI tcuParamSetv(CUfunction hfunc, int offset, void *ptr, unsigned int numbytes); typedef CUresult CUDAAPI tcuParamSetTexRef(CUfunction hfunc, int texunit, CUtexref hTexRef); /************************************ ** ** Launch functions ** ***********************************/ typedef CUresult CUDAAPI tcuLaunch(CUfunction f); typedef CUresult CUDAAPI tcuLaunchGrid(CUfunction f, int grid_width, int grid_height); typedef CUresult CUDAAPI tcuLaunchGridAsync(CUfunction f, int grid_width, int grid_height, CUstream hStream); /************************************ ** ** Events ** ***********************************/ typedef CUresult CUDAAPI tcuEventCreate(CUevent *phEvent, unsigned int Flags); typedef CUresult CUDAAPI tcuEventRecord(CUevent hEvent, CUstream hStream); typedef CUresult CUDAAPI tcuEventQuery(CUevent hEvent); typedef CUresult CUDAAPI tcuEventSynchronize(CUevent hEvent); typedef CUresult CUDAAPI tcuEventDestroy(CUevent hEvent); typedef CUresult CUDAAPI tcuEventElapsedTime(float *pMilliseconds, CUevent hStart, CUevent hEnd); /************************************ ** ** Streams ** ***********************************/ typedef CUresult CUDAAPI tcuStreamCreate(CUstream *phStream, unsigned int Flags); typedef CUresult CUDAAPI tcuStreamQuery(CUstream hStream); typedef CUresult CUDAAPI tcuStreamSynchronize(CUstream hStream); typedef CUresult CUDAAPI tcuStreamDestroy(CUstream hStream); /************************************ ** ** Graphics interop ** ***********************************/ typedef CUresult CUDAAPI tcuGraphicsUnregisterResource(CUgraphicsResource resource); typedef CUresult CUDAAPI tcuGraphicsSubResourceGetMappedArray(CUarray *pArray, CUgraphicsResource resource, unsigned int arrayIndex, unsigned int mipLevel); #if __CUDA_API_VERSION >= 3020 typedef CUresult CUDAAPI tcuGraphicsResourceGetMappedPointer(CUdeviceptr *pDevPtr, size_t *pSize, CUgraphicsResource resource); #else typedef CUresult CUDAAPI tcuGraphicsResourceGetMappedPointer(CUdeviceptr *pDevPtr, unsigned int *pSize, CUgraphicsResource resource); #endif typedef CUresult CUDAAPI tcuGraphicsResourceSetMapFlags(CUgraphicsResource resource, unsigned int flags); typedef CUresult CUDAAPI tcuGraphicsMapResources(unsigned int count, CUgraphicsResource *resources, CUstream hStream); typedef CUresult CUDAAPI tcuGraphicsUnmapResources(unsigned int count, CUgraphicsResource *resources, CUstream hStream); /************************************ ** ** Export tables ** ***********************************/ typedef CUresult CUDAAPI tcuGetExportTable(const void **ppExportTable, const CUuuid *pExportTableId); /************************************ ** ** Limits ** ***********************************/ typedef CUresult CUDAAPI tcuCtxSetLimit(CUlimit limit, size_t value); typedef CUresult CUDAAPI tcuCtxGetLimit(size_t *pvalue, CUlimit limit); extern tcuDriverGetVersion *cuDriverGetVersion; extern tcuDeviceGet *cuDeviceGet; extern tcuDeviceGetCount *cuDeviceGetCount; extern tcuDeviceGetName *cuDeviceGetName; extern tcuDeviceComputeCapability *cuDeviceComputeCapability; extern tcuDeviceGetProperties *cuDeviceGetProperties; extern tcuDeviceGetAttribute *cuDeviceGetAttribute; extern tcuCtxDestroy *cuCtxDestroy; extern tcuCtxAttach *cuCtxAttach; extern tcuCtxDetach *cuCtxDetach; extern tcuCtxPushCurrent *cuCtxPushCurrent; extern tcuCtxPopCurrent *cuCtxPopCurrent; extern tcuCtxSetCurrent *cuCtxSetCurrent; extern tcuCtxGetCurrent *cuCtxGetCurrent; extern tcuCtxGetDevice *cuCtxGetDevice; extern tcuCtxSynchronize *cuCtxSynchronize; extern tcuModuleLoad *cuModuleLoad; extern tcuModuleLoadData *cuModuleLoadData; extern tcuModuleLoadDataEx *cuModuleLoadDataEx; extern tcuModuleLoadFatBinary *cuModuleLoadFatBinary; extern tcuModuleUnload *cuModuleUnload; extern tcuModuleGetFunction *cuModuleGetFunction; extern tcuModuleGetTexRef *cuModuleGetTexRef; extern tcuModuleGetSurfRef *cuModuleGetSurfRef; extern tcuMemFreeHost *cuMemFreeHost; extern tcuMemHostAlloc *cuMemHostAlloc; extern tcuMemHostGetFlags *cuMemHostGetFlags; extern tcuMemHostRegister *cuMemHostRegister; extern tcuMemHostUnregister *cuMemHostUnregister; extern tcuMemcpy *cuMemcpy; extern tcuMemcpyPeer *cuMemcpyPeer; extern tcuDeviceTotalMem *cuDeviceTotalMem; extern tcuCtxCreate *cuCtxCreate; extern tcuModuleGetGlobal *cuModuleGetGlobal; extern tcuMemGetInfo *cuMemGetInfo; extern tcuMemAlloc *cuMemAlloc; extern tcuMemAllocPitch *cuMemAllocPitch; extern tcuMemFree *cuMemFree; extern tcuMemGetAddressRange *cuMemGetAddressRange; extern tcuMemAllocHost *cuMemAllocHost; extern tcuMemHostGetDevicePointer *cuMemHostGetDevicePointer; extern tcuFuncSetBlockShape *cuFuncSetBlockShape; extern tcuFuncSetSharedSize *cuFuncSetSharedSize; extern tcuFuncGetAttribute *cuFuncGetAttribute; extern tcuFuncSetCacheConfig *cuFuncSetCacheConfig; extern tcuLaunchKernel *cuLaunchKernel; extern tcuArrayDestroy *cuArrayDestroy; extern tcuTexRefCreate *cuTexRefCreate; extern tcuTexRefDestroy *cuTexRefDestroy; extern tcuTexRefSetArray *cuTexRefSetArray; extern tcuTexRefSetFormat *cuTexRefSetFormat; extern tcuTexRefSetAddressMode *cuTexRefSetAddressMode; extern tcuTexRefSetFilterMode *cuTexRefSetFilterMode; extern tcuTexRefSetFlags *cuTexRefSetFlags; extern tcuTexRefGetArray *cuTexRefGetArray; extern tcuTexRefGetAddressMode *cuTexRefGetAddressMode; extern tcuTexRefGetFilterMode *cuTexRefGetFilterMode; extern tcuTexRefGetFormat *cuTexRefGetFormat; extern tcuTexRefGetFlags *cuTexRefGetFlags; extern tcuSurfRefSetArray *cuSurfRefSetArray; extern tcuSurfRefGetArray *cuSurfRefGetArray; extern tcuParamSetSize *cuParamSetSize; extern tcuParamSeti *cuParamSeti; extern tcuParamSetf *cuParamSetf; extern tcuParamSetv *cuParamSetv; extern tcuParamSetTexRef *cuParamSetTexRef; extern tcuLaunch *cuLaunch; extern tcuLaunchGrid *cuLaunchGrid; extern tcuLaunchGridAsync *cuLaunchGridAsync; extern tcuEventCreate *cuEventCreate; extern tcuEventRecord *cuEventRecord; extern tcuEventQuery *cuEventQuery; extern tcuEventSynchronize *cuEventSynchronize; extern tcuEventDestroy *cuEventDestroy; extern tcuEventElapsedTime *cuEventElapsedTime; extern tcuStreamCreate *cuStreamCreate; extern tcuStreamQuery *cuStreamQuery; extern tcuStreamSynchronize *cuStreamSynchronize; extern tcuStreamDestroy *cuStreamDestroy; extern tcuGraphicsUnregisterResource *cuGraphicsUnregisterResource; extern tcuGraphicsSubResourceGetMappedArray *cuGraphicsSubResourceGetMappedArray; extern tcuGraphicsResourceSetMapFlags *cuGraphicsResourceSetMapFlags; extern tcuGraphicsMapResources *cuGraphicsMapResources; extern tcuGraphicsUnmapResources *cuGraphicsUnmapResources; extern tcuGetExportTable *cuGetExportTable; extern tcuCtxSetLimit *cuCtxSetLimit; extern tcuCtxGetLimit *cuCtxGetLimit; // These functions could be using the CUDA 3.2 interface (_v2) extern tcuMemcpyHtoD *cuMemcpyHtoD; extern tcuMemcpyDtoH *cuMemcpyDtoH; extern tcuMemcpyDtoD *cuMemcpyDtoD; extern tcuMemcpyDtoA *cuMemcpyDtoA; extern tcuMemcpyAtoD *cuMemcpyAtoD; extern tcuMemcpyHtoA *cuMemcpyHtoA; extern tcuMemcpyAtoH *cuMemcpyAtoH; extern tcuMemcpyAtoA *cuMemcpyAtoA; extern tcuMemcpy2D *cuMemcpy2D; extern tcuMemcpy2DUnaligned *cuMemcpy2DUnaligned; extern tcuMemcpy3D *cuMemcpy3D; extern tcuMemcpyHtoDAsync *cuMemcpyHtoDAsync; extern tcuMemcpyDtoHAsync *cuMemcpyDtoHAsync; extern tcuMemcpyDtoDAsync *cuMemcpyDtoDAsync; extern tcuMemcpyHtoAAsync *cuMemcpyHtoAAsync; extern tcuMemcpyAtoHAsync *cuMemcpyAtoHAsync; extern tcuMemcpy2DAsync *cuMemcpy2DAsync; extern tcuMemcpy3DAsync *cuMemcpy3DAsync; extern tcuMemsetD8 *cuMemsetD8; extern tcuMemsetD16 *cuMemsetD16; extern tcuMemsetD32 *cuMemsetD32; extern tcuMemsetD2D8 *cuMemsetD2D8; extern tcuMemsetD2D16 *cuMemsetD2D16; extern tcuMemsetD2D32 *cuMemsetD2D32; extern tcuArrayCreate *cuArrayCreate; extern tcuArrayGetDescriptor *cuArrayGetDescriptor; extern tcuArray3DCreate *cuArray3DCreate; extern tcuArray3DGetDescriptor *cuArray3DGetDescriptor; extern tcuTexRefSetAddress *cuTexRefSetAddress; extern tcuTexRefSetAddress2D *cuTexRefSetAddress2D; extern tcuTexRefGetAddress *cuTexRefGetAddress; extern tcuGraphicsResourceGetMappedPointer *cuGraphicsResourceGetMappedPointer; /************************************/ CUresult CUDAAPI cuInit (unsigned int, int cudaVersion, void *hHandleDriver); /************************************/ #ifdef __cplusplus } #endif #endif //__cuda_cuda_h__ ================================================ FILE: decoder/LAVVideo/decoders/cuvid/dynlink_cuda_d3d.h ================================================ /* * Copyright 1993-2015 NVIDIA Corporation. All rights reserved. * * Please refer to the NVIDIA end user license agreement (EULA) associated * with this source code for terms and conditions that govern your use of * this software. Any use, reproduction, disclosure, or distribution of * this software and related documentation outside the terms of the EULA * is strictly prohibited. * */ #ifndef __cuda_d3d_h__ #define __cuda_d3d_h__ #if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) #pragma warning(disable: 4312) #if defined (CUDA_INIT_D3D9) || defined(CUDA_INIT_D3D10) || defined(CUDA_INIT_D3D11) #include #include #endif #ifdef CUDA_INIT_D3D9 #pragma warning( disable : 4996 ) // disable deprecated warning #include #pragma warning( default : 4996 ) /** * CUDA 2.x compatibility - Flags to register a D3D9 graphics resource */ typedef enum CUd3d9register_flags_enum { CU_D3D9_REGISTER_FLAGS_NONE = 0x00, CU_D3D9_REGISTER_FLAGS_ARRAY = 0x01, } CUd3d9register_flags; /** * CUDA 2.x compatibility - Flags for D3D9 mapping and unmapping interop resources */ typedef enum CUd3d9map_flags_enum { CU_D3D9_MAPRESOURCE_FLAGS_NONE = 0x00, CU_D3D9_MAPRESOURCE_FLAGS_READONLY = 0x01, CU_D3D9_MAPRESOURCE_FLAGS_WRITEDISCARD = 0x02, } CUd3d9map_flags; // D3D9/CUDA interop (CUDA 1.x compatible API). These functions are deprecated, please use the ones below typedef CUresult CUDAAPI tcuD3D9Begin(IDirect3DDevice9 *pDevice); typedef CUresult CUDAAPI tcuD3D9End(void); typedef CUresult CUDAAPI tcuD3D9RegisterVertexBuffer(IDirect3DVertexBuffer9 *pVB); typedef CUresult CUDAAPI tcuD3D9MapVertexBuffer(CUdeviceptr *pDevPtr, unsigned int *pSize, IDirect3DVertexBuffer9 *pVB); typedef CUresult CUDAAPI tcuD3D9UnmapVertexBuffer(IDirect3DVertexBuffer9 *pVB); typedef CUresult CUDAAPI tcuD3D9UnregisterVertexBuffer(IDirect3DVertexBuffer9 *pVB); // D3D9/CUDA interop (CUDA 2.x compatible) typedef CUresult CUDAAPI tcuD3D9GetDirect3DDevice(IDirect3DDevice9 **ppD3DDevice); typedef CUresult CUDAAPI tcuD3D9RegisterResource(IDirect3DResource9 *pResource, unsigned int Flags); typedef CUresult CUDAAPI tcuD3D9UnregisterResource(IDirect3DResource9 *pResource); typedef CUresult CUDAAPI tcuD3D9MapResources(unsigned int count, IDirect3DResource9 **ppResource); typedef CUresult CUDAAPI tcuD3D9UnmapResources(unsigned int count, IDirect3DResource9 **ppResource); typedef CUresult CUDAAPI tcuD3D9ResourceSetMapFlags(IDirect3DResource9 *pResource, unsigned int Flags); typedef CUresult CUDAAPI tcuD3D9ResourceGetSurfaceDimensions(unsigned int *pWidth, unsigned int *pHeight, unsigned int *pDepth, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level); typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedArray(CUarray *pArray, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level); typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedPointer(CUdeviceptr *pDevPtr, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level); typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedSize(unsigned int *pSize, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level); typedef CUresult CUDAAPI tcuD3D9ResourceGetMappedPitch(unsigned int *pPitch, unsigned int *pPitchSlice, IDirect3DResource9 *pResource, unsigned int Face, unsigned int Level); // D3D9/CUDA interop (CUDA 2.0+) typedef CUresult CUDAAPI tcuD3D9GetDevice(CUdevice *pCudaDevice, const char *pszAdapterName); typedef CUresult CUDAAPI tcuD3D9CtxCreate(CUcontext *pCtx, CUdevice *pCudaDevice, unsigned int Flags, IDirect3DDevice9 *pD3DDevice); typedef CUresult CUDAAPI tcuGraphicsD3D9RegisterResource(CUgraphicsResource *pCudaResource, IDirect3DResource9 *pD3DResource, unsigned int Flags); #endif #ifdef CUDA_INIT_D3D10 #include #include #include #pragma warning( disable : 4996 ) // disable deprecated warning #include #pragma warning( default : 4996 ) // D3D11/CUDA interop (CUDA 3.0) typedef CUresult CUDAAPI tcuD3D10GetDevice(CUdevice *pCudaDevice, IDXGIAdapter *pAdapter); typedef CUresult CUDAAPI tcuD3D10CtxCreate(CUcontext *pCtx, CUdevice *pCudaDevice, unsigned int Flags, ID3D10Device *pD3DDevice); typedef CUresult CUDAAPI tcuGraphicsD3D10RegisterResource(CUgraphicsResource *pCudaResource, ID3D10Resource *pD3DResource, unsigned int Flags); #endif // CUDA_INIT_D3D10 #ifdef CUDA_INIT_D3D11 #include #include #pragma warning( disable : 4996 ) // disable deprecated warning #include #pragma warning( default : 4996 ) // D3D11/CUDA interop (CUDA 3.0) typedef CUresult CUDAAPI tcuD3D11GetDevice(CUdevice *pCudaDevice, IDXGIAdapter *pAdapter); typedef CUresult CUDAAPI tcuD3D11CtxCreate(CUcontext *pCtx, CUdevice *pCudaDevice, unsigned int Flags, ID3D11Device *pD3DDevice); typedef CUresult CUDAAPI tcuGraphicsD3D11RegisterResource(CUgraphicsResource *pCudaResource, ID3D11Resource *pD3DResource, unsigned int Flags); #endif // CUDA_INIT_D3D11 #endif // WIN32 #endif // __cuda_d3d_h__ ================================================ FILE: decoder/LAVVideo/decoders/cuvid/dynlink_cuviddec.h ================================================ /* * This copyright notice applies to this header file only: * * Copyright (c) 2010-2024 NVIDIA Corporation * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the software, and to permit persons to whom the * software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*****************************************************************************************************/ //! \file cuviddec.h //! NVDECODE API provides video decoding interface to NVIDIA GPU devices. //! This file contains constants, structure definitions and function prototypes used for decoding. /*****************************************************************************************************/ #if !defined(__CUDA_VIDEO_H__) #define __CUDA_VIDEO_H__ #ifndef __dynlink_cuda_h__ #include "dynlink_cuda.h" #endif // __dynlink_cuda_h__ #if defined(_WIN64) || defined(__LP64__) || defined(__x86_64) || defined(AMD64) || defined(_M_AMD64) #if (CUDA_VERSION >= 3020) && (!defined(CUDA_FORCE_API_VERSION) || (CUDA_FORCE_API_VERSION >= 3020)) #define __CUVID_DEVPTR64 #endif #endif #if defined(__cplusplus) extern "C" { #endif /* __cplusplus */ typedef void *CUvideodecoder; typedef struct _CUcontextlock_st *CUvideoctxlock; /*********************************************************************************/ //! \enum cudaVideoCodec //! Video codec enums //! These enums are used in CUVIDDECODECREATEINFO and CUVIDDECODECAPS structures /*********************************************************************************/ typedef enum cudaVideoCodec_enum { cudaVideoCodec_MPEG1 = 0, /**< MPEG1 */ cudaVideoCodec_MPEG2, /**< MPEG2 */ cudaVideoCodec_MPEG4, /**< MPEG4 */ cudaVideoCodec_VC1, /**< VC1 */ cudaVideoCodec_H264, /**< H264 */ cudaVideoCodec_JPEG, /**< JPEG */ cudaVideoCodec_H264_SVC, /**< H264-SVC */ cudaVideoCodec_H264_MVC, /**< H264-MVC */ cudaVideoCodec_HEVC, /**< HEVC */ cudaVideoCodec_VP8, /**< VP8 */ cudaVideoCodec_VP9, /**< VP9 */ cudaVideoCodec_AV1, /**< AV1 */ cudaVideoCodec_NumCodecs, /**< Max codecs */ // Uncompressed YUV cudaVideoCodec_YUV420 = (('I' << 24) | ('Y' << 16) | ('U' << 8) | ('V')), /**< Y,U,V (4:2:0) */ cudaVideoCodec_YV12 = (('Y' << 24) | ('V' << 16) | ('1' << 8) | ('2')), /**< Y,V,U (4:2:0) */ cudaVideoCodec_NV12 = (('N' << 24) | ('V' << 16) | ('1' << 8) | ('2')), /**< Y,UV (4:2:0) */ cudaVideoCodec_YUYV = (('Y' << 24) | ('U' << 16) | ('Y' << 8) | ('V')), /**< YUYV/YUY2 (4:2:2) */ cudaVideoCodec_UYVY = (('U' << 24) | ('Y' << 16) | ('V' << 8) | ('Y')) /**< UYVY (4:2:2) */ } cudaVideoCodec; /*********************************************************************************/ //! \enum cudaVideoSurfaceFormat //! Video surface format enums used for output format of decoded output //! These enums are used in CUVIDDECODECREATEINFO structure /*********************************************************************************/ typedef enum cudaVideoSurfaceFormat_enum { cudaVideoSurfaceFormat_NV12 = 0, /**< Semi-Planar YUV [Y plane followed by interleaved UV plane] */ cudaVideoSurfaceFormat_P016 = 1, /**< 16 bit Semi-Planar YUV [Y plane followed by interleaved UV plane]. Can be used for 10 bit(6LSB bits 0), 12 bit (4LSB bits 0) */ cudaVideoSurfaceFormat_YUV444 = 2, /**< Planar YUV [Y plane followed by U and V planes] */ cudaVideoSurfaceFormat_YUV444_16Bit = 3, /**< 16 bit Planar YUV [Y plane followed by U and V planes]. Can be used for 10 bit(6LSB bits 0), 12 bit (4LSB bits 0) */ } cudaVideoSurfaceFormat; /******************************************************************************************************************/ //! \enum cudaVideoDeinterlaceMode //! Deinterlacing mode enums //! These enums are used in CUVIDDECODECREATEINFO structure //! Use cudaVideoDeinterlaceMode_Weave for progressive content and for content that doesn't need deinterlacing //! cudaVideoDeinterlaceMode_Adaptive needs more video memory than other DImodes /******************************************************************************************************************/ typedef enum cudaVideoDeinterlaceMode_enum { cudaVideoDeinterlaceMode_Weave = 0, /**< Weave both fields (no deinterlacing) */ cudaVideoDeinterlaceMode_Bob, /**< Drop one field */ cudaVideoDeinterlaceMode_Adaptive /**< Adaptive deinterlacing */ } cudaVideoDeinterlaceMode; /**************************************************************************************************************/ //! \enum cudaVideoChromaFormat //! Chroma format enums //! These enums are used in CUVIDDECODECREATEINFO and CUVIDDECODECAPS structures /**************************************************************************************************************/ typedef enum cudaVideoChromaFormat_enum { cudaVideoChromaFormat_Monochrome = 0, /**< MonoChrome */ cudaVideoChromaFormat_420, /**< YUV 4:2:0 */ cudaVideoChromaFormat_422, /**< YUV 4:2:2 */ cudaVideoChromaFormat_444 /**< YUV 4:4:4 */ } cudaVideoChromaFormat; /*************************************************************************************************************/ //! \enum cudaVideoCreateFlags //! Decoder flag enums to select preferred decode path //! cudaVideoCreate_Default and cudaVideoCreate_PreferCUVID are most optimized, use these whenever possible /*************************************************************************************************************/ typedef enum cudaVideoCreateFlags_enum { cudaVideoCreate_Default = 0x00, /**< Default operation mode: use dedicated video engines */ cudaVideoCreate_PreferCUDA = 0x01, /**< Use CUDA-based decoder (requires valid vidLock object for multi-threading) */ cudaVideoCreate_PreferDXVA = 0x02, /**< Go through DXVA internally if possible (requires D3D9 interop) */ cudaVideoCreate_PreferCUVID = 0x04 /**< Use dedicated video engines directly */ } cudaVideoCreateFlags; /*************************************************************************/ //! \enum cuvidDecodeStatus //! Decode status enums //! These enums are used in CUVIDGETDECODESTATUS structure /*************************************************************************/ typedef enum cuvidDecodeStatus_enum { cuvidDecodeStatus_Invalid = 0, // Decode status is not valid cuvidDecodeStatus_InProgress = 1, // Decode is in progress cuvidDecodeStatus_Success = 2, // Decode is completed without any errors // 3 to 7 enums are reserved for future use cuvidDecodeStatus_Error = 8, // Decode is completed with an error (error is not concealed) cuvidDecodeStatus_Error_Concealed = 9, // Decode is completed with an error and error is concealed } cuvidDecodeStatus; /**************************************************************************************************************/ //! \struct CUVIDDECODECAPS; //! This structure is used in cuvidGetDecoderCaps API /**************************************************************************************************************/ typedef struct _CUVIDDECODECAPS { cudaVideoCodec eCodecType; /**< IN: cudaVideoCodec_XXX */ cudaVideoChromaFormat eChromaFormat; /**< IN: cudaVideoChromaFormat_XXX */ unsigned int nBitDepthMinus8; /**< IN: The Value "BitDepth minus 8" */ unsigned int reserved1[3]; /**< Reserved for future use - set to zero */ unsigned char bIsSupported; /**< OUT: 1 if codec supported, 0 if not supported */ unsigned char nNumNVDECs; /**< OUT: Number of NVDECs that can support IN params */ unsigned short nOutputFormatMask; /**< OUT: each bit represents corresponding cudaVideoSurfaceFormat enum */ unsigned int nMaxWidth; /**< OUT: Max supported coded width in pixels */ unsigned int nMaxHeight; /**< OUT: Max supported coded height in pixels */ unsigned int nMaxMBCount; /**< OUT: Max supported macroblock count CodedWidth*CodedHeight/256 must be <= nMaxMBCount */ unsigned short nMinWidth; /**< OUT: Min supported coded width in pixels */ unsigned short nMinHeight; /**< OUT: Min supported coded height in pixels */ unsigned char bIsHistogramSupported; /**< OUT: 1 if Y component histogram output is supported, 0 if not Note: histogram is computed on original picture data before any post-processing like scaling, cropping, etc. is applied */ unsigned char nCounterBitDepth; /**< OUT: histogram counter bit depth */ unsigned short nMaxHistogramBins; /**< OUT: Max number of histogram bins */ unsigned int reserved3[10]; /**< Reserved for future use - set to zero */ } CUVIDDECODECAPS; /**************************************************************************************************************/ //! \struct CUVIDDECODECREATEINFO //! This structure is used in cuvidCreateDecoder API /**************************************************************************************************************/ typedef struct _CUVIDDECODECREATEINFO { unsigned long ulWidth; /**< IN: Coded sequence width in pixels */ unsigned long ulHeight; /**< IN: Coded sequence height in pixels */ unsigned long ulNumDecodeSurfaces; /**< IN: Maximum number of internal decode surfaces */ cudaVideoCodec CodecType; /**< IN: cudaVideoCodec_XXX */ cudaVideoChromaFormat ChromaFormat; /**< IN: cudaVideoChromaFormat_XXX */ unsigned long ulCreationFlags; /**< IN: Decoder creation flags (cudaVideoCreateFlags_XXX) */ unsigned long bitDepthMinus8; /**< IN: The value "BitDepth minus 8" */ unsigned long ulIntraDecodeOnly; /**< IN: Set 1 only if video has all intra frames (default value is 0). This will optimize video memory for Intra frames only decoding. The support is limited to specific codecs - H264, HEVC, VP9, the flag will be ignored for codecs which are not supported. However decoding might fail if the flag is enabled in case of supported codecs for regular bit streams having P and/or B frames. */ unsigned long ulMaxWidth; /**< IN: Coded sequence max width in pixels used with reconfigure Decoder */ unsigned long ulMaxHeight; /**< IN: Coded sequence max height in pixels used with reconfigure Decoder */ unsigned long Reserved1; /**< Reserved for future use - set to zero */ /** * IN: area of the frame that should be displayed */ struct { short left; short top; short right; short bottom; } display_area; cudaVideoSurfaceFormat OutputFormat; /**< IN: cudaVideoSurfaceFormat_XXX */ cudaVideoDeinterlaceMode DeinterlaceMode; /**< IN: cudaVideoDeinterlaceMode_XXX */ unsigned long ulTargetWidth; /**< IN: Post-processed output width (Should be aligned to 2) */ unsigned long ulTargetHeight; /**< IN: Post-processed output height (Should be aligned to 2) */ unsigned long ulNumOutputSurfaces; /**< IN: Maximum number of output surfaces simultaneously mapped */ CUvideoctxlock vidLock; /**< IN: If non-NULL, context lock used for synchronizing ownership of the cuda context. Needed for cudaVideoCreate_PreferCUDA decode */ /** * IN: target rectangle in the output frame (for aspect ratio conversion) * if a null rectangle is specified, {0,0,ulTargetWidth,ulTargetHeight} will be used */ struct { short left; short top; short right; short bottom; } target_rect; unsigned long enableHistogram; /**< IN: enable histogram output, if supported */ unsigned long Reserved2[4]; /**< Reserved for future use - set to zero */ } CUVIDDECODECREATEINFO; /*********************************************************/ //! \struct CUVIDH264DPBENTRY //! H.264 DPB entry //! This structure is used in CUVIDH264PICPARAMS structure /*********************************************************/ typedef struct _CUVIDH264DPBENTRY { int PicIdx; /**< picture index of reference frame */ int FrameIdx; /**< frame_num(short-term) or LongTermFrameIdx(long-term) */ int is_long_term; /**< 0=short term reference, 1=long term reference */ int not_existing; /**< non-existing reference frame (corresponding PicIdx should be set to -1) */ int used_for_reference; /**< 0=unused, 1=top_field, 2=bottom_field, 3=both_fields */ int FieldOrderCnt[2]; /**< field order count of top and bottom fields */ } CUVIDH264DPBENTRY; /************************************************************/ //! \struct CUVIDH264MVCEXT //! H.264 MVC picture parameters ext //! This structure is used in CUVIDH264PICPARAMS structure /************************************************************/ typedef struct _CUVIDH264MVCEXT { int num_views_minus1; /**< Max number of coded views minus 1 in video : Range - 0 to 1023 */ int view_id; /**< view identifier */ unsigned char inter_view_flag; /**< 1 if used for inter-view prediction, 0 if not */ unsigned char num_inter_view_refs_l0; /**< number of inter-view ref pics in RefPicList0 */ unsigned char num_inter_view_refs_l1; /**< number of inter-view ref pics in RefPicList1 */ unsigned char MVCReserved8Bits; /**< Reserved bits */ int InterViewRefsL0[16]; /**< view id of the i-th view component for inter-view prediction in RefPicList0 */ int InterViewRefsL1[16]; /**< view id of the i-th view component for inter-view prediction in RefPicList1 */ } CUVIDH264MVCEXT; /*********************************************************/ //! \struct CUVIDH264SVCEXT //! H.264 SVC picture parameters ext //! This structure is used in CUVIDH264PICPARAMS structure /*********************************************************/ typedef struct _CUVIDH264SVCEXT { unsigned char profile_idc; unsigned char level_idc; unsigned char DQId; unsigned char DQIdMax; unsigned char disable_inter_layer_deblocking_filter_idc; unsigned char ref_layer_chroma_phase_y_plus1; signed char inter_layer_slice_alpha_c0_offset_div2; signed char inter_layer_slice_beta_offset_div2; unsigned short DPBEntryValidFlag; unsigned char inter_layer_deblocking_filter_control_present_flag; unsigned char extended_spatial_scalability_idc; unsigned char adaptive_tcoeff_level_prediction_flag; unsigned char slice_header_restriction_flag; unsigned char chroma_phase_x_plus1_flag; unsigned char chroma_phase_y_plus1; unsigned char tcoeff_level_prediction_flag; unsigned char constrained_intra_resampling_flag; unsigned char ref_layer_chroma_phase_x_plus1_flag; unsigned char store_ref_base_pic_flag; unsigned char Reserved8BitsA; unsigned char Reserved8BitsB; short scaled_ref_layer_left_offset; short scaled_ref_layer_top_offset; short scaled_ref_layer_right_offset; short scaled_ref_layer_bottom_offset; unsigned short Reserved16Bits; struct _CUVIDPICPARAMS *pNextLayer; /**< Points to the picparams for the next layer to be decoded. Linked list ends at the target layer. */ int bRefBaseLayer; /**< whether to store ref base pic */ } CUVIDH264SVCEXT; /******************************************************/ //! \struct CUVIDH264PICPARAMS //! H.264 picture parameters //! This structure is used in CUVIDPICPARAMS structure /******************************************************/ typedef struct _CUVIDH264PICPARAMS { // SPS int log2_max_frame_num_minus4; int pic_order_cnt_type; int log2_max_pic_order_cnt_lsb_minus4; int delta_pic_order_always_zero_flag; int frame_mbs_only_flag; int direct_8x8_inference_flag; int num_ref_frames; // NOTE: shall meet level 4.1 restrictions unsigned char residual_colour_transform_flag; unsigned char bit_depth_luma_minus8; // Must be 0 (only 8-bit supported) unsigned char bit_depth_chroma_minus8; // Must be 0 (only 8-bit supported) unsigned char qpprime_y_zero_transform_bypass_flag; // PPS int entropy_coding_mode_flag; int pic_order_present_flag; int num_ref_idx_l0_active_minus1; int num_ref_idx_l1_active_minus1; int weighted_pred_flag; int weighted_bipred_idc; int pic_init_qp_minus26; int deblocking_filter_control_present_flag; int redundant_pic_cnt_present_flag; int transform_8x8_mode_flag; int MbaffFrameFlag; int constrained_intra_pred_flag; int chroma_qp_index_offset; int second_chroma_qp_index_offset; int ref_pic_flag; int frame_num; int CurrFieldOrderCnt[2]; // DPB CUVIDH264DPBENTRY dpb[16]; // List of reference frames within the DPB // Quantization Matrices (raster-order) unsigned char WeightScale4x4[6][16]; unsigned char WeightScale8x8[2][64]; // FMO/ASO unsigned char fmo_aso_enable; unsigned char num_slice_groups_minus1; unsigned char slice_group_map_type; signed char pic_init_qs_minus26; unsigned int slice_group_change_rate_minus1; union { unsigned long long slice_group_map_addr; const unsigned char *pMb2SliceGroupMap; } fmo; unsigned int Reserved[12]; // SVC/MVC union { CUVIDH264MVCEXT mvcext; CUVIDH264SVCEXT svcext; }; } CUVIDH264PICPARAMS; /********************************************************/ //! \struct CUVIDMPEG2PICPARAMS //! MPEG-2 picture parameters //! This structure is used in CUVIDPICPARAMS structure /********************************************************/ typedef struct _CUVIDMPEG2PICPARAMS { int ForwardRefIdx; // Picture index of forward reference (P/B-frames) int BackwardRefIdx; // Picture index of backward reference (B-frames) int picture_coding_type; int full_pel_forward_vector; int full_pel_backward_vector; int f_code[2][2]; int intra_dc_precision; int frame_pred_frame_dct; int concealment_motion_vectors; int q_scale_type; int intra_vlc_format; int alternate_scan; int top_field_first; // Quantization matrices (raster order) unsigned char QuantMatrixIntra[64]; unsigned char QuantMatrixInter[64]; } CUVIDMPEG2PICPARAMS; // MPEG-4 has VOP types instead of Picture types #define I_VOP 0 #define P_VOP 1 #define B_VOP 2 #define S_VOP 3 /*******************************************************/ //! \struct CUVIDMPEG4PICPARAMS //! MPEG-4 picture parameters //! This structure is used in CUVIDPICPARAMS structure /*******************************************************/ typedef struct _CUVIDMPEG4PICPARAMS { int ForwardRefIdx; // Picture index of forward reference (P/B-frames) int BackwardRefIdx; // Picture index of backward reference (B-frames) // VOL int video_object_layer_width; int video_object_layer_height; int vop_time_increment_bitcount; int top_field_first; int resync_marker_disable; int quant_type; int quarter_sample; int short_video_header; int divx_flags; // VOP int vop_coding_type; int vop_coded; int vop_rounding_type; int alternate_vertical_scan_flag; int interlaced; int vop_fcode_forward; int vop_fcode_backward; int trd[2]; int trb[2]; // Quantization matrices (raster order) unsigned char QuantMatrixIntra[64]; unsigned char QuantMatrixInter[64]; int gmc_enabled; } CUVIDMPEG4PICPARAMS; /********************************************************/ //! \struct CUVIDVC1PICPARAMS //! VC1 picture parameters //! This structure is used in CUVIDPICPARAMS structure /********************************************************/ typedef struct _CUVIDVC1PICPARAMS { int ForwardRefIdx; /**< Picture index of forward reference (P/B-frames) */ int BackwardRefIdx; /**< Picture index of backward reference (B-frames) */ int FrameWidth; /**< Actual frame width */ int FrameHeight; /**< Actual frame height */ // PICTURE int intra_pic_flag; /**< Set to 1 for I,BI frames */ int ref_pic_flag; /**< Set to 1 for I,P frames */ int progressive_fcm; /**< Progressive frame */ // SEQUENCE int profile; int postprocflag; int pulldown; int interlace; int tfcntrflag; int finterpflag; int psf; int multires; int syncmarker; int rangered; int maxbframes; // ENTRYPOINT int panscan_flag; int refdist_flag; int extended_mv; int dquant; int vstransform; int loopfilter; int fastuvmc; int overlap; int quantizer; int extended_dmv; int range_mapy_flag; int range_mapy; int range_mapuv_flag; int range_mapuv; int rangeredfrm; // range reduction state } CUVIDVC1PICPARAMS; /***********************************************************/ //! \struct CUVIDJPEGPICPARAMS //! JPEG picture parameters //! This structure is used in CUVIDPICPARAMS structure /***********************************************************/ typedef struct _CUVIDJPEGPICPARAMS { int Reserved; } CUVIDJPEGPICPARAMS; /*******************************************************/ //! \struct CUVIDHEVCPICPARAMS //! HEVC picture parameters //! This structure is used in CUVIDPICPARAMS structure /*******************************************************/ typedef struct _CUVIDHEVCPICPARAMS { // sps int pic_width_in_luma_samples; int pic_height_in_luma_samples; unsigned char log2_min_luma_coding_block_size_minus3; unsigned char log2_diff_max_min_luma_coding_block_size; unsigned char log2_min_transform_block_size_minus2; unsigned char log2_diff_max_min_transform_block_size; unsigned char pcm_enabled_flag; unsigned char log2_min_pcm_luma_coding_block_size_minus3; unsigned char log2_diff_max_min_pcm_luma_coding_block_size; unsigned char pcm_sample_bit_depth_luma_minus1; unsigned char pcm_sample_bit_depth_chroma_minus1; unsigned char pcm_loop_filter_disabled_flag; unsigned char strong_intra_smoothing_enabled_flag; unsigned char max_transform_hierarchy_depth_intra; unsigned char max_transform_hierarchy_depth_inter; unsigned char amp_enabled_flag; unsigned char separate_colour_plane_flag; unsigned char log2_max_pic_order_cnt_lsb_minus4; unsigned char num_short_term_ref_pic_sets; unsigned char long_term_ref_pics_present_flag; unsigned char num_long_term_ref_pics_sps; unsigned char sps_temporal_mvp_enabled_flag; unsigned char sample_adaptive_offset_enabled_flag; unsigned char scaling_list_enable_flag; unsigned char IrapPicFlag; unsigned char IdrPicFlag; unsigned char bit_depth_luma_minus8; unsigned char bit_depth_chroma_minus8; // sps/pps extension fields unsigned char log2_max_transform_skip_block_size_minus2; unsigned char log2_sao_offset_scale_luma; unsigned char log2_sao_offset_scale_chroma; unsigned char high_precision_offsets_enabled_flag; unsigned char reserved1[10]; // pps unsigned char dependent_slice_segments_enabled_flag; unsigned char slice_segment_header_extension_present_flag; unsigned char sign_data_hiding_enabled_flag; unsigned char cu_qp_delta_enabled_flag; unsigned char diff_cu_qp_delta_depth; signed char init_qp_minus26; signed char pps_cb_qp_offset; signed char pps_cr_qp_offset; unsigned char constrained_intra_pred_flag; unsigned char weighted_pred_flag; unsigned char weighted_bipred_flag; unsigned char transform_skip_enabled_flag; unsigned char transquant_bypass_enabled_flag; unsigned char entropy_coding_sync_enabled_flag; unsigned char log2_parallel_merge_level_minus2; unsigned char num_extra_slice_header_bits; unsigned char loop_filter_across_tiles_enabled_flag; unsigned char loop_filter_across_slices_enabled_flag; unsigned char output_flag_present_flag; unsigned char num_ref_idx_l0_default_active_minus1; unsigned char num_ref_idx_l1_default_active_minus1; unsigned char lists_modification_present_flag; unsigned char cabac_init_present_flag; unsigned char pps_slice_chroma_qp_offsets_present_flag; unsigned char deblocking_filter_override_enabled_flag; unsigned char pps_deblocking_filter_disabled_flag; signed char pps_beta_offset_div2; signed char pps_tc_offset_div2; unsigned char tiles_enabled_flag; unsigned char uniform_spacing_flag; unsigned char num_tile_columns_minus1; unsigned char num_tile_rows_minus1; unsigned short column_width_minus1[21]; unsigned short row_height_minus1[21]; // sps and pps extension HEVC-main 444 unsigned char sps_range_extension_flag; unsigned char transform_skip_rotation_enabled_flag; unsigned char transform_skip_context_enabled_flag; unsigned char implicit_rdpcm_enabled_flag; unsigned char explicit_rdpcm_enabled_flag; unsigned char extended_precision_processing_flag; unsigned char intra_smoothing_disabled_flag; unsigned char persistent_rice_adaptation_enabled_flag; unsigned char cabac_bypass_alignment_enabled_flag; unsigned char pps_range_extension_flag; unsigned char cross_component_prediction_enabled_flag; unsigned char chroma_qp_offset_list_enabled_flag; unsigned char diff_cu_chroma_qp_offset_depth; unsigned char chroma_qp_offset_list_len_minus1; signed char cb_qp_offset_list[6]; signed char cr_qp_offset_list[6]; unsigned char reserved2[2]; unsigned int reserved3[8]; // RefPicSets int NumBitsForShortTermRPSInSlice; int NumDeltaPocsOfRefRpsIdx; int NumPocTotalCurr; int NumPocStCurrBefore; int NumPocStCurrAfter; int NumPocLtCurr; int CurrPicOrderCntVal; int RefPicIdx[16]; // [refpic] Indices of valid reference pictures (-1 if unused for reference) int PicOrderCntVal[16]; // [refpic] unsigned char IsLongTerm[16]; // [refpic] 0=not a long-term reference, 1=long-term reference unsigned char RefPicSetStCurrBefore[8]; // [0..NumPocStCurrBefore-1] -> refpic (0..15) unsigned char RefPicSetStCurrAfter[8]; // [0..NumPocStCurrAfter-1] -> refpic (0..15) unsigned char RefPicSetLtCurr[8]; // [0..NumPocLtCurr-1] -> refpic (0..15) unsigned char RefPicSetInterLayer0[8]; unsigned char RefPicSetInterLayer1[8]; unsigned int reserved4[12]; // scaling lists (diag order) unsigned char ScalingList4x4[6][16]; // [matrixId][i] unsigned char ScalingList8x8[6][64]; // [matrixId][i] unsigned char ScalingList16x16[6][64]; // [matrixId][i] unsigned char ScalingList32x32[2][64]; // [matrixId][i] unsigned char ScalingListDCCoeff16x16[6]; // [matrixId] unsigned char ScalingListDCCoeff32x32[2]; // [matrixId] } CUVIDHEVCPICPARAMS; /***********************************************************/ //! \struct CUVIDVP8PICPARAMS //! VP8 picture parameters //! This structure is used in CUVIDPICPARAMS structure /***********************************************************/ typedef struct _CUVIDVP8PICPARAMS { int width; int height; unsigned int first_partition_size; // Frame Indexes unsigned char LastRefIdx; unsigned char GoldenRefIdx; unsigned char AltRefIdx; union { struct { unsigned char frame_type : 1; /**< 0 = KEYFRAME, 1 = INTERFRAME */ unsigned char version : 3; unsigned char show_frame : 1; unsigned char update_mb_segmentation_data : 1; /**< Must be 0 if segmentation is not enabled */ unsigned char Reserved2Bits : 2; } vp8_frame_tag; unsigned char wFrameTagFlags; }; unsigned char Reserved1[4]; unsigned int Reserved2[3]; } CUVIDVP8PICPARAMS; /***********************************************************/ //! \struct CUVIDVP9PICPARAMS //! VP9 picture parameters //! This structure is used in CUVIDPICPARAMS structure /***********************************************************/ typedef struct _CUVIDVP9PICPARAMS { unsigned int width; unsigned int height; // Frame Indices unsigned char LastRefIdx; unsigned char GoldenRefIdx; unsigned char AltRefIdx; unsigned char colorSpace; unsigned short profile : 3; unsigned short frameContextIdx : 2; unsigned short frameType : 1; unsigned short showFrame : 1; unsigned short errorResilient : 1; unsigned short frameParallelDecoding : 1; unsigned short subSamplingX : 1; unsigned short subSamplingY : 1; unsigned short intraOnly : 1; unsigned short allow_high_precision_mv : 1; unsigned short refreshEntropyProbs : 1; unsigned short reserved2Bits : 2; unsigned short reserved16Bits; unsigned char refFrameSignBias[4]; unsigned char bitDepthMinus8Luma; unsigned char bitDepthMinus8Chroma; unsigned char loopFilterLevel; unsigned char loopFilterSharpness; unsigned char modeRefLfEnabled; unsigned char log2_tile_columns; unsigned char log2_tile_rows; unsigned char segmentEnabled : 1; unsigned char segmentMapUpdate : 1; unsigned char segmentMapTemporalUpdate : 1; unsigned char segmentFeatureMode : 1; unsigned char reserved4Bits : 4; unsigned char segmentFeatureEnable[8][4]; short segmentFeatureData[8][4]; unsigned char mb_segment_tree_probs[7]; unsigned char segment_pred_probs[3]; unsigned char reservedSegment16Bits[2]; int qpYAc; int qpYDc; int qpChDc; int qpChAc; unsigned int activeRefIdx[3]; unsigned int resetFrameContext; unsigned int mcomp_filter_type; unsigned int mbRefLfDelta[4]; unsigned int mbModeLfDelta[2]; unsigned int frameTagSize; unsigned int offsetToDctParts; unsigned int reserved128Bits[4]; } CUVIDVP9PICPARAMS; /***********************************************************/ //! \struct CUVIDAV1PICPARAMS //! AV1 picture parameters //! This structure is used in CUVIDPICPARAMS structure /***********************************************************/ typedef struct _CUVIDAV1PICPARAMS { unsigned int width; // coded width, if superres enabled then it is upscaled width unsigned int height; // coded height unsigned int frame_offset; // defined as order_hint in AV1 specification int decodePicIdx; // decoded output pic index, if film grain enabled, it will keep decoded (without film grain) // output It can be used as reference frame for future frames // sequence header unsigned int profile : 3; // 0 = profile0, 1 = profile1, 2 = profile2 unsigned int use_128x128_superblock : 1; // superblock size 0:64x64, 1: 128x128 unsigned int subsampling_x : 1; // (subsampling_x, _y) 1,1 = 420, 1,0 = 422, 0,0 = 444 unsigned int subsampling_y : 1; unsigned int mono_chrome : 1; // for monochrome content, mono_chrome = 1 and (subsampling_x, _y) should be 1,1 unsigned int bit_depth_minus8 : 4; // bit depth minus 8 unsigned int enable_filter_intra : 1; // tool enable in seq level, 0 : disable 1: frame header control unsigned int enable_intra_edge_filter : 1; // intra edge filtering process, 0 : disable 1: enabled unsigned int enable_interintra_compound : 1; // interintra, 0 : not present 1: present unsigned int enable_masked_compound : 1; // 1: mode info for inter blocks may contain the syntax element // compound_type. 0: syntax element compound_type will not be present unsigned int enable_dual_filter : 1; // vertical and horiz filter selection, 1: enable and 0: disable unsigned int enable_order_hint : 1; // order hint, and related tools, 1: enable and 0: disable unsigned int order_hint_bits_minus1 : 3; // is used to compute OrderHintBits unsigned int enable_jnt_comp : 1; // joint compound modes, 1: enable and 0: disable unsigned int enable_superres : 1; // superres in seq level, 0 : disable 1: frame level control unsigned int enable_cdef : 1; // cdef filtering in seq level, 0 : disable 1: frame level control unsigned int enable_restoration : 1; // loop restoration filtering in seq level, 0 : disable 1: frame level control unsigned int enable_fgs : 1; // defined as film_grain_params_present in AV1 specification unsigned int reserved0_7bits : 7; // reserved bits; must be set to 0 // frame header unsigned int frame_type : 2; // 0:Key frame, 1:Inter frame, 2:intra only, 3:s-frame unsigned int show_frame : 1; // show_frame = 1 implies that frame should be immediately output once decoded unsigned int disable_cdf_update : 1; // CDF update during symbol decoding, 1: disabled, 0: enabled unsigned int allow_screen_content_tools : 1; // 1: intra blocks may use palette encoding, 0: palette encoding is // never used unsigned int force_integer_mv : 1; // 1: motion vectors will always be integers, 0: can contain fractional bits unsigned int coded_denom : 3; // coded_denom of the superres scale as specified in AV1 specification unsigned int allow_intrabc : 1; // 1: intra block copy may be used, 0: intra block copy is not allowed unsigned int allow_high_precision_mv : 1; // 1/8 precision mv enable unsigned int interp_filter : 3; // interpolation filter. Refer to section 6.8.9 of the AV1 specification // Version 1.0.0 with Errata 1 unsigned int switchable_motion_mode : 1; // defined as is_motion_mode_switchable in AV1 specification unsigned int use_ref_frame_mvs : 1; // 1: current frame can use the previous frame mv information, 0: will not use. unsigned int disable_frame_end_update_cdf : 1; // 1: indicates that the end of frame CDF update is disabled unsigned int delta_q_present : 1; // quantizer index delta values are present in the block level unsigned int delta_q_res : 2; // left shift which should be applied to decoded quantizer index delta values unsigned int using_qmatrix : 1; // 1: quantizer matrix will be used to compute quantizers unsigned int coded_lossless : 1; // 1: all segments use lossless coding unsigned int use_superres : 1; // 1: superres enabled for frame unsigned int tx_mode : 2; // 0: ONLY4x4,1:LARGEST,2:SELECT unsigned int reference_mode : 1; // 0: SINGLE, 1: SELECT unsigned int allow_warped_motion : 1; // 1: allow_warped_motion may be present, 0: allow_warped_motion will not // be present unsigned int reduced_tx_set : 1; // 1: frame is restricted to subset of the full set of transform types, 0: no // such restriction unsigned int skip_mode : 1; // 1: most of the mode info is skipped, 0: mode info is not skipped unsigned int reserved1_3bits : 3; // reserved bits; must be set to 0 // tiling info unsigned int num_tile_cols : 8; // number of tiles across the frame., max is 64 unsigned int num_tile_rows : 8; // number of tiles down the frame., max is 64 unsigned int context_update_tile_id : 16; // specifies which tile to use for the CDF update unsigned short tile_widths[64]; // Width of each column in superblocks unsigned short tile_heights[64]; // height of each row in superblocks // CDEF - refer to section 6.10.14 of the AV1 specification Version 1.0.0 with Errata 1 unsigned char cdef_damping_minus_3 : 2; // controls the amount of damping in the deringing filter unsigned char cdef_bits : 2; // the number of bits needed to specify which CDEF filter to apply unsigned char reserved2_4bits : 4; // reserved bits; must be set to 0 unsigned char cdef_y_strength[8]; // 0-3 bits: y_pri_strength, 4-7 bits y_sec_strength unsigned char cdef_uv_strength[8]; // 0-3 bits: uv_pri_strength, 4-7 bits uv_sec_strength // SkipModeFrames unsigned char SkipModeFrame0 : 4; // specifies the frames to use for compound prediction when skip_mode is equal to 1. unsigned char SkipModeFrame1 : 4; // qp information - refer to section 6.8.11 of the AV1 specification Version 1.0.0 with Errata 1 unsigned char base_qindex; // indicates the base frame qindex. Defined as base_q_idx in AV1 specification char qp_y_dc_delta_q; // indicates the Y DC quantizer relative to base_q_idx. Defined as DeltaQYDc in AV1 // specification char qp_u_dc_delta_q; // indicates the U DC quantizer relative to base_q_idx. Defined as DeltaQUDc in AV1 // specification char qp_v_dc_delta_q; // indicates the V DC quantizer relative to base_q_idx. Defined as DeltaQVDc in AV1 // specification char qp_u_ac_delta_q; // indicates the U AC quantizer relative to base_q_idx. Defined as DeltaQUAc in AV1 // specification char qp_v_ac_delta_q; // indicates the V AC quantizer relative to base_q_idx. Defined as DeltaQVAc in AV1 // specification unsigned char qm_y; // specifies the level in the quantizer matrix that should be used for luma plane decoding unsigned char qm_u; // specifies the level in the quantizer matrix that should be used for chroma U plane decoding unsigned char qm_v; // specifies the level in the quantizer matrix that should be used for chroma V plane decoding // segmentation - refer to section 6.8.13 of the AV1 specification Version 1.0.0 with Errata 1 unsigned char segmentation_enabled : 1; // 1 indicates that this frame makes use of the segmentation tool unsigned char segmentation_update_map : 1; // 1 indicates that the segmentation map are updated during the // decoding of this frame unsigned char segmentation_update_data : 1; // 1 indicates that new parameters are about to be specified for each segment unsigned char segmentation_temporal_update : 1; // 1 indicates that the updates to the segmentation map are // coded relative to the existing segmentation map unsigned char reserved3_4bits : 4; // reserved bits; must be set to 0 short segmentation_feature_data[8][8]; // specifies the feature data for a segment feature unsigned char segmentation_feature_mask[8]; // indicates that the corresponding feature is unused or feature // value is coded // loopfilter - refer to section 6.8.10 of the AV1 specification Version 1.0.0 with Errata 1 unsigned char loop_filter_level[2]; // contains loop filter strength values unsigned char loop_filter_level_u; // loop filter strength value of U plane unsigned char loop_filter_level_v; // loop filter strength value of V plane unsigned char loop_filter_sharpness; // indicates the sharpness level char loop_filter_ref_deltas[8]; // contains the adjustment needed for the filter level based on the chosen // reference frame char loop_filter_mode_deltas[2]; // contains the adjustment needed for the filter level based on the chosen mode unsigned char loop_filter_delta_enabled : 1; // indicates that the filter level depends on the mode and // reference frame used to predict a block unsigned char loop_filter_delta_update : 1; // indicates that additional syntax elements are present that // specify which mode and reference frame deltas are to be updated unsigned char delta_lf_present : 1; // specifies whether loop filter delta values are present in the block level unsigned char delta_lf_res : 2; // specifies the left shift to apply to the decoded loop filter values unsigned char delta_lf_multi : 1; // separate loop filter deltas for Hy,Vy,U,V edges unsigned char reserved4_2bits : 2; // reserved bits; must be set to 0 // restoration - refer to section 6.10.15 of the AV1 specification Version 1.0.0 with Errata 1 unsigned char lr_unit_size[3]; // specifies the size of loop restoration units: 0: 32, 1: 64, 2: 128, 3: 256 unsigned char lr_type[3]; // used to compute FrameRestorationType // reference frames unsigned char primary_ref_frame; // specifies which reference frame contains the CDF values and other state that // should be loaded at the start of the frame unsigned char ref_frame_map[8]; // frames in dpb that can be used as reference for current or future frames unsigned char temporal_layer_id : 4; // temporal layer id unsigned char spatial_layer_id : 4; // spatial layer id unsigned char reserved5_32bits[4]; // reserved bits; must be set to 0 // ref frame list struct { unsigned int width; unsigned int height; unsigned char index; unsigned char reserved24Bits[3]; // reserved bits; must be set to 0 } ref_frame[7]; // frames used as reference frame for current frame. // global motion struct { unsigned char invalid : 1; unsigned char wmtype : 2; // defined as GmType in AV1 specification unsigned char reserved5Bits : 5; // reserved bits; must be set to 0 char reserved24Bits[3]; // reserved bits; must be set to 0 int wmmat[6]; // defined as gm_params[] in AV1 specification } global_motion[7]; // global motion params for reference frames // film grain params - refer to section 6.8.20 of the AV1 specification Version 1.0.0 with Errata 1 unsigned short apply_grain : 1; unsigned short overlap_flag : 1; unsigned short scaling_shift_minus8 : 2; unsigned short chroma_scaling_from_luma : 1; unsigned short ar_coeff_lag : 2; unsigned short ar_coeff_shift_minus6 : 2; unsigned short grain_scale_shift : 2; unsigned short clip_to_restricted_range : 1; unsigned short reserved6_4bits : 4; // reserved bits; must be set to 0 unsigned char num_y_points; unsigned char scaling_points_y[14][2]; unsigned char num_cb_points; unsigned char scaling_points_cb[10][2]; unsigned char num_cr_points; unsigned char scaling_points_cr[10][2]; unsigned char reserved7_8bits; // reserved bits; must be set to 0 unsigned short random_seed; short ar_coeffs_y[24]; short ar_coeffs_cb[25]; short ar_coeffs_cr[25]; unsigned char cb_mult; unsigned char cb_luma_mult; short cb_offset; unsigned char cr_mult; unsigned char cr_luma_mult; short cr_offset; int reserved[7]; // reserved bits; must be set to 0 } CUVIDAV1PICPARAMS; /******************************************************************************************/ //! \struct CUVIDPICPARAMS //! Picture parameters for decoding //! This structure is used in cuvidDecodePicture API //! IN for cuvidDecodePicture /******************************************************************************************/ typedef struct _CUVIDPICPARAMS { int PicWidthInMbs; /**< IN: Coded frame size in macroblocks */ int FrameHeightInMbs; /**< IN: Coded frame height in macroblocks */ int CurrPicIdx; /**< IN: Output index of the current picture */ int field_pic_flag; /**< IN: 0=frame picture, 1=field picture */ int bottom_field_flag; /**< IN: 0=top field, 1=bottom field (ignored if field_pic_flag=0) */ int second_field; /**< IN: Second field of a complementary field pair */ // Bitstream data unsigned int nBitstreamDataLen; /**< IN: Number of bytes in bitstream data buffer */ const unsigned char *pBitstreamData; /**< IN: Ptr to bitstream data for this picture (slice-layer) */ unsigned int nNumSlices; /**< IN: Number of slices in this picture */ const unsigned int *pSliceDataOffsets; /**< IN: nNumSlices entries, contains offset of each slice within the bitstream data buffer */ int ref_pic_flag; /**< IN: This picture is a reference picture */ int intra_pic_flag; /**< IN: This picture is entirely intra coded */ unsigned int Reserved[30]; /**< Reserved for future use */ // IN: Codec-specific data union { CUVIDMPEG2PICPARAMS mpeg2; /**< Also used for MPEG-1 */ CUVIDH264PICPARAMS h264; CUVIDVC1PICPARAMS vc1; CUVIDMPEG4PICPARAMS mpeg4; CUVIDJPEGPICPARAMS jpeg; CUVIDHEVCPICPARAMS hevc; CUVIDVP8PICPARAMS vp8; CUVIDVP9PICPARAMS vp9; CUVIDAV1PICPARAMS av1; unsigned int CodecReserved[1024]; } CodecSpecific; } CUVIDPICPARAMS; /******************************************************/ //! \struct CUVIDPROCPARAMS //! Picture parameters for postprocessing //! This structure is used in cuvidMapVideoFrame API /******************************************************/ typedef struct _CUVIDPROCPARAMS { int progressive_frame; /**< IN: Input is progressive (deinterlace_mode will be ignored) */ int second_field; /**< IN: Output the second field (ignored if deinterlace mode is Weave) */ int top_field_first; /**< IN: Input frame is top field first (1st field is top, 2nd field is bottom) */ int unpaired_field; /**< IN: Input only contains one field (2nd field is invalid) */ // The fields below are used for raw YUV input unsigned int reserved_flags; /**< Reserved for future use (set to zero) */ unsigned int reserved_zero; /**< Reserved (set to zero) */ unsigned long long raw_input_dptr; /**< IN: Input CUdeviceptr for raw YUV extensions */ unsigned int raw_input_pitch; /**< IN: pitch in bytes of raw YUV input (should be aligned appropriately) */ unsigned int raw_input_format; /**< IN: Input YUV format (cudaVideoCodec_enum) */ unsigned long long raw_output_dptr; /**< IN: Output CUdeviceptr for raw YUV extensions */ unsigned int raw_output_pitch; /**< IN: pitch in bytes of raw YUV output (should be aligned appropriately) */ unsigned int Reserved1; /**< Reserved for future use (set to zero) */ CUstream output_stream; /**< IN: stream object used by cuvidMapVideoFrame */ unsigned int Reserved[46]; /**< Reserved for future use (set to zero) */ unsigned long long *histogram_dptr; /**< OUT: Output CUdeviceptr for histogram extensions */ void *Reserved2[1]; /**< Reserved for future use (set to zero) */ } CUVIDPROCPARAMS; /*********************************************************************************************************/ //! \struct CUVIDGETDECODESTATUS //! Struct for reporting decode status. //! This structure is used in cuvidGetDecodeStatus API. /*********************************************************************************************************/ typedef struct _CUVIDGETDECODESTATUS { cuvidDecodeStatus decodeStatus; unsigned int reserved[31]; void *pReserved[8]; } CUVIDGETDECODESTATUS; /****************************************************/ //! \struct CUVIDRECONFIGUREDECODERINFO //! Struct for decoder reset //! This structure is used in cuvidReconfigureDecoder() API /****************************************************/ typedef struct _CUVIDRECONFIGUREDECODERINFO { unsigned int ulWidth; /**< IN: Coded sequence width in pixels, MUST be < = ulMaxWidth defined at CUVIDDECODECREATEINFO */ unsigned int ulHeight; /**< IN: Coded sequence height in pixels, MUST be < = ulMaxHeight defined at CUVIDDECODECREATEINFO */ unsigned int ulTargetWidth; /**< IN: Post processed output width */ unsigned int ulTargetHeight; /**< IN: Post Processed output height */ unsigned int ulNumDecodeSurfaces; /**< IN: Maximum number of internal decode surfaces */ unsigned int reserved1[12]; /**< Reserved for future use. Set to Zero */ /** * IN: Area of frame to be displayed. Use-case : Source Cropping */ struct { short left; short top; short right; short bottom; } display_area; /** * IN: Target Rectangle in the OutputFrame. Use-case : Aspect ratio Conversion */ struct { short left; short top; short right; short bottom; } target_rect; unsigned int reserved2[11]; /**< Reserved for future use. Set to Zero */ } CUVIDRECONFIGUREDECODERINFO; /***********************************************************************************************************/ //! VIDEO_DECODER //! //! In order to minimize decode latencies, there should be always at least 2 pictures in the decode //! queue at any time, in order to make sure that all decode engines are always busy. //! //! Overall data flow: //! - cuvidGetDecoderCaps(...) //! - cuvidCreateDecoder(...) //! - For each picture: //! + cuvidDecodePicture(N) //! + cuvidMapVideoFrame(N-4) //! + do some processing in cuda //! + cuvidUnmapVideoFrame(N-4) //! + cuvidDecodePicture(N+1) //! + cuvidMapVideoFrame(N-3) //! + ... //! - cuvidDestroyDecoder(...) //! //! NOTE: //! - When the cuda context is created from a D3D device, the D3D device must also be created //! with the D3DCREATE_MULTITHREADED flag. //! - There is a limit to how many pictures can be mapped simultaneously (ulNumOutputSurfaces) //! - cuvidDecodePicture may block the calling thread if there are too many pictures pending //! in the decode queue /***********************************************************************************************************/ /**********************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidGetDecoderCaps(CUVIDDECODECAPS *pdc) //! Queries decode capabilities of NVDEC-HW based on CodecType, ChromaFormat and BitDepthMinus8 parameters. //! 1. Application fills IN parameters CodecType, ChromaFormat and BitDepthMinus8 of CUVIDDECODECAPS structure //! 2. On calling cuvidGetDecoderCaps, driver fills OUT parameters if the IN parameters are supported //! If IN parameters passed to the driver are not supported by NVDEC-HW, then all OUT params are set to 0. //! E.g. on Geforce GTX 960: //! App fills - eCodecType = cudaVideoCodec_H264; eChromaFormat = cudaVideoChromaFormat_420; nBitDepthMinus8 = 0; //! Given IN parameters are supported, hence driver fills: bIsSupported = 1; nMinWidth = 48; nMinHeight = 16; //! nMaxWidth = 4096; nMaxHeight = 4096; nMaxMBCount = 65536; //! CodedWidth*CodedHeight/256 must be less than or equal to nMaxMBCount /**********************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidGetDecoderCaps(CUVIDDECODECAPS *pdc); /*****************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidCreateDecoder(CUvideodecoder *phDecoder, CUVIDDECODECREATEINFO *pdci) //! Create the decoder object based on pdci. A handle to the created decoder is returned /*****************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCreateDecoder(CUvideodecoder *phDecoder, CUVIDDECODECREATEINFO *pdci); /*****************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidDestroyDecoder(CUvideodecoder hDecoder) //! Destroy the decoder object /*****************************************************************************************************/ typedef CUresult CUDAAPI tcuvidDestroyDecoder(CUvideodecoder hDecoder); /*****************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidDecodePicture(CUvideodecoder hDecoder, CUVIDPICPARAMS *pPicParams) //! Decode a single picture (field or frame) //! Kicks off HW decoding /*****************************************************************************************************/ typedef CUresult CUDAAPI tcuvidDecodePicture(CUvideodecoder hDecoder, CUVIDPICPARAMS *pPicParams); /************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidGetDecodeStatus(CUvideodecoder hDecoder, int nPicIdx); //! Get the decode status for frame corresponding to nPicIdx //! API is supported for Maxwell and above generation GPUs. //! API is currently supported for HEVC, H264 and JPEG codecs. //! API returns CUDA_ERROR_NOT_SUPPORTED error code for unsupported GPU or codec. /************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidGetDecodeStatus(CUvideodecoder hDecoder, int nPicIdx, CUVIDGETDECODESTATUS *pDecodeStatus); /*********************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidReconfigureDecoder(CUvideodecoder hDecoder, CUVIDRECONFIGUREDECODERINFO //! *pDecReconfigParams) Used to reuse single decoder for multiple clips. Currently supports resolution change, //! resize params, display area params, target area params change for same codec. Must be called during //! CUVIDPARSERPARAMS::pfnSequenceCallback /*********************************************************************************************************/ typedef CUresult CUDAAPI tcuvidReconfigureDecoder(CUvideodecoder hDecoder, CUVIDRECONFIGUREDECODERINFO *pDecReconfigParams); #if !defined(__CUVID_DEVPTR64) || defined(__CUVID_INTERNAL) /************************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidMapVideoFrame(CUvideodecoder hDecoder, int nPicIdx, unsigned int *pDevPtr, //! unsigned int *pPitch, CUVIDPROCPARAMS *pVPP); //! Post-process and map video frame corresponding to nPicIdx for use in cuda. Returns cuda device pointer and //! associated pitch of the video frame /************************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidMapVideoFrame(CUvideodecoder hDecoder, int nPicIdx, unsigned int *pDevPtr, unsigned int *pPitch, CUVIDPROCPARAMS *pVPP); /*****************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidUnmapVideoFrame(CUvideodecoder hDecoder, unsigned int DevPtr) //! Unmap a previously mapped video frame /*****************************************************************************************************/ typedef CUresult CUDAAPI tcuvidUnmapVideoFrame(CUvideodecoder hDecoder, unsigned int DevPtr); #endif /****************************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidMapVideoFrame64(CUvideodecoder hDecoder, int nPicIdx, unsigned long long *pDevPtr, //! unsigned int * pPitch, CUVIDPROCPARAMS *pVPP); //! Post-process and map video frame corresponding to nPicIdx for use in cuda. Returns cuda device pointer and //! associated pitch of the video frame /****************************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidMapVideoFrame64(CUvideodecoder hDecoder, int nPicIdx, unsigned long long *pDevPtr, unsigned int *pPitch, CUVIDPROCPARAMS *pVPP); /**************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidUnmapVideoFrame64(CUvideodecoder hDecoder, unsigned long long DevPtr); //! Unmap a previously mapped video frame /**************************************************************************************************/ typedef CUresult CUDAAPI tcuvidUnmapVideoFrame64(CUvideodecoder hDecoder, unsigned long long DevPtr); #if defined(__CUVID_DEVPTR64) && !defined(__CUVID_INTERNAL) #define tcuvidMapVideoFrame tcuvidMapVideoFrame64 #define tcuvidUnmapVideoFrame tcuvidUnmapVideoFrame64 #endif /********************************************************************************************************************/ //! //! Context-locking: to facilitate multi-threaded implementations, the following 4 functions //! provide a simple mutex-style host synchronization. If a non-NULL context is specified //! in CUVIDDECODECREATEINFO, the codec library will acquire the mutex associated with the given //! context before making any cuda calls. //! A multi-threaded application could create a lock associated with a context handle so that //! multiple threads can safely share the same cuda context: //! - use cuCtxPopCurrent immediately after context creation in order to create a 'floating' context //! that can be passed to cuvidCtxLockCreate. //! - When using a floating context, all cuda calls should only be made within a cuvidCtxLock/cuvidCtxUnlock //! section. //! //! NOTE: This is a safer alternative to cuCtxPushCurrent and cuCtxPopCurrent, and is not related to video //! decoder in any way (implemented as a critical section associated with cuCtx{Push|Pop}Current calls). /********************************************************************************************************************/ /********************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidCtxLockCreate(CUvideoctxlock *pLock, CUcontext ctx) //! This API is used to create CtxLock object /********************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCtxLockCreate(CUvideoctxlock *pLock, CUcontext ctx); /********************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidCtxLockDestroy(CUvideoctxlock lck) //! This API is used to free CtxLock object /********************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCtxLockDestroy(CUvideoctxlock lck); /********************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidCtxLock(CUvideoctxlock lck, unsigned int reserved_flags) //! This API is used to acquire ctxlock /********************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCtxLock(CUvideoctxlock lck, unsigned int reserved_flags); /********************************************************************************************************************/ //! \fn CUresult CUDAAPI cuvidCtxUnlock(CUvideoctxlock lck, unsigned int reserved_flags) //! This API is used to release ctxlock /********************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCtxUnlock(CUvideoctxlock lck, unsigned int reserved_flags); /**********************************************************************************************/ #if defined(__cplusplus) } #endif /* __cplusplus */ #endif // __CUDA_VIDEO_H__ ================================================ FILE: decoder/LAVVideo/decoders/cuvid/dynlink_nvcuvid.h ================================================ /* * This copyright notice applies to this header file only: * * Copyright (c) 2010-2024 NVIDIA Corporation * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the software, and to permit persons to whom the * software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /********************************************************************************************************************/ //! \file nvcuvid.h //! NVDECODE API provides video decoding interface to NVIDIA GPU devices. //! \date 2015-2024 //! This file contains the interface constants, structure definitions and function prototypes. /********************************************************************************************************************/ #if !defined(__NVCUVID_H__) #define __NVCUVID_H__ #include "dynlink_cuviddec.h" #if defined(__cplusplus) extern "C" { #endif /* __cplusplus */ #define MAX_CLOCK_TS 3 /***********************************************/ //! //! High-level helper APIs for video sources //! /***********************************************/ typedef void *CUvideosource; typedef void *CUvideoparser; typedef long long CUvideotimestamp; /************************************************************************/ //! \enum cudaVideoState //! Video source state enums //! Used in cuvidSetVideoSourceState and cuvidGetVideoSourceState APIs /************************************************************************/ typedef enum { cudaVideoState_Error = -1, /**< Error state (invalid source) */ cudaVideoState_Stopped = 0, /**< Source is stopped (or reached end-of-stream) */ cudaVideoState_Started = 1 /**< Source is running and delivering data */ } cudaVideoState; /************************************************************************/ //! \enum cudaAudioCodec //! Audio compression enums //! Used in CUAUDIOFORMAT structure /************************************************************************/ typedef enum { cudaAudioCodec_MPEG1=0, /**< MPEG-1 Audio */ cudaAudioCodec_MPEG2, /**< MPEG-2 Audio */ cudaAudioCodec_MP3, /**< MPEG-1 Layer III Audio */ cudaAudioCodec_AC3, /**< Dolby Digital (AC3) Audio */ cudaAudioCodec_LPCM, /**< PCM Audio */ cudaAudioCodec_AAC, /**< AAC Audio */ } cudaAudioCodec; /************************************************************************/ //! \ingroup STRUCTS //! \struct TIMECODESET //! Used to store Time code set extracted from H264 and HEVC codecs /************************************************************************/ typedef struct _TIMECODESET { unsigned int time_offset_value; unsigned short n_frames; unsigned char clock_timestamp_flag; unsigned char units_field_based_flag; unsigned char counting_type; unsigned char full_timestamp_flag; unsigned char discontinuity_flag; unsigned char cnt_dropped_flag; unsigned char seconds_value; unsigned char minutes_value; unsigned char hours_value; unsigned char seconds_flag; unsigned char minutes_flag; unsigned char hours_flag; unsigned char time_offset_length; unsigned char reserved; } TIMECODESET; /************************************************************************/ //! \ingroup STRUCTS //! \struct TIMECODE //! Used to extract Time code in H264 and HEVC codecs /************************************************************************/ typedef struct _TIMECODE { TIMECODESET time_code_set[MAX_CLOCK_TS]; unsigned char num_clock_ts; } NVTIMECODE; /**********************************************************************************/ //! \ingroup STRUCTS //! \struct SEIMASTERINGDISPLAYINFO //! Used to extract mastering display color volume SEI in H264 and HEVC codecs /**********************************************************************************/ typedef struct _SEIMASTERINGDISPLAYINFO { unsigned short display_primaries_x[3]; unsigned short display_primaries_y[3]; unsigned short white_point_x; unsigned short white_point_y; unsigned int max_display_mastering_luminance; unsigned int min_display_mastering_luminance; } SEIMASTERINGDISPLAYINFO; /**********************************************************************************/ //! \ingroup STRUCTS //! \struct SEICONTENTLIGHTLEVELINFO //! Used to extract content light level info SEI in H264 and HEVC codecs /**********************************************************************************/ typedef struct _SEICONTENTLIGHTLEVELINFO { unsigned short max_content_light_level; unsigned short max_pic_average_light_level; unsigned int reserved; } SEICONTENTLIGHTLEVELINFO; /**********************************************************************************/ //! \ingroup STRUCTS //! \struct TIMECODEMPEG2 //! Used to extract Time code in MPEG2 codec /**********************************************************************************/ typedef struct _TIMECODEMPEG2 { unsigned char drop_frame_flag; unsigned char time_code_hours; unsigned char time_code_minutes; unsigned char marker_bit; unsigned char time_code_seconds; unsigned char time_code_pictures; } TIMECODEMPEG2; /**********************************************************************************/ //! \ingroup STRUCTS //! \struct SEIALTERNATIVETRANSFERCHARACTERISTICS //! Used to extract alternative transfer characteristics SEI in H264 and HEVC codecs /**********************************************************************************/ typedef struct _SEIALTERNATIVETRANSFERCHARACTERISTICS { unsigned char preferred_transfer_characteristics; } SEIALTERNATIVETRANSFERCHARACTERISTICS; /**********************************************************************************/ //! \ingroup STRUCTS //! \struct CUSEIMESSAGE; //! Used in CUVIDSEIMESSAGEINFO structure /**********************************************************************************/ typedef struct _CUSEIMESSAGE { unsigned char sei_message_type; /**< OUT: SEI Message Type */ unsigned char reserved[3]; unsigned int sei_message_size; /**< OUT: SEI Message Size */ } CUSEIMESSAGE; /************************************************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDEOFORMAT //! Video format //! Used in cuvidGetSourceVideoFormat API /************************************************************************************************/ typedef struct { cudaVideoCodec codec; /**< OUT: Compression format */ /** * OUT: frame rate = numerator / denominator (for example: 30000/1001) */ struct { /**< OUT: frame rate numerator (0 = unspecified or variable frame rate) */ unsigned int numerator; /**< OUT: frame rate denominator (0 = unspecified or variable frame rate) */ unsigned int denominator; } frame_rate; unsigned char progressive_sequence; /**< OUT: 0=interlaced, 1=progressive */ unsigned char bit_depth_luma_minus8; /**< OUT: high bit depth luma. E.g, 2 for 10-bitdepth, 4 for 12-bitdepth */ unsigned char bit_depth_chroma_minus8; /**< OUT: high bit depth chroma. E.g, 2 for 10-bitdepth, 4 for 12-bitdepth */ unsigned char min_num_decode_surfaces; /**< OUT: Minimum number of decode surfaces to be allocated for correct decoding. The client can send this value in ulNumDecodeSurfaces (in CUVIDDECODECREATEINFO structure). This guarantees correct functionality and optimal video memory usage but not necessarily the best performance, which depends on the design of the overall application. The optimal number of decode surfaces (in terms of performance and memory utilization) should be decided by experimentation for each application, but it cannot go below min_num_decode_surfaces. If this value is used for ulNumDecodeSurfaces then it must be returned to parser during sequence callback. */ unsigned int coded_width; /**< OUT: coded frame width in pixels */ unsigned int coded_height; /**< OUT: coded frame height in pixels */ /** * area of the frame that should be displayed * typical example: * coded_width = 1920, coded_height = 1088 * display_area = { 0,0,1920,1080 } */ struct { int left; /**< OUT: left position of display rect */ int top; /**< OUT: top position of display rect */ int right; /**< OUT: right position of display rect */ int bottom; /**< OUT: bottom position of display rect */ } display_area; cudaVideoChromaFormat chroma_format; /**< OUT: Chroma format */ unsigned int bitrate; /**< OUT: video bitrate (bps, 0=unknown) */ /** * OUT: Display Aspect Ratio = x:y (4:3, 16:9, etc) */ struct { int x; int y; } display_aspect_ratio; /** * Video Signal Description * Refer section E.2.1 (VUI parameters semantics) of H264 spec file */ struct { unsigned char video_format : 3; /**< OUT: 0-Component, 1-PAL, 2-NTSC, 3-SECAM, 4-MAC, 5-Unspecified */ unsigned char video_full_range_flag : 1; /**< OUT: indicates the black level and luma and chroma range */ unsigned char reserved_zero_bits : 4; /**< Reserved bits */ unsigned char color_primaries; /**< OUT: chromaticity coordinates of source primaries */ unsigned char transfer_characteristics; /**< OUT: opto-electronic transfer characteristic of the source picture */ unsigned char matrix_coefficients; /**< OUT: used in deriving luma and chroma signals from RGB primaries */ } video_signal_description; unsigned int seqhdr_data_length; /**< OUT: Additional bytes following (CUVIDEOFORMATEX) */ } CUVIDEOFORMAT; /****************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDOPERATINGPOINTINFO //! Operating point information of scalable bitstream /****************************************************************/ typedef struct { cudaVideoCodec codec; union { struct { unsigned char operating_points_cnt; unsigned char reserved24_bits[3]; unsigned short operating_points_idc[32]; } av1; unsigned char CodecReserved[1024]; }; } CUVIDOPERATINGPOINTINFO; /**********************************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDSEIMESSAGEINFO //! Used in cuvidParseVideoData API with PFNVIDSEIMSGCALLBACK pfnGetSEIMsg /**********************************************************************************/ typedef struct _CUVIDSEIMESSAGEINFO { void *pSEIData; /**< OUT: SEI Message Data */ CUSEIMESSAGE *pSEIMessage; /**< OUT: SEI Message Info */ unsigned int sei_message_count; /**< OUT: SEI Message Count */ unsigned int picIdx; /**< OUT: SEI Message Pic Index */ } CUVIDSEIMESSAGEINFO; /****************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDAV1SEQHDR //! AV1 specific sequence header information /****************************************************************/ typedef struct { unsigned int max_width; unsigned int max_height; unsigned char reserved[1016]; } CUVIDAV1SEQHDR; /****************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDEOFORMATEX //! Video format including raw sequence header information //! Used in cuvidGetSourceVideoFormat API /****************************************************************/ typedef struct { CUVIDEOFORMAT format; /**< OUT: CUVIDEOFORMAT structure */ union { CUVIDAV1SEQHDR av1; unsigned char raw_seqhdr_data[1024]; /**< OUT: Sequence header data */ }; } CUVIDEOFORMATEX; /****************************************************************/ //! \ingroup STRUCTS //! \struct CUAUDIOFORMAT //! Audio formats //! Used in cuvidGetSourceAudioFormat API /****************************************************************/ typedef struct { cudaAudioCodec codec; /**< OUT: Compression format */ unsigned int channels; /**< OUT: number of audio channels */ unsigned int samplespersec; /**< OUT: sampling frequency */ unsigned int bitrate; /**< OUT: For uncompressed, can also be used to determine bits per sample */ unsigned int reserved1; /**< Reserved for future use */ unsigned int reserved2; /**< Reserved for future use */ } CUAUDIOFORMAT; /***************************************************************/ //! \enum CUvideopacketflags //! Data packet flags //! Used in CUVIDSOURCEDATAPACKET structure /***************************************************************/ typedef enum { CUVID_PKT_ENDOFSTREAM = 0x01, /**< Set when this is the last packet for this stream */ CUVID_PKT_TIMESTAMP = 0x02, /**< Timestamp is valid */ CUVID_PKT_DISCONTINUITY = 0x04, /**< Set when a discontinuity has to be signalled */ CUVID_PKT_ENDOFPICTURE = 0x08, /**< Set when the packet contains exactly one frame or one field */ CUVID_PKT_NOTIFY_EOS = 0x10, /**< If this flag is set along with CUVID_PKT_ENDOFSTREAM, an additional (dummy) display callback will be invoked with null value of CUVIDPARSERDISPINFO which should be interpreted as end of the stream. */ } CUvideopacketflags; /*****************************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDSOURCEDATAPACKET //! Data Packet //! Used in cuvidParseVideoData API //! IN for cuvidParseVideoData /*****************************************************************************/ typedef struct _CUVIDSOURCEDATAPACKET { unsigned long flags; /**< IN: Combination of CUVID_PKT_XXX flags */ unsigned long payload_size; /**< IN: number of bytes in the payload (may be zero if EOS flag is set) */ const unsigned char *payload; /**< IN: Pointer to packet payload data (may be NULL if EOS flag is set) */ CUvideotimestamp timestamp; /**< IN: Presentation time stamp (10MHz clock), only valid if CUVID_PKT_TIMESTAMP flag is set */ } CUVIDSOURCEDATAPACKET; // Callback for packet delivery typedef int (CUDAAPI *PFNVIDSOURCECALLBACK)(void *, CUVIDSOURCEDATAPACKET *); /**************************************************************************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDSOURCEPARAMS //! Describes parameters needed in cuvidCreateVideoSource API //! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported //! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed. /**************************************************************************************************************************/ typedef struct _CUVIDSOURCEPARAMS { unsigned int ulClockRate; /**< IN: Time stamp units in Hz (0=default=10000000Hz) */ unsigned int bAnnexb : 1; /**< IN: AV1 annexB stream */ unsigned int uReserved : 31; /**< Reserved for future use - set to zero */ unsigned int uReserved1[6]; /**< Reserved for future use - set to zero */ void *pUserData; /**< IN: User private data passed in to the data handlers */ PFNVIDSOURCECALLBACK pfnVideoDataHandler; /**< IN: Called to deliver video packets */ PFNVIDSOURCECALLBACK pfnAudioDataHandler; /**< IN: Called to deliver audio packets. */ void *pvReserved2[8]; /**< Reserved for future use - set to NULL */ } CUVIDSOURCEPARAMS; /**********************************************/ //! \ingroup ENUMS //! \enum CUvideosourceformat_flags //! CUvideosourceformat_flags //! Used in cuvidGetSourceVideoFormat API /**********************************************/ typedef enum { CUVID_FMT_EXTFORMATINFO = 0x100 /**< Return extended format structure (CUVIDEOFORMATEX) */ } CUvideosourceformat_flags; #if !defined(__APPLE__) /***************************************************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams) //! Create CUvideosource object. CUvideosource spawns demultiplexer thread that provides two callbacks: //! pfnVideoDataHandler() and pfnAudioDataHandler() //! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported //! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed. /***************************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCreateVideoSource(CUvideosource *pObj, const char *pszFileName, CUVIDSOURCEPARAMS *pParams); /***************************************************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams) //! Create video source /***************************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCreateVideoSourceW(CUvideosource *pObj, const wchar_t *pwszFileName, CUVIDSOURCEPARAMS *pParams); /********************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidDestroyVideoSource(CUvideosource obj) //! Destroy video source /********************************************************************/ typedef CUresult CUDAAPI tcuvidDestroyVideoSource(CUvideosource obj); /******************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state) //! Set video source state to: //! cudaVideoState_Started - to signal the source to run and deliver data //! cudaVideoState_Stopped - to stop the source from delivering the data //! cudaVideoState_Error - invalid source /******************************************************************************************/ typedef CUresult CUDAAPI tcuvidSetVideoSourceState(CUvideosource obj, cudaVideoState state); /******************************************************************************************/ //! \ingroup FUNCTS //! \fn cudaVideoState CUDAAPI cuvidGetVideoSourceState(CUvideosource obj) //! Get video source state //! Returns: //! cudaVideoState_Started - if Source is running and delivering data //! cudaVideoState_Stopped - if Source is stopped or reached end-of-stream //! cudaVideoState_Error - if Source is in error state /******************************************************************************************/ typedef cudaVideoState CUDAAPI tcuvidGetVideoSourceState(CUvideosource obj); /******************************************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags) //! Gets video source format in pvidfmt, flags is set to combination of CUvideosourceformat_flags as per requirement /******************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidGetSourceVideoFormat(CUvideosource obj, CUVIDEOFORMAT *pvidfmt, unsigned int flags); /**************************************************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags) //! Get audio source format //! NVDECODE API is intended for HW accelerated video decoding so CUvideosource doesn't have audio demuxer for all supported //! containers. It's recommended to clients to use their own or third party demuxer if audio support is needed. /**************************************************************************************************************************/ typedef CUresult CUDAAPI tcuvidGetSourceAudioFormat(CUvideosource obj, CUAUDIOFORMAT *paudfmt, unsigned int flags); #endif /**********************************************************************************/ //! \ingroup STRUCTS //! \struct CUVIDPARSERDISPINFO //! Used in cuvidParseVideoData API with PFNVIDDISPLAYCALLBACK pfnDisplayPicture /**********************************************************************************/ typedef struct _CUVIDPARSERDISPINFO { int picture_index; /**< OUT: Index of the current picture */ int progressive_frame; /**< OUT: 1 if progressive frame; 0 otherwise */ int top_field_first; /**< OUT: 1 if top field is displayed first; 0 otherwise */ int repeat_first_field; /**< OUT: Number of additional fields (1=ivtc, 2=frame doubling, 4=frame tripling, -1=unpaired field) */ CUvideotimestamp timestamp; /**< OUT: Presentation time stamp */ } CUVIDPARSERDISPINFO; /***********************************************************************************************************************/ //! Parser callbacks //! The parser will call these synchronously from within cuvidParseVideoData(), whenever there is sequence change or a picture //! is ready to be decoded and/or displayed. First argument in functions is "void *pUserData" member of structure CUVIDSOURCEPARAMS //! Return values from these callbacks are interpreted as below. If the callbacks return failure, it will be propagated by //! cuvidParseVideoData() to the application. //! Parser picks default operating point as 0 and outputAllLayers flag as 0 if PFNVIDOPPOINTCALLBACK is not set or return value is //! -1 or invalid operating point. //! PFNVIDSEQUENCECALLBACK : 0: fail, 1: succeeded, > 1: override dpb size of parser (set by CUVIDPARSERPARAMS::ulMaxNumDecodeSurfaces //! while creating parser) //! PFNVIDDECODECALLBACK : 0: fail, >=1: succeeded //! PFNVIDDISPLAYCALLBACK : 0: fail, >=1: succeeded //! PFNVIDOPPOINTCALLBACK : <0: fail, >=0: succeeded (bit 0-9: OperatingPoint, bit 10-10: outputAllLayers, bit 11-30: reserved) //! PFNVIDSEIMSGCALLBACK : 0: fail, >=1: succeeded /***********************************************************************************************************************/ typedef int (CUDAAPI *PFNVIDSEQUENCECALLBACK)(void *, CUVIDEOFORMAT *); typedef int (CUDAAPI *PFNVIDDECODECALLBACK)(void *, CUVIDPICPARAMS *); typedef int (CUDAAPI *PFNVIDDISPLAYCALLBACK)(void *, CUVIDPARSERDISPINFO *); typedef int (CUDAAPI *PFNVIDOPPOINTCALLBACK)(void *, CUVIDOPERATINGPOINTINFO*); typedef int (CUDAAPI *PFNVIDSEIMSGCALLBACK) (void *, CUVIDSEIMESSAGEINFO *); /**************************************/ //! \ingroup STRUCTS //! \struct CUVIDPARSERPARAMS //! Used in cuvidCreateVideoParser API /**************************************/ typedef struct _CUVIDPARSERPARAMS { cudaVideoCodec CodecType; /**< IN: cudaVideoCodec_XXX */ unsigned int ulMaxNumDecodeSurfaces; /**< IN: Max # of decode surfaces (parser will cycle through these) */ unsigned int ulClockRate; /**< IN: Timestamp units in Hz (0=default=10000000Hz) */ unsigned int ulErrorThreshold; /**< IN: % Error threshold (0-100) for calling pfnDecodePicture (100=always IN: call pfnDecodePicture even if picture bitstream is fully corrupted) */ unsigned int ulMaxDisplayDelay; /**< IN: Max display queue delay (improves pipelining of decode with display) 0=no delay (recommended values: 2..4) */ unsigned int bAnnexb : 1; /**< IN: AV1 annexB stream */ unsigned int uReserved : 31; /**< Reserved for future use - set to zero */ unsigned int uReserved1[4]; /**< IN: Reserved for future use - set to 0 */ void *pUserData; /**< IN: User data for callbacks */ PFNVIDSEQUENCECALLBACK pfnSequenceCallback; /**< IN: Called before decoding frames and/or whenever there is a fmt change */ PFNVIDDECODECALLBACK pfnDecodePicture; /**< IN: Called when a picture is ready to be decoded (decode order) */ PFNVIDDISPLAYCALLBACK pfnDisplayPicture; /**< IN: Called whenever a picture is ready to be displayed (display order) */ PFNVIDOPPOINTCALLBACK pfnGetOperatingPoint; /**< IN: Called from AV1 sequence header to get operating point of a AV1 scalable bitstream */ PFNVIDSEIMSGCALLBACK pfnGetSEIMsg; /**< IN: Called when all SEI messages are parsed for particular frame */ void *pvReserved2[5]; /**< Reserved for future use - set to NULL */ CUVIDEOFORMATEX *pExtVideoInfo; /**< IN: [Optional] sequence header data from system layer */ } CUVIDPARSERPARAMS; /************************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams) //! Create video parser object and initialize /************************************************************************************************/ typedef CUresult CUDAAPI tcuvidCreateVideoParser(CUvideoparser *pObj, CUVIDPARSERPARAMS *pParams); /************************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket) //! Parse the video data from source data packet in pPacket //! Extracts parameter sets like SPS, PPS, bitstream etc. from pPacket and //! calls back pfnDecodePicture with CUVIDPICPARAMS data for kicking of HW decoding //! calls back pfnSequenceCallback with CUVIDEOFORMAT data for initial sequence header or when //! the decoder encounters a video format change //! calls back pfnDisplayPicture with CUVIDPARSERDISPINFO data to display a video frame /************************************************************************************************/ typedef CUresult CUDAAPI tcuvidParseVideoData(CUvideoparser obj, CUVIDSOURCEDATAPACKET *pPacket); /************************************************************************************************/ //! \ingroup FUNCTS //! \fn CUresult CUDAAPI cuvidDestroyVideoParser(CUvideoparser obj) //! Destroy the video parser /************************************************************************************************/ typedef CUresult CUDAAPI tcuvidDestroyVideoParser(CUvideoparser obj); /**********************************************************************************************/ #if defined(__cplusplus) } #endif /* __cplusplus */ #endif // __NVCUVID_H__ ================================================ FILE: decoder/LAVVideo/decoders/cuvid.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "cuvid.h" #include "moreuuids.h" #include "parsers/H264SequenceParser.h" #include "parsers/MPEG2HeaderParser.h" #include "parsers/VC1HeaderParser.h" #include "parsers/HEVCSequenceParser.h" #include "Media.h" //////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////// ILAVDecoder *CreateDecoderCUVID() { return new CDecCuvid(); } //////////////////////////////////////////////////////////////////////////////// // CUVID codec map //////////////////////////////////////////////////////////////////////////////// static struct { AVCodecID ffcodec; cudaVideoCodec cudaCodec; } cuda_codecs[] = { {AV_CODEC_ID_MPEG1VIDEO, cudaVideoCodec_MPEG1}, {AV_CODEC_ID_MPEG2VIDEO, cudaVideoCodec_MPEG2}, {AV_CODEC_ID_VC1, cudaVideoCodec_VC1}, {AV_CODEC_ID_H264, cudaVideoCodec_H264}, {AV_CODEC_ID_MPEG4, cudaVideoCodec_MPEG4}, {AV_CODEC_ID_HEVC, cudaVideoCodec_HEVC}, {AV_CODEC_ID_VP9, cudaVideoCodec_VP9}, }; //////////////////////////////////////////////////////////////////////////////// // Compatibility tables //////////////////////////////////////////////////////////////////////////////// #define LEVEL_C_LOW_LIMIT 0x0A20 static DWORD LevelCBlacklist[] = { 0x0A22, 0x0A67, // Geforce 315, no VDPAU at all 0x0A68, 0x0A69, // Geforce G105M, only B 0x0CA0, 0x0CA7, // Geforce GT 330, only A 0x0CAC, // Geforce GT 220, no VDPAU 0x10C3 // Geforce 8400GS, only A }; static DWORD LevelCWhitelist[] = { 0x06C0, // Geforce GTX 480 0x06C4, // Geforce GTX 465 0x06CA, // Geforce GTX 480M 0x06CD, // Geforce GTX 470 0x08A5, // Geforce 320M 0x06D8, 0x06DC, // Quadro 6000 0x06D9, // Quadro 5000 0x06DA, // Quadro 5000M 0x06DD, // Quadro 4000 0x06D1, // Tesla C2050 / C2070 0x06D2, // Tesla M2070 0x06DE, // Tesla T20 Processor 0x06DF, // Tesla M2070-Q }; static BOOL IsLevelC(DWORD deviceId) { int idx = 0; if (deviceId >= LEVEL_C_LOW_LIMIT) { for (idx = 0; idx < countof(LevelCBlacklist); idx++) { if (LevelCBlacklist[idx] == deviceId) return FALSE; } return TRUE; } else { for (idx = 0; idx < countof(LevelCWhitelist); idx++) { if (LevelCWhitelist[idx] == deviceId) return TRUE; } return FALSE; } } //////////////////////////////////////////////////////////////////////////////// // CUVID decoder implementation //////////////////////////////////////////////////////////////////////////////// CDecCuvid::CDecCuvid(void) : CDecBase() { ZeroMemory(&cuda, sizeof(cuda)); ZeroMemory(&m_VideoFormat, sizeof(m_VideoFormat)); ZeroMemory(&m_DXVAExtendedFormat, sizeof(m_DXVAExtendedFormat)); ZeroMemory(&m_VideoDecoderInfo, sizeof(m_VideoDecoderInfo)); } CDecCuvid::~CDecCuvid(void) { DestroyDecoder(true); } STDMETHODIMP CDecCuvid::DestroyDecoder(bool bFull) { if (m_cudaCtxLock) cuda.cuvidCtxLock(m_cudaCtxLock, 0); if (m_AnnexBConverter) { SAFE_DELETE(m_AnnexBConverter); } if (m_hDecoder) { cuda.cuvidDestroyDecoder(m_hDecoder); m_hDecoder = 0; } if (m_hParser) { cuda.cuvidDestroyVideoParser(m_hParser); m_hParser = 0; } if (m_pbRawNV12) { cuda.cuMemFreeHost(m_pbRawNV12); m_pbRawNV12 = nullptr; m_cRawNV12 = 0; } if (m_cudaCtxLock) cuda.cuvidCtxUnlock(m_cudaCtxLock, 0); if (bFull) { if (m_cudaCtxLock) { cuda.cuvidCtxLockDestroy(m_cudaCtxLock); m_cudaCtxLock = 0; } if (m_cudaContext) { cuda.cuCtxDestroy(m_cudaContext); m_cudaContext = 0; } SafeRelease(&m_pD3DDevice9); SafeRelease(&m_pD3D9); FreeLibrary(cuda.cudaLib); FreeLibrary(cuda.cuvidLib); ZeroMemory(&cuda, sizeof(cuda)); } return S_OK; } #define STRINGIFY(X) #X #define GET_PROC_EX_OPT(name, lib) cuda.name = (t##name *)GetProcAddress(lib, #name); #define GET_PROC_EX(name, lib) \ GET_PROC_EX_OPT(name, lib) \ if (cuda.name == nullptr) \ { \ DbgLog((LOG_ERROR, 10, L"-> Failed to load function \"%s\"", TEXT(#name))); \ return E_FAIL; \ } #define GET_PROC_EX_OPT_V2(name, lib) cuda.name = (t##name *)GetProcAddress(lib, STRINGIFY(name##_v2)); #define GET_PROC_EX_V2(name, lib) \ GET_PROC_EX_OPT_V2(name, lib) \ if (cuda.name == nullptr) \ { \ DbgLog((LOG_ERROR, 10, L"-> Failed to load function \"%s\"", TEXT(STRINGIFY(name##_v2)))); \ return E_FAIL; \ } #define GET_PROC_CUDA(name) GET_PROC_EX(name, cuda.cudaLib) #define GET_PROC_CUDA_V2(name) GET_PROC_EX_V2(name, cuda.cudaLib) #define GET_PROC_CUVID(name) GET_PROC_EX(name, cuda.cuvidLib) #define GET_PROC_CUVID_V2(name) GET_PROC_EX_V2(name, cuda.cuvidLib) STDMETHODIMP CDecCuvid::LoadCUDAFuncRefs() { // Load CUDA functions cuda.cudaLib = LoadLibrary(L"nvcuda.dll"); if (cuda.cudaLib == nullptr) { DbgLog((LOG_TRACE, 10, L"-> Loading nvcuda.dll failed")); return E_FAIL; } GET_PROC_CUDA(cuInit); GET_PROC_CUDA_V2(cuCtxCreate); GET_PROC_CUDA_V2(cuCtxDestroy); GET_PROC_CUDA_V2(cuCtxPushCurrent); GET_PROC_CUDA_V2(cuCtxPopCurrent); GET_PROC_CUDA_V2(cuD3D9CtxCreate); GET_PROC_CUDA_V2(cuMemAllocHost); GET_PROC_CUDA(cuMemFreeHost); GET_PROC_CUDA_V2(cuMemcpyDtoH); GET_PROC_CUDA(cuDeviceGetCount); GET_PROC_CUDA(cuDriverGetVersion); GET_PROC_CUDA(cuDeviceGetName); GET_PROC_CUDA(cuDeviceComputeCapability); GET_PROC_CUDA(cuDeviceGetAttribute); // Load CUVID function cuda.cuvidLib = LoadLibrary(L"nvcuvid.dll"); if (cuda.cuvidLib == nullptr) { DbgLog((LOG_TRACE, 10, L"-> Loading nvcuvid.dll failed")); return E_FAIL; } GET_PROC_CUVID(cuvidCtxLockCreate); GET_PROC_CUVID(cuvidCtxLockDestroy); GET_PROC_CUVID(cuvidCtxLock); GET_PROC_CUVID(cuvidCtxUnlock); GET_PROC_CUVID(cuvidCreateVideoParser); GET_PROC_CUVID(cuvidParseVideoData); GET_PROC_CUVID(cuvidDestroyVideoParser); GET_PROC_CUVID(cuvidCreateDecoder); GET_PROC_CUVID(cuvidDecodePicture); GET_PROC_CUVID(cuvidDestroyDecoder); #ifdef _M_AMD64 GET_PROC_CUVID(cuvidMapVideoFrame64); GET_PROC_CUVID(cuvidUnmapVideoFrame64); cuda.cuvidMapVideoFrame = cuda.cuvidMapVideoFrame64; cuda.cuvidUnmapVideoFrame = cuda.cuvidUnmapVideoFrame64; #else GET_PROC_CUVID(cuvidMapVideoFrame); GET_PROC_CUVID(cuvidUnmapVideoFrame); #endif return S_OK; } STDMETHODIMP CDecCuvid::FlushParser() { CUVIDSOURCEDATAPACKET pCuvidPacket; memset(&pCuvidPacket, 0, sizeof(pCuvidPacket)); pCuvidPacket.flags |= CUVID_PKT_ENDOFSTREAM; CUresult result = CUDA_SUCCESS; cuda.cuvidCtxLock(m_cudaCtxLock, 0); __try { result = cuda.cuvidParseVideoData(m_hParser, &pCuvidPacket); } __except (1) { DbgLog((LOG_ERROR, 10, L"cuvidFlushParser(): cuvidParseVideoData threw an exception")); result = CUDA_ERROR_UNKNOWN; } cuda.cuvidCtxUnlock(m_cudaCtxLock, 0); return result; } // Beginning of GPU Architecture definitions static int _ConvertSMVer2CoresDrvApi(int major, int minor) { // Defines for GPU Architecture types (using the SM version to determine the # of cores per SM typedef struct { int SM; // 0xMm (hexadecimal notation), M = SM Major version, and m = SM minor version int Cores; } sSMtoCores; sSMtoCores nGpuArchCoresPerSM[] = {{0x10, 8}, {0x11, 8}, {0x12, 8}, {0x13, 8}, {0x20, 32}, {0x21, 48}, {0x30, 192}, {0x32, 192}, {0x35, 192}, {0x37, 192}, {0x50, 128}, {0x52, 128}, {0x61, 128}, {0x70, 64} , {0x75, 64}, {0x80, 128}, {0x86, 128}, {0x89, 128}, {-1, -1}}; int index = 0; while (nGpuArchCoresPerSM[index].SM != -1) { if (nGpuArchCoresPerSM[index].SM == ((major << 4) + minor)) { return nGpuArchCoresPerSM[index].Cores; } index++; } DbgLog((LOG_ERROR, 10, L"MapSMtoCores undefined SMversion %d.%d!", major, minor)); return -1; } int CDecCuvid::GetMaxGflopsGraphicsDeviceId() { CUdevice current_device = 0, max_perf_device = 0; int device_count = 0, sm_per_multiproc = 0; int best_SM_arch = 0; int64_t max_compute_perf = 0; int major = 0, minor = 0, multiProcessorCount, clockRate; int bTCC = 0, version; char deviceName[256]; cuda.cuDeviceGetCount(&device_count); if (device_count <= 0) return -1; cuda.cuDriverGetVersion(&version); // Find the best major SM Architecture GPU device that are graphics devices while (current_device < device_count) { cuda.cuDeviceGetName(deviceName, 256, current_device); cuda.cuDeviceComputeCapability(&major, &minor, current_device); if (version >= 3020) { cuda.cuDeviceGetAttribute(&bTCC, CU_DEVICE_ATTRIBUTE_TCC_DRIVER, current_device); } else { // Assume a Tesla GPU is running in TCC if we are running CUDA 3.1 if (deviceName[0] == 'T') bTCC = 1; } if (!bTCC) { if (major > 0 && major < 9999) { best_SM_arch = max(best_SM_arch, major); } } current_device++; } // Find the best CUDA capable GPU device current_device = 0; while (current_device < device_count) { cuda.cuDeviceGetAttribute(&multiProcessorCount, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, current_device); cuda.cuDeviceGetAttribute(&clockRate, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, current_device); cuda.cuDeviceComputeCapability(&major, &minor, current_device); if (version >= 3020) { cuda.cuDeviceGetAttribute(&bTCC, CU_DEVICE_ATTRIBUTE_TCC_DRIVER, current_device); } else { // Assume a Tesla GPU is running in TCC if we are running CUDA 3.1 if (deviceName[0] == 'T') bTCC = 1; } if (major == 9999 && minor == 9999) { sm_per_multiproc = 1; } else { sm_per_multiproc = _ConvertSMVer2CoresDrvApi(major, minor); } // If this is a Tesla based GPU and SM 2.0, and TCC is disabled, this is a contender if (!bTCC) // Is this GPU running the TCC driver? If so we pass on this { int64_t compute_perf = int64_t(multiProcessorCount * sm_per_multiproc) * clockRate; if (compute_perf > max_compute_perf) { // If we find GPU with SM major > 2, search only these if (best_SM_arch > 2) { // If our device = dest_SM_arch, then we pick this one if (major == best_SM_arch) { max_compute_perf = compute_perf; max_perf_device = current_device; } } else { max_compute_perf = compute_perf; max_perf_device = current_device; } } #ifdef DEBUG cuda.cuDeviceGetName(deviceName, 256, current_device); DbgLog((LOG_TRACE, 10, L"CUDA Device (%d): %S, Compute: %d.%d, CUDA Cores: %d, Clock: %d MHz", current_device, deviceName, major, minor, multiProcessorCount * sm_per_multiproc, clockRate / 1000)); #endif } ++current_device; } return max_perf_device; } // ILAVDecoder STDMETHODIMP CDecCuvid::Init() { DbgLog((LOG_TRACE, 10, L"CDecCuvid::Init(): Trying to open CUVID device")); HRESULT hr = S_OK; CUresult cuStatus = CUDA_SUCCESS; hr = LoadCUDAFuncRefs(); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Loading CUDA interfaces failed (hr: 0x%x)", hr)); return hr; } cuStatus = cuda.cuInit(0); if (cuStatus != CUDA_SUCCESS) { DbgLog((LOG_ERROR, 10, L"-> cuInit failed (status: %d)", cuStatus)); return E_FAIL; } // TODO: select best device int best_device = GetMaxGflopsGraphicsDeviceId(); DWORD dwDeviceIndex = m_pCallback->GetGPUDeviceIndex(); if (dwDeviceIndex != DWORD_MAX) { best_device = (int)dwDeviceIndex; } select_device: hr = InitD3D9(best_device, dwDeviceIndex); if (hr != S_OK) { if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> No D3D device available, building non-D3D context on device %d", best_device)); } cuStatus = cuda.cuCtxCreate(&m_cudaContext, CU_CTX_SCHED_BLOCKING_SYNC, best_device); if (cuStatus == CUDA_SUCCESS) { int major, minor; cuda.cuDeviceComputeCapability(&major, &minor, best_device); m_bVDPAULevelC = (major >= 2); cuda.cuDeviceGetName(m_cudaDeviceName, sizeof(m_cudaDeviceName), best_device); DbgLog((LOG_TRACE, 10, L"InitCUDA(): pure CUDA context of device with compute %d.%d", major, minor)); } } if (cuStatus == CUDA_ERROR_INVALID_DEVICE && dwDeviceIndex != DWORD_MAX) { DbgLog((LOG_TRACE, 10, L"-> Specific device was requested, but no match was found, re-trying automatic selection")); dwDeviceIndex = DWORD_MAX; best_device = GetMaxGflopsGraphicsDeviceId(); goto select_device; } if (cuStatus == CUDA_SUCCESS) { // Switch to a floating context CUcontext curr_ctx = nullptr; cuStatus = cuda.cuCtxPopCurrent(&curr_ctx); if (cuStatus != CUDA_SUCCESS) { DbgLog((LOG_ERROR, 10, L"-> Storing context on the stack failed with error %d", cuStatus)); return E_FAIL; } cuStatus = cuda.cuvidCtxLockCreate(&m_cudaCtxLock, m_cudaContext); if (cuStatus != CUDA_SUCCESS) { DbgLog((LOG_ERROR, 10, L"-> Creation of floating context failed with error %d", cuStatus)); return E_FAIL; } } else { DbgLog((LOG_TRACE, 10, L"-> Creation of CUDA context failed with error %d", cuStatus)); return E_FAIL; } return S_OK; } STDMETHODIMP CDecCuvid::InitD3D9(int best_device, DWORD requested_device) { HRESULT hr = S_OK; CUresult cuStatus = CUDA_SUCCESS; int device = 0; if (IsWindows10OrNewer()) { DbgLog((LOG_ERROR, 10, L"-> D3D9 CUVID interop is not supported on Windows 10")); return E_FAIL; } // Check if D3D mode is enabled/wanted if (m_pSettings->GetHWAccelDeintHQ() == FALSE) { DbgLog((LOG_ERROR, 10, L"-> HQ mode is turned off, skipping D3D9 init")); return S_FALSE; } if (!m_pD3D9) m_pD3D9 = Direct3DCreate9(D3D_SDK_VERSION); if (!m_pD3D9) { DbgLog((LOG_ERROR, 10, L"-> Failed to acquire IDirect3D9")); return E_FAIL; } D3DADAPTER_IDENTIFIER9 d3dId; D3DPRESENT_PARAMETERS d3dpp; D3DDISPLAYMODE d3ddm; for (unsigned lAdapter = 0; lAdapter < m_pD3D9->GetAdapterCount(); lAdapter++) { DbgLog((LOG_TRACE, 10, L"-> Trying D3D Adapter %d..", lAdapter)); ZeroMemory(&d3dpp, sizeof(d3dpp)); m_pD3D9->GetAdapterDisplayMode(lAdapter, &d3ddm); d3dpp.Windowed = TRUE; d3dpp.BackBufferWidth = 640; d3dpp.BackBufferHeight = 480; d3dpp.BackBufferCount = 1; d3dpp.BackBufferFormat = d3ddm.Format; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.Flags = D3DPRESENTFLAG_VIDEO; IDirect3DDevice9 *pDev = nullptr; CUcontext cudaCtx = 0; hr = m_pD3D9->CreateDevice( lAdapter, D3DDEVTYPE_HAL, GetShellWindow(), D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE, &d3dpp, &pDev); if (SUCCEEDED(hr)) { m_pD3D9->GetAdapterIdentifier(lAdapter, 0, &d3dId); cuStatus = cuda.cuD3D9CtxCreate(&cudaCtx, &device, CU_CTX_SCHED_BLOCKING_SYNC, pDev); if (cuStatus == CUDA_SUCCESS) { DbgLog((LOG_TRACE, 10, L"-> Created D3D Device on adapter %S (%d), using CUDA device %d", d3dId.Description, lAdapter, device)); BOOL isLevelC = IsLevelC(d3dId.DeviceId); DbgLog( (LOG_TRACE, 10, L"InitCUDA(): D3D Device with Id 0x%x is level C: %d", d3dId.DeviceId, isLevelC)); if (m_bVDPAULevelC && !isLevelC) { DbgLog((LOG_TRACE, 10, L"InitCUDA(): We already had a Level C+ device, this one is not, skipping")); cuda.cuCtxDestroy(cudaCtx); SafeRelease(&pDev); continue; } // Release old resources SafeRelease(&m_pD3DDevice9); if (m_cudaContext) cuda.cuCtxDestroy(m_cudaContext); // Store resources m_pD3DDevice9 = pDev; m_cudaContext = cudaCtx; m_bVDPAULevelC = isLevelC; cuda.cuDeviceGetName(m_cudaDeviceName, sizeof(m_cudaDeviceName), best_device); // Is this the one we want? if (device == best_device) break; } else { DbgLog((LOG_TRACE, 10, L"-> D3D Device on adapter %d is not CUDA capable", lAdapter)); SafeRelease(&pDev); } } } if (requested_device != DWORD_MAX && device != best_device) { DbgLog((LOG_ERROR, 10, L"-> No D3D Device found matching the requested device")); SafeRelease(&m_pD3DDevice9); SafeRelease(&m_pD3D9); if (m_cudaContext) { cuda.cuCtxDestroy(m_cudaContext); m_cudaContext = 0; } return E_FAIL; } if (!m_pD3DDevice9) { SafeRelease(&m_pD3D9); return E_FAIL; } return S_OK; } STDMETHODIMP CDecCuvid::InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) { DbgLog((LOG_TRACE, 10, L"CDecCuvid::InitDecoder(): Initializing CUVID decoder")); HRESULT hr = S_OK; if (!m_cudaContext) { DbgLog((LOG_TRACE, 10, L"-> InitDecoder called without a cuda context")); return E_FAIL; } // Free old device DestroyDecoder(false); // Flush Display Queue memset(&m_DisplayQueue, 0, sizeof(m_DisplayQueue)); for (int i = 0; i < DISPLAY_DELAY; i++) m_DisplayQueue[i].picture_index = -1; m_DisplayPos = 0; m_DisplayDelay = DISPLAY_DELAY; // Reduce display delay for DVD decoding for lower decode latency if (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) m_DisplayDelay /= 2; cudaVideoCodec cudaCodec = (cudaVideoCodec)-1; for (int i = 0; i < countof(cuda_codecs); i++) { if (cuda_codecs[i].ffcodec == codec) { cudaCodec = cuda_codecs[i].cudaCodec; break; } } if (cudaCodec == -1) { DbgLog((LOG_TRACE, 10, L"-> Codec id %d does not map to a CUVID codec", codec)); return E_FAIL; } if (cudaCodec == cudaVideoCodec_MPEG4 && !m_bVDPAULevelC) { DbgLog((LOG_TRACE, 10, L"-> Device is not capable to decode this format (not >= Level C)")); return E_FAIL; } m_bUseTimestampQueue = (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_ONLY_DTS) || (cudaCodec == cudaVideoCodec_MPEG4 && pmt->formattype != FORMAT_MPEG2Video) || (cudaCodec == cudaVideoCodec_VP9); m_bWaitForKeyframe = m_bUseTimestampQueue; m_bInterlaced = TRUE; m_bFormatIncompatible = FALSE; m_bTFF = TRUE; m_rtPrevDiff = AV_NOPTS_VALUE; m_bARPresent = TRUE; // Create the CUDA Video Parser CUVIDPARSERPARAMS oVideoParserParameters; ZeroMemory(&oVideoParserParameters, sizeof(CUVIDPARSERPARAMS)); oVideoParserParameters.CodecType = cudaCodec; oVideoParserParameters.ulMaxNumDecodeSurfaces = MAX_DECODE_FRAMES; oVideoParserParameters.ulMaxDisplayDelay = m_DisplayDelay; oVideoParserParameters.pUserData = this; oVideoParserParameters.pfnSequenceCallback = CDecCuvid::HandleVideoSequence; // Called before decoding frames and/or whenever there is a format change oVideoParserParameters.pfnDecodePicture = CDecCuvid::HandlePictureDecode; // Called when a picture is ready to be decoded (decode order) oVideoParserParameters.pfnDisplayPicture = CDecCuvid::HandlePictureDisplay; // Called whenever a picture is ready to be displayed (display order) oVideoParserParameters.ulErrorThreshold = m_bUseTimestampQueue ? 100 : 0; memset(&m_VideoParserExInfo, 0, sizeof(CUVIDEOFORMATEX)); // Handle AnnexB conversion for H.264 and HEVC if (pmt->formattype == FORMAT_MPEG2Video && (pmt->subtype == MEDIASUBTYPE_AVC1 || pmt->subtype == MEDIASUBTYPE_avc1 || pmt->subtype == MEDIASUBTYPE_CCV1 || pmt->subtype == MEDIASUBTYPE_HVC1)) { MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->Format(); m_AnnexBConverter = new CAnnexBConverter(); m_AnnexBConverter->SetNALUSize(2); BYTE *annexBextra = nullptr; int size = 0; if (cudaCodec == cudaVideoCodec_H264) { m_AnnexBConverter->Convert(&annexBextra, &size, (BYTE *)mp2vi->dwSequenceHeader, mp2vi->cbSequenceHeader); } else if (cudaCodec == cudaVideoCodec_HEVC && mp2vi->cbSequenceHeader >= 23) { BYTE *bHEVCHeader = (BYTE *)mp2vi->dwSequenceHeader; int nal_len_size = (bHEVCHeader[21] & 3) + 1; if (nal_len_size != mp2vi->dwFlags) { DbgLog((LOG_ERROR, 10, L"hvcC nal length size doesn't match media type")); } m_AnnexBConverter->ConvertHEVCExtradata(&annexBextra, &size, (BYTE *)mp2vi->dwSequenceHeader, mp2vi->cbSequenceHeader); } if (annexBextra && size) { size = min(size, sizeof(m_VideoParserExInfo.raw_seqhdr_data)); memcpy(m_VideoParserExInfo.raw_seqhdr_data, annexBextra, size); m_VideoParserExInfo.format.seqhdr_data_length = size; av_freep(&annexBextra); } m_AnnexBConverter->SetNALUSize(mp2vi->dwFlags); } else { size_t hdr_len = 0; getExtraData(*pmt, nullptr, &hdr_len); if (hdr_len <= 1024) { getExtraData(*pmt, m_VideoParserExInfo.raw_seqhdr_data, &hdr_len); m_VideoParserExInfo.format.seqhdr_data_length = (unsigned int)hdr_len; } } int bitdepth = 8; m_bNeedSequenceCheck = FALSE; if (m_VideoParserExInfo.format.seqhdr_data_length) { if (cudaCodec == cudaVideoCodec_H264) { hr = CheckH264Sequence(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length); if (FAILED(hr)) { return VFW_E_UNSUPPORTED_VIDEO; } else if (hr == S_FALSE) { m_bNeedSequenceCheck = TRUE; } } else if (cudaCodec == cudaVideoCodec_MPEG2) { DbgLog((LOG_TRACE, 10, L"-> Scanning extradata for MPEG2 sequence header")); CMPEG2HeaderParser mpeg2parser(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length); if (mpeg2parser.hdr.valid) { if (mpeg2parser.hdr.chroma >= 2) { DbgLog((LOG_TRACE, 10, L" -> Sequence header indicates incompatible chroma sampling (chroma: %d)", mpeg2parser.hdr.chroma)); return VFW_E_UNSUPPORTED_VIDEO; } m_bInterlaced = mpeg2parser.hdr.interlaced; } } else if (cudaCodec == cudaVideoCodec_VC1) { CVC1HeaderParser vc1Parser(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length); m_bInterlaced = vc1Parser.hdr.interlaced; } else if (cudaCodec == cudaVideoCodec_HEVC) { hr = CheckHEVCSequence(m_VideoParserExInfo.raw_seqhdr_data, m_VideoParserExInfo.format.seqhdr_data_length, &bitdepth); if (FAILED(hr)) { return VFW_E_UNSUPPORTED_VIDEO; } else if (hr == S_FALSE) { m_bNeedSequenceCheck = TRUE; } } } else { m_bNeedSequenceCheck = (cudaCodec == cudaVideoCodec_H264 || cudaCodec == cudaVideoCodec_HEVC); } oVideoParserParameters.pExtVideoInfo = &m_VideoParserExInfo; CUresult oResult = cuda.cuvidCreateVideoParser(&m_hParser, &oVideoParserParameters); if (oResult != CUDA_SUCCESS) { DbgLog((LOG_ERROR, 10, L"-> Creating parser for type %d failed with code %d", cudaCodec, oResult)); return E_FAIL; } BITMAPINFOHEADER *bmi = nullptr; videoFormatTypeHandler(pmt->Format(), pmt->FormatType(), &bmi); { hr = CreateCUVIDDecoder(cudaCodec, bmi->biWidth, bmi->biHeight, bitdepth, !m_bInterlaced); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Creating CUVID decoder failed")); return hr; } } m_bForceSequenceUpdate = TRUE; DecodeSequenceData(); return S_OK; } STDMETHODIMP CDecCuvid::CreateCUVIDDecoder(cudaVideoCodec codec, DWORD dwWidth, DWORD dwHeight, int nBitdepth, bool bProgressiveSequence) { DbgLog((LOG_TRACE, 10, L"CDecCuvid::CreateCUVIDDecoder(): Creating CUVID decoder instance")); HRESULT hr = S_OK; BOOL bDXVAMode = (m_pD3DDevice9 != nullptr); cuda.cuvidCtxLock(m_cudaCtxLock, 0); CUVIDDECODECREATEINFO *dci = &m_VideoDecoderInfo; retry: if (m_hDecoder) { cuda.cuvidDestroyDecoder(m_hDecoder); m_hDecoder = 0; } ZeroMemory(dci, sizeof(*dci)); dci->ulWidth = dwWidth; dci->ulHeight = dwHeight; dci->ulNumDecodeSurfaces = MAX_DECODE_FRAMES; dci->CodecType = codec; dci->bitDepthMinus8 = nBitdepth - 8; dci->ChromaFormat = cudaVideoChromaFormat_420; dci->OutputFormat = nBitdepth > 8 ? cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12; dci->DeinterlaceMode = (bProgressiveSequence || (m_pSettings->GetDeinterlacingMode() == DeintMode_Disable)) ? cudaVideoDeinterlaceMode_Weave : (cudaVideoDeinterlaceMode)m_pSettings->GetHWAccelDeintMode(); dci->ulNumOutputSurfaces = 1; dci->ulTargetWidth = dwWidth; dci->ulTargetHeight = dwHeight; // can't provide the original values here, or the decoder starts doing weird things - scaling to the size and // cropping afterwards dci->display_area.right = (short)dwWidth; dci->display_area.bottom = (short)dwHeight; dci->ulCreationFlags = bDXVAMode ? cudaVideoCreate_PreferDXVA : cudaVideoCreate_PreferCUVID; dci->vidLock = m_cudaCtxLock; // create the decoder CUresult oResult = cuda.cuvidCreateDecoder(&m_hDecoder, dci); if (oResult != CUDA_SUCCESS) { DbgLog((LOG_ERROR, 10, L"-> Creation of decoder for type %d failed with code %d", dci->CodecType, oResult)); if (bDXVAMode) { DbgLog((LOG_ERROR, 10, L" -> Retrying in pure CUVID mode")); bDXVAMode = FALSE; goto retry; } hr = E_FAIL; } cuda.cuvidCtxUnlock(m_cudaCtxLock, 0); return hr; } STDMETHODIMP CDecCuvid::DecodeSequenceData() { CUresult oResult; CUVIDSOURCEDATAPACKET pCuvidPacket; ZeroMemory(&pCuvidPacket, sizeof(pCuvidPacket)); pCuvidPacket.payload = m_VideoParserExInfo.raw_seqhdr_data; pCuvidPacket.payload_size = m_VideoParserExInfo.format.seqhdr_data_length; if (pCuvidPacket.payload && pCuvidPacket.payload_size) { cuda.cuvidCtxLock(m_cudaCtxLock, 0); oResult = cuda.cuvidParseVideoData(m_hParser, &pCuvidPacket); cuda.cuvidCtxUnlock(m_cudaCtxLock, 0); } return S_OK; } CUVIDPARSERDISPINFO *CDecCuvid::GetNextFrame() { int next = (m_DisplayPos + 1) % m_DisplayDelay; return &m_DisplayQueue[next]; } int CUDAAPI CDecCuvid::HandleVideoSequence(void *obj, CUVIDEOFORMAT *cuvidfmt) { DbgLog((LOG_TRACE, 10, L"CDecCuvid::HandleVideoSequence(): New Video Sequence")); CDecCuvid *filter = static_cast(obj); CUVIDDECODECREATEINFO *dci = &filter->m_VideoDecoderInfo; // Check if we should be deinterlacing bool bShouldDeinterlace = (!cuvidfmt->progressive_sequence && filter->m_pSettings->GetDeinterlacingMode() != DeintMode_Disable && filter->m_pSettings->GetHWAccelDeintMode() != HWDeintMode_Weave); // Re-initialize the decoder if needed if ((cuvidfmt->codec != dci->CodecType) || (cuvidfmt->coded_width != dci->ulWidth) || (cuvidfmt->coded_height != dci->ulHeight) || (cuvidfmt->chroma_format != dci->ChromaFormat) || (cuvidfmt->bit_depth_luma_minus8 != dci->bitDepthMinus8) || (bShouldDeinterlace != (dci->DeinterlaceMode != cudaVideoDeinterlaceMode_Weave)) || filter->m_bForceSequenceUpdate) { filter->m_bForceSequenceUpdate = FALSE; HRESULT hr = filter->CreateCUVIDDecoder(cuvidfmt->codec, cuvidfmt->coded_width, cuvidfmt->coded_height, cuvidfmt->bit_depth_luma_minus8 + 8, cuvidfmt->progressive_sequence != 0); if (FAILED(hr)) filter->m_bFormatIncompatible = TRUE; } filter->m_bInterlaced = !cuvidfmt->progressive_sequence; filter->m_bDoubleRateDeint = bShouldDeinterlace && (filter->m_pSettings->GetHWAccelDeintOutput() == DeintOutput_FramePerField); if (filter->m_bInterlaced && cuvidfmt->frame_rate.numerator && cuvidfmt->frame_rate.denominator) { double dFrameTime = 10000000.0 / ((double)cuvidfmt->frame_rate.numerator / cuvidfmt->frame_rate.denominator); if (filter->m_bDoubleRateDeint && (int)(dFrameTime / 10000.0) == 41) { filter->m_bDoubleRateDeint = TRUE; } if (cuvidfmt->codec != cudaVideoCodec_MPEG4) filter->m_rtAvgTimePerFrame = REFERENCE_TIME(dFrameTime + 0.5); else filter->m_rtAvgTimePerFrame = AV_NOPTS_VALUE; // TODO: base on media type } else { filter->m_rtAvgTimePerFrame = AV_NOPTS_VALUE; } // Adjust frame time for double-rate deint if (filter->m_bDoubleRateDeint && filter->m_rtAvgTimePerFrame != AV_NOPTS_VALUE) filter->m_rtAvgTimePerFrame /= 2; filter->m_VideoFormat = *cuvidfmt; if (cuvidfmt->chroma_format != cudaVideoChromaFormat_420) { DbgLog((LOG_TRACE, 10, L"CDecCuvid::HandleVideoSequence(): Incompatible Chroma Format detected")); filter->m_bFormatIncompatible = TRUE; } fillDXVAExtFormat(filter->m_DXVAExtendedFormat, (filter->m_iFullRange > 0 || cuvidfmt->video_signal_description.video_full_range_flag), cuvidfmt->video_signal_description.color_primaries, cuvidfmt->video_signal_description.matrix_coefficients, cuvidfmt->video_signal_description.transfer_characteristics); return TRUE; } int CUDAAPI CDecCuvid::HandlePictureDecode(void *obj, CUVIDPICPARAMS *cuvidpic) { CDecCuvid *filter = reinterpret_cast(obj); if (filter->m_bFlushing) return FALSE; if (filter->m_bWaitForKeyframe) { if (cuvidpic->intra_pic_flag) filter->m_bWaitForKeyframe = FALSE; else { // Pop timestamp from the queue, drop frame if (!filter->m_timestampQueue.empty()) { filter->m_timestampQueue.pop(); } return FALSE; } } int flush_pos = filter->m_DisplayPos; for (;;) { bool frame_in_use = false; for (int i = 0; i < filter->m_DisplayDelay; i++) { if (filter->m_DisplayQueue[i].picture_index == cuvidpic->CurrPicIdx) { frame_in_use = true; break; } } if (!frame_in_use) { // No problem: we're safe to use this frame break; } // The target frame is still pending in the display queue: // Flush the oldest entry from the display queue and repeat if (filter->m_DisplayQueue[flush_pos].picture_index >= 0) { filter->Display(&filter->m_DisplayQueue[flush_pos]); filter->m_DisplayQueue[flush_pos].picture_index = -1; } flush_pos = (flush_pos + 1) % filter->m_DisplayDelay; } filter->cuda.cuvidCtxLock(filter->m_cudaCtxLock, 0); filter->m_PicParams[cuvidpic->CurrPicIdx] = *cuvidpic; __try { CUresult cuStatus = filter->cuda.cuvidDecodePicture(filter->m_hDecoder, cuvidpic); #ifdef DEBUG if (cuStatus != CUDA_SUCCESS) { DbgLog((LOG_ERROR, 10, L"CDecCuvid::HandlePictureDecode(): cuvidDecodePicture returned error code %d", cuStatus)); } #endif } __except (1) { DbgLog((LOG_ERROR, 10, L"CDecCuvid::HandlePictureDecode(): cuvidDecodePicture threw an exception")); } filter->cuda.cuvidCtxUnlock(filter->m_cudaCtxLock, 0); return TRUE; } int CUDAAPI CDecCuvid::HandlePictureDisplay(void *obj, CUVIDPARSERDISPINFO *cuviddisp) { CDecCuvid *filter = reinterpret_cast(obj); if (filter->m_bFlushing) return FALSE; if (filter->m_bUseTimestampQueue) { if (filter->m_timestampQueue.empty()) { cuviddisp->timestamp = AV_NOPTS_VALUE; } else { cuviddisp->timestamp = filter->m_timestampQueue.front(); filter->m_timestampQueue.pop(); } } // Drop samples with negative timestamps (preroll) or during flushing if (cuviddisp->timestamp != AV_NOPTS_VALUE && cuviddisp->timestamp < 0) return TRUE; if (filter->m_DisplayQueue[filter->m_DisplayPos].picture_index >= 0) { filter->Display(&filter->m_DisplayQueue[filter->m_DisplayPos]); filter->m_DisplayQueue[filter->m_DisplayPos].picture_index = -1; } filter->m_DisplayQueue[filter->m_DisplayPos] = *cuviddisp; filter->m_DisplayPos = (filter->m_DisplayPos + 1) % filter->m_DisplayDelay; return TRUE; } STDMETHODIMP CDecCuvid::Display(CUVIDPARSERDISPINFO *cuviddisp) { BOOL bTreatAsProgressive = m_pSettings->GetDeinterlacingMode() == DeintMode_Disable; if (bTreatAsProgressive) { cuviddisp->progressive_frame = TRUE; m_nSoftTelecine = FALSE; } else { if (m_VideoFormat.codec == cudaVideoCodec_MPEG2 || m_VideoFormat.codec == cudaVideoCodec_H264) { if (cuviddisp->repeat_first_field) { m_nSoftTelecine = 2; } else if (m_nSoftTelecine) { m_nSoftTelecine--; } if (!m_nSoftTelecine) m_bTFF = cuviddisp->top_field_first; } cuviddisp->progressive_frame = (cuviddisp->progressive_frame && !(m_bInterlaced && m_pSettings->GetDeinterlacingMode() == DeintMode_Aggressive && m_VideoFormat.codec != cudaVideoCodec_VC1 && !m_nSoftTelecine) && !(m_pSettings->GetDeinterlacingMode() == DeintMode_Force)); } LAVDeintFieldOrder fo = m_pSettings->GetDeintFieldOrder(); cuviddisp->top_field_first = (fo == DeintFieldOrder_Auto) ? (m_nSoftTelecine ? m_bTFF : cuviddisp->top_field_first) : (fo == DeintFieldOrder_TopFieldFirst); if (m_bDoubleRateDeint) { if (cuviddisp->progressive_frame || m_nSoftTelecine) { Deliver(cuviddisp, 2); } else { Deliver(cuviddisp, 0); Deliver(cuviddisp, 1); } } else { Deliver(cuviddisp); } return S_OK; } STDMETHODIMP CDecCuvid::Deliver(CUVIDPARSERDISPINFO *cuviddisp, int field) { CUdeviceptr devPtr = 0; unsigned int pitch = 0; CUVIDPROCPARAMS vpp; CUresult cuStatus = CUDA_SUCCESS; memset(&vpp, 0, sizeof(vpp)); vpp.progressive_frame = !m_nSoftTelecine && cuviddisp->progressive_frame; vpp.top_field_first = cuviddisp->top_field_first; vpp.second_field = (field == 1); cuda.cuvidCtxLock(m_cudaCtxLock, 0); cuStatus = cuda.cuvidMapVideoFrame(m_hDecoder, cuviddisp->picture_index, &devPtr, &pitch, &vpp); if (cuStatus != CUDA_SUCCESS) { DbgLog( (LOG_CUSTOM1, 1, L"CDecCuvid::Deliver(): cuvidMapVideoFrame failed on index %d", cuviddisp->picture_index)); goto cuda_fail; } int size = pitch * m_VideoDecoderInfo.ulTargetHeight * 3 / 2; if (!m_pbRawNV12 || size > m_cRawNV12) { if (m_pbRawNV12) { cuda.cuMemFreeHost(m_pbRawNV12); m_pbRawNV12 = nullptr; m_cRawNV12 = 0; } cuStatus = cuda.cuMemAllocHost((void **)&m_pbRawNV12, size); if (cuStatus != CUDA_SUCCESS) { DbgLog((LOG_CUSTOM1, 1, L"CDecCuvid::Deliver(): cuMemAllocHost failed to allocate %d bytes (%d)", size, cuStatus)); goto cuda_fail; } m_cRawNV12 = size; } // Copy memory from the device into the staging area if (m_pbRawNV12) { cuStatus = cuda.cuMemcpyDtoH(m_pbRawNV12, devPtr, size); if (cuStatus != CUDA_SUCCESS) { DbgLog((LOG_ERROR, 10, L"Memory Transfer failed (%d)", cuStatus)); goto cuda_fail; } } else { // If we don't have our memory, this is bad. DbgLog((LOG_ERROR, 10, L"No Valid Staging Memory - failing")); goto cuda_fail; } cuda.cuvidUnmapVideoFrame(m_hDecoder, devPtr); cuda.cuvidCtxUnlock(m_cudaCtxLock, 0); // Setup the LAVFrame LAVFrame *pFrame = nullptr; AllocateFrame(&pFrame); if (m_rtAvgTimePerFrame != AV_NOPTS_VALUE) { pFrame->avgFrameDuration = m_rtAvgTimePerFrame; if (m_bDoubleRateDeint && field == 2) pFrame->avgFrameDuration *= 2; } REFERENCE_TIME rtStart = cuviddisp->timestamp, rtStop = AV_NOPTS_VALUE; if (rtStart != AV_NOPTS_VALUE) { CUVIDPARSERDISPINFO *next = GetNextFrame(); if (next->picture_index != -1 && next->timestamp != AV_NOPTS_VALUE) { m_rtPrevDiff = next->timestamp - cuviddisp->timestamp; } if (m_rtPrevDiff != AV_NOPTS_VALUE) { REFERENCE_TIME rtHalfDiff = m_rtPrevDiff >> 1; if (field == 1) rtStart += rtHalfDiff; rtStop = rtStart + rtHalfDiff; if (field == 2 || !m_bDoubleRateDeint) rtStop += rtHalfDiff; } // Sanity check in case the duration is null if (rtStop <= rtStart) rtStop = AV_NOPTS_VALUE; } pFrame->format = (m_VideoDecoderInfo.OutputFormat == cudaVideoSurfaceFormat_P016) ? LAVPixFmt_P016 : LAVPixFmt_NV12; pFrame->sw_format = pFrame->format; pFrame->bpp = m_VideoDecoderInfo.bitDepthMinus8 + 8; pFrame->width = m_VideoFormat.display_area.right; pFrame->height = m_VideoFormat.display_area.bottom; pFrame->rtStart = rtStart; pFrame->rtStop = rtStop; pFrame->repeat = cuviddisp->repeat_first_field; { AVRational ar = {m_VideoFormat.display_aspect_ratio.x, m_VideoFormat.display_aspect_ratio.y}; AVRational arDim = {pFrame->width, pFrame->height}; if (m_bARPresent || av_cmp_q(ar, arDim) != 0) { pFrame->aspect_ratio = ar; } } pFrame->ext_format = m_DXVAExtendedFormat; pFrame->interlaced = !cuviddisp->progressive_frame && m_VideoDecoderInfo.DeinterlaceMode == cudaVideoDeinterlaceMode_Weave; pFrame->tff = cuviddisp->top_field_first; // TODO: This may be wrong for H264 where B-Frames can be references pFrame->frame_type = m_PicParams[cuviddisp->picture_index].intra_pic_flag ? 'I' : (m_PicParams[cuviddisp->picture_index].ref_pic_flag ? 'P' : 'B'); // Assign the buffer to the LAV Frame bufers int Ysize = m_VideoDecoderInfo.ulTargetHeight * pitch; pFrame->data[0] = m_pbRawNV12; pFrame->data[1] = m_pbRawNV12 + Ysize; pFrame->stride[0] = pFrame->stride[1] = pitch; pFrame->flags |= LAV_FRAME_FLAG_BUFFER_MODIFY; if (m_bEndOfSequence) pFrame->flags |= LAV_FRAME_FLAG_END_OF_SEQUENCE; m_pCallback->Deliver(pFrame); return S_OK; cuda_fail: cuda.cuvidUnmapVideoFrame(m_hDecoder, devPtr); cuda.cuvidCtxUnlock(m_cudaCtxLock, 0); return E_FAIL; } STDMETHODIMP CDecCuvid::CheckH264Sequence(const BYTE *buffer, int buflen) { DbgLog((LOG_TRACE, 10, L"CDecCuvid::CheckH264Sequence(): Checking H264 frame for SPS")); CH264SequenceParser h264parser; h264parser.ParseNALs(buffer, buflen, 0); if (h264parser.sps.valid) { m_bInterlaced = h264parser.sps.interlaced; m_iFullRange = h264parser.sps.full_range; m_bARPresent = h264parser.sps.ar_present; DbgLog((LOG_TRACE, 10, L"-> SPS found")); if (h264parser.sps.profile > 100 || h264parser.sps.chroma != 1 || h264parser.sps.luma_bitdepth != 8 || h264parser.sps.chroma_bitdepth != 8 || h264parser.sps.level >= 60) { DbgLog((LOG_TRACE, 10, L" -> SPS indicates video incompatible with CUVID, aborting (profile: %d, level: %d, chroma: %d, bitdepth: " L"%d/%d)", h264parser.sps.profile, h264parser.sps.level, h264parser.sps.chroma, h264parser.sps.luma_bitdepth, h264parser.sps.chroma_bitdepth)); return E_FAIL; } DbgLog((LOG_TRACE, 10, L"-> Video seems compatible with CUVID")); return S_OK; } return S_FALSE; } STDMETHODIMP CDecCuvid::CheckHEVCSequence(const BYTE *buffer, int buflen, int *bitdepth) { DbgLog((LOG_TRACE, 10, L"CDecCuvid::CheckHEVCSequence(): Checking HEVC frame for SPS")); CHEVCSequenceParser hevcParser; hevcParser.ParseNALs(buffer, buflen, 0); if (hevcParser.sps.valid) { DbgLog((LOG_TRACE, 10, L"-> SPS found")); if (hevcParser.sps.chroma > 1 || hevcParser.sps.bitdepth > 12 || !(hevcParser.sps.profile <= AV_PROFILE_HEVC_MAIN_10 || (hevcParser.sps.profile == AV_PROFILE_HEVC_REXT && hevcParser.sps.rext_profile == HEVC_REXT_PROFILE_MAIN_12))) { DbgLog((LOG_TRACE, 10, L" -> SPS indicates video incompatible with CUVID, aborting (profile: %d)", hevcParser.sps.profile)); return E_FAIL; } if (bitdepth) *bitdepth = hevcParser.sps.bitdepth; DbgLog((LOG_TRACE, 10, L"-> Video seems compatible with CUVID")); return S_OK; } return S_FALSE; } STDMETHODIMP CDecCuvid::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample) { CUresult result; HRESULT hr = S_OK; CUVIDSOURCEDATAPACKET pCuvidPacket; ZeroMemory(&pCuvidPacket, sizeof(pCuvidPacket)); BYTE *pBuffer = nullptr; if (m_AnnexBConverter) { int size = 0; hr = m_AnnexBConverter->Convert(&pBuffer, &size, buffer, buflen); if (SUCCEEDED(hr)) { pCuvidPacket.payload = pBuffer; pCuvidPacket.payload_size = size; } } else { pCuvidPacket.payload = buffer; pCuvidPacket.payload_size = buflen; if (m_VideoDecoderInfo.CodecType == cudaVideoCodec_MPEG2) { const uint8_t *eosmarker = nullptr; const uint8_t *end = buffer + buflen; int status = CheckForSequenceMarkers(AV_CODEC_ID_MPEG2VIDEO, buffer, buflen, &m_MpegParserState, &eosmarker); // If we found a EOS marker, but its not at the end of the packet, then split the packet // to be able to individually decode the frame before the EOS, and then decode the remainder if (status & STATE_EOS_FOUND && eosmarker && eosmarker != end) { Decode(buffer, (int)(eosmarker - buffer), rtStart, rtStop, bSyncPoint, bDiscontinuity, nullptr); rtStart = rtStop = AV_NOPTS_VALUE; pCuvidPacket.payload = eosmarker; pCuvidPacket.payload_size = (int)(end - eosmarker); } else if (eosmarker) { m_bEndOfSequence = TRUE; } } } if (m_bNeedSequenceCheck) { if (m_VideoDecoderInfo.CodecType == cudaVideoCodec_H264) { hr = CheckH264Sequence(pCuvidPacket.payload, pCuvidPacket.payload_size); } else if (m_VideoDecoderInfo.CodecType == cudaVideoCodec_HEVC) { hr = CheckHEVCSequence(pCuvidPacket.payload, pCuvidPacket.payload_size, nullptr); } if (FAILED(hr)) { m_bFormatIncompatible = TRUE; } else if (hr == S_OK) { m_bNeedSequenceCheck = FALSE; } } if (rtStart != AV_NOPTS_VALUE) { pCuvidPacket.flags |= CUVID_PKT_TIMESTAMP; pCuvidPacket.timestamp = rtStart; } if (bDiscontinuity) pCuvidPacket.flags |= CUVID_PKT_DISCONTINUITY; if (m_bUseTimestampQueue) m_timestampQueue.push(rtStart); cuda.cuvidCtxLock(m_cudaCtxLock, 0); __try { result = cuda.cuvidParseVideoData(m_hParser, &pCuvidPacket); } __except (1) { DbgLog((LOG_ERROR, 10, L"CDecCuvid::Decode(): cuvidParseVideoData threw an exception")); } cuda.cuvidCtxUnlock(m_cudaCtxLock, 0); av_freep(&pBuffer); if (m_bEndOfSequence) { EndOfStream(); m_pCallback->Deliver(m_pCallback->GetFlushFrame()); m_bEndOfSequence = FALSE; } if (m_bFormatIncompatible) { DbgLog((LOG_ERROR, 10, L"CDecCuvid::Decode(): Incompatible format detected, indicating failure...")); return E_FAIL; } return S_OK; } STDMETHODIMP CDecCuvid::Flush() { DbgLog((LOG_TRACE, 10, L"CDecCuvid::Flush(): Flushing CUVID decoder")); m_bFlushing = TRUE; FlushParser(); // Flush display queue for (int i = 0; i < m_DisplayDelay; ++i) { if (m_DisplayQueue[m_DisplayPos].picture_index >= 0) { m_DisplayQueue[m_DisplayPos].picture_index = -1; } m_DisplayPos = (m_DisplayPos + 1) % m_DisplayDelay; } m_bFlushing = FALSE; m_bWaitForKeyframe = m_bUseTimestampQueue; // Re-init decoder after flush DecodeSequenceData(); // Clear timestamp queue std::queue().swap(m_timestampQueue); m_nSoftTelecine = 0; return __super::Flush(); } STDMETHODIMP CDecCuvid::EndOfStream() { FlushParser(); // Display all frames left in the queue for (int i = 0; i < m_DisplayDelay; ++i) { if (m_DisplayQueue[m_DisplayPos].picture_index >= 0) { Display(&m_DisplayQueue[m_DisplayPos]); m_DisplayQueue[m_DisplayPos].picture_index = -1; } m_DisplayPos = (m_DisplayPos + 1) % m_DisplayDelay; } return S_OK; } STDMETHODIMP CDecCuvid::GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { // Output is always NV12 if (pPix) *pPix = (m_VideoDecoderInfo.OutputFormat == cudaVideoSurfaceFormat_P016) ? LAVPixFmt_P016 : LAVPixFmt_NV12; if (pBpp) *pBpp = m_VideoDecoderInfo.bitDepthMinus8 + 8; if (pPixSoftware) *pPixSoftware = (m_VideoDecoderInfo.OutputFormat == cudaVideoSurfaceFormat_P016) ? LAVPixFmt_P016 : LAVPixFmt_NV12; return S_OK; } STDMETHODIMP_(REFERENCE_TIME) CDecCuvid::GetFrameDuration() { return 0; } STDMETHODIMP_(BOOL) CDecCuvid::IsInterlaced(BOOL bAllowGuess) { return (m_bInterlaced || m_pSettings->GetDeinterlacingMode() == DeintMode_Force) && (m_VideoDecoderInfo.DeinterlaceMode == cudaVideoDeinterlaceMode_Weave); } STDMETHODIMP CDecCuvid::GetHWAccelActiveDevice(BSTR *pstrDeviceName) { CheckPointer(pstrDeviceName, E_POINTER); if (strlen(m_cudaDeviceName) == 0) return E_UNEXPECTED; int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, m_cudaDeviceName, -1, nullptr, 0); if (len == 0) return E_FAIL; *pstrDeviceName = SysAllocStringLen(nullptr, len); MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, m_cudaDeviceName, -1, *pstrDeviceName, len); return S_OK; } ================================================ FILE: decoder/LAVVideo/decoders/cuvid.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DecBase.h" #define MAX_DECODE_FRAMES 20 #define DISPLAY_DELAY 4 #define MAX_PIC_INDEX 64 #include "cuvid/dynlink_cuda.h" #include "cuvid/dynlink_nvcuvid.h" #define CUDA_INIT_D3D9 #include "cuvid/dynlink_cuda_d3d.h" #include "parsers/AnnexBConverter.h" #include #define CUMETHOD(name) t##name *##name class CDecCuvid : public CDecBase { public: CDecCuvid(void); virtual ~CDecCuvid(void); // ILAVDecoder STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware); STDMETHODIMP_(REFERENCE_TIME) GetFrameDuration(); STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess); STDMETHODIMP_(const WCHAR *) GetDecoderName() { return L"cuvid"; } STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName); // CDecBase STDMETHODIMP Init(); private: STDMETHODIMP LoadCUDAFuncRefs(); STDMETHODIMP DestroyDecoder(bool bFull); STDMETHODIMP InitD3D9(int best_device, DWORD requested_device); STDMETHODIMP CreateCUVIDDecoder(cudaVideoCodec codec, DWORD dwWidth, DWORD dwHeight, int nBitdepth, bool bProgressiveSequence); STDMETHODIMP DecodeSequenceData(); // CUDA Callbacks static int CUDAAPI HandleVideoSequence(void *obj, CUVIDEOFORMAT *cuvidfmt); static int CUDAAPI HandlePictureDecode(void *obj, CUVIDPICPARAMS *cuvidpic); static int CUDAAPI HandlePictureDisplay(void *obj, CUVIDPARSERDISPINFO *cuviddisp); STDMETHODIMP Display(CUVIDPARSERDISPINFO *cuviddisp); STDMETHODIMP Deliver(CUVIDPARSERDISPINFO *cuviddisp, int field = 0); CUVIDPARSERDISPINFO *GetNextFrame(); STDMETHODIMP FlushParser(); STDMETHODIMP CheckH264Sequence(const BYTE *buffer, int buflen); STDMETHODIMP CheckHEVCSequence(const BYTE *buffer, int buflen, int *bitdepth); int GetMaxGflopsGraphicsDeviceId(); private: struct { HMODULE cudaLib; CUMETHOD(cuInit); CUMETHOD(cuCtxCreate); CUMETHOD(cuCtxDestroy); CUMETHOD(cuCtxPushCurrent); CUMETHOD(cuCtxPopCurrent); CUMETHOD(cuD3D9CtxCreate); CUMETHOD(cuMemAllocHost); CUMETHOD(cuMemFreeHost); CUMETHOD(cuMemcpyDtoH); CUMETHOD(cuDeviceGetCount); CUMETHOD(cuDriverGetVersion); CUMETHOD(cuDeviceGetName); CUMETHOD(cuDeviceComputeCapability); CUMETHOD(cuDeviceGetAttribute); HMODULE cuvidLib; CUMETHOD(cuvidCtxLockCreate); CUMETHOD(cuvidCtxLockDestroy); CUMETHOD(cuvidCtxLock); CUMETHOD(cuvidCtxUnlock); CUMETHOD(cuvidCreateVideoParser); CUMETHOD(cuvidParseVideoData); CUMETHOD(cuvidDestroyVideoParser); CUMETHOD(cuvidCreateDecoder); CUMETHOD(cuvidDecodePicture); CUMETHOD(cuvidDestroyDecoder); CUMETHOD(cuvidMapVideoFrame); CUMETHOD(cuvidUnmapVideoFrame); #ifdef _M_AMD64 CUMETHOD(cuvidMapVideoFrame64); CUMETHOD(cuvidUnmapVideoFrame64); #endif } cuda; IDirect3D9 *m_pD3D9 = nullptr; IDirect3DDevice9 *m_pD3DDevice9 = nullptr; CUcontext m_cudaContext = 0; CUvideoctxlock m_cudaCtxLock = 0; CUvideoparser m_hParser = 0; CUVIDEOFORMATEX m_VideoParserExInfo; CUvideodecoder m_hDecoder = 0; CUVIDDECODECREATEINFO m_VideoDecoderInfo; CUVIDEOFORMAT m_VideoFormat; CUVIDPARSERDISPINFO m_DisplayQueue[DISPLAY_DELAY]; int m_DisplayPos = 0; CUVIDPICPARAMS m_PicParams[MAX_PIC_INDEX]; BOOL m_bVDPAULevelC = FALSE; char m_cudaDeviceName[256] = {0}; BOOL m_bForceSequenceUpdate = FALSE; BOOL m_bInterlaced = FALSE; BOOL m_bDoubleRateDeint = FALSE; BOOL m_bFlushing = FALSE; REFERENCE_TIME m_rtAvgTimePerFrame = AV_NOPTS_VALUE; REFERENCE_TIME m_rtPrevDiff = AV_NOPTS_VALUE; BOOL m_bWaitForKeyframe = FALSE; int m_iFullRange = -1; DXVA2_ExtendedFormat m_DXVAExtendedFormat; BYTE *m_pbRawNV12 = nullptr; int m_cRawNV12 = 0; CAnnexBConverter *m_AnnexBConverter = nullptr; BOOL m_bFormatIncompatible = FALSE; BOOL m_bNeedSequenceCheck = FALSE; BOOL m_bUseTimestampQueue = FALSE; std::queue m_timestampQueue; int m_nSoftTelecine = 0; BOOL m_bTFF = TRUE; BOOL m_bARPresent = TRUE; BOOL m_bEndOfSequence = FALSE; int m_DisplayDelay = DISPLAY_DELAY; }; ================================================ FILE: decoder/LAVVideo/decoders/d3d11/D3D11SurfaceAllocator.cpp ================================================ /* * Copyright (C) 2019-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "D3D11SurfaceAllocator.h" #include "decoders/d3d11va.h" extern "C" { #include "libavutil/hwcontext.h" } CD3D11MediaSample::CD3D11MediaSample(CD3D11SurfaceAllocator *pAllocator, AVFrame *pFrame, HRESULT *phr) : CMediaSampleSideData(NAME("CD3D11MediaSample"), (CBaseAllocator *)pAllocator, phr, nullptr, 0) , m_pFrame(pFrame) { ASSERT(m_pFrame && m_pFrame->format == AV_PIX_FMT_D3D11); pAllocator->AddRef(); m_pAllocatorCookie = pAllocator->m_pFramesCtx; } CD3D11MediaSample::~CD3D11MediaSample() { av_frame_free(&m_pFrame); SafeRelease(&m_pAllocator); } // Note: CMediaSample does not derive from CUnknown, so we cannot use the // DECLARE_IUNKNOWN macro that is used by most of the filter classes. STDMETHODIMP CD3D11MediaSample::QueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == __uuidof(IMediaSampleD3D11)) { return GetInterface((IMediaSampleD3D11 *)this, ppv); } else { return __super::QueryInterface(riid, ppv); } } STDMETHODIMP_(ULONG) CD3D11MediaSample::AddRef() { return __super::AddRef(); } STDMETHODIMP_(ULONG) CD3D11MediaSample::Release() { // Return a temporary variable for thread safety. ULONG cRef = __super::Release(); return cRef; } STDMETHODIMP CD3D11MediaSample::GetD3D11Texture(int nView, ID3D11Texture2D **ppTexture, UINT *pArraySlice) { CheckPointer(ppTexture, E_POINTER); CheckPointer(pArraySlice, E_POINTER); // only view 0 is implemented at this time if (nView != 0) return E_INVALIDARG; if (m_pFrame) { *ppTexture = (ID3D11Texture2D *)m_pFrame->data[0]; *pArraySlice = (UINT)(intptr_t)m_pFrame->data[1]; (*ppTexture)->AddRef(); return S_OK; } return E_FAIL; } static void bufref_release_sample(void *opaque, uint8_t *data) { CD3D11MediaSample *pSample = (CD3D11MediaSample *)opaque; pSample->Release(); } STDMETHODIMP CD3D11MediaSample::GetAVFrameBuffer(AVFrame *pFrame) { CheckPointer(pFrame, E_POINTER); // reference bufs for (int i = 0; i < AV_NUM_DATA_POINTERS; i++) { // copy existing refs if (m_pFrame->buf[i]) { pFrame->buf[i] = av_buffer_ref(m_pFrame->buf[i]); if (pFrame->buf[i] == 0) return E_OUTOFMEMORY; } else { // and add a ref to this sample pFrame->buf[i] = av_buffer_create((uint8_t *)this, 1, bufref_release_sample, this, 0); if (pFrame->buf[i] == 0) return E_OUTOFMEMORY; AddRef(); break; } } // ref the hwframes ctx pFrame->hw_frames_ctx = av_buffer_ref(m_pFrame->hw_frames_ctx); // copy data into the new frame pFrame->data[0] = m_pFrame->data[0]; pFrame->data[1] = m_pFrame->data[1]; pFrame->data[3] = (uint8_t *)this; pFrame->format = AV_PIX_FMT_D3D11; return S_OK; } CD3D11SurfaceAllocator::CD3D11SurfaceAllocator(CDecD3D11 *pDec, HRESULT *phr) : CBaseAllocator(NAME("CD3D11SurfaceAllocator"), nullptr, phr) , m_pDec(pDec) { } CD3D11SurfaceAllocator::~CD3D11SurfaceAllocator() { } HRESULT CD3D11SurfaceAllocator::Alloc(void) { DbgLog((LOG_TRACE, 10, L"CD3D11SurfaceAllocator::Alloc()")); HRESULT hr = S_OK; CAutoLock cObjectLock(this); if (m_pDec == nullptr) return E_FAIL; hr = __super::Alloc(); if (FAILED(hr)) return hr; // free old resources // m_pDec->FlushFromAllocator(); Free(); // get the frames context from the decoder AVBufferRef *pDecoderFramesCtx = m_pDec->m_pFramesCtx; if (pDecoderFramesCtx == nullptr) return S_FALSE; m_pFramesCtx = av_buffer_ref(pDecoderFramesCtx); if (m_pFramesCtx == nullptr) return E_FAIL; // create samples for (int i = 0; i < m_lCount; i++) { AVFrame *pFrame = av_frame_alloc(); int ret = av_hwframe_get_buffer(m_pFramesCtx, pFrame, 0); if (ret < 0) { av_frame_free(&pFrame); Free(); return E_FAIL; } CD3D11MediaSample *pSample = new CD3D11MediaSample(this, pFrame, &hr); if (pSample == nullptr || FAILED(hr)) { delete pSample; Free(); return E_FAIL; } m_lFree.Add(pSample); } m_lAllocated = m_lCount; m_bChanged = FALSE; return S_OK; } void CD3D11SurfaceAllocator::Free(void) { CAutoLock lock(this); CMediaSample *pSample = nullptr; do { pSample = m_lFree.RemoveHead(); if (pSample) { delete pSample; } } while (pSample); m_lAllocated = 0; av_buffer_unref(&m_pFramesCtx); } STDMETHODIMP CD3D11SurfaceAllocator::ReleaseBuffer(IMediaSample *pSample) { CD3D11MediaSample *pD3D11Sample = dynamic_cast(pSample); if (pD3D11Sample && pD3D11Sample->m_pAllocatorCookie != m_pFramesCtx) { DbgLog((LOG_TRACE, 10, L"CD3D11SurfaceAllocator::ReleaseBuffer: Freeing late sample")); delete pD3D11Sample; return S_OK; } else { return __super::ReleaseBuffer(pSample); } } STDMETHODIMP_(void) CD3D11SurfaceAllocator::ForceDecommit() { { CAutoLock lock(this); if (m_bCommitted || !m_bDecommitInProgress) return; // actually free all the samples that are already back Free(); // finish decommit, so that Alloc works again m_bDecommitInProgress = FALSE; } if (m_pNotify) { m_pNotify->NotifyRelease(); } // alloc holds one reference, we need free that here Release(); } ================================================ FILE: decoder/LAVVideo/decoders/d3d11/D3D11SurfaceAllocator.h ================================================ /* * Copyright (C) 2019-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #include "MediaSampleSideData.h" #include "ID3DVideoMemoryConfiguration.h" class CDecD3D11; class CD3D11MediaSample : public CMediaSampleSideData , public IMediaSampleD3D11 { friend class CD3D11SurfaceAllocator; public: CD3D11MediaSample(CD3D11SurfaceAllocator *pAllocator, AVFrame *pFrame, HRESULT *phr); virtual ~CD3D11MediaSample(); // IUnknown STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IMediaSample STDMETHODIMP GetPointer(BYTE **ppBuffer) { return E_NOTIMPL; } // IMediaSampleD3D11 STDMETHODIMP GetD3D11Texture(int nView, ID3D11Texture2D **ppTexture, UINT *pArraySlice); // LAV Interface STDMETHODIMP GetAVFrameBuffer(AVFrame *pFrame); private: AVFrame *m_pFrame = nullptr; void *m_pAllocatorCookie = nullptr; }; class CD3D11SurfaceAllocator : public CBaseAllocator { public: CD3D11SurfaceAllocator(CDecD3D11 *pDec, HRESULT *phr); virtual ~CD3D11SurfaceAllocator(); STDMETHODIMP ReleaseBuffer(IMediaSample *pSample); STDMETHODIMP_(BOOL) DecommitInProgress() { CAutoLock cal(this); return m_bDecommitInProgress; } STDMETHODIMP_(BOOL) IsCommited() { CAutoLock cal(this); return m_bCommitted; } STDMETHODIMP_(void) ForceDecommit(); // LAV interface STDMETHODIMP_(void) DecoderDestruct() { CAutoLock cal(this); m_pDec = nullptr; } protected: virtual void Free(void); virtual HRESULT Alloc(void); private: CDecD3D11 *m_pDec = nullptr; AVBufferRef *m_pFramesCtx = nullptr; friend class CD3D11MediaSample; }; ================================================ FILE: decoder/LAVVideo/decoders/d3d11va.cpp ================================================ /* * Copyright (C) 2017-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "d3d11va.h" #include "ID3DVideoMemoryConfiguration.h" #include "dxva2/dxva_common.h" #include "moreuuids.h" #include #define FF_DXVA2_WORKAROUND_NVIDIA_HEVC_420P12 4 ILAVDecoder *CreateDecoderD3D11() { return new CDecD3D11(); } HRESULT VerifyD3D11Device(DWORD &dwIndex, DWORD dwDeviceId) { HRESULT hr = S_OK; DXGI_ADAPTER_DESC desc; HMODULE dxgi = LoadLibrary(L"dxgi.dll"); if (dxgi == nullptr) { hr = E_FAIL; goto done; } PFN_CREATE_DXGI_FACTORY1 mCreateDXGIFactory1 = (PFN_CREATE_DXGI_FACTORY1)GetProcAddress(dxgi, "CreateDXGIFactory1"); if (mCreateDXGIFactory1 == nullptr) { hr = E_FAIL; goto done; } IDXGIAdapter *pDXGIAdapter = nullptr; IDXGIFactory1 *pDXGIFactory = nullptr; hr = mCreateDXGIFactory1(IID_IDXGIFactory1, (void **)&pDXGIFactory); if (FAILED(hr)) goto done; // check the adapter specified by dwIndex hr = pDXGIFactory->EnumAdapters(dwIndex, &pDXGIAdapter); if (FAILED(hr)) goto done; // if it matches the device id, then all is well and we're done pDXGIAdapter->GetDesc(&desc); if (desc.DeviceId == dwDeviceId) goto done; SafeRelease(&pDXGIAdapter); // try to find a device that matches this device id UINT i = 0; while (SUCCEEDED(pDXGIFactory->EnumAdapters(i, &pDXGIAdapter))) { pDXGIAdapter->GetDesc(&desc); SafeRelease(&pDXGIAdapter); if (desc.DeviceId == dwDeviceId) { dwIndex = i; goto done; } i++; } // if none is found, fail hr = E_FAIL; done: SafeRelease(&pDXGIAdapter); SafeRelease(&pDXGIFactory); FreeLibrary(dxgi); return hr; } //////////////////////////////////////////////////////////////////////////////// // D3D11 decoder implementation //////////////////////////////////////////////////////////////////////////////// static const D3D_FEATURE_LEVEL s_D3D11Levels[] = { D3D_FEATURE_LEVEL_12_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; static int s_GetD3D11FeatureLevels(int max_fl, const D3D_FEATURE_LEVEL **out) { static const int levels_len = countof(s_D3D11Levels); int start = 0; for (; start < levels_len; start++) { if (s_D3D11Levels[start] <= max_fl) break; } *out = &s_D3D11Levels[start]; return levels_len - start; } static DXGI_FORMAT d3d11va_map_sw_to_hw_format(enum AVPixelFormat pix_fmt) { switch (pix_fmt) { case AV_PIX_FMT_YUV444P: return DXGI_FORMAT_AYUV; case AV_PIX_FMT_YUV444P10: return DXGI_FORMAT_Y410; case AV_PIX_FMT_YUV444P12: case AV_PIX_FMT_YUV444P14: case AV_PIX_FMT_YUV444P16: return DXGI_FORMAT_Y416; case AV_PIX_FMT_YUV422P: return DXGI_FORMAT_YUY2; case AV_PIX_FMT_YUV422P10: return DXGI_FORMAT_Y210; case AV_PIX_FMT_YUV422P12: case AV_PIX_FMT_YUV422P14: case AV_PIX_FMT_YUV422P16: return DXGI_FORMAT_Y216; case AV_PIX_FMT_YUV420P12: case AV_PIX_FMT_YUV420P14: case AV_PIX_FMT_YUV420P16: case AV_PIX_FMT_P012: case AV_PIX_FMT_P016: return DXGI_FORMAT_P016; case AV_PIX_FMT_YUV420P10: case AV_PIX_FMT_P010: return DXGI_FORMAT_P010; case AV_PIX_FMT_NV12: default: return DXGI_FORMAT_NV12; } } static LAVPixelFormat d3d11va_map_hw_to_lav_format(DXGI_FORMAT dxgiFormat) { switch (dxgiFormat) { case DXGI_FORMAT_AYUV: return LAVPixFmt_AYUV; case DXGI_FORMAT_Y410: return LAVPixFmt_Y410; case DXGI_FORMAT_Y416: return LAVPixFmt_Y416; case DXGI_FORMAT_YUY2: return LAVPixFmt_YUY2; case DXGI_FORMAT_Y210: return LAVPixFmt_Y216; case DXGI_FORMAT_Y216: return LAVPixFmt_Y216; case DXGI_FORMAT_P010: return LAVPixFmt_P016; case DXGI_FORMAT_P016: return LAVPixFmt_P016; case DXGI_FORMAT_NV12: return LAVPixFmt_NV12; default: ASSERT(0); return LAVPixFmt_NV12; } } CDecD3D11::CDecD3D11(void) : CDecAvcodec() { ZeroMemory(&m_FrameQueue, sizeof(m_FrameQueue)); } CDecD3D11::~CDecD3D11(void) { DestroyDecoder(true); if (m_pAllocator) m_pAllocator->DecoderDestruct(); SafeRelease(&m_pAllocator); } STDMETHODIMP CDecD3D11::DestroyDecoder(bool bFull) { for (int i = 0; i < D3D11_QUEUE_SURFACES; i++) { ReleaseFrame(&m_FrameQueue[i]); } if (m_pOutputViews) { for (int i = 0; i < m_nOutputViews; i++) { SafeRelease(&m_pOutputViews[i]); } av_freep(&m_pOutputViews); m_nOutputViews = 0; } SafeRelease(&m_pDecoder); SafeRelease(&m_pD3D11StagingTexture); av_buffer_unref(&m_pFramesCtx); CDecAvcodec::DestroyDecoder(); if (bFull) { av_buffer_unref(&m_pDevCtx); if (dx.d3d11lib) { FreeLibrary(dx.d3d11lib); dx.d3d11lib = nullptr; } if (dx.dxgilib) { FreeLibrary(dx.dxgilib); dx.dxgilib = nullptr; } } return S_OK; } // ILAVDecoder STDMETHODIMP CDecD3D11::Init() { // D3D11 decoding requires Windows 8 or newer if (!IsWindows8OrNewer()) return E_NOINTERFACE; dx.d3d11lib = LoadLibrary(L"d3d11.dll"); if (dx.d3d11lib == nullptr) { DbgLog((LOG_TRACE, 10, L"Cannot open d3d11.dll")); return E_FAIL; } dx.mD3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(dx.d3d11lib, "D3D11CreateDevice"); if (dx.mD3D11CreateDevice == nullptr) { DbgLog((LOG_TRACE, 10, L"D3D11CreateDevice not available")); return E_FAIL; } dx.dxgilib = LoadLibrary(L"dxgi.dll"); if (dx.dxgilib == nullptr) { DbgLog((LOG_TRACE, 10, L"Cannot open dxgi.dll")); return E_FAIL; } dx.mCreateDXGIFactory1 = (PFN_CREATE_DXGI_FACTORY1)GetProcAddress(dx.dxgilib, "CreateDXGIFactory1"); if (dx.mCreateDXGIFactory1 == nullptr) { DbgLog((LOG_TRACE, 10, L"CreateDXGIFactory1 not available")); return E_FAIL; } return S_OK; } STDMETHODIMP CDecD3D11::Check() { // attempt creating a hardware device with video support // by passing nullptr to the device parameter, no actual device will be created and only support will be checked // do probing agains level 11.1 only, to avoid complex checking logic here const D3D_FEATURE_LEVEL *levels = NULL; int level_count = s_GetD3D11FeatureLevels(D3D_FEATURE_LEVEL_11_1, &levels); HRESULT hr = dx.mD3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, D3D11_CREATE_DEVICE_VIDEO_SUPPORT, levels, level_count, D3D11_SDK_VERSION, nullptr, nullptr, nullptr); return hr; } STDMETHODIMP CDecD3D11::InitAllocator(IMemAllocator **ppAlloc) { HRESULT hr = S_OK; if (m_bReadBackFallback) return E_NOTIMPL; if (m_pAllocator == nullptr) { m_pAllocator = new CD3D11SurfaceAllocator(this, &hr); if (!m_pAllocator) { return E_OUTOFMEMORY; } if (FAILED(hr)) { SAFE_DELETE(m_pAllocator); return hr; } // Hold a reference on the allocator m_pAllocator->AddRef(); } // return the proper interface return m_pAllocator->QueryInterface(__uuidof(IMemAllocator), (void **)ppAlloc); } STDMETHODIMP CDecD3D11::CreateD3D11Device(UINT nDeviceIndex, ID3D11Device **ppDevice, DXGI_ADAPTER_DESC *pDesc) { ID3D11Device *pD3D11Device = nullptr; // create DXGI factory IDXGIAdapter *pDXGIAdapter = nullptr; IDXGIFactory1 *pDXGIFactory = nullptr; HRESULT hr = dx.mCreateDXGIFactory1(IID_IDXGIFactory1, (void **)&pDXGIFactory); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> DXGIFactory creation failed")); goto fail; } // find the adapter enum_adapter: hr = pDXGIFactory->EnumAdapters(nDeviceIndex, &pDXGIAdapter); if (FAILED(hr)) { if (nDeviceIndex != 0) { DbgLog( (LOG_ERROR, 10, L"-> Requested DXGI device %d not available, falling back to default", nDeviceIndex)); nDeviceIndex = 0; hr = pDXGIFactory->EnumAdapters(0, &pDXGIAdapter); } if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Failed to enumerate a valid DXGI device")); goto fail; } } // Create a device with video support, and BGRA support for Direct2D interoperability (drawing UI, etc) UINT nCreationFlags = D3D11_CREATE_DEVICE_VIDEO_SUPPORT | D3D11_CREATE_DEVICE_BGRA_SUPPORT; D3D_FEATURE_LEVEL max_level = D3D_FEATURE_LEVEL_12_1; D3D_FEATURE_LEVEL d3dFeatureLevel; do { const D3D_FEATURE_LEVEL *levels = NULL; int level_count = s_GetD3D11FeatureLevels(max_level, &levels); hr = dx.mD3D11CreateDevice(pDXGIAdapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, nCreationFlags, levels, level_count, D3D11_SDK_VERSION, &pD3D11Device, &d3dFeatureLevel, nullptr); if (SUCCEEDED(hr)) break; // 12.0+ devices fail on Windows 8.1, try without it if (max_level >= D3D_FEATURE_LEVEL_12_0) { max_level = D3D_FEATURE_LEVEL_11_1; continue; } break; } while (true); if (FAILED(hr)) { if (nDeviceIndex != 0) { DbgLog(( LOG_ERROR, 10, L"-> Failed to create a D3D11 device with video support on requested device %d, re-trying with default", nDeviceIndex)); SafeRelease(&pDXGIAdapter); nDeviceIndex = 0; goto enum_adapter; } DbgLog((LOG_ERROR, 10, L"-> Failed to create a D3D11 device with video support")); goto fail; } DbgLog((LOG_TRACE, 10, L"-> Created D3D11 device with feature level %d.%d", d3dFeatureLevel >> 12, (d3dFeatureLevel >> 8) & 0xF)); // enable multithreaded protection ID3D10Multithread *pMultithread = nullptr; hr = pD3D11Device->QueryInterface(&pMultithread); if (SUCCEEDED(hr)) { pMultithread->SetMultithreadProtected(TRUE); SafeRelease(&pMultithread); } // store adapter info if (pDesc) { ZeroMemory(pDesc, sizeof(*pDesc)); pDXGIAdapter->GetDesc(pDesc); } // return device *ppDevice = pD3D11Device; fail: SafeRelease(&pDXGIFactory); SafeRelease(&pDXGIAdapter); return hr; } STDMETHODIMP CDecD3D11::PostConnect(IPin *pPin) { DbgLog((LOG_TRACE, 10, L"CDecD3D11::PostConnect()")); HRESULT hr = S_OK; ID3D11DecoderConfiguration *pD3D11DecoderConfiguration = nullptr; hr = pPin->QueryInterface(&pD3D11DecoderConfiguration); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> ID3D11DecoderConfiguration not available, using fallback mode")); } // Release old D3D resources, we're about to re-init m_pCallback->ReleaseAllDXVAResources(); // free the decoder to force a re-init down the line SafeRelease(&m_pDecoder); // and the old device av_buffer_unref(&m_pDevCtx); // device id UINT nDevice = m_pSettings->GetHWAccelDeviceIndex(HWAccel_D3D11, nullptr); // in automatic mode use the device the renderer gives us if (nDevice == LAVHWACCEL_DEVICE_DEFAULT && pD3D11DecoderConfiguration) { nDevice = pD3D11DecoderConfiguration->GetD3D11AdapterIndex(); } else { // if a device is specified manually, fallback to copy-back and use the selected device SafeRelease(&pD3D11DecoderConfiguration); // use the configured device if (nDevice == LAVHWACCEL_DEVICE_DEFAULT) nDevice = 0; } // create the device ID3D11Device *pD3D11Device = nullptr; hr = CreateD3D11Device(nDevice, &pD3D11Device, &m_AdapterDesc); if (FAILED(hr)) { goto fail; } // allocate and fill device context m_pDevCtx = av_hwdevice_ctx_alloc(AV_HWDEVICE_TYPE_D3D11VA); AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx; pDeviceContext->device = pD3D11Device; // finalize the context int ret = av_hwdevice_ctx_init(m_pDevCtx); if (ret < 0) { av_buffer_unref(&m_pDevCtx); goto fail; } // enable multithreaded protection ID3D10Multithread *pMultithread = nullptr; hr = pDeviceContext->device_context->QueryInterface(&pMultithread); if (SUCCEEDED(hr)) { pMultithread->SetMultithreadProtected(TRUE); SafeRelease(&pMultithread); } // check if the connection supports native mode if (pD3D11DecoderConfiguration) { CMediaType mt = m_pCallback->GetOutputMediaType(); if ((m_SurfaceFormat == DXGI_FORMAT_NV12 && mt.subtype != MEDIASUBTYPE_NV12) || (m_SurfaceFormat == DXGI_FORMAT_P010 && mt.subtype != MEDIASUBTYPE_P010) || (m_SurfaceFormat == DXGI_FORMAT_P016 && mt.subtype != MEDIASUBTYPE_P016) || (m_SurfaceFormat == DXGI_FORMAT_AYUV && mt.subtype != MEDIASUBTYPE_AYUV) || (m_SurfaceFormat == DXGI_FORMAT_Y410 && mt.subtype != MEDIASUBTYPE_Y410) || (m_SurfaceFormat == DXGI_FORMAT_Y416 && mt.subtype != MEDIASUBTYPE_Y416) || (m_SurfaceFormat == DXGI_FORMAT_YUY2 && mt.subtype != MEDIASUBTYPE_YUY2) || (m_SurfaceFormat == DXGI_FORMAT_Y210 && mt.subtype != MEDIASUBTYPE_Y210) || (m_SurfaceFormat == DXGI_FORMAT_Y216 && mt.subtype != MEDIASUBTYPE_Y216)) { DbgLog((LOG_ERROR, 10, L"-> Connection is not the appropriate pixel format for D3D11 Native")); SafeRelease(&pD3D11DecoderConfiguration); } } // verify hardware support { int level = 0; if (m_pAVCtx->codec_id == AV_CODEC_ID_HEVC) { int64_t value = 0; if (av_opt_get_int(m_pAVCtx->priv_data, "rext_profile", 0, &value) >= 0) level = (int)value; } GUID guidConversion = GUID_NULL; hr = FindVideoServiceConversion(m_pAVCtx->codec_id, m_pAVCtx->profile, level, m_SurfaceFormat, &guidConversion); if (FAILED(hr)) { goto fail; } // get decoder configuration D3D11_VIDEO_DECODER_DESC desc = {0}; desc.Guid = guidConversion; desc.OutputFormat = m_SurfaceFormat; desc.SampleWidth = m_pAVCtx->coded_width; desc.SampleHeight = m_pAVCtx->coded_height; D3D11_VIDEO_DECODER_CONFIG decoder_config = {0}; hr = FindDecoderConfiguration(&desc, &decoder_config); if (FAILED(hr)) { goto fail; } // test creating a texture D3D11_TEXTURE2D_DESC texDesc = {0}; texDesc.Width = m_pAVCtx->coded_width; texDesc.Height = m_pAVCtx->coded_height; texDesc.MipLevels = 1; texDesc.ArraySize = GetBufferCount(); texDesc.Format = m_SurfaceFormat; texDesc.SampleDesc.Count = 1; texDesc.Usage = D3D11_USAGE_DEFAULT; texDesc.BindFlags = D3D11_BIND_DECODER | D3D11_BIND_SHADER_RESOURCE; texDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED; hr = pD3D11Device->CreateTexture2D(&texDesc, nullptr, nullptr); if (FAILED(hr)) { goto fail; } } // Notice the connected pin that we're sending D3D11 textures if (pD3D11DecoderConfiguration) { hr = pD3D11DecoderConfiguration->ActivateD3D11Decoding(pDeviceContext->device, pDeviceContext->device_context, pDeviceContext->lock_ctx, 0); SafeRelease(&pD3D11DecoderConfiguration); m_bReadBackFallback = FAILED(hr); } else { m_bReadBackFallback = true; } return S_OK; fail: SafeRelease(&pD3D11DecoderConfiguration); return E_FAIL; } STDMETHODIMP CDecD3D11::BreakConnect() { if (m_bReadBackFallback) return S_FALSE; // release any resources held by the core m_pCallback->ReleaseAllDXVAResources(); // flush all buffers out of the decoder to ensure the allocator can be properly de-allocated if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) avcodec_flush_buffers(m_pAVCtx); return S_OK; } STDMETHODIMP CDecD3D11::InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) { HRESULT hr = S_OK; DbgLog((LOG_TRACE, 10, L"CDecD3D11::InitDecoder(): Initializing D3D11 decoder")); // Destroy old decoder DestroyDecoder(false); // reset stream compatibility m_bFailHWDecode = false; m_DisplayDelay = D3D11_QUEUE_SURFACES; // Reduce display delay for DVD decoding for lower decode latency if (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) m_DisplayDelay /= 2; // Initialize ffmpeg hr = CDecAvcodec::InitDecoder(codec, pmt, pSideData); if (FAILED(hr)) return hr; if (check_dxva_codec_profile(m_pAVCtx, AV_PIX_FMT_D3D11)) { DbgLog((LOG_TRACE, 10, L"-> Incompatible profile detected, falling back to software decoding")); return E_FAIL; } // initialize surface format to ensure the default media type is set properly m_SurfaceFormat = d3d11va_map_sw_to_hw_format(m_pAVCtx->sw_pix_fmt); m_dwSurfaceWidth = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_width); m_dwSurfaceHeight = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_height); return S_OK; } HRESULT CDecD3D11::AdditionaDecoderInit() { AVD3D11VAContext *ctx = av_d3d11va_alloc_context(); if (m_pDecoder) { FillHWContext(ctx); } m_pAVCtx->thread_count = 1; m_pAVCtx->thread_type = 0; m_pAVCtx->hwaccel_context = ctx; m_pAVCtx->get_format = get_d3d11_format; m_pAVCtx->get_buffer2 = get_d3d11_buffer; m_pAVCtx->opaque = this; m_pAVCtx->slice_flags |= SLICE_FLAG_ALLOW_FIELD; // disable error concealment in hwaccel mode, it doesn't work either way m_pAVCtx->error_concealment = 0; av_opt_set_int(m_pAVCtx, "enable_er", 0, AV_OPT_SEARCH_CHILDREN); return S_OK; } STDMETHODIMP CDecD3D11::FillHWContext(AVD3D11VAContext *ctx) { AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx; ctx->decoder = m_pDecoder; ctx->video_context = pDeviceContext->video_context; ctx->cfg = &m_DecoderConfig; ctx->surface_count = m_nOutputViews; ctx->surface = m_pOutputViews; ctx->context_mutex = pDeviceContext->lock_ctx; ctx->workaround = 0; if (m_AdapterDesc.VendorId == VEND_ID_NVIDIA) ctx->workaround = FF_DXVA2_WORKAROUND_NVIDIA_HEVC_420P12; return S_OK; } STDMETHODIMP_(long) CDecD3D11::GetBufferCount(long *pMaxBuffers) { long buffers = 0; // Native decoding should use 16 buffers to enable seamless codec changes if (!m_bReadBackFallback) buffers = 16; else { // Buffers based on max ref frames if (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_HEVC) buffers = 16; else if (m_nCodecId == AV_CODEC_ID_VP9 || m_nCodecId == AV_CODEC_ID_AV1) buffers = 8; else buffers = 2; } // 4 extra buffers for handling and safety buffers += 4; if (m_bReadBackFallback) { buffers += m_DisplayDelay; } if (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) { buffers += 4; } if (pMaxBuffers) { // cap at 127, because it needs to fit into the 7-bit DXVA structs *pMaxBuffers = 127; // VC-1 and VP9 decoding has stricter requirements (decoding flickers otherwise) if (m_nCodecId == AV_CODEC_ID_VC1 || m_nCodecId == AV_CODEC_ID_VP9 || m_nCodecId == AV_CODEC_ID_AV1) *pMaxBuffers = 32; } return buffers; } STDMETHODIMP CDecD3D11::FlushDisplayQueue(BOOL bDeliver) { for (int i = 0; i < m_DisplayDelay; ++i) { if (m_FrameQueue[m_FrameQueuePosition]) { if (bDeliver) { DeliverD3D11Frame(m_FrameQueue[m_FrameQueuePosition]); m_FrameQueue[m_FrameQueuePosition] = nullptr; } else { ReleaseFrame(&m_FrameQueue[m_FrameQueuePosition]); } } m_FrameQueuePosition = (m_FrameQueuePosition + 1) % m_DisplayDelay; } return S_OK; } STDMETHODIMP CDecD3D11::Flush() { CDecAvcodec::Flush(); // Flush display queue FlushDisplayQueue(FALSE); return S_OK; } STDMETHODIMP CDecD3D11::EndOfStream() { CDecAvcodec::EndOfStream(); // Flush display queue FlushDisplayQueue(TRUE); return S_OK; } HRESULT CDecD3D11::PostDecode() { if (m_bFailHWDecode) { DbgLog((LOG_TRACE, 10, L"::PostDecode(): HW Decoder failed, falling back to software decoding")); return E_FAIL; } return S_OK; } enum AVPixelFormat CDecD3D11::get_d3d11_format(struct AVCodecContext *s, const enum AVPixelFormat *pix_fmts) { CDecD3D11 *pDec = (CDecD3D11 *)s->opaque; const enum AVPixelFormat *p; for (p = pix_fmts; *p != -1; p++) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p); if (!desc || !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) break; if (*p == AV_PIX_FMT_D3D11) { HRESULT hr = pDec->ReInitD3D11Decoder(s); if (FAILED(hr)) { pDec->m_bFailHWDecode = TRUE; continue; } else { break; } } } return *p; } int CDecD3D11::get_d3d11_buffer(struct AVCodecContext *c, AVFrame *frame, int flags) { CDecD3D11 *pDec = (CDecD3D11 *)c->opaque; HRESULT hr = S_OK; if (frame->format != AV_PIX_FMT_D3D11) { DbgLog((LOG_ERROR, 10, L"D3D11 buffer request, but not D3D11 pixfmt")); pDec->m_bFailHWDecode = TRUE; return -1; } hr = pDec->ReInitD3D11Decoder(c); if (FAILED(hr)) { pDec->m_bFailHWDecode = TRUE; return -1; } if (pDec->m_bReadBackFallback && pDec->m_pFramesCtx) { int ret = av_hwframe_get_buffer(pDec->m_pFramesCtx, frame, 0); frame->width = c->coded_width; frame->height = c->coded_height; return ret; } else if (pDec->m_bReadBackFallback == false && pDec->m_pAllocator) { IMediaSample *pSample = nullptr; hr = pDec->m_pAllocator->GetBuffer(&pSample, nullptr, nullptr, 0); if (SUCCEEDED(hr)) { CD3D11MediaSample *pD3D11Sample = dynamic_cast(pSample); // fill the frame from the sample, including a reference to the sample if (FAILED(pD3D11Sample->GetAVFrameBuffer(frame))) { pD3D11Sample->Release(); return -1; } frame->width = c->coded_width; frame->height = c->coded_height; // the frame holds the sample now, can release the direct interface pD3D11Sample->Release(); return 0; } } return -1; } STDMETHODIMP CDecD3D11::ReInitD3D11Decoder(AVCodecContext *c) { HRESULT hr = S_OK; // Don't allow decoder creation during first init if (m_bInInit) return S_FALSE; // sanity check that we have a device if (m_pDevCtx == nullptr) return E_FAIL; // we need an allocator at this point if (m_bReadBackFallback == false && m_pAllocator == nullptr) return E_FAIL; DXGI_FORMAT surfaceFormatToTest = d3d11va_map_sw_to_hw_format(c->sw_pix_fmt); if (surfaceFormatToTest == DXGI_FORMAT_P016 && m_bP016ToP010Fallback) surfaceFormatToTest = DXGI_FORMAT_P010; if (m_pDecoder == nullptr || m_dwSurfaceWidth != dxva_align_dimensions(c->codec_id, c->coded_width) || m_dwSurfaceHeight != dxva_align_dimensions(c->codec_id, c->coded_height) || m_SurfaceFormat != surfaceFormatToTest) { AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx; DbgLog((LOG_TRACE, 10, L"No D3D11 Decoder or image dimensions changed -> Re-Allocating resources")); // if we're not in readback mode, we need to flush all the frames if (m_bReadBackFallback == false) if (m_pDecoder) avcodec_flush_buffers(c); else FlushDisplayQueue(TRUE); pDeviceContext->lock(pDeviceContext->lock_ctx); hr = CreateD3D11Decoder(); pDeviceContext->unlock(pDeviceContext->lock_ctx); if (FAILED(hr)) return hr; // Update the frames context in the allocator if (m_bReadBackFallback == false) { // decommit the allocator m_pAllocator->Decommit(); // verify we were able to decommit all its resources if (m_pAllocator->DecommitInProgress()) { DbgLog((LOG_TRACE, 10, L"WARNING! D3D11 Allocator is still busy, trying to flush downstream")); m_pCallback->ReleaseAllDXVAResources(); m_pCallback->GetOutputPin()->GetConnected()->BeginFlush(); m_pCallback->GetOutputPin()->GetConnected()->EndFlush(); if (m_pAllocator->DecommitInProgress()) { DbgLog( (LOG_TRACE, 10, L"WARNING! Flush had no effect, decommit of the allocator still not complete")); m_pAllocator->ForceDecommit(); } else { DbgLog((LOG_TRACE, 10, L"Flush was successful, decommit completed!")); } } // re-commit it to update its frame reference m_pAllocator->Commit(); } } return S_OK; } STDMETHODIMP CDecD3D11::FindVideoServiceConversion(AVCodecID codec, int profile, int level, DXGI_FORMAT &surface_format, GUID *input) { AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx; HRESULT hr = S_OK; UINT nProfiles = pDeviceContext->video_device->GetVideoDecoderProfileCount(); GUID *guid_list = (GUID *)av_malloc_array(nProfiles, sizeof(*guid_list)); m_bP016ToP010Fallback = false; DbgLog((LOG_TRACE, 10, L"-> Enumerating supported D3D11 modes (count: %d)", nProfiles)); for (UINT i = 0; i < nProfiles; i++) { hr = pDeviceContext->video_device->GetVideoDecoderProfile(i, &guid_list[i]); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"Error retrieving decoder profile")); av_free(guid_list); return hr; } #ifdef DEBUG const dxva_mode_t *mode = get_dxva_mode_from_guid(&guid_list[i]); if (mode) { DbgLog((LOG_TRACE, 10, L" -> %S", mode->name)); } else { DbgLog((LOG_TRACE, 10, L" -> Unknown GUID (%s)", WStringFromGUID(guid_list[i]).c_str())); } #endif } /* Iterate over our priority list */ for (unsigned i = 0; dxva_modes[i].name; i++) { const dxva_mode_t *mode = &dxva_modes[i]; if (!check_dxva_mode_compatibility(mode, codec, profile, level, (surface_format == DXGI_FORMAT_NV12))) continue; BOOL supported = FALSE; for (UINT g = 0; !supported && g < nProfiles; g++) { supported = IsEqualGUID(*mode->guid, guid_list[g]); } if (!supported) continue; DbgLog((LOG_TRACE, 10, L"-> Trying to use '%S'", mode->name)); hr = pDeviceContext->video_device->CheckVideoDecoderFormat(mode->guid, surface_format, &supported); // some high bitdepth decoders only accept P010, despite the memory layout otherwise being identical if (SUCCEEDED(hr) && !supported && surface_format == DXGI_FORMAT_P016) { hr = pDeviceContext->video_device->CheckVideoDecoderFormat(mode->guid, DXGI_FORMAT_P010, &supported); if (SUCCEEDED(hr) && supported) { surface_format = DXGI_FORMAT_P010; m_bP016ToP010Fallback = true; } } if (SUCCEEDED(hr) && supported) { *input = *mode->guid; av_free(guid_list); return S_OK; } } av_free(guid_list); return E_FAIL; } STDMETHODIMP CDecD3D11::FindDecoderConfiguration(const D3D11_VIDEO_DECODER_DESC *desc, D3D11_VIDEO_DECODER_CONFIG *pConfig) { AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx; HRESULT hr = S_OK; UINT nConfig = 0; hr = pDeviceContext->video_device->GetVideoDecoderConfigCount(desc, &nConfig); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"Unable to retrieve decoder configuration count")); return E_FAIL; } int best_score = -1; D3D11_VIDEO_DECODER_CONFIG best_config; for (UINT i = 0; i < nConfig; i++) { D3D11_VIDEO_DECODER_CONFIG config = {0}; hr = pDeviceContext->video_device->GetVideoDecoderConfig(desc, i, &config); if (FAILED(hr)) continue; DbgLog((LOG_ERROR, 10, "-> Configuration Record %d: ConfigBitstreamRaw = %d", i, config.ConfigBitstreamRaw)); int score; if (config.ConfigBitstreamRaw == 1) score = 1; else if (m_pAVCtx->codec_id == AV_CODEC_ID_H264 && config.ConfigBitstreamRaw == 2) score = 2; else if (m_pAVCtx->codec_id == AV_CODEC_ID_VP9) // hack for broken AMD drivers score = 0; else continue; if (IsEqualGUID(config.guidConfigBitstreamEncryption, DXVA2_NoEncrypt)) score += 16; if (score > best_score) { best_score = score; best_config = config; } } if (best_score < 0) { DbgLog((LOG_TRACE, 10, L"-> No matching configuration available")); return E_FAIL; } *pConfig = best_config; return S_OK; } STDMETHODIMP CDecD3D11::CreateD3D11Decoder() { HRESULT hr = S_OK; AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx; // release the old decoder, it needs to be re-created SafeRelease(&m_pDecoder); // find a decoder configuration GUID profileGUID = GUID_NULL; DXGI_FORMAT surface_format = d3d11va_map_sw_to_hw_format(m_pAVCtx->sw_pix_fmt); // codec sub-level int level = 0; if (m_pAVCtx->codec_id == AV_CODEC_ID_HEVC) { int64_t value = 0; if (av_opt_get_int(m_pAVCtx->priv_data, "rext_profile", 0, &value) >= 0) level = (int)value; } hr = FindVideoServiceConversion(m_pAVCtx->codec_id, m_pAVCtx->profile, level, surface_format, &profileGUID); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> No video service profile found")); return hr; } // get decoder configuration D3D11_VIDEO_DECODER_DESC desc = {0}; desc.Guid = profileGUID; desc.OutputFormat = surface_format; desc.SampleWidth = m_pAVCtx->coded_width; desc.SampleHeight = m_pAVCtx->coded_height; D3D11_VIDEO_DECODER_CONFIG decoder_config = {0}; hr = FindDecoderConfiguration(&desc, &decoder_config); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> No valid video decoder configuration found")); return hr; } m_DecoderConfig = decoder_config; // update surface properties m_dwSurfaceWidth = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_width); m_dwSurfaceHeight = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_height); m_SurfaceFormat = surface_format; if (m_bReadBackFallback == false && m_pAllocator) { ALLOCATOR_PROPERTIES properties; hr = m_pAllocator->GetProperties(&properties); if (FAILED(hr)) return hr; m_dwSurfaceCount = properties.cBuffers; } else { m_dwSurfaceCount = GetBufferCount(); } // allocate a new frames context for the dimensions and format hr = AllocateFramesContext(m_dwSurfaceWidth, m_dwSurfaceHeight, m_SurfaceFormat, m_dwSurfaceCount, &m_pFramesCtx); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Error allocating frames context")); return hr; } // release any old output views and allocate memory for the new ones if (m_pOutputViews) { for (int i = 0; i < m_nOutputViews; i++) { SafeRelease(&m_pOutputViews[i]); } av_freep(&m_pOutputViews); } m_pOutputViews = (ID3D11VideoDecoderOutputView **)av_calloc(m_dwSurfaceCount, sizeof(*m_pOutputViews)); m_nOutputViews = m_dwSurfaceCount; // allocate output views for the frames AVD3D11VAFramesContext *pFramesContext = (AVD3D11VAFramesContext *)((AVHWFramesContext *)m_pFramesCtx->data)->hwctx; for (int i = 0; i < m_nOutputViews; i++) { D3D11_VIDEO_DECODER_OUTPUT_VIEW_DESC viewDesc = {0}; viewDesc.DecodeProfile = profileGUID; viewDesc.ViewDimension = D3D11_VDOV_DIMENSION_TEXTURE2D; viewDesc.Texture2D.ArraySlice = i; hr = pDeviceContext->video_device->CreateVideoDecoderOutputView(pFramesContext->texture, &viewDesc, &m_pOutputViews[i]); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Failed to create video decoder output views")); return E_FAIL; } } // flush textures to black if (surface_format == DXGI_FORMAT_NV12 || surface_format == DXGI_FORMAT_P010 || surface_format == DXGI_FORMAT_P016) { D3D11_FEATURE_DATA_D3D11_OPTIONS d3d11Options{}; pDeviceContext->device->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &d3d11Options, sizeof(D3D11_FEATURE_DATA_D3D11_OPTIONS)); // XXX: The ClearView path does not function properly on Intel GPUs for P010 // Investigation has shown that contrary to the documentation, Intel transforms the color information, // instead of treating the values like integral floats, as required. ID3D11DeviceContext1 *pDeviceContext1 = nullptr; if (m_AdapterDesc.VendorId != VEND_ID_INTEL && d3d11Options.ClearView && SUCCEEDED(hr = pDeviceContext->device_context->QueryInterface(&pDeviceContext1))) { for (int i = 0; i < m_nOutputViews; i++) { // clear the Luma channel to zero and Chroma channel to half // for both P010/P016, the full 16-bit range value needs to be used due to the nature of their memory layout float fChromaBlack = (surface_format == DXGI_FORMAT_NV12) ? 128.0f : 32768.0f; const FLOAT ClearYUV[4] = {0.0f, fChromaBlack, fChromaBlack, 0.0f}; pDeviceContext1->ClearView(m_pOutputViews[i], ClearYUV, nullptr, 0); } SafeRelease(&pDeviceContext1); } else { D3D11_TEXTURE2D_DESC FlushTexDesc{}; FlushTexDesc.Width = m_dwSurfaceWidth; FlushTexDesc.Height = m_dwSurfaceHeight; FlushTexDesc.MipLevels = 1; FlushTexDesc.ArraySize = 1; FlushTexDesc.Format = surface_format; FlushTexDesc.SampleDesc.Count = 1; FlushTexDesc.Usage = D3D11_USAGE_DEFAULT; FlushTexDesc.BindFlags = D3D11_BIND_RENDER_TARGET; FlushTexDesc.CPUAccessFlags = 0; FlushTexDesc.MiscFlags = 0; ID3D11Texture2D *pFlushTexture = NULL; if (SUCCEEDED(pDeviceContext->device->CreateTexture2D(&FlushTexDesc, NULL, &pFlushTexture))) { D3D11_RENDER_TARGET_VIEW_DESC rtvDesc{}; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtvDesc.Format = surface_format; ID3D11RenderTargetView *pRTV = nullptr; // clear the Luma channel to zero rtvDesc.Format = (surface_format == DXGI_FORMAT_NV12) ? DXGI_FORMAT_R8_UNORM : DXGI_FORMAT_R16_UNORM; if (SUCCEEDED(hr = pDeviceContext->device->CreateRenderTargetView(pFlushTexture, &rtvDesc, &pRTV))) { const FLOAT ClearYUV[4] = { 0.0f }; pDeviceContext->device_context->ClearRenderTargetView(pRTV, ClearYUV); SafeRelease(&pRTV); } // clear the Chroma channel to half rtvDesc.Format = (surface_format == DXGI_FORMAT_NV12) ? DXGI_FORMAT_R8G8_UNORM : DXGI_FORMAT_R16G16_UNORM; if (SUCCEEDED(hr = pDeviceContext->device->CreateRenderTargetView(pFlushTexture, &rtvDesc, &pRTV))) { const FLOAT ClearYUV[4] = { 0.5f, 0.5f, 0.0f, 0.0f }; pDeviceContext->device_context->ClearRenderTargetView(pRTV, ClearYUV); SafeRelease(&pRTV); } // update all surfaces with the flush color for (unsigned i = 0; i < m_dwSurfaceCount; i++) { pDeviceContext->device_context->CopySubresourceRegion(pFramesContext->texture, i, 0, 0, 0, pFlushTexture, 0, NULL); } SafeRelease(&pFlushTexture); } } // flush all pending work pDeviceContext->device_context->Flush(); } // create the decoder hr = pDeviceContext->video_device->CreateVideoDecoder(&desc, &decoder_config, &m_pDecoder); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Failed to create video decoder object")); return E_FAIL; } FillHWContext((AVD3D11VAContext *)m_pAVCtx->hwaccel_context); return S_OK; } static AVPixelFormat s_GetAVD3D11PixelFormat(DXGI_FORMAT format) { switch (format) { case DXGI_FORMAT_NV12: return AV_PIX_FMT_NV12; case DXGI_FORMAT_P010: return AV_PIX_FMT_P010; case DXGI_FORMAT_P016: return AV_PIX_FMT_P016; case DXGI_FORMAT_YUY2: return AV_PIX_FMT_YUYV422; case DXGI_FORMAT_Y210: return AV_PIX_FMT_Y210; case DXGI_FORMAT_Y216: return AV_PIX_FMT_Y216; case DXGI_FORMAT_AYUV: return AV_PIX_FMT_VUYX; case DXGI_FORMAT_Y410: return AV_PIX_FMT_XV30; case DXGI_FORMAT_Y416: return AV_PIX_FMT_XV48; } ASSERT(0); return AV_PIX_FMT_NV12; } STDMETHODIMP CDecD3D11::AllocateFramesContext(int width, int height, DXGI_FORMAT format, int nSurfaces, AVBufferRef **ppFramesCtx) { ASSERT(m_pAVCtx); ASSERT(m_pDevCtx); ASSERT(ppFramesCtx); // unref any old buffer av_buffer_unref(ppFramesCtx); SafeRelease(&m_pD3D11StagingTexture); // allocate a new frames context for the device context *ppFramesCtx = av_hwframe_ctx_alloc(m_pDevCtx); if (*ppFramesCtx == nullptr) return E_OUTOFMEMORY; AVHWFramesContext *pFrames = (AVHWFramesContext *)(*ppFramesCtx)->data; pFrames->format = AV_PIX_FMT_D3D11; pFrames->sw_format = s_GetAVD3D11PixelFormat(format); pFrames->width = width; pFrames->height = height; pFrames->initial_pool_size = nSurfaces; AVD3D11VAFramesContext *pFramesHWContext = (AVD3D11VAFramesContext *)pFrames->hwctx; pFramesHWContext->BindFlags |= D3D11_BIND_DECODER | D3D11_BIND_SHADER_RESOURCE; pFramesHWContext->MiscFlags |= D3D11_RESOURCE_MISC_SHARED; int ret = av_hwframe_ctx_init(*ppFramesCtx); if (ret < 0) { av_buffer_unref(ppFramesCtx); return E_FAIL; } return S_OK; } HRESULT CDecD3D11::HandleDXVA2Frame(LAVFrame *pFrame) { if (pFrame->flags & LAV_FRAME_FLAG_FLUSH) { if (m_bReadBackFallback) { FlushDisplayQueue(TRUE); } Deliver(pFrame); return S_OK; } ASSERT(pFrame->format == LAVPixFmt_D3D11); if (m_bReadBackFallback == false || m_DisplayDelay == 0) { DeliverD3D11Frame(pFrame); } else { LAVFrame *pQueuedFrame = m_FrameQueue[m_FrameQueuePosition]; m_FrameQueue[m_FrameQueuePosition] = pFrame; m_FrameQueuePosition = (m_FrameQueuePosition + 1) % m_DisplayDelay; if (pQueuedFrame) { DeliverD3D11Frame(pQueuedFrame); } } return S_OK; } HRESULT CDecD3D11::DeliverD3D11Frame(LAVFrame *pFrame) { if (m_bReadBackFallback) { if (m_bDirect) DeliverD3D11ReadbackDirect(pFrame); else DeliverD3D11Readback(pFrame); } else { AVFrame *pAVFrame = (AVFrame *)pFrame->priv_data; pFrame->data[0] = pAVFrame->data[3]; pFrame->data[1] = pFrame->data[2] = pFrame->data[3] = nullptr; GetPixelFormat(&pFrame->format, &pFrame->bpp, &pFrame->sw_format); Deliver(pFrame); } return S_OK; } HRESULT CDecD3D11::DeliverD3D11Readback(LAVFrame *pFrame) { AVFrame *src = (AVFrame *)pFrame->priv_data; AVFrame *dst = av_frame_alloc(); int ret = av_hwframe_transfer_data(dst, src, 0); if (ret < 0) { ReleaseFrame(&pFrame); av_frame_free(&dst); return E_FAIL; } // free the source frame av_frame_free(&src); // and store the dst frame in LAVFrame pFrame->priv_data = dst; GetPixelFormat(&pFrame->format, &pFrame->bpp, &pFrame->sw_format); ASSERT(getFFPixelFormatFromLAV(pFrame->format, pFrame->bpp) == dst->format); for (int i = 0; i < 4; i++) { pFrame->data[i] = dst->data[i]; pFrame->stride[i] = dst->linesize[i]; } return Deliver(pFrame); } struct D3D11DirectPrivate { AVBufferRef *pDeviceContex; ID3D11Texture2D *pStagingTexture; }; static bool d3d11_direct_lock(LAVFrame *pFrame, LAVDirectBuffer *pBuffer) { D3D11DirectPrivate *c = (D3D11DirectPrivate *)pFrame->priv_data; AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)c->pDeviceContex->data)->hwctx; D3D11_TEXTURE2D_DESC desc; D3D11_MAPPED_SUBRESOURCE map; ASSERT(pFrame && pBuffer); // lock the device context pDeviceContext->lock(pDeviceContext->lock_ctx); c->pStagingTexture->GetDesc(&desc); // map HRESULT hr = pDeviceContext->device_context->Map(c->pStagingTexture, 0, D3D11_MAP_READ, 0, &map); if (FAILED(hr)) { pDeviceContext->unlock(pDeviceContext->lock_ctx); return false; } pBuffer->Width = desc.Width; pBuffer->Height = desc.Height; pBuffer->data[0] = (BYTE *)map.pData; pBuffer->stride[0] = map.RowPitch; // semi-packed formats have a second plane if (desc.Format == DXGI_FORMAT_NV12 || desc.Format == DXGI_FORMAT_P010 || desc.Format == DXGI_FORMAT_P016) { pBuffer->data[1] = pBuffer->data[0] + desc.Height * map.RowPitch; pBuffer->stride[1] = map.RowPitch; } return true; } static void d3d11_direct_unlock(LAVFrame *pFrame) { D3D11DirectPrivate *c = (D3D11DirectPrivate *)pFrame->priv_data; AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)c->pDeviceContex->data)->hwctx; pDeviceContext->device_context->Unmap(c->pStagingTexture, 0); pDeviceContext->unlock(pDeviceContext->lock_ctx); } static void d3d11_direct_free(LAVFrame *pFrame) { D3D11DirectPrivate *c = (D3D11DirectPrivate *)pFrame->priv_data; av_buffer_unref(&c->pDeviceContex); c->pStagingTexture->Release(); delete c; } HRESULT CDecD3D11::DeliverD3D11ReadbackDirect(LAVFrame *pFrame) { AVD3D11VADeviceContext *pDeviceContext = (AVD3D11VADeviceContext *)((AVHWDeviceContext *)m_pDevCtx->data)->hwctx; AVFrame *src = (AVFrame *)pFrame->priv_data; D3D11_TEXTURE2D_DESC videoTexDesc{}; ((ID3D11Texture2D *)src->data[0])->GetDesc(&videoTexDesc); // validate the properties of the staging texture to match the video texture, re-create if needed if (m_pD3D11StagingTexture) { D3D11_TEXTURE2D_DESC stagingTexDesc{}; m_pD3D11StagingTexture->GetDesc(&stagingTexDesc); if (stagingTexDesc.Width != videoTexDesc.Width || stagingTexDesc.Height != videoTexDesc.Height || stagingTexDesc.Format != videoTexDesc.Format) SafeRelease(&m_pD3D11StagingTexture); } // (re-)create the staging texture if (m_pD3D11StagingTexture == nullptr) { D3D11_TEXTURE2D_DESC stagingTexDesc = videoTexDesc; stagingTexDesc.ArraySize = 1; stagingTexDesc.Usage = D3D11_USAGE_STAGING; stagingTexDesc.BindFlags = 0; stagingTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; stagingTexDesc.MiscFlags = 0; HRESULT hr = pDeviceContext->device->CreateTexture2D(&stagingTexDesc, nullptr, &m_pD3D11StagingTexture); if (FAILED(hr)) { ReleaseFrame(&pFrame); return E_FAIL; } } pDeviceContext->lock(pDeviceContext->lock_ctx); pDeviceContext->device_context->CopySubresourceRegion( m_pD3D11StagingTexture, 0, 0, 0, 0, (ID3D11Texture2D *)src->data[0], (UINT)(intptr_t)src->data[1], nullptr); pDeviceContext->unlock(pDeviceContext->lock_ctx); av_frame_free(&src); D3D11DirectPrivate *c = new D3D11DirectPrivate; c->pDeviceContex = av_buffer_ref(m_pDevCtx); c->pStagingTexture = m_pD3D11StagingTexture; m_pD3D11StagingTexture->AddRef(); pFrame->priv_data = c; pFrame->destruct = d3d11_direct_free; GetPixelFormat(&pFrame->format, &pFrame->bpp, &pFrame->sw_format); pFrame->direct = true; pFrame->direct_lock = d3d11_direct_lock; pFrame->direct_unlock = d3d11_direct_unlock; return Deliver(pFrame); } STDMETHODIMP CDecD3D11::GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { // Output is always NV12 or P010 if (pPix) *pPix = m_bReadBackFallback == false ? LAVPixFmt_D3D11 : d3d11va_map_hw_to_lav_format(m_SurfaceFormat); if (pBpp) *pBpp = (m_SurfaceFormat == DXGI_FORMAT_NV12 || m_SurfaceFormat == DXGI_FORMAT_YUY2 || m_SurfaceFormat == DXGI_FORMAT_AYUV) ? 8 : (m_SurfaceFormat == DXGI_FORMAT_P010 || m_SurfaceFormat == DXGI_FORMAT_Y210 || m_SurfaceFormat == DXGI_FORMAT_Y410) ? 10 : (m_SurfaceFormat == DXGI_FORMAT_P016 || m_SurfaceFormat == DXGI_FORMAT_Y216 || m_SurfaceFormat == DXGI_FORMAT_Y416) ? 16 : 8; if (pPixSoftware) *pPixSoftware = d3d11va_map_hw_to_lav_format(m_SurfaceFormat); return S_OK; } STDMETHODIMP_(DWORD) CDecD3D11::GetHWAccelNumDevices() { DWORD nDevices = 0; UINT i = 0; IDXGIAdapter *pDXGIAdapter = nullptr; IDXGIFactory1 *pDXGIFactory = nullptr; HRESULT hr = dx.mCreateDXGIFactory1(IID_IDXGIFactory1, (void **)&pDXGIFactory); if (FAILED(hr)) goto fail; DXGI_ADAPTER_DESC desc; while (SUCCEEDED(pDXGIFactory->EnumAdapters(i, &pDXGIAdapter))) { pDXGIAdapter->GetDesc(&desc); SafeRelease(&pDXGIAdapter); // stop when we hit the MS software device if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) break; i++; } nDevices = i; fail: SafeRelease(&pDXGIFactory); return nDevices; } STDMETHODIMP CDecD3D11::GetHWAccelDeviceInfo(DWORD dwIndex, BSTR *pstrDeviceName, DWORD *dwDeviceIdentifier) { IDXGIAdapter *pDXGIAdapter = nullptr; IDXGIFactory1 *pDXGIFactory = nullptr; HRESULT hr = dx.mCreateDXGIFactory1(IID_IDXGIFactory1, (void **)&pDXGIFactory); if (FAILED(hr)) goto fail; hr = pDXGIFactory->EnumAdapters(dwIndex, &pDXGIAdapter); if (FAILED(hr)) goto fail; DXGI_ADAPTER_DESC desc; pDXGIAdapter->GetDesc(&desc); // stop when we hit the MS software device if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) { hr = E_INVALIDARG; goto fail; } if (pstrDeviceName) *pstrDeviceName = SysAllocString(desc.Description); if (dwDeviceIdentifier) *dwDeviceIdentifier = desc.DeviceId; fail: SafeRelease(&pDXGIFactory); SafeRelease(&pDXGIAdapter); return hr; } STDMETHODIMP CDecD3D11::GetHWAccelActiveDevice(BSTR *pstrDeviceName) { CheckPointer(pstrDeviceName, E_POINTER); if (m_AdapterDesc.Description[0] == 0) return E_UNEXPECTED; *pstrDeviceName = SysAllocString(m_AdapterDesc.Description); return S_OK; } ================================================ FILE: decoder/LAVVideo/decoders/d3d11va.h ================================================ /* * Copyright (C) 2017-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DecBase.h" #include "avcodec.h" #include #include #include "d3d11/D3D11SurfaceAllocator.h" extern "C" { #include "libavutil/hwcontext.h" #include "libavutil/hwcontext_d3d11va.h" #include "libavcodec/d3d11va.h" #include "libavcodec/h265_rext_profiles.h" } #define D3D11_QUEUE_SURFACES 4 typedef HRESULT(WINAPI *PFN_CREATE_DXGI_FACTORY1)(REFIID riid, void **ppFactory); class CDecD3D11 : public CDecAvcodec { public: CDecD3D11(void); virtual ~CDecD3D11(void); // ILAVDecoder STDMETHODIMP Check(); STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); STDMETHODIMP InitAllocator(IMemAllocator **ppAlloc); STDMETHODIMP PostConnect(IPin *pPin); STDMETHODIMP BreakConnect(); STDMETHODIMP_(long) GetBufferCount(long *pMaxBuffers = nullptr); STDMETHODIMP_(const WCHAR *) GetDecoderName() { return m_bReadBackFallback ? (m_bDirect ? L"d3d11 cb direct" : L"d3d11 cb") : L"d3d11 native"; } STDMETHODIMP HasThreadSafeBuffers() { return S_FALSE; } STDMETHODIMP SetDirectOutput(BOOL bDirect) { m_bDirect = bDirect; return S_OK; } STDMETHODIMP_(DWORD) GetHWAccelNumDevices(); STDMETHODIMP GetHWAccelDeviceInfo(DWORD dwIndex, BSTR *pstrDeviceName, DWORD *dwDeviceIdentifier); STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName); // CDecBase STDMETHODIMP Init(); protected: HRESULT AdditionaDecoderInit(); HRESULT PostDecode(); HRESULT HandleDXVA2Frame(LAVFrame *pFrame); HRESULT DeliverD3D11Frame(LAVFrame *pFrame); HRESULT DeliverD3D11Readback(LAVFrame *pFrame); HRESULT DeliverD3D11ReadbackDirect(LAVFrame *pFrame); BOOL IsHardwareAccelerator() { return TRUE; } private: STDMETHODIMP DestroyDecoder(bool bFull); STDMETHODIMP ReInitD3D11Decoder(AVCodecContext *c); STDMETHODIMP CreateD3D11Device(UINT nDeviceIndex, ID3D11Device **ppDevice, DXGI_ADAPTER_DESC *pDesc); STDMETHODIMP CreateD3D11Decoder(); STDMETHODIMP AllocateFramesContext(int width, int height, DXGI_FORMAT format, int nSurfaces, AVBufferRef **pFramesCtx); STDMETHODIMP FindVideoServiceConversion(AVCodecID codec, int profile, int level, DXGI_FORMAT &surface_format, GUID *input); STDMETHODIMP FindDecoderConfiguration(const D3D11_VIDEO_DECODER_DESC *desc, D3D11_VIDEO_DECODER_CONFIG *pConfig); STDMETHODIMP FillHWContext(AVD3D11VAContext *ctx); STDMETHODIMP FlushDisplayQueue(BOOL bDeliver); static enum AVPixelFormat get_d3d11_format(struct AVCodecContext *s, const enum AVPixelFormat *pix_fmts); static int get_d3d11_buffer(struct AVCodecContext *c, AVFrame *pic, int flags); private: CD3D11SurfaceAllocator *m_pAllocator = nullptr; AVBufferRef *m_pDevCtx = nullptr; AVBufferRef *m_pFramesCtx = nullptr; D3D11_VIDEO_DECODER_CONFIG m_DecoderConfig; ID3D11VideoDecoder *m_pDecoder = nullptr; int m_nOutputViews = 0; ID3D11VideoDecoderOutputView **m_pOutputViews = nullptr; DWORD m_dwSurfaceWidth = 0; DWORD m_dwSurfaceHeight = 0; DWORD m_dwSurfaceCount = 0; DXGI_FORMAT m_SurfaceFormat = DXGI_FORMAT_UNKNOWN; BOOL m_bReadBackFallback = FALSE; BOOL m_bDirect = FALSE; BOOL m_bFailHWDecode = FALSE; BOOL m_bP016ToP010Fallback = FALSE; ID3D11Texture2D *m_pD3D11StagingTexture = nullptr; LAVFrame *m_FrameQueue[D3D11_QUEUE_SURFACES]; int m_FrameQueuePosition = 0; int m_DisplayDelay = D3D11_QUEUE_SURFACES; struct { HMODULE d3d11lib; PFN_D3D11_CREATE_DEVICE mD3D11CreateDevice; HMODULE dxgilib; PFN_CREATE_DXGI_FACTORY1 mCreateDXGIFactory1; } dx = {0}; DXGI_ADAPTER_DESC m_AdapterDesc = {0}; friend class CD3D11SurfaceAllocator; }; ================================================ FILE: decoder/LAVVideo/decoders/dxva2/DXVA2SurfaceAllocator.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial Design and Concept taken from MPC-HC, licensed under GPLv2 */ #include "stdafx.h" #include "decoders/dxva2dec.h" #include "DXVA2SurfaceAllocator.h" #include "moreuuids.h" #include #include CDXVA2Sample::CDXVA2Sample(CDXVA2SurfaceAllocator *pAlloc, HRESULT *phr) : CMediaSampleSideData(NAME("CDXVA2Sample"), (CBaseAllocator *)pAlloc, phr, nullptr, 0) { } CDXVA2Sample::~CDXVA2Sample() { SafeRelease(&m_pSurface); } // Note: CMediaSample does not derive from CUnknown, so we cannot use the // DECLARE_IUNKNOWN macro that is used by most of the filter classes. STDMETHODIMP CDXVA2Sample::QueryInterface(REFIID riid, __deref_out void **ppv) { CheckPointer(ppv, E_POINTER); ValidateReadWritePtr(ppv, sizeof(PVOID)); if (riid == __uuidof(IMFGetService)) { return GetInterface((IMFGetService *)this, ppv); } else if (riid == __uuidof(ILAVDXVA2Sample)) { return GetInterface((ILAVDXVA2Sample *)this, ppv); } else { return __super::QueryInterface(riid, ppv); } } STDMETHODIMP_(ULONG) CDXVA2Sample::AddRef() { return __super::AddRef(); } STDMETHODIMP_(ULONG) CDXVA2Sample::Release() { // Return a temporary variable for thread safety. ULONG cRef = __super::Release(); return cRef; } // IMFGetService::GetService STDMETHODIMP CDXVA2Sample::GetService(REFGUID guidService, REFIID riid, LPVOID *ppv) { if (guidService != MR_BUFFER_SERVICE) { return MF_E_UNSUPPORTED_SERVICE; } else if (m_pSurface == nullptr) { return E_NOINTERFACE; } else { return m_pSurface->QueryInterface(riid, ppv); } } // Override GetPointer because this class does not manage a system memory buffer. // The EVR uses the MR_BUFFER_SERVICE service to get the Direct3D surface. STDMETHODIMP CDXVA2Sample::GetPointer(BYTE **ppBuffer) { return E_NOTIMPL; } // Sets the pointer to the Direct3D surface. void CDXVA2Sample::SetSurface(DWORD surfaceId, IDirect3DSurface9 *pSurf) { SafeRelease(&m_pSurface); m_pSurface = pSurf; m_dwSurfaceId = surfaceId; if (m_pSurface) m_pSurface->AddRef(); } STDMETHODIMP_(int) CDXVA2Sample::GetDXSurfaceId() { return m_dwSurfaceId; } CDXVA2SurfaceAllocator::CDXVA2SurfaceAllocator(CDecDXVA2 *m_pDXVA2Dec, HRESULT *phr) : CBaseAllocator(NAME("CDXVA2SurfaceAllocator"), nullptr, phr) , m_pDec(m_pDXVA2Dec) { } CDXVA2SurfaceAllocator::~CDXVA2SurfaceAllocator(void) { if (m_pDec && m_pDec->m_pDXVA2Allocator == this) m_pDec->m_pDXVA2Allocator = nullptr; } // IUnknown STDMETHODIMP CDXVA2SurfaceAllocator::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; return QI(ILAVDXVA2SurfaceAllocator) __super::NonDelegatingQueryInterface(riid, ppv); } HRESULT CDXVA2SurfaceAllocator::Alloc() { DbgLog((LOG_TRACE, 10, L"CDXVA2SurfaceAllocator::Alloc()")); HRESULT hr = S_OK; IDirectXVideoDecoderService *pDXVA2Service = nullptr; if (!m_pDec) return E_FAIL; CheckPointer(m_pDec->m_pD3DDevMngr, E_UNEXPECTED); hr = m_pDec->m_pD3DDevMngr->GetVideoService(m_pDec->m_hDevice, IID_IDirectXVideoDecoderService, (void **)&pDXVA2Service); CheckPointer(pDXVA2Service, E_UNEXPECTED); CAutoLock lock(this); hr = __super::Alloc(); if (SUCCEEDED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Releasing old resources")); // Free the old resources. m_pDec->FlushFromAllocator(); Free(); m_nSurfaceArrayCount = m_lCount; // Allocate a new array of pointers. m_ppRTSurfaceArray = new IDirect3DSurface9 *[m_lCount]; if (m_ppRTSurfaceArray == nullptr) { hr = E_OUTOFMEMORY; } else { ZeroMemory(m_ppRTSurfaceArray, sizeof(IDirect3DSurface9 *) * m_lCount); } } // Allocate the surfaces. if (SUCCEEDED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Allocating surfaces")); hr = pDXVA2Service->CreateSurface(m_pDec->m_dwSurfaceWidth, m_pDec->m_dwSurfaceHeight, m_lCount - 1, m_pDec->m_eSurfaceFormat, D3DPOOL_DEFAULT, 0, DXVA2_VideoDecoderRenderTarget, m_ppRTSurfaceArray, nullptr); } if (SUCCEEDED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creating samples")); // Important : create samples in reverse order ! for (int i = m_lCount - 1; i >= 0; i--) { CDXVA2Sample *pSample = new CDXVA2Sample(this, &hr); if (pSample == nullptr) { hr = E_OUTOFMEMORY; break; } if (FAILED(hr)) { break; } // Assign the Direct3D surface pointer and the index. pSample->SetSurface(i, m_ppRTSurfaceArray[i]); // Add to the sample list. m_lFree.Add(pSample); } hr = m_pDec->CreateDXVA2Decoder(m_lCount, m_ppRTSurfaceArray); if (FAILED(hr)) { Free(); } } m_lAllocated = m_lCount; if (SUCCEEDED(hr)) { m_bChanged = FALSE; } SafeRelease(&pDXVA2Service); return hr; } void CDXVA2SurfaceAllocator::Free() { DbgLog((LOG_TRACE, 10, L"CDXVA2SurfaceAllocator::Free()")); CMediaSample *pSample = nullptr; CAutoLock lock(this); do { pSample = m_lFree.RemoveHead(); if (pSample) { delete pSample; } } while (pSample); if (m_ppRTSurfaceArray) { for (UINT i = 0; i < m_nSurfaceArrayCount; i++) { if (m_ppRTSurfaceArray[i] != nullptr) { m_ppRTSurfaceArray[i]->Release(); } } delete[] m_ppRTSurfaceArray; m_ppRTSurfaceArray = nullptr; } m_lAllocated = 0; m_nSurfaceArrayCount = 0; } ================================================ FILE: decoder/LAVVideo/decoders/dxva2/DXVA2SurfaceAllocator.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial Design and Concept taken from MPC-HC, licensed under GPLv2 */ #pragma once #include #include "MediaSampleSideData.h" class CDecDXVA2; interface __declspec(uuid("50A8A9A1-FF44-45C1-9DC2-79066ED1E576")) ILAVDXVA2Sample : public IUnknown { STDMETHOD_(int, GetDXSurfaceId()) = 0; }; class CDXVA2Sample : public CMediaSampleSideData , public IMFGetService , public ILAVDXVA2Sample { friend class CDXVA2SurfaceAllocator; public: CDXVA2Sample(CDXVA2SurfaceAllocator *pAlloc, HRESULT *phr); virtual ~CDXVA2Sample(); STDMETHODIMP QueryInterface(REFIID riid, __deref_out void **ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // IMFGetService::GetService STDMETHODIMP GetService(REFGUID guidService, REFIID riid, LPVOID *ppv); // ILAVDXVA2Sample STDMETHODIMP_(int) GetDXSurfaceId(); // Override GetPointer because this class does not manage a system memory buffer. // The EVR uses the MR_BUFFER_SERVICE service to get the Direct3D surface. STDMETHODIMP GetPointer(BYTE **ppBuffer); private: // Sets the pointer to the Direct3D surface. void SetSurface(DWORD surfaceId, IDirect3DSurface9 *pSurf); IDirect3DSurface9 *m_pSurface = nullptr; DWORD m_dwSurfaceId = 0; }; interface __declspec(uuid("23F80BD8-2654-4F74-B7CC-621868D0A850")) ILAVDXVA2SurfaceAllocator : public IUnknown { STDMETHOD_(void, DecoderDestruct)() = 0; }; class CDXVA2SurfaceAllocator : public CBaseAllocator , public ILAVDXVA2SurfaceAllocator { public: CDXVA2SurfaceAllocator(CDecDXVA2 *m_pDXVA2Dec, HRESULT *phr); virtual ~CDXVA2SurfaceAllocator(void); DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); HRESULT Alloc(); void Free(); STDMETHODIMP_(BOOL) DecommitInProgress() { CAutoLock cal(this); return m_bDecommitInProgress; } STDMETHODIMP_(BOOL) IsCommited() { CAutoLock cal(this); return m_bCommitted; } STDMETHODIMP_(void) DecoderDestruct() { m_pDec = nullptr; } private: CDecDXVA2 *m_pDec = nullptr; IDirect3DSurface9 **m_ppRTSurfaceArray = nullptr; UINT m_nSurfaceArrayCount = 0; }; ================================================ FILE: decoder/LAVVideo/decoders/dxva2/dxva_common.cpp ================================================ /* * Copyright (C) 2011-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "dxva_common.h" #include "moreuuids.h" extern "C" { #include "libavcodec/h265_rext_profiles.h" }; #define DXVA_SURFACE_BASE_ALIGN 16 DWORD dxva_align_dimensions(AVCodecID codec, DWORD dim) { int align = DXVA_SURFACE_BASE_ALIGN; // MPEG-2 needs higher alignment on Intel cards, and it doesn't seem to harm anything to do it for all cards. if (codec == AV_CODEC_ID_MPEG2VIDEO) align <<= 1; else if (codec == AV_CODEC_ID_HEVC || codec == AV_CODEC_ID_AV1) align = 128; return FFALIGN(dim, align); } //////////////////////////////////////////////////////////////////////////////// // Codec Maps //////////////////////////////////////////////////////////////////////////////// /* DXVA2 Codec Mappings, as defined by VLC */ static const int prof_mpeg2_main[] = { AV_PROFILE_MPEG2_SIMPLE, AV_PROFILE_MPEG2_MAIN, AV_PROFILE_UNKNOWN }; static const int prof_h264_high[] = { AV_PROFILE_H264_CONSTRAINED_BASELINE, AV_PROFILE_H264_MAIN, AV_PROFILE_H264_HIGH, AV_PROFILE_UNKNOWN }; static const int prof_hevc_main[] = { AV_PROFILE_HEVC_MAIN, AV_PROFILE_UNKNOWN }; static const int prof_hevc_main10[] = { AV_PROFILE_HEVC_MAIN_10, AV_PROFILE_UNKNOWN }; static const int prof_hevc_rext[] = {AV_PROFILE_HEVC_REXT, AV_PROFILE_UNKNOWN}; static const int prof_vp9_0[] = { AV_PROFILE_VP9_0, AV_PROFILE_UNKNOWN }; static const int prof_vp9_2_10bit[] = { AV_PROFILE_VP9_2, AV_PROFILE_UNKNOWN }; static const int prof_av1_0[] = {AV_PROFILE_AV1_MAIN, AV_PROFILE_UNKNOWN}; static const int prof_av1_1[] = {AV_PROFILE_AV1_HIGH, AV_PROFILE_UNKNOWN}; static const int prof_av1_2[] = {AV_PROFILE_AV1_PROFESSIONAL, AV_PROFILE_UNKNOWN}; /* XXX Preferred modes must come first */ // clang-format off const dxva_mode_t dxva_modes[] = { /* MPEG-1/2 */ { "MPEG-2 variable-length decoder", &DXVA2_ModeMPEG2_VLD, AV_CODEC_ID_MPEG2VIDEO, prof_mpeg2_main }, { "MPEG-2 & MPEG-1 variable-length decoder", &DXVA2_ModeMPEG2and1_VLD, AV_CODEC_ID_MPEG2VIDEO, prof_mpeg2_main }, { "MPEG-2 motion compensation", &DXVA2_ModeMPEG2_MoComp, 0 }, { "MPEG-2 inverse discrete cosine transform", &DXVA2_ModeMPEG2_IDCT, 0 }, { "MPEG-1 variable-length decoder", &DXVA2_ModeMPEG1_VLD, 0 }, /* H.264 */ { "H.264 variable-length decoder, film grain technology", &DXVA2_ModeH264_F, AV_CODEC_ID_H264, prof_h264_high }, { "H.264 variable-length decoder, no film grain technology", &DXVA2_ModeH264_E, AV_CODEC_ID_H264, prof_h264_high }, { "H.264 variable-length decoder, no film grain technology, FMO/ASO", &DXVA_ModeH264_VLD_WithFMOASO_NoFGT, AV_CODEC_ID_H264, prof_h264_high }, { "H.264 variable-length decoder, no film grain technology, Flash", &DXVA_ModeH264_VLD_NoFGT_Flash, AV_CODEC_ID_H264, prof_h264_high }, { "H.264 inverse discrete cosine transform, film grain technology", &DXVA2_ModeH264_D, 0 }, { "H.264 inverse discrete cosine transform, no film grain technology", &DXVA2_ModeH264_C, 0 }, { "H.264 motion compensation, film grain technology", &DXVA2_ModeH264_B, 0 }, { "H.264 motion compensation, no film grain technology", &DXVA2_ModeH264_A, 0 }, /* WMV */ { "Windows Media Video 8 motion compensation", &DXVA2_ModeWMV8_B, 0 }, { "Windows Media Video 8 post processing", &DXVA2_ModeWMV8_A, 0 }, { "Windows Media Video 9 IDCT", &DXVA2_ModeWMV9_C, 0 }, { "Windows Media Video 9 motion compensation", &DXVA2_ModeWMV9_B, 0 }, { "Windows Media Video 9 post processing", &DXVA2_ModeWMV9_A, 0 }, /* VC-1 */ { "VC-1 variable-length decoder (2010)", &DXVA2_ModeVC1_D2010, AV_CODEC_ID_VC1 }, { "VC-1 variable-length decoder (2010)", &DXVA2_ModeVC1_D2010, AV_CODEC_ID_WMV3 }, { "VC-1 variable-length decoder", &DXVA2_ModeVC1_D, AV_CODEC_ID_VC1 }, { "VC-1 variable-length decoder", &DXVA2_ModeVC1_D, AV_CODEC_ID_WMV3 }, { "VC-1 inverse discrete cosine transform", &DXVA2_ModeVC1_C, 0 }, { "VC-1 motion compensation", &DXVA2_ModeVC1_B, 0 }, { "VC-1 post processing", &DXVA2_ModeVC1_A, 0 }, /* MPEG4-ASP */ { "MPEG-4 Part 2 nVidia bitstream decoder", &DXVA_nVidia_MPEG4_ASP, 0 }, { "MPEG-4 Part 2 variable-length decoder, Simple Profile", &DXVA_ModeMPEG4pt2_VLD_Simple, 0 }, { "MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, no GMC", &DXVA_ModeMPEG4pt2_VLD_AdvSimple_NoGMC, 0 }, { "MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, GMC", &DXVA_ModeMPEG4pt2_VLD_AdvSimple_GMC, 0 }, { "MPEG-4 Part 2 variable-length decoder, Simple&Advanced Profile, Avivo", &DXVA_ModeMPEG4pt2_VLD_AdvSimple_Avivo, 0 }, /* H.264 MVC */ { "H.264 MVC variable-length decoder, stereo, progressive", &DXVA_ModeH264_VLD_Stereo_Progressive_NoFGT, 0 }, { "H.264 MVC variable-length decoder, stereo", &DXVA_ModeH264_VLD_Stereo_NoFGT, 0 }, { "H.264 MVC variable-length decoder, multiview", &DXVA_ModeH264_VLD_Multiview_NoFGT, 0 }, /* H.264 SVC */ { "H.264 SVC variable-length decoder, baseline", &DXVA_ModeH264_VLD_SVC_Scalable_Baseline, 0 }, { "H.264 SVC variable-length decoder, constrained baseline", &DXVA_ModeH264_VLD_SVC_Restricted_Scalable_Baseline, 0 }, { "H.264 SVC variable-length decoder, high", &DXVA_ModeH264_VLD_SVC_Scalable_High, 0 }, { "H.264 SVC variable-length decoder, constrained high progressive", &DXVA_ModeH264_VLD_SVC_Restricted_Scalable_High_Progressive, 0 }, /* HEVC / H.265 */ { "HEVC / H.265 variable-length decoder, main", &DXVA_ModeHEVC_VLD_Main, AV_CODEC_ID_HEVC, prof_hevc_main }, { "HEVC / H.265 variable-length decoder, main10", &DXVA_ModeHEVC_VLD_Main10, AV_CODEC_ID_HEVC, prof_hevc_main10 }, { "HEVC / H.265 variable-length decoder, main12", &DXVA_ModeHEVC_VLD_Main12, AV_CODEC_ID_HEVC, prof_hevc_rext, FF_HEVC_REXT_PROFILE_MAIN_12 }, { "HEVC / H.265 variable-length decoder, main10 422", &DXVA_ModeHEVC_VLD_Main10_422, AV_CODEC_ID_HEVC, prof_hevc_rext, FF_HEVC_REXT_PROFILE_MAIN422_10 }, { "HEVC / H.265 variable-length decoder, main12 422", &DXVA_ModeHEVC_VLD_Main12_422, AV_CODEC_ID_HEVC, prof_hevc_rext, FF_HEVC_REXT_PROFILE_MAIN422_12 }, { "HEVC / H.265 variable-length decoder, main 444", &DXVA_ModeHEVC_VLD_Main_444, AV_CODEC_ID_HEVC, prof_hevc_rext, FF_HEVC_REXT_PROFILE_MAIN444 }, { "HEVC / H.265 variable-length decoder, main10 extended", &DXVA_ModeHEVC_VLD_Main10_Ext, 0 }, { "HEVC / H.265 variable-length decoder, main10 444", &DXVA_ModeHEVC_VLD_Main10_444, AV_CODEC_ID_HEVC, prof_hevc_rext, FF_HEVC_REXT_PROFILE_MAIN444_10 }, { "HEVC / H.265 variable-length decoder, main12 444", &DXVA_ModeHEVC_VLD_Main12_444, AV_CODEC_ID_HEVC, prof_hevc_rext, FF_HEVC_REXT_PROFILE_MAIN444_12 }, { "HEVC / H.265 variable-length decoder, main16", &DXVA_ModeHEVC_VLD_Main16, AV_CODEC_ID_HEVC, prof_hevc_rext, FF_HEVC_REXT_PROFILE_MAIN444_16 }, { "HEVC / H.265 variable-length decoder, monochrome", &DXVA_ModeHEVC_VLD_Monochrome, 0 }, { "HEVC / H.265 variable-length decoder, monochrome10", &DXVA_ModeHEVC_VLD_Monochrome10, 0 }, /* VP8/9 */ { "VP9 variable-length decoder, profile 0", &DXVA_ModeVP9_VLD_Profile0, AV_CODEC_ID_VP9, prof_vp9_0 }, { "VP9 variable-length decoder, 10bit, profile 2", &DXVA_ModeVP9_VLD_10bit_Profile2, AV_CODEC_ID_VP9, prof_vp9_2_10bit }, { "VP8 variable-length decoder", &DXVA_ModeVP8_VLD, 0 }, /* AV1 */ { "AV1 variable-length decoder, profile 0", &DXVA_ModeAV1_VLD_Profile0, AV_CODEC_ID_AV1, prof_av1_0 }, { "AV1 variable-length decoder, profile 1", &DXVA_ModeAV1_VLD_Profile1, 0 }, { "AV1 variable-length decoder, profile 2", &DXVA_ModeAV1_VLD_Profile2, 0 }, { "AV1 variable-length decoder, profile 2 12-bit", &DXVA_ModeAV1_VLD_12bit_Profile2, 0 }, { "AV1 variable-length decoder, profile 2 12-bit 4:2:0", &DXVA_ModeAV1_VLD_12bit_Profile2_420, 0 }, /* Intel specific modes (only useful on older GPUs) */ { "H.264 variable-length decoder, no film grain technology (Intel ClearVideo)", &DXVADDI_Intel_ModeH264_E, AV_CODEC_ID_H264, prof_h264_high }, { "H.264 inverse discrete cosine transform, no film grain technology (Intel)", &DXVADDI_Intel_ModeH264_C, 0 }, { "H.264 motion compensation, no film grain technology (Intel)", &DXVADDI_Intel_ModeH264_A, 0 }, { "VC-1 variable-length decoder 2 (Intel)", &DXVA_Intel_VC1_ClearVideo_2, 0 }, { "VC-1 variable-length decoder (Intel)", &DXVA_Intel_VC1_ClearVideo, 0 }, { nullptr, nullptr, 0 } }; // clang-format on const dxva_mode_t *get_dxva_mode_from_guid(const GUID *guid) { for (unsigned i = 0; dxva_modes[i].name; i++) { if (IsEqualGUID(*dxva_modes[i].guid, *guid)) return &dxva_modes[i]; } return nullptr; } int check_dxva_mode_compatibility(const dxva_mode_t *mode, int codec, int profile, int level, bool b8Bit) { if (mode->codec != codec) return 0; if (mode->profiles && profile != AV_PROFILE_UNKNOWN) { for (int i = 0; mode->profiles[i] != AV_PROFILE_UNKNOWN; i++) { if (mode->profiles[i] == profile && (mode->level == 0 || mode->level == level)) return 1; } /* hevc main and main10 are very similar, and in some cases streams can be flagged as main10, but actually contain 8-bit content */ if (codec == AV_CODEC_ID_HEVC && mode->profiles[0] == AV_PROFILE_HEVC_MAIN && profile == AV_PROFILE_HEVC_MAIN_10 && b8Bit) return 1; return 0; } return 1; } #define H264_MAX_REF_DPB(ctx, dpbsize, dpblimit, mbcount) (min(dpblimit, (dpbsize) / (mbcount))) int check_dxva_codec_profile(const AVCodecContext *ctx, int hwpixfmt) { AVCodecID codec = ctx->codec_id; AVPixelFormat pix_fmt = ctx->pix_fmt; int profile = ctx->profile; int level = ctx->level; // check mpeg2 pixfmt if (codec == AV_CODEC_ID_MPEG2VIDEO && pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != hwpixfmt && pix_fmt != AV_PIX_FMT_NONE) return 1; // check h264 pixfmt if (codec == AV_CODEC_ID_H264 && pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != hwpixfmt && pix_fmt != AV_PIX_FMT_NONE) return 1; // check h264 profile if (codec == AV_CODEC_ID_H264 && profile != AV_PROFILE_UNKNOWN && !H264_CHECK_PROFILE(profile)) return 1; // H.264 Level 5.1 ref frame limits const int h264mb_count = (ctx->coded_width / 16) * (ctx->coded_height / 16); if (codec == AV_CODEC_ID_H264 && h264mb_count > 0 && ctx->refs > H264_MAX_REF_DPB(ctx, 184320, 16, h264mb_count)) return 1; // check wmv/vc1 profile if ((codec == AV_CODEC_ID_WMV3 || codec == AV_CODEC_ID_VC1) && profile == AV_PROFILE_VC1_COMPLEX) return 1; // check vp9 profile/pixfmt if (codec == AV_CODEC_ID_VP9 && (!VP9_CHECK_PROFILE(profile) || (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUV420P10 && pix_fmt != hwpixfmt && pix_fmt != AV_PIX_FMT_NONE))) return 1; // check av1 profile/pixfmt if (codec == AV_CODEC_ID_AV1 && (profile != AV_PROFILE_AV1_MAIN || (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUV420P10 && pix_fmt != hwpixfmt && pix_fmt != AV_PIX_FMT_NONE))) return 1; return 0; } ================================================ FILE: decoder/LAVVideo/decoders/dxva2/dxva_common.h ================================================ /* * Copyright (C) 2011-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once /* Align dimensions for hardware and codec requirements */ DWORD dxva_align_dimensions(AVCodecID codec, DWORD dim); #define VEND_ID_ATI 0x1002 #define VEND_ID_NVIDIA 0x10DE #define VEND_ID_INTEL 0x8086 /* hardware mode description */ typedef struct { const char *name; const GUID *guid; int codec; const int *profiles; const int level; } dxva_mode_t; extern const dxva_mode_t dxva_modes[]; const dxva_mode_t *get_dxva_mode_from_guid(const GUID *guid); int check_dxva_mode_compatibility(const dxva_mode_t *mode, int codec, int profile, int level, bool b8Bit); int check_dxva_codec_profile(const AVCodecContext *ctx, int hwpixfmt); #define H264_CHECK_PROFILE(profile) (((profile) & ~AV_PROFILE_H264_CONSTRAINED) <= AV_PROFILE_H264_HIGH) #define HEVC_CHECK_PROFILE(profile) ((profile) <= AV_PROFILE_HEVC_MAIN_10) #define VP9_CHECK_PROFILE(profile) ((profile) == AV_PROFILE_VP9_0 || (profile) == AV_PROFILE_VP9_2) ================================================ FILE: decoder/LAVVideo/decoders/dxva2dec.cpp ================================================ /* * Copyright (C) 2011-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Basic concept based on VLC DXVA2 decoder, licensed under GPLv2 */ #include "stdafx.h" #include "dxva2dec.h" #include "dxva2/dxva_common.h" #include "dxva2/DXVA2SurfaceAllocator.h" #include "moreuuids.h" #include "Media.h" #include #include #include #include "libavcodec/dxva2.h" extern "C" { #include "libavutil/imgutils.h" #define FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG 1 #define FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO 2 #define FF_DXVA2_WORKAROUND_NVIDIA_HEVC_420P12 4 } //////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////// ILAVDecoder *CreateDecoderDXVA2() { return new CDecDXVA2(); } ILAVDecoder *CreateDecoderDXVA2Native() { CDecDXVA2 *dec = new CDecDXVA2(); dec->SetNativeMode(TRUE); return dec; } HRESULT VerifyD3D9Device(DWORD &dwIndex, DWORD dwDeviceId) { HRESULT hr = S_OK; IDirect3D9 *pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!pD3D) return E_FAIL; D3DADAPTER_IDENTIFIER9 d3dai = {0}; // Check the combination of adapter and device id hr = pD3D->GetAdapterIdentifier(dwIndex, 0, &d3dai); if (hr == D3D_OK && d3dai.DeviceId == dwDeviceId) goto done; // find an adapter with the specified device id for (UINT i = 0; i < pD3D->GetAdapterCount(); i++) { hr = pD3D->GetAdapterIdentifier(i, 0, &d3dai); if (hr == D3D_OK && d3dai.DeviceId == dwDeviceId) { dwIndex = i; goto done; } } // fail otherwise hr = E_FAIL; done: SafeRelease(&pD3D); return hr; } // List of PCI Device ID of ATI cards with UVD or UVD+ decoding block. static DWORD UVDDeviceID[] = {0x94C7, // ATI Radeon HD 2350 0x94C1, // ATI Radeon HD 2400 XT 0x94CC, // ATI Radeon HD 2400 Series 0x958A, // ATI Radeon HD 2600 X2 Series 0x9588, // ATI Radeon HD 2600 XT 0x9405, // ATI Radeon HD 2900 GT 0x9400, // ATI Radeon HD 2900 XT 0x9611, // ATI Radeon 3100 Graphics 0x9610, // ATI Radeon HD 3200 Graphics 0x9614, // ATI Radeon HD 3300 Graphics 0x95C0, // ATI Radeon HD 3400 Series (and others) 0x95C5, // ATI Radeon HD 3400 Series (and others) 0x95C4, // ATI Radeon HD 3400 Series (and others) 0x94C3, // ATI Radeon HD 3410 0x9589, // ATI Radeon HD 3600 Series (and others) 0x9598, // ATI Radeon HD 3600 Series (and others) 0x9591, // ATI Radeon HD 3600 Series (and others) 0x9501, // ATI Radeon HD 3800 Series (and others) 0x9505, // ATI Radeon HD 3800 Series (and others) 0x9507, // ATI Radeon HD 3830 0x9513, // ATI Radeon HD 3850 X2 0x950F, // ATI Radeon HD 3850 X2 0x0000}; static int IsAMDUVD(DWORD dwDeviceId) { for (int i = 0; UVDDeviceID[i] != 0; i++) { if (UVDDeviceID[i] == dwDeviceId) return 1; } return 0; } static D3DFORMAT get_dxva_surface_format(AVCodecContext *ctx) { if (ctx->sw_pix_fmt == AV_PIX_FMT_YUV420P || ctx->sw_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->sw_pix_fmt == AV_PIX_FMT_NV12) return (D3DFORMAT)FOURCC_NV12; else if (ctx->sw_pix_fmt == AV_PIX_FMT_YUV420P10 || ctx->sw_pix_fmt == AV_PIX_FMT_P010) return (D3DFORMAT)FOURCC_P010; ASSERT(ctx->sw_pix_fmt == AV_PIX_FMT_NONE); return (D3DFORMAT)FOURCC_NV12; } //////////////////////////////////////////////////////////////////////////////// // DXVA2 decoder implementation //////////////////////////////////////////////////////////////////////////////// CDecDXVA2::CDecDXVA2(void) : CDecAvcodec() { ZeroMemory(&dx, sizeof(dx)); ZeroMemory(&m_pSurfaces, sizeof(m_pSurfaces)); ZeroMemory(&m_pRawSurface, sizeof(m_pRawSurface)); ZeroMemory(&m_FrameQueue, sizeof(m_FrameQueue)); ZeroMemory(&m_DXVAVideoDecoderConfig, sizeof(m_DXVAVideoDecoderConfig)); } CDecDXVA2::~CDecDXVA2(void) { DestroyDecoder(true); if (m_pDXVA2Allocator) m_pDXVA2Allocator->DecoderDestruct(); } STDMETHODIMP CDecDXVA2::DestroyDecoder(bool bFull, bool bNoAVCodec) { for (int i = 0; i < DXVA2_QUEUE_SURFACES; i++) { ReleaseFrame(&m_FrameQueue[i]); } m_pCallback->ReleaseAllDXVAResources(); for (int i = 0; i < m_NumSurfaces; i++) { SafeRelease(&m_pSurfaces[i].d3d); } m_NumSurfaces = 0; SafeRelease(&m_pDecoder); if (!bNoAVCodec) { CDecAvcodec::DestroyDecoder(); } if (bFull) { FreeD3DResources(); } return S_OK; } STDMETHODIMP CDecDXVA2::FreeD3DResources() { SafeRelease(&m_pDXVADecoderService); if (m_pD3DDevMngr && m_hDevice != INVALID_HANDLE_VALUE) m_pD3DDevMngr->CloseDeviceHandle(m_hDevice); m_hDevice = INVALID_HANDLE_VALUE; SafeRelease(&m_pD3DDevMngr); SafeRelease(&m_pD3DDev); SafeRelease(&m_pD3D); if (dx.d3dlib) { FreeLibrary(dx.d3dlib); dx.d3dlib = nullptr; } if (dx.dxva2lib) { FreeLibrary(dx.dxva2lib); dx.dxva2lib = nullptr; } return S_OK; } STDMETHODIMP CDecDXVA2::InitAllocator(IMemAllocator **ppAlloc) { HRESULT hr = S_OK; if (!m_bNative) return E_NOTIMPL; m_pDXVA2Allocator = new CDXVA2SurfaceAllocator(this, &hr); if (!m_pDXVA2Allocator) { return E_OUTOFMEMORY; } if (FAILED(hr)) { SAFE_DELETE(m_pDXVA2Allocator); return hr; } return m_pDXVA2Allocator->QueryInterface(__uuidof(IMemAllocator), (void **)ppAlloc); } STDMETHODIMP CDecDXVA2::PostConnect(IPin *pPin) { HRESULT hr = S_OK; if (!m_bNative && m_pD3DDevMngr) return S_OK; DbgLog((LOG_TRACE, 10, L"CDecDXVA2::PostConnect()")); IMFGetService *pGetService = nullptr; hr = pPin->QueryInterface(__uuidof(IMFGetService), (void **)&pGetService); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> IMFGetService not available")); goto done; } // Release old D3D resources, we're about to re-init m_pCallback->ReleaseAllDXVAResources(); FreeD3DResources(); // Get the Direct3D device manager. hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, __uuidof(IDirect3DDeviceManager9), (void **)&m_pD3DDevMngr); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> D3D Device Manager not available")); goto done; } hr = SetD3DDeviceManager(m_pD3DDevMngr); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Setting D3D Device Manager failed")); goto done; } if (m_bNative) { if (!m_pDecoder) { // If this is the first call, re-align surfaces, as the requirements may only be known now m_dwSurfaceWidth = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_width); m_dwSurfaceHeight = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_height); } CMediaType mt = m_pCallback->GetOutputMediaType(); if ((m_eSurfaceFormat == FOURCC_NV12 && mt.subtype != MEDIASUBTYPE_NV12) || (m_eSurfaceFormat == FOURCC_P010 && mt.subtype != MEDIASUBTYPE_P010) || (m_eSurfaceFormat == FOURCC_P016 && mt.subtype != MEDIASUBTYPE_P016)) { DbgLog((LOG_ERROR, 10, L"-> Connection is not the appropriate pixel format for DXVA2 Native")); hr = E_FAIL; goto done; } hr = DXVA2NotifyEVR(); } done: SafeRelease(&pGetService); if (FAILED(hr)) { FreeD3DResources(); } return hr; } HRESULT CDecDXVA2::DXVA2NotifyEVR() { HRESULT hr = S_OK; IMFGetService *pGetService = nullptr; IDirectXVideoMemoryConfiguration *pVideoConfig = nullptr; hr = m_pCallback->GetOutputPin()->GetConnected()->QueryInterface(&pGetService); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> IMFGetService not available")); goto done; } // Configure EVR for receiving DXVA2 samples hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, __uuidof(IDirectXVideoMemoryConfiguration), (void **)&pVideoConfig); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> IDirectXVideoMemoryConfiguration not available")); goto done; } // Notify the EVR about the format we're sending DXVA2_SurfaceType surfaceType; for (DWORD iTypeIndex = 0;; iTypeIndex++) { hr = pVideoConfig->GetAvailableSurfaceTypeByIndex(iTypeIndex, &surfaceType); if (FAILED(hr)) { hr = S_OK; break; } if (surfaceType == DXVA2_SurfaceType_DecoderRenderTarget) { hr = pVideoConfig->SetSurfaceType(DXVA2_SurfaceType_DecoderRenderTarget); break; } } done: SafeRelease(&pGetService); SafeRelease(&pVideoConfig); return hr; } STDMETHODIMP CDecDXVA2::LoadDXVA2Functions() { // Load D3D9 library dx.d3dlib = LoadLibrary(L"d3d9.dll"); if (dx.d3dlib == nullptr) { DbgLog((LOG_TRACE, 10, L"-> Loading d3d9.dll failed")); return E_FAIL; } dx.direct3DCreate9Ex = (pDirect3DCreate9Ex *)GetProcAddress(dx.d3dlib, "Direct3DCreate9Ex"); // Load DXVA2 library dx.dxva2lib = LoadLibrary(L"dxva2.dll"); if (dx.dxva2lib == nullptr) { DbgLog((LOG_TRACE, 10, L"-> Loading dxva2.dll failed")); return E_FAIL; } dx.createDeviceManager = (pCreateDeviceManager9 *)GetProcAddress(dx.dxva2lib, "DXVA2CreateDirect3DDeviceManager9"); if (dx.createDeviceManager == nullptr) { DbgLog((LOG_TRACE, 10, L"-> DXVA2CreateDirect3DDeviceManager9 unavailable")); return E_FAIL; } return S_OK; } static const struct { unsigned id; char name[32]; } vendors[] = {{VEND_ID_ATI, "ATI"}, {VEND_ID_NVIDIA, "NVIDIA"}, {VEND_ID_INTEL, "Intel"}, {0, ""}}; HRESULT CDecDXVA2::CreateD3DDeviceManager(IDirect3DDevice9 *pDevice, UINT *pReset, IDirect3DDeviceManager9 **ppManager) { UINT resetToken = 0; IDirect3DDeviceManager9 *pD3DManager = nullptr; HRESULT hr = dx.createDeviceManager(&resetToken, &pD3DManager); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> DXVA2CreateDirect3DDeviceManager9 failed")); goto done; } hr = pD3DManager->ResetDevice(pDevice, resetToken); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> ResetDevice failed")); goto done; } *ppManager = pD3DManager; (*ppManager)->AddRef(); *pReset = resetToken; done: SafeRelease(&pD3DManager); return hr; } HRESULT CDecDXVA2::CreateDXVAVideoService(IDirect3DDeviceManager9 *pManager, IDirectXVideoDecoderService **ppService) { HRESULT hr = S_OK; IDirectXVideoDecoderService *pService = nullptr; hr = pManager->OpenDeviceHandle(&m_hDevice); if (FAILED(hr)) { m_hDevice = INVALID_HANDLE_VALUE; DbgLog((LOG_ERROR, 10, L"-> OpenDeviceHandle failed")); goto done; } hr = pManager->GetVideoService(m_hDevice, IID_IDirectXVideoDecoderService, (void **)&pService); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Acquiring VideoDecoderService failed")); goto done; } (*ppService) = pService; done: return hr; } HRESULT CDecDXVA2::FindVideoServiceConversion(AVCodecID codec, int profile, D3DFORMAT suggestedOutput, GUID *input, D3DFORMAT *output) { HRESULT hr = S_OK; UINT count = 0; GUID *input_list = nullptr; /* Gather the format supported by the decoder */ hr = m_pDXVADecoderService->GetDecoderDeviceGuids(&count, &input_list); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> GetDecoderDeviceGuids failed with hr: %X", hr)); goto done; } DbgLog((LOG_TRACE, 10, L"-> Enumerating supported DXVA2 modes (count: %d)", count)); for (unsigned i = 0; i < count; i++) { const GUID *g = &input_list[i]; const dxva_mode_t *mode = get_dxva_mode_from_guid(g); if (mode) { DbgLog((LOG_TRACE, 10, L" -> %S", mode->name)); } else { DbgLog((LOG_TRACE, 10, L" -> Unknown GUID (%s)", WStringFromGUID(*g).c_str())); } } /* Iterate over our priority list */ for (unsigned i = 0; dxva_modes[i].name; i++) { const dxva_mode_t *mode = &dxva_modes[i]; if (!check_dxva_mode_compatibility(mode, codec, profile, 0, (suggestedOutput == FOURCC_NV12))) continue; BOOL supported = FALSE; for (const GUID *g = &input_list[0]; !supported && g < &input_list[count]; g++) { supported = IsEqualGUID(*mode->guid, *g); } if (!supported) continue; DbgLog((LOG_TRACE, 10, L"-> Trying to use '%S'", mode->name)); UINT out_count = 0; D3DFORMAT *out_list = nullptr; hr = m_pDXVADecoderService->GetDecoderRenderTargets(*mode->guid, &out_count, &out_list); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Retrieving render targets failed with hr: %X", hr)); continue; } BOOL matchingFormat = FALSE; D3DFORMAT format = D3DFMT_UNKNOWN; DbgLog((LOG_TRACE, 10, L"-> Enumerating render targets (count: %d)", out_count)); for (unsigned j = 0; j < out_count; j++) { const D3DFORMAT f = out_list[j]; DbgLog((LOG_TRACE, 10, L" -> %d is supported (%4.4S)", f, (const char *)&f)); if (suggestedOutput == f || (suggestedOutput == FOURCC_P010 && f == FOURCC_P016)) { matchingFormat = TRUE; format = f; } } if (matchingFormat) { DbgLog((LOG_TRACE, 10, L"-> Found matching output format, finished setup with render target %d (%4.4S)", format, (const char *)&format)); *input = *mode->guid; *output = format; SAFE_CO_FREE(out_list); SAFE_CO_FREE(input_list); return S_OK; } SAFE_CO_FREE(out_list); } done: SAFE_CO_FREE(input_list); return E_FAIL; } HRESULT CDecDXVA2::InitD3DAdapterIdentifier(UINT lAdapter) { ASSERT(m_pD3D); D3DADAPTER_IDENTIFIER9 d3dai = {0}; HRESULT hr = m_pD3D->GetAdapterIdentifier(lAdapter, 0, &d3dai); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Querying of adapter identifier %d failed with hr: %X", lAdapter, hr)); return E_FAIL; } const char *vendor = "Unknown"; for (int i = 0; vendors[i].id != 0; i++) { if (vendors[i].id == d3dai.VendorId) { vendor = vendors[i].name; break; } } DbgLog((LOG_TRACE, 10, L"-> Running on adapter %d, %S, vendor 0x%04X(%S), device 0x%04X", lAdapter, d3dai.Description, d3dai.VendorId, vendor, d3dai.DeviceId)); m_dwVendorId = d3dai.VendorId; m_dwDeviceId = d3dai.DeviceId; return S_OK; } /** * This function is only called in non-native mode * Its responsibility is to initialize D3D, create a device and a device manager * and call SetD3DDeviceManager with it. */ HRESULT CDecDXVA2::InitD3D(UINT lAdapter) { HRESULT hr = S_OK; m_pD3D = Direct3DCreate9(D3D_SDK_VERSION); if (!m_pD3D) { DbgLog((LOG_ERROR, 10, L"-> Failed to acquire IDirect3D9")); return E_FAIL; } // populate the adapter identifier values hr = InitD3DAdapterIdentifier(lAdapter); // if the requested adapter failed, try again if (FAILED(hr) && lAdapter != D3DADAPTER_DEFAULT) { lAdapter = D3DADAPTER_DEFAULT; hr = InitD3DAdapterIdentifier(lAdapter); } if (FAILED(hr)) { return hr; } D3DPRESENT_PARAMETERS d3dpp = {0}; D3DDISPLAYMODE d3ddm = {0}; m_pD3D->GetAdapterDisplayMode(lAdapter, &d3ddm); d3dpp.Windowed = TRUE; d3dpp.BackBufferWidth = 640; d3dpp.BackBufferHeight = 480; d3dpp.BackBufferCount = 0; d3dpp.BackBufferFormat = d3ddm.Format; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.Flags = D3DPRESENTFLAG_VIDEO; hr = m_pD3D->CreateDevice(lAdapter, D3DDEVTYPE_HAL, GetShellWindow(), D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE, &d3dpp, &m_pD3DDev); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creation of device failed with hr: %X", hr)); return E_FAIL; } return S_OK; } HRESULT CDecDXVA2::InitD3DEx(UINT lAdapter) { HRESULT hr = S_OK; if (dx.direct3DCreate9Ex == nullptr) { DbgLog((LOG_ERROR, 10, L"-> Direct3DCreate9Ex not available")); return E_NOINTERFACE; } IDirect3D9Ex *pD3D9Ex = nullptr; hr = dx.direct3DCreate9Ex(D3D_SDK_VERSION, &pD3D9Ex); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> Failed to acquire IDirect3D9Ex")); return E_NOINTERFACE; } m_pD3D = dynamic_cast(pD3D9Ex); // populate the adapter identifier values hr = InitD3DAdapterIdentifier(lAdapter); // if the requested adapter failed, try again if (FAILED(hr) && lAdapter != D3DADAPTER_DEFAULT) { lAdapter = D3DADAPTER_DEFAULT; hr = InitD3DAdapterIdentifier(lAdapter); } if (FAILED(hr)) { SafeRelease(&m_pD3D); return hr; } D3DPRESENT_PARAMETERS d3dpp = {0}; D3DDISPLAYMODEEX d3ddm = {0}; d3ddm.Size = sizeof(D3DDISPLAYMODEEX); pD3D9Ex->GetAdapterDisplayModeEx(lAdapter, &d3ddm, NULL); d3dpp.Windowed = TRUE; d3dpp.BackBufferWidth = 640; d3dpp.BackBufferHeight = 480; d3dpp.BackBufferCount = 0; d3dpp.BackBufferFormat = d3ddm.Format; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.Flags = D3DPRESENTFLAG_VIDEO; IDirect3DDevice9Ex *pD3D9DeviceEx = nullptr; hr = pD3D9Ex->CreateDeviceEx(lAdapter, D3DDEVTYPE_HAL, GetShellWindow(), D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE, &d3dpp, NULL, &pD3D9DeviceEx); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creation of device failed with hr: %X", hr)); SafeRelease(&m_pD3D); return E_FAIL; } m_pD3DDev = dynamic_cast(pD3D9DeviceEx); return S_OK; } HRESULT CDecDXVA2::RetrieveVendorId(IDirect3DDeviceManager9 *pDevManager) { HANDLE hDevice = 0; IDirect3D9 *pD3D = nullptr; IDirect3DDevice9 *pDevice = nullptr; HRESULT hr = pDevManager->OpenDeviceHandle(&hDevice); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to open device handle with hr: %X", hr)); goto done; } hr = pDevManager->LockDevice(hDevice, &pDevice, TRUE); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to lock device with hr: %X", hr)); goto done; } hr = pDevice->GetDirect3D(&pD3D); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to get D3D object hr: %X", hr)); goto done; } D3DDEVICE_CREATION_PARAMETERS devParams; hr = pDevice->GetCreationParameters(&devParams); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to get device creation params hr: %X", hr)); goto done; } D3DADAPTER_IDENTIFIER9 adIdentifier; hr = pD3D->GetAdapterIdentifier(devParams.AdapterOrdinal, 0, &adIdentifier); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to get adapter identified hr: %X", hr)); goto done; } m_dwVendorId = adIdentifier.VendorId; m_dwDeviceId = adIdentifier.DeviceId; memcpy(m_cDeviceName, adIdentifier.Description, sizeof(m_cDeviceName)); done: SafeRelease(&pD3D); SafeRelease(&pDevice); if (hDevice && hDevice != INVALID_HANDLE_VALUE) { pDevManager->UnlockDevice(hDevice, FALSE); pDevManager->CloseDeviceHandle(hDevice); } return hr; } HRESULT CDecDXVA2::CheckHWCompatConditions(GUID decoderGuid) { if (m_dwSurfaceWidth == 0 || m_dwSurfaceHeight == 0) return E_UNEXPECTED; int width_mbs = m_dwSurfaceWidth / 16; int height_mbs = m_dwSurfaceHeight / 16; int max_ref_frames_dpb41 = min(11, 32768 / (width_mbs * height_mbs)); if (m_dwVendorId == VEND_ID_ATI) { if (IsAMDUVD(m_dwDeviceId)) { if (m_pAVCtx->codec_id == AV_CODEC_ID_H264 && m_pAVCtx->refs > max_ref_frames_dpb41) { DbgLog((LOG_TRACE, 10, L"-> Too many reference frames for AMD UVD/UVD+ H.264 decoder")); return E_FAIL; } else if ((m_pAVCtx->codec_id == AV_CODEC_ID_VC1 || m_pAVCtx->codec_id == AV_CODEC_ID_MPEG2VIDEO) && (m_dwSurfaceWidth > 1920 || m_dwSurfaceHeight > 1200)) { DbgLog((LOG_TRACE, 10, L"-> VC-1 Resolutions above FullHD are not supported by the UVD/UVD+ decoder")); return E_FAIL; } else if (m_pAVCtx->codec_id == AV_CODEC_ID_WMV3) { DbgLog((LOG_TRACE, 10, L"-> AMD UVD/UVD+ is currently not compatible with WMV3")); return E_FAIL; } } } else if (m_dwVendorId == VEND_ID_INTEL) { if (decoderGuid == DXVADDI_Intel_ModeH264_E && m_pAVCtx->codec_id == AV_CODEC_ID_H264 && m_pAVCtx->refs > max_ref_frames_dpb41) { DbgLog((LOG_TRACE, 10, L"-> Too many reference frames for Intel H.264 decoder implementation")); return E_FAIL; } } return S_OK; } /** * Called from both native and non-native mode * Initialize all the common DXVA2 interfaces and device handles */ HRESULT CDecDXVA2::SetD3DDeviceManager(IDirect3DDeviceManager9 *pDevManager) { HRESULT hr = S_OK; ASSERT(pDevManager); m_pD3DDevMngr = pDevManager; RetrieveVendorId(pDevManager); // This should really be null here, but since we're overwriting it, make sure its actually released SafeRelease(&m_pDXVADecoderService); hr = CreateDXVAVideoService(m_pD3DDevMngr, &m_pDXVADecoderService); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creation of DXVA2 Decoder Service failed with hr: %X", hr)); goto done; } // If the decoder was initialized already, check if we can use this device if (m_pAVCtx) { DbgLog((LOG_TRACE, 10, L"-> Checking hardware for format support...")); GUID input = GUID_NULL; D3DFORMAT output; hr = FindVideoServiceConversion(m_pAVCtx->codec_id, m_pAVCtx->profile, get_dxva_surface_format(m_pAVCtx), &input, &output); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> No decoder device available that can decode codec '%S' to a matching output", avcodec_get_name(m_pAVCtx->codec_id))); goto done; } m_eSurfaceFormat = output; if (FAILED(CheckHWCompatConditions(input))) { hr = E_FAIL; goto done; } DXVA2_VideoDesc desc; ZeroMemory(&desc, sizeof(desc)); desc.SampleWidth = m_dwSurfaceWidth; desc.SampleHeight = m_dwSurfaceHeight; desc.Format = output; DXVA2_ConfigPictureDecode config; hr = FindDecoderConfiguration(input, &desc, &config); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> No decoder configuration available for codec '%S'", avcodec_get_name(m_pAVCtx->codec_id))); goto done; } LPDIRECT3DSURFACE9 pSurfaces[DXVA2_MAX_SURFACES] = {0}; UINT numSurfaces = max(config.ConfigMinRenderTargetBuffCount, 1); hr = m_pDXVADecoderService->CreateSurface(m_dwSurfaceWidth, m_dwSurfaceHeight, numSurfaces, output, D3DPOOL_DEFAULT, 0, DXVA2_VideoDecoderRenderTarget, pSurfaces, nullptr); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creation of surfaces failed with hr: %X", hr)); goto done; } IDirectXVideoDecoder *decoder = nullptr; hr = m_pDXVADecoderService->CreateVideoDecoder(input, &desc, &config, pSurfaces, numSurfaces, &decoder); // Release resources, decoder and surfaces SafeRelease(&decoder); int i = DXVA2_MAX_SURFACES; while (i > 0) { SafeRelease(&pSurfaces[--i]); } if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creation of decoder failed with hr: %X", hr)); goto done; } } done: return hr; } // ILAVDecoder STDMETHODIMP CDecDXVA2::Init() { DbgLog((LOG_TRACE, 10, L"CDecDXVA2::Init(): Trying to open DXVA2 decoder")); HRESULT hr = S_OK; // Initialize all D3D interfaces in non-native mode if (!m_bNative) { // load DLLs and functions if (FAILED(hr = LoadDXVA2Functions())) { DbgLog((LOG_ERROR, 10, L"-> Failed to load DXVA2 DLL functions")); return E_FAIL; } // determin the adapter the user requested UINT lAdapter = m_pSettings->GetHWAccelDeviceIndex(HWAccel_DXVA2CopyBack, nullptr); if (lAdapter == LAVHWACCEL_DEVICE_DEFAULT) lAdapter = D3DADAPTER_DEFAULT; DWORD dwDeviceIndex = m_pCallback->GetGPUDeviceIndex(); if (dwDeviceIndex != DWORD_MAX) { lAdapter = (UINT)dwDeviceIndex; } // initialize D3D hr = InitD3DEx(lAdapter); if (hr == E_NOINTERFACE) { // D3D9Ex failed, try plain D3D hr = InitD3D(lAdapter); } if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> D3D Initialization failed with hr: %X", hr)); return hr; } // create device manager for the device hr = CreateD3DDeviceManager(m_pD3DDev, &m_pD3DResetToken, &m_pD3DDevMngr); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creation of Device manager failed with hr: %X", hr)); return E_FAIL; } // set it as the active device manager hr = SetD3DDeviceManager(m_pD3DDevMngr); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> SetD3DDeviceManager failed with hr: %X", hr)); return E_FAIL; } } // Init the ffmpeg parts // This is our main software decoder, unable to fail! CDecAvcodec::Init(); return S_OK; } STDMETHODIMP CDecDXVA2::InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) { HRESULT hr = S_OK; DbgLog((LOG_TRACE, 10, L"CDecDXVA2::InitDecoder(): Initializing DXVA2 decoder")); // Hack-ish check to avoid re-creating the full decoder when only the aspect ratio changes. // Re-creating the DXVA2 decoder can lead to issues like missing frames or a several second delay if (m_pDecoder) { CMediaType mediaTypeCheck = m_MediaType; if (mediaTypeCheck.formattype == FORMAT_VideoInfo2 && pmt->formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2 *vih2Old = (VIDEOINFOHEADER2 *)mediaTypeCheck.Format(); VIDEOINFOHEADER2 *vih2New = (VIDEOINFOHEADER2 *)pmt->Format(); vih2Old->dwPictAspectRatioX = vih2New->dwPictAspectRatioX; vih2Old->dwPictAspectRatioY = vih2New->dwPictAspectRatioY; if (mediaTypeCheck == *pmt) { DbgLog((LOG_TRACE, 10, L"-> Skipping re-init because media type is unchanged.")); m_MediaType = *pmt; // flush the decoder so we can resume decoding properly (before a re-init, EndOfStream would be called, // making this necessary) avcodec_flush_buffers(m_pAVCtx); return S_OK; } } } DestroyDecoder(false); m_DisplayDelay = DXVA2_QUEUE_SURFACES; // Intel GPUs don't like the display and performance goes way down, so disable it. if (m_dwVendorId == VEND_ID_INTEL) m_DisplayDelay = 0; // Reduce display delay for DVD decoding for lower decode latency if (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) m_DisplayDelay /= 2; m_bFailHWDecode = FALSE; DbgLog((LOG_TRACE, 10, L"-> Creation of DXVA2 decoder successful, initializing ffmpeg")); hr = CDecAvcodec::InitDecoder(codec, pmt, pSideData); if (FAILED(hr)) { return hr; } if (check_dxva_codec_profile(m_pAVCtx, AV_PIX_FMT_DXVA2_VLD)) { DbgLog((LOG_TRACE, 10, L"-> Incompatible profile detected, falling back to software decoding")); return E_FAIL; } // If we have a DXVA Decoder, check if its capable // If we don't have one yet, it may be handed to us later, and compat is checked at that point GUID input = GUID_NULL; D3DFORMAT output = D3DFMT_UNKNOWN; if (m_pDXVADecoderService) { hr = FindVideoServiceConversion(codec, m_pAVCtx->profile, get_dxva_surface_format(m_pAVCtx), &input, &output); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> No decoder device available that can decode codec '%S' to a matching output", avcodec_get_name(codec))); return E_FAIL; } } else { output = get_dxva_surface_format(m_pAVCtx); } m_dwSurfaceWidth = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_width); m_dwSurfaceHeight = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_height); m_eSurfaceFormat = output; m_DecoderPixelFormat = m_pAVCtx->sw_pix_fmt; if (FAILED(CheckHWCompatConditions(input))) { return E_FAIL; } m_MediaType = *pmt; return S_OK; } STDMETHODIMP_(long) CDecDXVA2::GetBufferCount(long *pMaxBuffers) { long buffers = 0; // Native decoding should use 16 buffers to enable seamless codec changes if (m_bNative) buffers = 16; else { // Buffers based on max ref frames if (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_HEVC) buffers = 16; else if (m_nCodecId == AV_CODEC_ID_VP9 || m_nCodecId == AV_CODEC_ID_AV1) buffers = 8; else buffers = 2; } // 4 extra buffers for handling and safety buffers += 4; if (!m_bNative) { buffers += m_DisplayDelay; } if (m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_DVD) { buffers += 4; } if (pMaxBuffers) { // cap at 127, because it needs to fit into the 7-bit DXVA structs *pMaxBuffers = 127; // VC-1 and VP9 decoding has stricter requirements (decoding flickers otherwise) if (m_nCodecId == AV_CODEC_ID_VC1 || m_nCodecId == AV_CODEC_ID_VP9 || m_nCodecId == AV_CODEC_ID_AV1) *pMaxBuffers = 32; } return buffers; } HRESULT CDecDXVA2::FindDecoderConfiguration(const GUID &input, const DXVA2_VideoDesc *pDesc, DXVA2_ConfigPictureDecode *pConfig) { CheckPointer(pConfig, E_INVALIDARG); CheckPointer(pDesc, E_INVALIDARG); HRESULT hr = S_OK; UINT cfg_count = 0; DXVA2_ConfigPictureDecode *cfg_list = nullptr; hr = m_pDXVADecoderService->GetDecoderConfigurations(input, pDesc, nullptr, &cfg_count, &cfg_list); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> GetDecoderConfigurations failed with hr: %X", hr)); return E_FAIL; } DbgLog((LOG_TRACE, 10, L"-> We got %d decoder configurations", cfg_count)); int best_score = -1; DXVA2_ConfigPictureDecode best_cfg; for (unsigned i = 0; i < cfg_count; i++) { DXVA2_ConfigPictureDecode *cfg = &cfg_list[i]; DbgLog((LOG_ERROR, 10, "-> Configuration Record %d: ConfigBitstreamRaw = %d", i, cfg->ConfigBitstreamRaw)); int score; if (cfg->ConfigBitstreamRaw == 1) score = 1; else if (m_pAVCtx->codec_id == AV_CODEC_ID_H264 && cfg->ConfigBitstreamRaw == 2) score = 2; else if (m_pAVCtx->codec_id == AV_CODEC_ID_VP9) // hack for broken AMD drivers score = 0; else continue; if (IsEqualGUID(cfg->guidConfigBitstreamEncryption, DXVA2_NoEncrypt)) score += 16; if (score > best_score) { best_score = score; best_cfg = *cfg; } } SAFE_CO_FREE(cfg_list); if (best_score < 0) { DbgLog((LOG_TRACE, 10, L"-> No matching configuration available")); return E_FAIL; } *pConfig = best_cfg; return S_OK; } HRESULT CDecDXVA2::CreateDXVA2Decoder(int nSurfaces, IDirect3DSurface9 **ppSurfaces) { DbgLog((LOG_TRACE, 10, L"-> CDecDXVA2::CreateDXVA2Decoder")); HRESULT hr = S_OK; LPDIRECT3DSURFACE9 pSurfaces[DXVA2_MAX_SURFACES]; if (!m_pDXVADecoderService) return E_FAIL; DestroyDecoder(false, true); GUID input = GUID_NULL; D3DFORMAT output; FindVideoServiceConversion(m_pAVCtx->codec_id, m_pAVCtx->profile, get_dxva_surface_format(m_pAVCtx),&input, &output); if (!nSurfaces) { m_dwSurfaceWidth = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_width); m_dwSurfaceHeight = dxva_align_dimensions(m_pAVCtx->codec_id, m_pAVCtx->coded_height); m_eSurfaceFormat = output; m_DecoderPixelFormat = m_pAVCtx->sw_pix_fmt; m_NumSurfaces = GetBufferCount(); hr = m_pDXVADecoderService->CreateSurface(m_dwSurfaceWidth, m_dwSurfaceHeight, m_NumSurfaces - 1, output, D3DPOOL_DEFAULT, 0, DXVA2_VideoDecoderRenderTarget, pSurfaces, nullptr); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Creation of surfaces failed with hr: %X", hr)); m_NumSurfaces = 0; return E_FAIL; } ppSurfaces = pSurfaces; } else { m_NumSurfaces = nSurfaces; for (int i = 0; i < m_NumSurfaces; i++) { ppSurfaces[i]->AddRef(); } } if (m_NumSurfaces <= 0) { DbgLog((LOG_TRACE, 10, L"-> No surfaces? No good!")); return E_FAIL; } // get the device, for ColorFill() to init the surfaces in black IDirect3DDevice9 *pDev = nullptr; ppSurfaces[0]->GetDevice(&pDev); for (int i = 0; i < m_NumSurfaces; i++) { m_pSurfaces[i].index = i; m_pSurfaces[i].d3d = ppSurfaces[i]; m_pSurfaces[i].age = UINT64_MAX; m_pSurfaces[i].used = false; // fill the surface in black, to avoid the "green screen" in case the first frame fails to decode. if (pDev) pDev->ColorFill(ppSurfaces[i], NULL, D3DCOLOR_XYUV(0, 128, 128)); } // and done with the device SafeRelease(&pDev); DbgLog((LOG_TRACE, 10, L"-> Successfully created %d surfaces (%dx%d)", m_NumSurfaces, m_dwSurfaceWidth, m_dwSurfaceHeight)); DXVA2_VideoDesc desc; ZeroMemory(&desc, sizeof(desc)); desc.SampleWidth = m_dwSurfaceWidth; desc.SampleHeight = m_dwSurfaceHeight; desc.Format = output; hr = FindDecoderConfiguration(input, &desc, &m_DXVAVideoDecoderConfig); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> FindDecoderConfiguration failed with hr: %X", hr)); return hr; } IDirectXVideoDecoder *decoder = nullptr; hr = m_pDXVADecoderService->CreateVideoDecoder(input, &desc, &m_DXVAVideoDecoderConfig, ppSurfaces, m_NumSurfaces, &decoder); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> CreateVideoDecoder failed with hr: %X", hr)); return E_FAIL; } m_pDecoder = decoder; m_guidDecoderDevice = input; /* fill hwaccel_context */ FillHWContext((dxva_context *)m_pAVCtx->hwaccel_context); memset(m_pRawSurface, 0, sizeof(m_pRawSurface)); for (int i = 0; i < m_NumSurfaces; i++) { m_pRawSurface[i] = m_pSurfaces[i].d3d; } return S_OK; } HRESULT CDecDXVA2::FillHWContext(dxva_context *ctx) { ctx->cfg = &m_DXVAVideoDecoderConfig; ctx->decoder = m_pDecoder; ctx->surface = m_pRawSurface; ctx->surface_count = m_NumSurfaces; if (m_dwVendorId == VEND_ID_INTEL && m_guidDecoderDevice == DXVADDI_Intel_ModeH264_E) ctx->workaround = FF_DXVA2_WORKAROUND_INTEL_CLEARVIDEO; else if (m_dwVendorId == VEND_ID_ATI && IsAMDUVD(m_dwDeviceId)) ctx->workaround = FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG; else ctx->workaround = 0; return S_OK; } enum AVPixelFormat CDecDXVA2::get_dxva2_format(struct AVCodecContext *c, const enum AVPixelFormat *pix_fmts) { CDecDXVA2 *pDec = (CDecDXVA2 *)c->opaque; const enum AVPixelFormat *p; for (p = pix_fmts; *p != -1; p++) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p); if (!desc || !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) break; if (*p == AV_PIX_FMT_DXVA2_VLD) { HRESULT hr = pDec->ReInitDXVA2Decoder(c); if (FAILED(hr)) { pDec->m_bFailHWDecode = TRUE; continue; } else { break; } } } return *p; } typedef struct SurfaceWrapper { LPDIRECT3DSURFACE9 surface; IMediaSample *sample; CDecDXVA2 *pDec; IDirectXVideoDecoder *pDXDecoder; } SurfaceWrapper; void CDecDXVA2::free_dxva2_buffer(void *opaque, uint8_t *data) { SurfaceWrapper *sw = (SurfaceWrapper *)opaque; CDecDXVA2 *pDec = sw->pDec; LPDIRECT3DSURFACE9 pSurface = sw->surface; for (int i = 0; i < pDec->m_NumSurfaces; i++) { if (pDec->m_pSurfaces[i].d3d == pSurface) { pDec->m_pSurfaces[i].used = false; break; } } SafeRelease(&pSurface); SafeRelease(&sw->pDXDecoder); SafeRelease(&sw->sample); delete sw; } HRESULT CDecDXVA2::ReInitDXVA2Decoder(AVCodecContext *c) { HRESULT hr = S_OK; // Don't allow decoder creation during first init if (m_bInInit) return S_FALSE; if (!m_pDecoder || dxva_align_dimensions(c->codec_id, c->coded_width) != m_dwSurfaceWidth || dxva_align_dimensions(c->codec_id, c->coded_height) != m_dwSurfaceHeight || m_DecoderPixelFormat != c->sw_pix_fmt) { DbgLog((LOG_TRACE, 10, L"No DXVA2 Decoder or image dimensions changed -> Re-Allocating resources")); if (!m_pDecoder && m_bNative && !m_pDXVA2Allocator) { ASSERT(0); hr = E_FAIL; } else if (m_bNative) { // shortcut to update only the Decoder Pixel Format if needed if (m_pDecoder && m_DecoderPixelFormat == AV_PIX_FMT_NONE && m_DecoderPixelFormat != c->sw_pix_fmt) { GUID input; D3DFORMAT output; FindVideoServiceConversion(c->codec_id, c->profile, get_dxva_surface_format(m_pAVCtx), &input, &output); if (output == m_eSurfaceFormat) { m_DecoderPixelFormat = c->sw_pix_fmt; return ReInitDXVA2Decoder(c); } } avcodec_flush_buffers(c); m_dwSurfaceWidth = dxva_align_dimensions(c->codec_id, c->coded_width); m_dwSurfaceHeight = dxva_align_dimensions(c->codec_id, c->coded_height); m_DecoderPixelFormat = c->sw_pix_fmt; GUID input; FindVideoServiceConversion(c->codec_id, c->profile, get_dxva_surface_format(m_pAVCtx), &input, &m_eSurfaceFormat); // Re-Commit the allocator (creates surfaces and new decoder) hr = m_pDXVA2Allocator->Decommit(); if (m_pDXVA2Allocator->DecommitInProgress()) { DbgLog((LOG_TRACE, 10, L"WARNING! DXVA2 Allocator is still busy, trying to flush downstream")); m_pCallback->ReleaseAllDXVAResources(); m_pCallback->GetOutputPin()->GetConnected()->BeginFlush(); m_pCallback->GetOutputPin()->GetConnected()->EndFlush(); if (m_pDXVA2Allocator->DecommitInProgress()) { DbgLog( (LOG_TRACE, 10, L"WARNING! Flush had no effect, decommit of the allocator still not complete")); } else { DbgLog((LOG_TRACE, 10, L"Flush was successful, decommit completed!")); } } hr = m_pDXVA2Allocator->Commit(); } else if (!m_bNative) { FlushDisplayQueue(TRUE); hr = CreateDXVA2Decoder(); } } return hr; } int CDecDXVA2::get_dxva2_buffer(struct AVCodecContext *c, AVFrame *pic, int flags) { CDecDXVA2 *pDec = (CDecDXVA2 *)c->opaque; IMediaSample *pSample = nullptr; HRESULT hr = S_OK; if (pic->format != AV_PIX_FMT_DXVA2_VLD || (c->codec_id == AV_CODEC_ID_H264 && !H264_CHECK_PROFILE(c->profile)) || (c->codec_id == AV_CODEC_ID_HEVC && !HEVC_CHECK_PROFILE(c->profile)) || (c->codec_id == AV_CODEC_ID_VP9 && !VP9_CHECK_PROFILE(c->profile))) { DbgLog((LOG_ERROR, 10, L"DXVA2 buffer request, but not dxva2 pixfmt or unsupported profile")); pDec->m_bFailHWDecode = TRUE; return -1; } hr = pDec->ReInitDXVA2Decoder(c); if (FAILED(hr)) { pDec->m_bFailHWDecode = TRUE; return -1; } if (FAILED(pDec->m_pD3DDevMngr->TestDevice(pDec->m_hDevice))) { DbgLog((LOG_ERROR, 10, L"Device Lost")); } int i; if (pDec->m_bNative) { if (!pDec->m_pDXVA2Allocator) return -1; hr = pDec->m_pDXVA2Allocator->GetBuffer(&pSample, nullptr, nullptr, 0); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"DXVA2Allocator returned error, hr: 0x%x", hr)); return -1; } ILAVDXVA2Sample *pLavDXVA2 = nullptr; hr = pSample->QueryInterface(&pLavDXVA2); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"Sample is no LAV DXVA2 sample?????")); SafeRelease(&pSample); return -1; } i = pLavDXVA2->GetDXSurfaceId(); SafeRelease(&pLavDXVA2); } else { int old, old_unused; for (i = 0, old = 0, old_unused = -1; i < pDec->m_NumSurfaces; i++) { d3d_surface_t *surface = &pDec->m_pSurfaces[i]; if (!surface->used && (old_unused == -1 || surface->age < pDec->m_pSurfaces[old_unused].age)) old_unused = i; if (surface->age < pDec->m_pSurfaces[old].age) old = i; } if (old_unused == -1) { DbgLog((LOG_TRACE, 10, L"No free surface, using oldest")); i = old; } else { i = old_unused; } } LPDIRECT3DSURFACE9 pSurface = pDec->m_pSurfaces[i].d3d; if (!pSurface) { DbgLog((LOG_ERROR, 10, L"There is a sample, but no D3D Surace? WTF?")); SafeRelease(&pSample); return -1; } pDec->m_pSurfaces[i].age = pDec->m_CurrentSurfaceAge++; pDec->m_pSurfaces[i].used = true; memset(pic->data, 0, sizeof(pic->data)); memset(pic->linesize, 0, sizeof(pic->linesize)); memset(pic->buf, 0, sizeof(pic->buf)); pic->data[0] = pic->data[3] = (uint8_t *)pSurface; pic->data[4] = (uint8_t *)pSample; SurfaceWrapper *surfaceWrapper = new SurfaceWrapper(); surfaceWrapper->pDec = pDec; surfaceWrapper->sample = pSample; surfaceWrapper->surface = pSurface; surfaceWrapper->surface->AddRef(); surfaceWrapper->pDXDecoder = pDec->m_pDecoder; surfaceWrapper->pDXDecoder->AddRef(); pic->buf[0] = av_buffer_create(nullptr, 0, free_dxva2_buffer, surfaceWrapper, 0); return 0; } HRESULT CDecDXVA2::AdditionaDecoderInit() { /* Create ffmpeg dxva_context, but only fill it if we have a decoder already. */ dxva_context *ctx = (dxva_context *)av_mallocz(sizeof(dxva_context)); if (m_pDecoder) { FillHWContext(ctx); } m_pAVCtx->thread_count = 1; m_pAVCtx->thread_type = 0; m_pAVCtx->hwaccel_context = ctx; m_pAVCtx->get_format = get_dxva2_format; m_pAVCtx->get_buffer2 = get_dxva2_buffer; m_pAVCtx->opaque = this; m_pAVCtx->slice_flags |= SLICE_FLAG_ALLOW_FIELD; // disable error conealment in hwaccel mode, it doesn't work either way m_pAVCtx->error_concealment = 0; av_opt_set_int(m_pAVCtx, "enable_er", 0, AV_OPT_SEARCH_CHILDREN); return S_OK; } HRESULT CDecDXVA2::PostDecode() { if (m_bFailHWDecode) { DbgLog((LOG_TRACE, 10, L"::PostDecode(): HW Decoder failed, falling back to software decoding")); return E_FAIL; } return S_OK; } STDMETHODIMP CDecDXVA2::FlushFromAllocator() { if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) avcodec_flush_buffers(m_pAVCtx); FlushDisplayQueue(FALSE); return S_OK; } STDMETHODIMP CDecDXVA2::Flush() { CDecAvcodec::Flush(); FlushDisplayQueue(FALSE); #ifdef DEBUG int used = 0; for (int i = 0; i < m_NumSurfaces; i++) { d3d_surface_t *s = &m_pSurfaces[i]; if (s->used) { used++; } } if (used > 0) { DbgLog((LOG_TRACE, 10, L"WARNING! %d frames still in use after flush", used)); } #endif // This solves an issue with corruption after seeks on AMD systems, see JIRA LAV-5 if (m_dwVendorId == VEND_ID_ATI && m_nCodecId == AV_CODEC_ID_H264 && m_pDecoder) { if (m_bNative && m_pDXVA2Allocator) { // The allocator needs to be locked because flushes can happen async to other graph events // and in the worst case the allocator is decommited while we're using it. CAutoLock allocatorLock(m_pDXVA2Allocator); if (m_pDXVA2Allocator->IsCommited()) CreateDXVA2Decoder(m_NumSurfaces, m_pRawSurface); } else if (!m_bNative) CreateDXVA2Decoder(); } return S_OK; } STDMETHODIMP CDecDXVA2::FlushDisplayQueue(BOOL bDeliver) { for (int i = 0; i < m_DisplayDelay; ++i) { if (m_FrameQueue[m_FrameQueuePosition]) { if (bDeliver) { DeliverDXVA2Frame(m_FrameQueue[m_FrameQueuePosition]); m_FrameQueue[m_FrameQueuePosition] = nullptr; } else { ReleaseFrame(&m_FrameQueue[m_FrameQueuePosition]); } } m_FrameQueuePosition = (m_FrameQueuePosition + 1) % m_DisplayDelay; } return S_OK; } STDMETHODIMP CDecDXVA2::EndOfStream() { CDecAvcodec::EndOfStream(); // Flush display queue FlushDisplayQueue(TRUE); return S_OK; } HRESULT CDecDXVA2::HandleDXVA2Frame(LAVFrame *pFrame) { if (pFrame->flags & LAV_FRAME_FLAG_FLUSH) { if (!m_bNative) { FlushDisplayQueue(TRUE); } Deliver(pFrame); return S_OK; } if (m_bNative || m_DisplayDelay == 0) { DeliverDXVA2Frame(pFrame); } else { LAVFrame *pQueuedFrame = m_FrameQueue[m_FrameQueuePosition]; m_FrameQueue[m_FrameQueuePosition] = pFrame; m_FrameQueuePosition = (m_FrameQueuePosition + 1) % m_DisplayDelay; if (pQueuedFrame) { DeliverDXVA2Frame(pQueuedFrame); } } return S_OK; } HRESULT CDecDXVA2::DeliverDXVA2Frame(LAVFrame *pFrame) { if (m_bNative) { if (!pFrame->data[0] || !pFrame->data[3]) { DbgLog((LOG_ERROR, 10, L"No sample or surface for DXVA2 frame?!?!")); ReleaseFrame(&pFrame); return S_FALSE; } GetPixelFormat(&pFrame->format, &pFrame->bpp, &pFrame->sw_format); Deliver(pFrame); } else { if (m_bDirect) { DeliverDirect(pFrame); } else { if (CopyFrame(pFrame)) Deliver(pFrame); else ReleaseFrame(&pFrame); } } return S_OK; } STDMETHODIMP CDecDXVA2::GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { // Output is always NV12 or P010 if (pPix) { if (m_bNative) *pPix = LAVPixFmt_DXVA2; else *pPix = (m_eSurfaceFormat == FOURCC_P010 || m_eSurfaceFormat == FOURCC_P016) ? LAVPixFmt_P016 : LAVPixFmt_NV12; } if (pBpp) *pBpp = (m_eSurfaceFormat == FOURCC_P016) ? 16 : ((m_eSurfaceFormat == FOURCC_P010) ? 10 : 8); if (pPixSoftware) *pPixSoftware = (m_eSurfaceFormat == FOURCC_P010 || m_eSurfaceFormat == FOURCC_P016) ? LAVPixFmt_P016 : LAVPixFmt_NV12; return S_OK; } __forceinline bool CDecDXVA2::CopyFrame(LAVFrame *pFrame) { HRESULT hr; LPDIRECT3DSURFACE9 pSurface = (LPDIRECT3DSURFACE9)pFrame->data[3]; GetPixelFormat(&pFrame->format, &pFrame->bpp, &pFrame->sw_format); D3DSURFACE_DESC surfaceDesc; pSurface->GetDesc(&surfaceDesc); D3DLOCKED_RECT LockedRect; hr = pSurface->LockRect(&LockedRect, nullptr, D3DLOCK_READONLY); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"pSurface->LockRect failed (hr: %X)", hr)); return false; } // Store AVFrame-based buffers, and reset pFrame LAVFrame tmpFrame = *pFrame; pFrame->destruct = nullptr; pFrame->priv_data = nullptr; // side-data shall not be copied to tmpFrame tmpFrame.side_data = nullptr; tmpFrame.side_data_count = 0; // Allocate memory buffers hr = AllocLAVFrameBuffers(pFrame, (pFrame->format == LAVPixFmt_P016) ? (LockedRect.Pitch >> 1) : LockedRect.Pitch); if (FAILED(hr)) { pSurface->UnlockRect(); *pFrame = tmpFrame; return false; } // Copy surface onto memory buffers const uint8_t *src[4] = {(const uint8_t *)LockedRect.pBits, ((const uint8_t *)LockedRect.pBits) + (LockedRect.Pitch * surfaceDesc.Height), 0, 0}; const ptrdiff_t src_pitch[4] = {LockedRect.Pitch, LockedRect.Pitch, 0, 0}; av_image_copy_uc_from(pFrame->data, pFrame->stride, src, src_pitch, (pFrame->format == LAVPixFmt_P016) ? AV_PIX_FMT_P010 : AV_PIX_FMT_NV12, pFrame->width, pFrame->height); pSurface->UnlockRect(); // Free AVFrame based buffers, now that we're done FreeLAVFrameBuffers(&tmpFrame); return true; } static bool direct_lock(LAVFrame *pFrame, LAVDirectBuffer *pBuffer) { ASSERT(pFrame && pBuffer); HRESULT hr; LPDIRECT3DSURFACE9 pSurface = (LPDIRECT3DSURFACE9)pFrame->data[3]; D3DSURFACE_DESC surfaceDesc; pSurface->GetDesc(&surfaceDesc); D3DLOCKED_RECT LockedRect; hr = pSurface->LockRect(&LockedRect, nullptr, D3DLOCK_READONLY); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"pSurface->LockRect failed (hr: %X)", hr)); return false; } memset(pBuffer, 0, sizeof(*pBuffer)); pBuffer->Width = surfaceDesc.Width; pBuffer->Height = surfaceDesc.Height; pBuffer->data[0] = (BYTE *)LockedRect.pBits; pBuffer->data[1] = pBuffer->data[0] + surfaceDesc.Height * LockedRect.Pitch; pBuffer->stride[0] = LockedRect.Pitch; pBuffer->stride[1] = LockedRect.Pitch; return true; } static void direct_unlock(LAVFrame *pFrame) { ASSERT(pFrame); LPDIRECT3DSURFACE9 pSurface = (LPDIRECT3DSURFACE9)pFrame->data[3]; pSurface->UnlockRect(); } bool CDecDXVA2::DeliverDirect(LAVFrame *pFrame) { GetPixelFormat(&pFrame->format, &pFrame->bpp, &pFrame->sw_format); pFrame->direct = true; pFrame->direct_lock = direct_lock; pFrame->direct_unlock = direct_unlock; Deliver(pFrame); return true; } STDMETHODIMP_(DWORD) CDecDXVA2::GetHWAccelNumDevices() { if (m_bNative) return 0; if (!m_pD3D) return 0; return m_pD3D->GetAdapterCount(); } STDMETHODIMP CDecDXVA2::GetHWAccelDeviceInfo(DWORD dwIndex, BSTR *pstrDeviceName, DWORD *dwDeviceIdentifier) { if (m_bNative) return E_UNEXPECTED; if (!m_pD3D) return E_NOINTERFACE; D3DADAPTER_IDENTIFIER9 d3dai = {0}; HRESULT err = m_pD3D->GetAdapterIdentifier(dwIndex, 0, &d3dai); if (err != D3D_OK) return E_INVALIDARG; if (pstrDeviceName) { int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, d3dai.Description, -1, nullptr, 0); if (len == 0) return E_FAIL; *pstrDeviceName = SysAllocStringLen(nullptr, len); MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, d3dai.Description, -1, *pstrDeviceName, len); } if (dwDeviceIdentifier) *dwDeviceIdentifier = d3dai.DeviceId; return S_OK; } STDMETHODIMP CDecDXVA2::GetHWAccelActiveDevice(BSTR *pstrDeviceName) { CheckPointer(pstrDeviceName, E_POINTER); if (strlen(m_cDeviceName) == 0) return E_UNEXPECTED; int len = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, m_cDeviceName, -1, nullptr, 0); if (len == 0) return E_FAIL; *pstrDeviceName = SysAllocStringLen(nullptr, len); MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, m_cDeviceName, -1, *pstrDeviceName, len); return S_OK; } ================================================ FILE: decoder/LAVVideo/decoders/dxva2dec.h ================================================ /* * Copyright (C) 2011-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DecBase.h" #include "avcodec.h" #include "libavcodec/dxva2.h" #define DXVA2_MAX_SURFACES 64 #define DXVA2_QUEUE_SURFACES 4 typedef HRESULT WINAPI pDirect3DCreate9Ex(UINT, IDirect3D9Ex **); typedef HRESULT WINAPI pCreateDeviceManager9(UINT *pResetToken, IDirect3DDeviceManager9 **); typedef struct { int index; bool used; LPDIRECT3DSURFACE9 d3d; uint64_t age; } d3d_surface_t; class CDXVA2SurfaceAllocator; class CDecDXVA2 : public CDecAvcodec { public: CDecDXVA2(void); virtual ~CDecDXVA2(void); // ILAVDecoder STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); STDMETHODIMP InitAllocator(IMemAllocator **ppAlloc); STDMETHODIMP PostConnect(IPin *pPin); STDMETHODIMP_(long) GetBufferCount(long *pMaxBuffers = nullptr); STDMETHODIMP_(const WCHAR *) GetDecoderName() { return m_bNative ? L"dxva2n" : (m_bDirect ? L"dxva2cb direct" : L"dxva2cb"); } STDMETHODIMP HasThreadSafeBuffers() { return m_bNative ? S_FALSE : S_OK; } STDMETHODIMP SetDirectOutput(BOOL bDirect) { m_bDirect = bDirect; return S_OK; } STDMETHODIMP_(DWORD) GetHWAccelNumDevices(); STDMETHODIMP GetHWAccelDeviceInfo(DWORD dwIndex, BSTR *pstrDeviceName, DWORD *dwDeviceIdentifier); STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName); // CDecBase STDMETHODIMP Init(); HRESULT SetNativeMode(BOOL bNative) { m_bNative = bNative; return S_OK; } protected: HRESULT AdditionaDecoderInit(); HRESULT PostDecode(); HRESULT HandleDXVA2Frame(LAVFrame *pFrame); HRESULT DeliverDXVA2Frame(LAVFrame *pFrame); BOOL IsHardwareAccelerator() { return TRUE; } bool CopyFrame(LAVFrame *pFrame); bool DeliverDirect(LAVFrame *pFrame); private: HRESULT InitD3D(UINT lAdapter); HRESULT InitD3DEx(UINT lAdapter); HRESULT InitD3DAdapterIdentifier(UINT lAdapter); STDMETHODIMP DestroyDecoder(bool bFull, bool bNoAVCodec = false); STDMETHODIMP FreeD3DResources(); STDMETHODIMP LoadDXVA2Functions(); HRESULT CreateD3DDeviceManager(IDirect3DDevice9 *pDevice, UINT *pReset, IDirect3DDeviceManager9 **ppManager); HRESULT CreateDXVAVideoService(IDirect3DDeviceManager9 *pManager, IDirectXVideoDecoderService **ppService); HRESULT FindVideoServiceConversion(AVCodecID codec, int profile, D3DFORMAT suggestedOutput, GUID *input, D3DFORMAT *output); HRESULT FindDecoderConfiguration(const GUID &input, const DXVA2_VideoDesc *pDesc, DXVA2_ConfigPictureDecode *pConfig); HRESULT CreateDXVA2Decoder(int nSurfaces = 0, IDirect3DSurface9 **ppSurfaces = nullptr); HRESULT SetD3DDeviceManager(IDirect3DDeviceManager9 *pDevManager); HRESULT DXVA2NotifyEVR(); HRESULT RetrieveVendorId(IDirect3DDeviceManager9 *pDevManager); HRESULT CheckHWCompatConditions(GUID decoderGuid); HRESULT FillHWContext(dxva_context *ctx); HRESULT ReInitDXVA2Decoder(AVCodecContext *c); static enum AVPixelFormat get_dxva2_format(struct AVCodecContext *s, const enum AVPixelFormat *pix_fmts); static int get_dxva2_buffer(struct AVCodecContext *c, AVFrame *pic, int flags); static void free_dxva2_buffer(void *opaque, uint8_t *data); STDMETHODIMP FlushDisplayQueue(BOOL bDeliver); STDMETHODIMP FlushFromAllocator(); private: friend class CDXVA2SurfaceAllocator; BOOL m_bNative = FALSE; BOOL m_bDirect = FALSE; CDXVA2SurfaceAllocator *m_pDXVA2Allocator = nullptr; struct { HMODULE d3dlib; pDirect3DCreate9Ex *direct3DCreate9Ex; HMODULE dxva2lib; pCreateDeviceManager9 *createDeviceManager; } dx; IDirect3D9 *m_pD3D = nullptr; IDirect3DDevice9 *m_pD3DDev = nullptr; IDirect3DDeviceManager9 *m_pD3DDevMngr = nullptr; UINT m_pD3DResetToken = 0; HANDLE m_hDevice = INVALID_HANDLE_VALUE; IDirectXVideoDecoderService *m_pDXVADecoderService = nullptr; IDirectXVideoDecoder *m_pDecoder = nullptr; DXVA2_ConfigPictureDecode m_DXVAVideoDecoderConfig; int m_NumSurfaces = 0; d3d_surface_t m_pSurfaces[DXVA2_MAX_SURFACES]; uint64_t m_CurrentSurfaceAge = 1; LPDIRECT3DSURFACE9 m_pRawSurface[DXVA2_MAX_SURFACES]; BOOL m_bFailHWDecode = FALSE; LAVFrame *m_FrameQueue[DXVA2_QUEUE_SURFACES]; int m_FrameQueuePosition = 0; AVPixelFormat m_DecoderPixelFormat = AV_PIX_FMT_NONE; DWORD m_dwSurfaceWidth = 0; DWORD m_dwSurfaceHeight = 0; D3DFORMAT m_eSurfaceFormat = D3DFMT_UNKNOWN; DWORD m_dwVendorId = 0; DWORD m_dwDeviceId = 0; char m_cDeviceName[512] = {0}; GUID m_guidDecoderDevice = GUID_NULL; int m_DisplayDelay = DXVA2_QUEUE_SURFACES; CMediaType m_MediaType; }; ================================================ FILE: decoder/LAVVideo/decoders/msdk_mvc.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "msdk_mvc.h" #include "moreuuids.h" #include "ByteParser.h" #include "H264Nalu.h" //////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////// ILAVDecoder *CreateDecoderMSDKMVC() { return new CDecMSDKMVC(); } //////////////////////////////////////////////////////////////////////////////// // Bitstream buffering //////////////////////////////////////////////////////////////////////////////// class CBitstreamBuffer { public: CBitstreamBuffer(GrowableArray *arrStorage) : m_pStorage(arrStorage) { } ~CBitstreamBuffer() { ASSERT(m_nConsumed <= m_pStorage->GetCount()); if (m_nConsumed < m_pStorage->GetCount()) { BYTE *p = m_pStorage->Ptr(); memmove(p, p + m_nConsumed, m_pStorage->GetCount() - m_nConsumed); m_pStorage->SetSize(DWORD(m_pStorage->GetCount() - m_nConsumed)); } else { m_pStorage->Clear(); } } void Allocate(size_t size) { m_pStorage->Allocate((DWORD)size); } void Append(const BYTE *buffer, size_t size) { m_pStorage->Append(buffer, DWORD(size)); } void Consume(size_t count) { m_nConsumed += min(count, GetBufferSize()); } void Clear() { m_nConsumed += GetBufferSize(); } BYTE *GetBuffer() { return m_pStorage->Ptr() + m_nConsumed; } size_t GetBufferSize() { return m_pStorage->GetCount() - m_nConsumed; } private: GrowableArray *m_pStorage = nullptr; size_t m_nConsumed = 0; }; //////////////////////////////////////////////////////////////////////////////// // MSDK MVC decoder implementation //////////////////////////////////////////////////////////////////////////////// CDecMSDKMVC::CDecMSDKMVC() { } CDecMSDKMVC::~CDecMSDKMVC() { DestroyDecoder(true); } STDMETHODIMP CDecMSDKMVC::Init() { mfxIMPL impls[] = {MFX_IMPL_AUTO_ANY, MFX_IMPL_SOFTWARE}; mfxVersion version = {8, 1}; // Check if HWAccel is allowed if (!m_pSettings->GetHWAccelCodec(HWCodec_H264MVC)) impls[0] = MFX_IMPL_SOFTWARE; for (int i = 0; i < countof(impls); i++) { mfxStatus sts = MFXInit(impls[i], &version, &m_mfxSession); if (sts != MFX_ERR_NONE) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Init(): MSDK not available")); return E_NOINTERFACE; } // query actual API version MFXQueryVersion(m_mfxSession, &m_mfxVersion); mfxIMPL impl = 0; MFXQueryIMPL(m_mfxSession, &impl); DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Init(): MSDK Initialized, version %d.%d, impl 0x%04x", m_mfxVersion.Major, m_mfxVersion.Minor, impl)); if ((impl & MFX_IMPL_VIA_MASK) == MFX_IMPL_VIA_D3D11 && !IsWindows8OrNewer()) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Init(): Skipping D3D11 acceleration on pre-Windows 8 system")); MFXClose(m_mfxSession); m_mfxSession = nullptr; continue; } m_mfxImpl = impl; break; } return S_OK; } void CDecMSDKMVC::DestroyDecoder(bool bFull) { if (m_bDecodeReady) { MFXVideoDECODE_Close(m_mfxSession); m_bDecodeReady = FALSE; } { CAutoLock lock(&m_BufferCritSec); for (int i = 0; i < ASYNC_QUEUE_SIZE; i++) { ReleaseBuffer(&m_pOutputQueue[i]->surface); } memset(m_pOutputQueue, 0, sizeof(m_pOutputQueue)); for (auto it = m_BufferQueue.begin(); it != m_BufferQueue.end(); it++) { if (!(*it)->queued) { av_freep(&(*it)->surface.Data.Y); delete (*it); } } m_BufferQueue.clear(); } // delete MVC sequence buffers SAFE_DELETE(m_mfxExtMVCSeq.View); SAFE_DELETE(m_mfxExtMVCSeq.ViewId); SAFE_DELETE(m_mfxExtMVCSeq.OP); m_nMP4NALUSize = 0; if (bFull) { if (m_mfxSession) { MFXClose(m_mfxSession); m_mfxSession = nullptr; } } } STDMETHODIMP CDecMSDKMVC::InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) { if (codec != AV_CODEC_ID_H264_MVC) return E_UNEXPECTED; if (*pmt->FormatType() != FORMAT_MPEG2Video) return E_UNEXPECTED; DestroyDecoder(false); // Init and reset video param arrays memset(&m_mfxVideoParams, 0, sizeof(m_mfxVideoParams)); m_mfxVideoParams.mfx.CodecId = MFX_CODEC_AVC; memset(&m_mfxExtMVCSeq, 0, sizeof(m_mfxExtMVCSeq)); m_mfxExtMVCSeq.Header.BufferId = MFX_EXTBUFF_MVC_SEQ_DESC; m_mfxExtMVCSeq.Header.BufferSz = sizeof(m_mfxExtMVCSeq); m_mfxExtParam[0] = (mfxExtBuffer *)&m_mfxExtMVCSeq; // Attach ext params to VideoParams m_mfxVideoParams.ExtParam = m_mfxExtParam; m_mfxVideoParams.NumExtParam = 1; MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->Format(); if (*pmt->Subtype() == MEDIASUBTYPE_MVC1) { m_nMP4NALUSize = 2; // Decode sequence header from the media type if (mp2vi->cbSequenceHeader) { HRESULT hr = Decode((const BYTE *)mp2vi->dwSequenceHeader, mp2vi->cbSequenceHeader, AV_NOPTS_VALUE, AV_NOPTS_VALUE, TRUE, TRUE, nullptr); if (FAILED(hr)) return hr; } m_nMP4NALUSize = mp2vi->dwFlags; } else if (*pmt->Subtype() == MEDIASUBTYPE_AMVC) { // Decode sequence header from the media type if (mp2vi->cbSequenceHeader) { HRESULT hr = Decode((const BYTE *)mp2vi->dwSequenceHeader, mp2vi->cbSequenceHeader, AV_NOPTS_VALUE, AV_NOPTS_VALUE, TRUE, TRUE, nullptr); if (FAILED(hr)) return hr; } } return S_OK; } STDMETHODIMP CDecMSDKMVC::AllocateMVCExtBuffers() { mfxU32 i; SAFE_DELETE(m_mfxExtMVCSeq.View); SAFE_DELETE(m_mfxExtMVCSeq.ViewId); SAFE_DELETE(m_mfxExtMVCSeq.OP); m_mfxExtMVCSeq.View = new mfxMVCViewDependency[m_mfxExtMVCSeq.NumView]; CheckPointer(m_mfxExtMVCSeq.View, E_OUTOFMEMORY); for (i = 0; i < m_mfxExtMVCSeq.NumView; ++i) { memset(&m_mfxExtMVCSeq.View[i], 0, sizeof(m_mfxExtMVCSeq.View[i])); } m_mfxExtMVCSeq.NumViewAlloc = m_mfxExtMVCSeq.NumView; m_mfxExtMVCSeq.ViewId = new mfxU16[m_mfxExtMVCSeq.NumViewId]; CheckPointer(m_mfxExtMVCSeq.ViewId, E_OUTOFMEMORY); for (i = 0; i < m_mfxExtMVCSeq.NumViewId; ++i) { memset(&m_mfxExtMVCSeq.ViewId[i], 0, sizeof(m_mfxExtMVCSeq.ViewId[i])); } m_mfxExtMVCSeq.NumViewIdAlloc = m_mfxExtMVCSeq.NumViewId; m_mfxExtMVCSeq.OP = new mfxMVCOperationPoint[m_mfxExtMVCSeq.NumOP]; CheckPointer(m_mfxExtMVCSeq.OP, E_OUTOFMEMORY); for (i = 0; i < m_mfxExtMVCSeq.NumOP; ++i) { memset(&m_mfxExtMVCSeq.OP[i], 0, sizeof(m_mfxExtMVCSeq.OP[i])); } m_mfxExtMVCSeq.NumOPAlloc = m_mfxExtMVCSeq.NumOP; return S_OK; } MVCBuffer *CDecMSDKMVC::GetBuffer() { CAutoLock lock(&m_BufferCritSec); MVCBuffer *pBuffer = nullptr; for (auto it = m_BufferQueue.begin(); it != m_BufferQueue.end(); it++) { if (!(*it)->surface.Data.Locked && !(*it)->queued) { pBuffer = *it; break; } } if (!pBuffer) { pBuffer = new MVCBuffer(); pBuffer->surface.Info = m_mfxVideoParams.mfx.FrameInfo; pBuffer->surface.Info.FourCC = MFX_FOURCC_NV12; pBuffer->surface.Data.PitchLow = FFALIGN(m_mfxVideoParams.mfx.FrameInfo.Width, 64); pBuffer->surface.Data.Y = (mfxU8 *)av_malloc(pBuffer->surface.Data.PitchLow * FFALIGN(m_mfxVideoParams.mfx.FrameInfo.Height, 64) * 3 / 2); if (pBuffer->surface.Data.Y == nullptr) { delete pBuffer; return nullptr; } pBuffer->surface.Data.UV = pBuffer->surface.Data.Y + (pBuffer->surface.Data.PitchLow * FFALIGN(m_mfxVideoParams.mfx.FrameInfo.Height, 64)); m_BufferQueue.push_back(pBuffer); DbgLog((LOG_TRACE, 10, L"Allocated new MSDK MVC buffer (%d total)", m_BufferQueue.size())); } return pBuffer; } MVCBuffer *CDecMSDKMVC::FindBuffer(mfxFrameSurface1 *pSurface) { CAutoLock lock(&m_BufferCritSec); bool bFound = false; for (auto it = m_BufferQueue.begin(); it != m_BufferQueue.end(); it++) { if (&(*it)->surface == pSurface) { return *it; } } return nullptr; } void CDecMSDKMVC::ReleaseBuffer(mfxFrameSurface1 *pSurface) { if (!pSurface) return; CAutoLock lock(&m_BufferCritSec); MVCBuffer *pBuffer = FindBuffer(pSurface); if (pBuffer) { pBuffer->queued = 0; pBuffer->sync = nullptr; } } static const BYTE s_AnnexBStartCode3[3] = {0x00, 0x00, 0x01}; static const BYTE s_AnnexBStartCode4[4] = {0x00, 0x00, 0x00, 0x01}; STDMETHODIMP CDecMSDKMVC::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample) { if (!m_mfxSession) return E_UNEXPECTED; HRESULT hr = S_OK; CBitstreamBuffer bsBuffer(&m_buff); mfxStatus sts = MFX_ERR_NONE; mfxBitstream bs = {0}; BOOL bFlush = (buffer == nullptr); if (rtStart >= -TIMESTAMP_OFFSET && rtStart != AV_NOPTS_VALUE) bs.TimeStamp = rtStart + TIMESTAMP_OFFSET; else bs.TimeStamp = MFX_TIMESTAMP_UNKNOWN; bs.DecodeTimeStamp = MFX_TIMESTAMP_UNKNOWN; if (!bFlush) { bsBuffer.Allocate(bsBuffer.GetBufferSize() + buflen); // Check the buffer for SEI NALU, and some unwanted NALUs that need filtering // MSDK's SEI reading functionality is slightly buggy CH264Nalu nalu; nalu.SetBuffer(buffer, buflen, m_nMP4NALUSize); BOOL bNeedFilter = FALSE; while (nalu.ReadNext()) { // Don't include End-of-Sequence or AUD NALUs if (nalu.GetType() == NALU_TYPE_EOSEQ || nalu.GetType() == NALU_TYPE_AUD) continue; if (nalu.GetType() == NALU_TYPE_SEI) { CH264NALUnescape seiNalu(nalu.GetDataBuffer() + 1, nalu.GetDataLength() - 1); ParseSEI(seiNalu.GetBuffer(), seiNalu.GetSize(), bs.TimeStamp); } // copy filtered NALs into the data buffer if (m_nMP4NALUSize) { // write annex b nal if (nalu.GetNALPos() == 0 || nalu.GetType() == NALU_TYPE_SPS || nalu.GetType() == NALU_TYPE_PPS) bsBuffer.Append(s_AnnexBStartCode4, 4); else bsBuffer.Append(s_AnnexBStartCode3, 3); // append nal data bsBuffer.Append(nalu.GetDataBuffer(), nalu.GetDataLength()); } else { bsBuffer.Append(nalu.GetNALBuffer(), nalu.GetLength()); } } bs.Data = bsBuffer.GetBuffer(); bs.DataLength = mfxU32(bsBuffer.GetBufferSize()); bs.MaxLength = bs.DataLength; AddFrameToGOP(bs.TimeStamp); } if (!m_bDecodeReady) { sts = MFXVideoDECODE_DecodeHeader(m_mfxSession, &bs, &m_mfxVideoParams); if (sts == MFX_ERR_NOT_ENOUGH_BUFFER) { hr = AllocateMVCExtBuffers(); if (FAILED(hr)) return hr; sts = MFXVideoDECODE_DecodeHeader(m_mfxSession, &bs, &m_mfxVideoParams); } if (sts == MFX_ERR_NONE) { m_mfxVideoParams.IOPattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY; m_mfxVideoParams.AsyncDepth = ASYNC_DEPTH; sts = MFXVideoDECODE_Init(m_mfxSession, &m_mfxVideoParams); if (sts != MFX_ERR_NONE) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Decode(): Error initializing the MSDK decoder (%d)", sts)); return E_FAIL; } if (m_mfxExtMVCSeq.NumView != 2) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Decode(): Only MVC with two views is supported")); return E_FAIL; } DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Decode(): Initialized MVC with View Ids %d, %d", m_mfxExtMVCSeq.View[0].ViewId, m_mfxExtMVCSeq.View[1].ViewId)); m_bDecodeReady = TRUE; } } if (!m_bDecodeReady) return S_FALSE; mfxSyncPoint sync = nullptr; // Loop over the decoder to ensure all data is being consumed while (1) { MVCBuffer *pInputBuffer = GetBuffer(); if (pInputBuffer == nullptr) return E_OUTOFMEMORY; mfxFrameSurface1 *outsurf = nullptr; sts = MFXVideoDECODE_DecodeFrameAsync(m_mfxSession, bFlush ? nullptr : &bs, &pInputBuffer->surface, &outsurf, &sync); if (sts == MFX_ERR_INCOMPATIBLE_VIDEO_PARAM) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Decode(): Incompatible video parameters detected, flushing decoder")); bsBuffer.Clear(); bFlush = TRUE; m_bDecodeReady = FALSE; continue; } if (sync) { MVCBuffer *pOutputBuffer = FindBuffer(outsurf); pOutputBuffer->queued = 1; pOutputBuffer->sync = sync; HandleOutput(pOutputBuffer); continue; } if (sts != MFX_ERR_MORE_SURFACE && sts < 0) break; } if (!bs.DataOffset && !sync && !bFlush) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Decode(): Decoder did not consume any data, discarding")); bs.DataOffset = mfxU32(bsBuffer.GetBufferSize()); } bsBuffer.Consume(bs.DataOffset); if (sts != MFX_ERR_MORE_DATA && sts < 0) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::Decode(): Error from Decode call (%d)", sts)); return S_FALSE; } return S_OK; } HRESULT CDecMSDKMVC::ParseSEI(const BYTE *buffer, size_t size, mfxU64 timestamp) { CByteParser seiParser(buffer, size); while (seiParser.RemainingBits() > 16 && seiParser.BitRead(16, true)) { int type = 0; unsigned size = 0; do { if (seiParser.RemainingBits() < 8) return E_FAIL; type += seiParser.BitRead(8, true); } while (seiParser.BitRead(8) == 0xFF); do { if (seiParser.RemainingBits() < 8) return E_FAIL; size += seiParser.BitRead(8, true); } while (seiParser.BitRead(8) == 0xFF); if (size > seiParser.Remaining()) { DbgLog((LOG_TRACE, 10, L"CDecMSDKMVC::ParseSEI(): SEI type %d size %d truncated, available: %d", type, size, seiParser.Remaining())); return E_FAIL; } switch (type) { case 5: ParseUnregUserDataSEI(buffer + seiParser.Pos(), size, timestamp); break; case 37: ParseMVCNestedSEI(buffer + seiParser.Pos(), size, timestamp); break; } seiParser.BitSkip(size * 8); } return S_OK; } HRESULT CDecMSDKMVC::ParseMVCNestedSEI(const BYTE *buffer, size_t size, mfxU64 timestamp) { CByteParser seiParser(buffer, size); // Parse the MVC Scalable Nesting SEI first int op_flag = seiParser.BitRead(1); if (!op_flag) { int all_views_in_au = seiParser.BitRead(1); if (!all_views_in_au) { int num_views_min1 = seiParser.UExpGolombRead(); for (int i = 0; i <= num_views_min1; i++) { seiParser.BitRead(10); // sei_view_id[i] } } } else { int num_views_min1 = seiParser.UExpGolombRead(); for (int i = 0; i <= num_views_min1; i++) { seiParser.BitRead(10); // sei_op_view_id[i] } seiParser.BitRead(3); // sei_op_temporal_id } seiParser.BitByteAlign(); // Parse nested SEI ParseSEI(buffer + seiParser.Pos(), seiParser.Remaining(), timestamp); return S_OK; } static const uint8_t uuid_iso_iec_11578[16] = {0x17, 0xee, 0x8c, 0x60, 0xf8, 0x4d, 0x11, 0xd9, 0x8c, 0xd6, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66}; HRESULT CDecMSDKMVC::ParseUnregUserDataSEI(const BYTE *buffer, size_t size, mfxU64 timestamp) { if (size < 20) return E_FAIL; if (memcmp(buffer, uuid_iso_iec_11578, 16) != 0) { DbgLog((LOG_TRACE, 10, L"CDecMSDKMVC::ParseUnregUserDataSEI(): Unknown User Data GUID")); return S_FALSE; } uint32_t type = AV_RB32(buffer + 16); // Offset metadata if (type == 0x4F464D44) { return ParseOffsetMetadata(buffer + 20, size - 20, timestamp); } return S_FALSE; } HRESULT CDecMSDKMVC::ParseOffsetMetadata(const BYTE *buffer, size_t size, mfxU64 timestamp) { if (size < 10) return E_FAIL; // Skip PTS part, its not used. Start parsing at first marker bit after the PTS CByteParser offset(buffer + 6, size - 6); offset.BitSkip(2); // Skip marker and re served unsigned int nOffsets = offset.BitRead(6); unsigned int nFrames = offset.BitRead(8); DbgLog((LOG_CUSTOM2, 10, L"CDecMSDKMVC::ParseOffsetMetadata(): offset_metadata with %d offsets and %d frames for time %I64u", nOffsets, nFrames, timestamp)); if (nOffsets > 32) { DbgLog((LOG_TRACE, 10, L"CDecMSDKMVC::ParseOffsetMetadata(): > 32 offsets is not supported")); return E_FAIL; } offset.BitSkip(16); // Skip marker and reserved if (nOffsets * nFrames > (size - 10)) { DbgLog((LOG_TRACE, 10, L"CDecMSDKMVC::ParseOffsetMetadata(): not enough data for all offsets (need %d, have %d)", nOffsets * nFrames, size - 4)); return E_FAIL; } MVCGOP GOP; for (unsigned int o = 0; o < nOffsets; o++) { for (unsigned int f = 0; f < nFrames; f++) { if (o == 0) { MediaSideData3DOffset off = {(int)nOffsets}; GOP.offsets.push_back(off); } int direction_flag = offset.BitRead(1); int value = offset.BitRead(7); if (direction_flag) value = -value; GOP.offsets[f].offset[o] = value; } } m_GOPs.push_back(GOP); return S_OK; } void CDecMSDKMVC::AddFrameToGOP(mfxU64 timestamp) { if (m_GOPs.size() > 0) m_GOPs.back().timestamps.push_back(timestamp); } BOOL CDecMSDKMVC::RemoveFrameFromGOP(MVCGOP *pGOP, mfxU64 timestamp) { if (pGOP->timestamps.empty() || pGOP->offsets.empty()) return FALSE; auto e = std::find(pGOP->timestamps.begin(), pGOP->timestamps.end(), timestamp); if (e != pGOP->timestamps.end()) { pGOP->timestamps.erase(e); return TRUE; } return FALSE; } void CDecMSDKMVC::GetOffsetSideData(LAVFrame *pFrame, mfxU64 timestamp) { MediaSideData3DOffset offset = {255}; // Go over all stored GOPs and find an entry for our timestamp // In general it should be found in the first GOP, unless we lost frames in between or something else went wrong. for (auto it = m_GOPs.begin(); it != m_GOPs.end(); it++) { if (RemoveFrameFromGOP(&(*it), timestamp)) { offset = it->offsets.front(); it->offsets.pop_front(); // Erase previous GOPs when we start accessing a new one if (it != m_GOPs.begin()) { #ifdef DEBUG // Check that all to-be-erased GOPs are empty for (auto itd = m_GOPs.begin(); itd < it; itd++) { if (!itd->offsets.empty()) { DbgLog((LOG_TRACE, 10, L"CDecMSDKMVC::GetOffsetSideData(): Switched to next GOP at %I64u with %Iu entries " L"remaining", timestamp, itd->offsets.size())); } } #endif m_GOPs.erase(m_GOPs.begin(), it); } break; } } if (offset.offset_count == 255) { DbgLog((LOG_TRACE, 10, L"CDecMSDKMVC::GetOffsetSideData():No offset for frame at %I64u", timestamp)); offset = m_PrevOffset; } m_PrevOffset = offset; // Only set the offset when data is present if (offset.offset_count > 0) { MediaSideData3DOffset *FrameOffset = (MediaSideData3DOffset *)AddLAVFrameSideData( pFrame, IID_MediaSideData3DOffset, sizeof(MediaSideData3DOffset)); if (FrameOffset) *FrameOffset = offset; } } HRESULT CDecMSDKMVC::HandleOutput(MVCBuffer *pOutputBuffer) { int nCur = m_nOutputQueuePosition, nNext = (m_nOutputQueuePosition + 1) % ASYNC_QUEUE_SIZE; if (m_pOutputQueue[nCur] && m_pOutputQueue[nNext]) { DeliverOutput(m_pOutputQueue[nCur], m_pOutputQueue[nNext]); m_pOutputQueue[nCur] = nullptr; m_pOutputQueue[nNext] = nullptr; } else if (m_pOutputQueue[nCur]) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::HandleOutput(): Dropping unpaired frame")); ReleaseBuffer(&m_pOutputQueue[nCur]->surface); m_pOutputQueue[nCur]->sync = nullptr; m_pOutputQueue[nCur] = nullptr; } m_pOutputQueue[nCur] = pOutputBuffer; m_nOutputQueuePosition = nNext; return S_OK; } HRESULT CDecMSDKMVC::DeliverOutput(MVCBuffer *pBaseView, MVCBuffer *pExtraView) { mfxStatus sts = MFX_ERR_NONE; ASSERT(pBaseView->surface.Info.FrameId.ViewId == 0 && pExtraView->surface.Info.FrameId.ViewId > 0); ASSERT(pBaseView->surface.Data.FrameOrder == pExtraView->surface.Data.FrameOrder); // Sync base view do { sts = MFXVideoCORE_SyncOperation(m_mfxSession, pBaseView->sync, 1000); } while (sts == MFX_WRN_IN_EXECUTION); pBaseView->sync = nullptr; // Sync extra view do { sts = MFXVideoCORE_SyncOperation(m_mfxSession, pExtraView->sync, 1000); } while (sts == MFX_WRN_IN_EXECUTION); pExtraView->sync = nullptr; LAVFrame *pFrame = nullptr; AllocateFrame(&pFrame); pFrame->width = pBaseView->surface.Info.CropW; pFrame->height = pBaseView->surface.Info.CropH; pFrame->data[0] = pBaseView->surface.Data.Y; pFrame->data[1] = pBaseView->surface.Data.UV; pFrame->stereo[0] = pExtraView->surface.Data.Y; pFrame->stereo[1] = pExtraView->surface.Data.UV; pFrame->data[2] = (uint8_t *)pBaseView; pFrame->data[3] = (uint8_t *)pExtraView; pFrame->stride[0] = pBaseView->surface.Data.PitchLow; pFrame->stride[1] = pBaseView->surface.Data.PitchLow; pFrame->format = LAVPixFmt_NV12; pFrame->sw_format = pFrame->format; pFrame->bpp = 8; pFrame->flags |= LAV_FRAME_FLAG_MVC; if (!(pBaseView->surface.Data.DataFlag & MFX_FRAMEDATA_ORIGINAL_TIMESTAMP)) pBaseView->surface.Data.TimeStamp = MFX_TIMESTAMP_UNKNOWN; if (pBaseView->surface.Data.TimeStamp != MFX_TIMESTAMP_UNKNOWN) { pFrame->rtStart = pBaseView->surface.Data.TimeStamp; pFrame->rtStart -= TIMESTAMP_OFFSET; } else { pFrame->rtStart = AV_NOPTS_VALUE; } int64_t num = (int64_t)pBaseView->surface.Info.AspectRatioW * pFrame->width; int64_t den = (int64_t)pBaseView->surface.Info.AspectRatioH * pFrame->height; av_reduce(&pFrame->aspect_ratio.num, &pFrame->aspect_ratio.den, num, den, INT_MAX); pFrame->destruct = msdk_buffer_destruct; pFrame->priv_data = this; GetOffsetSideData(pFrame, pBaseView->surface.Data.TimeStamp); return Deliver(pFrame); } void CDecMSDKMVC::msdk_buffer_destruct(LAVFrame *pFrame) { CDecMSDKMVC *pDec = (CDecMSDKMVC *)pFrame->priv_data; CAutoLock lock(&pDec->m_BufferCritSec); MVCBuffer *pBaseBuffer = (MVCBuffer *)pFrame->data[2]; MVCBuffer *pStoredBuffer = pDec->FindBuffer(&pBaseBuffer->surface); if (pStoredBuffer) { pDec->ReleaseBuffer(&pBaseBuffer->surface); } else { av_free(pBaseBuffer->surface.Data.Y); SAFE_DELETE(pBaseBuffer); } MVCBuffer *pExtraBuffer = (MVCBuffer *)pFrame->data[3]; pStoredBuffer = pDec->FindBuffer(&pExtraBuffer->surface); if (pStoredBuffer) { pDec->ReleaseBuffer(&pExtraBuffer->surface); } else { av_free(pExtraBuffer->surface.Data.Y); SAFE_DELETE(pExtraBuffer); } } STDMETHODIMP CDecMSDKMVC::Flush() { m_buff.Clear(); if (m_mfxSession) { if (m_bDecodeReady) MFXVideoDECODE_Reset(m_mfxSession, &m_mfxVideoParams); // TODO: decode sequence data for (int i = 0; i < ASYNC_QUEUE_SIZE; i++) { ReleaseBuffer(&m_pOutputQueue[i]->surface); } memset(m_pOutputQueue, 0, sizeof(m_pOutputQueue)); } m_GOPs.clear(); memset(&m_PrevOffset, 0, sizeof(m_PrevOffset)); return __super::Flush(); } STDMETHODIMP CDecMSDKMVC::EndOfStream() { if (!m_bDecodeReady) return S_FALSE; // Flush frames out of the decoder Decode(nullptr, 0, AV_NOPTS_VALUE, AV_NOPTS_VALUE, FALSE, FALSE, nullptr); // Process all remaining frames in the queue for (int i = 0; i < ASYNC_QUEUE_SIZE; i++) { int nCur = (m_nOutputQueuePosition + i) % ASYNC_QUEUE_SIZE, nNext = (m_nOutputQueuePosition + i + 1) % ASYNC_QUEUE_SIZE; if (m_pOutputQueue[nCur] && m_pOutputQueue[nNext]) { DeliverOutput(m_pOutputQueue[nCur], m_pOutputQueue[nNext]); m_pOutputQueue[nCur] = nullptr; m_pOutputQueue[nNext] = nullptr; i++; } else if (m_pOutputQueue[nCur]) { DbgLog((LOG_TRACE, 10, L"CDevMSDKMVC::EndOfStream(): Dropping unpaired frame")); ReleaseBuffer(&m_pOutputQueue[nCur]->surface); m_pOutputQueue[nCur] = nullptr; } } m_nOutputQueuePosition = 0; return S_OK; } ================================================ FILE: decoder/LAVVideo/decoders/msdk_mvc.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DecBase.h" #include "IMediaSideData.h" #include "mfxvideo.h" #include "mfxmvc.h" #include #include #define ASYNC_DEPTH 8 #define ASYNC_QUEUE_SIZE (ASYNC_DEPTH + 2) // 10s timestamp offset to avoid negative timestamps #define TIMESTAMP_OFFSET 100000000i64 #define MFX_IMPL_VIA_MASK 0x0F00 typedef struct _MVCBuffer { mfxFrameSurface1 surface = {0}; bool queued = false; mfxSyncPoint sync = nullptr; } MVCBuffer; typedef struct _MVCGOP { std::deque timestamps; std::deque offsets; } MVCGOP; class CDecMSDKMVC : public CDecBase { public: CDecMSDKMVC(); virtual ~CDecMSDKMVC(); // ILAVDecoder STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { if (pPix) *pPix = LAVPixFmt_NV12; if (pBpp) *pBpp = 8; if (pPixSoftware) *pPixSoftware = LAVPixFmt_NV12; return S_OK; } STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess) { return FALSE; } STDMETHODIMP_(const WCHAR *) GetDecoderName() { return (m_mfxImpl != MFX_IMPL_SOFTWARE) ? L"msdk mvc hw" : L"msdk mvc"; } STDMETHODIMP HasThreadSafeBuffers() { return S_OK; } // CDecBase STDMETHODIMP Init(); private: void DestroyDecoder(bool bFull); STDMETHODIMP AllocateMVCExtBuffers(); MVCBuffer *GetBuffer(); MVCBuffer *FindBuffer(mfxFrameSurface1 *pSurface); void ReleaseBuffer(mfxFrameSurface1 *pSurface); HRESULT HandleOutput(MVCBuffer *pOutputBuffer); HRESULT DeliverOutput(MVCBuffer *pBaseView, MVCBuffer *pExtraView); HRESULT ParseSEI(const BYTE *buffer, size_t size, mfxU64 timestamp); HRESULT ParseMVCNestedSEI(const BYTE *buffer, size_t size, mfxU64 timestamp); HRESULT ParseUnregUserDataSEI(const BYTE *buffer, size_t size, mfxU64 timestamp); HRESULT ParseOffsetMetadata(const BYTE *buffer, size_t size, mfxU64 timestamp); void AddFrameToGOP(mfxU64 timestamp); BOOL RemoveFrameFromGOP(MVCGOP *pGOP, mfxU64 timestamp); void GetOffsetSideData(LAVFrame *pFrame, mfxU64 timestamp); static void msdk_buffer_destruct(LAVFrame *pFrame); private: mfxSession m_mfxSession = nullptr; mfxVersion m_mfxVersion = {0}; mfxIMPL m_mfxImpl = 0; BOOL m_bDecodeReady = FALSE; mfxVideoParam m_mfxVideoParams = {0}; mfxExtBuffer *m_mfxExtParam[1] = {0}; mfxExtMVCSeqDesc m_mfxExtMVCSeq = {0}; CCritSec m_BufferCritSec; std::vector m_BufferQueue; GrowableArray m_buff; int m_nMP4NALUSize = 0; MVCBuffer *m_pOutputQueue[ASYNC_QUEUE_SIZE] = {0}; int m_nOutputQueuePosition = 0; std::deque m_GOPs; MediaSideData3DOffset m_PrevOffset; }; ================================================ FILE: decoder/LAVVideo/decoders/mvc/include/mfxcommon.h ================================================ /******************************************************************************* Copyright (C) 2013-2018 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfxcommon.h *******************************************************************************/ #ifndef __MFXCOMMON_H__ #define __MFXCOMMON_H__ #include "mfxdefs.h" #if !defined (__GNUC__) #pragma warning(disable: 4201) #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #define MFX_MAKEFOURCC(A,B,C,D) ((((int)A))+(((int)B)<<8)+(((int)C)<<16)+(((int)D)<<24)) /* Extended Configuration Header Structure */ typedef struct { mfxU32 BufferId; mfxU32 BufferSz; } mfxExtBuffer; /* Library initialization and deinitialization */ typedef mfxI32 mfxIMPL; #define MFX_IMPL_BASETYPE(x) (0x00ff & (x)) enum { MFX_IMPL_AUTO = 0x0000, /* Auto Selection/In or Not Supported/Out */ MFX_IMPL_SOFTWARE = 0x0001, /* Pure Software Implementation */ MFX_IMPL_HARDWARE = 0x0002, /* Hardware Accelerated Implementation (default device) */ MFX_IMPL_AUTO_ANY = 0x0003, /* Auto selection of any hardware/software implementation */ MFX_IMPL_HARDWARE_ANY = 0x0004, /* Auto selection of any hardware implementation */ MFX_IMPL_HARDWARE2 = 0x0005, /* Hardware accelerated implementation (2nd device) */ MFX_IMPL_HARDWARE3 = 0x0006, /* Hardware accelerated implementation (3rd device) */ MFX_IMPL_HARDWARE4 = 0x0007, /* Hardware accelerated implementation (4th device) */ MFX_IMPL_RUNTIME = 0x0008, MFX_IMPL_VIA_ANY = 0x0100, MFX_IMPL_VIA_D3D9 = 0x0200, MFX_IMPL_VIA_D3D11 = 0x0300, MFX_IMPL_VIA_VAAPI = 0x0400, MFX_IMPL_AUDIO = 0x8000, MFX_IMPL_UNSUPPORTED = 0x0000 /* One of the MFXQueryIMPL returns */ }; /* Version Info */ typedef union { struct { mfxU16 Minor; mfxU16 Major; }; mfxU32 Version; } mfxVersion; /* session priority */ typedef enum { MFX_PRIORITY_LOW = 0, MFX_PRIORITY_NORMAL = 1, MFX_PRIORITY_HIGH = 2 } mfxPriority; typedef struct _mfxEncryptedData mfxEncryptedData; typedef struct { union { struct { mfxEncryptedData* EncryptedData; mfxExtBuffer **ExtParam; mfxU16 NumExtParam; }; mfxU32 reserved[6]; }; mfxI64 DecodeTimeStamp; mfxU64 TimeStamp; mfxU8* Data; mfxU32 DataOffset; mfxU32 DataLength; mfxU32 MaxLength; mfxU16 PicStruct; mfxU16 FrameType; mfxU16 DataFlag; mfxU16 reserved2; } mfxBitstream; typedef struct _mfxSyncPoint *mfxSyncPoint; /* GPUCopy */ enum { MFX_GPUCOPY_DEFAULT = 0, MFX_GPUCOPY_ON = 1, MFX_GPUCOPY_OFF = 2 }; typedef struct { mfxIMPL Implementation; mfxVersion Version; mfxU16 ExternalThreads; union { struct { mfxExtBuffer **ExtParam; mfxU16 NumExtParam; }; mfxU16 reserved2[5]; }; mfxU16 GPUCopy; mfxU16 reserved[21]; } mfxInitParam; enum { MFX_EXTBUFF_THREADS_PARAM = MFX_MAKEFOURCC('T','H','D','P') }; typedef struct { mfxExtBuffer Header; mfxU16 NumThread; mfxI32 SchedulingType; mfxI32 Priority; mfxU16 reserved[55]; } mfxExtThreadsParam; /* PlatformCodeName */ enum { MFX_PLATFORM_UNKNOWN = 0, MFX_PLATFORM_SANDYBRIDGE = 1, MFX_PLATFORM_IVYBRIDGE = 2, MFX_PLATFORM_HASWELL = 3, MFX_PLATFORM_BAYTRAIL = 4, MFX_PLATFORM_BROADWELL = 5, MFX_PLATFORM_CHERRYTRAIL = 6, MFX_PLATFORM_SKYLAKE = 7, MFX_PLATFORM_APOLLOLAKE = 8, MFX_PLATFORM_KABYLAKE = 9, MFX_PLATFORM_GEMINILAKE = 10, MFX_PLATFORM_COFFEELAKE = 11, MFX_PLATFORM_CANNONLAKE = 20, MFX_PLATFORM_ICELAKE = 30, }; typedef struct { mfxU16 CodeName; mfxU16 DeviceId; mfxU16 reserved[14]; } mfxPlatform; #ifdef __cplusplus } #endif /* __cplusplus */ #endif ================================================ FILE: decoder/LAVVideo/decoders/mvc/include/mfxdefs.h ================================================ /* ****************************************************************************** *\ Copyright (C) 2007-2018 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfxdefs.h \* ****************************************************************************** */ #ifndef __MFXDEFS_H__ #define __MFXDEFS_H__ #define MFX_VERSION_MAJOR 1 #define MFX_VERSION_MINOR 27 #define MFX_VERSION_NEXT 1028 #ifndef MFX_VERSION #define MFX_VERSION (MFX_VERSION_MAJOR * 1000 + MFX_VERSION_MINOR) #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #if (defined( _WIN32 ) || defined ( _WIN64 )) && !defined (__GNUC__) #define __INT64 __int64 #define __UINT64 unsigned __int64 #else #define __INT64 long long #define __UINT64 unsigned long long #endif #ifdef _WIN32 #define MFX_CDECL __cdecl #define MFX_STDCALL __stdcall #else #define MFX_CDECL #define MFX_STDCALL #endif /* _WIN32 */ #define MFX_INFINITE 0xFFFFFFFF typedef unsigned char mfxU8; typedef char mfxI8; typedef short mfxI16; typedef unsigned short mfxU16; typedef unsigned int mfxU32; typedef int mfxI32; #if defined( _WIN32 ) || defined ( _WIN64 ) typedef unsigned long mfxUL32; typedef long mfxL32; #else typedef unsigned int mfxUL32; typedef int mfxL32; #endif typedef float mfxF32; typedef double mfxF64; typedef __UINT64 mfxU64; typedef __INT64 mfxI64; typedef void* mfxHDL; typedef mfxHDL mfxMemId; typedef void* mfxThreadTask; typedef char mfxChar; typedef struct { mfxI16 x; mfxI16 y; } mfxI16Pair; typedef struct { mfxHDL first; mfxHDL second; } mfxHDLPair; /*********************************************************************************\ Error message \*********************************************************************************/ typedef enum { /* no error */ MFX_ERR_NONE = 0, /* no error */ /* reserved for unexpected errors */ MFX_ERR_UNKNOWN = -1, /* unknown error. */ /* error codes <0 */ MFX_ERR_NULL_PTR = -2, /* null pointer */ MFX_ERR_UNSUPPORTED = -3, /* undeveloped feature */ MFX_ERR_MEMORY_ALLOC = -4, /* failed to allocate memory */ MFX_ERR_NOT_ENOUGH_BUFFER = -5, /* insufficient buffer at input/output */ MFX_ERR_INVALID_HANDLE = -6, /* invalid handle */ MFX_ERR_LOCK_MEMORY = -7, /* failed to lock the memory block */ MFX_ERR_NOT_INITIALIZED = -8, /* member function called before initialization */ MFX_ERR_NOT_FOUND = -9, /* the specified object is not found */ MFX_ERR_MORE_DATA = -10, /* expect more data at input */ MFX_ERR_MORE_SURFACE = -11, /* expect more surface at output */ MFX_ERR_ABORTED = -12, /* operation aborted */ MFX_ERR_DEVICE_LOST = -13, /* lose the HW acceleration device */ MFX_ERR_INCOMPATIBLE_VIDEO_PARAM = -14, /* incompatible video parameters */ MFX_ERR_INVALID_VIDEO_PARAM = -15, /* invalid video parameters */ MFX_ERR_UNDEFINED_BEHAVIOR = -16, /* undefined behavior */ MFX_ERR_DEVICE_FAILED = -17, /* device operation failure */ MFX_ERR_MORE_BITSTREAM = -18, /* expect more bitstream buffers at output */ MFX_ERR_INCOMPATIBLE_AUDIO_PARAM = -19, /* incompatible audio parameters */ MFX_ERR_INVALID_AUDIO_PARAM = -20, /* invalid audio parameters */ MFX_ERR_GPU_HANG = -21, /* device operation failure caused by GPU hang */ MFX_ERR_REALLOC_SURFACE = -22, /* bigger output surface required */ /* warnings >0 */ MFX_WRN_IN_EXECUTION = 1, /* the previous asynchronous operation is in execution */ MFX_WRN_DEVICE_BUSY = 2, /* the HW acceleration device is busy */ MFX_WRN_VIDEO_PARAM_CHANGED = 3, /* the video parameters are changed during decoding */ MFX_WRN_PARTIAL_ACCELERATION = 4, /* SW is used */ MFX_WRN_INCOMPATIBLE_VIDEO_PARAM = 5, /* incompatible video parameters */ MFX_WRN_VALUE_NOT_CHANGED = 6, /* the value is saturated based on its valid range */ MFX_WRN_OUT_OF_RANGE = 7, /* the value is out of valid range */ MFX_WRN_FILTER_SKIPPED = 10, /* one of requested filters has been skipped */ MFX_WRN_INCOMPATIBLE_AUDIO_PARAM = 11, /* incompatible audio parameters */ /* threading statuses */ MFX_TASK_DONE = MFX_ERR_NONE, /* task has been completed */ MFX_TASK_WORKING = 8, /* there is some more work to do */ MFX_TASK_BUSY = 9, /* task is waiting for resources */ /* plug-in statuses */ MFX_ERR_MORE_DATA_SUBMIT_TASK = -10000, /* return MFX_ERR_MORE_DATA but submit internal asynchronous task */ } mfxStatus; // Application #if defined(MFX_DISPATCHER_EXPOSED_PREFIX) #include "mfxdispatcherprefixedfunctions.h" #endif // MFX_DISPATCHER_EXPOSED_PREFIX #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __MFXDEFS_H__ */ ================================================ FILE: decoder/LAVVideo/decoders/mvc/include/mfxmvc.h ================================================ /******************************************************************************* *\ Copyright (C) 2010-2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfxmvc.h *******************************************************************************/ #ifndef __MFXMVC_H__ #define __MFXMVC_H__ #include "mfxdefs.h" #ifdef __cplusplus extern "C" { #endif /* CodecProfile, CodecLevel */ enum { /* MVC profiles */ MFX_PROFILE_AVC_MULTIVIEW_HIGH =118, MFX_PROFILE_AVC_STEREO_HIGH =128 }; /* Extended Buffer Ids */ enum { MFX_EXTBUFF_MVC_SEQ_DESC = MFX_MAKEFOURCC('M','V','C','D'), MFX_EXTBUFF_MVC_TARGET_VIEWS = MFX_MAKEFOURCC('M','V','C','T') }; typedef struct { mfxU16 ViewId; mfxU16 NumAnchorRefsL0; mfxU16 NumAnchorRefsL1; mfxU16 AnchorRefL0[16]; mfxU16 AnchorRefL1[16]; mfxU16 NumNonAnchorRefsL0; mfxU16 NumNonAnchorRefsL1; mfxU16 NonAnchorRefL0[16]; mfxU16 NonAnchorRefL1[16]; } mfxMVCViewDependency; typedef struct { mfxU16 TemporalId; mfxU16 LevelIdc; mfxU16 NumViews; mfxU16 NumTargetViews; mfxU16 *TargetViewId; } mfxMVCOperationPoint; typedef struct { mfxExtBuffer Header; mfxU32 NumView; mfxU32 NumViewAlloc; mfxMVCViewDependency *View; mfxU32 NumViewId; mfxU32 NumViewIdAlloc; mfxU16 *ViewId; mfxU32 NumOP; mfxU32 NumOPAlloc; mfxMVCOperationPoint *OP; mfxU16 NumRefsTotal; mfxU32 Reserved[16]; } mfxExtMVCSeqDesc; typedef struct { mfxExtBuffer Header; mfxU16 TemporalId; mfxU32 NumView; mfxU16 ViewId[1024]; } mfxExtMVCTargetViews ; #ifdef __cplusplus } // extern "C" #endif #endif ================================================ FILE: decoder/LAVVideo/decoders/mvc/include/mfxsession.h ================================================ /******************************************************************************* Copyright (C) 2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfxsession.h *******************************************************************************/ #ifndef __MFXSESSION_H__ #define __MFXSESSION_H__ #include "mfxcommon.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Global Functions */ typedef struct _mfxSession *mfxSession; mfxStatus MFX_CDECL MFXInit(mfxIMPL impl, mfxVersion *ver, mfxSession *session); mfxStatus MFX_CDECL MFXInitEx(mfxInitParam par, mfxSession *session); mfxStatus MFX_CDECL MFXClose(mfxSession session); mfxStatus MFX_CDECL MFXQueryIMPL(mfxSession session, mfxIMPL *impl); mfxStatus MFX_CDECL MFXQueryVersion(mfxSession session, mfxVersion *version); mfxStatus MFX_CDECL MFXJoinSession(mfxSession session, mfxSession child); mfxStatus MFX_CDECL MFXDisjoinSession(mfxSession session); mfxStatus MFX_CDECL MFXCloneSession(mfxSession session, mfxSession *clone); mfxStatus MFX_CDECL MFXSetPriority(mfxSession session, mfxPriority priority); mfxStatus MFX_CDECL MFXGetPriority(mfxSession session, mfxPriority *priority); mfxStatus MFX_CDECL MFXDoWork(mfxSession session); #ifdef __cplusplus } #endif /* __cplusplus */ #endif ================================================ FILE: decoder/LAVVideo/decoders/mvc/include/mfxstructures.h ================================================ /******************************************************************************* *\ Copyright (C) 2007-2018 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfxstructures.h *******************************************************************************/ #ifndef __MFXSTRUCTURES_H__ #define __MFXSTRUCTURES_H__ #include "mfxcommon.h" #if !defined (__GNUC__) #pragma warning(disable: 4201) #endif #ifdef __cplusplus extern "C" { #endif /* Frame ID for SVC and MVC */ typedef struct { mfxU16 TemporalId; mfxU16 PriorityId; union { struct { mfxU16 DependencyId; mfxU16 QualityId; }; struct { mfxU16 ViewId; }; }; } mfxFrameId; #pragma pack(push, 4) /* Frame Info */ typedef struct { mfxU32 reserved[4]; mfxU16 reserved4; mfxU16 BitDepthLuma; mfxU16 BitDepthChroma; mfxU16 Shift; mfxFrameId FrameId; mfxU32 FourCC; union { struct { /* Frame parameters */ mfxU16 Width; mfxU16 Height; mfxU16 CropX; mfxU16 CropY; mfxU16 CropW; mfxU16 CropH; }; struct { /* Buffer parameters (for plain formats like P8) */ mfxU64 BufferSize; mfxU32 reserved5; }; }; mfxU32 FrameRateExtN; mfxU32 FrameRateExtD; mfxU16 reserved3; mfxU16 AspectRatioW; mfxU16 AspectRatioH; mfxU16 PicStruct; mfxU16 ChromaFormat; mfxU16 reserved2; } mfxFrameInfo; #pragma pack(pop) /* FourCC */ enum { MFX_FOURCC_NV12 = MFX_MAKEFOURCC('N','V','1','2'), /* Native Format */ MFX_FOURCC_YV12 = MFX_MAKEFOURCC('Y','V','1','2'), MFX_FOURCC_NV16 = MFX_MAKEFOURCC('N','V','1','6'), MFX_FOURCC_YUY2 = MFX_MAKEFOURCC('Y','U','Y','2'), MFX_FOURCC_RGB3 = MFX_MAKEFOURCC('R','G','B','3'), /* deprecated */ MFX_FOURCC_RGB4 = MFX_MAKEFOURCC('R','G','B','4'), /* ARGB in that order, A channel is 8 MSBs */ MFX_FOURCC_P8 = 41, /* D3DFMT_P8 */ MFX_FOURCC_P8_TEXTURE = MFX_MAKEFOURCC('P','8','M','B'), MFX_FOURCC_P010 = MFX_MAKEFOURCC('P','0','1','0'), MFX_FOURCC_P210 = MFX_MAKEFOURCC('P','2','1','0'), MFX_FOURCC_BGR4 = MFX_MAKEFOURCC('B','G','R','4'), /* ABGR in that order, A channel is 8 MSBs */ MFX_FOURCC_A2RGB10 = MFX_MAKEFOURCC('R','G','1','0'), /* ARGB in that order, A channel is two MSBs */ MFX_FOURCC_ARGB16 = MFX_MAKEFOURCC('R','G','1','6'), /* ARGB in that order, 64 bits, A channel is 16 MSBs */ MFX_FOURCC_ABGR16 = MFX_MAKEFOURCC('B','G','1','6'), /* ABGR in that order, 64 bits, A channel is 16 MSBs */ MFX_FOURCC_R16 = MFX_MAKEFOURCC('R','1','6','U'), MFX_FOURCC_AYUV = MFX_MAKEFOURCC('A','Y','U','V'), /* YUV 4:4:4, AYUV in that order, A channel is 8 MSBs */ MFX_FOURCC_AYUV_RGB4 = MFX_MAKEFOURCC('A','V','U','Y'), /* ARGB in that order, A channel is 8 MSBs stored in AYUV surface*/ MFX_FOURCC_UYVY = MFX_MAKEFOURCC('U','Y','V','Y'), MFX_FOURCC_Y210 = MFX_MAKEFOURCC('Y','2','1','0'), MFX_FOURCC_Y410 = MFX_MAKEFOURCC('Y','4','1','0'), }; /* PicStruct */ enum { MFX_PICSTRUCT_UNKNOWN =0x00, MFX_PICSTRUCT_PROGRESSIVE =0x01, MFX_PICSTRUCT_FIELD_TFF =0x02, MFX_PICSTRUCT_FIELD_BFF =0x04, MFX_PICSTRUCT_FIELD_REPEATED=0x10, /* first field repeated, pic_struct=5 or 6 in H.264 */ MFX_PICSTRUCT_FRAME_DOUBLING=0x20, /* pic_struct=7 in H.264 */ MFX_PICSTRUCT_FRAME_TRIPLING=0x40, /* pic_struct=8 in H.264 */ MFX_PICSTRUCT_FIELD_SINGLE =0x100, MFX_PICSTRUCT_FIELD_TOP =MFX_PICSTRUCT_FIELD_SINGLE | MFX_PICSTRUCT_FIELD_TFF, MFX_PICSTRUCT_FIELD_BOTTOM =MFX_PICSTRUCT_FIELD_SINGLE | MFX_PICSTRUCT_FIELD_BFF, MFX_PICSTRUCT_FIELD_PAIRED_PREV =0x200, MFX_PICSTRUCT_FIELD_PAIRED_NEXT =0x400, }; /* ColorFormat */ enum { MFX_CHROMAFORMAT_MONOCHROME =0, MFX_CHROMAFORMAT_YUV420 =1, MFX_CHROMAFORMAT_YUV422 =2, MFX_CHROMAFORMAT_YUV444 =3, MFX_CHROMAFORMAT_YUV400 = MFX_CHROMAFORMAT_MONOCHROME, MFX_CHROMAFORMAT_YUV411 = 4, MFX_CHROMAFORMAT_YUV422H = MFX_CHROMAFORMAT_YUV422, MFX_CHROMAFORMAT_YUV422V = 5, MFX_CHROMAFORMAT_RESERVED1 = 6 }; enum { MFX_TIMESTAMP_UNKNOWN = -1 }; enum { MFX_FRAMEORDER_UNKNOWN = -1 }; /* DataFlag in mfxFrameData */ enum { MFX_FRAMEDATA_ORIGINAL_TIMESTAMP = 0x0001 }; /* Corrupted in mfxFrameData */ enum { MFX_CORRUPTION_MINOR = 0x0001, MFX_CORRUPTION_MAJOR = 0x0002, MFX_CORRUPTION_ABSENT_TOP_FIELD = 0x0004, MFX_CORRUPTION_ABSENT_BOTTOM_FIELD = 0x0008, MFX_CORRUPTION_REFERENCE_FRAME = 0x0010, MFX_CORRUPTION_REFERENCE_LIST = 0x0020 }; #pragma pack(push, 4) typedef struct { mfxU32 U : 10; mfxU32 Y : 10; mfxU32 V : 10; mfxU32 A : 2; } mfxY410; #pragma pack(pop) #pragma pack(push, 4) typedef struct { mfxU32 B : 10; mfxU32 G : 10; mfxU32 R : 10; mfxU32 A : 2; } mfxA2RGB10; #pragma pack(pop) /* Frame Data Info */ typedef struct { union { mfxExtBuffer **ExtParam; mfxU64 reserved2; }; mfxU16 NumExtParam; mfxU16 reserved[9]; mfxU16 MemType; mfxU16 PitchHigh; mfxU64 TimeStamp; mfxU32 FrameOrder; mfxU16 Locked; union{ mfxU16 Pitch; mfxU16 PitchLow; }; /* color planes */ union { mfxU8 *Y; mfxU16 *Y16; mfxU8 *R; }; union { mfxU8 *UV; /* for UV merged formats */ mfxU8 *VU; /* for VU merged formats */ mfxU8 *CbCr; /* for CbCr merged formats */ mfxU8 *CrCb; /* for CrCb merged formats */ mfxU8 *Cb; mfxU8 *U; mfxU16 *U16; mfxU8 *G; mfxY410 *Y410; /* for Y410 format (merged AVYU) */ }; union { mfxU8 *Cr; mfxU8 *V; mfxU16 *V16; mfxU8 *B; mfxA2RGB10 *A2RGB10; /* for A2RGB10 format (merged ARGB) */ }; mfxU8 *A; mfxMemId MemId; /* Additional Flags */ mfxU16 Corrupted; mfxU16 DataFlag; } mfxFrameData; /* Frame Surface */ typedef struct { mfxU32 reserved[4]; mfxFrameInfo Info; mfxFrameData Data; } mfxFrameSurface1; enum { MFX_TIMESTAMPCALC_UNKNOWN = 0, MFX_TIMESTAMPCALC_TELECINE = 1, }; /* Transcoding Info */ typedef struct { mfxU32 reserved[7]; mfxU16 LowPower; mfxU16 BRCParamMultiplier; mfxFrameInfo FrameInfo; mfxU32 CodecId; mfxU16 CodecProfile; mfxU16 CodecLevel; mfxU16 NumThread; union { struct { /* Encoding Options */ mfxU16 TargetUsage; mfxU16 GopPicSize; mfxU16 GopRefDist; mfxU16 GopOptFlag; mfxU16 IdrInterval; mfxU16 RateControlMethod; union { mfxU16 InitialDelayInKB; mfxU16 QPI; mfxU16 Accuracy; }; mfxU16 BufferSizeInKB; union { mfxU16 TargetKbps; mfxU16 QPP; mfxU16 ICQQuality; }; union { mfxU16 MaxKbps; mfxU16 QPB; mfxU16 Convergence; }; mfxU16 NumSlice; mfxU16 NumRefFrame; mfxU16 EncodedOrder; }; struct { /* Decoding Options */ mfxU16 DecodedOrder; mfxU16 ExtendedPicStruct; mfxU16 TimeStampCalc; mfxU16 SliceGroupsPresent; mfxU16 MaxDecFrameBuffering; mfxU16 EnableReallocRequest; mfxU16 reserved2[7]; }; struct { /* JPEG Decoding Options */ mfxU16 JPEGChromaFormat; mfxU16 Rotation; mfxU16 JPEGColorFormat; mfxU16 InterleavedDec; mfxU8 SamplingFactorH[4]; mfxU8 SamplingFactorV[4]; mfxU16 reserved3[5]; }; struct { /* JPEG Encoding Options */ mfxU16 Interleaved; mfxU16 Quality; mfxU16 RestartInterval; mfxU16 reserved5[10]; }; }; } mfxInfoMFX; typedef struct { mfxU32 reserved[8]; mfxFrameInfo In; mfxFrameInfo Out; } mfxInfoVPP; typedef struct { mfxU32 AllocId; mfxU32 reserved[2]; mfxU16 reserved3; mfxU16 AsyncDepth; union { mfxInfoMFX mfx; mfxInfoVPP vpp; }; mfxU16 Protected; mfxU16 IOPattern; mfxExtBuffer** ExtParam; mfxU16 NumExtParam; mfxU16 reserved2; } mfxVideoParam; /* IOPattern */ enum { MFX_IOPATTERN_IN_VIDEO_MEMORY = 0x01, MFX_IOPATTERN_IN_SYSTEM_MEMORY = 0x02, MFX_IOPATTERN_IN_OPAQUE_MEMORY = 0x04, MFX_IOPATTERN_OUT_VIDEO_MEMORY = 0x10, MFX_IOPATTERN_OUT_SYSTEM_MEMORY = 0x20, MFX_IOPATTERN_OUT_OPAQUE_MEMORY = 0x40 }; /* CodecId */ enum { MFX_CODEC_AVC =MFX_MAKEFOURCC('A','V','C',' '), MFX_CODEC_HEVC =MFX_MAKEFOURCC('H','E','V','C'), MFX_CODEC_MPEG2 =MFX_MAKEFOURCC('M','P','G','2'), MFX_CODEC_VC1 =MFX_MAKEFOURCC('V','C','1',' '), MFX_CODEC_CAPTURE =MFX_MAKEFOURCC('C','A','P','T'), MFX_CODEC_VP9 =MFX_MAKEFOURCC('V','P','9',' '), MFX_CODEC_AV1 =MFX_MAKEFOURCC('A','V','1',' ') }; /* CodecProfile, CodecLevel */ enum { MFX_PROFILE_UNKNOWN =0, MFX_LEVEL_UNKNOWN =0, /* AVC Profiles & Levels */ MFX_PROFILE_AVC_CONSTRAINT_SET0 = (0x100 << 0), MFX_PROFILE_AVC_CONSTRAINT_SET1 = (0x100 << 1), MFX_PROFILE_AVC_CONSTRAINT_SET2 = (0x100 << 2), MFX_PROFILE_AVC_CONSTRAINT_SET3 = (0x100 << 3), MFX_PROFILE_AVC_CONSTRAINT_SET4 = (0x100 << 4), MFX_PROFILE_AVC_CONSTRAINT_SET5 = (0x100 << 5), MFX_PROFILE_AVC_BASELINE =66, MFX_PROFILE_AVC_MAIN =77, MFX_PROFILE_AVC_EXTENDED =88, MFX_PROFILE_AVC_HIGH =100, MFX_PROFILE_AVC_HIGH_422 =122, MFX_PROFILE_AVC_CONSTRAINED_BASELINE =MFX_PROFILE_AVC_BASELINE + MFX_PROFILE_AVC_CONSTRAINT_SET1, MFX_PROFILE_AVC_CONSTRAINED_HIGH =MFX_PROFILE_AVC_HIGH + MFX_PROFILE_AVC_CONSTRAINT_SET4 + MFX_PROFILE_AVC_CONSTRAINT_SET5, MFX_PROFILE_AVC_PROGRESSIVE_HIGH =MFX_PROFILE_AVC_HIGH + MFX_PROFILE_AVC_CONSTRAINT_SET4, MFX_LEVEL_AVC_1 =10, MFX_LEVEL_AVC_1b =9, MFX_LEVEL_AVC_11 =11, MFX_LEVEL_AVC_12 =12, MFX_LEVEL_AVC_13 =13, MFX_LEVEL_AVC_2 =20, MFX_LEVEL_AVC_21 =21, MFX_LEVEL_AVC_22 =22, MFX_LEVEL_AVC_3 =30, MFX_LEVEL_AVC_31 =31, MFX_LEVEL_AVC_32 =32, MFX_LEVEL_AVC_4 =40, MFX_LEVEL_AVC_41 =41, MFX_LEVEL_AVC_42 =42, MFX_LEVEL_AVC_5 =50, MFX_LEVEL_AVC_51 =51, MFX_LEVEL_AVC_52 =52, /* MPEG-2 Profiles & Levels */ MFX_PROFILE_MPEG2_SIMPLE =0x50, MFX_PROFILE_MPEG2_MAIN =0x40, MFX_PROFILE_MPEG2_HIGH =0x10, MFX_LEVEL_MPEG2_LOW =0xA, MFX_LEVEL_MPEG2_MAIN =0x8, MFX_LEVEL_MPEG2_HIGH =0x4, MFX_LEVEL_MPEG2_HIGH1440 =0x6, /* VC1 Profiles & Levels */ MFX_PROFILE_VC1_SIMPLE =(0+1), MFX_PROFILE_VC1_MAIN =(4+1), MFX_PROFILE_VC1_ADVANCED =(12+1), /* VC1 levels for simple & main profiles */ MFX_LEVEL_VC1_LOW =(0+1), MFX_LEVEL_VC1_MEDIAN =(2+1), MFX_LEVEL_VC1_HIGH =(4+1), /* VC1 levels for the advanced profile */ MFX_LEVEL_VC1_0 =(0x00+1), MFX_LEVEL_VC1_1 =(0x01+1), MFX_LEVEL_VC1_2 =(0x02+1), MFX_LEVEL_VC1_3 =(0x03+1), MFX_LEVEL_VC1_4 =(0x04+1), /* HEVC Profiles & Levels & Tiers */ MFX_PROFILE_HEVC_MAIN =1, MFX_PROFILE_HEVC_MAIN10 =2, MFX_PROFILE_HEVC_MAINSP =3, MFX_PROFILE_HEVC_REXT =4, MFX_LEVEL_HEVC_1 = 10, MFX_LEVEL_HEVC_2 = 20, MFX_LEVEL_HEVC_21 = 21, MFX_LEVEL_HEVC_3 = 30, MFX_LEVEL_HEVC_31 = 31, MFX_LEVEL_HEVC_4 = 40, MFX_LEVEL_HEVC_41 = 41, MFX_LEVEL_HEVC_5 = 50, MFX_LEVEL_HEVC_51 = 51, MFX_LEVEL_HEVC_52 = 52, MFX_LEVEL_HEVC_6 = 60, MFX_LEVEL_HEVC_61 = 61, MFX_LEVEL_HEVC_62 = 62, MFX_TIER_HEVC_MAIN = 0, MFX_TIER_HEVC_HIGH = 0x100, /* VP9 Profiles */ MFX_PROFILE_VP9_0 = 1, MFX_PROFILE_VP9_1 = 2, MFX_PROFILE_VP9_2 = 3, MFX_PROFILE_VP9_3 = 4, }; /* GopOptFlag */ enum { MFX_GOP_CLOSED =1, MFX_GOP_STRICT =2 }; /* TargetUsages: from 1 to 7 inclusive */ enum { MFX_TARGETUSAGE_1 =1, MFX_TARGETUSAGE_2 =2, MFX_TARGETUSAGE_3 =3, MFX_TARGETUSAGE_4 =4, MFX_TARGETUSAGE_5 =5, MFX_TARGETUSAGE_6 =6, MFX_TARGETUSAGE_7 =7, MFX_TARGETUSAGE_UNKNOWN =0, MFX_TARGETUSAGE_BEST_QUALITY =MFX_TARGETUSAGE_1, MFX_TARGETUSAGE_BALANCED =MFX_TARGETUSAGE_4, MFX_TARGETUSAGE_BEST_SPEED =MFX_TARGETUSAGE_7 }; /* RateControlMethod */ enum { MFX_RATECONTROL_CBR =1, MFX_RATECONTROL_VBR =2, MFX_RATECONTROL_CQP =3, MFX_RATECONTROL_AVBR =4, MFX_RATECONTROL_RESERVED1 =5, MFX_RATECONTROL_RESERVED2 =6, MFX_RATECONTROL_RESERVED3 =100, MFX_RATECONTROL_RESERVED4 =7, MFX_RATECONTROL_LA =8, MFX_RATECONTROL_ICQ =9, MFX_RATECONTROL_VCM =10, MFX_RATECONTROL_LA_ICQ =11, MFX_RATECONTROL_LA_EXT =12, MFX_RATECONTROL_LA_HRD =13, MFX_RATECONTROL_QVBR =14, }; /* Trellis control*/ enum { MFX_TRELLIS_UNKNOWN =0, MFX_TRELLIS_OFF =0x01, MFX_TRELLIS_I =0x02, MFX_TRELLIS_P =0x04, MFX_TRELLIS_B =0x08 }; typedef struct { mfxExtBuffer Header; mfxU16 reserved1; mfxU16 RateDistortionOpt; /* tri-state option */ mfxU16 MECostType; mfxU16 MESearchType; mfxI16Pair MVSearchWindow; mfxU16 EndOfSequence; /* tri-state option */ mfxU16 FramePicture; /* tri-state option */ mfxU16 CAVLC; /* tri-state option */ mfxU16 reserved2[2]; mfxU16 RecoveryPointSEI; /* tri-state option */ mfxU16 ViewOutput; /* tri-state option */ mfxU16 NalHrdConformance; /* tri-state option */ mfxU16 SingleSeiNalUnit; /* tri-state option */ mfxU16 VuiVclHrdParameters; /* tri-state option */ mfxU16 RefPicListReordering; /* tri-state option */ mfxU16 ResetRefList; /* tri-state option */ mfxU16 RefPicMarkRep; /* tri-state option */ mfxU16 FieldOutput; /* tri-state option */ mfxU16 IntraPredBlockSize; mfxU16 InterPredBlockSize; mfxU16 MVPrecision; mfxU16 MaxDecFrameBuffering; mfxU16 AUDelimiter; /* tri-state option */ mfxU16 EndOfStream; /* tri-state option */ mfxU16 PicTimingSEI; /* tri-state option */ mfxU16 VuiNalHrdParameters; /* tri-state option */ } mfxExtCodingOption; enum { MFX_B_REF_UNKNOWN = 0, MFX_B_REF_OFF = 1, MFX_B_REF_PYRAMID = 2 }; enum { MFX_LOOKAHEAD_DS_UNKNOWN = 0, MFX_LOOKAHEAD_DS_OFF = 1, MFX_LOOKAHEAD_DS_2x = 2, MFX_LOOKAHEAD_DS_4x = 3 }; enum { MFX_BPSEI_DEFAULT = 0x00, MFX_BPSEI_IFRAME = 0x01 }; enum { MFX_SKIPFRAME_NO_SKIP = 0, MFX_SKIPFRAME_INSERT_DUMMY = 1, MFX_SKIPFRAME_INSERT_NOTHING = 2, MFX_SKIPFRAME_BRC_ONLY = 3, }; /* Intra refresh types */ enum { MFX_REFRESH_NO = 0, MFX_REFRESH_VERTICAL = 1, MFX_REFRESH_HORIZONTAL = 2, MFX_REFRESH_SLICE = 3 }; typedef struct { mfxExtBuffer Header; mfxU16 IntRefType; mfxU16 IntRefCycleSize; mfxI16 IntRefQPDelta; mfxU32 MaxFrameSize; mfxU32 MaxSliceSize; mfxU16 BitrateLimit; /* tri-state option */ mfxU16 MBBRC; /* tri-state option */ mfxU16 ExtBRC; /* tri-state option */ mfxU16 LookAheadDepth; mfxU16 Trellis; mfxU16 RepeatPPS; /* tri-state option */ mfxU16 BRefType; mfxU16 AdaptiveI; /* tri-state option */ mfxU16 AdaptiveB; /* tri-state option */ mfxU16 LookAheadDS; mfxU16 NumMbPerSlice; mfxU16 SkipFrame; mfxU8 MinQPI; /* 1..51, 0 = default */ mfxU8 MaxQPI; /* 1..51, 0 = default */ mfxU8 MinQPP; /* 1..51, 0 = default */ mfxU8 MaxQPP; /* 1..51, 0 = default */ mfxU8 MinQPB; /* 1..51, 0 = default */ mfxU8 MaxQPB; /* 1..51, 0 = default */ mfxU16 FixedFrameRate; /* tri-state option */ mfxU16 DisableDeblockingIdc; mfxU16 DisableVUI; mfxU16 BufferingPeriodSEI; mfxU16 EnableMAD; /* tri-state option */ mfxU16 UseRawRef; /* tri-state option */ } mfxExtCodingOption2; /* WeightedPred */ enum { MFX_WEIGHTED_PRED_UNKNOWN = 0, MFX_WEIGHTED_PRED_DEFAULT = 1, MFX_WEIGHTED_PRED_EXPLICIT = 2, MFX_WEIGHTED_PRED_IMPLICIT = 3 }; /* ScenarioInfo */ enum { MFX_SCENARIO_UNKNOWN = 0, MFX_SCENARIO_DISPLAY_REMOTING = 1, MFX_SCENARIO_VIDEO_CONFERENCE = 2, MFX_SCENARIO_ARCHIVE = 3, MFX_SCENARIO_LIVE_STREAMING = 4, MFX_SCENARIO_CAMERA_CAPTURE = 5 }; /* ContentInfo */ enum { MFX_CONTENT_UNKNOWN = 0, MFX_CONTENT_FULL_SCREEN_VIDEO = 1, MFX_CONTENT_NON_VIDEO_SCREEN = 2 }; /* PRefType */ enum { MFX_P_REF_DEFAULT = 0, MFX_P_REF_SIMPLE = 1, MFX_P_REF_PYRAMID = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 NumSliceI; mfxU16 NumSliceP; mfxU16 NumSliceB; mfxU16 WinBRCMaxAvgKbps; mfxU16 WinBRCSize; mfxU16 QVBRQuality; mfxU16 EnableMBQP; mfxU16 IntRefCycleDist; mfxU16 DirectBiasAdjustment; /* tri-state option */ mfxU16 GlobalMotionBiasAdjustment; /* tri-state option */ mfxU16 MVCostScalingFactor; mfxU16 MBDisableSkipMap; /* tri-state option */ mfxU16 WeightedPred; mfxU16 WeightedBiPred; mfxU16 AspectRatioInfoPresent; /* tri-state option */ mfxU16 OverscanInfoPresent; /* tri-state option */ mfxU16 OverscanAppropriate; /* tri-state option */ mfxU16 TimingInfoPresent; /* tri-state option */ mfxU16 BitstreamRestriction; /* tri-state option */ mfxU16 LowDelayHrd; /* tri-state option */ mfxU16 MotionVectorsOverPicBoundaries; /* tri-state option */ mfxU16 reserved1[2]; mfxU16 ScenarioInfo; mfxU16 ContentInfo; mfxU16 PRefType; mfxU16 FadeDetection; /* tri-state option */ mfxU16 reserved2[2]; mfxU16 GPB; /* tri-state option */ mfxU32 MaxFrameSizeI; mfxU32 MaxFrameSizeP; mfxU32 reserved3[3]; mfxU16 EnableQPOffset; /* tri-state option */ mfxI16 QPOffset[8]; /* FrameQP = QPX + QPOffset[pyramid_layer]; QPX = QPB for B-pyramid, QPP for P-pyramid */ mfxU16 NumRefActiveP[8]; mfxU16 NumRefActiveBL0[8]; mfxU16 NumRefActiveBL1[8]; mfxU16 reserved6; mfxU16 TransformSkip; /* tri-state option; HEVC transform_skip_enabled_flag */ mfxU16 TargetChromaFormatPlus1; /* Minus 1 specifies target encoding chroma format (see ColorFormat enum). May differ from input one. */ mfxU16 TargetBitDepthLuma; /* Target encoding bit depth for luma samples. May differ from input one. */ mfxU16 TargetBitDepthChroma; /* Target encoding bit depth for chroma samples. May differ from input one. */ mfxU16 BRCPanicMode; /* tri-state option */ mfxU16 LowDelayBRC; /* tri-state option */ mfxU16 EnableMBForceIntra; /* tri-state option */ mfxU16 AdaptiveMaxFrameSize; /* tri-state option */ mfxU16 RepartitionCheckEnable; /* tri-state option */ mfxU16 reserved5[3]; mfxU16 EncodedUnitsInfo; /* tri-state option */ mfxU16 EnableNalUnitType; /* tri-state option */ mfxU16 ExtBrcAdaptiveLTR; /* tri-state option for ExtBRC */ mfxU16 reserved[163]; } mfxExtCodingOption3; /* IntraPredBlockSize/InterPredBlockSize */ enum { MFX_BLOCKSIZE_UNKNOWN = 0, MFX_BLOCKSIZE_MIN_16X16 = 1, /* 16x16 */ MFX_BLOCKSIZE_MIN_8X8 = 2, /* 16x16, 8x8 */ MFX_BLOCKSIZE_MIN_4X4 = 3 /* 16x16, 8x8, 4x4 */ }; /* MVPrecision */ enum { MFX_MVPRECISION_UNKNOWN = 0, MFX_MVPRECISION_INTEGER = (1 << 0), MFX_MVPRECISION_HALFPEL = (1 << 1), MFX_MVPRECISION_QUARTERPEL = (1 << 2) }; enum { MFX_CODINGOPTION_UNKNOWN =0, MFX_CODINGOPTION_ON =0x10, MFX_CODINGOPTION_OFF =0x20, MFX_CODINGOPTION_ADAPTIVE =0x30 }; /* Data Flag for mfxBitstream*/ enum { MFX_BITSTREAM_COMPLETE_FRAME = 0x0001, /* the bitstream contains a complete frame or field pair of data */ MFX_BITSTREAM_EOS = 0x0002 }; /* Extended Buffer Ids */ enum { MFX_EXTBUFF_CODING_OPTION = MFX_MAKEFOURCC('C','D','O','P'), MFX_EXTBUFF_CODING_OPTION_SPSPPS = MFX_MAKEFOURCC('C','O','S','P'), MFX_EXTBUFF_VPP_DONOTUSE = MFX_MAKEFOURCC('N','U','S','E'), MFX_EXTBUFF_VPP_AUXDATA = MFX_MAKEFOURCC('A','U','X','D'), MFX_EXTBUFF_VPP_DENOISE = MFX_MAKEFOURCC('D','N','I','S'), MFX_EXTBUFF_VPP_SCENE_ANALYSIS = MFX_MAKEFOURCC('S','C','L','Y'), MFX_EXTBUFF_VPP_SCENE_CHANGE = MFX_EXTBUFF_VPP_SCENE_ANALYSIS, MFX_EXTBUFF_VPP_PROCAMP = MFX_MAKEFOURCC('P','A','M','P'), MFX_EXTBUFF_VPP_DETAIL = MFX_MAKEFOURCC('D','E','T',' '), MFX_EXTBUFF_VIDEO_SIGNAL_INFO = MFX_MAKEFOURCC('V','S','I','N'), MFX_EXTBUFF_VPP_DOUSE = MFX_MAKEFOURCC('D','U','S','E'), MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION = MFX_MAKEFOURCC('O','P','Q','S'), MFX_EXTBUFF_AVC_REFLIST_CTRL = MFX_MAKEFOURCC('R','L','S','T'), MFX_EXTBUFF_VPP_FRAME_RATE_CONVERSION = MFX_MAKEFOURCC('F','R','C',' '), MFX_EXTBUFF_PICTURE_TIMING_SEI = MFX_MAKEFOURCC('P','T','S','E'), MFX_EXTBUFF_AVC_TEMPORAL_LAYERS = MFX_MAKEFOURCC('A','T','M','L'), MFX_EXTBUFF_CODING_OPTION2 = MFX_MAKEFOURCC('C','D','O','2'), MFX_EXTBUFF_VPP_IMAGE_STABILIZATION = MFX_MAKEFOURCC('I','S','T','B'), MFX_EXTBUFF_VPP_PICSTRUCT_DETECTION = MFX_MAKEFOURCC('I','D','E','T'), MFX_EXTBUFF_ENCODER_CAPABILITY = MFX_MAKEFOURCC('E','N','C','P'), MFX_EXTBUFF_ENCODER_RESET_OPTION = MFX_MAKEFOURCC('E','N','R','O'), MFX_EXTBUFF_ENCODED_FRAME_INFO = MFX_MAKEFOURCC('E','N','F','I'), MFX_EXTBUFF_VPP_COMPOSITE = MFX_MAKEFOURCC('V','C','M','P'), MFX_EXTBUFF_VPP_VIDEO_SIGNAL_INFO = MFX_MAKEFOURCC('V','V','S','I'), MFX_EXTBUFF_ENCODER_ROI = MFX_MAKEFOURCC('E','R','O','I'), MFX_EXTBUFF_VPP_DEINTERLACING = MFX_MAKEFOURCC('V','P','D','I'), MFX_EXTBUFF_AVC_REFLISTS = MFX_MAKEFOURCC('R','L','T','S'), MFX_EXTBUFF_DEC_VIDEO_PROCESSING = MFX_MAKEFOURCC('D','E','C','V'), MFX_EXTBUFF_VPP_FIELD_PROCESSING = MFX_MAKEFOURCC('F','P','R','O'), MFX_EXTBUFF_CODING_OPTION3 = MFX_MAKEFOURCC('C','D','O','3'), MFX_EXTBUFF_CHROMA_LOC_INFO = MFX_MAKEFOURCC('C','L','I','N'), MFX_EXTBUFF_MBQP = MFX_MAKEFOURCC('M','B','Q','P'), MFX_EXTBUFF_MB_FORCE_INTRA = MFX_MAKEFOURCC('M','B','F','I'), MFX_EXTBUFF_HEVC_TILES = MFX_MAKEFOURCC('2','6','5','T'), MFX_EXTBUFF_MB_DISABLE_SKIP_MAP = MFX_MAKEFOURCC('M','D','S','M'), MFX_EXTBUFF_HEVC_PARAM = MFX_MAKEFOURCC('2','6','5','P'), MFX_EXTBUFF_DECODED_FRAME_INFO = MFX_MAKEFOURCC('D','E','F','I'), MFX_EXTBUFF_TIME_CODE = MFX_MAKEFOURCC('T','M','C','D'), MFX_EXTBUFF_HEVC_REGION = MFX_MAKEFOURCC('2','6','5','R'), MFX_EXTBUFF_PRED_WEIGHT_TABLE = MFX_MAKEFOURCC('E','P','W','T'), MFX_EXTBUFF_DIRTY_RECTANGLES = MFX_MAKEFOURCC('D','R','O','I'), MFX_EXTBUFF_MOVING_RECTANGLES = MFX_MAKEFOURCC('M','R','O','I'), MFX_EXTBUFF_CODING_OPTION_VPS = MFX_MAKEFOURCC('C','O','V','P'), MFX_EXTBUFF_VPP_ROTATION = MFX_MAKEFOURCC('R','O','T',' '), MFX_EXTBUFF_ENCODED_SLICES_INFO = MFX_MAKEFOURCC('E','N','S','I'), MFX_EXTBUFF_VPP_SCALING = MFX_MAKEFOURCC('V','S','C','L'), MFX_EXTBUFF_HEVC_REFLIST_CTRL = MFX_EXTBUFF_AVC_REFLIST_CTRL, MFX_EXTBUFF_HEVC_REFLISTS = MFX_EXTBUFF_AVC_REFLISTS, MFX_EXTBUFF_HEVC_TEMPORAL_LAYERS = MFX_EXTBUFF_AVC_TEMPORAL_LAYERS, MFX_EXTBUFF_VPP_MIRRORING = MFX_MAKEFOURCC('M','I','R','R'), MFX_EXTBUFF_MV_OVER_PIC_BOUNDARIES = MFX_MAKEFOURCC('M','V','P','B'), MFX_EXTBUFF_VPP_COLORFILL = MFX_MAKEFOURCC('V','C','L','F'), MFX_EXTBUFF_DECODE_ERROR_REPORT = MFX_MAKEFOURCC('D', 'E', 'R', 'R'), MFX_EXTBUFF_VPP_COLOR_CONVERSION = MFX_MAKEFOURCC('V', 'C', 'S', 'C'), MFX_EXTBUFF_CONTENT_LIGHT_LEVEL_INFO = MFX_MAKEFOURCC('L', 'L', 'I', 'S'), MFX_EXTBUFF_MASTERING_DISPLAY_COLOUR_VOLUME = MFX_MAKEFOURCC('D', 'C', 'V', 'S'), MFX_EXTBUFF_MULTI_FRAME_PARAM = MFX_MAKEFOURCC('M', 'F', 'R', 'P'), MFX_EXTBUFF_MULTI_FRAME_CONTROL = MFX_MAKEFOURCC('M', 'F', 'R', 'C'), MFX_EXTBUFF_ENCODED_UNITS_INFO = MFX_MAKEFOURCC('E', 'N', 'U', 'I'), MFX_EXTBUFF_VPP_MCTF = MFX_MAKEFOURCC('M', 'C', 'T', 'F'), MFX_EXTBUFF_VP9_SEGMENTATION = MFX_MAKEFOURCC('9', 'S', 'E', 'G'), MFX_EXTBUFF_VP9_TEMPORAL_LAYERS = MFX_MAKEFOURCC('9', 'T', 'M', 'L'), MFX_EXTBUFF_VP9_PARAM = MFX_MAKEFOURCC('9', 'P', 'A', 'R'), MFX_EXTBUFF_AVC_ROUNDING_OFFSET = MFX_MAKEFOURCC('R','N','D','O'), }; /* VPP Conf: Do not use certain algorithms */ typedef struct { mfxExtBuffer Header; mfxU32 NumAlg; mfxU32* AlgList; } mfxExtVPPDoNotUse; typedef struct { mfxExtBuffer Header; mfxU16 DenoiseFactor; } mfxExtVPPDenoise; typedef struct { mfxExtBuffer Header; mfxU16 DetailFactor; } mfxExtVPPDetail; typedef struct { mfxExtBuffer Header; mfxF64 Brightness; mfxF64 Contrast; mfxF64 Hue; mfxF64 Saturation; } mfxExtVPPProcAmp; /* statistics collected for decode, encode and vpp */ typedef struct { mfxU32 reserved[16]; mfxU32 NumFrame; mfxU64 NumBit; mfxU32 NumCachedFrame; } mfxEncodeStat; typedef struct { mfxU32 reserved[16]; mfxU32 NumFrame; mfxU32 NumSkippedFrame; mfxU32 NumError; mfxU32 NumCachedFrame; } mfxDecodeStat; typedef struct { mfxU32 reserved[16]; mfxU32 NumFrame; mfxU32 NumCachedFrame; } mfxVPPStat; typedef struct { mfxExtBuffer Header; union{ struct{ mfxU32 SpatialComplexity; mfxU32 TemporalComplexity; }; struct{ mfxU16 PicStruct; mfxU16 reserved[3]; }; }; mfxU16 SceneChangeRate; mfxU16 RepeatedFrame; } mfxExtVppAuxData; /* CtrlFlags */ enum { MFX_PAYLOAD_CTRL_SUFFIX = 0x00000001 /* HEVC suffix SEI */ }; typedef struct { mfxU32 CtrlFlags; mfxU32 reserved[3]; mfxU8 *Data; /* buffer pointer */ mfxU32 NumBit; /* number of bits */ mfxU16 Type; /* SEI message type in H.264 or user data start_code in MPEG-2 */ mfxU16 BufSize; /* payload buffer size in bytes */ } mfxPayload; typedef struct { mfxExtBuffer Header; mfxU32 reserved[4]; mfxU16 reserved1; mfxU16 MfxNalUnitType; mfxU16 SkipFrame; mfxU16 QP; /* per frame QP */ mfxU16 FrameType; mfxU16 NumExtParam; mfxU16 NumPayload; /* MPEG-2 user data or H.264 SEI message(s) */ mfxU16 reserved2; mfxExtBuffer **ExtParam; mfxPayload **Payload; /* for field pair, first field uses even payloads and second field uses odd payloads */ } mfxEncodeCtrl; /* Buffer Memory Types */ enum { /* Buffer types */ MFX_MEMTYPE_PERSISTENT_MEMORY =0x0002 }; /* Frame Memory Types */ #define MFX_MEMTYPE_BASE(x) (0x90ff & (x)) enum { MFX_MEMTYPE_DXVA2_DECODER_TARGET =0x0010, MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET =0x0020, MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET = MFX_MEMTYPE_DXVA2_DECODER_TARGET, MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET = MFX_MEMTYPE_DXVA2_PROCESSOR_TARGET, MFX_MEMTYPE_SYSTEM_MEMORY =0x0040, MFX_MEMTYPE_RESERVED1 =0x0080, MFX_MEMTYPE_FROM_ENCODE = 0x0100, MFX_MEMTYPE_FROM_DECODE = 0x0200, MFX_MEMTYPE_FROM_VPPIN = 0x0400, MFX_MEMTYPE_FROM_VPPOUT = 0x0800, MFX_MEMTYPE_FROM_ENC = 0x2000, MFX_MEMTYPE_FROM_PAK = 0x4000, //reserved MFX_MEMTYPE_INTERNAL_FRAME = 0x0001, MFX_MEMTYPE_EXTERNAL_FRAME = 0x0002, MFX_MEMTYPE_OPAQUE_FRAME = 0x0004, MFX_MEMTYPE_EXPORT_FRAME = 0x0008, MFX_MEMTYPE_SHARED_RESOURCE = MFX_MEMTYPE_EXPORT_FRAME, MFX_MEMTYPE_VIDEO_MEMORY_ENCODER_TARGET = 0x1000 }; typedef struct { union { mfxU32 AllocId; mfxU32 reserved[1]; }; mfxU32 reserved3[3]; mfxFrameInfo Info; mfxU16 Type; /* decoder or processor render targets */ mfxU16 NumFrameMin; mfxU16 NumFrameSuggested; mfxU16 reserved2; } mfxFrameAllocRequest; typedef struct { mfxU32 AllocId; mfxU32 reserved[3]; mfxMemId *mids; /* the array allocated by application */ mfxU16 NumFrameActual; mfxU16 reserved2; } mfxFrameAllocResponse; /* FrameType */ enum { MFX_FRAMETYPE_UNKNOWN =0x0000, MFX_FRAMETYPE_I =0x0001, MFX_FRAMETYPE_P =0x0002, MFX_FRAMETYPE_B =0x0004, MFX_FRAMETYPE_S =0x0008, MFX_FRAMETYPE_REF =0x0040, MFX_FRAMETYPE_IDR =0x0080, MFX_FRAMETYPE_xI =0x0100, MFX_FRAMETYPE_xP =0x0200, MFX_FRAMETYPE_xB =0x0400, MFX_FRAMETYPE_xS =0x0800, MFX_FRAMETYPE_xREF =0x4000, MFX_FRAMETYPE_xIDR =0x8000 }; enum { MFX_HEVC_NALU_TYPE_UNKNOWN = 0, MFX_HEVC_NALU_TYPE_TRAIL_N = ( 0+1), MFX_HEVC_NALU_TYPE_TRAIL_R = ( 1+1), MFX_HEVC_NALU_TYPE_RADL_N = ( 6+1), MFX_HEVC_NALU_TYPE_RADL_R = ( 7+1), MFX_HEVC_NALU_TYPE_RASL_N = ( 8+1), MFX_HEVC_NALU_TYPE_RASL_R = ( 9+1), MFX_HEVC_NALU_TYPE_IDR_W_RADL = (19+1), MFX_HEVC_NALU_TYPE_IDR_N_LP = (20+1), MFX_HEVC_NALU_TYPE_CRA_NUT = (21+1) }; typedef enum { MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9 =1, /* IDirect3DDeviceManager9 */ MFX_HANDLE_D3D9_DEVICE_MANAGER = MFX_HANDLE_DIRECT3D_DEVICE_MANAGER9, MFX_HANDLE_RESERVED1 = 2, MFX_HANDLE_D3D11_DEVICE = 3, MFX_HANDLE_VA_DISPLAY = 4, MFX_HANDLE_RESERVED3 = 5, } mfxHandleType; typedef enum { MFX_SKIPMODE_NOSKIP=0, MFX_SKIPMODE_MORE=1, MFX_SKIPMODE_LESS=2 } mfxSkipMode; typedef struct { mfxExtBuffer Header; mfxU8 *SPSBuffer; mfxU8 *PPSBuffer; mfxU16 SPSBufSize; mfxU16 PPSBufSize; mfxU16 SPSId; mfxU16 PPSId; } mfxExtCodingOptionSPSPPS; typedef struct { mfxExtBuffer Header; union { mfxU8 *VPSBuffer; mfxU64 reserved1; }; mfxU16 VPSBufSize; mfxU16 VPSId; mfxU16 reserved[6]; } mfxExtCodingOptionVPS; typedef struct { mfxExtBuffer Header; mfxU16 VideoFormat; mfxU16 VideoFullRange; mfxU16 ColourDescriptionPresent; mfxU16 ColourPrimaries; mfxU16 TransferCharacteristics; mfxU16 MatrixCoefficients; } mfxExtVideoSignalInfo; typedef struct { mfxExtBuffer Header; mfxU32 NumAlg; mfxU32 *AlgList; } mfxExtVPPDoUse; typedef struct { mfxExtBuffer Header; mfxU32 reserved1[2]; struct { mfxFrameSurface1 **Surfaces; mfxU32 reserved2[5]; mfxU16 Type; mfxU16 NumSurface; } In, Out; } mfxExtOpaqueSurfaceAlloc; typedef struct { mfxExtBuffer Header; mfxU16 NumRefIdxL0Active; mfxU16 NumRefIdxL1Active; struct { mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 ViewId; mfxU16 LongTermIdx; mfxU16 reserved[3]; } PreferredRefList[32], RejectedRefList[16], LongTermRefList[16]; mfxU16 ApplyLongTermIdx; mfxU16 reserved[15]; } mfxExtAVCRefListCtrl; enum { MFX_FRCALGM_PRESERVE_TIMESTAMP = 0x0001, MFX_FRCALGM_DISTRIBUTED_TIMESTAMP = 0x0002, MFX_FRCALGM_FRAME_INTERPOLATION = 0x0004 }; typedef struct { mfxExtBuffer Header; mfxU16 Algorithm; mfxU16 reserved; mfxU32 reserved2[15]; } mfxExtVPPFrameRateConversion; enum { MFX_IMAGESTAB_MODE_UPSCALE = 0x0001, MFX_IMAGESTAB_MODE_BOXING = 0x0002 }; typedef struct { mfxExtBuffer Header; mfxU16 Mode; mfxU16 reserved[11]; } mfxExtVPPImageStab; enum { MFX_PAYLOAD_OFF = 0, MFX_PAYLOAD_IDR = 1 }; typedef struct { mfxExtBuffer Header; mfxU16 reserved[15]; mfxU16 InsertPayloadToggle; mfxU16 DisplayPrimariesX[3]; mfxU16 DisplayPrimariesY[3]; mfxU16 WhitePointX; mfxU16 WhitePointY; mfxU32 MaxDisplayMasteringLuminance; mfxU32 MinDisplayMasteringLuminance; } mfxExtMasteringDisplayColourVolume; typedef struct { mfxExtBuffer Header; mfxU16 reserved[9]; mfxU16 InsertPayloadToggle; mfxU16 MaxContentLightLevel; mfxU16 MaxPicAverageLightLevel; } mfxExtContentLightLevelInfo; typedef struct { mfxExtBuffer Header; mfxU32 reserved[14]; struct { mfxU16 ClockTimestampFlag; mfxU16 CtType; mfxU16 NuitFieldBasedFlag; mfxU16 CountingType; mfxU16 FullTimestampFlag; mfxU16 DiscontinuityFlag; mfxU16 CntDroppedFlag; mfxU16 NFrames; mfxU16 SecondsFlag; mfxU16 MinutesFlag; mfxU16 HoursFlag; mfxU16 SecondsValue; mfxU16 MinutesValue; mfxU16 HoursValue; mfxU32 TimeOffset; } TimeStamp[3]; } mfxExtPictureTimingSEI; typedef struct { mfxExtBuffer Header; mfxU32 reserved1[4]; mfxU16 reserved2; mfxU16 BaseLayerPID; struct { mfxU16 Scale; mfxU16 reserved[3]; }Layer[8]; } mfxExtAvcTemporalLayers; typedef struct { mfxExtBuffer Header; mfxU32 MBPerSec; mfxU16 reserved[58]; } mfxExtEncoderCapability; typedef struct { mfxExtBuffer Header; mfxU16 StartNewSequence; mfxU16 reserved[11]; } mfxExtEncoderResetOption; /*LongTermIdx*/ enum { MFX_LONGTERM_IDX_NO_IDX = 0xFFFF }; typedef struct { mfxExtBuffer Header; mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 LongTermIdx; mfxU32 MAD; mfxU16 BRCPanicMode; mfxU16 QP; mfxU32 SecondFieldOffset; mfxU16 reserved[2]; struct { mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 LongTermIdx; mfxU16 reserved[4]; } UsedRefListL0[32], UsedRefListL1[32]; } mfxExtAVCEncodedFrameInfo; typedef struct mfxVPPCompInputStream { mfxU32 DstX; mfxU32 DstY; mfxU32 DstW; mfxU32 DstH; mfxU16 LumaKeyEnable; mfxU16 LumaKeyMin; mfxU16 LumaKeyMax; mfxU16 GlobalAlphaEnable; mfxU16 GlobalAlpha; mfxU16 PixelAlphaEnable; mfxU16 TileId; mfxU16 reserved2[17]; } mfxVPPCompInputStream; typedef struct { mfxExtBuffer Header; /* background color*/ union { mfxU16 Y; mfxU16 R; }; union { mfxU16 U; mfxU16 G; }; union { mfxU16 V; mfxU16 B; }; mfxU16 NumTiles; mfxU16 reserved1[23]; mfxU16 NumInputStream; mfxVPPCompInputStream *InputStream; } mfxExtVPPComposite; /* TransferMatrix */ enum { MFX_TRANSFERMATRIX_UNKNOWN = 0, MFX_TRANSFERMATRIX_BT709 = 1, MFX_TRANSFERMATRIX_BT601 = 2 }; /* NominalRange */ enum { MFX_NOMINALRANGE_UNKNOWN = 0, MFX_NOMINALRANGE_0_255 = 1, MFX_NOMINALRANGE_16_235 = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 reserved1[4]; union { struct { // Init struct { mfxU16 TransferMatrix; mfxU16 NominalRange; mfxU16 reserved2[6]; } In, Out; }; struct { // Runtime mfxU16 TransferMatrix; mfxU16 NominalRange; mfxU16 reserved3[14]; }; }; } mfxExtVPPVideoSignalInfo; /* ROI encoding mode */ enum { MFX_ROI_MODE_PRIORITY = 0, MFX_ROI_MODE_QP_DELTA = 1 }; typedef struct { mfxExtBuffer Header; mfxU16 NumROI; mfxU16 ROIMode; mfxU16 reserved1[10]; struct { mfxU32 Left; mfxU32 Top; mfxU32 Right; mfxU32 Bottom; union { mfxI16 Priority; mfxI16 DeltaQP; }; mfxU16 reserved2[7]; } ROI[256]; } mfxExtEncoderROI; /*Deinterlacing Mode*/ enum { MFX_DEINTERLACING_BOB = 1, MFX_DEINTERLACING_ADVANCED = 2, MFX_DEINTERLACING_AUTO_DOUBLE = 3, MFX_DEINTERLACING_AUTO_SINGLE = 4, MFX_DEINTERLACING_FULL_FR_OUT = 5, MFX_DEINTERLACING_HALF_FR_OUT = 6, MFX_DEINTERLACING_24FPS_OUT = 7, MFX_DEINTERLACING_FIXED_TELECINE_PATTERN = 8, MFX_DEINTERLACING_30FPS_OUT = 9, MFX_DEINTERLACING_DETECT_INTERLACE = 10, MFX_DEINTERLACING_ADVANCED_NOREF = 11, MFX_DEINTERLACING_ADVANCED_SCD = 12, MFX_DEINTERLACING_FIELD_WEAVING = 13 }; /*TelecinePattern*/ enum { MFX_TELECINE_PATTERN_32 = 0, MFX_TELECINE_PATTERN_2332 = 1, MFX_TELECINE_PATTERN_FRAME_REPEAT = 2, MFX_TELECINE_PATTERN_41 = 3, MFX_TELECINE_POSITION_PROVIDED = 4 }; typedef struct { mfxExtBuffer Header; mfxU16 Mode; mfxU16 TelecinePattern; mfxU16 TelecineLocation; mfxU16 reserved[9]; } mfxExtVPPDeinterlacing; typedef struct { mfxExtBuffer Header; mfxU16 NumRefIdxL0Active; mfxU16 NumRefIdxL1Active; mfxU16 reserved[2]; struct mfxRefPic{ mfxU32 FrameOrder; mfxU16 PicStruct; mfxU16 reserved[5]; } RefPicList0[32], RefPicList1[32]; }mfxExtAVCRefLists; enum { MFX_VPP_COPY_FRAME =0x01, MFX_VPP_COPY_FIELD =0x02, MFX_VPP_SWAP_FIELDS =0x03 }; /*PicType*/ enum { MFX_PICTYPE_UNKNOWN =0x00, MFX_PICTYPE_FRAME =0x01, MFX_PICTYPE_TOPFIELD =0x02, MFX_PICTYPE_BOTTOMFIELD =0x04 }; typedef struct { mfxExtBuffer Header; mfxU16 Mode; mfxU16 InField; mfxU16 OutField; mfxU16 reserved[25]; } mfxExtVPPFieldProcessing; typedef struct { mfxExtBuffer Header; struct mfxIn{ mfxU16 CropX; mfxU16 CropY; mfxU16 CropW; mfxU16 CropH; mfxU16 reserved[12]; }In; struct mfxOut{ mfxU32 FourCC; mfxU16 ChromaFormat; mfxU16 reserved1; mfxU16 Width; mfxU16 Height; mfxU16 CropX; mfxU16 CropY; mfxU16 CropW; mfxU16 CropH; mfxU16 reserved[22]; }Out; mfxU16 reserved[13]; } mfxExtDecVideoProcessing; typedef struct { mfxExtBuffer Header; mfxU16 ChromaLocInfoPresentFlag; mfxU16 ChromaSampleLocTypeTopField; mfxU16 ChromaSampleLocTypeBottomField; mfxU16 reserved[9]; } mfxExtChromaLocInfo; /* MBQPMode */ enum { MFX_MBQP_MODE_QP_VALUE = 0, // supported in CQP mode only MFX_MBQP_MODE_QP_DELTA = 1 }; typedef struct { mfxExtBuffer Header; mfxU32 reserved[10]; mfxU16 Mode; // see MBQPMode enum mfxU16 BlockSize; // QP block size, valid for HEVC only during Init and Runtime mfxU32 NumQPAlloc; // Size of allocated by application QP or DeltaQP array union { mfxU8 *QP; // Block QP value. Valid when Mode = MFX_MBQP_MODE_QP_VALUE mfxI8 *DeltaQP; // For block i: QP[i] = BrcQP[i] + DeltaQP[i]. Valid when Mode = MFX_MBQP_MODE_QP_DELTA mfxU64 reserved2; }; } mfxExtMBQP; typedef struct { mfxExtBuffer Header; mfxU32 reserved[11]; mfxU32 MapSize; union { mfxU8 *Map; mfxU64 reserved2; }; } mfxExtMBForceIntra; typedef struct { mfxExtBuffer Header; mfxU16 NumTileRows; mfxU16 NumTileColumns; mfxU16 reserved[74]; }mfxExtHEVCTiles; typedef struct { mfxExtBuffer Header; mfxU32 reserved[11]; mfxU32 MapSize; union { mfxU8 *Map; mfxU64 reserved2; }; } mfxExtMBDisableSkipMap; /*GeneralConstraintFlags*/ enum { /* REXT Profile constraint flags*/ MFX_HEVC_CONSTR_REXT_MAX_12BIT = (1 << 0), MFX_HEVC_CONSTR_REXT_MAX_10BIT = (1 << 1), MFX_HEVC_CONSTR_REXT_MAX_8BIT = (1 << 2), MFX_HEVC_CONSTR_REXT_MAX_422CHROMA = (1 << 3), MFX_HEVC_CONSTR_REXT_MAX_420CHROMA = (1 << 4), MFX_HEVC_CONSTR_REXT_MAX_MONOCHROME = (1 << 5), MFX_HEVC_CONSTR_REXT_INTRA = (1 << 6), MFX_HEVC_CONSTR_REXT_ONE_PICTURE_ONLY = (1 << 7), MFX_HEVC_CONSTR_REXT_LOWER_BIT_RATE = (1 << 8) }; /* SampleAdaptiveOffset */ enum { MFX_SAO_UNKNOWN = 0x00, MFX_SAO_DISABLE = 0x01, MFX_SAO_ENABLE_LUMA = 0x02, MFX_SAO_ENABLE_CHROMA = 0x04 }; #pragma pack(push, 4) typedef struct { mfxExtBuffer Header; mfxU16 PicWidthInLumaSamples; mfxU16 PicHeightInLumaSamples; mfxU64 GeneralConstraintFlags; mfxU16 SampleAdaptiveOffset; /* see enum SampleAdaptiveOffset, valid during Init and Runtime */ mfxU16 LCUSize; mfxU16 reserved[116]; } mfxExtHEVCParam; #pragma pack(pop) /*ErrorTypes in mfxExtDecodeErrorReport*/ enum { MFX_ERROR_PPS = (1 << 0), MFX_ERROR_SPS = (1 << 1), MFX_ERROR_SLICEHEADER = (1 << 2), MFX_ERROR_SLICEDATA = (1 << 3), MFX_ERROR_FRAME_GAP = (1 << 4), }; typedef struct { mfxExtBuffer Header; mfxU32 ErrorTypes; mfxU16 reserved[10]; } mfxExtDecodeErrorReport; typedef struct { mfxExtBuffer Header; mfxU16 FrameType; mfxU16 reserved[59]; } mfxExtDecodedFrameInfo; typedef struct { mfxExtBuffer Header; mfxU16 DropFrameFlag; mfxU16 TimeCodeHours; mfxU16 TimeCodeMinutes; mfxU16 TimeCodeSeconds; mfxU16 TimeCodePictures; mfxU16 reserved[7]; } mfxExtTimeCode; /*RegionType*/ enum { MFX_HEVC_REGION_SLICE = 0 }; /*RegionEncoding*/ enum { MFX_HEVC_REGION_ENCODING_ON = 0, MFX_HEVC_REGION_ENCODING_OFF = 1 }; typedef struct { mfxExtBuffer Header; mfxU32 RegionId; mfxU16 RegionType; mfxU16 RegionEncoding; mfxU16 reserved[24]; } mfxExtHEVCRegion; typedef struct { mfxExtBuffer Header; mfxU16 LumaLog2WeightDenom; // 0..7 mfxU16 ChromaLog2WeightDenom; // 0..7 mfxU16 LumaWeightFlag[2][32]; // [list] 0,1 mfxU16 ChromaWeightFlag[2][32]; // [list] 0,1 mfxI16 Weights[2][32][3][2]; // [list][list entry][Y, Cb, Cr][weight, offset] mfxU16 reserved[58]; } mfxExtPredWeightTable; typedef struct { mfxExtBuffer Header; mfxU16 EnableRoundingIntra; // tri-state option mfxU16 RoundingOffsetIntra; // valid value [0,7] mfxU16 EnableRoundingInter; // tri-state option mfxU16 RoundingOffsetInter; // valid value [0,7] mfxU16 reserved[24]; } mfxExtAVCRoundingOffset; typedef struct { mfxExtBuffer Header; mfxU16 NumRect; mfxU16 reserved1[11]; struct { mfxU32 Left; mfxU32 Top; mfxU32 Right; mfxU32 Bottom; mfxU16 reserved2[8]; } Rect[256]; } mfxExtDirtyRect; typedef struct { mfxExtBuffer Header; mfxU16 NumRect; mfxU16 reserved1[11]; struct { mfxU32 DestLeft; mfxU32 DestTop; mfxU32 DestRight; mfxU32 DestBottom; mfxU32 SourceLeft; mfxU32 SourceTop; mfxU16 reserved2[4]; } Rect[256]; } mfxExtMoveRect; /* Angle */ enum { MFX_ANGLE_0 = 0, MFX_ANGLE_90 = 90, MFX_ANGLE_180 = 180, MFX_ANGLE_270 = 270 }; typedef struct { mfxExtBuffer Header; mfxU16 Angle; mfxU16 reserved[11]; } mfxExtVPPRotation; typedef struct { mfxExtBuffer Header; mfxU16 SliceSizeOverflow; mfxU16 NumSliceNonCopliant; mfxU16 NumEncodedSlice; mfxU16 NumSliceSizeAlloc; union { mfxU16 *SliceSize; mfxU64 reserved1; }; mfxU16 reserved[20]; } mfxExtEncodedSlicesInfo; /* ScalingMode */ enum { MFX_SCALING_MODE_DEFAULT = 0, MFX_SCALING_MODE_LOWPOWER = 1, MFX_SCALING_MODE_QUALITY = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 ScalingMode; mfxU16 reserved[11]; } mfxExtVPPScaling; typedef mfxExtAVCRefListCtrl mfxExtHEVCRefListCtrl; typedef mfxExtAVCRefLists mfxExtHEVCRefLists; typedef mfxExtAvcTemporalLayers mfxExtHEVCTemporalLayers; /* MirroringType */ enum { MFX_MIRRORING_DISABLED = 0, MFX_MIRRORING_HORIZONTAL = 1, MFX_MIRRORING_VERTICAL = 2 }; typedef struct { mfxExtBuffer Header; mfxU16 Type; mfxU16 reserved[11]; } mfxExtVPPMirroring; typedef struct { mfxExtBuffer Header; mfxU16 StickTop; /* tri-state option */ mfxU16 StickBottom; /* tri-state option */ mfxU16 StickLeft; /* tri-state option */ mfxU16 StickRight; /* tri-state option */ mfxU16 reserved[8]; } mfxExtMVOverPicBoundaries; typedef struct { mfxExtBuffer Header; mfxU16 Enable; /* tri-state option */ mfxU16 reserved[11]; } mfxExtVPPColorFill; /* ChromaSiting */ enum { MFX_CHROMA_SITING_UNKNOWN = 0x0000, MFX_CHROMA_SITING_VERTICAL_TOP = 0x0001, /* Chroma samples are co-sited vertically on the top with the luma samples. */ MFX_CHROMA_SITING_VERTICAL_CENTER = 0x0002, /* Chroma samples are not co-sited vertically with the luma samples. */ MFX_CHROMA_SITING_VERTICAL_BOTTOM = 0x0004, /* Chroma samples are co-sited vertically on the bottom with the luma samples. */ MFX_CHROMA_SITING_HORIZONTAL_LEFT = 0x0010, /* Chroma samples are co-sited horizontally on the left with the luma samples. */ MFX_CHROMA_SITING_HORIZONTAL_CENTER = 0x0020 /* Chroma samples are not co-sited horizontally with the luma samples. */ }; typedef struct { mfxExtBuffer Header; mfxU16 ChromaSiting; mfxU16 reserved[27]; } mfxExtColorConversion; /* VP9ReferenceFrame */ enum { MFX_VP9_REF_INTRA = 0, MFX_VP9_REF_LAST = 1, MFX_VP9_REF_GOLDEN = 2, MFX_VP9_REF_ALTREF = 3 }; /* SegmentIdBlockSize */ enum { MFX_VP9_SEGMENT_ID_BLOCK_SIZE_UNKNOWN = 0, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_8x8 = 8, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_16x16 = 16, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_32x32 = 32, MFX_VP9_SEGMENT_ID_BLOCK_SIZE_64x64 = 64, }; /* SegmentFeature */ enum { MFX_VP9_SEGMENT_FEATURE_QINDEX = 0x0001, MFX_VP9_SEGMENT_FEATURE_LOOP_FILTER = 0x0002, MFX_VP9_SEGMENT_FEATURE_REFERENCE = 0x0004, MFX_VP9_SEGMENT_FEATURE_SKIP = 0x0008 /* (0,0) MV, no residual */ }; typedef struct { mfxU16 FeatureEnabled; /* see enum SegmentFeature */ mfxI16 QIndexDelta; mfxI16 LoopFilterLevelDelta; mfxU16 ReferenceFrame; /* see enum VP9ReferenceFrame */ mfxU16 reserved[12]; } mfxVP9SegmentParam; typedef struct { mfxExtBuffer Header; mfxU16 NumSegments; /* 0..8 */ mfxVP9SegmentParam Segment[8]; mfxU16 SegmentIdBlockSize; /* see enum SegmentIdBlockSize */ mfxU32 NumSegmentIdAlloc; /* >= (Ceil(Width / SegmentIdBlockSize) * Ceil(Height / SegmentIdBlockSize)) */ union { mfxU8 *SegmentId; /*[NumSegmentIdAlloc] = 0..7, index in Segment array, blocks of SegmentIdBlockSize map */ mfxU64 reserved1; }; mfxU16 reserved[52]; } mfxExtVP9Segmentation; typedef struct { mfxU16 FrameRateScale; /* Layer[n].FrameRateScale = Layer[n - 1].FrameRateScale * (uint)m */ mfxU16 TargetKbps; /* affected by BRCParamMultiplier, Layer[n].TargetKbps > Layer[n - 1].TargetKbps */ mfxU16 reserved[14]; } mfxVP9TemporalLayer; typedef struct { mfxExtBuffer Header; mfxVP9TemporalLayer Layer[8]; mfxU16 reserved[60]; } mfxExtVP9TemporalLayers; typedef struct { mfxExtBuffer Header; mfxU16 FrameWidth; mfxU16 FrameHeight; mfxU16 WriteIVFHeaders; /* tri-state option */ mfxI16 reserved1[6]; mfxI16 QIndexDeltaLumaDC; mfxI16 QIndexDeltaChromaAC; mfxI16 QIndexDeltaChromaDC; mfxU16 reserved[112]; } mfxExtVP9Param; /* Multi-Frame Mode */ enum { MFX_MF_DEFAULT = 0, MFX_MF_DISABLED = 1, MFX_MF_AUTO = 2, MFX_MF_MANUAL = 3 }; /* Multi-Frame Initialization parameters */ typedef struct { mfxExtBuffer Header; mfxU16 MFMode; mfxU16 MaxNumFrames; mfxU16 reserved[58]; } mfxExtMultiFrameParam; /* Multi-Frame Run-time controls */ typedef struct { mfxExtBuffer Header; mfxU32 Timeout; /* timeout in millisecond */ mfxU16 Flush; /* Flush internal frame buffer, e.g. submit all collected frames. */ mfxU16 reserved[57]; } mfxExtMultiFrameControl; typedef struct { mfxU16 Type; mfxU16 reserved1; mfxU32 Offset; mfxU32 Size; mfxU32 reserved[5]; } mfxEncodedUnitInfo; typedef struct { mfxExtBuffer Header; union { mfxEncodedUnitInfo *UnitInfo; mfxU64 reserved1; }; mfxU16 NumUnitsAlloc; mfxU16 NumUnitsEncoded; mfxU16 reserved[22]; } mfxExtEncodedUnitsInfo; /* MCTF initialization & runtime */ typedef struct { mfxExtBuffer Header; mfxU16 FilterStrength; mfxU16 reserved[27]; } mfxExtVppMctf; #ifdef __cplusplus } // extern "C" #endif #endif ================================================ FILE: decoder/LAVVideo/decoders/mvc/include/mfxvideo.h ================================================ /* ****************************************************************************** *\ Copyright (C) 2007-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfxvideo.h \* ****************************************************************************** */ #ifndef __MFXVIDEO_H__ #define __MFXVIDEO_H__ #include "mfxsession.h" #include "mfxvstructures.h" #ifdef __cplusplus extern "C" { #endif /* MFXVideoCORE */ typedef struct { mfxU32 reserved[4]; mfxHDL pthis; mfxStatus (MFX_CDECL *Alloc) (mfxHDL pthis, mfxU32 nbytes, mfxU16 type, mfxMemId *mid); mfxStatus (MFX_CDECL *Lock) (mfxHDL pthis, mfxMemId mid, mfxU8 **ptr); mfxStatus (MFX_CDECL *Unlock) (mfxHDL pthis, mfxMemId mid); mfxStatus (MFX_CDECL *Free) (mfxHDL pthis, mfxMemId mid); } mfxBufferAllocator; typedef struct { mfxU32 reserved[4]; mfxHDL pthis; mfxStatus (MFX_CDECL *Alloc) (mfxHDL pthis, mfxFrameAllocRequest *request, mfxFrameAllocResponse *response); mfxStatus (MFX_CDECL *Lock) (mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr); mfxStatus (MFX_CDECL *Unlock) (mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr); mfxStatus (MFX_CDECL *GetHDL) (mfxHDL pthis, mfxMemId mid, mfxHDL *handle); mfxStatus (MFX_CDECL *Free) (mfxHDL pthis, mfxFrameAllocResponse *response); } mfxFrameAllocator; /* VideoCORE */ mfxStatus MFX_CDECL MFXVideoCORE_SetBufferAllocator(mfxSession session, mfxBufferAllocator *allocator); mfxStatus MFX_CDECL MFXVideoCORE_SetFrameAllocator(mfxSession session, mfxFrameAllocator *allocator); mfxStatus MFX_CDECL MFXVideoCORE_SetHandle(mfxSession session, mfxHandleType type, mfxHDL hdl); mfxStatus MFX_CDECL MFXVideoCORE_GetHandle(mfxSession session, mfxHandleType type, mfxHDL *hdl); mfxStatus MFX_CDECL MFXVideoCORE_QueryPlatform(mfxSession session, mfxPlatform* platform); mfxStatus MFX_CDECL MFXVideoCORE_SyncOperation(mfxSession session, mfxSyncPoint syncp, mfxU32 wait); /* VideoENCODE */ mfxStatus MFX_CDECL MFXVideoENCODE_Query(mfxSession session, mfxVideoParam *in, mfxVideoParam *out); mfxStatus MFX_CDECL MFXVideoENCODE_QueryIOSurf(mfxSession session, mfxVideoParam *par, mfxFrameAllocRequest *request); mfxStatus MFX_CDECL MFXVideoENCODE_Init(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoENCODE_Reset(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoENCODE_Close(mfxSession session); mfxStatus MFX_CDECL MFXVideoENCODE_GetVideoParam(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoENCODE_GetEncodeStat(mfxSession session, mfxEncodeStat *stat); mfxStatus MFX_CDECL MFXVideoENCODE_EncodeFrameAsync(mfxSession session, mfxEncodeCtrl *ctrl, mfxFrameSurface1 *surface, mfxBitstream *bs, mfxSyncPoint *syncp); /* VideoDECODE */ mfxStatus MFX_CDECL MFXVideoDECODE_Query(mfxSession session, mfxVideoParam *in, mfxVideoParam *out); mfxStatus MFX_CDECL MFXVideoDECODE_DecodeHeader(mfxSession session, mfxBitstream *bs, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoDECODE_QueryIOSurf(mfxSession session, mfxVideoParam *par, mfxFrameAllocRequest *request); mfxStatus MFX_CDECL MFXVideoDECODE_Init(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoDECODE_Reset(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoDECODE_Close(mfxSession session); mfxStatus MFX_CDECL MFXVideoDECODE_GetVideoParam(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoDECODE_GetDecodeStat(mfxSession session, mfxDecodeStat *stat); mfxStatus MFX_CDECL MFXVideoDECODE_SetSkipMode(mfxSession session, mfxSkipMode mode); mfxStatus MFX_CDECL MFXVideoDECODE_GetPayload(mfxSession session, mfxU64 *ts, mfxPayload *payload); mfxStatus MFX_CDECL MFXVideoDECODE_DecodeFrameAsync(mfxSession session, mfxBitstream *bs, mfxFrameSurface1 *surface_work, mfxFrameSurface1 **surface_out, mfxSyncPoint *syncp); /* VideoVPP */ mfxStatus MFX_CDECL MFXVideoVPP_Query(mfxSession session, mfxVideoParam *in, mfxVideoParam *out); mfxStatus MFX_CDECL MFXVideoVPP_QueryIOSurf(mfxSession session, mfxVideoParam *par, mfxFrameAllocRequest request[2]); mfxStatus MFX_CDECL MFXVideoVPP_Init(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoVPP_Reset(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoVPP_Close(mfxSession session); mfxStatus MFX_CDECL MFXVideoVPP_GetVideoParam(mfxSession session, mfxVideoParam *par); mfxStatus MFX_CDECL MFXVideoVPP_GetVPPStat(mfxSession session, mfxVPPStat *stat); mfxStatus MFX_CDECL MFXVideoVPP_RunFrameVPPAsync(mfxSession session, mfxFrameSurface1 *in, mfxFrameSurface1 *out, mfxExtVppAuxData *aux, mfxSyncPoint *syncp); mfxStatus MFX_CDECL MFXVideoVPP_RunFrameVPPAsyncEx(mfxSession session, mfxFrameSurface1 *in, mfxFrameSurface1 *surface_work, mfxFrameSurface1 **surface_out, mfxSyncPoint *syncp); #ifdef __cplusplus } // extern "C" #endif #endif ================================================ FILE: decoder/LAVVideo/decoders/mvc/include/mfxvstructures.h ================================================ /******************************************************************************* Copyright (C) 2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfxvstructures.h *******************************************************************************/ #include "mfxstructures.h" ================================================ FILE: decoder/LAVVideo/decoders/pixfmt.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "ILAVDecoder.h" static LAVPixFmtDesc lav_pixfmt_desc[] = { {1, 3, {1, 2, 2}, {1, 2, 2}}, ///< LAVPixFmt_YUV420 {2, 3, {1, 2, 2}, {1, 2, 2}}, ///< LAVPixFmt_YUV420bX {1, 3, {1, 2, 2}, {1, 1, 1}}, ///< LAVPixFmt_YUV422 {2, 3, {1, 2, 2}, {1, 1, 1}}, ///< LAVPixFmt_YUV422bX {1, 3, {1, 1, 1}, {1, 1, 1}}, ///< LAVPixFmt_YUV444 {2, 3, {1, 1, 1}, {1, 1, 1}}, ///< LAVPixFmt_YUV444bX {1, 2, {1, 1}, {1, 2}}, ///< LAVPixFmt_NV12 {2, 1, {1}, {1}}, ///< LAVPixFmt_YUY2 {2, 2, {1, 1}, {1, 2}}, ///< LAVPixFmt_P016 {3, 1, {1}, {1}}, ///< LAVPixFmt_RGB24 {4, 1, {1}, {1}}, ///< LAVPixFmt_RGB32 {4, 1, {1}, {1}}, ///< LAVPixFmt_ARGB32 {6, 1, {1}, {1}}, ///< LAVPixFmt_RGB48 {4, 1, {1}, {1}}, ///< LAVPixFmt_AYUV {4, 1, {1}, {1}}, ///< LAVPixFmt_Y410 {8, 1, {1}, {1}}, ///< LAVPixFmt_Y416 {4, 1, {1}, {1}}, ///< LAVPixFmt_Y216 }; LAVPixFmtDesc getPixelFormatDesc(LAVPixelFormat pixFmt) { return lav_pixfmt_desc[pixFmt]; } static struct { LAVPixelFormat pixfmt; AVPixelFormat ffpixfmt; } lav_ff_pixfmt_map[] = { {LAVPixFmt_YUV420, AV_PIX_FMT_YUV420P}, {LAVPixFmt_YUV422, AV_PIX_FMT_YUV422P}, {LAVPixFmt_YUV444, AV_PIX_FMT_YUV444P}, {LAVPixFmt_NV12, AV_PIX_FMT_NV12}, {LAVPixFmt_YUY2, AV_PIX_FMT_YUYV422}, {LAVPixFmt_RGB24, AV_PIX_FMT_BGR24}, {LAVPixFmt_RGB32, AV_PIX_FMT_BGRA}, {LAVPixFmt_ARGB32, AV_PIX_FMT_BGRA}, {LAVPixFmt_RGB48, AV_PIX_FMT_RGB48LE}, {LAVPixFmt_AYUV, AV_PIX_FMT_VUYX}, {LAVPixFmt_Y410, AV_PIX_FMT_XV30}, {LAVPixFmt_Y416, AV_PIX_FMT_XV48}, }; AVPixelFormat getFFPixelFormatFromLAV(LAVPixelFormat pixFmt, int bpp) { AVPixelFormat fmt = AV_PIX_FMT_NONE; for (int i = 0; i < countof(lav_ff_pixfmt_map); i++) { if (lav_ff_pixfmt_map[i].pixfmt == pixFmt) { fmt = lav_ff_pixfmt_map[i].ffpixfmt; break; } } if (fmt == AV_PIX_FMT_NONE) { switch (pixFmt) { case LAVPixFmt_YUV420bX: fmt = (bpp == 9) ? AV_PIX_FMT_YUV420P9LE : ((bpp == 10) ? AV_PIX_FMT_YUV420P10LE : ((bpp == 12) ? AV_PIX_FMT_YUV420P12LE : ((bpp == 14) ? AV_PIX_FMT_YUV420P14LE : AV_PIX_FMT_YUV420P16LE))); break; case LAVPixFmt_YUV422bX: fmt = (bpp == 9) ? AV_PIX_FMT_YUV422P9LE : ((bpp == 10) ? AV_PIX_FMT_YUV422P10LE : ((bpp == 12) ? AV_PIX_FMT_YUV422P12LE : ((bpp == 14) ? AV_PIX_FMT_YUV422P14LE : AV_PIX_FMT_YUV422P16LE))); break; case LAVPixFmt_YUV444bX: fmt = (bpp == 9) ? AV_PIX_FMT_YUV444P9LE : ((bpp == 10) ? AV_PIX_FMT_YUV444P10LE : ((bpp == 12) ? AV_PIX_FMT_YUV444P12LE : ((bpp == 14) ? AV_PIX_FMT_YUV444P14LE : AV_PIX_FMT_YUV444P16LE))); break; case LAVPixFmt_P016: fmt = (bpp <= 10) ? AV_PIX_FMT_P010LE : AV_PIX_FMT_P016LE; break; case LAVPixFmt_Y216: fmt = (bpp <= 10) ? AV_PIX_FMT_Y210 : AV_PIX_FMT_Y216; break; default: ASSERT(0); } } return fmt; } static void free_buffers(struct LAVFrame *pFrame) { _aligned_free(pFrame->data[0]); _aligned_free(pFrame->data[1]); _aligned_free(pFrame->data[2]); _aligned_free(pFrame->data[3]); memset(pFrame->data, 0, sizeof(pFrame->data)); _aligned_free(pFrame->stereo[0]); _aligned_free(pFrame->stereo[1]); _aligned_free(pFrame->stereo[2]); _aligned_free(pFrame->stereo[3]); memset(pFrame->stereo, 0, sizeof(pFrame->stereo)); } HRESULT AllocLAVFrameBuffers(LAVFrame *pFrame, ptrdiff_t stride) { LAVPixFmtDesc desc = getPixelFormatDesc(pFrame->format); if (stride < pFrame->width) { // Ensure alignment of at least 32 on all planes stride = FFALIGN(pFrame->width, 64); } stride *= desc.codedbytes; int alignedHeight = FFALIGN(pFrame->height, 2); memset(pFrame->data, 0, sizeof(pFrame->data)); memset(pFrame->stereo, 0, sizeof(pFrame->stereo)); memset(pFrame->stride, 0, sizeof(pFrame->stride)); for (int plane = 0; plane < desc.planes; plane++) { ptrdiff_t planeStride = stride / desc.planeWidth[plane]; size_t size = planeStride * (alignedHeight / desc.planeHeight[plane]); pFrame->data[plane] = (BYTE *)_aligned_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE, 64); if (pFrame->data[plane] == nullptr) { free_buffers(pFrame); return E_OUTOFMEMORY; } pFrame->stride[plane] = planeStride; } if (pFrame->flags & LAV_FRAME_FLAG_MVC) { for (int plane = 0; plane < desc.planes; plane++) { size_t size = pFrame->stride[plane] * (alignedHeight / desc.planeHeight[plane]); pFrame->stereo[plane] = (BYTE *)_aligned_malloc(size + AV_INPUT_BUFFER_PADDING_SIZE, 64); if (pFrame->stereo[plane] == nullptr) { free_buffers(pFrame); return E_OUTOFMEMORY; } } } pFrame->destruct = &free_buffers; pFrame->flags |= LAV_FRAME_FLAG_BUFFER_MODIFY; return S_OK; } HRESULT FreeLAVFrameBuffers(LAVFrame *pFrame) { CheckPointer(pFrame, E_POINTER); if (pFrame->destruct) { pFrame->destruct(pFrame); pFrame->destruct = nullptr; pFrame->priv_data = nullptr; } memset(pFrame->data, 0, sizeof(pFrame->data)); memset(pFrame->stereo, 0, sizeof(pFrame->stereo)); memset(pFrame->stride, 0, sizeof(pFrame->stride)); for (int i = 0; i < pFrame->side_data_count; i++) { SAFE_CO_FREE(pFrame->side_data[i].data); } SAFE_CO_FREE(pFrame->side_data); pFrame->side_data_count = 0; return S_OK; } HRESULT CopyLAVFrame(LAVFrame *pSrc, LAVFrame **ppDst) { ASSERT(pSrc->format != LAVPixFmt_DXVA2 && pSrc->format != LAVPixFmt_D3D11); *ppDst = (LAVFrame *)CoTaskMemAlloc(sizeof(LAVFrame)); if (!*ppDst) return E_OUTOFMEMORY; **ppDst = *pSrc; (*ppDst)->destruct = nullptr; (*ppDst)->priv_data = nullptr; HRESULT hr = AllocLAVFrameBuffers(*ppDst); if (FAILED(hr)) return hr; LAVPixFmtDesc desc = getPixelFormatDesc(pSrc->format); for (int plane = 0; plane < desc.planes; plane++) { size_t linesize = (pSrc->width / desc.planeWidth[plane]) * desc.codedbytes; BYTE *dst = (*ppDst)->data[plane]; BYTE *src = pSrc->data[plane]; if (!dst || !src) return E_FAIL; for (int i = 0; i < (pSrc->height / desc.planeHeight[plane]); i++) { memcpy(dst, src, linesize); dst += (*ppDst)->stride[plane]; src += pSrc->stride[plane]; } if (pSrc->flags & LAV_FRAME_FLAG_MVC) { dst = (*ppDst)->stereo[plane]; src = pSrc->stereo[plane]; if (!dst || !src) return E_FAIL; for (int i = 0; i < (pSrc->height / desc.planeHeight[plane]); i++) { memcpy(dst, src, linesize); dst += (*ppDst)->stride[plane]; src += pSrc->stride[plane]; } } } (*ppDst)->side_data = nullptr; (*ppDst)->side_data_count = 0; for (int i = 0; i < pSrc->side_data_count; i++) { BYTE *p = AddLAVFrameSideData(*ppDst, pSrc->side_data[i].guidType, pSrc->side_data[i].size); if (p) memcpy(p, pSrc->side_data[i].data, pSrc->side_data[i].size); } return S_OK; } HRESULT CopyLAVFrameInPlace(LAVFrame *pFrame) { LAVFrame *tmpFrame = nullptr; CopyLAVFrame(pFrame, &tmpFrame); FreeLAVFrameBuffers(pFrame); *pFrame = *tmpFrame; SAFE_CO_FREE(tmpFrame); return S_OK; } BYTE *AddLAVFrameSideData(LAVFrame *pFrame, GUID guidType, size_t size) { BYTE *ptr = (BYTE *)CoTaskMemRealloc(pFrame->side_data, sizeof(LAVFrameSideData) * (pFrame->side_data_count + 1)); if (!ptr) return NULL; pFrame->side_data = (LAVFrameSideData *)ptr; pFrame->side_data[pFrame->side_data_count].guidType = guidType; pFrame->side_data[pFrame->side_data_count].data = (BYTE *)CoTaskMemAlloc(size); pFrame->side_data[pFrame->side_data_count].size = size; if (!pFrame->side_data[pFrame->side_data_count].data) return NULL; memset(pFrame->side_data[pFrame->side_data_count].data, 0, size); pFrame->side_data_count++; return pFrame->side_data[pFrame->side_data_count - 1].data; } BYTE *GetLAVFrameSideData(LAVFrame *pFrame, GUID guidType, size_t *pSize) { if (!pFrame || pFrame->side_data_count == 0) return NULL; ASSERT(pSize); for (int i = 0; i < pFrame->side_data_count; i++) { if (pFrame->side_data[i].guidType == guidType) { *pSize = pFrame->side_data[i].size; return pFrame->side_data[i].data; } } return NULL; } bool ValidateLAVFrameBuffers(LAVFrame* pFrame) { if (pFrame->format >= LAVPixFmt_HWFormats) return true; if (pFrame->format <= LAVPixFmt_None) return false; // direct doesn't use the pointers, but will provide them through callbacks if (pFrame->direct) return true; LAVPixFmtDesc desc = getPixelFormatDesc(pFrame->format); for (int i = 0; i < desc.planes; i++) { if (pFrame->data[i] == nullptr) return false; ptrdiff_t min_linesize = (pFrame->width / desc.planeWidth[i]) * desc.codedbytes; if (abs(pFrame->stride[i]) < min_linesize) return false; } return true; } ================================================ FILE: decoder/LAVVideo/decoders/quicksync.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "quicksync.h" #include "moreuuids.h" #include "parsers/H264SequenceParser.h" #include "parsers/MPEG2HeaderParser.h" #include "parsers/VC1HeaderParser.h" #include "Media.h" #include #include #include // Timestamp padding to avoid an issue with negative timestamps // 10 hours should be enough padding to take care of all eventualities #define RTPADDING 360000000000i64 //////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////// ILAVDecoder *CreateDecoderQuickSync() { return new CDecQuickSync(); } //////////////////////////////////////////////////////////////////////////////// // Codec FourCC map //////////////////////////////////////////////////////////////////////////////// static const FOURCC FourCC_MPG1 = mmioFOURCC('M', 'P', 'G', '1'); static const FOURCC FourCC_MPG2 = mmioFOURCC('M', 'P', 'G', '2'); static const FOURCC FourCC_VC1 = mmioFOURCC('W', 'V', 'C', '1'); static const FOURCC FourCC_WMV3 = mmioFOURCC('W', 'M', 'V', '3'); static const FOURCC FourCC_H264 = mmioFOURCC('H', '2', '6', '4'); static const FOURCC FourCC_AVC1 = mmioFOURCC('A', 'V', 'C', '1'); static struct { AVCodecID ffcodec; FOURCC fourCC; } quicksync_codecs[] = { {AV_CODEC_ID_MPEG2VIDEO, FourCC_MPG2}, {AV_CODEC_ID_VC1, FourCC_VC1}, {AV_CODEC_ID_WMV3, FourCC_WMV3}, {AV_CODEC_ID_H264, FourCC_H264}, }; //////////////////////////////////////////////////////////////////////////////// // CQSMediaSample Implementation //////////////////////////////////////////////////////////////////////////////// class CQSMediaSample : public IMediaSample { public: CQSMediaSample(BYTE *pBuffer, long len) : m_pBuffer(pBuffer) , m_lLen(len) , m_lActualLen(len) { } // IUnknown STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject) { if (riid == IID_IUnknown) { AddRef(); *ppvObject = (IUnknown *)this; } else if (riid == IID_IMediaSample) { AddRef(); *ppvObject = (IMediaSample *)this; } else { return E_NOINTERFACE; } return S_OK; } STDMETHODIMP_(ULONG) AddRef() { LONG lRef = InterlockedIncrement(&m_cRef); return max(ULONG(lRef), 1ul); } STDMETHODIMP_(ULONG) Release() { LONG lRef = InterlockedDecrement(&m_cRef); if (lRef == 0) { m_cRef++; delete this; return 0; } return max(ULONG(lRef), 1ul); } // IMediaSample STDMETHODIMP GetPointer(BYTE **ppBuffer) { CheckPointer(ppBuffer, E_POINTER); *ppBuffer = m_pBuffer; return S_OK; } STDMETHODIMP_(long) GetSize(void) { return m_lLen; } STDMETHODIMP GetTime(REFERENCE_TIME *pTimeStart, REFERENCE_TIME *pTimeEnd) { CheckPointer(pTimeStart, E_POINTER); CheckPointer(pTimeEnd, E_POINTER); if (m_rtStart != AV_NOPTS_VALUE) { *pTimeStart = m_rtStart; if (m_rtStop != AV_NOPTS_VALUE) { *pTimeEnd = m_rtStop; return S_OK; } *pTimeEnd = m_rtStart + 1; return VFW_S_NO_STOP_TIME; } return VFW_E_SAMPLE_TIME_NOT_SET; } STDMETHODIMP SetTime(REFERENCE_TIME *pTimeStart, REFERENCE_TIME *pTimeEnd) { if (!pTimeStart) { m_rtStart = m_rtStop = AV_NOPTS_VALUE; } else { m_rtStart = *pTimeStart; if (!pTimeEnd) m_rtStop = AV_NOPTS_VALUE; else m_rtStop = *pTimeEnd; } return S_OK; } STDMETHODIMP IsSyncPoint(void) { return m_bSyncPoint ? S_OK : S_FALSE; } STDMETHODIMP SetSyncPoint(BOOL bIsSyncPoint) { m_bSyncPoint = bIsSyncPoint; return S_OK; } STDMETHODIMP IsPreroll(void) { return E_NOTIMPL; } STDMETHODIMP SetPreroll(BOOL bIsPreroll) { return E_NOTIMPL; } STDMETHODIMP_(long) GetActualDataLength(void) { return m_lActualLen; } STDMETHODIMP SetActualDataLength(long length) { m_lActualLen = length; return S_OK; } STDMETHODIMP GetMediaType(AM_MEDIA_TYPE **ppMediaType) { return S_FALSE; } STDMETHODIMP SetMediaType(AM_MEDIA_TYPE *pMediaType) { return E_NOTIMPL; } STDMETHODIMP IsDiscontinuity(void) { return m_bDiscontinuity ? S_OK : S_FALSE; } STDMETHODIMP SetDiscontinuity(BOOL bDiscontinuity) { m_bDiscontinuity = bDiscontinuity; return S_OK; } STDMETHODIMP GetMediaTime(LONGLONG *pTimeStart, LONGLONG *pTimeEnd) { return E_NOTIMPL; } STDMETHODIMP SetMediaTime(LONGLONG *pTimeStart, LONGLONG *pTimeEnd) { return E_NOTIMPL; } private: BYTE *m_pBuffer = nullptr; long m_lLen = 0; long m_lActualLen = 0; REFERENCE_TIME m_rtStart = AV_NOPTS_VALUE; REFERENCE_TIME m_rtStop = AV_NOPTS_VALUE; BOOL m_bSyncPoint = FALSE; BOOL m_bDiscontinuity = FALSE; ULONG m_cRef = 1; }; class CIDirect3DDeviceManager9Proxy : public IDirect3DDeviceManager9 { public: CIDirect3DDeviceManager9Proxy(IPin *pPin) : m_pPin(pPin) { } ~CIDirect3DDeviceManager9Proxy() { SafeRelease(&m_D3DManager); } #define CREATE_DEVICE \ if (!m_D3DManager) \ { \ if (FAILED(CreateDeviceManager())) \ return E_FAIL; \ } // IUnknown HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { CREATE_DEVICE; return m_D3DManager->QueryInterface(riid, ppvObject); } ULONG STDMETHODCALLTYPE AddRef(void) { ULONG lRef = InterlockedIncrement(&m_cRef); return max(ULONG(lRef), 1ul); } ULONG STDMETHODCALLTYPE Release(void) { ULONG lRef = InterlockedDecrement(&m_cRef); if (lRef == 0) { m_cRef++; delete this; return 0; } return max(ULONG(lRef), 1ul); } // IDirect3DDeviceManager9 HRESULT STDMETHODCALLTYPE ResetDevice(IDirect3DDevice9 *pDevice, UINT resetToken) { CREATE_DEVICE; return m_D3DManager->ResetDevice(pDevice, resetToken); } HRESULT STDMETHODCALLTYPE OpenDeviceHandle(HANDLE *phDevice) { CREATE_DEVICE; return m_D3DManager->OpenDeviceHandle(phDevice); } HRESULT STDMETHODCALLTYPE CloseDeviceHandle(HANDLE hDevice) { CREATE_DEVICE; return m_D3DManager->CloseDeviceHandle(hDevice); } HRESULT STDMETHODCALLTYPE TestDevice(HANDLE hDevice) { CREATE_DEVICE; return m_D3DManager->TestDevice(hDevice); } HRESULT STDMETHODCALLTYPE LockDevice(HANDLE hDevice, IDirect3DDevice9 **ppDevice, BOOL fBlock) { CREATE_DEVICE; return m_D3DManager->LockDevice(hDevice, ppDevice, fBlock); } HRESULT STDMETHODCALLTYPE UnlockDevice(HANDLE hDevice, BOOL fSaveState) { CREATE_DEVICE; return m_D3DManager->UnlockDevice(hDevice, fSaveState); } HRESULT STDMETHODCALLTYPE GetVideoService(HANDLE hDevice, REFIID riid, void **ppService) { CREATE_DEVICE; return m_D3DManager->GetVideoService(hDevice, riid, ppService); } private: HRESULT STDMETHODCALLTYPE CreateDeviceManager() { DbgLog((LOG_TRACE, 10, L"CIDirect3DDeviceManager9Proxy::CreateDeviceManager()")); HRESULT hr = S_OK; IMFGetService *pGetService = nullptr; hr = m_pPin->QueryInterface(__uuidof(IMFGetService), (void **)&pGetService); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> IMFGetService not available")); goto done; } // Get the Direct3D device manager. IDirect3DDeviceManager9 *pDevMgr = nullptr; hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, __uuidof(IDirect3DDeviceManager9), (void **)&pDevMgr); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"-> D3D Device Manager not available")); goto done; } m_D3DManager = pDevMgr; done: SafeRelease(&pGetService); return hr; } private: IDirect3DDeviceManager9 *m_D3DManager = nullptr; IPin *m_pPin = nullptr; ULONG m_cRef = 1; }; //////////////////////////////////////////////////////////////////////////////// // QuickSync decoder implementation //////////////////////////////////////////////////////////////////////////////// CDecQuickSync::CDecQuickSync(void) : CDecBase() { ZeroMemory(&qs, sizeof(qs)); ZeroMemory(&m_DXVAExtendedFormat, sizeof(m_DXVAExtendedFormat)); } CDecQuickSync::~CDecQuickSync(void) { DestroyDecoder(true); } STDMETHODIMP CDecQuickSync::DestroyDecoder(bool bFull) { if (m_pDecoder) { qs.destroy(m_pDecoder); m_pDecoder = nullptr; } if (bFull) { SafeRelease(&m_pD3DDevMngr); FreeLibrary(qs.quickSyncLib); } return S_OK; } // ILAVDecoder STDMETHODIMP CDecQuickSync::Init() { DbgLog((LOG_TRACE, 10, L"CDecQuickSync::Init(): Trying to open QuickSync decoder")); int flags = av_get_cpu_flags(); if (!(flags & AV_CPU_FLAG_SSE4)) { DbgLog((LOG_TRACE, 10, L"-> CPU is not SSE 4.1 capable, this is not even worth a try....")); return E_FAIL; } if (!qs.quickSyncLib) { WCHAR wModuleFile[1024]; GetModuleFileName(g_hInst, wModuleFile, 1024); PathRemoveFileSpecW(wModuleFile); wcscat_s(wModuleFile, TEXT("\\") TEXT(QS_DEC_DLL_NAME)); qs.quickSyncLib = LoadLibrary(wModuleFile); if (qs.quickSyncLib == nullptr) { DWORD dwError = GetLastError(); DbgLog((LOG_ERROR, 10, L"-> Loading of " TEXT(QS_DEC_DLL_NAME) L" failed (%d)", dwError)); return E_FAIL; } qs.create = (pcreateQuickSync *)GetProcAddress(qs.quickSyncLib, "createQuickSync"); if (qs.create == nullptr) { DbgLog((LOG_ERROR, 10, L"-> Failed to load function \"createQuickSync\"")); return E_FAIL; } qs.destroy = (pdestroyQuickSync *)GetProcAddress(qs.quickSyncLib, "destroyQuickSync"); if (qs.destroy == nullptr) { DbgLog((LOG_ERROR, 10, L"-> Failed to load function \"destroyQuickSync\"")); return E_FAIL; } qs.check = (pcheck *)GetProcAddress(qs.quickSyncLib, "check"); if (qs.check == nullptr) { DbgLog((LOG_ERROR, 10, L"-> Failed to load function \"check\"")); return E_FAIL; } } return S_OK; } STDMETHODIMP CDecQuickSync::PostConnect(IPin *pPin) { HRESULT hr = S_OK; DbgLog((LOG_TRACE, 10, L"CDecQuickSync::PostConnect()")); // Release the previous manager (if any) SafeRelease(&m_pD3DDevMngr); // Create our proxy object m_pD3DDevMngr = new CIDirect3DDeviceManager9Proxy(pPin); // Tell the QuickSync decoder about it m_pDecoder->SetD3DDeviceManager(m_pD3DDevMngr); return S_OK; } STDMETHODIMP CDecQuickSync::Check() { if (!qs.check) return E_FAIL; DWORD qsflags = qs.check(); if (qsflags & QS_CAP_HW_ACCELERATION) { return S_OK; } DbgLog((LOG_TRACE, 10, L"-> Decoder records no HW acceleration")); return E_FAIL; } STDMETHODIMP CDecQuickSync::CheckH264Sequence(const BYTE *buffer, size_t buflen, int nal_size, int *pRefFrames, int *pProfile, int *pLevel) { DbgLog((LOG_TRACE, 10, L"CDecQuickSync::CheckH264Sequence(): Checking H264 frame for SPS")); CH264SequenceParser h264parser; h264parser.ParseNALs(buffer, buflen, nal_size); if (h264parser.sps.valid) { m_bInterlaced = h264parser.sps.interlaced; fillDXVAExtFormat(m_DXVAExtendedFormat, h264parser.sps.full_range, h264parser.sps.primaries, h264parser.sps.colorspace, h264parser.sps.trc); if (pRefFrames) *pRefFrames = h264parser.sps.ref_frames; if (pProfile) *pProfile = h264parser.sps.profile; if (pLevel) *pLevel = h264parser.sps.level; DbgLog((LOG_TRACE, 10, L"-> SPS found")); if (h264parser.sps.profile > 100 || h264parser.sps.chroma != 1 || h264parser.sps.luma_bitdepth != 8 || h264parser.sps.chroma_bitdepth != 8) { DbgLog((LOG_TRACE, 10, L" -> SPS indicates video incompatible with QuickSync, aborting (profile: %d, chroma: %d, " L"bitdepth: %d/%d)", h264parser.sps.profile, h264parser.sps.chroma, h264parser.sps.luma_bitdepth, h264parser.sps.chroma_bitdepth)); return E_FAIL; } DbgLog((LOG_TRACE, 10, L"-> Video seems compatible with QuickSync")); return S_OK; } return S_FALSE; } STDMETHODIMP CDecQuickSync::InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) { HRESULT hr = S_OK; DbgLog((LOG_TRACE, 10, L"CDecQuickSync::InitDecoder(): Initializing QuickSync decoder")); DestroyDecoder(false); FOURCC fourCC = (FOURCC)0; for (int i = 0; i < countof(quicksync_codecs); i++) { if (quicksync_codecs[i].ffcodec == codec) { fourCC = quicksync_codecs[i].fourCC; break; } } if (fourCC == 0) { DbgLog((LOG_TRACE, 10, L"-> Codec id %d does not map to a QuickSync FourCC codec", codec)); return E_FAIL; } m_pDecoder = qs.create(); if (!m_pDecoder || !m_pDecoder->getOK()) { DbgLog((LOG_TRACE, 10, L"-> Decoder creation failed")); return E_FAIL; } m_pDecoder->SetDeliverSurfaceCallback(this, &QS_DeliverSurfaceCallback); m_nAVCNalSize = 0; if (pmt->subtype == MEDIASUBTYPE_AVC1 || pmt->subtype == MEDIASUBTYPE_avc1 || pmt->subtype == MEDIASUBTYPE_CCV1) { if (pmt->formattype == FORMAT_MPEG2Video) { MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->pbFormat; fourCC = FourCC_AVC1; m_bAVC1 = TRUE; m_nAVCNalSize = mp2vi->dwFlags; } else { DbgLog((LOG_TRACE, 10, L"-> AVC1 without MPEG2VIDEOINFO not supported")); return E_FAIL; } } BYTE *extradata = nullptr; size_t extralen = 0; getExtraData(*pmt, nullptr, &extralen); if (extralen > 0) { extradata = (BYTE *)av_malloc(extralen + AV_INPUT_BUFFER_PADDING_SIZE); if (extradata == nullptr) return E_OUTOFMEMORY; getExtraData(*pmt, extradata, nullptr); } m_bNeedSequenceCheck = FALSE; m_bInterlaced = TRUE; m_bUseTimestampQueue = m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_ONLY_DTS; int ref_frames = 0; int profile = 0; int level = 0; if (extralen > 0) { if (fourCC == FourCC_AVC1 || fourCC == FourCC_H264) { hr = CheckH264Sequence(extradata, extralen, m_bAVC1 ? 2 : 0, &ref_frames, &profile, &level); if (FAILED(hr)) { return VFW_E_UNSUPPORTED_VIDEO; } else if (hr == S_FALSE) { m_bNeedSequenceCheck = TRUE; } } else if (fourCC == FourCC_MPG2) { DbgLog((LOG_TRACE, 10, L"-> Scanning extradata for MPEG2 sequence header")); CMPEG2HeaderParser mpeg2parser(extradata, extralen); if (mpeg2parser.hdr.valid) { if (mpeg2parser.hdr.chroma >= 2) { DbgLog((LOG_TRACE, 10, L" -> Sequence header indicates incompatible chroma sampling (chroma: %d)", mpeg2parser.hdr.chroma)); return VFW_E_UNSUPPORTED_VIDEO; } m_bInterlaced = mpeg2parser.hdr.interlaced; } } else if (fourCC == FourCC_VC1) { CVC1HeaderParser vc1Parser(extradata, extralen); m_bInterlaced = vc1Parser.hdr.interlaced; } } else { m_bNeedSequenceCheck = (fourCC == FourCC_H264); } // Done with the extradata if (extradata) av_freep(&extradata); // Configure QuickSync decoder CQsConfig qsConfig; m_pDecoder->GetConfig(&qsConfig); // Timestamp correction is only used for VC-1 codecs which send PTS // because this is not handled properly by the API (it expects DTS) qsConfig.bTimeStampCorrection = 1; //(codec == AV_CODEC_ID_VC1 && !(m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_ONLY_DTS)); // Configure number of buffers (dependant on ref_frames) // MPEG2 and VC1 always use "low latency" mode if (ref_frames > 8 || qsConfig.bTimeStampCorrection) qsConfig.nOutputQueueLength = 8; else qsConfig.nOutputQueueLength = 0; // Disallow software fallback qsConfig.bEnableSwEmulation = false; // Enable DVD support qsConfig.bEnableDvdDecoding = true; // We want the pure image, no mod-16 padding qsConfig.bMod16Width = false; // Configure threading qsConfig.bEnableMultithreading = true; qsConfig.bEnableMtCopy = true; // Configure video processing qsConfig.vpp = 0; m_bDI = m_pSettings->GetHWAccelDeintMode() == HWDeintMode_Hardware && !m_pSettings->GetDeintTreatAsProgressive(); qsConfig.bEnableVideoProcessing = m_bDI ? true : false; qsConfig.bVppEnableDeinterlacing = m_bDI ? true : false; qsConfig.bVppEnableFullRateDI = m_pSettings->GetHWAccelDeintOutput() == DeintOutput_FramePerField; qsConfig.bVppEnableDITimeStampsInterpolation = true; qsConfig.bVppEnableForcedDeinterlacing = m_bDI && ((m_bInterlaced && m_pSettings->GetDeinterlacingMode() == DeintMode_Aggressive) || m_pSettings->GetDeinterlacingMode() == DeintMode_Force); qsConfig.bForceFieldOrder = m_pSettings->GetDeintFieldOrder() != DeintFieldOrder_Auto; qsConfig.eFieldOrder = (QsFieldOrder)m_pSettings->GetDeintFieldOrder(); // Save! m_pDecoder->SetConfig(&qsConfig); CMediaType mt = *pmt; // Fixup media type - the QuickSync decoder is a bit picky about this. // We usually do not trust the media type information and instead scan the bitstream. // This ensures that we only ever send valid and supported data to the decoder, // so with this we try to circumvent the checks in the QuickSync decoder mt.SetType(&MEDIATYPE_Video); MPEG2VIDEOINFO *mp2vi = (*mt.FormatType() == FORMAT_MPEG2Video) ? (MPEG2VIDEOINFO *)mt.Format() : nullptr; BITMAPINFOHEADER *bmi = nullptr; videoFormatTypeHandler(mt.Format(), mt.FormatType(), &bmi); switch (fourCC) { case FourCC_MPG2: mt.SetSubtype(&MEDIASUBTYPE_MPEG2_VIDEO); if (mp2vi) mp2vi->dwProfile = 4; break; case FourCC_AVC1: case FourCC_H264: if (mp2vi) { mp2vi->dwProfile = profile ? profile : 100; mp2vi->dwLevel = level ? level : 41; } break; case FourCC_VC1: if (mp2vi) mp2vi->dwProfile = 3; bmi->biCompression = fourCC; break; case FourCC_WMV3: mt.SetSubtype(&MEDIASUBTYPE_WMV3); if (mp2vi) mp2vi->dwProfile = 0; bmi->biCompression = fourCC; break; } hr = m_pDecoder->TestMediaType(&mt, fourCC); if (hr != S_OK) { DbgLog((LOG_TRACE, 10, L"-> TestMediaType failed")); return E_FAIL; } hr = m_pDecoder->InitDecoder(&mt, fourCC); if (hr != S_OK) { DbgLog((LOG_TRACE, 10, L"-> InitDecoder failed")); return E_FAIL; } m_Codec = fourCC; return S_OK; } STDMETHODIMP CDecQuickSync::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pMediaSample) { HRESULT hr; if (m_bNeedSequenceCheck && (m_Codec == FourCC_H264 || m_Codec == FourCC_AVC1)) { hr = CheckH264Sequence(buffer, buflen, m_nAVCNalSize); if (FAILED(hr)) { return E_FAIL; } else if (hr == S_OK) { m_bNeedSequenceCheck = FALSE; } } if (m_Codec == FourCC_MPG2) { const uint8_t *eosmarker = nullptr; const uint8_t *end = buffer + buflen; int status = CheckForSequenceMarkers(AV_CODEC_ID_MPEG2VIDEO, buffer, buflen, &m_MpegParserState, &eosmarker); // If we found a EOS marker, but its not at the end of the packet, then split the packet // to be able to individually decode the frame before the EOS, and then decode the remainder if (status & STATE_EOS_FOUND && eosmarker && eosmarker != end) { Decode(buffer, (int)(eosmarker - buffer), rtStart, rtStop, bSyncPoint, bDiscontinuity, nullptr); rtStart = rtStop = AV_NOPTS_VALUE; buffer = eosmarker; buflen = (int)(end - eosmarker); } else if (eosmarker) { m_bEndOfSequence = TRUE; } } if (rtStart != AV_NOPTS_VALUE) { rtStart += RTPADDING; if (rtStart < 0) rtStart = 0; if (rtStop != AV_NOPTS_VALUE) { rtStop += RTPADDING; if (rtStop < 0) rtStop = AV_NOPTS_VALUE; } } if (m_bUseTimestampQueue) { m_timestampQueue.push(rtStart); } IMediaSample *pSample = new CQSMediaSample(const_cast(buffer), buflen); pSample->SetTime(&rtStart, &rtStop); pSample->SetDiscontinuity(bDiscontinuity); pSample->SetSyncPoint(bSyncPoint); hr = m_pDecoder->Decode(pSample); SafeRelease(&pSample); if (m_bEndOfSequence) { m_bEndOfSequence = FALSE; EndOfStream(); Deliver(m_pCallback->GetFlushFrame()); } return hr; } HRESULT CDecQuickSync::QS_DeliverSurfaceCallback(void *obj, QsFrameData *data) { CDecQuickSync *filter = (CDecQuickSync *)obj; if (filter->m_bUseTimestampQueue) { if (filter->m_timestampQueue.empty()) { data->rtStart = AV_NOPTS_VALUE; } else { data->rtStart = filter->m_timestampQueue.front(); filter->m_timestampQueue.pop(); } data->rtStop = AV_NOPTS_VALUE; } if (data->rtStart != AV_NOPTS_VALUE && data->rtStart > 0) { data->rtStart -= RTPADDING; if (data->rtStop != AV_NOPTS_VALUE) data->rtStop -= RTPADDING; } else { data->rtStop = AV_NOPTS_VALUE; } filter->HandleFrame(data); return S_OK; } STDMETHODIMP CDecQuickSync::HandleFrame(QsFrameData *data) { // Setup the LAVFrame LAVFrame *pFrame = nullptr; AllocateFrame(&pFrame); pFrame->format = LAVPixFmt_NV12; pFrame->sw_format = pFrame->format; pFrame->width = data->rcClip.right - data->rcClip.left + 1; pFrame->height = data->rcClip.bottom - data->rcClip.top + 1; pFrame->rtStart = data->rtStart; pFrame->rtStop = (data->rtStop - 1 > data->rtStart) ? data->rtStop : AV_NOPTS_VALUE; pFrame->repeat = !!(data->dwInterlaceFlags & AM_VIDEO_FLAG_REPEAT_FIELD); pFrame->aspect_ratio.num = data->dwPictAspectRatioX; pFrame->aspect_ratio.den = data->dwPictAspectRatioY; pFrame->ext_format = m_DXVAExtendedFormat; pFrame->interlaced = !(data->dwInterlaceFlags & AM_VIDEO_FLAG_WEAVE); pFrame->avgFrameDuration = GetFrameDuration(); LAVDeintFieldOrder fo = m_pSettings->GetDeintFieldOrder(); pFrame->tff = (fo == DeintFieldOrder_Auto) ? !!(data->dwInterlaceFlags & AM_VIDEO_FLAG_FIELD1FIRST) : (fo == DeintFieldOrder_TopFieldFirst); // Assign the buffer to the LAV Frame bufers pFrame->data[0] = data->y; pFrame->data[1] = data->u; pFrame->stride[0] = pFrame->stride[1] = data->dwStride; if (!m_bInterlaced && pFrame->interlaced) m_bInterlaced = TRUE; pFrame->interlaced = (pFrame->interlaced || (m_bInterlaced && m_pSettings->GetDeinterlacingMode() == DeintMode_Aggressive) || m_pSettings->GetDeinterlacingMode() == DeintMode_Force) && !(m_pSettings->GetDeinterlacingMode() == DeintMode_Disable) && !m_bDI; if (m_bEndOfSequence) pFrame->flags |= LAV_FRAME_FLAG_END_OF_SEQUENCE; m_pCallback->Deliver(pFrame); return S_OK; } STDMETHODIMP CDecQuickSync::Flush() { DbgLog((LOG_TRACE, 10, L"CDecQuickSync::Flush(): Flushing QuickSync decoder")); m_pDecoder->BeginFlush(); m_pDecoder->OnSeek(0); m_pDecoder->EndFlush(); // Clear timestamp queue std::queue().swap(m_timestampQueue); return __super::Flush(); } STDMETHODIMP CDecQuickSync::EndOfStream() { m_pDecoder->Flush(true); m_pDecoder->OnSeek(0); return S_OK; } STDMETHODIMP CDecQuickSync::GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { // Output is always NV12 if (pPix) *pPix = LAVPixFmt_NV12; if (pBpp) *pBpp = 8; if (pPixSoftware) *pPixSoftware = LAVPixFmt_NV12; return S_OK; } STDMETHODIMP_(REFERENCE_TIME) CDecQuickSync::GetFrameDuration() { CMediaType &mt = m_pCallback->GetInputMediaType(); REFERENCE_TIME rtDuration = 0; videoFormatTypeHandler(mt.Format(), mt.FormatType(), nullptr, &rtDuration, nullptr, nullptr); return (m_bInterlaced && m_bDI && m_pSettings->GetHWAccelDeintOutput() == DeintOutput_FramePerField) ? rtDuration / 2 : rtDuration; } STDMETHODIMP_(BOOL) CDecQuickSync::IsInterlaced(BOOL bAllowGuess) { return (m_bInterlaced || m_pSettings->GetDeinterlacingMode() == DeintMode_Force) && !m_bDI; } ================================================ FILE: decoder/LAVVideo/decoders/quicksync.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DecBase.h" #include "IQuickSyncDecoder.h" typedef IQuickSyncDecoder *__stdcall pcreateQuickSync(); typedef void __stdcall pdestroyQuickSync(IQuickSyncDecoder *); typedef DWORD __stdcall pcheck(); #include class CDecQuickSync : public CDecBase { public: CDecQuickSync(void); virtual ~CDecQuickSync(void); // ILAVDecoder STDMETHODIMP Check(); STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware); STDMETHODIMP_(REFERENCE_TIME) GetFrameDuration(); STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess); STDMETHODIMP_(const WCHAR *) GetDecoderName() { return L"quicksync"; } STDMETHODIMP PostConnect(IPin *pPin); STDMETHODIMP GetHWAccelActiveDevice(BSTR *pstrDeviceName) { CheckPointer(pstrDeviceName, E_POINTER); *pstrDeviceName = SysAllocString(L"Intel\xae QuickSync"); if (!*pstrDeviceName) return E_OUTOFMEMORY; return S_OK; } // CDecBase STDMETHODIMP Init(); private: STDMETHODIMP DestroyDecoder(bool bFull); static HRESULT QS_DeliverSurfaceCallback(void *obj, QsFrameData *data); STDMETHODIMP HandleFrame(QsFrameData *data); STDMETHODIMP CheckH264Sequence(const BYTE *buffer, size_t buflen, int nal_size, int *pRefFrames = nullptr, int *pProfile = nullptr, int *pLevel = nullptr); private: struct { HMODULE quickSyncLib; pcreateQuickSync *create; pdestroyQuickSync *destroy; pcheck *check; } qs; IQuickSyncDecoder *m_pDecoder = nullptr; BOOL m_bNeedSequenceCheck = FALSE; BOOL m_bInterlaced = TRUE; BOOL m_bDI = FALSE; BOOL m_bAVC1 = FALSE; int m_nAVCNalSize = 0; BOOL m_bEndOfSequence = FALSE; BOOL m_bUseTimestampQueue; std::queue m_timestampQueue; DXVA2_ExtendedFormat m_DXVAExtendedFormat; FOURCC m_Codec = 0; IDirect3DDeviceManager9 *m_pD3DDevMngr = nullptr; }; ================================================ FILE: decoder/LAVVideo/decoders/wmv9mft.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "wmv9mft.h" #include #include #include #include #include "parsers/VC1HeaderParser.h" EXTERN_GUID(CLSID_CWMVDecMediaObject, 0x82d353df, 0x90bd, 0x4382, 0x8b, 0xc2, 0x3f, 0x61, 0x92, 0xb7, 0x6e, 0x34); //////////////////////////////////////////////////////////////////////////////// // Constructor //////////////////////////////////////////////////////////////////////////////// ILAVDecoder *CreateDecoderWMV9MFT() { return new CDecWMV9MFT(); } //////////////////////////////////////////////////////////////////////////////// // WMV9 MFT decoder implementation //////////////////////////////////////////////////////////////////////////////// CDecWMV9MFT::CDecWMV9MFT(void) : CDecBase() { memset(&MF, 0, sizeof(MF)); } CDecWMV9MFT::~CDecWMV9MFT(void) { DestroyDecoder(true); } STDMETHODIMP CDecWMV9MFT::DestroyDecoder(bool bFull) { SAFE_DELETE(m_vc1Header); { CAutoLock lock(&m_BufferCritSec); for (auto it = m_BufferQueue.begin(); it != m_BufferQueue.end(); it++) { SafeRelease(&(*it)->pBuffer); delete (*it); } m_BufferQueue.clear(); } if (bFull) { SafeRelease(&m_pMFT); if (MF.Shutdown) MF.Shutdown(); FreeLibrary(MF.mfplat); } return S_OK; } #define GET_PROC_MF(name) \ MF.name = (tMF##name *)GetProcAddress(MF.mfplat, "MF" #name); \ if (MF.name == nullptr) \ { \ DbgLog((LOG_ERROR, 10, L"-> Failed to load function \"%s\"", TEXT("MF") TEXT(#name))); \ return E_FAIL; \ } // ILAVDecoder STDMETHODIMP CDecWMV9MFT::Init() { DbgLog((LOG_TRACE, 10, L"CDecWMV9MFT::Init(): Trying to open WMV9 MFT decoder")); HRESULT hr = S_OK; MF.mfplat = LoadLibrary(L"mfplat.dll"); if (!MF.mfplat) { DbgLog((LOG_TRACE, 10, L"-> Failed to load mfplat.dll")); return E_FAIL; } GET_PROC_MF(Startup); GET_PROC_MF(Shutdown); GET_PROC_MF(CreateMediaType); GET_PROC_MF(CreateSample); GET_PROC_MF(CreateAlignedMemoryBuffer); GET_PROC_MF(AverageTimePerFrameToFrameRate); MF.Startup(MF_VERSION, MFSTARTUP_LITE); hr = CoCreateInstance(CLSID_CWMVDecMediaObject, nullptr, CLSCTX_INPROC_SERVER, IID_IMFTransform, (void **)&m_pMFT); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to create MFT object")); return hr; } // Force decoder deinterlacing, dxva and FI to off IPropertyStore *pProp = nullptr; hr = m_pMFT->QueryInterface(&pProp); if (SUCCEEDED(hr)) { PROPVARIANT variant; InitPropVariantFromBoolean(FALSE, &variant); pProp->SetValue(MFPKEY_DECODER_DEINTERLACING, variant); pProp->SetValue(MFPKEY_DXVA_ENABLED, variant); pProp->SetValue(MFPKEY_FI_ENABLED, variant); SafeRelease(&pProp); } return S_OK; } static GUID VerifySubtype(AVCodecID codec, GUID subtype) { if (codec == AV_CODEC_ID_WMV3) { return MEDIASUBTYPE_WMV3; } else { if (subtype == MEDIASUBTYPE_WVC1 || subtype == MEDIASUBTYPE_wvc1) return MEDIASUBTYPE_WVC1; else if (subtype == MEDIASUBTYPE_WMVA || subtype == MEDIASUBTYPE_wmva) return MEDIASUBTYPE_WMVA; else // fallback return MEDIASUBTYPE_WVC1; } } STDMETHODIMP CDecWMV9MFT::InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData) { HRESULT hr = S_OK; DbgLog((LOG_TRACE, 10, L"CDecWMV9MFT::InitDecoder(): Initializing WMV9 MFT decoder")); DestroyDecoder(false); BITMAPINFOHEADER *pBMI = nullptr; REFERENCE_TIME rtAvg = 0; DWORD dwARX = 0, dwARY = 0; videoFormatTypeHandler(*pmt, &pBMI, &rtAvg, &dwARX, &dwARY); size_t extralen = 0; BYTE *extra = nullptr; getExtraData(*pmt, nullptr, &extralen); if (extralen > 0) { extra = (BYTE *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData(*pmt, extra, &extralen); } if (codec == AV_CODEC_ID_VC1 && extralen) { size_t i = 0; for (i = 0; i < (extralen - 4); i++) { uint32_t code = AV_RB32(extra + i); if ((code & ~0xFF) == 0x00000100) break; } if (i == 0) { memmove(extra + 1, extra, extralen); *extra = 0; extralen++; } else if (i > 1) { DbgLog((LOG_TRACE, 10, L"-> VC-1 Header at position %u (should be 0 or 1)", i)); } } if (extralen > 0) { m_vc1Header = new CVC1HeaderParser(extra, extralen, codec); } /* Create input type */ m_nCodecId = codec; IMFMediaType *pMTIn = nullptr; MF.CreateMediaType(&pMTIn); pMTIn->SetUINT32(MF_MT_COMPRESSED, TRUE); pMTIn->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, FALSE); pMTIn->SetUINT32(MF_MT_FIXED_SIZE_SAMPLES, FALSE); pMTIn->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); pMTIn->SetGUID(MF_MT_SUBTYPE, VerifySubtype(codec, pmt->subtype)); MFSetAttributeSize(pMTIn, MF_MT_FRAME_SIZE, pBMI->biWidth, pBMI->biHeight); UINT32 rateNum = 0, rateDen = 0; MF.AverageTimePerFrameToFrameRate(rtAvg, &rateNum, &rateDen); MFSetAttributeRatio(pMTIn, MF_MT_FRAME_RATE, rateNum, rateDen); if (dwARX != 0 && dwARY != 0) { int uParX = 1, uParY = 1; av_reduce(&uParX, &uParY, dwARX * pBMI->biHeight, dwARY * pBMI->biWidth, INT_MAX); MFSetAttributeRatio(pMTIn, MF_MT_PIXEL_ASPECT_RATIO, uParX, uParY); } pMTIn->SetBlob(MF_MT_USER_DATA, extra, (UINT32)extralen); av_freep(&extra); hr = m_pMFT->SetInputType(0, pMTIn, 0); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to set input type on MFT")); return hr; } /* Create output type */ hr = SelectOutputType(); SafeRelease(&pMTIn); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to set output type on MFT")); return hr; } IMFMediaType *pMTOut = nullptr; m_pMFT->GetOutputCurrentType(0, &pMTOut); m_bInterlaced = MFGetAttributeUINT32(pMTOut, MF_MT_INTERLACE_MODE, MFVideoInterlace_Unknown) > MFVideoInterlace_Progressive; SafeRelease(&pMTOut); m_bManualReorder = (codec == AV_CODEC_ID_VC1) && !(m_pCallback->GetDecodeFlags() & LAV_VIDEO_DEC_FLAG_ONLY_DTS); return S_OK; } STDMETHODIMP CDecWMV9MFT::SelectOutputType() { HRESULT hr = S_OK; int idx = 0; m_OutPixFmt = LAVPixFmt_None; IMFMediaType *pMTOut = nullptr; while (SUCCEEDED(hr = m_pMFT->GetOutputAvailableType(0, idx++, &pMTOut)) && m_OutPixFmt == LAVPixFmt_None) { GUID outSubtype; if (SUCCEEDED(pMTOut->GetGUID(MF_MT_SUBTYPE, &outSubtype))) { if (outSubtype == MEDIASUBTYPE_NV12) { hr = m_pMFT->SetOutputType(0, pMTOut, 0); m_OutPixFmt = LAVPixFmt_NV12; break; } else if (outSubtype == MEDIASUBTYPE_YV12) { hr = m_pMFT->SetOutputType(0, pMTOut, 0); m_OutPixFmt = LAVPixFmt_YUV420; break; } } SafeRelease(&pMTOut); } return hr; } IMFMediaBuffer *CDecWMV9MFT::CreateMediaBuffer(const BYTE *pData, DWORD dwDataLen) { HRESULT hr; IMFMediaBuffer *pBuffer = nullptr; hr = MF.CreateAlignedMemoryBuffer(dwDataLen, MF_16_BYTE_ALIGNMENT, &pBuffer); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"Unable to allocate MF Media Buffer, hr: 0x%x", hr)); goto done; } BYTE *pOutBuffer = nullptr; hr = pBuffer->Lock(&pOutBuffer, NULL, NULL); if (FAILED(hr)) { SafeRelease(&pBuffer); DbgLog((LOG_ERROR, 10, L"Unable to lock MF Media Buffer, hr: 0x%x", hr)); goto done; } memcpy(pOutBuffer, pData, dwDataLen); pBuffer->Unlock(); pBuffer->SetCurrentLength(dwDataLen); done: return pBuffer; } STDMETHODIMP CDecWMV9MFT::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pMediaSample) { HRESULT hr = S_OK; DWORD dwStatus = 0; hr = m_pMFT->GetInputStatus(0, &dwStatus); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> GetInputStatus() failed with hr: 0x%x", hr)); return S_FALSE; } if (!(dwStatus & MFT_INPUT_STATUS_ACCEPT_DATA)) return S_FALSE; if (m_vc1Header && (m_bManualReorder || m_bNeedKeyFrame)) { AVPictureType pictype = m_vc1Header->ParseVC1PictureType(buffer, buflen); if (m_bManualReorder) { if (pictype == AV_PICTURE_TYPE_I || pictype == AV_PICTURE_TYPE_P) { if (m_bReorderBufferValid) m_timestampQueue.push(m_rtReorderBuffer); m_rtReorderBuffer = rtStart; m_bReorderBufferValid = TRUE; } else { m_timestampQueue.push(rtStart); } } if (m_bNeedKeyFrame) { if (pictype != AV_PICTURE_TYPE_I) { if (m_bManualReorder) m_timestampQueue.pop(); return S_OK; } else { m_bNeedKeyFrame = FALSE; bSyncPoint = TRUE; } } } IMFSample *pSample = nullptr; hr = MF.CreateSample(&pSample); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"Unable to allocate MF Sample, hr: 0x%x", hr)); return E_FAIL; } IMFMediaBuffer *pMFBuffer = CreateMediaBuffer(buffer, buflen); if (!pMFBuffer) { DbgLog((LOG_TRACE, 10, L"Unable to allocate media buffer")); SafeRelease(&pSample); return E_FAIL; } pSample->AddBuffer(pMFBuffer); if (rtStart != AV_NOPTS_VALUE) { pSample->SetSampleTime(rtStart); if (rtStop != AV_NOPTS_VALUE && rtStop > (rtStart - 1)) pSample->SetSampleDuration(rtStop - rtStart); } pSample->SetUINT32(MFSampleExtension_CleanPoint, bSyncPoint); pSample->SetUINT32(MFSampleExtension_Discontinuity, bDiscontinuity); hr = m_pMFT->ProcessInput(0, pSample, 0); if (hr == MF_E_NOTACCEPTING) { // Not accepting data right now, try to process output and try again ProcessOutput(); hr = m_pMFT->ProcessInput(0, pSample, 0); } SafeRelease(&pMFBuffer); SafeRelease(&pSample); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> ProcessInput failed with hr: 0x%x", hr)); return E_FAIL; } return ProcessOutput(); } static inline void memcpy_plane(BYTE *dst, const BYTE *src, ptrdiff_t width, ptrdiff_t stride, int height) { for (int i = 0; i < height; i++) { memcpy(dst, src, width); dst += stride; src += width; } } IMFMediaBuffer *CDecWMV9MFT::GetBuffer(DWORD dwRequiredSize) { CAutoLock lock(&m_BufferCritSec); HRESULT hr; Buffer *buffer = nullptr; for (auto it = m_BufferQueue.begin(); it != m_BufferQueue.end(); it++) { if (!(*it)->used) { buffer = *it; break; } } if (buffer) { // Validate Size if (buffer->size < dwRequiredSize || !buffer->pBuffer) { SafeRelease(&buffer->pBuffer); hr = MF.CreateAlignedMemoryBuffer(dwRequiredSize, MF_32_BYTE_ALIGNMENT, &buffer->pBuffer); if (FAILED(hr)) return nullptr; buffer->size = dwRequiredSize; } } else { // Create a new buffer DbgLog((LOG_TRACE, 10, L"Allocating new buffer for WMV9 MFT")); buffer = new Buffer(); hr = MF.CreateAlignedMemoryBuffer(dwRequiredSize, MF_32_BYTE_ALIGNMENT, &buffer->pBuffer); if (FAILED(hr)) { delete buffer; return nullptr; } buffer->size = dwRequiredSize; m_BufferQueue.push_back(buffer); } buffer->used = 1; buffer->pBuffer->AddRef(); buffer->pBuffer->SetCurrentLength(0); return buffer->pBuffer; } void CDecWMV9MFT::ReleaseBuffer(IMFMediaBuffer *pBuffer) { CAutoLock lock(&m_BufferCritSec); Buffer *buffer = nullptr; for (auto it = m_BufferQueue.begin(); it != m_BufferQueue.end(); it++) { if ((*it)->pBuffer == pBuffer) { (*it)->used = 0; break; } } pBuffer->Release(); } void CDecWMV9MFT::wmv9_buffer_destruct(LAVFrame *pFrame) { CDecWMV9MFT *pDec = (CDecWMV9MFT *)pFrame->priv_data; IMFMediaBuffer *pMFBuffer = (IMFMediaBuffer *)pFrame->data[3]; pMFBuffer->Unlock(); pDec->ReleaseBuffer(pMFBuffer); } STDMETHODIMP CDecWMV9MFT::ProcessOutput() { HRESULT hr = S_OK; DWORD dwStatus = 0; MFT_OUTPUT_STREAM_INFO outputInfo = {0}; m_pMFT->GetOutputStreamInfo(0, &outputInfo); IMFMediaBuffer *pMFBuffer = nullptr; ASSERT(!(outputInfo.dwFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES)); MFT_OUTPUT_DATA_BUFFER OutputBuffer = {0}; if (!(outputInfo.dwFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES)) { pMFBuffer = GetBuffer(outputInfo.cbSize); if (!pMFBuffer) { DbgLog((LOG_TRACE, 10, L"Unable to allocate media buffere")); return E_FAIL; } IMFSample *pSampleOut = nullptr; hr = MF.CreateSample(&pSampleOut); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"Unable to allocate MF sample, hr: 0x%x", hr)); ReleaseBuffer(pMFBuffer); return E_FAIL; } pSampleOut->AddBuffer(pMFBuffer); OutputBuffer.pSample = pSampleOut; } hr = m_pMFT->ProcessOutput(0, 1, &OutputBuffer, &dwStatus); // We don't process events, just release them SafeRelease(&OutputBuffer.pEvents); // handle stream format changes if (hr == MF_E_TRANSFORM_STREAM_CHANGE || OutputBuffer.dwStatus == MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE) { SafeRelease(&OutputBuffer.pSample); ReleaseBuffer(pMFBuffer); hr = SelectOutputType(); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> Failed to handle stream change, hr: %x", hr)); return E_FAIL; } // try again with the new type, it should work now! return ProcessOutput(); } // the MFT generated no output, discard the sample and return if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT || OutputBuffer.dwStatus == MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE) { SafeRelease(&OutputBuffer.pSample); ReleaseBuffer(pMFBuffer); return S_FALSE; } // unknown error condition if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"-> ProcessOutput failed with hr: %x", hr)); SafeRelease(&OutputBuffer.pSample); ReleaseBuffer(pMFBuffer); return E_FAIL; } LAVFrame *pFrame = nullptr; AllocateFrame(&pFrame); IMFMediaType *pMTOut = nullptr; m_pMFT->GetOutputCurrentType(0, &pMTOut); MFGetAttributeSize(pMTOut, MF_MT_FRAME_SIZE, (UINT32 *)&pFrame->width, (UINT32 *)&pFrame->height); pFrame->format = m_OutPixFmt; pFrame->sw_format = pFrame->format; AVRational pixel_aspect_ratio = {1, 1}; MFGetAttributeRatio(pMTOut, MF_MT_PIXEL_ASPECT_RATIO, (UINT32 *)&pixel_aspect_ratio.num, (UINT32 *)&pixel_aspect_ratio.den); AVRational display_aspect_ratio = {0, 0}; av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den, (int64_t)pixel_aspect_ratio.num * pFrame->width, (int64_t)pixel_aspect_ratio.den * pFrame->height, INT_MAX); pFrame->aspect_ratio = display_aspect_ratio; pFrame->interlaced = MFGetAttributeUINT32(OutputBuffer.pSample, MFSampleExtension_Interlaced, FALSE); pFrame->repeat = MFGetAttributeUINT32(OutputBuffer.pSample, MFSampleExtension_RepeatFirstField, FALSE); LAVDeintFieldOrder fo = m_pSettings->GetDeintFieldOrder(); pFrame->tff = (fo == DeintFieldOrder_Auto) ? !MFGetAttributeUINT32(OutputBuffer.pSample, MFSampleExtension_BottomFieldFirst, FALSE) : (fo == DeintFieldOrder_TopFieldFirst); if (pFrame->interlaced && !m_bInterlaced) m_bInterlaced = TRUE; pFrame->interlaced = (pFrame->interlaced || (m_bInterlaced && m_pSettings->GetDeinterlacingMode() == DeintMode_Aggressive) || m_pSettings->GetDeinterlacingMode() == DeintMode_Force) && !(m_pSettings->GetDeinterlacingMode() == DeintMode_Disable); pFrame->ext_format.VideoPrimaries = MFGetAttributeUINT32(pMTOut, MF_MT_VIDEO_PRIMARIES, MFVideoPrimaries_Unknown); pFrame->ext_format.VideoTransferFunction = MFGetAttributeUINT32(pMTOut, MF_MT_TRANSFER_FUNCTION, MFVideoTransFunc_Unknown); pFrame->ext_format.VideoTransferMatrix = MFGetAttributeUINT32(pMTOut, MF_MT_YUV_MATRIX, MFVideoTransferMatrix_Unknown); pFrame->ext_format.VideoChromaSubsampling = MFGetAttributeUINT32(pMTOut, MF_MT_VIDEO_CHROMA_SITING, MFVideoChromaSubsampling_Unknown); pFrame->ext_format.NominalRange = MFGetAttributeUINT32(pMTOut, MF_MT_VIDEO_NOMINAL_RANGE, MFNominalRange_Unknown); // HACK: don't flag range=limited if its the only value set, since its also the implied default, this helps to avoid // a reconnect The MFT always sets this value, even if the bitstream says nothing about it, causing a reconnect on // every vc1/wmv3 file if (pFrame->ext_format.value == 0x2000) pFrame->ext_format.value = 0; // Timestamps if (m_bManualReorder) { if (!m_timestampQueue.empty()) { pFrame->rtStart = m_timestampQueue.front(); m_timestampQueue.pop(); LONGLONG llDuration = 0; hr = OutputBuffer.pSample->GetSampleDuration(&llDuration); if (SUCCEEDED(hr) && llDuration > 0) { pFrame->rtStop = pFrame->rtStart + llDuration; } } } else { LONGLONG llTimestamp = 0; hr = OutputBuffer.pSample->GetSampleTime(&llTimestamp); if (SUCCEEDED(hr)) { pFrame->rtStart = llTimestamp; LONGLONG llDuration = 0; hr = OutputBuffer.pSample->GetSampleDuration(&llDuration); if (SUCCEEDED(hr) && llDuration > 0) { pFrame->rtStop = pFrame->rtStart + llDuration; } } } SafeRelease(&pMTOut); // Lock memory in the buffer BYTE *pBuffer = nullptr; pMFBuffer->Lock(&pBuffer, NULL, NULL); // Check alignment // If not properly aligned, we need to make the data aligned. int alignment = (m_OutPixFmt == LAVPixFmt_NV12) ? 16 : 32; if ((pFrame->width % alignment) != 0) { hr = AllocLAVFrameBuffers(pFrame); if (FAILED(hr)) { pMFBuffer->Unlock(); ReleaseBuffer(pMFBuffer); SafeRelease(&OutputBuffer.pSample); return hr; } size_t ySize = pFrame->width * pFrame->height; memcpy_plane(pFrame->data[0], pBuffer, pFrame->width, pFrame->stride[0], pFrame->height); if (m_OutPixFmt == LAVPixFmt_NV12) { memcpy_plane(pFrame->data[1], pBuffer + ySize, pFrame->width, pFrame->stride[1], pFrame->height / 2); } else if (m_OutPixFmt == LAVPixFmt_YUV420) { size_t uvSize = ySize / 4; memcpy_plane(pFrame->data[2], pBuffer + ySize, pFrame->width / 2, pFrame->stride[2], pFrame->height / 2); memcpy_plane(pFrame->data[1], pBuffer + ySize + uvSize, pFrame->width / 2, pFrame->stride[1], pFrame->height / 2); } pMFBuffer->Unlock(); ReleaseBuffer(pMFBuffer); } else { if (m_OutPixFmt == LAVPixFmt_NV12) { pFrame->data[0] = pBuffer; pFrame->data[1] = pBuffer + pFrame->width * pFrame->height; pFrame->stride[0] = pFrame->stride[1] = pFrame->width; } else if (m_OutPixFmt == LAVPixFmt_YUV420) { pFrame->data[0] = pBuffer; pFrame->data[2] = pBuffer + pFrame->width * pFrame->height; pFrame->data[1] = pFrame->data[2] + (pFrame->width / 2) * (pFrame->height / 2); pFrame->stride[0] = pFrame->width; pFrame->stride[1] = pFrame->stride[2] = pFrame->width / 2; } pFrame->data[3] = (BYTE *)pMFBuffer; pFrame->destruct = wmv9_buffer_destruct; pFrame->priv_data = this; } pFrame->flags |= LAV_FRAME_FLAG_BUFFER_MODIFY; Deliver(pFrame); SafeRelease(&OutputBuffer.pSample); if (OutputBuffer.dwStatus == MFT_OUTPUT_DATA_BUFFER_INCOMPLETE) return ProcessOutput(); return hr; } STDMETHODIMP CDecWMV9MFT::Flush() { DbgLog((LOG_TRACE, 10, L"CDecWMV9MFT::Flush(): Flushing WMV9 decoder")); m_pMFT->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0); std::queue().swap(m_timestampQueue); m_rtReorderBuffer = AV_NOPTS_VALUE; m_bReorderBufferValid = FALSE; m_bNeedKeyFrame = TRUE; return __super::Flush(); } STDMETHODIMP CDecWMV9MFT::EndOfStream() { if (m_bReorderBufferValid) m_timestampQueue.push(m_rtReorderBuffer); m_bReorderBufferValid = FALSE; m_rtReorderBuffer = AV_NOPTS_VALUE; m_pMFT->ProcessMessage(MFT_MESSAGE_COMMAND_DRAIN, 0); ProcessOutput(); return S_OK; } STDMETHODIMP CDecWMV9MFT::GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware) { if (pPix) *pPix = (m_OutPixFmt != LAVPixFmt_None) ? m_OutPixFmt : LAVPixFmt_NV12; if (pBpp) *pBpp = 8; if (pPixSoftware) *pPixSoftware = (m_OutPixFmt != LAVPixFmt_None) ? m_OutPixFmt : LAVPixFmt_NV12; return S_OK; } STDMETHODIMP_(BOOL) CDecWMV9MFT::IsInterlaced(BOOL bAllowGuess) { return (m_bInterlaced || m_pSettings->GetDeinterlacingMode() == DeintMode_Force); } ================================================ FILE: decoder/LAVVideo/decoders/wmv9mft.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DecBase.h" #include #include #include //////////////////////////////////////////////////////////////////////////////// // Dynlink types //////////////////////////////////////////////////////////////////////////////// typedef HRESULT STDAPICALLTYPE tMFStartup(ULONG Version, DWORD dwFlags); typedef HRESULT STDAPICALLTYPE tMFShutdown(); typedef HRESULT STDAPICALLTYPE tMFCreateMediaType(IMFMediaType **ppMFType); typedef HRESULT STDAPICALLTYPE tMFCreateSample(IMFSample **ppIMFSample); typedef HRESULT STDAPICALLTYPE tMFCreateAlignedMemoryBuffer(DWORD cbMaxLength, DWORD cbAligment, IMFMediaBuffer **ppBuffer); typedef HRESULT STDAPICALLTYPE tMFAverageTimePerFrameToFrameRate(UINT64 unAverageTimePerFrame, UINT32 *punNumerator, UINT32 *punDenominator); #define MFMETHOD(name) tMF##name *##name //////////////////////////////////////////////////////////////////////////////// // Class //////////////////////////////////////////////////////////////////////////////// class CVC1HeaderParser; class CDecWMV9MFT : public CDecBase { typedef struct _Buffer { IMFMediaBuffer *pBuffer = nullptr; DWORD size = 0; bool used = false; } Buffer; public: CDecWMV9MFT(void); virtual ~CDecWMV9MFT(void); // ILAVDecoder STDMETHODIMP InitDecoder(AVCodecID codec, const CMediaType *pmt, const MediaSideDataFFMpeg *pSideData); STDMETHODIMP Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, BOOL bSyncPoint, BOOL bDiscontinuity, IMediaSample *pSample); STDMETHODIMP Flush(); STDMETHODIMP EndOfStream(); STDMETHODIMP GetPixelFormat(LAVPixelFormat *pPix, int *pBpp, LAVPixelFormat *pPixSoftware); STDMETHODIMP_(BOOL) IsInterlaced(BOOL bAllowGuess); STDMETHODIMP_(const WCHAR *) GetDecoderName() { return L"wmv9 mft"; } STDMETHODIMP HasThreadSafeBuffers() { return S_OK; } // CDecBase STDMETHODIMP Init(); private: STDMETHODIMP DestroyDecoder(bool bFull); STDMETHODIMP ProcessOutput(); STDMETHODIMP SelectOutputType(); IMFMediaBuffer *CreateMediaBuffer(const BYTE *pData, DWORD dwDataLen); static void wmv9_buffer_destruct(LAVFrame *pFrame); IMFMediaBuffer *GetBuffer(DWORD dwRequiredSize); void ReleaseBuffer(IMFMediaBuffer *pBuffer); private: IMFTransform *m_pMFT = nullptr; BOOL m_bInterlaced = TRUE; LAVPixelFormat m_OutPixFmt = LAVPixFmt_None; AVCodecID m_nCodecId = AV_CODEC_ID_NONE; CCritSec m_BufferCritSec; std::vector m_BufferQueue; BOOL m_bNeedKeyFrame = TRUE; BOOL m_bManualReorder = FALSE; BOOL m_bReorderBufferValid = FALSE; REFERENCE_TIME m_rtReorderBuffer = AV_NOPTS_VALUE; std::queue m_timestampQueue; CVC1HeaderParser *m_vc1Header = nullptr; struct { HMODULE mfplat = NULL; MFMETHOD(Startup); MFMETHOD(Shutdown); MFMETHOD(CreateAlignedMemoryBuffer); MFMETHOD(CreateSample); MFMETHOD(CreateMediaType); MFMETHOD(AverageTimePerFrameToFrameRate); } MF; }; ================================================ FILE: decoder/LAVVideo/dllmain.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Based on the SampleParser Template by GDCL // -------------------------------------------------------------------------------- // Copyright (c) GDCL 2004. All Rights Reserved. // You are free to re-use this as the basis for your own filter development, // provided you retain this copyright notice in the source. // http://www.gdcl.co.uk // -------------------------------------------------------------------------------- #include "stdafx.h" // Initialize the GUIDs #include #include #include #include "LAVVideo.h" #include "VideoSettingsProp.h" #include "moreuuids.h" #include "IMediaSideDataFFmpeg.h" #include "registry.h" // --- COM factory table and registration code -------------- const AMOVIESETUP_PIN sudpPinsVideoDec[] = {{L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, CLAVVideo::sudPinTypesInCount, CLAVVideo::sudPinTypesIn}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, CLAVVideo::sudPinTypesOutCount, CLAVVideo::sudPinTypesOut}}; const AMOVIESETUP_FILTER sudFilterReg = {&__uuidof(CLAVVideo), // filter clsid L"LAV Video Decoder", // filter name MERIT_PREFERRED + 3, // merit countof(sudpPinsVideoDec), sudpPinsVideoDec, CLSID_LegacyAmFilterCategory}; // --- COM factory table and registration code -------------- // DirectShow base class COM factory requires this table, // declaring all the COM objects in this DLL CFactoryTemplate g_Templates[] = { // one entry for each CoCreate-able object {sudFilterReg.strName, sudFilterReg.clsID, CreateInstance, nullptr, &sudFilterReg}, // This entry is for the property page. {L"LAV Video Properties", &CLSID_LAVVideoSettingsProp, CreateInstance, nullptr, nullptr}, {L"LAV Video Format Settings", &CLSID_LAVVideoFormatsProp, CreateInstance, nullptr, nullptr}}; int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); // self-registration entrypoint STDAPI DllRegisterServer() { // base classes will handle registration using the factory template table return AMovieDllRegisterServer2(true); } STDAPI DllUnregisterServer() { // base classes will handle de-registration using the factory template table return AMovieDllRegisterServer2(false); } // if we declare the correct C runtime entrypoint and then forward it to the DShow base // classes we will be sure that both the C/C++ runtimes and the base classes are initialized // correctly extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD dwReason, LPVOID lpReserved) { return DllEntryPoint(reinterpret_cast(hDllHandle), dwReason, lpReserved); } void CALLBACK OpenConfiguration(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) { HRESULT hr = S_OK; CUnknown *pInstance = CreateInstance(nullptr, &hr); IBaseFilter *pFilter = nullptr; pInstance->NonDelegatingQueryInterface(IID_IBaseFilter, (void **)&pFilter); if (pFilter) { pFilter->AddRef(); CBaseDSPropPage::ShowPropPageDialog(pFilter); } delete pInstance; } ================================================ FILE: decoder/LAVVideo/parsers/AnnexBConverter.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "AnnexBConverter.h" #include "libavutil/intreadwrite.h" CAnnexBConverter::CAnnexBConverter(void) { } CAnnexBConverter::~CAnnexBConverter(void) { } static HRESULT alloc_and_copy(uint8_t **poutbuf, int *poutbuf_size, const uint8_t *in, uint32_t in_size) { uint32_t offset = *poutbuf_size; uint8_t nal_header_size = offset ? 3 : 4; void *tmp; *poutbuf_size += in_size + nal_header_size; tmp = av_realloc(*poutbuf, *poutbuf_size); if (!tmp) return E_OUTOFMEMORY; *poutbuf = (uint8_t *)tmp; memcpy(*poutbuf + nal_header_size + offset, in, in_size); if (!offset) { AV_WB32(*poutbuf, 1); } else { (*poutbuf + offset)[0] = (*poutbuf + offset)[1] = 0; (*poutbuf + offset)[2] = 1; } return S_OK; } HRESULT CAnnexBConverter::Convert(BYTE **poutbuf, int *poutbuf_size, const BYTE *buf, int buf_size) { int32_t nal_size; const uint8_t *buf_end = buf + buf_size; *poutbuf_size = 0; do { if (buf + m_NaluSize > buf_end) goto fail; if (m_NaluSize == 1) { nal_size = buf[0]; } else if (m_NaluSize == 2) { nal_size = AV_RB16(buf); } else { nal_size = AV_RB32(buf); if (m_NaluSize == 3) nal_size >>= 8; } buf += m_NaluSize; if (buf + nal_size > buf_end || nal_size < 0) goto fail; if (FAILED(alloc_and_copy(poutbuf, poutbuf_size, buf, nal_size))) goto fail; buf += nal_size; buf_size -= (nal_size + m_NaluSize); } while (buf_size > 0); return S_OK; fail: av_freep(poutbuf); return E_FAIL; } HRESULT CAnnexBConverter::ConvertHEVCExtradata(BYTE **poutbuf, int *poutbuf_size, const BYTE *buf, int buf_size) { if (buf_size < 23) return E_INVALIDARG; SetNALUSize(2); *poutbuf = nullptr; *poutbuf_size = 0; int num_arrays = buf[22]; int remaining_size = buf_size - 23; buf += 23; for (int i = 0; i < num_arrays; i++) { if (remaining_size < 3) break; int cnt = AV_RB16(buf + 1); buf += 3; remaining_size -= 3; for (int j = 0; j < cnt; j++) { if (remaining_size < 2) break; int len = AV_RB16(buf) + 2; if (remaining_size < len) break; alloc_and_copy(poutbuf, poutbuf_size, buf + 2, len - 2); buf += len; remaining_size -= len; } } return S_OK; } ================================================ FILE: decoder/LAVVideo/parsers/AnnexBConverter.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class CAnnexBConverter { public: CAnnexBConverter(void); ~CAnnexBConverter(void); HRESULT SetNALUSize(int nalusize) { m_NaluSize = nalusize; return S_OK; } HRESULT Convert(BYTE **poutbuf, int *poutbuf_size, const BYTE *buf, int buf_size); HRESULT ConvertHEVCExtradata(BYTE **poutbuf, int *poutbuf_size, const BYTE *buf, int buf_size); private: int m_NaluSize = 0; }; ================================================ FILE: decoder/LAVVideo/parsers/H264SequenceParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "H264SequenceParser.h" #include "ByteParser.h" #include "H264Nalu.h" CH264SequenceParser::CH264SequenceParser(void) { ZeroMemory(&sps, sizeof(sps)); ZeroMemory(&pps, sizeof(pps)); } CH264SequenceParser::~CH264SequenceParser(void) { } HRESULT CH264SequenceParser::ParseNALs(const BYTE *buffer, size_t buflen, int nal_size) { CH264Nalu nalu; nalu.SetBuffer(buffer, buflen, nal_size); while (nalu.ReadNext()) { const BYTE *data = nalu.GetDataBuffer() + 1; const size_t len = nalu.GetDataLength() - 1; if (nalu.GetType() == NALU_TYPE_SPS) { ParseSPS(data, len); break; } } return S_OK; } static void SPSDecodeScalingList(CByteParser &parser, int size) { int i, last = 8, next = 8; int matrix = parser.BitRead(1); if (matrix) { for (i = 0; i < size; i++) { if (next) next = (last + parser.SExpGolombRead()) & 0xff; if (!i && !next) { /* matrix not written */ break; } last = next ? next : last; } } } HRESULT CH264SequenceParser::ParseSPS(const BYTE *buffer, size_t buflen) { CByteParser parser(buffer, buflen); int i; ZeroMemory(&sps, sizeof(sps)); // Defaults sps.valid = 1; sps.primaries = AVCOL_PRI_UNSPECIFIED; sps.trc = AVCOL_TRC_UNSPECIFIED; sps.colorspace = AVCOL_SPC_UNSPECIFIED; sps.full_range = -1; // Parse sps.profile = parser.BitRead(8); parser.BitRead(4); // constraint flags parser.BitRead(4); // reserved sps.level = parser.BitRead(8); parser.UExpGolombRead(); // sps id if (sps.profile == 100 || sps.profile == 110 || sps.profile == 122 || sps.profile == 244 || sps.profile == 44 || sps.profile == 83 || sps.profile == 86 || sps.profile == 118 || sps.profile == 128 || sps.profile == 144) { sps.chroma = (int)parser.UExpGolombRead(); if (sps.chroma == 3) parser.BitRead(1); sps.luma_bitdepth = (int)parser.UExpGolombRead() + 8; sps.chroma_bitdepth = (int)parser.UExpGolombRead() + 8; parser.BitRead(1); // transform_bypass // decode scaling matrices int scaling = parser.BitRead(1); if (scaling) { // Decode scaling lists SPSDecodeScalingList(parser, 16); // Intra, Y SPSDecodeScalingList(parser, 16); // Intra, Cr SPSDecodeScalingList(parser, 16); // Intra, Cb SPSDecodeScalingList(parser, 16); // Inter, Y SPSDecodeScalingList(parser, 16); // Inter, Cr SPSDecodeScalingList(parser, 16); // Inter, Cb SPSDecodeScalingList(parser, 64); // Intra, Y SPSDecodeScalingList(parser, 64); // Inter, Y if (sps.chroma == 3) { SPSDecodeScalingList(parser, 64); // Intra, Cr SPSDecodeScalingList(parser, 64); // Inter, Cr SPSDecodeScalingList(parser, 64); // Intra, Cb SPSDecodeScalingList(parser, 64); // Inter, Cb } } } else { sps.chroma = 1; sps.luma_bitdepth = 8; sps.chroma_bitdepth = 8; } parser.UExpGolombRead(); // log2_max_frame_num int poc_type = (int)parser.UExpGolombRead(); // poc_type if (poc_type == 0) parser.UExpGolombRead(); // log2_max_poc_lsb else if (poc_type == 1) { parser.BitRead(1); // delta_pic_order_always_zero_flag parser.SExpGolombRead(); // offset_for_non_ref_pic parser.SExpGolombRead(); // offset_for_top_to_bottom_field int cyclen = (int)parser.UExpGolombRead(); // poc_cycle_length for (i = 0; i < cyclen; i++) parser.SExpGolombRead(); // offset_for_ref_frame[i] } sps.ref_frames = parser.UExpGolombRead(); // ref_frame_count parser.BitRead(1); // gaps_in_frame_num_allowed_flag parser.UExpGolombRead(); // mb_width parser.UExpGolombRead(); // mb_height sps.interlaced = !parser.BitRead(1); // frame_mbs_only_flag if (sps.interlaced) parser.BitRead(1); // mb_aff parser.BitRead(1); // direct_8x8_inference_flag int crop = parser.BitRead(1); // crop if (crop) { parser.UExpGolombRead(); // crop_left parser.UExpGolombRead(); // crop_right parser.UExpGolombRead(); // crop_top parser.UExpGolombRead(); // crop_bottom } int vui_present = parser.BitRead(1); // vui_parameters_present_flag if (vui_present) { sps.ar_present = parser.BitRead(1); // aspect_ratio_info_present_flag if (sps.ar_present) { int ar_idc = parser.BitRead(8); // aspect_ratio_idc if (ar_idc == 255) { parser.BitRead(16); // sar.num parser.BitRead(16); // sar.den } } int overscan = parser.BitRead(1); // overscan_info_present_flag if (overscan) parser.BitRead(1); // overscan_appropriate_flag int vid_sig_type = parser.BitRead(1); // video_signal_type_present_flag if (vid_sig_type) { parser.BitRead(3); // video_format sps.full_range = parser.BitRead(1); // video_full_range_flag int colorinfo = parser.BitRead(1); // colour_description_present_flag if (colorinfo) { sps.primaries = parser.BitRead(8); sps.trc = parser.BitRead(8); sps.colorspace = parser.BitRead(8); } } } return S_OK; } ================================================ FILE: decoder/LAVVideo/parsers/H264SequenceParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class CH264SequenceParser { public: CH264SequenceParser(void); virtual ~CH264SequenceParser(void); HRESULT ParseNALs(const BYTE *buffer, size_t buflen, int nal_size); public: struct { int valid; int profile; int level; int chroma; int luma_bitdepth; int chroma_bitdepth; int ref_frames; int interlaced; int ar_present; int full_range; int primaries; int trc; int colorspace; } sps; struct { int valid; } pps; private: HRESULT ParseSPS(const BYTE *buffer, size_t buflen); }; ================================================ FILE: decoder/LAVVideo/parsers/HEVCSequenceParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "HEVCSequenceParser.h" #include "H264Nalu.h" #define HEVC_NAL_VPS 32 #define HEVC_NAL_SPS 33 #define HEVC_NAL_PPS 34 CHEVCSequenceParser::CHEVCSequenceParser() { ZeroMemory(&sps, sizeof(sps)); sps.bitdepth = 8; } CHEVCSequenceParser::~CHEVCSequenceParser() { } HRESULT CHEVCSequenceParser::ParseNALs(const BYTE *buffer, size_t buflen, int nal_size) { CH265Nalu nalu; nalu.SetBuffer(buffer, buflen, nal_size); while (nalu.ReadNext()) { const BYTE *data = nalu.GetDataBuffer() + 2; const size_t len = nalu.GetDataLength() - 2; if (nalu.GetType() == HEVC_NAL_SPS) { CH264NALUnescape unescapedNAL(data, len); ParseSPS(unescapedNAL.GetBuffer(), unescapedNAL.GetSize()); break; } } return S_OK; } HRESULT CHEVCSequenceParser::ParseSPS(const BYTE *buffer, size_t buflen) { CByteParser parser(buffer, buflen); int i; ZeroMemory(&sps, sizeof(sps)); sps.valid = 1; struct { int profile_present; int level_present; } Sublayers[7]; parser.BitSkip(4); // sps_video_parameter_set_id int max_sub_layers = parser.BitRead(3); // sps_max_sub_layers_minus1 parser.BitSkip(1); // sps_temporal_id_nesting_flag // profile tier level parser.BitSkip(2); // general_profile_space parser.BitSkip(1); // general_tier_flag sps.profile = parser.BitRead(5); // general_profile_idc for (i = 0; i < 32; i++) { int flag = parser.BitRead(1); if (sps.profile == 0 && i > 0 && flag) sps.profile = i; } parser.BitSkip(1); // general_progressive_source_flag parser.BitSkip(1); // general_interlaced_source_flag parser.BitSkip(1); // general_non_packed_constraint_flag parser.BitSkip(1); // general_frame_only_constraint_flag if (sps.profile == 4) { sps.rext_profile = parser.BitRead(8); // 8 constraint flags parser.BitSkip(1); // general_lower_bit_rate_constraint_flag parser.BitSkip(17); // general_reserved_zero_34bits parser.BitSkip(17); // general_reserved_zero_34bits } else { parser.BitSkip(21); // general_reserved_zero_43bits parser.BitSkip(22); // general_reserved_zero_43bits } parser.BitSkip(1); // general_reserved_zero_bit sps.level = parser.BitRead(8); // general_level_idc if (max_sub_layers > 7) return E_FAIL; for (i = 0; i < max_sub_layers; i++) { Sublayers[i].profile_present = parser.BitRead(1); // sub_layer_profile_present_flag Sublayers[i].level_present = parser.BitRead(1); // sub_layer_level_present_flag } if (max_sub_layers > 0) { for (i = max_sub_layers; i < 8; i++) parser.BitSkip(2); // reserved_zero_2bits } for (i = 0; i < max_sub_layers; i++) { if (Sublayers[i].profile_present) { parser.BitSkip(2); // general_profile_space parser.BitSkip(1); // general_tier_flag parser.BitSkip(5); // general_profile_idc parser.BitSkip(32); // profile_compatibility_flag[32] parser.BitSkip(1); // progressive_source_flag parser.BitSkip(1); // interlaced_source_flag parser.BitSkip(1); // non_packed_constraint_flag parser.BitSkip(1); // frame_only_constraint_flag parser.BitSkip(22); // reserved_zero_44bits parser.BitSkip(22); // reserved_zero_44bits } if (Sublayers[i].level_present) { parser.BitSkip(8); // level_idc } } parser.UExpGolombRead(); // sps_id sps.chroma = parser.UExpGolombRead(); // chroma_format_idc if (sps.chroma == 3) parser.BitRead(1); // separate_color_plane_flag parser.UExpGolombRead(); // width parser.UExpGolombRead(); // height if (parser.BitRead(1)) { // conformance_window_flag parser.UExpGolombRead(); // left offset parser.UExpGolombRead(); // right offset parser.UExpGolombRead(); // top offset parser.UExpGolombRead(); // bottom offset } sps.bitdepth = parser.UExpGolombRead() + 8; // bit_depth_luma_minus8 parser.UExpGolombRead(); // bit_depth_chroma_minus8 /*int log2_max_pic_order_count = parser.UExpGolombRead() + 4; // log2_max_pic_order_cnt_lsb_minus4 for (i = (parser.BitRead(1) ? 0 : max_sub_layers); i <= max_sub_layers; i++) { parser.UExpGolombRead(); // sps_max_dec_pic_buffering_minus1 parser.UExpGolombRead(); // sps_max_num_reorder_pics parser.UExpGolombRead(); // sps_max_latency_increase_plus1 } parser.UExpGolombRead(); // log2_min_luma_coding_block_size_minus3 parser.UExpGolombRead(); // log2_diff_max_min_luma_coding_block_size parser.UExpGolombRead(); // log2_min_luma_transform_block_size_minus2 parser.UExpGolombRead(); // log2_diff_max_min_luma_transform_block_size parser.UExpGolombRead(); // max_transform_hierarchy_depth_inter parser.UExpGolombRead(); // max_transform_hierarchy_depth_intra // scaling list if (parser.BitRead(1)) { // scaling_list_enabled_flag if (parser.BitRead(1)) { // sps_scaling_list_data_present_flag for (int sizeId = 0; sizeId < 4; sizeId++) { for (int matrixId = 0; matrixId < 6; matrixId += ((sizeId == 3) ? 3 : 1)) { if (!parser.BitRead(1)) { // scaling_list_pred_mode_flag parser.UExpGolombRead(); // scaling_list_pred_matrix_id_delta } else { if (sizeId > 1) parser.SExpGolombRead(); int coefNum = min(64, 1 << (4 + (sizeId << 1))); for (i = 0; i < coefNum; i++) parser.SExpGolombRead(); // scaling_list_delta_coef } } } } } parser.BitSkip(1); // amp_enabled_flag parser.BitSkip(1); // sao_enabled_flag if (parser.BitRead(1)) { // pcm_enabled_flag parser.BitSkip(4); // pcm_sample_bit_depth_luma_minus1 parser.BitSkip(4); // pcm_sample_bit_depth_chroma_minus1 parser.UExpGolombRead(); // log2_min_pcm_luma_coding_block_size_minus3 parser.UExpGolombRead(); // log2_diff_max_min_pcm_luma_coding_block_size parser.BitSkip(1); // pcm_loop_filter_disabled_flag } int num_short_term_ref_pic_set = parser.UExpGolombRead(); if (num_short_term_ref_pic_set > 64) return E_FAIL; // st_ref_pic_set for (i = 0; i < num_short_term_ref_pic_set; i++) { if (i > 0 && parser.BitRead(1)) { // inter_ref_pic_set_prediction_flag if (i == num_short_term_ref_pic_set) // only in slice header? parser.UExpGolombRead(); // delta_idx_minus1 parser.BitSkip(1); // delta_rps_sign parser.UExpGolombRead(); // abs_delta_rps_minus1 for (j = 0; j <= ShortTermRPS[i - 1].NumDeltaPocs; j++) { if (!parser.BitRead(1)) // used_by_curr_pic_flag parser.BitRead(1); // use_delta_flag } } else { int num_negative = parser.UExpGolombRead(); int num_positive = parser.UExpGolombRead(); ShortTermRPS[i].NumDeltaPocs = num_negative + num_positive; for (j = 0; j < num_negative; j++) { parser.UExpGolombRead(); // delta_poc_s0_minus1 parser.BitSkip(1); // used_by_curr_pic_s0_flag } for (j = 0; j < num_positive; j++) { parser.UExpGolombRead(); // delta_poc_s0_minus1 parser.BitSkip(1); // used_by_curr_pic_s0_flag } } } if (parser.BitRead(1)) { // long_term_ref_pics_present_flag int num_long_term = parser.UExpGolombRead(); for (i = 0; i < num_long_term; i++) { parser.BitSkip(log2_max_pic_order_count); parser.BitSkip(1); } } parser.BitSkip(1); // sps_temporal_mvp_enabled_flag parser.BitSkip(1); // strong_intra_smoothing_enabled_flag // VUI if (parser.BitRead(1)) { // vui_parameters_present_flag if (parser.BitRead(1)) { // aspect_ratio_info_present_flag if (parser.BitRead(8) == 255) { // aspect_ratio_idc parser.BitSkip(16); // sar_width parser.BitSkip(16); // sar_height } } if (parser.BitRead(1)) // overscan_info_present_flag parser.BitSkip(1); // overscan_appropriate_flag if (parser.BitRead(1)) { // video_signal_type_present_flag parser.BitSkip(3); // video_format parser.BitSkip(1); // video_full_range_flag if (parser.BitRead(1)) { // colour_description_present_flag parser.BitSkip(8); // colour_primaries parser.BitSkip(8); // transfer_characteristics parser.BitSkip(8); // matrix_coeffs } } if (parser.BitRead(1)) { // chroma_loc_info_present_flag parser.UExpGolombRead(); // chroma_sample_loc_type_top_field parser.UExpGolombRead(); // chroma_sample_loc_type_bottom_field } parser.BitSkip(1); // neutral_chroma_indication_flag parser.BitSkip(1); // field_seq_flag parser.BitSkip(1); // frame_field_info_present_flag if (parser.BitRead(1)) { // default_display_window_flag parser.UExpGolombRead(); // def_disp_win_left_offset parser.UExpGolombRead(); // def_disp_win_right_offset parser.UExpGolombRead(); // def_disp_win_top_offset parser.UExpGolombRead(); // def_disp_win_bottom_offset } if (parser.BitRead(1)) { // vui_timing_info_present_flag parser.BitSkip(32); // vui_num_units_in_tick parser.BitSkip(32); // vui_time_scale if (parser.BitRead(1)) // vui_poc_proportional_to_timing_flag parser.UExpGolombRead(); // vui_num_ticks_poc_diff_one_minus1 // hrd parameters if (parser.BitRead(1)) { // vui_hrd_parameters_present_flag int nal_hrd_parameters_present = parser.BitRead(1); int vcl_hrd_parameters_present = parser.BitRead(1); int sub_hrd_parameters_present = 0; if (nal_hrd_parameters_present || vcl_hrd_parameters_present) { sub_hrd_parameters_present = parser.BitRead(1); if (sub_hrd_parameters_present) { parser.BitSkip(8); // tick_divisor_minus2 parser.BitSkip(5); // du_cpb_removal_delay_increment_length_minus1 parser.BitSkip(1); // sub_pic_cpb_params_in_pic_timing_sei_flag parser.BitSkip(5); // dpb_output_delay_du_length_minus1 } parser.BitSkip(4); // bit_rate_scale parser.BitSkip(4); // cbp_size_scale if (sub_hrd_parameters_present) parser.BitSkip(4); // cbp_size_du_scale parser.BitSkip(5); // initial_cpb_removal_delay_length_minus1 parser.BitSkip(5); // au_cpb_removal_delay_length_minus1 parser.BitSkip(5); // dpb_output_delay_length_minus1 } for (i = 0; i <= max_sub_layers; i++) { int fixed_pic_rate_flag = parser.BitRead(1); int fixed_pic_rate_in_cvs_flag = 1, low_delay_hrd = 0; if (!fixed_pic_rate_flag) fixed_pic_rate_in_cvs_flag = parser.BitRead(1); if (fixed_pic_rate_in_cvs_flag) parser.UExpGolombRead(); else low_delay_hrd = parser.BitRead(1); int cpb_count = 0; if (!low_delay_hrd) cpb_count = parser.UExpGolombRead(); if (nal_hrd_parameters_present) { for (j = 0; j <= cpb_count; j++) { parser.UExpGolombRead(); // bit_rate_value_minus1 parser.UExpGolombRead(); // cpb_size_value_minus1 if (sub_hrd_parameters_present) { parser.UExpGolombRead(); // bit_rate_du_value_minus1 parser.UExpGolombRead(); // cpb_size_du_value_minus1 } parser.BitSkip(1); } } if (vcl_hrd_parameters_present) { for (j = 0; j <= cpb_count; j++) { parser.UExpGolombRead(); // bit_rate_value_minus1 parser.UExpGolombRead(); // cpb_size_value_minus1 if (sub_hrd_parameters_present) { parser.UExpGolombRead(); // bit_rate_du_value_minus1 parser.UExpGolombRead(); // cpb_size_du_value_minus1 } parser.BitSkip(1); } } } } } } int sps_range_extension_present = 0; if (parser.BitRead(1)) { // sps_extension_present_flag sps_range_extension_present = parser.BitRead(1); parser.BitSkip(1); // sps_multilayer_extension_flag parser.BitSkip(1); // sps_3d_extension_flag parser.BitSkip(5); // sps_extension_5bits } if (sps_range_extension_present) { sps.range_extension_flags = parser.BitRead(9); }*/ return S_OK; } ================================================ FILE: decoder/LAVVideo/parsers/HEVCSequenceParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "ByteParser.h" #define HEVC_REXT_PROFILE_MAIN_12 0x98 class CHEVCSequenceParser { public: CHEVCSequenceParser(); ~CHEVCSequenceParser(); HRESULT ParseNALs(const BYTE *buffer, size_t buflen, int nal_size); public: struct { int valid; int profile; int rext_profile; int level; int chroma; int bitdepth; } sps; private: HRESULT ParseSPS(const BYTE *buffer, size_t buflen); }; ================================================ FILE: decoder/LAVVideo/parsers/MPEG2HeaderParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "MPEG2HeaderParser.h" #pragma warning(push) #pragma warning(disable : 4101) #pragma warning(disable : 5033) #define AVCODEC_X86_MATHOPS_H #include "libavcodec/get_bits.h" #pragma warning(pop) #define SEQ_START_CODE 0x000001b3 #define EXT_START_CODE 0x000001b5 static inline const uint8_t *find_next_marker(const uint8_t *src, const uint8_t *end) { uint32_t mrk = 0xFFFFFFFF; if (end - src < 4) return end; while (src < end) { mrk = (mrk << 8) | *src++; if ((mrk & ~0xFF) == 0x00000100) return src - 4; } return end; } CMPEG2HeaderParser::CMPEG2HeaderParser(const BYTE *pData, size_t length) { memset(&hdr, 0, sizeof(hdr)); ParseMPEG2Header(pData, length); } CMPEG2HeaderParser::~CMPEG2HeaderParser(void) { } void CMPEG2HeaderParser::ParseMPEG2Header(const BYTE *pData, size_t length) { if (length < 16) return; GetBitContext gb; const uint8_t *start = pData; const uint8_t *end = start + length; const uint8_t *next = nullptr; int size; start = find_next_marker(start, end); next = start; for (; next < end; start = next) { next = find_next_marker(start + 4, end); size = (int)(next - start - 4); if (size <= 0) continue; init_get_bits(&gb, start + 4, (size - 4) * 8); switch (AV_RB32(start)) { case SEQ_START_CODE: MPEG2ParseSequenceHeader(&gb); break; case EXT_START_CODE: MPEG2ParseExtHeader(&gb); break; } } } void CMPEG2HeaderParser::MPEG2ParseSequenceHeader(GetBitContext *gb) { } void CMPEG2HeaderParser::MPEG2ParseExtHeader(GetBitContext *gb) { int startcode = get_bits(gb, 4); // Start Code if (startcode == 1) { hdr.valid = 1; skip_bits(gb, 1); // profile and level esc hdr.profile = get_bits(gb, 3); hdr.level = get_bits(gb, 4); hdr.interlaced = !get_bits1(gb); hdr.chroma = get_bits(gb, 2); // TODO: Fill in other fields, if needed } } ================================================ FILE: decoder/LAVVideo/parsers/MPEG2HeaderParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once struct GetBitContext; class CMPEG2HeaderParser { public: CMPEG2HeaderParser(const BYTE *pData, size_t length); ~CMPEG2HeaderParser(void); public: struct { int valid; int profile; int level; int interlaced; int chroma; } hdr; private: void ParseMPEG2Header(const BYTE *pData, size_t length); void MPEG2ParseSequenceHeader(GetBitContext *gb); void MPEG2ParseExtHeader(GetBitContext *gb); }; ================================================ FILE: decoder/LAVVideo/parsers/VC1HeaderParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "VC1HeaderParser.h" #pragma warning(push) #pragma warning(disable : 4101) #pragma warning(disable : 5033) extern "C" { #define AVCODEC_X86_MATHOPS_H #include "libavcodec/get_bits.h" #include "libavcodec/unary.h" extern __declspec(dllimport) const AVRational ff_vc1_pixel_aspect[16]; }; #pragma warning(pop) /** Markers used in VC-1 AP frame data */ //@{ enum VC1Code { VC1_CODE_RES0 = 0x00000100, VC1_CODE_ENDOFSEQ = 0x0000010A, VC1_CODE_SLICE, VC1_CODE_FIELD, VC1_CODE_FRAME, VC1_CODE_ENTRYPOINT, VC1_CODE_SEQHDR, }; //@} /** Available Profiles */ //@{ enum Profile { PROFILE_SIMPLE, PROFILE_MAIN, PROFILE_COMPLEX, ///< TODO: WMV9 specific PROFILE_ADVANCED }; //@} enum FrameCodingMode { PROGRESSIVE = 0, ///< in the bitstream is reported as 00b ILACE_FRAME, ///< in the bitstream is reported as 10b ILACE_FIELD ///< in the bitstream is reported as 11b }; #define IS_MARKER(x) (((x) & ~0xFF) == VC1_CODE_RES0) /** Find VC-1 marker in buffer * @return position where next marker starts or end of buffer if no marker found */ static inline const uint8_t *find_next_marker(const uint8_t *src, const uint8_t *end) { uint32_t mrk = 0xFFFFFFFF; if (end - src < 4) return end; while (src < end) { mrk = (mrk << 8) | *src++; if (IS_MARKER(mrk)) return src - 4; } return end; } static inline int vc1_unescape_buffer(const uint8_t *src, int size, uint8_t *dst) { int dsize = 0, i; if (size < 4) { for (dsize = 0; dsize < size; dsize++) *dst++ = *src++; return size; } for (i = 0; i < size; i++, src++) { if (src[0] == 3 && i >= 2 && !src[-1] && !src[-2] && i < size - 1 && src[1] < 4) { dst[dsize++] = src[1]; src++; i++; } else dst[dsize++] = *src; } return dsize; } CVC1HeaderParser::CVC1HeaderParser(const BYTE *pData, size_t length, AVCodecID codec) { memset(&hdr, 0, sizeof(hdr)); ParseVC1Header(pData, length, codec); } CVC1HeaderParser::~CVC1HeaderParser(void) { } void CVC1HeaderParser::ParseVC1Header(const BYTE *pData, size_t length, AVCodecID codec) { GetBitContext gb; if (codec == AV_CODEC_ID_VC1) { if (length < 16) return; const uint8_t *start = pData; const uint8_t *end = start + length; const uint8_t *next = nullptr; int size, buf2_size; uint8_t *buf2; buf2 = (uint8_t *)av_mallocz(length + AV_INPUT_BUFFER_PADDING_SIZE); start = find_next_marker(start, end); next = start; for (; next < end; start = next) { next = find_next_marker(start + 4, end); size = (int)(next - start - 4); if (size <= 0) continue; buf2_size = vc1_unescape_buffer(start + 4, size, buf2); init_get_bits(&gb, buf2, buf2_size * 8); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: VC1ParseSequenceHeader(&gb); break; } } av_freep(&buf2); } else if (codec == AV_CODEC_ID_WMV3) { if (length < 4) return; init_get_bits8(&gb, pData, (int)length); VC1ParseSequenceHeader(&gb); } } void CVC1HeaderParser::VC1ParseSequenceHeader(GetBitContext *gb) { hdr.profile = get_bits(gb, 2); if (hdr.profile == PROFILE_ADVANCED) { hdr.valid = 1; hdr.level = get_bits(gb, 3); skip_bits(gb, 2); // Chroma Format, only 1 should be set for 4:2:0 skip_bits(gb, 3); // frmrtq_postproc skip_bits(gb, 5); // bitrtq_postproc skip_bits1(gb); // postprocflag hdr.width = (get_bits(gb, 12) + 1) << 1; hdr.height = (get_bits(gb, 12) + 1) << 1; hdr.broadcast = get_bits1(gb); // broadcast hdr.interlaced = get_bits1(gb); // interlaced skip_bits1(gb); // tfcntrflag skip_bits1(gb); // finterpflag skip_bits1(gb); // reserved skip_bits1(gb); // psf if (get_bits1(gb)) { // Display Info int w, h, ar = 0; w = get_bits(gb, 14) + 1; h = get_bits(gb, 14) + 1; if (get_bits1(gb)) ar = get_bits(gb, 4); if (ar && ar < 14) { hdr.ar = ff_vc1_pixel_aspect[ar]; } else if (ar == 15) { w = get_bits(gb, 8) + 1; h = get_bits(gb, 8) + 1; hdr.ar.num = w; hdr.ar.den = h; } else { av_reduce(&hdr.ar.num, &hdr.ar.den, (int64_t)hdr.height * w, (int64_t)hdr.width * h, INT_MAX); } } // TODO: add other fields } else { hdr.valid = 1; hdr.old_interlaced = get_bits1(gb); // res_y411 skip_bits1(gb); // res_sprite skip_bits(gb, 3); // frmrtq_postproc skip_bits(gb, 5); // bitrtq_postproc skip_bits1(gb); // loop_filter skip_bits1(gb); // res_x8 skip_bits1(gb); // multires skip_bits1(gb); // rest_fasttx skip_bits1(gb); // fastuvmc skip_bits1(gb); // extended_mv skip_bits(gb, 2); // dquant skip_bits1(gb); // vstransform skip_bits1(gb); // res_transtab skip_bits1(gb); // overlap skip_bits1(gb); // resync marker hdr.rangered = get_bits1(gb); hdr.bframes = get_bits(gb, 3); skip_bits(gb, 2); // quant mode hdr.finterp = get_bits1(gb); } } AVPictureType CVC1HeaderParser::ParseVC1PictureType(const uint8_t *buf, int buflen) { AVPictureType pictype = AV_PICTURE_TYPE_NONE; int skipped = 0; const BYTE *framestart = buf; if (IS_MARKER(AV_RB32(buf))) { framestart = nullptr; const BYTE *start, *end, *next; next = buf; for (start = buf, end = buf + buflen; next < end; start = next) { if (AV_RB32(start) == VC1_CODE_FRAME) { framestart = start + 4; break; } next = find_next_marker(start + 4, end); } } if (framestart) { GetBitContext gb; init_get_bits8(&gb, framestart, (int)(buflen - (framestart - buf))); if (hdr.profile == PROFILE_ADVANCED) { int fcm = PROGRESSIVE; if (hdr.interlaced) fcm = decode012(&gb); if (fcm == ILACE_FIELD) { int fptype = get_bits(&gb, 3); pictype = (fptype & 2) ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I; if (fptype & 4) // B-picture pictype = (fptype & 2) ? AV_PICTURE_TYPE_BI : AV_PICTURE_TYPE_B; } else { switch (get_unary(&gb, 0, 4)) { case 0: pictype = AV_PICTURE_TYPE_P; break; case 1: pictype = AV_PICTURE_TYPE_B; break; case 2: pictype = AV_PICTURE_TYPE_I; break; case 3: pictype = AV_PICTURE_TYPE_BI; break; case 4: pictype = AV_PICTURE_TYPE_P; // skipped pic skipped = 1; break; } } } else { if (hdr.finterp) skip_bits1(&gb); skip_bits(&gb, 2); // framecnt if (hdr.rangered) skip_bits1(&gb); int pic = get_bits1(&gb); if (hdr.bframes) { if (!pic) { if (get_bits1(&gb)) { pictype = AV_PICTURE_TYPE_I; } else { pictype = AV_PICTURE_TYPE_B; } } else { pictype = AV_PICTURE_TYPE_P; } } else { pictype = pic ? AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_I; } } } return pictype; } ================================================ FILE: decoder/LAVVideo/parsers/VC1HeaderParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once struct GetBitContext; class CVC1HeaderParser { public: CVC1HeaderParser(const BYTE *pData, size_t length, AVCodecID codec = AV_CODEC_ID_VC1); ~CVC1HeaderParser(void); AVPictureType ParseVC1PictureType(const uint8_t *buf, int buflen); public: struct { int valid; int profile; int level; int width; int height; int broadcast; int interlaced; AVRational ar; int old_interlaced; int bframes; int finterp; int rangered; } hdr; private: void ParseVC1Header(const BYTE *pData, size_t length, AVCodecID codec); void VC1ParseSequenceHeader(GetBitContext *gb); }; ================================================ FILE: decoder/LAVVideo/pixconv/convert_direct.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" // This function is only designed for NV12-like pixel formats, like NV12, P010, P016, ... DECLARE_CONV_FUNC_IMPL(plane_copy_direct_nv12_sse4) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t chromaHeight = (height >> 1); const ptrdiff_t byteWidth = (outputFormat == LAVOutPixFmt_P010 || outputFormat == LAVOutPixFmt_P016) ? width << 1 : width; const ptrdiff_t stride = min(FFALIGN(byteWidth, 64), min(inStride, outStride)); __m128i xmm0, xmm1, xmm2, xmm3; _mm_sfence(); ptrdiff_t line, i; for (line = 0; line < height; line++) { const uint8_t *y = (src[0] + line * inStride); uint8_t *dy = (dst[0] + line * outStride); for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, y + i + 0); PIXCONV_STREAM_LOAD(xmm1, y + i + 16); PIXCONV_STREAM_LOAD(xmm2, y + i + 32); PIXCONV_STREAM_LOAD(xmm3, y + i + 48); _ReadWriteBarrier(); PIXCONV_PUT_STREAM(dy + i + 0, xmm0); PIXCONV_PUT_STREAM(dy + i + 16, xmm1); PIXCONV_PUT_STREAM(dy + i + 32, xmm2); PIXCONV_PUT_STREAM(dy + i + 48, xmm3); } for (; i < byteWidth; i += 16) { PIXCONV_LOAD_ALIGNED(xmm0, y + i); PIXCONV_PUT_STREAM(dy + i, xmm0); } } for (line = 0; line < chromaHeight; line++) { const uint8_t *uv = (src[1] + line * inStride); uint8_t *duv = (dst[1] + line * outStride); for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, uv + i + 0); PIXCONV_STREAM_LOAD(xmm1, uv + i + 16); PIXCONV_STREAM_LOAD(xmm2, uv + i + 32); PIXCONV_STREAM_LOAD(xmm3, uv + i + 48); _ReadWriteBarrier(); PIXCONV_PUT_STREAM(duv + i + 0, xmm0); PIXCONV_PUT_STREAM(duv + i + 16, xmm1); PIXCONV_PUT_STREAM(duv + i + 32, xmm2); PIXCONV_PUT_STREAM(duv + i + 48, xmm3); } for (; i < byteWidth; i += 16) { PIXCONV_LOAD_ALIGNED(xmm0, uv + i); PIXCONV_PUT_STREAM(duv + i, xmm0); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(plane_copy_direct_sse4) { LAVOutPixFmtDesc desc = lav_pixfmt_desc[outputFormat]; const int widthBytes = width * desc.codedbytes; const int planes = max(desc.planes, 1); ptrdiff_t line, plane; for (plane = 0; plane < planes; plane++) { const int planeWidth = widthBytes / desc.planeWidth[plane]; const int planeHeight = height / desc.planeHeight[plane]; const ptrdiff_t srcPlaneStride = srcStride[plane]; const ptrdiff_t dstPlaneStride = dstStride[plane]; const uint8_t *const srcBuf = src[plane]; uint8_t *const dstBuf = dst[plane]; for (line = 0; line < planeHeight; ++line) { const uint8_t *const srcLinePtr = srcBuf + line * srcPlaneStride; uint8_t *const dstLinePtr = dstBuf + line * dstPlaneStride; __m128i r1, r2, r3, r4; ptrdiff_t i; for (i = 0; i < (planeWidth - 63); i += 64) { PIXCONV_STREAM_LOAD(r1, srcLinePtr + i + 0) PIXCONV_STREAM_LOAD(r2, srcLinePtr + i + 16); PIXCONV_STREAM_LOAD(r3, srcLinePtr + i + 32); PIXCONV_STREAM_LOAD(r4, srcLinePtr + i + 48); _ReadWriteBarrier(); PIXCONV_PUT_STREAM(dstLinePtr + i + 0, r1); PIXCONV_PUT_STREAM(dstLinePtr + i + 16, r2); PIXCONV_PUT_STREAM(dstLinePtr + i + 32, r3); PIXCONV_PUT_STREAM(dstLinePtr + i + 48, r4); } for (; i < planeWidth; i += 16) { PIXCONV_STREAM_LOAD(r1, srcLinePtr + i); PIXCONV_PUT_STREAM(dstLinePtr + i, r1); } } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_nv12_yv12_direct_sse4) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t outChromaStride = dstStride[1]; const ptrdiff_t chromaHeight = (height >> 1); const ptrdiff_t stride = min(FFALIGN(width, 64), min(inStride, outStride)); __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm7; xmm7 = _mm_set1_epi16(0x00FF); _mm_sfence(); ptrdiff_t line, i; for (line = 0; line < height; line++) { const uint8_t *y = (src[0] + line * inStride); uint8_t *dy = (dst[0] + line * outStride); for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, y + i + 0); PIXCONV_STREAM_LOAD(xmm1, y + i + 16); PIXCONV_STREAM_LOAD(xmm2, y + i + 32); PIXCONV_STREAM_LOAD(xmm3, y + i + 48); _ReadWriteBarrier(); PIXCONV_PUT_STREAM(dy + i + 0, xmm0); PIXCONV_PUT_STREAM(dy + i + 16, xmm1); PIXCONV_PUT_STREAM(dy + i + 32, xmm2); PIXCONV_PUT_STREAM(dy + i + 48, xmm3); } for (; i < width; i += 16) { PIXCONV_LOAD_ALIGNED(xmm0, y + i); PIXCONV_PUT_STREAM(dy + i, xmm0); } } for (line = 0; line < chromaHeight; line++) { const uint8_t *uv = (src[1] + line * inStride); uint8_t *dv = (dst[1] + line * outChromaStride); uint8_t *du = (dst[2] + line * outChromaStride); for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, uv + i + 0); PIXCONV_STREAM_LOAD(xmm1, uv + i + 16); PIXCONV_STREAM_LOAD(xmm2, uv + i + 32); PIXCONV_STREAM_LOAD(xmm3, uv + i + 48); _ReadWriteBarrier(); // process first pair xmm4 = _mm_srli_epi16(xmm0, 8); xmm5 = _mm_srli_epi16(xmm1, 8); xmm0 = _mm_and_si128(xmm0, xmm7); xmm1 = _mm_and_si128(xmm1, xmm7); xmm0 = _mm_packus_epi16(xmm0, xmm1); xmm4 = _mm_packus_epi16(xmm4, xmm5); PIXCONV_PUT_STREAM(du + (i >> 1) + 0, xmm0); PIXCONV_PUT_STREAM(dv + (i >> 1) + 0, xmm4); // and second pair xmm4 = _mm_srli_epi16(xmm2, 8); xmm5 = _mm_srli_epi16(xmm3, 8); xmm2 = _mm_and_si128(xmm2, xmm7); xmm3 = _mm_and_si128(xmm3, xmm7); xmm2 = _mm_packus_epi16(xmm2, xmm3); xmm4 = _mm_packus_epi16(xmm4, xmm5); PIXCONV_PUT_STREAM(du + (i >> 1) + 16, xmm2); PIXCONV_PUT_STREAM(dv + (i >> 1) + 16, xmm4); } for (; i < width; i += 32) { PIXCONV_LOAD_ALIGNED(xmm0, uv + i + 0); PIXCONV_LOAD_ALIGNED(xmm1, uv + i + 16); xmm4 = _mm_srli_epi16(xmm0, 8); xmm5 = _mm_srli_epi16(xmm1, 8); xmm0 = _mm_and_si128(xmm0, xmm7); xmm1 = _mm_and_si128(xmm1, xmm7); xmm0 = _mm_packus_epi16(xmm0, xmm1); xmm4 = _mm_packus_epi16(xmm4, xmm5); PIXCONV_PUT_STREAM(du + (i >> 1), xmm0); PIXCONV_PUT_STREAM(dv + (i >> 1), xmm4); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_p010_nv12_direct_sse4) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t chromaHeight = (height >> 1); const ptrdiff_t byteWidth = width << 1; const ptrdiff_t stride = min(FFALIGN(byteWidth, 64), min(inStride, outStride << 1)); LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = GetRandomDitherCoeffs(height, 4, 8, 0); if (dithers == nullptr) ditherMode = LAVDither_Ordered; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; _mm_sfence(); ptrdiff_t line, i; for (line = 0; line < height; line++) { // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm4 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 0)); xmm5 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 8)); xmm6 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 16)); xmm7 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 24)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm7, line, 8, dithers); xmm4 = xmm5 = xmm6 = xmm7; } const uint8_t *y = (src[0] + line * inStride); uint8_t *dy = (dst[0] + line * outStride); for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, y + i + 0); PIXCONV_STREAM_LOAD(xmm1, y + i + 16); PIXCONV_STREAM_LOAD(xmm2, y + i + 32); PIXCONV_STREAM_LOAD(xmm3, y + i + 48); _ReadWriteBarrier(); // apply dithering coeffs xmm0 = _mm_adds_epu16(xmm0, xmm4); xmm1 = _mm_adds_epu16(xmm1, xmm5); xmm2 = _mm_adds_epu16(xmm2, xmm6); xmm3 = _mm_adds_epu16(xmm3, xmm7); // shift and pack to 8-bit xmm0 = _mm_packus_epi16(_mm_srli_epi16(xmm0, 8), _mm_srli_epi16(xmm1, 8)); xmm2 = _mm_packus_epi16(_mm_srli_epi16(xmm2, 8), _mm_srli_epi16(xmm3, 8)); PIXCONV_PUT_STREAM(dy + (i >> 1) + 0, xmm0); PIXCONV_PUT_STREAM(dy + (i >> 1) + 16, xmm2); } for (; i < byteWidth; i += 32) { PIXCONV_LOAD_ALIGNED(xmm0, y + i + 0); PIXCONV_LOAD_ALIGNED(xmm1, y + i + 16); // apply dithering coeffs xmm0 = _mm_adds_epu16(xmm0, xmm4); xmm1 = _mm_adds_epu16(xmm1, xmm5); // shift and pack to 8-bit xmm0 = _mm_packus_epi16(_mm_srli_epi16(xmm0, 8), _mm_srli_epi16(xmm1, 8)); PIXCONV_PUT_STREAM(dy + (i >> 1), xmm0); } } for (line = 0; line < chromaHeight; line++) { // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm4 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 0)); xmm5 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 8)); xmm6 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 16)); xmm7 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 24)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm7, line, 8, dithers); xmm4 = xmm5 = xmm6 = xmm7; } const uint8_t *uv = (src[1] + line * inStride); uint8_t *duv = (dst[1] + line * outStride); for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, uv + i + 0); PIXCONV_STREAM_LOAD(xmm1, uv + i + 16); PIXCONV_STREAM_LOAD(xmm2, uv + i + 32); PIXCONV_STREAM_LOAD(xmm3, uv + i + 48); _ReadWriteBarrier(); // apply dithering coeffs xmm0 = _mm_adds_epu16(xmm0, xmm4); xmm1 = _mm_adds_epu16(xmm1, xmm5); xmm2 = _mm_adds_epu16(xmm2, xmm6); xmm3 = _mm_adds_epu16(xmm3, xmm7); // shift and pack to 8-bit xmm0 = _mm_packus_epi16(_mm_srli_epi16(xmm0, 8), _mm_srli_epi16(xmm1, 8)); xmm2 = _mm_packus_epi16(_mm_srli_epi16(xmm2, 8), _mm_srli_epi16(xmm3, 8)); PIXCONV_PUT_STREAM(duv + (i >> 1) + 0, xmm0); PIXCONV_PUT_STREAM(duv + (i >> 1) + 16, xmm2); } for (; i < byteWidth; i += 32) { PIXCONV_LOAD_ALIGNED(xmm0, uv + i + 0); PIXCONV_LOAD_ALIGNED(xmm1, uv + i + 16); // apply dithering coeffs xmm0 = _mm_adds_epu16(xmm0, xmm4); xmm1 = _mm_adds_epu16(xmm1, xmm5); // shift and pack to 8-bit xmm0 = _mm_packus_epi16(_mm_srli_epi16(xmm0, 8), _mm_srli_epi16(xmm1, 8)); PIXCONV_PUT_STREAM(duv + (i >> 1), xmm0); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_y210_p210_direct_sse4) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t byteWidth = width << 2; const ptrdiff_t stride = min(FFALIGN(byteWidth, 64), min(inStride, outStride << 1)); ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_set1_epi32(0x0000FFFF); for (line = 0; line < height; line++) { const uint8_t *srcLine = src[0] + line * inStride; uint8_t *dstY = dst[0] + line * dstStride[0]; uint8_t *dstUV = dst[1] + line * dstStride[1]; for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, srcLine + i + 0); // Y0 U Y1 V PIXCONV_STREAM_LOAD(xmm1, srcLine + i + 16); PIXCONV_STREAM_LOAD(xmm2, srcLine + i + 32); PIXCONV_STREAM_LOAD(xmm3, srcLine + i + 48); // extract Y xmm4 = _mm_and_si128(xmm0, xmm7); xmm5 = _mm_and_si128(xmm1, xmm7); xmm6 = _mm_packus_epi32(xmm4, xmm5); xmm4 = _mm_and_si128(xmm2, xmm7); xmm5 = _mm_and_si128(xmm3, xmm7); xmm4 = _mm_packus_epi32(xmm4, xmm5); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 0, xmm6); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 16, xmm4); // extract UV xmm4 = _mm_srli_epi32(xmm0, 16); xmm5 = _mm_srli_epi32(xmm1, 16); xmm6 = _mm_packus_epi32(xmm4, xmm5); xmm4 = _mm_srli_epi32(xmm2, 16); xmm5 = _mm_srli_epi32(xmm3, 16); xmm4 = _mm_packus_epi32(xmm4, xmm5); PIXCONV_PUT_STREAM(dstUV + (i >> 1) + 0, xmm6); PIXCONV_PUT_STREAM(dstUV + (i >> 1) + 16, xmm4); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_yuy2_yv16_direct_sse4) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t byteWidth = width << 1; const ptrdiff_t stride = min(FFALIGN(byteWidth, 64), min(inStride, outStride << 1)); ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_set1_epi16(0x00FF); for (line = 0; line < height; line++) { const uint8_t *srcLine = src[0] + line * inStride; uint8_t *dstY = dst[0] + line * dstStride[0]; uint8_t *dstV = dst[1] + line * dstStride[1]; uint8_t *dstU = dst[2] + line * dstStride[2]; for (i = 0; i < (stride - 63); i += 64) { PIXCONV_STREAM_LOAD(xmm0, srcLine + i + 0); // Y0 U Y1 V PIXCONV_STREAM_LOAD(xmm1, srcLine + i + 16); PIXCONV_STREAM_LOAD(xmm2, srcLine + i + 32); PIXCONV_STREAM_LOAD(xmm3, srcLine + i + 48); _ReadWriteBarrier(); // extract Y xmm4 = _mm_and_si128(xmm0, xmm7); xmm5 = _mm_and_si128(xmm1, xmm7); xmm6 = _mm_packus_epi16(xmm4, xmm5); xmm4 = _mm_and_si128(xmm2, xmm7); xmm5 = _mm_and_si128(xmm3, xmm7); xmm4 = _mm_packus_epi16(xmm4, xmm5); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 0, xmm6); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 16, xmm4); // extract UV xmm4 = _mm_srli_epi16(xmm0, 8); xmm5 = _mm_srli_epi16(xmm1, 8); xmm0 = _mm_packus_epi16(xmm4, xmm5); xmm4 = _mm_srli_epi16(xmm2, 8); xmm5 = _mm_srli_epi16(xmm3, 8); xmm1 = _mm_packus_epi16(xmm4, xmm5); // split into U/V xmm4 = _mm_srli_epi16(xmm0, 8); xmm5 = _mm_srli_epi16(xmm1, 8); xmm0 = _mm_and_si128(xmm0, xmm7); xmm1 = _mm_and_si128(xmm1, xmm7); xmm0 = _mm_packus_epi16(xmm0, xmm1); xmm4 = _mm_packus_epi16(xmm4, xmm5); PIXCONV_PUT_STREAM(dstU + (i >> 2), xmm0); PIXCONV_PUT_STREAM(dstV + (i >> 2), xmm4); } } return S_OK; } ================================================ FILE: decoder/LAVVideo/pixconv/convert_generic.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "pixconv_internal.h" extern "C" { #include "libavutil/intreadwrite.h" }; #define ALIGN(x, a) (((x) + (a)-1UL) & ~((a)-1UL)) DECLARE_CONV_FUNC_IMPL(convert_generic) { HRESULT hr = S_OK; AVPixelFormat inputFmt = GetFFInput(); switch (m_OutputPixFmt) { case LAVOutPixFmt_YV12: hr = swscale_scale(inputFmt, AV_PIX_FMT_YUV420P, src, srcStride, dst, width, height, dstStride, lav_pixfmt_desc[m_OutputPixFmt], true); break; case LAVOutPixFmt_NV12: hr = swscale_scale(inputFmt, AV_PIX_FMT_NV12, src, srcStride, dst, width, height, dstStride, lav_pixfmt_desc[m_OutputPixFmt]); break; case LAVOutPixFmt_YUY2: hr = ConvertTo422Packed(src, srcStride, dst, width, height, dstStride); break; case LAVOutPixFmt_UYVY: hr = ConvertTo422Packed(src, srcStride, dst, width, height, dstStride); break; case LAVOutPixFmt_AYUV: hr = ConvertToAYUV(src, srcStride, dst, width, height, dstStride); break; case LAVOutPixFmt_P010: hr = ConvertToPX1X(src, srcStride, dst, width, height, dstStride, 2); break; case LAVOutPixFmt_P016: hr = ConvertToPX1X(src, srcStride, dst, width, height, dstStride, 2); break; case LAVOutPixFmt_P210: hr = ConvertToPX1X(src, srcStride, dst, width, height, dstStride, 1); break; case LAVOutPixFmt_P216: hr = ConvertToPX1X(src, srcStride, dst, width, height, dstStride, 1); break; case LAVOutPixFmt_Y410: hr = ConvertToY410(src, srcStride, dst, width, height, dstStride); break; case LAVOutPixFmt_Y416: hr = ConvertToY416(src, srcStride, dst, width, height, dstStride); break; case LAVOutPixFmt_RGB32: hr = swscale_scale(inputFmt, AV_PIX_FMT_BGRA, src, srcStride, dst, width, height, dstStride, lav_pixfmt_desc[m_OutputPixFmt]); break; case LAVOutPixFmt_RGB24: hr = swscale_scale(inputFmt, AV_PIX_FMT_BGR24, src, srcStride, dst, width, height, dstStride, lav_pixfmt_desc[m_OutputPixFmt]); break; case LAVOutPixFmt_v210: hr = ConvertTov210(src, srcStride, dst, width, height, dstStride); break; case LAVOutPixFmt_v410: hr = ConvertTov410(src, srcStride, dst, width, height, dstStride); break; case LAVOutPixFmt_YV16: hr = swscale_scale(inputFmt, AV_PIX_FMT_YUV422P, src, srcStride, dst, width, height, dstStride, lav_pixfmt_desc[m_OutputPixFmt], true); break; case LAVOutPixFmt_YV24: hr = swscale_scale(inputFmt, AV_PIX_FMT_YUV444P, src, srcStride, dst, width, height, dstStride, lav_pixfmt_desc[m_OutputPixFmt], true); break; case LAVOutPixFmt_RGB48: hr = swscale_scale(inputFmt, AV_PIX_FMT_RGB48LE, src, srcStride, dst, width, height, dstStride, lav_pixfmt_desc[m_OutputPixFmt]); break; default: ASSERT(0); hr = E_FAIL; break; } return S_OK; } inline SwsContext *CLAVPixFmtConverter::GetSWSContext(int width, int height, enum AVPixelFormat srcPix, enum AVPixelFormat dstPix, int flags) { if (!m_pSwsContext || swsWidth != width || swsHeight != height) { // Get context m_pSwsContext = sws_getCachedContext(m_pSwsContext, width, height, srcPix, width, height, dstPix, flags | SWS_PRINT_INFO, nullptr, nullptr, nullptr); int *inv_tbl = nullptr, *tbl = nullptr; int srcRange, dstRange, brightness, contrast, saturation; int ret = sws_getColorspaceDetails(m_pSwsContext, &inv_tbl, &srcRange, &tbl, &dstRange, &brightness, &contrast, &saturation); if (ret >= 0) { const int *rgbTbl = nullptr; if (m_ColorProps.VideoTransferMatrix != DXVA2_VideoTransferMatrix_Unknown) { int colorspace = SWS_CS_ITU709; switch (m_ColorProps.VideoTransferMatrix) { case DXVA2_VideoTransferMatrix_BT709: colorspace = SWS_CS_ITU709; break; case DXVA2_VideoTransferMatrix_BT601: colorspace = SWS_CS_ITU601; break; case DXVA2_VideoTransferMatrix_SMPTE240M: colorspace = SWS_CS_SMPTE240M; break; } rgbTbl = sws_getCoefficients(colorspace); } else { BOOL isHD = (height >= 720 || width >= 1280); rgbTbl = sws_getCoefficients(isHD ? SWS_CS_ITU709 : SWS_CS_ITU601); } srcRange = dstRange = (m_ColorProps.NominalRange == DXVA2_NominalRange_0_255); sws_setColorspaceDetails(m_pSwsContext, rgbTbl, srcRange, rgbTbl, dstRange, brightness, contrast, saturation); } swsWidth = width; swsHeight = height; } return m_pSwsContext; } HRESULT CLAVPixFmtConverter::swscale_scale(enum AVPixelFormat srcPix, enum AVPixelFormat dstPix, const uint8_t *const src[], const ptrdiff_t srcStride[], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[], LAVOutPixFmtDesc pixFmtDesc, bool swapPlanes12) { int ret; SwsContext *ctx = GetSWSContext(width, height, srcPix, dstPix, SWS_BILINEAR); CheckPointer(m_pSwsContext, E_POINTER); if (swapPlanes12) { uint8_t *tmp = dst[1]; dst[1] = dst[2]; dst[2] = tmp; } ret = sws_scale2(ctx, src, srcStride, 0, height, dst, dstStride); return S_OK; } HRESULT CLAVPixFmtConverter::ConvertTo422Packed(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[]) { const BYTE *y = nullptr; const BYTE *u = nullptr; const BYTE *v = nullptr; ptrdiff_t line, i; ptrdiff_t sourceStride = 0; BYTE *pTmpBuffer = nullptr; if (m_InputPixFmt != LAVPixFmt_YUV422) { uint8_t *tmp[4] = {nullptr}; ptrdiff_t tmpStride[4] = {0}; ptrdiff_t scaleStride = FFALIGN(width, 32); pTmpBuffer = (BYTE *)av_malloc(height * scaleStride * 2); if (pTmpBuffer == nullptr) return E_OUTOFMEMORY; tmp[0] = pTmpBuffer; tmp[1] = tmp[0] + (height * scaleStride); tmp[2] = tmp[1] + (height * scaleStride / 2); tmp[3] = nullptr; tmpStride[0] = scaleStride; tmpStride[1] = scaleStride / 2; tmpStride[2] = scaleStride / 2; tmpStride[3] = 0; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), AV_PIX_FMT_YUV422P, SWS_BILINEAR); sws_scale2(ctx, src, srcStride, 0, height, tmp, tmpStride); y = tmp[0]; u = tmp[1]; v = tmp[2]; sourceStride = scaleStride; } else { y = src[0]; u = src[1]; v = src[2]; sourceStride = srcStride[0]; } #define YUV422_PACK_YUY2(offset) \ *idst++ = y[(i + offset) * 2] | (u[i + offset] << 8) | (y[(i + offset) * 2 + 1] << 16) | (v[i + offset] << 24); #define YUV422_PACK_UYVY(offset) \ *idst++ = u[i + offset] | (y[(i + offset) * 2] << 8) | (v[i + offset] << 16) | (y[(i + offset) * 2 + 1] << 24); uint8_t *out = dst[0]; int halfwidth = width >> 1; ptrdiff_t halfstride = sourceStride >> 1; if (m_OutputPixFmt == LAVOutPixFmt_YUY2) { for (line = 0; line < height; ++line) { uint32_t *idst = (uint32_t *)out; for (i = 0; i < (halfwidth - 7); i += 8) { YUV422_PACK_YUY2(0) YUV422_PACK_YUY2(1) YUV422_PACK_YUY2(2) YUV422_PACK_YUY2(3) YUV422_PACK_YUY2(4) YUV422_PACK_YUY2(5) YUV422_PACK_YUY2(6) YUV422_PACK_YUY2(7) } for (; i < halfwidth; ++i) { YUV422_PACK_YUY2(0) } y += sourceStride; u += halfstride; v += halfstride; out += dstStride[0]; } } else { for (line = 0; line < height; ++line) { uint32_t *idst = (uint32_t *)out; for (i = 0; i < (halfwidth - 7); i += 8) { YUV422_PACK_UYVY(0) YUV422_PACK_UYVY(1) YUV422_PACK_UYVY(2) YUV422_PACK_UYVY(3) YUV422_PACK_UYVY(4) YUV422_PACK_UYVY(5) YUV422_PACK_UYVY(6) YUV422_PACK_UYVY(7) } for (; i < halfwidth; ++i) { YUV422_PACK_UYVY(0) } y += sourceStride; u += halfstride; v += halfstride; out += dstStride[0]; } } av_freep(&pTmpBuffer); return S_OK; } HRESULT CLAVPixFmtConverter::ConvertToAYUV(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[]) { const BYTE *y = nullptr; const BYTE *u = nullptr; const BYTE *v = nullptr; ptrdiff_t line, i = 0; ptrdiff_t sourceStride = 0; BYTE *pTmpBuffer = nullptr; if (m_InputPixFmt != LAVPixFmt_YUV444) { uint8_t *tmp[4] = {nullptr}; ptrdiff_t tmpStride[4] = {0}; ptrdiff_t scaleStride = FFALIGN(width, 32); pTmpBuffer = (BYTE *)av_malloc(height * scaleStride * 3); if (pTmpBuffer == nullptr) return E_OUTOFMEMORY; tmp[0] = pTmpBuffer; tmp[1] = tmp[0] + (height * scaleStride); tmp[2] = tmp[1] + (height * scaleStride); tmp[3] = nullptr; tmpStride[0] = scaleStride; tmpStride[1] = scaleStride; tmpStride[2] = scaleStride; tmpStride[3] = 0; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), AV_PIX_FMT_YUV444P, SWS_BILINEAR); sws_scale2(ctx, src, srcStride, 0, height, tmp, tmpStride); y = tmp[0]; u = tmp[1]; v = tmp[2]; sourceStride = scaleStride; } else { y = src[0]; u = src[1]; v = src[2]; sourceStride = srcStride[0]; } #define YUV444_PACK_AYUV(offset) *idst++ = v[i + offset] | (u[i + offset] << 8) | (y[i + offset] << 16) | (0xff << 24); BYTE *out = dst[0]; for (line = 0; line < height; ++line) { uint32_t *idst = (uint32_t *)out; for (i = 0; i < (width - 7); i += 8) { YUV444_PACK_AYUV(0) YUV444_PACK_AYUV(1) YUV444_PACK_AYUV(2) YUV444_PACK_AYUV(3) YUV444_PACK_AYUV(4) YUV444_PACK_AYUV(5) YUV444_PACK_AYUV(6) YUV444_PACK_AYUV(7) } for (; i < width; ++i) { YUV444_PACK_AYUV(0) } y += sourceStride; u += sourceStride; v += sourceStride; out += dstStride[0]; } av_freep(&pTmpBuffer); return S_OK; } HRESULT CLAVPixFmtConverter::ConvertToPX1X(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[], int chromaVertical) { const BYTE *y = nullptr; const BYTE *u = nullptr; const BYTE *v = nullptr; ptrdiff_t line, i = 0; ptrdiff_t sourceStride = 0; int shift = 0; BYTE *pTmpBuffer = nullptr; if ((chromaVertical == 1 && m_InputPixFmt != LAVPixFmt_YUV422bX) || (chromaVertical == 2 && m_InputPixFmt != LAVPixFmt_YUV420bX)) { uint8_t *tmp[4] = {nullptr}; ptrdiff_t tmpStride[4] = {0}; ptrdiff_t scaleStride = FFALIGN(width, 32) * 2; pTmpBuffer = (BYTE *)av_malloc(height * scaleStride * 2); if (pTmpBuffer == nullptr) return E_OUTOFMEMORY; tmp[0] = pTmpBuffer; tmp[1] = tmp[0] + (height * scaleStride); tmp[2] = tmp[1] + ((height / chromaVertical) * (scaleStride / 2)); tmp[3] = nullptr; tmpStride[0] = scaleStride; tmpStride[1] = scaleStride / 2; tmpStride[2] = scaleStride / 2; tmpStride[3] = 0; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), chromaVertical == 1 ? AV_PIX_FMT_YUV422P16LE : AV_PIX_FMT_YUV420P16LE, SWS_BILINEAR); sws_scale2(ctx, src, srcStride, 0, height, tmp, tmpStride); y = tmp[0]; u = tmp[1]; v = tmp[2]; sourceStride = scaleStride; } else { y = src[0]; u = src[1]; v = src[2]; sourceStride = srcStride[0]; shift = (16 - m_InBpp); } // copy Y BYTE *pLineOut = dst[0]; const BYTE *pLineIn = y; for (line = 0; line < height; ++line) { if (shift == 0) { memcpy(pLineOut, pLineIn, width * 2); } else { const uint16_t *yc = (uint16_t *)pLineIn; uint16_t *idst = (uint16_t *)pLineOut; for (i = 0; i < width; ++i) { uint16_t yv = AV_RL16(yc + i); if (shift) yv <<= shift; *idst++ = yv; } } pLineOut += dstStride[0]; pLineIn += sourceStride; } sourceStride >>= 2; // Merge U/V BYTE *out = dst[1]; const uint16_t *uc = (uint16_t *)u; const uint16_t *vc = (uint16_t *)v; for (line = 0; line < height / chromaVertical; ++line) { uint32_t *idst = (uint32_t *)out; for (i = 0; i < width / 2; ++i) { uint16_t uv = AV_RL16(uc + i); uint16_t vv = AV_RL16(vc + i); if (shift) { uv <<= shift; vv <<= shift; } *idst++ = uv | (vv << 16); } uc += sourceStride; vc += sourceStride; out += dstStride[1]; } av_freep(&pTmpBuffer); return S_OK; } #define YUV444_PACKED_LOOP_HEAD(width, height, y, u, v, out) \ for (int line = 0; line < height; ++line) \ { \ uint32_t *idst = (uint32_t *)out; \ for (int i = 0; i < width; ++i) \ { \ uint32_t yv, uv, vv; #define YUV444_PACKED_LOOP_HEAD_LE(width, height, y, u, v, out) \ YUV444_PACKED_LOOP_HEAD(width, height, y, u, v, out) \ yv = AV_RL16(y + i); \ uv = AV_RL16(u + i); \ vv = AV_RL16(v + i); #define YUV444_PACKED_LOOP_END(y, u, v, out, srcStride, dstStride) \ } \ y += srcStride; \ u += srcStride; \ v += srcStride; \ out += dstStride; \ } HRESULT CLAVPixFmtConverter::ConvertToY410(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[]) { const uint16_t *y = nullptr; const uint16_t *u = nullptr; const uint16_t *v = nullptr; ptrdiff_t sourceStride = 0; bool b9Bit = false; BYTE *pTmpBuffer = nullptr; if (m_InputPixFmt != LAVPixFmt_YUV444bX || m_InBpp > 10) { uint8_t *tmp[4] = {nullptr}; ptrdiff_t tmpStride[4] = {0}; ptrdiff_t scaleStride = FFALIGN(width, 32); pTmpBuffer = (BYTE *)av_malloc(height * scaleStride * 6); if (pTmpBuffer == nullptr) return E_OUTOFMEMORY; tmp[0] = pTmpBuffer; tmp[1] = tmp[0] + (height * scaleStride * 2); tmp[2] = tmp[1] + (height * scaleStride * 2); tmp[3] = nullptr; tmpStride[0] = scaleStride * 2; tmpStride[1] = scaleStride * 2; tmpStride[2] = scaleStride * 2; tmpStride[3] = 0; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), AV_PIX_FMT_YUV444P10LE, SWS_BILINEAR); sws_scale2(ctx, src, srcStride, 0, height, tmp, tmpStride); y = (uint16_t *)tmp[0]; u = (uint16_t *)tmp[1]; v = (uint16_t *)tmp[2]; sourceStride = scaleStride; } else { y = (uint16_t *)src[0]; u = (uint16_t *)src[1]; v = (uint16_t *)src[2]; sourceStride = srcStride[0] / 2; b9Bit = (m_InBpp == 9); } #define YUV444_Y410_PACK *idst++ = (uv & 0x3FF) | ((yv & 0x3FF) << 10) | ((vv & 0x3FF) << 20) | (3 << 30); BYTE *out = dst[0]; YUV444_PACKED_LOOP_HEAD_LE(width, height, y, u, v, out) if (b9Bit) { yv <<= 1; uv <<= 1; vv <<= 1; } YUV444_Y410_PACK YUV444_PACKED_LOOP_END(y, u, v, out, sourceStride, dstStride[0]) av_freep(&pTmpBuffer); return S_OK; } HRESULT CLAVPixFmtConverter::ConvertToY416(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[]) { const uint16_t *y = nullptr; const uint16_t *u = nullptr; const uint16_t *v = nullptr; ptrdiff_t sourceStride = 0; BYTE *pTmpBuffer = nullptr; int shift = (16 - m_InBpp); if (m_InputPixFmt != LAVPixFmt_YUV444bX) { uint8_t *tmp[4] = {nullptr}; ptrdiff_t tmpStride[4] = {0}; ptrdiff_t scaleStride = FFALIGN(width, 32); pTmpBuffer = (BYTE *)av_malloc(height * scaleStride * 6); if (pTmpBuffer == nullptr) return E_OUTOFMEMORY; tmp[0] = pTmpBuffer; tmp[1] = tmp[0] + (height * scaleStride * 2); tmp[2] = tmp[1] + (height * scaleStride * 2); tmp[3] = nullptr; tmpStride[0] = scaleStride * 2; tmpStride[1] = scaleStride * 2; tmpStride[2] = scaleStride * 2; tmpStride[3] = 0; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), AV_PIX_FMT_YUV444P16LE, SWS_BILINEAR); sws_scale2(ctx, src, srcStride, 0, height, tmp, tmpStride); y = (uint16_t *)tmp[0]; u = (uint16_t *)tmp[1]; v = (uint16_t *)tmp[2]; sourceStride = scaleStride; shift = 0; } else { y = (uint16_t *)src[0]; u = (uint16_t *)src[1]; v = (uint16_t *)src[2]; sourceStride = srcStride[0] / 2; } BYTE *out = dst[0]; YUV444_PACKED_LOOP_HEAD_LE(width, height, y, u, v, out) uint16_t *p = (uint16_t *)idst; p[0] = (uv << shift); p[1] = (yv << shift); p[2] = (vv << shift); p[3] = 0xFFFF; idst += 2; YUV444_PACKED_LOOP_END(y, u, v, out, sourceStride, dstStride[0]) av_freep(&pTmpBuffer); return S_OK; } HRESULT CLAVPixFmtConverter::ConvertTov210(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[]) { const uint16_t *y = nullptr; const uint16_t *u = nullptr; const uint16_t *v = nullptr; ptrdiff_t srcyStride = 0; ptrdiff_t srcuvStride = 0; BYTE *pTmpBuffer = nullptr; if (m_InputPixFmt != LAVPixFmt_YUV422bX || m_InBpp != 10) { uint8_t *tmp[4] = {nullptr}; ptrdiff_t tmpStride[4] = {0}; ptrdiff_t scaleStride = FFALIGN(width, 32); pTmpBuffer = (BYTE *)av_malloc(height * scaleStride * 6); if (pTmpBuffer == nullptr) return E_OUTOFMEMORY; tmp[0] = pTmpBuffer; tmp[1] = tmp[0] + (height * scaleStride * 2); tmp[2] = tmp[1] + (height * scaleStride * 2); tmp[3] = nullptr; tmpStride[0] = scaleStride * 2; tmpStride[1] = scaleStride; tmpStride[2] = scaleStride; tmpStride[3] = 0; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), AV_PIX_FMT_YUV422P10LE, SWS_BILINEAR); sws_scale2(ctx, src, srcStride, 0, height, tmp, tmpStride); y = (uint16_t *)tmp[0]; u = (uint16_t *)tmp[1]; v = (uint16_t *)tmp[2]; srcyStride = scaleStride; srcuvStride = scaleStride >> 1; } else { y = (uint16_t *)src[0]; u = (uint16_t *)src[1]; v = (uint16_t *)src[2]; srcyStride = srcStride[0] >> 1; srcuvStride = srcStride[1] >> 1; } // Calculate v210 stride ptrdiff_t outStride = (((dstStride[0] >> 2) + 47) / 48) * 128; // Align width to an even number for processing // This may read into the source stride, but otherwise the algorithm won't work. width = FFALIGN(width, 2); BYTE *pdst = dst[0]; uint32_t *p = (uint32_t *)pdst; int w; //#define CLIP(v) av_clip(v, 4, 1019) #define CLIP(v) (v & 0x03FF) #define WRITE_PIXELS(a, b, c) \ do \ { \ val = CLIP(*a++); \ val |= (CLIP(*b++) << 10) | (CLIP(*c++) << 20); \ *p++ = val; \ } while (0) for (int h = 0; h < height; h++) { uint32_t val; for (w = 0; w < width - 5; w += 6) { WRITE_PIXELS(u, y, v); WRITE_PIXELS(y, u, y); WRITE_PIXELS(v, y, u); WRITE_PIXELS(y, v, y); } if (w < width - 1) { WRITE_PIXELS(u, y, v); val = CLIP(*y++); if (w == width - 2) *p++ = val; if (w < width - 3) { val |= (CLIP(*u++) << 10) | (CLIP(*y++) << 20); *p++ = val; val = CLIP(*v++) | (CLIP(*y++) << 10); *p++ = val; } } pdst += outStride; memset(p, 0, pdst - (BYTE *)p); p = (uint32_t *)pdst; y += srcyStride - width; u += srcuvStride - (width >> 1); v += srcuvStride - (width >> 1); } av_freep(&pTmpBuffer); return S_OK; } HRESULT CLAVPixFmtConverter::ConvertTov410(const uint8_t *const src[4], const ptrdiff_t srcStride[4], uint8_t *dst[], int width, int height, const ptrdiff_t dstStride[]) { const uint16_t *y = nullptr; const uint16_t *u = nullptr; const uint16_t *v = nullptr; ptrdiff_t sourceStride = 0; bool b9Bit = false; BYTE *pTmpBuffer = nullptr; if (m_InputPixFmt != LAVPixFmt_YUV444bX || m_InBpp > 10) { uint8_t *tmp[4] = {nullptr}; ptrdiff_t tmpStride[4] = {0}; ptrdiff_t scaleStride = FFALIGN(width, 32); pTmpBuffer = (BYTE *)av_malloc(height * scaleStride * 6); if (pTmpBuffer == nullptr) return E_OUTOFMEMORY; tmp[0] = pTmpBuffer; tmp[1] = tmp[0] + (height * scaleStride * 2); tmp[2] = tmp[1] + (height * scaleStride * 2); tmp[3] = nullptr; tmpStride[0] = scaleStride * 2; tmpStride[1] = scaleStride * 2; tmpStride[2] = scaleStride * 2; tmpStride[3] = 0; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), AV_PIX_FMT_YUV444P10LE, SWS_BILINEAR); sws_scale2(ctx, src, srcStride, 0, height, tmp, tmpStride); y = (uint16_t *)tmp[0]; u = (uint16_t *)tmp[1]; v = (uint16_t *)tmp[2]; sourceStride = scaleStride; } else { y = (uint16_t *)src[0]; u = (uint16_t *)src[1]; v = (uint16_t *)src[2]; sourceStride = srcStride[0] / 2; b9Bit = (m_InBpp == 9); } #define YUV444_v410_PACK *idst++ = ((uv & 0x3FF) << 2) | ((yv & 0x3FF) << 12) | ((vv & 0x3FF) << 22); BYTE *out = dst[0]; YUV444_PACKED_LOOP_HEAD_LE(width, height, y, u, v, out) if (b9Bit) { yv <<= 1; uv <<= 1; vv <<= 1; } YUV444_v410_PACK YUV444_PACKED_LOOP_END(y, u, v, out, sourceStride, dstStride[0]) av_freep(&pTmpBuffer); return S_OK; } ================================================ FILE: decoder/LAVVideo/pixconv/interleave.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" DECLARE_CONV_FUNC_IMPL(convert_yuv444_y410) { const uint16_t *y = (const uint16_t *)src[0]; const uint16_t *u = (const uint16_t *)src[1]; const uint16_t *v = (const uint16_t *)src[2]; const ptrdiff_t inStride = srcStride[0] >> 1; const ptrdiff_t outStride = dstStride[0]; int shift = 10 - bpp; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_set1_epi32(0xC0000000); xmm6 = _mm_setzero_si128(); _mm_sfence(); for (line = 0; line < height; ++line) { __m128i *dst128 = (__m128i *)(dst[0] + line * outStride); for (i = 0; i < width; i += 8) { PIXCONV_LOAD_PIXEL8_ALIGNED(xmm0, (y + i)); xmm0 = _mm_slli_epi16(xmm0, shift); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm1, (u + i)); xmm1 = _mm_slli_epi16(xmm1, shift); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm2, (v + i)); xmm2 = _mm_slli_epi16(xmm2, shift + 4); // +4 so its directly aligned properly (data from bit 14 to bit 4) xmm3 = _mm_unpacklo_epi16(xmm1, xmm2); // 0VVVVV00000UUUUU xmm4 = _mm_unpackhi_epi16(xmm1, xmm2); // 0VVVVV00000UUUUU xmm3 = _mm_or_si128(xmm3, xmm7); // AVVVVV00000UUUUU xmm4 = _mm_or_si128(xmm4, xmm7); // AVVVVV00000UUUUU xmm5 = _mm_unpacklo_epi16(xmm0, xmm6); // 00000000000YYYYY xmm2 = _mm_unpackhi_epi16(xmm0, xmm6); // 00000000000YYYYY xmm5 = _mm_slli_epi32(xmm5, 10); // 000000YYYYY00000 xmm2 = _mm_slli_epi32(xmm2, 10); // 000000YYYYY00000 xmm3 = _mm_or_si128(xmm3, xmm5); // AVVVVVYYYYYUUUUU xmm4 = _mm_or_si128(xmm4, xmm2); // AVVVVVYYYYYUUUUU // Write data back _mm_stream_si128(dst128++, xmm3); _mm_stream_si128(dst128++, xmm4); } y += inStride; u += inStride; v += inStride; } return S_OK; } ================================================ FILE: decoder/LAVVideo/pixconv/pixconv.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" // 8x8 Bayes ordered dithering table, scaled to the 0-255 range for 16->8 conversion // stored as 16-bit unsigned for optimized SIMD access // clang-format off __declspec(align(16)) const uint16_t dither_8x8_256[8][8] = { { 0, 192, 48, 240, 12, 204, 60, 252 }, { 128, 64, 176, 112, 140, 76, 188, 124 }, { 32, 224, 16, 208, 44, 236, 28, 220 }, { 160, 96, 144, 80, 172, 108, 156, 92 }, { 8, 200, 56, 248, 4, 196, 52, 244 }, { 136, 72, 184, 120, 132, 68, 180, 116 }, { 40, 232, 24, 216, 36, 228, 20, 212 }, { 168, 104, 152, 88, 164, 100, 148, 84 } }; // clang-format on DECLARE_CONV_FUNC_IMPL(plane_copy) { LAVOutPixFmtDesc desc = lav_pixfmt_desc[outputFormat]; const int widthBytes = width * desc.codedbytes; const int planes = max(desc.planes, 1); ptrdiff_t line, plane; for (plane = 0; plane < planes; plane++) { const int planeWidth = widthBytes / desc.planeWidth[plane]; const int planeHeight = height / desc.planeHeight[plane]; const ptrdiff_t srcPlaneStride = srcStride[plane]; const ptrdiff_t dstPlaneStride = dstStride[plane]; const uint8_t *const srcBuf = src[plane]; uint8_t *const dstBuf = dst[plane]; for (line = 0; line < planeHeight; ++line) { memcpy(dstBuf + line * dstPlaneStride, srcBuf + line * srcPlaneStride, planeWidth); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(plane_copy_sse2) { LAVOutPixFmtDesc desc = lav_pixfmt_desc[outputFormat]; const int widthBytes = width * desc.codedbytes; const int planes = max(desc.planes, 1); ptrdiff_t line, plane; for (plane = 0; plane < planes; plane++) { const int planeWidth = widthBytes / desc.planeWidth[plane]; const int planeHeight = height / desc.planeHeight[plane]; const ptrdiff_t srcPlaneStride = srcStride[plane]; const ptrdiff_t dstPlaneStride = dstStride[plane]; const uint8_t *const srcBuf = src[plane]; uint8_t *const dstBuf = dst[plane]; if ((dstPlaneStride % 16) == 0 && ((intptr_t)dstBuf % 16u) == 0) { for (line = 0; line < planeHeight; ++line) { PIXCONV_MEMCPY_ALIGNED(dstBuf + line * dstPlaneStride, srcBuf + line * srcPlaneStride, planeWidth); } } else { for (line = 0; line < planeHeight; ++line) { memcpy(dstBuf + line * dstPlaneStride, srcBuf + line * srcPlaneStride, planeWidth); } } } return S_OK; } ================================================ FILE: decoder/LAVVideo/pixconv/pixconv_internal.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "LAVPixFmtConverter.h" #include #include "timer.h" #include "Media.h" extern __declspec(align(16)) const uint16_t dither_8x8_256[8][8]; ================================================ FILE: decoder/LAVVideo/pixconv/pixconv_sse2_templates.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #include // Load the dithering coefficients for this line // reg - register to load coefficients into // line - index of line to process (0 based) // bits - number of bits to dither (for 10 -> 8, set to 2) #define PIXCONV_LOAD_DITHER_COEFFS(reg, line, bits, name) \ const uint16_t *name = dither_8x8_256[(line) % 8]; \ reg = _mm_load_si128((const __m128i *)name); \ reg = _mm_srli_epi16(reg, 8 - bits); /* shift to the required dithering strength */ // Load 8 16-bit pixels into a register, using aligned memory access // reg - register to store pixels in // src - memory pointer of the source // bpp - bit depth of the pixels #define PIXCONV_LOAD_PIXEL16(reg, src, bpp) \ reg = _mm_load_si128((const __m128i *)(src)); /* load (aligned) */ \ reg = _mm_slli_epi16(reg, 16 - bpp); /* shift to 16-bit */ // Load 2x8 16-bit pixels into registers, using aligned memory access // reg1 - register to store pixels in // reg2 - register to store pixels in // src1 - memory pointer of the source // src2 - memory pointer of the source // bpp - bit depth of the pixels #define PIXCONV_LOAD_PIXEL16X2(reg1, reg2, src1, src2, bpp) \ { \ const __m128i shift = _mm_cvtsi32_si128(16 - bpp); \ reg1 = _mm_load_si128((const __m128i *)(src1)); \ reg2 = _mm_load_si128((const __m128i *)(src2)); \ reg1 = _mm_sll_epi16(reg1, shift); \ reg2 = _mm_sll_epi16(reg2, shift); \ } // Load 8 16-bit pixels into a register, and dither them to 8 bit // The 8-bit pixels will be in the high-bytes of the 8 16-bit parts // NOTE: the low-bytes are clobbered, and not empty. // reg - register to store pixels in // dreg - register with dithering coefficients // src - memory pointer of the source // bpp - bit depth of the pixels #define PIXCONV_LOAD_PIXEL16_DITHER_HIGH(reg, dreg, src, bpp) \ PIXCONV_LOAD_PIXEL16(reg, src, bpp) \ reg = _mm_adds_epu16(reg, dreg); /* dither */ // Load 8 16-bit pixels into a register, and dither them to 8 bit // The 8-bit pixels will be in the low-bytes of the 8 16-bit parts // reg - register to store pixels in // dreg - register with dithering coefficients // src - memory pointer of the source // bpp - bit depth of the pixels #define PIXCONV_LOAD_PIXEL16_DITHER(reg, dreg, src, bpp) \ PIXCONV_LOAD_PIXEL16_DITHER_HIGH(reg, dreg, src, bpp) \ reg = _mm_srli_epi16(reg, 8); /* shift to 8-bit */ // Load 8 16-bit pixels into a register, and dither them to 8 bit // The 8-bit pixels will be in the 8 low-bytes in the register // reg - register to store pixels in // dreg - register with dithering coefficients // src - memory pointer of the source // bpp - bit depth of the pixels #define PIXCONV_LOAD_PIXEL16_DITHER_PACKED(reg, dreg, zero, src, bpp) \ PIXCONV_LOAD_PIXEL16_DITHER(reg, dreg, src, bpp) /* load unpacked */ \ reg = _mm_packus_epi16(reg, zero); /* pack */ // Load 16 8-bit pixels into a register // reg - register to store pixels in // src - memory pointer of the source #define PIXCONV_LOAD_PIXEL8(reg, src) reg = _mm_loadu_si128((const __m128i *)(src)); /* load (unaligned) */ // Load 128-bit into a register, using aligned memory access // reg - register to store pixels in // src - memory pointer of the source #define PIXCONV_LOAD_ALIGNED(reg, src) reg = _mm_load_si128((const __m128i *)(src)); /* load (aligned) */ // Load 128-bit into a register, using streaming memory access // reg - register to store pixels in // src - memory pointer of the source #define PIXCONV_STREAM_LOAD(reg, src) reg = _mm_stream_load_si128((__m128i *)(src)); /* load (streaming) */ #define PIXCONV_LOAD_PIXEL8_ALIGNED PIXCONV_LOAD_ALIGNED // Put 128-bit into memory, using streaming write #define PIXCONV_PUT_STREAM(dst, reg) _mm_stream_si128((__m128i *)(dst), reg); /* streaming write */ // Load 4 8-bit pixels into the register // reg - register to store pixels in // src - source memory #define PIXCONV_LOAD_4PIXEL8(reg, src) reg = _mm_cvtsi32_si128(*(const int *)(src)); /* load 32-bit (4 pixel) */ // Load 4 16-bit pixels into the register // reg - register to store pixels in // src - source memory #define PIXCONV_LOAD_4PIXEL16(reg, src) reg = _mm_loadl_epi64((const __m128i *)(src)); /* load 64-bit (4 pixel) */ // SSE2 Aligned memcpy // dst - memory destination // src - memory source // len - size in bytes #define PIXCONV_MEMCPY_ALIGNED(dst, src, len) \ { \ const uint8_t *const srcLinePtr = (src); \ uint8_t *const dstLinePtr = (dst); \ __m128i r1, r2, r3, r4; \ ptrdiff_t i; \ for (i = 0; i < (len - 63); i += 64) \ { \ PIXCONV_LOAD_ALIGNED(r1, srcLinePtr + i + 0) \ PIXCONV_LOAD_ALIGNED(r2, srcLinePtr + i + 16); \ PIXCONV_LOAD_ALIGNED(r3, srcLinePtr + i + 32); \ PIXCONV_LOAD_ALIGNED(r4, srcLinePtr + i + 48); \ PIXCONV_PUT_STREAM(dstLinePtr + i + 0, r1); \ PIXCONV_PUT_STREAM(dstLinePtr + i + 16, r2); \ PIXCONV_PUT_STREAM(dstLinePtr + i + 32, r3); \ PIXCONV_PUT_STREAM(dstLinePtr + i + 48, r4); \ } \ for (; i < len; i += 16) \ { \ PIXCONV_LOAD_ALIGNED(r1, srcLinePtr + i); \ PIXCONV_PUT_STREAM(dstLinePtr + i, r1); \ } \ } // SSE2 Aligned memcpy // Copys the same size from two source into two destinations at the same time // dst1 - memory destination // src1 - memory source // dst2 - memory destination // src2 - memory source // len - size in bytes #define PIXCONV_MEMCPY_ALIGNED_TWO(dst1, src1, dst2, src2, len) \ { \ const uint8_t *const src1LinePtr = (src1); \ const uint8_t *const src2LinePtr = (src2); \ uint8_t *const dst1LinePtr = (dst1); \ uint8_t *const dst2LinePtr = (dst2); \ __m128i r1, r2, r3, r4, r5, r6, r7, r8; \ ptrdiff_t i; \ for (i = 0; i < (len - 63); i += 64) \ { \ PIXCONV_LOAD_ALIGNED(r1, src1LinePtr + i + 0); \ PIXCONV_LOAD_ALIGNED(r2, src1LinePtr + i + 16); \ PIXCONV_LOAD_ALIGNED(r3, src1LinePtr + i + 32); \ PIXCONV_LOAD_ALIGNED(r4, src1LinePtr + i + 48); \ PIXCONV_LOAD_ALIGNED(r5, src2LinePtr + i + 0); \ PIXCONV_LOAD_ALIGNED(r6, src2LinePtr + i + 16); \ PIXCONV_LOAD_ALIGNED(r7, src2LinePtr + i + 32); \ PIXCONV_LOAD_ALIGNED(r8, src2LinePtr + i + 48); \ PIXCONV_PUT_STREAM(dst1LinePtr + i + 0, r1); \ PIXCONV_PUT_STREAM(dst1LinePtr + i + 16, r2); \ PIXCONV_PUT_STREAM(dst1LinePtr + i + 32, r3); \ PIXCONV_PUT_STREAM(dst1LinePtr + i + 48, r4); \ PIXCONV_PUT_STREAM(dst2LinePtr + i + 0, r5); \ PIXCONV_PUT_STREAM(dst2LinePtr + i + 16, r6); \ PIXCONV_PUT_STREAM(dst2LinePtr + i + 32, r7); \ PIXCONV_PUT_STREAM(dst2LinePtr + i + 48, r8); \ } \ for (; i < len; i += 16) \ { \ PIXCONV_LOAD_ALIGNED(r1, src1LinePtr + i); \ PIXCONV_LOAD_ALIGNED(r2, src2LinePtr + i); \ PIXCONV_PUT_STREAM(dst1LinePtr + i, r1); \ PIXCONV_PUT_STREAM(dst2LinePtr + i, r2); \ } \ } ================================================ FILE: decoder/LAVVideo/pixconv/rgb2rgb_unscaled.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" DECLARE_CONV_FUNC_IMPL(convert_rgb48_rgb32_ssse3) { const uint16_t *rgb = (const uint16_t *)src[0]; const ptrdiff_t inStride = srcStride[0] >> 1; const ptrdiff_t outStride = dstStride[0]; ptrdiff_t line, i; int processWidth = width * 3; LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = GetRandomDitherCoeffs(height, 4, 8, 0); if (dithers == nullptr) ditherMode = LAVDither_Ordered; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; __m128i mask = _mm_setr_epi8(4, 5, 2, 3, 0, 1, -1, -1, 10, 11, 8, 9, 6, 7, -1, -1); _mm_sfence(); for (line = 0; line < height; line++) { __m128i *dst128 = (__m128i *)(dst[0] + line * outStride); // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm5 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 0)); xmm6 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 8)); xmm7 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 16)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm7, line, 8, dithers); xmm5 = xmm6 = xmm7; } for (i = 0; i < processWidth; i += 24) { PIXCONV_LOAD_ALIGNED(xmm0, (rgb + i)); /* load */ PIXCONV_LOAD_ALIGNED(xmm1, (rgb + i + 8)); PIXCONV_LOAD_ALIGNED(xmm2, (rgb + i + 16)); xmm0 = _mm_adds_epu16(xmm0, xmm5); /* apply dithering coefficients */ xmm1 = _mm_adds_epu16(xmm1, xmm6); xmm2 = _mm_adds_epu16(xmm2, xmm7); xmm0 = _mm_srli_epi16(xmm0, 8); /* shift to 8-bit */ xmm1 = _mm_srli_epi16(xmm1, 8); xmm2 = _mm_srli_epi16(xmm2, 8); xmm3 = _mm_shuffle_epi8(xmm0, mask); xmm4 = _mm_shuffle_epi8(_mm_alignr_epi8(xmm1, xmm0, 12), mask); xmm0 = _mm_shuffle_epi8(_mm_alignr_epi8(xmm2, xmm1, 8), mask); xmm1 = _mm_shuffle_epi8(_mm_alignr_epi8(xmm2, xmm2, 4), mask); xmm3 = _mm_packus_epi16(xmm3, xmm4); xmm0 = _mm_packus_epi16(xmm0, xmm1); _mm_stream_si128(dst128++, xmm3); _mm_stream_si128(dst128++, xmm0); } rgb += inStride; } return S_OK; } template DECLARE_CONV_FUNC_IMPL(convert_rgb48_rgb) { // Byte Swap to BGR layout uint8_t *dstBS[4] = {nullptr}; dstBS[0] = (BYTE *)av_malloc(height * srcStride[0]); if (dstBS[0] == nullptr) return E_OUTOFMEMORY; SwsContext *ctx = GetSWSContext(width, height, GetFFInput(), AV_PIX_FMT_BGR48LE, SWS_POINT); sws_scale2(ctx, src, srcStride, 0, height, dstBS, srcStride); // Dither to RGB24/32 with SSE2 const uint16_t *rgb = (const uint16_t *)dstBS[0]; const ptrdiff_t inStride = srcStride[0] >> 1; const ptrdiff_t outStride = dstStride[0]; ptrdiff_t line, i; int processWidth = width * 3; LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = GetRandomDitherCoeffs(height, 2, 8, 0); if (dithers == nullptr) ditherMode = LAVDither_Ordered; __m128i xmm0, xmm1, xmm6, xmm7; uint8_t *rgb24buffer = nullptr; if (out32) { rgb24buffer = (uint8_t *)av_malloc(outStride + AV_INPUT_BUFFER_PADDING_SIZE); if (rgb24buffer == nullptr) { av_freep(&dstBS[0]); return E_OUTOFMEMORY; } } _mm_sfence(); for (line = 0; line < height; line++) { __m128i *dst128 = nullptr; if (out32) { dst128 = (__m128i *)rgb24buffer; } else { dst128 = (__m128i *)(dst[0] + line * outStride); } // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm6 = _mm_load_si128((const __m128i *)(dithers + (line << 4) + 0)); xmm7 = _mm_load_si128((const __m128i *)(dithers + (line << 4) + 8)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm7, line, 8, dithers); xmm6 = xmm7; } for (i = 0; i < processWidth; i += 16) { PIXCONV_LOAD_ALIGNED(xmm0, (rgb + i)); /* load */ PIXCONV_LOAD_ALIGNED(xmm1, (rgb + i + 8)); xmm0 = _mm_adds_epu16(xmm0, xmm6); /* apply dithering coefficients */ xmm1 = _mm_adds_epu16(xmm1, xmm7); xmm0 = _mm_srli_epi16(xmm0, 8); /* shift to 8-bit */ xmm1 = _mm_srli_epi16(xmm1, 8); xmm0 = _mm_packus_epi16(xmm0, xmm1); _mm_stream_si128(dst128++, xmm0); } rgb += inStride; if (out32) { uint32_t *src24 = (uint32_t *)rgb24buffer; uint32_t *dst32 = (uint32_t *)(dst[0] + line * outStride); for (i = 0; i < width; i += 4) { uint32_t sa = src24[0]; uint32_t sb = src24[1]; uint32_t sc = src24[2]; dst32[i + 0] = sa; dst32[i + 1] = (sa >> 24) | (sb << 8); dst32[i + 2] = (sb >> 16) | (sc << 16); dst32[i + 3] = sc >> 8; src24 += 3; } } } if (out32) av_freep(&rgb24buffer); av_freep(&dstBS[0]); return S_OK; } template HRESULT CLAVPixFmtConverter::convert_rgb48_rgb<0> CONV_FUNC_PARAMS; template HRESULT CLAVPixFmtConverter::convert_rgb48_rgb<1> CONV_FUNC_PARAMS; ================================================ FILE: decoder/LAVVideo/pixconv/yuv2rgb.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" #pragma warning(push) #pragma warning(disable : 4556) #define DITHER_STEPS 3 // This function converts 4x2 pixels from the source into 4x2 RGB pixels in the destination template __forceinline static int yuv2rgb_convert_pixels(const uint8_t *&srcY, const uint8_t *&srcU, const uint8_t *&srcV, uint8_t *&dst, ptrdiff_t srcStrideY, ptrdiff_t srcStrideUV, ptrdiff_t dstStride, ptrdiff_t line, const RGBCoeffs *coeffs, const uint16_t *&dithers, ptrdiff_t pos) { __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_setzero_si128(); // Shift > 0 is for 9/10 bit formats if (inputFormat == LAVPixFmt_P016) { // Load 2 32-bit macro pixels from each line, which contain 4 UV at 16-bit each samples PIXCONV_LOAD_PIXEL8(xmm0, srcU); PIXCONV_LOAD_PIXEL8(xmm2, srcU + srcStrideUV); } else if (shift > 0) { // Load 4 U/V values from line 0/1 into registers PIXCONV_LOAD_4PIXEL16(xmm1, srcU); PIXCONV_LOAD_4PIXEL16(xmm3, srcU + srcStrideUV); PIXCONV_LOAD_4PIXEL16(xmm0, srcV); PIXCONV_LOAD_4PIXEL16(xmm2, srcV + srcStrideUV); // Interleave U and V xmm0 = _mm_unpacklo_epi16(xmm1, xmm0); /* 0V0U0V0U */ xmm2 = _mm_unpacklo_epi16(xmm3, xmm2); /* 0V0U0V0U */ } else if (inputFormat == LAVPixFmt_NV12) { // Load 4 16-bit macro pixels, which contain 4 UV samples PIXCONV_LOAD_4PIXEL16(xmm0, srcU); PIXCONV_LOAD_4PIXEL16(xmm2, srcU + srcStrideUV); // Expand to 16-bit xmm0 = _mm_unpacklo_epi8(xmm0, xmm7); /* 0V0U0V0U */ xmm2 = _mm_unpacklo_epi8(xmm2, xmm7); /* 0V0U0V0U */ } else { PIXCONV_LOAD_4PIXEL8(xmm1, srcU); PIXCONV_LOAD_4PIXEL8(xmm3, srcU + srcStrideUV); PIXCONV_LOAD_4PIXEL8(xmm0, srcV); PIXCONV_LOAD_4PIXEL8(xmm2, srcV + srcStrideUV); // Interleave U and V xmm0 = _mm_unpacklo_epi8(xmm1, xmm0); /* VUVU0000 */ xmm2 = _mm_unpacklo_epi8(xmm3, xmm2); /* VUVU0000 */ // Expand to 16-bit xmm0 = _mm_unpacklo_epi8(xmm0, xmm7); /* 0V0U0V0U */ xmm2 = _mm_unpacklo_epi8(xmm2, xmm7); /* 0V0U0V0U */ } // xmm0/xmm2 contain 4 interleaved U/V samples from two lines each in the 16bit parts, still in their native // bitdepth // Chroma upsampling required if (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_NV12 || inputFormat == LAVPixFmt_YUV422 || inputFormat == LAVPixFmt_P016) { if (inputFormat == LAVPixFmt_P016) { srcU += 8; srcV += 8; } else if (shift > 0 || inputFormat == LAVPixFmt_NV12) { srcU += 4; srcV += 4; } else { srcU += 2; srcV += 2; } // Cut off the over-read into the stride and replace it with the last valid pixel if (right_edge) { xmm6 = _mm_set_epi32(0, 0xffffffff, 0, 0); // First line xmm1 = xmm0; xmm1 = _mm_slli_si128(xmm1, 4); xmm1 = _mm_and_si128(xmm1, xmm6); xmm0 = _mm_andnot_si128(xmm6, xmm0); xmm0 = _mm_or_si128(xmm0, xmm1); // Second line xmm3 = xmm2; xmm3 = _mm_slli_si128(xmm3, 4); xmm3 = _mm_and_si128(xmm3, xmm6); xmm2 = _mm_andnot_si128(xmm6, xmm2); xmm2 = _mm_or_si128(xmm2, xmm3); } // 4:2:0 - upsample to 4:2:2 using 75:25 if (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_NV12 || inputFormat == LAVPixFmt_P016) { // Too high bitdepth, shift down to 14-bit if (shift >= 7) { xmm0 = _mm_srli_epi16(xmm0, shift - 6); xmm2 = _mm_srli_epi16(xmm2, shift - 6); } xmm1 = xmm0; xmm1 = _mm_add_epi16(xmm1, xmm0); /* 2x line 0 */ xmm1 = _mm_add_epi16(xmm1, xmm0); /* 3x line 0 */ xmm1 = _mm_add_epi16(xmm1, xmm2); /* 3x line 0 + line 1 (10bit) */ xmm3 = xmm2; xmm3 = _mm_add_epi16(xmm3, xmm2); /* 2x line 1 */ xmm3 = _mm_add_epi16(xmm3, xmm2); /* 3x line 1 */ xmm3 = _mm_add_epi16(xmm3, xmm0); /* 3x line 1 + line 0 (10bit) */ // If the bit depth is too high, we need to reduce it here (max 15bit) // 14-16 bits need the reduction, because they all result in a 16-bit result if (shift >= 6) { xmm1 = _mm_srli_epi16(xmm1, 1); xmm3 = _mm_srli_epi16(xmm3, 1); } } else { xmm1 = xmm0; xmm3 = xmm2; // Shift to maximum of 15-bit, if required if (shift >= 8) { xmm1 = _mm_srli_epi16(xmm1, 1); xmm3 = _mm_srli_epi16(xmm3, 1); } } // After this step, xmm1 and xmm3 contain 8 16-bit values, V and U interleaved. For 4:2:2, filling 8 to 15 bits // (original bit depth). For 4:2:0, filling input+2 bits (10 to 15). // Upsample to 4:4:4 using 100:0, 50:50, 0:100 scheme (MPEG2 chroma siting) // TODO: MPEG1 chroma siting, use 75:25 xmm0 = xmm1; /* UV UV UV UV */ xmm0 = _mm_unpacklo_epi32(xmm0, xmm7); /* UV 00 UV 00 */ xmm1 = _mm_srli_si128(xmm1, 4); /* UV UV UV 00 */ xmm1 = _mm_unpacklo_epi32(xmm7, xmm1); /* 00 UV 00 UV */ xmm1 = _mm_add_epi16(xmm1, xmm0); /* UV UV UV UV */ xmm1 = _mm_add_epi16(xmm1, xmm0); /* 2UV UV 2UV UV */ xmm0 = _mm_slli_si128(xmm0, 4); /* 00 UV 00 UV */ xmm1 = _mm_add_epi16(xmm1, xmm0); /* 2UV 2UV 2UV 2UV */ // Same for the second row xmm2 = xmm3; /* UV UV UV UV */ xmm2 = _mm_unpacklo_epi32(xmm2, xmm7); /* UV 00 UV 00 */ xmm3 = _mm_srli_si128(xmm3, 4); /* UV UV UV 00 */ xmm3 = _mm_unpacklo_epi32(xmm7, xmm3); /* 00 UV 00 UV */ xmm3 = _mm_add_epi16(xmm3, xmm2); /* UV UV UV UV */ xmm3 = _mm_add_epi16(xmm3, xmm2); /* 2UV UV 2UV UV */ xmm2 = _mm_slli_si128(xmm2, 4); /* 00 UV 00 UV */ xmm3 = _mm_add_epi16(xmm3, xmm2); /* 2UV 2UV 2UV 2UV */ // Shift the result to 12 bit // For 10-bit input, we need to shift one bit off, or we exceed the allowed processing depth // For 8-bit, we need to add one bit if ((inputFormat == LAVPixFmt_YUV420 && shift > 1) || inputFormat == LAVPixFmt_P016) { if (shift >= 5) { xmm1 = _mm_srli_epi16(xmm1, 4); xmm3 = _mm_srli_epi16(xmm3, 4); } else { xmm1 = _mm_srli_epi16(xmm1, shift - 1); xmm3 = _mm_srli_epi16(xmm3, shift - 1); } } else if (inputFormat == LAVPixFmt_YUV422) { if (shift >= 7) { xmm1 = _mm_srli_epi16(xmm1, 4); xmm3 = _mm_srli_epi16(xmm3, 4); } else if (shift > 3) { xmm1 = _mm_srli_epi16(xmm1, shift - 3); xmm3 = _mm_srli_epi16(xmm3, shift - 3); } else if (shift < 3) { xmm1 = _mm_slli_epi16(xmm1, 3 - shift); xmm3 = _mm_slli_epi16(xmm3, 3 - shift); } } else if ((inputFormat == LAVPixFmt_YUV420 && shift == 0) || inputFormat == LAVPixFmt_NV12) { xmm1 = _mm_slli_epi16(xmm1, 1); xmm3 = _mm_slli_epi16(xmm3, 1); } // 12-bit result, xmm1 & xmm3 with 4 UV combinations each } else if (inputFormat == LAVPixFmt_YUV444) { if (shift > 0) { srcU += 8; srcV += 8; } else { srcU += 4; srcV += 4; } // Shift to 12 bit if (shift > 4) { xmm1 = _mm_srli_epi16(xmm0, shift - 4); xmm3 = _mm_srli_epi16(xmm2, shift - 4); } else if (shift < 4) { xmm1 = _mm_slli_epi16(xmm0, 4 - shift); xmm3 = _mm_slli_epi16(xmm2, 4 - shift); } else { xmm1 = xmm0; xmm3 = xmm2; } } // Load Y if (shift > 0) { // Load 4 Y values from line 0/1 into registers PIXCONV_LOAD_4PIXEL16(xmm5, srcY); PIXCONV_LOAD_4PIXEL16(xmm0, srcY + srcStrideY); srcY += 8; } else { PIXCONV_LOAD_4PIXEL8(xmm5, srcY); PIXCONV_LOAD_4PIXEL8(xmm0, srcY + srcStrideY); srcY += 4; xmm5 = _mm_unpacklo_epi8(xmm5, xmm7); /* YYYY0000 (16-bit fields) */ xmm0 = _mm_unpacklo_epi8(xmm0, xmm7); /* YYYY0000 (16-bit fields)*/ } xmm0 = _mm_unpacklo_epi64(xmm0, xmm5); /* YYYYYYYY */ // After this step, xmm1 & xmm3 contain 4 UV pairs, each in a 16-bit value, filling 12-bit. if (!ycgco) { // YCbCr conversion // Shift Y to 14 bits if (shift < 6) { xmm0 = _mm_slli_epi16(xmm0, 6 - shift); } else if (shift > 6) { xmm0 = _mm_srli_epi16(xmm0, shift - 6); } xmm0 = _mm_subs_epu16(xmm0, coeffs->Ysub); /* Y-16 (in case of range expansion) */ xmm0 = _mm_mulhi_epi16(xmm0, coeffs->cy); /* Y*cy (result is 28 bits, with 12 high-bits packed into the result) */ xmm0 = _mm_add_epi16(xmm0, coeffs->rgb_add); /* Y*cy + 16 (in case of range compression) */ xmm1 = _mm_subs_epi16(xmm1, coeffs->CbCr_center); /* move CbCr to proper range */ xmm3 = _mm_subs_epi16(xmm3, coeffs->CbCr_center); xmm6 = xmm1; xmm4 = xmm3; xmm6 = _mm_madd_epi16(xmm6, coeffs->cR_Cr); /* Result is 25 bits (12 from chroma, 13 from coeff) */ xmm4 = _mm_madd_epi16(xmm4, coeffs->cR_Cr); xmm6 = _mm_srai_epi32(xmm6, 13); /* Reduce to 12 bit */ xmm4 = _mm_srai_epi32(xmm4, 13); xmm6 = _mm_packs_epi32(xmm6, xmm7); /* Pack back into 16 bit cells */ xmm4 = _mm_packs_epi32(xmm4, xmm7); xmm6 = _mm_unpacklo_epi64(xmm4, xmm6); /* Interleave both parts */ xmm6 = _mm_add_epi16(xmm6, xmm0); /* R (12bit) */ xmm5 = xmm1; xmm4 = xmm3; xmm5 = _mm_madd_epi16(xmm5, coeffs->cG_Cb_cG_Cr); /* Result is 25 bits (12 from chroma, 13 from coeff) */ xmm4 = _mm_madd_epi16(xmm4, coeffs->cG_Cb_cG_Cr); xmm5 = _mm_srai_epi32(xmm5, 13); /* Reduce to 12 bit */ xmm4 = _mm_srai_epi32(xmm4, 13); xmm5 = _mm_packs_epi32(xmm5, xmm7); /* Pack back into 16 bit cells */ xmm4 = _mm_packs_epi32(xmm4, xmm7); xmm5 = _mm_unpacklo_epi64(xmm4, xmm5); /* Interleave both parts */ xmm5 = _mm_add_epi16(xmm5, xmm0); /* G (12bit) */ xmm1 = _mm_madd_epi16(xmm1, coeffs->cB_Cb); /* Result is 25 bits (12 from chroma, 13 from coeff) */ xmm3 = _mm_madd_epi16(xmm3, coeffs->cB_Cb); xmm1 = _mm_srai_epi32(xmm1, 13); /* Reduce to 12 bit */ xmm3 = _mm_srai_epi32(xmm3, 13); xmm1 = _mm_packs_epi32(xmm1, xmm7); /* Pack back into 16 bit cells */ xmm3 = _mm_packs_epi32(xmm3, xmm7); xmm1 = _mm_unpacklo_epi64(xmm3, xmm1); /* Interleave both parts */ xmm1 = _mm_add_epi16(xmm1, xmm0); /* B (12bit) */ } else { // YCgCo conversion // Shift Y to 12 bits if (shift < 4) { xmm0 = _mm_slli_epi16(xmm0, 4 - shift); } else if (shift > 4) { xmm0 = _mm_srli_epi16(xmm0, shift - 4); } xmm7 = _mm_set1_epi32(0x0000FFFF); xmm2 = xmm1; xmm4 = xmm3; xmm1 = _mm_and_si128(xmm1, xmm7); /* null out the high-order bytes to get the Cg values */ xmm4 = _mm_and_si128(xmm4, xmm7); xmm3 = _mm_srli_epi32(xmm3, 16); /* right shift the Co values */ xmm2 = _mm_srli_epi32(xmm2, 16); xmm1 = _mm_packs_epi32(xmm4, xmm1); /* Pack Cg into xmm1 */ xmm3 = _mm_packs_epi32(xmm3, xmm2); /* Pack Co into xmm3 */ xmm2 = coeffs->CbCr_center; /* move CgCo to proper range */ xmm1 = _mm_subs_epi16(xmm1, xmm2); xmm3 = _mm_subs_epi16(xmm3, xmm2); xmm2 = xmm0; xmm2 = _mm_subs_epi16(xmm2, xmm1); /* tmp = Y - Cg */ xmm6 = _mm_adds_epi16(xmm2, xmm3); /* R = tmp + Co */ xmm5 = _mm_adds_epi16(xmm0, xmm1); /* G = Y + Cg */ xmm1 = _mm_subs_epi16(xmm2, xmm3); /* B = tmp - Co */ } // Dithering if (dithertype == LAVDither_Random) { /* Load random dithering coeffs from the dithers buffer */ int offset = (pos % (DITHER_STEPS * 4 * 2)) * 6; xmm2 = _mm_load_si128((const __m128i *)(dithers + 0 + offset)); xmm3 = _mm_load_si128((const __m128i *)(dithers + 8 + offset)); xmm4 = _mm_load_si128((const __m128i *)(dithers + 16 + offset)); } else { /* Load dithering coeffs and combine them for two lines */ const uint16_t *d1 = dither_8x8_256[line % 8]; xmm2 = _mm_load_si128((const __m128i *)d1); const uint16_t *d2 = dither_8x8_256[(line + 1) % 8]; xmm3 = _mm_load_si128((const __m128i *)d2); xmm4 = xmm2; xmm2 = _mm_unpacklo_epi64(xmm2, xmm3); xmm4 = _mm_unpackhi_epi64(xmm4, xmm3); xmm2 = _mm_srli_epi16(xmm2, 4); xmm4 = _mm_srli_epi16(xmm4, 4); xmm3 = xmm4; } xmm6 = _mm_adds_epu16(xmm6, xmm2); /* Apply coefficients to the RGB values */ xmm5 = _mm_adds_epu16(xmm5, xmm3); xmm1 = _mm_adds_epu16(xmm1, xmm4); xmm6 = _mm_srai_epi16(xmm6, 4); /* Shift to 8 bit */ xmm5 = _mm_srai_epi16(xmm5, 4); xmm1 = _mm_srai_epi16(xmm1, 4); xmm2 = _mm_cmpeq_epi8(xmm2, xmm2); /* 0xffffffff,0xffffffff,0xffffffff,0xffffffff */ xmm6 = _mm_packus_epi16(xmm6, xmm7); /* R (lower 8bytes,8bit) * 8 */ xmm5 = _mm_packus_epi16(xmm5, xmm7); /* G (lower 8bytes,8bit) * 8 */ xmm1 = _mm_packus_epi16(xmm1, xmm7); /* B (lower 8bytes,8bit) * 8 */ xmm6 = _mm_unpacklo_epi8(xmm6, xmm2); // 0xff,R xmm1 = _mm_unpacklo_epi8(xmm1, xmm5); // G,B xmm2 = xmm1; xmm1 = _mm_unpackhi_epi16(xmm1, xmm6); // 0xff,RGB * 4 (line 0) xmm2 = _mm_unpacklo_epi16(xmm2, xmm6); // 0xff,RGB * 4 (line 1) // TODO: RGB limiting if (outFmt == 1) { _mm_stream_si128((__m128i *)(dst), xmm1); _mm_stream_si128((__m128i *)(dst + dstStride), xmm2); dst += 16; } else { // RGB 24 output is terribly inefficient due to the un-aligned size of 3 bytes per pixel uint32_t eax; __declspec(align(16)) uint8_t rgbbuf[32]; *(uint32_t *)rgbbuf = _mm_cvtsi128_si32(xmm1); xmm1 = _mm_srli_si128(xmm1, 4); *(uint32_t *)(rgbbuf + 3) = _mm_cvtsi128_si32(xmm1); xmm1 = _mm_srli_si128(xmm1, 4); *(uint32_t *)(rgbbuf + 6) = _mm_cvtsi128_si32(xmm1); xmm1 = _mm_srli_si128(xmm1, 4); *(uint32_t *)(rgbbuf + 9) = _mm_cvtsi128_si32(xmm1); *(uint32_t *)(rgbbuf + 16) = _mm_cvtsi128_si32(xmm2); xmm2 = _mm_srli_si128(xmm2, 4); *(uint32_t *)(rgbbuf + 19) = _mm_cvtsi128_si32(xmm2); xmm2 = _mm_srli_si128(xmm2, 4); *(uint32_t *)(rgbbuf + 22) = _mm_cvtsi128_si32(xmm2); xmm2 = _mm_srli_si128(xmm2, 4); *(uint32_t *)(rgbbuf + 25) = _mm_cvtsi128_si32(xmm2); xmm1 = _mm_loadl_epi64((const __m128i *)(rgbbuf)); xmm2 = _mm_loadl_epi64((const __m128i *)(rgbbuf + 16)); _mm_storel_epi64((__m128i *)(dst), xmm1); eax = *(uint32_t *)(rgbbuf + 8); *(uint32_t *)(dst + 8) = eax; _mm_storel_epi64((__m128i *)(dst + dstStride), xmm2); eax = *(uint32_t *)(rgbbuf + 24); *(uint32_t *)(dst + dstStride + 8) = eax; dst += 12; } return 0; } template static int __stdcall yuv2rgb_convert(const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV, uint8_t *dst, int width, int height, ptrdiff_t srcStrideY, ptrdiff_t srcStrideUV, ptrdiff_t dstStride, ptrdiff_t sliceYStart, ptrdiff_t sliceYEnd, const RGBCoeffs *coeffs, const uint16_t *dithers) { const uint8_t *y = srcY; const uint8_t *u = srcU; const uint8_t *v = srcV; uint8_t *rgb = dst; ptrdiff_t line = sliceYStart; ptrdiff_t lastLine = sliceYEnd; bool lastLineInOddHeight = false; const ptrdiff_t endx = width - 4; const uint16_t *lineDither = dithers; _mm_sfence(); // 4:2:0 needs special handling for the first and the last line if (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_NV12 || inputFormat == LAVPixFmt_P016) { if (line == 0) { for (ptrdiff_t i = 0; i < endx; i += 4) { yuv2rgb_convert_pixels(y, u, v, rgb, 0, 0, 0, line, coeffs, lineDither, i); } yuv2rgb_convert_pixels(y, u, v, rgb, 0, 0, 0, line, coeffs, lineDither, 0); line = 1; } if (lastLine == height) lastLine--; } else if (lastLine == height && (lastLine & 1)) { lastLine--; lastLineInOddHeight = true; } for (; line < lastLine; line += 2) { if (dithertype == LAVDither_Random) lineDither = dithers + (line * 24 * DITHER_STEPS); y = srcY + line * srcStrideY; if (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_NV12 || inputFormat == LAVPixFmt_P016) { u = srcU + (line >> 1) * srcStrideUV; v = srcV + (line >> 1) * srcStrideUV; } else { u = srcU + line * srcStrideUV; v = srcV + line * srcStrideUV; } rgb = dst + line * dstStride; for (ptrdiff_t i = 0; i < endx; i += 4) { yuv2rgb_convert_pixels( y, u, v, rgb, srcStrideY, srcStrideUV, dstStride, line, coeffs, lineDither, i); } yuv2rgb_convert_pixels( y, u, v, rgb, srcStrideY, srcStrideUV, dstStride, line, coeffs, lineDither, 0); } if (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_NV12 || inputFormat == LAVPixFmt_P016 || lastLineInOddHeight) { if (sliceYEnd == height) { if (dithertype == LAVDither_Random) lineDither = dithers + ((height - 2) * 24 * DITHER_STEPS); y = srcY + (height - 1) * srcStrideY; if (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_NV12 || inputFormat == LAVPixFmt_P016) { u = srcU + ((height >> 1) - 1) * srcStrideUV; v = srcV + ((height >> 1) - 1) * srcStrideUV; } else { u = srcU + (height - 1) * srcStrideUV; v = srcV + (height - 1) * srcStrideUV; } rgb = dst + (height - 1) * dstStride; for (ptrdiff_t i = 0; i < endx; i += 4) { yuv2rgb_convert_pixels(y, u, v, rgb, 0, 0, 0, line, coeffs, lineDither, i); } yuv2rgb_convert_pixels(y, u, v, rgb, 0, 0, 0, line, coeffs, lineDither, 0); } } return 0; } DECLARE_CONV_FUNC_IMPL(convert_yuv_rgb) { const RGBCoeffs *coeffs = getRGBCoeffs(width, height); if (coeffs == nullptr) return E_OUTOFMEMORY; if (!m_bRGBConvInit) { m_bRGBConvInit = TRUE; InitRGBConvDispatcher(); } BOOL bYCgCo = (m_ColorProps.VideoTransferMatrix == 7); int shift = max(bpp - 8, 0); ASSERT(shift >= 0 && shift <= 8); int outFmt = -1; switch (outputFormat) { case LAVOutPixFmt_RGB24: outFmt = 0; break; case LAVOutPixFmt_RGB32: outFmt = 1; break; default: ASSERT(0); } LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = (ditherMode == LAVDither_Random) ? GetRandomDitherCoeffs(height, DITHER_STEPS * 3, 4, 0) : nullptr; if (ditherMode == LAVDither_Random && dithers == nullptr) { ditherMode = LAVDither_Ordered; } // Map the bX formats to their normal counter part, the shift parameter controls this now if (inputFormat == LAVPixFmt_YUV420bX || inputFormat == LAVPixFmt_YUV422bX || inputFormat == LAVPixFmt_YUV444bX) inputFormat = (LAVPixelFormat)(inputFormat - 1); // P010 has the data in the high bits, so set shift appropriately if (inputFormat == LAVPixFmt_P016) shift = 8; YUVRGBConversionFunc convFn = m_RGBConvFuncs[outFmt][ditherMode][bYCgCo][inputFormat][shift]; if (convFn == nullptr) { ASSERT(0); return E_FAIL; } // run conversion, threaded if (m_NumThreads <= 1) { convFn(src[0], src[1], src[2], dst[0], width, height, srcStride[0], srcStride[1], dstStride[0], 0, height, coeffs, dithers); } else { const int is_odd = (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_NV12 || inputFormat == LAVPixFmt_P016); const ptrdiff_t lines_per_thread = (height / m_NumThreads) & ~1; Concurrency::parallel_for(0, m_NumThreads, [&](int i) { const ptrdiff_t starty = (i * lines_per_thread); const ptrdiff_t endy = (i == (m_NumThreads - 1)) ? height : starty + lines_per_thread + is_odd; convFn(src[0], src[1], src[2], dst[0], width, height, srcStride[0], srcStride[1], dstStride[0], starty + (i ? is_odd : 0), endy, coeffs, dithers); }); } return S_OK; } #define CONV_FUNC_INT2(out32, dither, ycgco, format, shift) \ m_RGBConvFuncs[out32][dither][ycgco][format][shift] = yuv2rgb_convert; #define CONV_FUNC_INT(dither, ycgco, format, shift) \ CONV_FUNC_INT2(0, dither, ycgco, format, shift) \ CONV_FUNC_INT2(1, dither, ycgco, format, shift) #define CONV_FUNC(format, shift) \ CONV_FUNC_INT(LAVDither_Ordered, 0, format, shift) \ CONV_FUNC_INT(LAVDither_Random, 0, format, shift) \ CONV_FUNC_INT(LAVDither_Ordered, 1, format, shift) \ CONV_FUNC_INT(LAVDither_Random, 1, format, shift) #define CONV_FUNCX(format) \ CONV_FUNC(format, 0) \ CONV_FUNC(format, 1) \ CONV_FUNC(format, 2) \ /* CONV_FUNC(format, 3) */ \ CONV_FUNC(format, 4) \ /* CONV_FUNC(format, 5) */ \ CONV_FUNC(format, 6) \ /* CONV_FUNC(format, 7) */ \ CONV_FUNC(format, 8) void CLAVPixFmtConverter::InitRGBConvDispatcher() { ZeroMemory(&m_RGBConvFuncs, sizeof(m_RGBConvFuncs)); CONV_FUNC(LAVPixFmt_NV12, 0); CONV_FUNC(LAVPixFmt_P016, 8); CONV_FUNCX(LAVPixFmt_YUV420); CONV_FUNCX(LAVPixFmt_YUV422); CONV_FUNCX(LAVPixFmt_YUV444); } const RGBCoeffs *CLAVPixFmtConverter::getRGBCoeffs(int width, int height) { if (!m_rgbCoeffs || width != swsWidth || height != swsHeight) { swsWidth = width; swsHeight = height; if (!m_rgbCoeffs) { m_rgbCoeffs = (RGBCoeffs *)_aligned_malloc(sizeof(RGBCoeffs), 16); if (m_rgbCoeffs == nullptr) return nullptr; } DXVA2_VideoTransferMatrix matrix = (DXVA2_VideoTransferMatrix)m_ColorProps.VideoTransferMatrix; if (matrix == DXVA2_VideoTransferMatrix_Unknown) { matrix = (swsHeight > 576 || swsWidth > 1024) ? DXVA2_VideoTransferMatrix_BT709 : DXVA2_VideoTransferMatrix_BT601; } BOOL inFullRange = (m_ColorProps.NominalRange == DXVA2_NominalRange_0_255); BOOL outFullRange = (swsOutputRange == 0) ? inFullRange : (swsOutputRange == 2); int inputWhite, inputBlack, inputChroma, outputWhite, outputBlack; if (inFullRange) { inputWhite = 255; inputBlack = 0; inputChroma = 1; } else { inputWhite = 235; inputBlack = 16; inputChroma = 16; } if (outFullRange) { outputWhite = 255; outputBlack = 0; } else { outputWhite = 235; outputBlack = 16; } double Kr, Kg, Kb; switch (matrix) { case DXVA2_VideoTransferMatrix_BT601: Kr = 0.299; Kg = 0.587; Kb = 0.114; break; case DXVA2_VideoTransferMatrix_SMPTE240M: Kr = 0.2120; Kg = 0.7010; Kb = 0.0870; break; case 6: // FCC Kr = 0.300; Kg = 0.590; Kb = 0.110; break; case 4: // BT.2020 Kr = 0.2627; Kg = 0.6780; Kb = 0.0593; break; default: DbgLog((LOG_TRACE, 10, L"::getRGBCoeffs(): Unknown color space: %d - defaulting to BT709", matrix)); case DXVA2_VideoTransferMatrix_BT709: Kr = 0.2126; Kg = 0.7152; Kb = 0.0722; break; } double in_y_range = inputWhite - inputBlack; double chr_range = 128 - inputChroma; double cspOptionsRGBrange = outputWhite - outputBlack; double y_mul, vr_mul, ug_mul, vg_mul, ub_mul; y_mul = cspOptionsRGBrange / in_y_range; vr_mul = (cspOptionsRGBrange / chr_range) * (1.0 - Kr); ug_mul = (cspOptionsRGBrange / chr_range) * (1.0 - Kb) * Kb / Kg; vg_mul = (cspOptionsRGBrange / chr_range) * (1.0 - Kr) * Kr / Kg; ub_mul = (cspOptionsRGBrange / chr_range) * (1.0 - Kb); short sub = min(outputBlack, inputBlack); short Ysub = inputBlack - sub; short RGB_add1 = outputBlack - sub; short cy = short(y_mul * 16384 + 0.5); short crv = short(vr_mul * 8192 + 0.5); short cgu = short(-ug_mul * 8192 - 0.5); short cgv = short(-vg_mul * 8192 - 0.5); short cbu = short(ub_mul * 8192 + 0.5); m_rgbCoeffs->Ysub = _mm_set1_epi16(Ysub << 6); m_rgbCoeffs->cy = _mm_set1_epi16(cy); m_rgbCoeffs->CbCr_center = _mm_set1_epi16(128 << 4); m_rgbCoeffs->cR_Cr = _mm_set1_epi32(crv << 16); // R m_rgbCoeffs->cG_Cb_cG_Cr = _mm_set1_epi32((cgv << 16) + cgu); // G m_rgbCoeffs->cB_Cb = _mm_set1_epi32(cbu); // B m_rgbCoeffs->rgb_add = _mm_set1_epi16(RGB_add1 << 4); // YCgCo if (matrix == 7) { m_rgbCoeffs->CbCr_center = _mm_set1_epi16(0x0800); // Other Coeffs are not used in YCgCo } } return m_rgbCoeffs; } #pragma warning(pop) ================================================ FILE: decoder/LAVVideo/pixconv/yuv2yuv_unscaled.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" template DECLARE_CONV_FUNC_IMPL(convert_yuv_yv_nv12_dither_le) { const ptrdiff_t inYStride = srcStride[0]; const ptrdiff_t inUVStride = srcStride[1]; const ptrdiff_t outYStride = dstStride[0]; const ptrdiff_t outUVStride = dstStride[1]; ptrdiff_t chromaWidth = width; ptrdiff_t chromaHeight = height; LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = GetRandomDitherCoeffs(height, 4, 8, 0); if (dithers == nullptr) ditherMode = LAVDither_Ordered; if (inputFormat == LAVPixFmt_YUV420bX) chromaHeight = chromaHeight >> 1; if (inputFormat == LAVPixFmt_YUV420bX || inputFormat == LAVPixFmt_YUV422bX) chromaWidth = (chromaWidth + 1) >> 1; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; _mm_sfence(); // Process Y for (line = 0; line < height; ++line) { // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm4 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 0)); xmm5 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 8)); xmm6 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 16)); xmm7 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 24)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm7, line, 8, dithers); xmm4 = xmm5 = xmm6 = xmm7; } const uint16_t *const y = (const uint16_t *)(src[0] + line * inYStride); uint16_t *const dy = (uint16_t *)(dst[0] + line * outYStride); for (i = 0; i < width; i += 32) { // Load pixels into registers, and apply dithering PIXCONV_LOAD_PIXEL16_DITHER(xmm0, xmm4, (y + i + 0), bpp); /* Y0Y0Y0Y0 */ PIXCONV_LOAD_PIXEL16_DITHER(xmm1, xmm5, (y + i + 8), bpp); /* Y0Y0Y0Y0 */ PIXCONV_LOAD_PIXEL16_DITHER(xmm2, xmm6, (y + i + 16), bpp); /* Y0Y0Y0Y0 */ PIXCONV_LOAD_PIXEL16_DITHER(xmm3, xmm7, (y + i + 24), bpp); /* Y0Y0Y0Y0 */ xmm0 = _mm_packus_epi16(xmm0, xmm1); /* YYYYYYYY */ xmm2 = _mm_packus_epi16(xmm2, xmm3); /* YYYYYYYY */ // Write data back PIXCONV_PUT_STREAM(dy + (i >> 1) + 0, xmm0); PIXCONV_PUT_STREAM(dy + (i >> 1) + 8, xmm2); } // Process U/V for chromaHeight lines if (line < chromaHeight) { const uint16_t *const u = (const uint16_t *)(src[1] + line * inUVStride); const uint16_t *const v = (const uint16_t *)(src[2] + line * inUVStride); uint8_t *const duv = (uint8_t *)(dst[1] + line * outUVStride); uint8_t *const du = (uint8_t *)(dst[2] + line * outUVStride); uint8_t *const dv = (uint8_t *)(dst[1] + line * outUVStride); for (i = 0; i < chromaWidth; i += 16) { PIXCONV_LOAD_PIXEL16_DITHER(xmm0, xmm4, (u + i + 0), bpp); /* U0U0U0U0 */ PIXCONV_LOAD_PIXEL16_DITHER(xmm1, xmm5, (u + i + 8), bpp); /* U0U0U0U0 */ PIXCONV_LOAD_PIXEL16_DITHER(xmm2, xmm6, (v + i + 0), bpp); /* V0V0V0V0 */ PIXCONV_LOAD_PIXEL16_DITHER(xmm3, xmm7, (v + i + 8), bpp); /* V0V0V0V0 */ xmm0 = _mm_packus_epi16(xmm0, xmm1); /* UUUUUUUU */ xmm2 = _mm_packus_epi16(xmm2, xmm3); /* VVVVVVVV */ if (nv12) { xmm1 = xmm0; xmm0 = _mm_unpacklo_epi8(xmm0, xmm2); xmm1 = _mm_unpackhi_epi8(xmm1, xmm2); PIXCONV_PUT_STREAM(duv + (i << 1) + 0, xmm0); PIXCONV_PUT_STREAM(duv + (i << 1) + 16, xmm1); } else { PIXCONV_PUT_STREAM(du + i, xmm0); PIXCONV_PUT_STREAM(dv + i, xmm2); } } } } return S_OK; } // Force creation of these two variants template HRESULT CLAVPixFmtConverter::convert_yuv_yv_nv12_dither_le<0> CONV_FUNC_PARAMS; template HRESULT CLAVPixFmtConverter::convert_yuv_yv_nv12_dither_le<1> CONV_FUNC_PARAMS; DECLARE_CONV_FUNC_IMPL(convert_yuv420_px1x_le) { const ptrdiff_t inYStride = srcStride[0]; const ptrdiff_t inUVStride = srcStride[1]; const ptrdiff_t outYStride = dstStride[0]; const ptrdiff_t outUVStride = dstStride[1]; const ptrdiff_t uvHeight = (outputFormat == LAVOutPixFmt_P010 || outputFormat == LAVOutPixFmt_P016) ? (height >> 1) : height; const ptrdiff_t uvWidth = (width + 1) >> 1; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2; _mm_sfence(); // Process Y for (line = 0; line < height; ++line) { const uint16_t *const y = (const uint16_t *)(src[0] + line * inYStride); uint16_t *const d = (uint16_t *)(dst[0] + line * outYStride); for (i = 0; i < width; i += 16) { // Load 2x8 pixels into registers PIXCONV_LOAD_PIXEL16X2(xmm0, xmm1, (y + i + 0), (y + i + 8), bpp); // and write them out PIXCONV_PUT_STREAM(d + i + 0, xmm0); PIXCONV_PUT_STREAM(d + i + 8, xmm1); } } // Process UV for (line = 0; line < uvHeight; ++line) { const uint16_t *const u = (const uint16_t *)(src[1] + line * inUVStride); const uint16_t *const v = (const uint16_t *)(src[2] + line * inUVStride); uint16_t *const d = (uint16_t *)(dst[1] + line * outUVStride); for (i = 0; i < uvWidth; i += 8) { // Load 8 pixels into register PIXCONV_LOAD_PIXEL16X2(xmm0, xmm1, (v + i), (u + i), bpp); // Load V and U xmm2 = xmm0; xmm0 = _mm_unpacklo_epi16(xmm1, xmm0); /* UVUV */ xmm2 = _mm_unpackhi_epi16(xmm1, xmm2); /* UVUV */ PIXCONV_PUT_STREAM(d + (i << 1) + 0, xmm0); PIXCONV_PUT_STREAM(d + (i << 1) + 8, xmm2); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_yuv_yv) { const uint8_t *y = src[0]; const uint8_t *u = src[1]; const uint8_t *v = src[2]; const ptrdiff_t inLumaStride = srcStride[0]; const ptrdiff_t inChromaStride = srcStride[1]; const ptrdiff_t outLumaStride = dstStride[0]; const ptrdiff_t outChromaStride = dstStride[1]; ptrdiff_t line; ptrdiff_t chromaWidth = width; ptrdiff_t chromaHeight = height; if (inputFormat == LAVPixFmt_YUV420) chromaHeight = chromaHeight >> 1; if (inputFormat == LAVPixFmt_YUV420 || inputFormat == LAVPixFmt_YUV422) chromaWidth = (chromaWidth + 1) >> 1; // Copy planes _mm_sfence(); // Y if ((outLumaStride % 16) == 0 && ((intptr_t)dst[0] % 16u) == 0) { for (line = 0; line < height; ++line) { PIXCONV_MEMCPY_ALIGNED(dst[0] + outLumaStride * line, y + inLumaStride * line, width); } } else { for (line = 0; line < height; ++line) { memcpy(dst[0] + outLumaStride * line, y + inLumaStride * line, width); } } // U/V if ((outChromaStride % 16) == 0 && ((intptr_t)dst[1] % 16u) == 0) { for (line = 0; line < chromaHeight; ++line) { PIXCONV_MEMCPY_ALIGNED_TWO(dst[2] + outChromaStride * line, u + inChromaStride * line, dst[1] + outChromaStride * line, v + inChromaStride * line, chromaWidth); } } else { for (line = 0; line < chromaHeight; ++line) { memcpy(dst[2] + outChromaStride * line, u + inChromaStride * line, chromaWidth); memcpy(dst[1] + outChromaStride * line, v + inChromaStride * line, chromaWidth); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_yuv420_nv12) { const ptrdiff_t inLumaStride = srcStride[0]; const ptrdiff_t inChromaStride = srcStride[1]; const ptrdiff_t outLumaStride = dstStride[0]; const ptrdiff_t outChromaStride = dstStride[1]; const ptrdiff_t chromaWidth = (width + 1) >> 1; const ptrdiff_t chromaHeight = height >> 1; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4; _mm_sfence(); // Y for (line = 0; line < height; ++line) { PIXCONV_MEMCPY_ALIGNED(dst[0] + outLumaStride * line, src[0] + inLumaStride * line, width); } // U/V for (line = 0; line < chromaHeight; ++line) { const uint8_t *const u = src[1] + line * inChromaStride; const uint8_t *const v = src[2] + line * inChromaStride; uint8_t *const d = dst[1] + line * outChromaStride; for (i = 0; i < (chromaWidth - 31); i += 32) { PIXCONV_LOAD_PIXEL8_ALIGNED(xmm0, v + i); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm1, u + i); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm2, v + i + 16); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm3, u + i + 16); xmm4 = xmm0; xmm0 = _mm_unpacklo_epi8(xmm1, xmm0); xmm4 = _mm_unpackhi_epi8(xmm1, xmm4); xmm1 = xmm2; xmm2 = _mm_unpacklo_epi8(xmm3, xmm2); xmm1 = _mm_unpackhi_epi8(xmm3, xmm1); PIXCONV_PUT_STREAM(d + (i << 1) + 0, xmm0); PIXCONV_PUT_STREAM(d + (i << 1) + 16, xmm4); PIXCONV_PUT_STREAM(d + (i << 1) + 32, xmm2); PIXCONV_PUT_STREAM(d + (i << 1) + 48, xmm1); } for (; i < chromaWidth; i += 16) { PIXCONV_LOAD_PIXEL8_ALIGNED(xmm0, v + i); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm1, u + i); xmm2 = xmm0; xmm0 = _mm_unpacklo_epi8(xmm1, xmm0); xmm2 = _mm_unpackhi_epi8(xmm1, xmm2); PIXCONV_PUT_STREAM(d + (i << 1) + 0, xmm0); PIXCONV_PUT_STREAM(d + (i << 1) + 16, xmm2); } } return S_OK; } template DECLARE_CONV_FUNC_IMPL(convert_yuv422_yuy2_uyvy) { const ptrdiff_t inLumaStride = srcStride[0]; const ptrdiff_t inChromaStride = srcStride[1]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t chromaWidth = (width + 1) >> 1; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5; _mm_sfence(); for (line = 0; line < height; ++line) { const uint8_t *const y = src[0] + line * inLumaStride; const uint8_t *const u = src[1] + line * inChromaStride; const uint8_t *const v = src[2] + line * inChromaStride; uint8_t *const d = dst[0] + line * outStride; for (i = 0; i < chromaWidth; i += 16) { // Load pixels PIXCONV_LOAD_PIXEL8_ALIGNED(xmm0, (y + (i << 1) + 0)); /* YYYY */ PIXCONV_LOAD_PIXEL8_ALIGNED(xmm1, (y + (i << 1) + 16)); /* YYYY */ PIXCONV_LOAD_PIXEL8_ALIGNED(xmm2, (u + i)); /* UUUU */ PIXCONV_LOAD_PIXEL8_ALIGNED(xmm3, (v + i)); /* VVVV */ // Interleave Us and Vs xmm4 = xmm2; xmm4 = _mm_unpacklo_epi8(xmm4, xmm3); xmm2 = _mm_unpackhi_epi8(xmm2, xmm3); // Interlave those with the Ys if (uyvy) { xmm3 = xmm4; xmm3 = _mm_unpacklo_epi8(xmm3, xmm0); xmm4 = _mm_unpackhi_epi8(xmm4, xmm0); xmm5 = xmm2; xmm5 = _mm_unpacklo_epi8(xmm5, xmm1); xmm2 = _mm_unpackhi_epi8(xmm2, xmm1); } else { xmm3 = xmm0; xmm3 = _mm_unpacklo_epi8(xmm3, xmm4); xmm4 = _mm_unpackhi_epi8(xmm0, xmm4); xmm5 = xmm1; xmm5 = _mm_unpacklo_epi8(xmm5, xmm2); xmm2 = _mm_unpackhi_epi8(xmm1, xmm2); } PIXCONV_PUT_STREAM(d + (i << 2) + 0, xmm3); PIXCONV_PUT_STREAM(d + (i << 2) + 16, xmm4); PIXCONV_PUT_STREAM(d + (i << 2) + 32, xmm5); PIXCONV_PUT_STREAM(d + (i << 2) + 48, xmm2); } } return S_OK; } // Force creation of these two variants template HRESULT CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy<0> CONV_FUNC_PARAMS; template HRESULT CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy<1> CONV_FUNC_PARAMS; template DECLARE_CONV_FUNC_IMPL(convert_yuv422_yuy2_uyvy_dither_le) { const ptrdiff_t inLumaStride = srcStride[0]; const ptrdiff_t inChromaStride = srcStride[1]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t chromaWidth = (width + 1) >> 1; LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = GetRandomDitherCoeffs(height, 4, 8, 0); if (dithers == nullptr) ditherMode = LAVDither_Ordered; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; _mm_sfence(); for (line = 0; line < height; ++line) { const uint16_t *const y = (const uint16_t *)(src[0] + line * inLumaStride); const uint16_t *const u = (const uint16_t *)(src[1] + line * inChromaStride); const uint16_t *const v = (const uint16_t *)(src[2] + line * inChromaStride); uint16_t *const d = (uint16_t *)(dst[0] + line * outStride); // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm4 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 0)); xmm5 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 8)); xmm6 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 16)); xmm7 = _mm_load_si128((const __m128i *)(dithers + (line << 5) + 24)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm7, line, 8, dithers); xmm4 = xmm5 = xmm6 = xmm7; } for (i = 0; i < chromaWidth; i += 8) { // Load pixels PIXCONV_LOAD_PIXEL16_DITHER(xmm0, xmm4, (y + (i * 2) + 0), bpp); /* YYYY */ PIXCONV_LOAD_PIXEL16_DITHER(xmm1, xmm5, (y + (i * 2) + 8), bpp); /* YYYY */ PIXCONV_LOAD_PIXEL16_DITHER(xmm2, xmm6, (u + i), bpp); /* UUUU */ PIXCONV_LOAD_PIXEL16_DITHER(xmm3, xmm7, (v + i), bpp); /* VVVV */ // Pack Ys xmm0 = _mm_packus_epi16(xmm0, xmm1); // Interleave Us and Vs xmm2 = _mm_packus_epi16(xmm2, xmm2); xmm3 = _mm_packus_epi16(xmm3, xmm3); xmm2 = _mm_unpacklo_epi8(xmm2, xmm3); // Interlave those with the Ys if (uyvy) { xmm3 = xmm2; xmm3 = _mm_unpacklo_epi8(xmm3, xmm0); xmm2 = _mm_unpackhi_epi8(xmm2, xmm0); } else { xmm3 = xmm0; xmm3 = _mm_unpacklo_epi8(xmm3, xmm2); xmm2 = _mm_unpackhi_epi8(xmm0, xmm2); } PIXCONV_PUT_STREAM(d + (i << 1) + 0, xmm3); PIXCONV_PUT_STREAM(d + (i << 1) + 8, xmm2); } } return S_OK; } // Force creation of these two variants template HRESULT CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy_dither_le<0> CONV_FUNC_PARAMS; template HRESULT CLAVPixFmtConverter::convert_yuv422_yuy2_uyvy_dither_le<1> CONV_FUNC_PARAMS; DECLARE_CONV_FUNC_IMPL(convert_nv12_yv12) { const ptrdiff_t inLumaStride = srcStride[0]; const ptrdiff_t inChromaStride = srcStride[1]; const ptrdiff_t outLumaStride = dstStride[0]; const ptrdiff_t outChromaStride = dstStride[1]; const ptrdiff_t chromaHeight = height >> 1; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm7; xmm7 = _mm_set1_epi16(0x00FF); _mm_sfence(); // Copy the y for (line = 0; line < height; line++) { PIXCONV_MEMCPY_ALIGNED(dst[0] + outLumaStride * line, src[0] + inLumaStride * line, width); } for (line = 0; line < chromaHeight; line++) { const uint8_t *const uv = src[1] + line * inChromaStride; uint8_t *const dv = dst[1] + outChromaStride * line; uint8_t *const du = dst[2] + outChromaStride * line; for (i = 0; i < width; i += 32) { PIXCONV_LOAD_PIXEL8_ALIGNED(xmm0, uv + i + 0); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm1, uv + i + 16); xmm2 = xmm0; xmm3 = xmm1; // null out the high-order bytes to get the U values xmm0 = _mm_and_si128(xmm0, xmm7); xmm1 = _mm_and_si128(xmm1, xmm7); // right shift the V values xmm2 = _mm_srli_epi16(xmm2, 8); xmm3 = _mm_srli_epi16(xmm3, 8); // unpack the values xmm0 = _mm_packus_epi16(xmm0, xmm1); xmm2 = _mm_packus_epi16(xmm2, xmm3); PIXCONV_PUT_STREAM(du + (i >> 1), xmm0); PIXCONV_PUT_STREAM(dv + (i >> 1), xmm2); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_p010_nv12_sse2) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t chromaHeight = (height >> 1); const ptrdiff_t byteWidth = width << 1; LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = GetRandomDitherCoeffs(height, 2, 8, 0); if (dithers == nullptr) ditherMode = LAVDither_Ordered; __m128i xmm0, xmm1, xmm2, xmm3; _mm_sfence(); ptrdiff_t line, i; for (line = 0; line < height; line++) { // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm2 = _mm_load_si128((const __m128i *)(dithers + (line << 4) + 0)); xmm3 = _mm_load_si128((const __m128i *)(dithers + (line << 4) + 8)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm2, line, 8, dithers); xmm3 = xmm2; } const uint8_t *y = (src[0] + line * inStride); uint8_t *dy = (dst[0] + line * outStride); for (i = 0; i < byteWidth; i += 32) { PIXCONV_LOAD_ALIGNED(xmm0, y + i + 0); PIXCONV_LOAD_ALIGNED(xmm1, y + i + 16); // apply dithering coeffs xmm0 = _mm_adds_epu16(xmm0, xmm2); xmm1 = _mm_adds_epu16(xmm1, xmm3); // shift and pack to 8-bit xmm0 = _mm_packus_epi16(_mm_srli_epi16(xmm0, 8), _mm_srli_epi16(xmm1, 8)); PIXCONV_PUT_STREAM(dy + (i >> 1), xmm0); } } for (line = 0; line < chromaHeight; line++) { // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm2 = _mm_load_si128((const __m128i *)(dithers + (line << 4) + 0)); xmm3 = _mm_load_si128((const __m128i *)(dithers + (line << 4) + 8)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm2, line, 8, dithers); xmm3 = xmm2; } const uint8_t *uv = (src[1] + line * inStride); uint8_t *duv = (dst[1] + line * outStride); for (i = 0; i < byteWidth; i += 32) { PIXCONV_LOAD_ALIGNED(xmm0, uv + i + 0); PIXCONV_LOAD_ALIGNED(xmm1, uv + i + 16); // apply dithering coeffs xmm0 = _mm_adds_epu16(xmm0, xmm2); xmm1 = _mm_adds_epu16(xmm1, xmm3); // shift and pack to 8-bit xmm0 = _mm_packus_epi16(_mm_srli_epi16(xmm0, 8), _mm_srli_epi16(xmm1, 8)); PIXCONV_PUT_STREAM(duv + (i >> 1), xmm0); } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_y210_p210_sse4) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t byteWidth = width << 2; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_set1_epi32(0x0000FFFF); for (line = 0; line < height; line++) { const uint8_t *srcLine = src[0] + line * inStride; uint8_t *dstY = dst[0] + line * dstStride[0]; uint8_t *dstUV = dst[1] + line * dstStride[1]; for (i = 0; i < (byteWidth - 63); i += 64) { PIXCONV_LOAD_ALIGNED(xmm0, srcLine + i + 0); // Y0 U Y1 V PIXCONV_LOAD_ALIGNED(xmm1, srcLine + i + 16); PIXCONV_LOAD_ALIGNED(xmm2, srcLine + i + 32); PIXCONV_LOAD_ALIGNED(xmm3, srcLine + i + 48); // extract Y xmm4 = _mm_and_si128(xmm0, xmm7); xmm5 = _mm_and_si128(xmm1, xmm7); xmm6 = _mm_packus_epi32(xmm4, xmm5); xmm4 = _mm_and_si128(xmm2, xmm7); xmm5 = _mm_and_si128(xmm3, xmm7); xmm4 = _mm_packus_epi32(xmm4, xmm5); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 0, xmm6); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 16, xmm4); // extract UV xmm4 = _mm_srli_epi32(xmm0, 16); xmm5 = _mm_srli_epi32(xmm1, 16); xmm6 = _mm_packus_epi32(xmm4, xmm5); xmm4 = _mm_srli_epi32(xmm2, 16); xmm5 = _mm_srli_epi32(xmm3, 16); xmm4 = _mm_packus_epi32(xmm4, xmm5); PIXCONV_PUT_STREAM(dstUV + (i >> 1) + 0, xmm6); PIXCONV_PUT_STREAM(dstUV + (i >> 1) + 16, xmm4); } // process left-over pixel for (; i < (byteWidth - 7); i += 8) { const uint16_t *pixel = (const uint16_t *)(srcLine + i); uint16_t *out_y = (uint16_t *)(dstY + (i >> 1)); uint16_t *out_uv = (uint16_t *)(dstUV + (i >> 1)); out_y [0] = pixel[0]; out_uv[0] = pixel[1]; out_y [1] = pixel[2]; out_uv[1] = pixel[3]; } } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_yuy2_yv16_sse2) { const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; const ptrdiff_t byteWidth = width << 1; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_set1_epi16(0x00FF); for (line = 0; line < height; line++) { const uint8_t *srcLine = src[0] + line * inStride; uint8_t *dstY = dst[0] + line * dstStride[0]; uint8_t *dstV = dst[1] + line * dstStride[1]; uint8_t *dstU = dst[2] + line * dstStride[2]; for (i = 0; i < (byteWidth - 63); i += 64) { PIXCONV_LOAD_ALIGNED(xmm0, srcLine + i + 0); // Y0 U Y1 V PIXCONV_LOAD_ALIGNED(xmm1, srcLine + i + 16); PIXCONV_LOAD_ALIGNED(xmm2, srcLine + i + 32); PIXCONV_LOAD_ALIGNED(xmm3, srcLine + i + 48); // extract Y xmm4 = _mm_and_si128(xmm0, xmm7); xmm5 = _mm_and_si128(xmm1, xmm7); xmm6 = _mm_packus_epi16(xmm4, xmm5); xmm4 = _mm_and_si128(xmm2, xmm7); xmm5 = _mm_and_si128(xmm3, xmm7); xmm4 = _mm_packus_epi16(xmm4, xmm5); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 0, xmm6); PIXCONV_PUT_STREAM(dstY + (i >> 1) + 16, xmm4); // extract UV xmm4 = _mm_srli_epi16(xmm0, 8); xmm5 = _mm_srli_epi16(xmm1, 8); xmm0 = _mm_packus_epi16(xmm4, xmm5); xmm4 = _mm_srli_epi16(xmm2, 8); xmm5 = _mm_srli_epi16(xmm3, 8); xmm1 = _mm_packus_epi16(xmm4, xmm5); // split into U/V xmm4 = _mm_srli_epi16(xmm0, 8); xmm5 = _mm_srli_epi16(xmm1, 8); xmm0 = _mm_and_si128(xmm0, xmm7); xmm1 = _mm_and_si128(xmm1, xmm7); xmm0 = _mm_packus_epi16(xmm0, xmm1); xmm4 = _mm_packus_epi16(xmm4, xmm5); PIXCONV_PUT_STREAM(dstU + (i >> 2), xmm0); PIXCONV_PUT_STREAM(dstV + (i >> 2), xmm4); } // process left-over pixel for (; i < (byteWidth - 3); i += 4) { const uint8_t *pixel = (const uint8_t *)(srcLine + i); uint8_t *out_y = (uint8_t *)(dstY + (i >> 1)); uint8_t *out_u = (uint8_t *)(dstU + (i >> 2)); uint8_t *out_v = (uint8_t *)(dstV + (i >> 2)); out_y[0] = pixel[0]; out_u[0] = pixel[1]; out_y[1] = pixel[2]; out_v[0] = pixel[3]; } } return S_OK; } ================================================ FILE: decoder/LAVVideo/pixconv/yuv420_yuy2.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" #define DITHER_STEPS 2 // This function converts 8x2 pixels from the source into 8x2 YUY2 pixels in the destination template __forceinline static int yuv420yuy2_convert_pixels(const uint8_t *&srcY, const uint8_t *&srcU, const uint8_t *&srcV, uint8_t *&dst, ptrdiff_t srcStrideY, ptrdiff_t srcStrideUV, ptrdiff_t dstStride, ptrdiff_t line, const uint16_t *&dithers, ptrdiff_t pos) { __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_setzero_si128(); // Shift > 0 is for 9/10 bit formats if (shift > 0) { // Load 4 U/V values from line 0/1 into registers PIXCONV_LOAD_4PIXEL16(xmm1, srcU); PIXCONV_LOAD_4PIXEL16(xmm3, srcU + srcStrideUV); PIXCONV_LOAD_4PIXEL16(xmm0, srcV); PIXCONV_LOAD_4PIXEL16(xmm2, srcV + srcStrideUV); // Interleave U and V xmm0 = _mm_unpacklo_epi16(xmm1, xmm0); /* 0V0U0V0U */ xmm2 = _mm_unpacklo_epi16(xmm3, xmm2); /* 0V0U0V0U */ } else if (inputFormat == LAVPixFmt_NV12) { // Load 4 16-bit macro pixels, which contain 4 UV samples PIXCONV_LOAD_4PIXEL16(xmm0, srcU); PIXCONV_LOAD_4PIXEL16(xmm2, srcU + srcStrideUV); // Expand to 16-bit xmm0 = _mm_unpacklo_epi8(xmm0, xmm7); /* 0V0U0V0U */ xmm2 = _mm_unpacklo_epi8(xmm2, xmm7); /* 0V0U0V0U */ } else { PIXCONV_LOAD_4PIXEL8(xmm1, srcU); PIXCONV_LOAD_4PIXEL8(xmm3, srcU + srcStrideUV); PIXCONV_LOAD_4PIXEL8(xmm0, srcV); PIXCONV_LOAD_4PIXEL8(xmm2, srcV + srcStrideUV); // Interleave U and V xmm0 = _mm_unpacklo_epi8(xmm1, xmm0); /* VUVU0000 */ xmm2 = _mm_unpacklo_epi8(xmm3, xmm2); /* VUVU0000 */ // Expand to 16-bit xmm0 = _mm_unpacklo_epi8(xmm0, xmm7); /* 0V0U0V0U */ xmm2 = _mm_unpacklo_epi8(xmm2, xmm7); /* 0V0U0V0U */ } // xmm0/xmm2 contain 4 interleaved U/V samples from two lines each in the 16bit parts, still in their native // bitdepth // Chroma upsampling if (shift > 0 || inputFormat == LAVPixFmt_NV12) { srcU += 8; srcV += 8; } else { srcU += 4; srcV += 4; } xmm1 = xmm0; xmm1 = _mm_add_epi16(xmm1, xmm0); /* 2x line 0 */ xmm1 = _mm_add_epi16(xmm1, xmm0); /* 3x line 0 */ xmm1 = _mm_add_epi16(xmm1, xmm2); /* 3x line 0 + line 1 (10bit) */ xmm3 = xmm2; xmm3 = _mm_add_epi16(xmm3, xmm2); /* 2x line 1 */ xmm3 = _mm_add_epi16(xmm3, xmm2); /* 3x line 1 */ xmm3 = _mm_add_epi16(xmm3, xmm0); /* 3x line 1 + line 0 (10bit) */ // After this step, xmm1 and xmm3 contain 8 16-bit values, V and U interleaved. For 4:2:0, filling input+2 bits (10, // 11, 12). Load Y if (shift > 0) { // Load 8 Y values from line 0/1 into registers PIXCONV_LOAD_PIXEL8_ALIGNED(xmm0, srcY); PIXCONV_LOAD_PIXEL8_ALIGNED(xmm5, srcY + srcStrideY); srcY += 16; } else { PIXCONV_LOAD_4PIXEL16(xmm0, srcY); PIXCONV_LOAD_4PIXEL16(xmm5, srcY + srcStrideY); srcY += 8; xmm0 = _mm_unpacklo_epi8(xmm0, xmm7); /* YYYYYYYY (16-bit fields)*/ xmm5 = _mm_unpacklo_epi8(xmm5, xmm7); /* YYYYYYYY (16-bit fields) */ } // Dither everything to 8-bit // Dithering if (dithertype == LAVDither_Random) { /* Load random dithering coeffs from the dithers buffer */ int offset = (pos % (DITHER_STEPS * 8 * 2)) * 2; xmm6 = _mm_load_si128((const __m128i *)(dithers + 0 + offset)); xmm7 = _mm_load_si128((const __m128i *)(dithers + 8 + offset)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm6, line + 0, shift + 2, odithers); PIXCONV_LOAD_DITHER_COEFFS(xmm7, line + 1, shift + 2, odithers2); } // Dither UV xmm1 = _mm_adds_epu16(xmm1, xmm6); xmm3 = _mm_adds_epu16(xmm3, xmm7); xmm1 = _mm_srai_epi16(xmm1, shift + 2); xmm3 = _mm_srai_epi16(xmm3, shift + 2); if (shift) { /* Y only needs to be dithered if it was > 8 bit */ xmm6 = _mm_srli_epi16(xmm6, 2); /* Shift dithering coeffs to proper strength */ xmm7 = _mm_srli_epi16(xmm6, 2); xmm0 = _mm_adds_epu16(xmm0, xmm6); /* Apply dithering coeffs */ xmm0 = _mm_srai_epi16(xmm0, shift); /* Shift to 8 bit */ xmm5 = _mm_adds_epu16(xmm5, xmm7); /* Apply dithering coeffs */ xmm5 = _mm_srai_epi16(xmm5, shift); /* Shift to 8 bit */ } // Pack into 8-bit containers xmm0 = _mm_packus_epi16(xmm0, xmm5); xmm1 = _mm_packus_epi16(xmm1, xmm3); // Interleave U/V with Y if (uyvy) { xmm3 = xmm1; xmm3 = _mm_unpacklo_epi8(xmm3, xmm0); xmm4 = _mm_unpackhi_epi8(xmm1, xmm0); } else { xmm3 = xmm0; xmm3 = _mm_unpacklo_epi8(xmm3, xmm1); xmm4 = _mm_unpackhi_epi8(xmm0, xmm1); } // Write back into the target memory _mm_stream_si128((__m128i *)(dst), xmm3); _mm_stream_si128((__m128i *)(dst + dstStride), xmm4); dst += 16; return 0; } template static int __stdcall yuv420yuy2_process_lines(const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV, uint8_t *dst, int width, int height, ptrdiff_t srcStrideY, ptrdiff_t srcStrideUV, ptrdiff_t dstStride, const uint16_t *dithers) { const uint8_t *y = srcY; const uint8_t *u = srcU; const uint8_t *v = srcV; uint8_t *yuy2 = dst; // Processing starts at line 1, and ends at height - 1. The first and last line have special handling ptrdiff_t line = 1; const ptrdiff_t lastLine = height - 1; const uint16_t *lineDither = dithers; _mm_sfence(); // Process first line // This needs special handling because of the chroma offset of YUV420 for (ptrdiff_t i = 0; i < width; i += 8) { yuv420yuy2_convert_pixels(y, u, v, yuy2, 0, 0, 0, 0, lineDither, i); } for (; line < lastLine; line += 2) { if (dithertype == LAVDither_Random) lineDither = dithers + (line * 16 * DITHER_STEPS); y = srcY + line * srcStrideY; u = srcU + (line >> 1) * srcStrideUV; v = srcV + (line >> 1) * srcStrideUV; yuy2 = dst + line * dstStride; for (int i = 0; i < width; i += 8) { yuv420yuy2_convert_pixels(y, u, v, yuy2, srcStrideY, srcStrideUV, dstStride, line, lineDither, i); } } // Process last line // This needs special handling because of the chroma offset of YUV420 if (dithertype == LAVDither_Random) lineDither = dithers + ((height - 2) * 16 * DITHER_STEPS); y = srcY + (height - 1) * srcStrideY; u = srcU + ((height >> 1) - 1) * srcStrideUV; v = srcV + ((height >> 1) - 1) * srcStrideUV; yuy2 = dst + (height - 1) * dstStride; for (ptrdiff_t i = 0; i < width; i += 8) { yuv420yuy2_convert_pixels(y, u, v, yuy2, 0, 0, 0, line, lineDither, i); } return 0; } template static int __stdcall yuv420yuy2_dispatch(LAVPixelFormat inputFormat, int bpp, const uint8_t *srcY, const uint8_t *srcU, const uint8_t *srcV, uint8_t *dst, int width, int height, ptrdiff_t srcStrideY, ptrdiff_t srcStrideUV, ptrdiff_t dstStride, const uint16_t *dithers) { // Wrap the input format into template args switch (inputFormat) { case LAVPixFmt_YUV420: return yuv420yuy2_process_lines( srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers); case LAVPixFmt_NV12: return yuv420yuy2_process_lines( srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers); case LAVPixFmt_YUV420bX: if (bpp == 9) return yuv420yuy2_process_lines( srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers); else if (bpp == 10) return yuv420yuy2_process_lines( srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers); /*else if (bpp == 11) return yuv420yuy2_process_lines(srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers);*/ else if (bpp == 12) return yuv420yuy2_process_lines( srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers); /*else if (bpp == 13) return yuv420yuy2_process_lines(srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers);*/ else if (bpp == 14) return yuv420yuy2_process_lines( srcY, srcU, srcV, dst, width, height, srcStrideY, srcStrideUV, dstStride, dithers); else ASSERT(0); break; default: ASSERT(0); } return 0; } template DECLARE_CONV_FUNC_IMPL(convert_yuv420_yuy2) { LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = (ditherMode == LAVDither_Random) ? GetRandomDitherCoeffs(height, DITHER_STEPS * 2, bpp - 8 + 2, 0) : nullptr; if (ditherMode == LAVDither_Random && dithers != nullptr) { yuv420yuy2_dispatch(inputFormat, bpp, src[0], src[1], src[2], dst[0], width, height, srcStride[0], srcStride[1], dstStride[0], dithers); } else { yuv420yuy2_dispatch(inputFormat, bpp, src[0], src[1], src[2], dst[0], width, height, srcStride[0], srcStride[1], dstStride[0], nullptr); } return S_OK; } // Force creation of these two variants template HRESULT CLAVPixFmtConverter::convert_yuv420_yuy2<0> CONV_FUNC_PARAMS; template HRESULT CLAVPixFmtConverter::convert_yuv420_yuy2<1> CONV_FUNC_PARAMS; ================================================ FILE: decoder/LAVVideo/pixconv/yuv444_ayuv.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include "pixconv_internal.h" #include "pixconv_sse2_templates.h" #define PIXCONV_INTERLEAVE_AYUV(regY, regU, regV, regA, regOut1, regOut2) \ regY = _mm_unpacklo_epi8(regY, regA); /* YAYAYAYA */ \ regV = _mm_unpacklo_epi8(regV, regU); /* VUVUVUVU */ \ regOut1 = _mm_unpacklo_epi16(regV, regY); /* VUYAVUYA */ \ regOut2 = _mm_unpackhi_epi16(regV, regY); /* VUYAVUYA */ #define YUV444_PACK_AYUV(dst) *idst++ = v[i] | (u[i] << 8) | (y[i] << 16) | (0xff << 24); DECLARE_CONV_FUNC_IMPL(convert_yuv444_ayuv) { const uint8_t *y = (const uint8_t *)src[0]; const uint8_t *u = (const uint8_t *)src[1]; const uint8_t *v = (const uint8_t *)src[2]; const ptrdiff_t inStride = srcStride[0]; const ptrdiff_t outStride = dstStride[0]; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6; xmm6 = _mm_set1_epi32(-1); _mm_sfence(); for (line = 0; line < height; ++line) { __m128i *dst128 = (__m128i *)(dst[0] + line * outStride); for (i = 0; i < width; i += 16) { // Load pixels into registers PIXCONV_LOAD_PIXEL8_ALIGNED(xmm0, (y + i)); /* YYYYYYYY */ PIXCONV_LOAD_PIXEL8_ALIGNED(xmm1, (u + i)); /* UUUUUUUU */ PIXCONV_LOAD_PIXEL8_ALIGNED(xmm2, (v + i)); /* VVVVVVVV */ // Interlave into AYUV xmm4 = xmm0; xmm0 = _mm_unpacklo_epi8(xmm0, xmm6); /* YAYAYAYA */ xmm4 = _mm_unpackhi_epi8(xmm4, xmm6); /* YAYAYAYA */ xmm5 = xmm2; xmm2 = _mm_unpacklo_epi8(xmm2, xmm1); /* VUVUVUVU */ xmm5 = _mm_unpackhi_epi8(xmm5, xmm1); /* VUVUVUVU */ xmm1 = _mm_unpacklo_epi16(xmm2, xmm0); /* VUYAVUYA */ xmm2 = _mm_unpackhi_epi16(xmm2, xmm0); /* VUYAVUYA */ xmm0 = _mm_unpacklo_epi16(xmm5, xmm4); /* VUYAVUYA */ xmm3 = _mm_unpackhi_epi16(xmm5, xmm4); /* VUYAVUYA */ // Write data back _mm_stream_si128(dst128++, xmm1); _mm_stream_si128(dst128++, xmm2); _mm_stream_si128(dst128++, xmm0); _mm_stream_si128(dst128++, xmm3); } y += inStride; u += inStride; v += inStride; } return S_OK; } DECLARE_CONV_FUNC_IMPL(convert_yuv444_ayuv_dither_le) { const uint16_t *y = (const uint16_t *)src[0]; const uint16_t *u = (const uint16_t *)src[1]; const uint16_t *v = (const uint16_t *)src[2]; const ptrdiff_t inStride = srcStride[0] >> 1; const ptrdiff_t outStride = dstStride[0]; LAVDitherMode ditherMode = m_pSettings->GetDitherMode(); const uint16_t *dithers = GetRandomDitherCoeffs(height, 3, 8, 0); if (dithers == nullptr) ditherMode = LAVDither_Ordered; ptrdiff_t line, i; __m128i xmm0, xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7; xmm7 = _mm_set1_epi16(-256); /* 0xFF00 - 0A0A0A0A */ _mm_sfence(); for (line = 0; line < height; ++line) { // Load dithering coefficients for this line if (ditherMode == LAVDither_Random) { xmm4 = _mm_load_si128((const __m128i *)(dithers + (line * 24) + 0)); xmm5 = _mm_load_si128((const __m128i *)(dithers + (line * 24) + 8)); xmm6 = _mm_load_si128((const __m128i *)(dithers + (line * 24) + 16)); } else { PIXCONV_LOAD_DITHER_COEFFS(xmm6, line, 8, dithers); xmm4 = xmm5 = xmm6; } __m128i *dst128 = (__m128i *)(dst[0] + line * outStride); for (i = 0; i < width; i += 8) { // Load pixels into registers, and apply dithering PIXCONV_LOAD_PIXEL16_DITHER(xmm0, xmm4, (y + i), bpp); /* Y0Y0Y0Y0 */ PIXCONV_LOAD_PIXEL16_DITHER_HIGH(xmm1, xmm5, (u + i), bpp); /* U0U0U0U0 */ PIXCONV_LOAD_PIXEL16_DITHER(xmm2, xmm6, (v + i), bpp); /* V0V0V0V0 */ // Interlave into AYUV xmm0 = _mm_or_si128(xmm0, xmm7); /* YAYAYAYA */ xmm1 = _mm_and_si128(xmm1, xmm7); /* clear out clobbered low-bytes */ xmm2 = _mm_or_si128(xmm2, xmm1); /* VUVUVUVU */ xmm3 = xmm2; xmm2 = _mm_unpacklo_epi16(xmm2, xmm0); /* VUYAVUYA */ xmm3 = _mm_unpackhi_epi16(xmm3, xmm0); /* VUYAVUYA */ // Write data back _mm_stream_si128(dst128++, xmm2); _mm_stream_si128(dst128++, xmm3); } y += inStride; u += inStride; v += inStride; } return S_OK; } ================================================ FILE: decoder/LAVVideo/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by LAVVideo.rc // #define IDD_PROPPAGE_VIDEO_SETTINGS 9 #define IDD_PROPPAGE_FORMATS 10 #define IDS_SETTINGS 101 #define IDS_FORMATS 102 #define IDI_ICON1 103 #define IDS_FIELDORDER_AUTO 104 #define IDS_FIELDORDER_TOP 105 #define IDS_FIELDORDER_BOTTOM 106 #define IDS_DEINTMODE_AUTO 107 #define IDS_DEINTMODE_AGGRESSIVE 108 #define IDS_DEINTMODE_FORCE 109 #define IDS_DEINTMODE_DISABLE 110 #define IDC_CODECS 1001 #define IDC_LAVVIDEO_FOOTER 1002 #define IDC_VIDEO_SETTINGS 1003 #define IDC_STREAMAR 1004 #define IDC_THREADS 1005 #define IDC_LBL_MULTITHREAD 1006 #define IDC_OUTPUT_FORMATS 1008 #define IDC_OUT_YV12 1009 #define IDC_OUT_NV12 1010 #define IDC_OUT_P010 1011 #define IDC_OUT_P016 1012 #define IDC_OUT_YUY2 1013 #define IDC_OUT_P210 1014 #define IDC_OUT_P216 1015 #define IDC_OUT_AYUV 1016 #define IDC_OUT_Y410 1017 #define IDC_OUT_Y416 1018 #define IDC_OUT_RGB32 1019 #define IDC_OUT_RGB24 1020 #define IDC_OUT_420 1021 #define IDC_OUT_422 1022 #define IDC_OUT_444 1023 #define IDC_OUT_RGB 1024 #define IDC_OUT_8BIT 1025 #define IDC_OUT_10BIT 1026 #define IDC_OUT_16BIT 1027 #define IDC_OUT_UYVY 1028 #define IDC_OUT_RGB48 1029 #define IDC_LBL_RGBOUT 1030 #define IDC_RGBOUT_AUTO 1031 #define IDC_RGBOUT_TV 1032 #define IDC_RGBOUT_PC 1033 #define IDC_HWACCEL_SETTINGS 1034 #define IDC_LBL_HWACCEL 1035 #define IDC_HWACCEL 1036 #define IDC_LBL_HWCODECS 1037 #define IDC_HWACCEL_H264 1038 #define IDC_HWACCEL_VC1 1039 #define IDC_HWACCEL_MPEG2 1040 #define IDC_HW_DEINT 1041 #define IDC_LBL_HWDEINT_MODE 1046 #define IDC_HWDEINT_OUT_VIDEO 1047 #define IDC_HWDEINT_OUT_FILM 1048 #define IDC_LBL_DEINT_FIELDORDER 1049 #define IDC_DEINT_FIELDORDER 1050 #define IDC_LBL_DEINT_MODE 1051 #define IDC_HWACCEL_AVAIL 1053 #define IDC_DEINT_SETTINGS 1054 #define IDC_DEINT_MODE 1055 #define IDC_SWDEINT_MODE 1056 #define IDC_SWDEINT 1057 #define IDC_LBL_SWDEINT_MODE 1058 #define IDC_SWDEINT_OUT_FILM 1059 #define IDC_SWDEINT_OUT_VIDEO 1060 #define IDC_OUT_V210 1062 #define IDC_OUT_V410 1063 #define IDC_HWACCEL_MPEG4 1064 #define IDC_LBL_FORMATS 1065 #define IDC_DITHER_ORDERED 1066 #define IDC_DITHER_RANDOM 1067 #define IDC_CODECS_MSWMVDMO 1068 #define IDC_ACTIVE_DECODER 1069 #define IDC_OUT_YV24 1070 #define IDC_DVD_VIDEO 1071 #define IDC_GROUP_HWDEINT 1072 #define IDC_HWDEINT_ENABLE 1073 #define IDC_LBL_HWRESOLUTIONS 1074 #define IDC_HWRES_SD 1075 #define IDC_HWRES_HD 1076 #define IDC_HWRES_UHD 1077 #define IDC_TRAYICON 1079 #define IDC_HWACCEL_HEVC 1080 #define IDC_HWACCEL_VP9 1081 #define IDC_LBL_SWDEINT_ALGO 1082 #define IDC_LBL_HWACCEL_DEVICE 1083 #define IDC_HWACCEL_DEVICE 1084 #define IDC_HWACCEL_DEVICE_SELECT 1085 #define IDC_LBL_HWACCEL_DEVICE_SELECT 1086 #define IDC_LBL_HWACCEL_DEVICE_HINT 1087 #define IDC_HWACCEL_CUVID_DXVA 1088 #define IDC_HWACCEL_H264MVC 1089 #define IDC_HWACCEL_AV1 1090 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 111 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1091 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: decoder/LAVVideo/stdafx.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Pre-compiled header #include "stdafx.h" ================================================ FILE: decoder/LAVVideo/stdafx.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // pre-compiled header #pragma once // Support for Version 6.0 styles #pragma comment( \ linker, \ "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #include "common_defines.h" // include headers #include #include #include #include #include #include #include #pragma warning(push) #pragma warning(disable : 4244) extern "C" { #define __STDC_CONSTANT_MACROS #include "libavcodec/avcodec.h" #include "libswscale/swscale.h" #include "libavfilter/avfilter.h" #include "libavfilter/buffersink.h" #include "libavfilter/buffersrc.h" #include "libavutil/cpu.h" #include "libavutil/intreadwrite.h" #include "libavutil/pixdesc.h" #include "libavutil/opt.h" } #pragma warning(pop) #include "streams.h" #include "DShowUtil.h" #include "growarray.h" #include "SubRenderIntf.h" #define REF_SECOND_MULT 10000000LL ================================================ FILE: decoder/LAVVideo/subtitles/LAVSubtitleConsumer.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVSubtitleConsumer.h" #include "LAVVideo.h" #include "Media.h" #include "version.h" #define OFFSET(x) offsetof(LAVSubtitleConsumerContext, x) // clang-format off static const SubRenderOption options[] = { { "name", OFFSET(name), SROPT_TYPE_STRING, SROPT_FLAG_READONLY }, { "version", OFFSET(version), SROPT_TYPE_STRING, SROPT_FLAG_READONLY }, { "originalVideoSize", OFFSET(originalVideoSize), SROPT_TYPE_SIZE, SROPT_FLAG_READONLY }, { 0 } }; // clang-format on #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16) CLAVSubtitleConsumer::CLAVSubtitleConsumer(CLAVVideo *pLAVVideo) : CSubRenderOptionsImpl(::options, &context) , CUnknown(L"CLAVSubtitleConsumer", nullptr) , m_pLAVVideo(pLAVVideo) { ZeroMemory(&context, sizeof(context)); context.name = TEXT(LAV_VIDEO); context.version = TEXT(LAV_VERSION_STR); m_evFrame.Reset(); } CLAVSubtitleConsumer::~CLAVSubtitleConsumer(void) { if (m_pProvider) { m_pProvider->Disconnect(); } Disconnect(); } STDMETHODIMP CLAVSubtitleConsumer::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; return QI(ISubRenderConsumer) QI(ISubRenderConsumer2) __super::NonDelegatingQueryInterface(riid, ppv); } STDMETHODIMP CLAVSubtitleConsumer::Connect(ISubRenderProvider *subtitleRenderer) { SafeRelease(&m_pProvider); m_pProvider = subtitleRenderer; return S_OK; } STDMETHODIMP CLAVSubtitleConsumer::Disconnect(void) { SafeRelease(&m_pProvider); if (m_pSwsContext) { sws_freeContext(m_pSwsContext); m_pSwsContext = nullptr; } return S_OK; } STDMETHODIMP CLAVSubtitleConsumer::DeliverFrame(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context, ISubRenderFrame *subtitleFrame) { ASSERT(m_SubtitleFrame == nullptr); if (subtitleFrame) subtitleFrame->AddRef(); m_SubtitleFrame = subtitleFrame; m_evFrame.Set(); return S_OK; } STDMETHODIMP CLAVSubtitleConsumer::Clear(REFERENCE_TIME clearNewerThan) { m_pLAVVideo->RedrawStillImage(); return S_OK; } STDMETHODIMP CLAVSubtitleConsumer::RequestFrame(REFERENCE_TIME rtStart, REFERENCE_TIME rtStop) { CheckPointer(m_pProvider, E_FAIL); return m_pProvider->RequestFrame(rtStart, rtStop, nullptr); } STDMETHODIMP CLAVSubtitleConsumer::ProcessFrame(LAVFrame *pFrame) { CheckPointer(m_pProvider, E_FAIL); HRESULT hr = S_OK; LPDIRECT3DSURFACE9 pSurface = nullptr; // Wait for the requested frame m_evFrame.Wait(); if (m_SubtitleFrame != nullptr) { int count = 0; if (FAILED(m_SubtitleFrame->GetBitmapCount(&count))) { count = 0; } if (count == 0) { SafeRelease(&m_SubtitleFrame); return S_FALSE; } BYTE *data[4] = {0}; ptrdiff_t stride[4] = {0}; LAVPixelFormat format = pFrame->format; int bpp = pFrame->bpp; if (pFrame->format == LAVPixFmt_DXVA2) { SafeRelease(&m_SubtitleFrame); return E_FAIL; } else if (pFrame->format == LAVPixFmt_D3D11) { SafeRelease(&m_SubtitleFrame); return E_FAIL; } else { if (!(pFrame->flags & LAV_FRAME_FLAG_BUFFER_MODIFY)) { CopyLAVFrameInPlace(pFrame); } memcpy(&data, &pFrame->data, sizeof(pFrame->data)); memcpy(&stride, &pFrame->stride, sizeof(pFrame->stride)); } RECT videoRect; ::SetRect(&videoRect, 0, 0, pFrame->width, pFrame->height); RECT subRect; m_SubtitleFrame->GetOutputRect(&subRect); ULONGLONG id; POINT position; SIZE size; const uint8_t *rgbData; int pitch; for (int i = 0; i < count; i++) { if (FAILED(m_SubtitleFrame->GetBitmap(i, &id, &position, &size, (LPCVOID *)&rgbData, &pitch))) { DbgLog((LOG_TRACE, 10, L"GetBitmap() failed on index %d", i)); break; } ProcessSubtitleBitmap(format, bpp, videoRect, data, stride, subRect, position, size, rgbData, pitch); } if (pSurface) pSurface->UnlockRect(); SafeRelease(&m_SubtitleFrame); return S_OK; } return S_FALSE; } static struct { LAVPixelFormat pixfmt; AVPixelFormat ffpixfmt; } lav_ff_subtitle_pixfmt_map[] = { {LAVPixFmt_YUV420, AV_PIX_FMT_YUVA420P}, {LAVPixFmt_YUV420bX, AV_PIX_FMT_YUVA420P}, {LAVPixFmt_YUV422, AV_PIX_FMT_YUVA422P}, {LAVPixFmt_YUV422bX, AV_PIX_FMT_YUVA422P}, {LAVPixFmt_YUV444, AV_PIX_FMT_YUVA444P}, {LAVPixFmt_YUV444bX, AV_PIX_FMT_YUVA444P}, {LAVPixFmt_NV12, AV_PIX_FMT_YUVA420P}, {LAVPixFmt_P016, AV_PIX_FMT_YUVA420P}, {LAVPixFmt_YUY2, AV_PIX_FMT_YUVA422P}, {LAVPixFmt_RGB24, AV_PIX_FMT_BGRA}, {LAVPixFmt_RGB32, AV_PIX_FMT_BGRA}, {LAVPixFmt_ARGB32, AV_PIX_FMT_BGRA}, }; static LAVPixFmtDesc ff_sub_pixfmt_desc[] = { {1, 4, {1, 2, 2, 1}, {1, 2, 2, 1}}, ///< PIX_FMT_YUVA420P {1, 4, {1, 2, 2, 1}, {1, 1, 1, 1}}, ///< PIX_FMT_YUVA422P {1, 4, {1, 1, 1, 1}, {1, 1, 1, 1}}, ///< PIX_FMT_YUVA444P {4, 1, {1}, {1}}, ///< PIX_FMT_BGRA }; static LAVPixFmtDesc getFFSubPixelFormatDesc(AVPixelFormat pixFmt) { int index = 0; switch (pixFmt) { case AV_PIX_FMT_YUVA420P: index = 0; break; case AV_PIX_FMT_YUVA422P: index = 1; break; case AV_PIX_FMT_YUVA444P: index = 2; break; case AV_PIX_FMT_BGRA: index = 3; break; default: ASSERT(0); } return ff_sub_pixfmt_desc[index]; } static AVPixelFormat getFFPixFmtForSubtitle(LAVPixelFormat pixFmt) { AVPixelFormat fmt = AV_PIX_FMT_NONE; for (int i = 0; i < countof(lav_ff_subtitle_pixfmt_map); i++) { if (lav_ff_subtitle_pixfmt_map[i].pixfmt == pixFmt) { return lav_ff_subtitle_pixfmt_map[i].ffpixfmt; } } ASSERT(0); return AV_PIX_FMT_NONE; } STDMETHODIMP CLAVSubtitleConsumer::SelectBlendFunction() { switch (m_PixFmt) { case LAVPixFmt_RGB32: case LAVPixFmt_RGB24: blend = &CLAVSubtitleConsumer::blend_rgb_c; break; case LAVPixFmt_NV12: blend = &CLAVSubtitleConsumer::blend_yuv_c; break; case LAVPixFmt_P016: blend = &CLAVSubtitleConsumer::blend_yuv_c; break; case LAVPixFmt_YUV420: case LAVPixFmt_YUV422: case LAVPixFmt_YUV444: blend = &CLAVSubtitleConsumer::blend_yuv_c; break; case LAVPixFmt_YUV420bX: case LAVPixFmt_YUV422bX: case LAVPixFmt_YUV444bX: blend = &CLAVSubtitleConsumer::blend_yuv_c; break; default: DbgLog((LOG_ERROR, 10, L"ProcessSubtitleBitmap(): No Blend function available")); blend = nullptr; } return S_OK; } STDMETHODIMP CLAVSubtitleConsumer::ProcessSubtitleBitmap(LAVPixelFormat pixFmt, int bpp, RECT videoRect, BYTE *videoData[4], ptrdiff_t videoStride[4], RECT subRect, POINT subPosition, SIZE subSize, const uint8_t *rgbData, ptrdiff_t pitch) { if (subRect.left != 0 || subRect.top != 0) { DbgLog((LOG_ERROR, 10, L"ProcessSubtitleBitmap(): Left/Top in SubRect non-zero")); } BOOL bNeedScaling = FALSE; // We need scaling if the width is not the same, or the subtitle rect is higher then the video rect if (subRect.right != videoRect.right || subRect.bottom > videoRect.bottom) { bNeedScaling = TRUE; } if (pixFmt != LAVPixFmt_RGB32 && pixFmt != LAVPixFmt_RGB24) { bNeedScaling = TRUE; } if (m_PixFmt != pixFmt) { m_PixFmt = pixFmt; SelectBlendFunction(); } // P010/P016 is always handled like its 16 bpp to compensate for having the data in the high bits if (pixFmt == LAVPixFmt_P016) bpp = 16; BYTE *subData[4] = {nullptr, nullptr, nullptr, nullptr}; ptrdiff_t subStride[4] = {0, 0, 0, 0}; // If we need scaling (either scaling or pixel conversion), do it here before starting the blend process if (bNeedScaling) { uint8_t *tmpBuf = nullptr; const AVPixelFormat avPixFmt = getFFPixFmtForSubtitle(pixFmt); // Calculate scaled size // We must ensure that the scaled subs still fit into the video // HACK: Scale to video size. In the future, we should take AR and the likes into account RECT newRect = videoRect; /* float subAR = (float)subRect.right / (float)subRect.bottom; if (newRect.right != videoRect.right) { newRect.right = videoRect.right; newRect.bottom = (LONG)(newRect.right / subAR); } if (newRect.bottom > videoRect.bottom) { newRect.bottom = videoRect.bottom; newRect.right = (LONG)(newRect.bottom * subAR); }*/ SIZE newSize; newSize.cx = (LONG)av_rescale(subSize.cx, newRect.right, subRect.right); newSize.cy = (LONG)av_rescale(subSize.cy, newRect.bottom, subRect.bottom); // And scaled position subPosition.x = (LONG)av_rescale(subPosition.x, newSize.cx, subSize.cx); subPosition.y = (LONG)av_rescale(subPosition.y, newSize.cy, subSize.cy); m_pSwsContext = sws_getCachedContext(m_pSwsContext, subSize.cx, subSize.cy, AV_PIX_FMT_BGRA, newSize.cx, newSize.cy, avPixFmt, SWS_BILINEAR | SWS_FULL_CHR_H_INP, nullptr, nullptr, nullptr); const uint8_t *src[4] = {(const uint8_t *)rgbData, nullptr, nullptr, nullptr}; const ptrdiff_t srcStride[4] = {pitch, 0, 0, 0}; const LAVPixFmtDesc desc = getFFSubPixelFormatDesc(avPixFmt); const ptrdiff_t stride = FFALIGN(newSize.cx, 64) * desc.codedbytes; for (int plane = 0; plane < desc.planes; plane++) { subStride[plane] = stride / desc.planeWidth[plane]; const size_t size = subStride[plane] * FFALIGN(newSize.cy, 2) / desc.planeHeight[plane]; subData[plane] = (BYTE *)av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE); if (subData[plane] == nullptr) goto fail; } // Un-pre-multiply alpha for YUV formats // TODO: Can we SIMD this? See ARGBUnattenuateRow_C/SSE2 in libyuv if (avPixFmt != AV_PIX_FMT_BGRA) { tmpBuf = (uint8_t *)av_malloc(pitch * subSize.cy); if (tmpBuf == nullptr) goto fail; memcpy(tmpBuf, rgbData, pitch * subSize.cy); for (int line = 0; line < subSize.cy; line++) { uint8_t *p = tmpBuf + line * pitch; for (int col = 0; col < subSize.cx; col++) { if (p[3] != 0 && p[3] != 255) { p[0] = av_clip_uint8(p[0] * 255 / p[3]); p[1] = av_clip_uint8(p[1] * 255 / p[3]); p[2] = av_clip_uint8(p[2] * 255 / p[3]); } p += 4; } } src[0] = tmpBuf; } int ret = sws_scale2(m_pSwsContext, src, srcStride, 0, subSize.cy, subData, subStride); subSize = newSize; if (tmpBuf) av_free(tmpBuf); } else { subData[0] = (BYTE *)rgbData; subStride[0] = pitch; } ASSERT((subPosition.x + subSize.cx) <= videoRect.right); ASSERT((subPosition.y + subSize.cy) <= videoRect.bottom); if (blend) (this->*blend)(videoData, videoStride, videoRect, subData, subStride, subPosition, subSize, pixFmt, bpp); if (bNeedScaling) { for (int i = 0; i < 4; i++) { av_freep(&subData[i]); } } return S_OK; fail: for (int i = 0; i < 4; i++) { av_freep(&subData[i]); } return E_OUTOFMEMORY; } ================================================ FILE: decoder/LAVVideo/subtitles/LAVSubtitleConsumer.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "SubRenderOptionsImpl.h" #include "LAVSubtitleFrame.h" #include "../decoders/ILAVDecoder.h" #define BLEND_FUNC_PARAMS \ (BYTE * video[4], ptrdiff_t videoStride[4], RECT vidRect, BYTE * subData[4], ptrdiff_t subStride[4], \ POINT position, SIZE size, LAVPixelFormat pixFmt, int bpp) #define DECLARE_BLEND_FUNC(name) HRESULT name BLEND_FUNC_PARAMS #define DECLARE_BLEND_FUNC_IMPL(name) DECLARE_BLEND_FUNC(CLAVSubtitleConsumer::name) typedef struct LAVSubtitleConsumerContext { LPWSTR name; ///< name of the Consumer LPWSTR version; ///< Version of the Consumer SIZE originalVideoSize; ///< Size of the video } LAVSubtitleConsumerContext; class CLAVVideo; class CLAVSubtitleConsumer : public ISubRenderConsumer2 , public CSubRenderOptionsImpl , public CUnknown { public: CLAVSubtitleConsumer(CLAVVideo *pLAVVideo); virtual ~CLAVSubtitleConsumer(void); DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); DECLARE_ISUBRENDEROPTIONS; // ISubRenderConsumer2 STDMETHODIMP GetMerit(ULONG *merit) { CheckPointer(merit, E_POINTER); *merit = 0x00010000; return S_OK; } STDMETHODIMP Connect(ISubRenderProvider *subtitleRenderer); STDMETHODIMP Disconnect(void); STDMETHODIMP DeliverFrame(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context, ISubRenderFrame *subtitleFrame); STDMETHODIMP Clear(REFERENCE_TIME clearNewerThan = 0); // LAV Internal methods STDMETHODIMP RequestFrame(REFERENCE_TIME rtStart, REFERENCE_TIME rtStop); STDMETHODIMP ProcessFrame(LAVFrame *pFrame); STDMETHODIMP DisconnectProvider() { if (m_pProvider) m_pProvider->Disconnect(); SafeRelease(&m_pProvider); return S_OK; } BOOL HasProvider() const { return m_pProvider != nullptr; } void SetVideoSize(LONG w, LONG h) { context.originalVideoSize.cx = w; context.originalVideoSize.cy = h; } private: STDMETHODIMP ProcessSubtitleBitmap(LAVPixelFormat pixFmt, int bpp, RECT videoRect, BYTE *videoData[4], ptrdiff_t videoStride[4], RECT subRect, POINT subPosition, SIZE subSize, const uint8_t *rgbData, ptrdiff_t pitch); STDMETHODIMP SelectBlendFunction(); typedef HRESULT(CLAVSubtitleConsumer::*BlendFn) BLEND_FUNC_PARAMS; BlendFn blend = nullptr; DECLARE_BLEND_FUNC(blend_rgb_c); template DECLARE_BLEND_FUNC(blend_yuv_c); private: ISubRenderProvider *m_pProvider = nullptr; ISubRenderFrame *m_SubtitleFrame = nullptr; CAMEvent m_evFrame{FALSE}; SwsContext *m_pSwsContext = nullptr; LAVPixelFormat m_PixFmt = LAVPixFmt_None; LAVSubtitleConsumerContext context; CLAVVideo *m_pLAVVideo = nullptr; }; ================================================ FILE: decoder/LAVVideo/subtitles/LAVSubtitleFrame.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVSubtitleFrame.h" CLAVSubtitleFrame::CLAVSubtitleFrame(void) : CUnknown(L"CLAVSubtitleFrame", nullptr) { ZeroMemory(&m_outputRect, sizeof(m_outputRect)); ZeroMemory(&m_clipRect, sizeof(m_clipRect)); } CLAVSubtitleFrame::~CLAVSubtitleFrame(void) { for (int i = 0; i < m_NumBitmaps; i++) { m_Bitmaps[i]->Release(); } SAFE_CO_FREE(m_Bitmaps); } STDMETHODIMP CLAVSubtitleFrame::SetOutputRect(RECT outputRect) { m_outputRect = m_clipRect = outputRect; return S_OK; } STDMETHODIMP CLAVSubtitleFrame::SetClipRect(RECT clipRect) { m_clipRect = clipRect; return S_OK; } STDMETHODIMP CLAVSubtitleFrame::AddBitmap(CLAVSubRect *subRect) { // Allocate memory for the new block void *mem = CoTaskMemRealloc(m_Bitmaps, sizeof(*m_Bitmaps) * (m_NumBitmaps + 1)); if (!mem) { return E_OUTOFMEMORY; } m_Bitmaps = (CLAVSubRect **)mem; m_Bitmaps[m_NumBitmaps] = subRect; m_NumBitmaps++; // Hold reference on the subtitle rect subRect->AddRef(); return S_OK; } STDMETHODIMP CLAVSubtitleFrame::GetOutputRect(RECT *outputRect) { CheckPointer(outputRect, E_POINTER); *outputRect = m_outputRect; return S_OK; } STDMETHODIMP CLAVSubtitleFrame::GetClipRect(RECT *clipRect) { CheckPointer(clipRect, E_POINTER); *clipRect = m_clipRect; return S_OK; } STDMETHODIMP CLAVSubtitleFrame::GetBitmapCount(int *count) { CheckPointer(count, E_POINTER); *count = m_NumBitmaps; return S_OK; } STDMETHODIMP CLAVSubtitleFrame::GetBitmap(int index, ULONGLONG *id, POINT *position, SIZE *size, LPCVOID *pixels, int *pitch) { if (index < 0 || index >= m_NumBitmaps) return E_INVALIDARG; CheckPointer(id, E_POINTER); CheckPointer(position, E_POINTER); CheckPointer(size, E_POINTER); CheckPointer(pixels, E_POINTER); CheckPointer(pitch, E_POINTER); *id = m_Bitmaps[index]->id; *position = m_Bitmaps[index]->position; *size = m_Bitmaps[index]->size; *pixels = m_Bitmaps[index]->pixels; *pitch = m_Bitmaps[index]->pitch * 4; return S_OK; } ================================================ FILE: decoder/LAVVideo/subtitles/LAVSubtitleFrame.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once class CLAVSubRect : public IUnknown { public: CLAVSubRect() { memset(&position, 0, sizeof(position)); memset(&size, 0, sizeof(size)); } ~CLAVSubRect() { SAFE_CO_FREE(pixels); SAFE_CO_FREE(pixelsPal); } // IUnknown STDMETHODIMP QueryInterface(REFIID riid, void **ppvObject) { if (riid == IID_IUnknown) { AddRef(); *ppvObject = (IUnknown *)this; } else { return E_NOINTERFACE; } return S_OK; } STDMETHODIMP_(ULONG) AddRef() { ULONG lRef = InterlockedIncrement(&m_cRef); return max(ULONG(lRef), 1ul); } STDMETHODIMP_(ULONG) Release() { ULONG lRef = InterlockedDecrement(&m_cRef); if (lRef == 0) { m_cRef++; delete this; return 0; } return max(ULONG(lRef), 1ul); } // Reset the reference count to 0, can be used after a copy-constructor STDMETHODIMP ResetRefCount() { m_cRef = 0ul; return S_OK; } public: REFERENCE_TIME rtStart = AV_NOPTS_VALUE; ///< Start Time REFERENCE_TIME rtStop = AV_NOPTS_VALUE; ///< Stop time ULONGLONG id = 0; ///< Unique Identifier (same ID = same subtitle) POINT position; ///< Position (relative to outputRect) SIZE size; ///< Size LPVOID pixels = nullptr; ///< Pixel Data LPVOID pixelsPal = nullptr; ///< Pixel Data (in paletted form, required by dvd HLI) int pitch = 0; ///< Pitch of the subtitle lines bool forced = false; ///< Forced/Menu bool freePixels = false; ///< If true, pixel data is free'ed upon destroy private: ULONG m_cRef = 0; }; class CLAVSubtitleFrame : public ISubRenderFrame , public CUnknown { public: CLAVSubtitleFrame(void); virtual ~CLAVSubtitleFrame(void); DECLARE_IUNKNOWN; // ISubRenderFrame STDMETHODIMP GetOutputRect(RECT *outputRect); STDMETHODIMP GetClipRect(RECT *clipRect); STDMETHODIMP GetBitmapCount(int *count); STDMETHODIMP GetBitmap(int index, ULONGLONG *id, POINT *position, SIZE *size, LPCVOID *pixels, int *pitch); STDMETHODIMP SetOutputRect(RECT outputRect); STDMETHODIMP SetClipRect(RECT clipRect); STDMETHODIMP AddBitmap(CLAVSubRect *subRect); BOOL Empty() const { return m_NumBitmaps == 0; }; private: RECT m_outputRect; RECT m_clipRect; CLAVSubRect **m_Bitmaps = nullptr; int m_NumBitmaps = 0; }; ================================================ FILE: decoder/LAVVideo/subtitles/LAVSubtitleProvider.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVSubtitleProvider.h" #include "moreuuids.h" #include "libavutil/colorspace.h" #include "LAVVideo.h" #include "version.h" #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16) #define SUBTITLE_PTS_TIMEOUT (AV_NOPTS_VALUE + 1) #define OFFSET(x) offsetof(LAVSubtitleProviderContext, x) // clang-format off static const SubRenderOption options[] = { { "name", OFFSET(name), SROPT_TYPE_STRING, SROPT_FLAG_READONLY }, { "version", OFFSET(version), SROPT_TYPE_STRING, SROPT_FLAG_READONLY }, { "yuvMatrix", OFFSET(yuvMatrix), SROPT_TYPE_STRING, SROPT_FLAG_READONLY }, { "outputLevels", OFFSET(outputLevels), SROPT_TYPE_STRING, SROPT_FLAG_READONLY }, { "colorPrimaries", OFFSET(primaries), SROPT_TYPE_STRING, SROPT_FLAG_READONLY }, { "isBitmap", OFFSET(isBitmap), SROPT_TYPE_BOOL, SROPT_FLAG_READONLY }, { "isMovable", OFFSET(isMovable), SROPT_TYPE_BOOL, SROPT_FLAG_READONLY }, { "combineBitmaps", OFFSET(combineBitmaps), SROPT_TYPE_BOOL, 0 }, { 0 } }; // clang-format on #define COLOR_PRIM_NTSC _T("601_525") #define COLOR_PRIM_PAL _T("601_625") CLAVSubtitleProvider::CLAVSubtitleProvider(CLAVVideo *pLAVVideo, ISubRenderConsumer *pConsumer) : CSubRenderOptionsImpl(::options, &context) , CUnknown(L"CLAVSubtitleProvider", nullptr) , m_pLAVVideo(pLAVVideo) { m_ControlThread = new CLAVSubtitleProviderControlThread(); ASSERT(pConsumer); ZeroMemory(&context, sizeof(context)); context.name = TEXT(LAV_VIDEO); context.version = TEXT(LAV_VERSION_STR); context.yuvMatrix = _T("None"); context.outputLevels = _T("PC"); context.primaries = COLOR_PRIM_NTSC; context.isBitmap = true; context.isMovable = true; AddRef(); SetConsumer(pConsumer); } CLAVSubtitleProvider::~CLAVSubtitleProvider(void) { Flush(); CloseDecoder(); DisconnectConsumer(); SAFE_DELETE(m_ControlThread); } void CLAVSubtitleProvider::CloseDecoder() { CAutoLock lock(this); m_pAVCodec = nullptr; if (m_pAVCtx) { if (m_pAVCtx->extradata) av_freep(&m_pAVCtx->extradata); avcodec_free_context(&m_pAVCtx); } if (m_pParser) { av_parser_close(m_pParser); m_pParser = nullptr; } av_packet_free(&m_pSubtitlePacket); } STDMETHODIMP CLAVSubtitleProvider::SetConsumer(ISubRenderConsumer *pConsumer) { CAutoLock lock(this); if (m_pConsumer) DisconnectConsumer(); CheckPointer(pConsumer, E_FAIL); m_pConsumer = pConsumer; m_pConsumer->AddRef(); m_pConsumer->Connect(this); if (FAILED(m_pConsumer->QueryInterface(&m_pConsumer2))) m_pConsumer2 = nullptr; m_ControlThread->SetConsumer2(m_pConsumer2); return S_OK; } STDMETHODIMP CLAVSubtitleProvider::DisconnectConsumer(void) { CAutoLock lock(this); CheckPointer(m_pConsumer, S_FALSE); m_ControlThread->SetConsumer2(nullptr); m_pConsumer->Disconnect(); SafeRelease(&m_pConsumer); SafeRelease(&m_pConsumer2); return S_OK; } #define PTS2RT(pts) (10000i64 * pts / 90) STDMETHODIMP CLAVSubtitleProvider::RequestFrame(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context) { ASSERT(m_pConsumer); // Create a new frame CLAVSubtitleFrame *subtitleFrame = new CLAVSubtitleFrame(); subtitleFrame->AddRef(); if (m_pAVCtx->width == 720 && m_pAVCtx->height == 480) { SIZE videoSize; m_pConsumer->GetSize("originalVideoSize", &videoSize); if (videoSize.cx == 720) { m_pAVCtx->height = videoSize.cy; } } // update primaries based on the video dimensions if (m_pAVCtx->height == 480) this->context.primaries = COLOR_PRIM_NTSC; else if (m_pAVCtx->height == 576) this->context.primaries = COLOR_PRIM_PAL; RECT outputRect; ::SetRect(&outputRect, 0, 0, m_pAVCtx->width, m_pAVCtx->height); subtitleFrame->SetOutputRect(outputRect); REFERENCE_TIME mid = start + ((stop-start) >> 1); // Scope this so we limit the provider-lock to the part where its needed { CAutoLock lock(this); for (auto it = m_SubFrames.begin(); it != m_SubFrames.end(); it++) { CLAVSubRect *pRect = *it; if ((pRect->rtStart == AV_NOPTS_VALUE || pRect->rtStart <= mid) && (pRect->rtStop == AV_NOPTS_VALUE || pRect->rtStop > mid) && (m_bComposit || pRect->forced)) { if (m_pHLI && PTS2RT(m_pHLI->StartPTM) <= mid && PTS2RT(m_pHLI->EndPTM) >= mid) { pRect = ProcessDVDHLI(pRect); } subtitleFrame->AddBitmap(pRect); } } m_rtLastFrame = start; } if (subtitleFrame->Empty()) { SafeRelease(&subtitleFrame); } // Deliver Frame m_pConsumer->DeliverFrame(start, stop, context, subtitleFrame); SafeRelease(&subtitleFrame); TimeoutSubtitleRects(stop); return S_OK; } STDMETHODIMP CLAVSubtitleProvider::Disconnect(void) { SafeRelease(&m_pConsumer); return S_OK; } STDMETHODIMP CLAVSubtitleProvider::InitDecoder(const CMediaType *pmt, AVCodecID codecId) { CAutoLock lock(this); m_pAVCodec = avcodec_find_decoder(codecId); CheckPointer(m_pAVCodec, VFW_E_TYPE_NOT_ACCEPTED); m_pAVCtx = avcodec_alloc_context3(m_pAVCodec); CheckPointer(m_pAVCtx, E_POINTER); m_pParser = av_parser_init(codecId); size_t extralen = 0; getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), nullptr, &extralen); if (extralen > 0) { // Just copy extradata BYTE *extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), extra, nullptr); m_pAVCtx->extradata = extra; m_pAVCtx->extradata_size = (int)extralen; } if (pmt->formattype == FORMAT_SubtitleInfo) { // Not much info in here } else { // Try video info BITMAPINFOHEADER *bmi = nullptr; videoFormatTypeHandler(*pmt, &bmi, nullptr, nullptr, nullptr); m_pAVCtx->width = bmi->biWidth; m_pAVCtx->height = bmi->biHeight; } int ret = avcodec_open2(m_pAVCtx, m_pAVCodec, nullptr); if (ret < 0) { DbgLog((LOG_TRACE, 10, L"CLAVSubtitleProvider::InitDecoder(): avocdec_open2 failed with %d", ret)); CloseDecoder(); return VFW_E_TYPE_NOT_ACCEPTED; } return S_OK; } STDMETHODIMP CLAVSubtitleProvider::Flush() { CAutoLock lock(this); ClearSubtitleRects(); SAFE_DELETE(m_pHLI); m_rtLastFrame = AV_NOPTS_VALUE; context.isMovable = true; m_pLAVVideo->SetInDVDMenu(false); av_packet_free(&m_pSubtitlePacket); return S_OK; } void CLAVSubtitleProvider::ClearSubtitleRects() { CAutoLock lock(this); for (auto it = m_SubFrames.begin(); it != m_SubFrames.end(); it++) { (*it)->Release(); } m_SubFrames.clear(); } void CLAVSubtitleProvider::TimeoutSubtitleRects(REFERENCE_TIME rt) { CAutoLock lock(this); REFERENCE_TIME timestamp = rt - 10 * 10000000; // Timeout all subs 10 seconds in the past auto it = m_SubFrames.begin(); while (it != m_SubFrames.end()) { if ((*it)->rtStop != AV_NOPTS_VALUE && (*it)->rtStop < timestamp) { DbgLog((LOG_TRACE, 10, L"Timed out subtitle at %I64d", (*it)->rtStart)); (*it)->Release(); it = m_SubFrames.erase(it); } else { it++; } } } STDMETHODIMP CLAVSubtitleProvider::Decode(BYTE *buf, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn) { ASSERT(m_pAVCtx); if (m_pSubtitlePacket == nullptr) m_pSubtitlePacket = av_packet_alloc(); AVSubtitle sub; memset(&sub, 0, sizeof(sub)); if (!buflen || !buf) { return S_OK; } while (buflen > 0) { REFERENCE_TIME rtStart = rtStartIn, rtStop = rtStopIn; int used_bytes = 0; int got_sub = 0; if (m_pParser) { uint8_t *pOut = nullptr; int pOut_size = 0; used_bytes = av_parser_parse2(m_pParser, m_pAVCtx, &pOut, &pOut_size, buf, buflen, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (used_bytes == 0 && pOut_size == 0) { DbgLog((LOG_TRACE, 50, L"CLAVSubtitleProvider::Decode - could not process buffer")); break; } if (used_bytes > pOut_size) { if (rtStartIn != AV_NOPTS_VALUE) m_rtStartCache = rtStartIn; } else if (used_bytes == pOut_size) { m_rtStartCache = rtStartIn = AV_NOPTS_VALUE; } else if (pOut_size > used_bytes) { rtStart = m_rtStartCache; m_rtStartCache = rtStartIn; // The value was used once, don't use it for multiple frames, that ends up in weird timings rtStartIn = AV_NOPTS_VALUE; } if (pOut_size > 0) { m_pSubtitlePacket->data = pOut; m_pSubtitlePacket->size = pOut_size; m_pSubtitlePacket->pts = rtStart; m_pSubtitlePacket->duration = 0; int ret = avcodec_decode_subtitle2(m_pAVCtx, &sub, &got_sub, m_pSubtitlePacket); if (ret < 0) { DbgLog((LOG_TRACE, 50, L"CLAVSubtitleProvider::Decode - decoding failed despite successful parsing")); got_sub = 0; } } else { got_sub = 0; } } if (used_bytes < 0) { return S_OK; } if (!m_pParser && (!got_sub && used_bytes == 0)) { buflen = 0; } else { buf += used_bytes; buflen -= used_bytes; } if (got_sub) { ProcessSubtitleFrame(&sub, rtStart); } avsubtitle_free(&sub); } return S_OK; } void CLAVSubtitleProvider::ProcessSubtitleFrame(AVSubtitle *sub, REFERENCE_TIME rtStart) { DbgLog((LOG_TRACE, 10, L"Decoded Sub: rtStart: %I64d, start_display_time: %d, end_display_time: %d, num_rects: %u, num_dvd_palette: %d", rtStart, sub->start_display_time, sub->end_display_time, sub->num_rects, sub->num_dvd_palette)); if (sub->num_rects > 0) { if (m_pAVCtx->codec_id == AV_CODEC_ID_DVD_SUBTITLE) { CAutoLock lock(this); // DVD subs have the limitation that only one subtitle can be shown at a given time, // so we need to timeout unlimited subs when a new one appears, as well as limit the duration of timed subs // to prevent overlapping subtitles REFERENCE_TIME rtSubTimeout = (rtStart != AV_NOPTS_VALUE) ? rtStart - 1 : SUBTITLE_PTS_TIMEOUT; for (auto it = m_SubFrames.begin(); it != m_SubFrames.end(); it++) { if ((*it)->rtStop == AV_NOPTS_VALUE || rtStart == AV_NOPTS_VALUE || (*it)->rtStop > rtStart) { (*it)->rtStop = rtSubTimeout; } } // Override subtitle timestamps if we have a timeout, and are not in a menu if (rtStart == AV_NOPTS_VALUE && sub->end_display_time > 0 && !(sub->rects[0]->flags & AV_SUBTITLE_FLAG_FORCED)) { DbgLog((LOG_TRACE, 10, L" -> Overriding subtitle timestamp to %I64d", m_rtLastFrame)); rtStart = m_rtLastFrame; } } REFERENCE_TIME rtStop = AV_NOPTS_VALUE; if (rtStart != AV_NOPTS_VALUE) { if (sub->end_display_time > 0) { rtStop = rtStart + (sub->end_display_time * 10000i64); } rtStart += sub->start_display_time * 10000i64; } for (unsigned i = 0; i < sub->num_rects; i++) { if (sub->num_dvd_palette > 1 && rtStart != AV_NOPTS_VALUE) { REFERENCE_TIME rtStartRect = rtStart - (sub->start_display_time * 10000i64); REFERENCE_TIME rtStopRect = rtStart; for (unsigned k = 0; k < sub->num_dvd_palette; k++) { // Start is the stop of the previous part rtStartRect = rtStopRect; // Stop is either the start of the next part, or the final stop if (k < (sub->num_dvd_palette-1)) rtStopRect = rtStart + (sub->dvd_palette[k+1]->start_display_time * 10000i64); else rtStopRect = rtStop; // Update palette with new alpha values for (unsigned j = 0; j < 4; j++) sub->rects[i]->data[1][(j << 2) + 3] = sub->dvd_palette[k]->alpha[j] * 17; ProcessSubtitleRect(sub->rects[i], rtStartRect, rtStopRect); } } else { ProcessSubtitleRect(sub->rects[i], rtStart, rtStop); } } } } void CLAVSubtitleProvider::ProcessSubtitleRect(AVSubtitleRect *rect, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop) { DbgLog((LOG_TRACE, 10, L"Subtitle Rect, start: %I64d, stop: %I64d", rtStart, rtStop)); // Skip zero-length subs if (rtStart != AV_NOPTS_VALUE && rtStart == rtStop) return; int hpad = rect->x & 1; int vpad = rect->y & 1; int width = rect->w + hpad; if (width & 1) width++; int height = rect->h + vpad; if (height & 1) height++; int rgbStride = FFALIGN(width, 16); BYTE *rgbSub = (BYTE *)CoTaskMemAlloc(rgbStride * height * 4); if (!rgbSub) return; BYTE *rgbSubStart = rgbSub; const BYTE *palSub = rect->data[0]; const BYTE *palette = rect->data[1]; memset(rgbSub, 0, rgbStride * height * 4); rgbSub += (rgbStride * vpad + hpad) * 4; for (int y = 0; y < rect->h; y++) { for (int x = 0; x < rect->w; x++) { // Read paletted value int idx = palSub[x]; // Skip invalid values if (idx >= rect->nb_colors) continue; // Read RGB values from palette BYTE b = palette[(idx << 2) + 0]; BYTE g = palette[(idx << 2) + 1]; BYTE r = palette[(idx << 2) + 2]; BYTE a = palette[(idx << 2) + 3]; // Store as RGBA pixel, pre-multiplied rgbSub[(x << 2) + 0] = FAST_DIV255(b * a); rgbSub[(x << 2) + 1] = FAST_DIV255(g * a); rgbSub[(x << 2) + 2] = FAST_DIV255(r * a); rgbSub[(x << 2) + 3] = a; } palSub += rect->linesize[0]; rgbSub += rgbStride * 4; } // Store the rect POINT position = { rect->x - hpad, rect->y - vpad }; SIZE size = { width, height }; CLAVSubRect *lavRect = new CLAVSubRect(); if (!lavRect) return; lavRect->id = m_SubPicId++; lavRect->pitch = rgbStride; lavRect->pixels = rgbSubStart; lavRect->position = position; lavRect->size = size; lavRect->rtStart = rtStart; lavRect->rtStop = rtStop; lavRect->forced = rect->flags & AV_SUBTITLE_FLAG_FORCED; if (m_pAVCtx->codec_id == AV_CODEC_ID_DVD_SUBTITLE) { lavRect->pixelsPal = CoTaskMemAlloc(lavRect->pitch * lavRect->size.cy); if (!lavRect->pixelsPal) return; int paletteTransparent = 0; for (int i = 0; i < rect->nb_colors; i++) { if (palette[(i << 2) + 3] == 0) { paletteTransparent = i; break; } } memset(lavRect->pixelsPal, paletteTransparent, lavRect->pitch * lavRect->size.cy); BYTE *palPixels = (BYTE *)lavRect->pixelsPal; palSub = rect->data[0]; palPixels += lavRect->pitch * vpad + hpad; for (int y = 0; y < rect->h; y++) { memcpy(palPixels, palSub, rect->w); palPixels += lavRect->pitch; palSub += rect->linesize[0]; } } // Ensure the width/height in avctx are valid m_pAVCtx->width = FFMAX(m_pAVCtx->width, position.x + size.cx); m_pAVCtx->height = FFMAX(m_pAVCtx->height, position.y + size.cy); // HACK: Since we're only dealing with DVDs so far, do some trickery here if (m_pAVCtx->height > 480 && m_pAVCtx->height < 576) m_pAVCtx->height = 576; AddSubtitleRect(lavRect); } void CLAVSubtitleProvider::AddSubtitleRect(CLAVSubRect *rect) { CAutoLock lock(this); rect->AddRef(); m_SubFrames.push_back(rect); } typedef struct DVDSubContext { AVClass *avclass; uint32_t palette[16]; char *palette_str; char *ifo_str; int has_palette; uint8_t colormap[4]; uint8_t alpha[256]; uint8_t buf[0x10000]; int buf_size; int forced_subs_only; } DVDSubContext; #define MAX_NEG_CROP 1024 extern "C" __declspec(dllimport) uint8_t ff_crop_tab[256 + 2 * MAX_NEG_CROP]; STDMETHODIMP CLAVSubtitleProvider::SetDVDPalette(AM_PROPERTY_SPPAL *pPal) { DbgLog((LOG_TRACE, 10, L"CLAVSubtitleProvider(): Setting new DVD Palette")); CAutoLock lock(this); if (!m_pAVCtx || m_pAVCtx->codec_id != AV_CODEC_ID_DVD_SUBTITLE || !pPal) { return E_FAIL; } DVDSubContext *ctx = (DVDSubContext *)m_pAVCtx->priv_data; ctx->has_palette = 1; uint8_t r,g,b; int i, y, cb, cr; int r_add, g_add, b_add; uint8_t *cm = ff_crop_tab + MAX_NEG_CROP; for (i = 0; i < 16; i++) { y = pPal->sppal[i].Y; cb = pPal->sppal[i].V; cr = pPal->sppal[i].U; YUV_TO_RGB1_CCIR(cb, cr); YUV_TO_RGB2_CCIR(r, g, b, y); ctx->palette[i] = (0xFF << 24) | (r << 16) | (g << 8) | b; } return S_OK; } STDMETHODIMP CLAVSubtitleProvider::SetDVDHLI(struct _AM_PROPERTY_SPHLI *pHLI) { bool redraw = false; // Scoped lock so the lock is lifted when the redraw is issued // Otherwise we can deadlock in the decoder - this one holding the provider lock, the decoder holding the decoder lock... { CAutoLock lock(this); if (pHLI) { #define DHLI(var) (pHLI->var != m_pHLI->var) if (!m_pHLI || DHLI(StartX) || DHLI(StopX) || DHLI(StartY) || DHLI(StopY) || memcmp(&pHLI->ColCon, &m_pHLI->ColCon, sizeof(pHLI->ColCon)) != 0) { DbgLog((LOG_TRACE, 10, L"CLAVSubtitleProvider(): DVD HLI event. HLISS: %u, x: %u->%u, y: %u->%u, StartPTM: %u, EndPTM: %u", pHLI->HLISS, pHLI->StartX, pHLI->StopX, pHLI->StartY, pHLI->StopY, pHLI->StartPTM, pHLI->EndPTM)); SAFE_DELETE(m_pHLI); m_pHLI = new AM_PROPERTY_SPHLI(*pHLI); redraw = true; } context.isMovable = false; m_pLAVVideo->SetInDVDMenu(true); } else { SAFE_DELETE(m_pHLI); } } if (redraw) ControlCmd(CNTRL_FLUSH); return S_OK; } CLAVSubRect* CLAVSubtitleProvider::ProcessDVDHLI(CLAVSubRect *rect) { DVDSubContext *ctx = (DVDSubContext *)m_pAVCtx->priv_data; if (!m_pHLI || !rect->pixelsPal || !ctx->has_palette) return rect; LPVOID newPixels = CoTaskMemAlloc(rect->pitch * rect->size.cy * 4); if (!newPixels) return rect; // copy pixels before modification memcpy(newPixels, rect->pixels, rect->pitch * rect->size.cy * 4); uint8_t *originalPalPixels = (uint8_t *)rect->pixelsPal; // create new object rect = new CLAVSubRect(*rect); rect->ResetRefCount(); rect->pixels = newPixels; rect->pixelsPal = nullptr; // Need to assign a new Id since we're modifying it here.. rect->id = m_SubPicId++; uint8_t *palette = (uint8_t *)ctx->palette; for (int y = 0; y < rect->size.cy; y++) { if (y+rect->position.y < m_pHLI->StartY || y+rect->position.y > m_pHLI->StopY) continue; uint8_t *pixelsPal = originalPalPixels + rect->pitch * y; uint8_t *pixels = ((uint8_t *)rect->pixels) + rect->pitch * y * 4; for (int x = 0; x < rect->size.cx; x++) { if (x+rect->position.x < m_pHLI->StartX || x+rect->position.x > m_pHLI->StopX) continue; uint8_t idx = pixelsPal[x]; uint8_t alpha = 0; switch (idx) { case 0: idx = m_pHLI->ColCon.backcol; alpha = m_pHLI->ColCon.backcon; break; case 1: idx = m_pHLI->ColCon.patcol; alpha = m_pHLI->ColCon.patcon; break; case 2: idx = m_pHLI->ColCon.emph1col; alpha = m_pHLI->ColCon.emph1con; break; case 3: idx = m_pHLI->ColCon.emph2col; alpha = m_pHLI->ColCon.emph2con; break; } // Read RGB values from palette BYTE b = palette[(idx << 2) + 0]; BYTE g = palette[(idx << 2) + 1]; BYTE r = palette[(idx << 2) + 2]; BYTE a = alpha << 4; // Store as RGBA pixel, pre-multiplied pixels[(x << 2) + 0] = FAST_DIV255(b * a); pixels[(x << 2) + 1] = FAST_DIV255(g * a); pixels[(x << 2) + 2] = FAST_DIV255(r * a); pixels[(x << 2) + 3] = a; } } return rect; } STDMETHODIMP CLAVSubtitleProvider::SetDVDComposit(BOOL bComposit) { CAutoLock lock(this); m_bComposit = bComposit; return S_OK; } CLAVSubtitleProviderControlThread::CLAVSubtitleProviderControlThread() : CAMThread() { Create(); } CLAVSubtitleProviderControlThread::~CLAVSubtitleProviderControlThread() { CallWorker(CLAVSubtitleProvider::CNTRL_EXIT); Close(); } void CLAVSubtitleProviderControlThread::SetConsumer2(ISubRenderConsumer2 * pConsumer2) { CAutoLock lock(this); m_pConsumer2 = pConsumer2; } DWORD CLAVSubtitleProviderControlThread::ThreadProc() { SetThreadName(-1, "LAV Subtitle Control Thread"); DWORD cmd; while (1) { cmd = GetRequest(); switch (cmd) { case CLAVSubtitleProvider::CNTRL_EXIT: Reply(S_OK); return 0; case CLAVSubtitleProvider::CNTRL_FLUSH: Reply(S_OK); { CAutoLock lock(this); if (m_pConsumer2) m_pConsumer2->Clear(); } break; } } return 1; } ================================================ FILE: decoder/LAVVideo/subtitles/LAVSubtitleProvider.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "SubRenderOptionsImpl.h" #include "LAVSubtitleFrame.h" class CLAVVideo; typedef struct LAVSubtitleProviderContext { LPWSTR name; ///< name of the Provider LPWSTR version; ///< Version of the Provider LPWSTR yuvMatrix; ///< YUV Matrix LPWSTR outputLevels; ///< RGB output levels LPWSTR primaries; ///< Color Primaries bool combineBitmaps; ///< Control if the provider combines all bitmaps into one bool isBitmap; bool isMovable; } LAVSubtitleProviderContext; struct _AM_PROPERTY_SPPAL; struct _AM_PROPERTY_SPHLI; class CLAVSubtitleProviderControlThread : public CAMThread , protected CCritSec { public: CLAVSubtitleProviderControlThread(); ~CLAVSubtitleProviderControlThread(); void SetConsumer2(ISubRenderConsumer2 *pConsumer2); protected: DWORD ThreadProc(); private: ISubRenderConsumer2 *m_pConsumer2 = nullptr; }; class CLAVSubtitleProvider : public ISubRenderProvider , public CSubRenderOptionsImpl , public CUnknown , private CCritSec { public: CLAVSubtitleProvider(CLAVVideo *pLAVVideo, ISubRenderConsumer *pConsumer); ~CLAVSubtitleProvider(void); DECLARE_IUNKNOWN; DECLARE_ISUBRENDEROPTIONS; // ISubRenderProvider STDMETHODIMP RequestFrame(REFERENCE_TIME start, REFERENCE_TIME stop, LPVOID context); STDMETHODIMP Disconnect(void); // CLAVSubtitleProvider public STDMETHODIMP SetConsumer(ISubRenderConsumer *pConsumer); STDMETHODIMP DisconnectConsumer(void); STDMETHODIMP InitDecoder(const CMediaType *pmt, AVCodecID codecId); STDMETHODIMP Decode(BYTE *buf, int buflen, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop); STDMETHODIMP Flush(); STDMETHODIMP SetDVDPalette(struct _AM_PROPERTY_SPPAL *pPal); STDMETHODIMP SetDVDHLI(struct _AM_PROPERTY_SPHLI *pHLI); STDMETHODIMP SetDVDComposit(BOOL bComposit); private: void CloseDecoder(); void ProcessSubtitleFrame(AVSubtitle *sub, REFERENCE_TIME rtStart); void ProcessSubtitleRect(AVSubtitleRect *rect, REFERENCE_TIME rtStart, REFERENCE_TIME rtStop); void AddSubtitleRect(CLAVSubRect *rect); CLAVSubRect *ProcessDVDHLI(CLAVSubRect *rect); void ClearSubtitleRects(); void TimeoutSubtitleRects(REFERENCE_TIME rtStop); enum { CNTRL_EXIT, CNTRL_FLUSH }; HRESULT ControlCmd(DWORD cmd) { return m_ControlThread->CallWorker(cmd); } private: friend class CLAVSubtitleProviderControlThread; LAVSubtitleProviderContext context; CLAVVideo *m_pLAVVideo = nullptr; ISubRenderConsumer *m_pConsumer = nullptr; ISubRenderConsumer2 *m_pConsumer2 = nullptr; const AVCodec *m_pAVCodec = nullptr; AVCodecContext *m_pAVCtx = nullptr; AVCodecParserContext *m_pParser = nullptr; REFERENCE_TIME m_rtLastFrame = AV_NOPTS_VALUE; REFERENCE_TIME m_rtStartCache = AV_NOPTS_VALUE; ULONGLONG m_SubPicId = 0; BOOL m_bComposit = TRUE; AVPacket *m_pSubtitlePacket = nullptr; std::list m_SubFrames; struct _AM_PROPERTY_SPHLI *m_pHLI = nullptr; CLAVSubtitleProviderControlThread *m_ControlThread = nullptr; }; ================================================ FILE: decoder/LAVVideo/subtitles/LAVVideoSubtitleInputPin.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVVideoSubtitleInputPin.h" #include "LAVVideo.h" #include "moreuuids.h" typedef struct { const CLSID *clsMajorType; const CLSID *clsMinorType; const enum AVCodecID nFFCodec; } LAV_TYPE_MAP; static const LAV_TYPE_MAP lav_subtitle_codecs[] = { {&MEDIATYPE_DVD_ENCRYPTED_PACK, &MEDIASUBTYPE_DVD_SUBPICTURE, AV_CODEC_ID_DVD_SUBTITLE}, {&MEDIATYPE_MPEG2_PACK, &MEDIASUBTYPE_DVD_SUBPICTURE, AV_CODEC_ID_DVD_SUBTITLE}, {&MEDIATYPE_MPEG2_PES, &MEDIASUBTYPE_DVD_SUBPICTURE, AV_CODEC_ID_DVD_SUBTITLE}, {&MEDIATYPE_Video, &MEDIASUBTYPE_DVD_SUBPICTURE, AV_CODEC_ID_DVD_SUBTITLE}}; CLAVVideoSubtitleInputPin::CLAVVideoSubtitleInputPin(TCHAR *pObjectName, CLAVVideo *pFilter, CCritSec *pcsFilter, HRESULT *phr, LPWSTR pName) : CBaseInputPin(pObjectName, pFilter, pcsFilter, phr, pName) , m_pLAVVideo(pFilter) , CDeCSSPinHelper() { } CLAVVideoSubtitleInputPin::~CLAVVideoSubtitleInputPin(void) { SafeRelease(&m_pConsumer); SafeRelease(&m_pProvider); } STDMETHODIMP CLAVVideoSubtitleInputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); return QI(IKsPropertySet) __super::NonDelegatingQueryInterface(riid, ppv); } HRESULT CLAVVideoSubtitleInputPin::CheckMediaType(const CMediaType *mtIn) { for (int i = 0; i < countof(lav_subtitle_codecs); i++) { if (*lav_subtitle_codecs[i].clsMajorType == mtIn->majortype && *lav_subtitle_codecs[i].clsMinorType == mtIn->subtype && (mtIn->formattype == FORMAT_SubtitleInfo || mtIn->formattype == FORMAT_MPEG2_VIDEO)) { return S_OK; } } return VFW_E_TYPE_NOT_ACCEPTED; } HRESULT CLAVVideoSubtitleInputPin::SetMediaType(const CMediaType *pmt) { CAutoLock lock(&m_csReceive); SetCSSMediaType(pmt); ASSERT(m_pConsumer); SafeRelease(&m_pProvider); AVCodecID codecId = AV_CODEC_ID_NONE; for (int i = 0; i < countof(lav_subtitle_codecs); i++) { if (*lav_subtitle_codecs[i].clsMajorType == pmt->majortype && *lav_subtitle_codecs[i].clsMinorType == pmt->subtype) { codecId = lav_subtitle_codecs[i].nFFCodec; } } if (codecId == AV_CODEC_ID_NONE) return VFW_E_TYPE_NOT_ACCEPTED; m_pProvider = new CLAVSubtitleProvider(m_pLAVVideo, m_pConsumer); m_pProvider->AddRef(); HRESULT hr = m_pProvider->InitDecoder(pmt, codecId); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"Subtitle Decoder Init failed....")); return hr; } return __super::SetMediaType(pmt); } HRESULT CLAVVideoSubtitleInputPin::BreakConnect() { if (m_pProvider) { m_pProvider->DisconnectConsumer(); SafeRelease(&m_pProvider); } return __super::BreakConnect(); } STDMETHODIMP CLAVVideoSubtitleInputPin::BeginFlush() { return __super::BeginFlush(); } STDMETHODIMP CLAVVideoSubtitleInputPin::EndFlush() { CAutoLock lock(&m_csReceive); DbgLog((LOG_TRACE, 10, L"CLAVVideoSubtitleInputPin::EndFlush()")); if (m_pProvider) { m_pProvider->Flush(); } return __super::EndFlush(); } HRESULT CLAVVideoSubtitleInputPin::SetSubtitleConsumer(ISubRenderConsumer *pConsumer) { if (pConsumer == m_pConsumer) return S_OK; SafeRelease(&m_pConsumer); m_pConsumer = pConsumer; m_pConsumer->AddRef(); if (m_pProvider) { m_pProvider->DisconnectConsumer(); m_pProvider->SetConsumer(pConsumer); } return S_OK; } STDMETHODIMP CLAVVideoSubtitleInputPin::Receive(IMediaSample *pSample) { CAutoLock lock(&m_csReceive); HRESULT hr = S_OK; Decrypt(pSample); ASSERT(m_pProvider); hr = CBaseInputPin::Receive(pSample); if (hr == S_OK) { long len = pSample->GetActualDataLength(); BYTE *pBuffer = nullptr; if (FAILED(hr = pSample->GetPointer(&pBuffer))) { DbgLog((LOG_TRACE, 10, L"CLAVVideoSubtitleInputPin::Receive() GetPointer failed")); return S_OK; } StripPacket(pBuffer, len); REFERENCE_TIME rtStart, rtStop; hr = pSample->GetTime(&rtStart, &rtStop); if (hr == VFW_S_NO_STOP_TIME) { rtStop = AV_NOPTS_VALUE; } else if (FAILED(hr)) { rtStart = rtStop = AV_NOPTS_VALUE; } m_pProvider->Decode(pBuffer, len, rtStart, rtStop); } return S_OK; } // IKsPropertySet STDMETHODIMP CLAVVideoSubtitleInputPin::Set(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength) { if (PropSet != AM_KSPROPSETID_DvdSubPic) { return __super::Set(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength); } switch (Id) { case AM_PROPERTY_DVDSUBPIC_PALETTE: { AM_PROPERTY_SPPAL *pSPPAL = (AM_PROPERTY_SPPAL *)pPropertyData; if (m_pProvider) { m_pProvider->SetDVDPalette(pSPPAL); } } break; case AM_PROPERTY_DVDSUBPIC_HLI: { AM_PROPERTY_SPHLI *pSPHLI = (AM_PROPERTY_SPHLI *)pPropertyData; if (pSPHLI->HLISS) { if (m_pProvider) { m_pProvider->SetDVDHLI(pSPHLI); } } else { if (m_pProvider) { m_pProvider->SetDVDHLI(nullptr); } } } break; case AM_PROPERTY_DVDSUBPIC_COMPOSIT_ON: { AM_PROPERTY_COMPOSIT_ON *pCompositOn = (AM_PROPERTY_COMPOSIT_ON *)pPropertyData; DbgLog((LOG_TRACE, 10, L"Composit Event - on: %d", *pCompositOn)); m_pProvider->SetDVDComposit(*pCompositOn); } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CLAVVideoSubtitleInputPin::QuerySupported(REFGUID PropSet, ULONG Id, ULONG *pTypeSupport) { if (PropSet != AM_KSPROPSETID_DvdSubPic) { return __super::QuerySupported(PropSet, Id, pTypeSupport); } switch (Id) { case AM_PROPERTY_DVDSUBPIC_PALETTE: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDSUBPIC_HLI: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_PROPERTY_DVDSUBPIC_COMPOSIT_ON: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } ================================================ FILE: decoder/LAVVideo/subtitles/LAVVideoSubtitleInputPin.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "DeCSS/DeCSSInputPin.h" #include "SubRenderIntf.h" #include "LAVSubtitleProvider.h" class CLAVVideo; class CLAVVideoSubtitleInputPin : public CBaseInputPin , public CDeCSSPinHelper { public: CLAVVideoSubtitleInputPin(TCHAR *pObjectName, CLAVVideo *pFilter, CCritSec *pcsFilter, HRESULT *phr, LPWSTR pName); virtual ~CLAVVideoSubtitleInputPin(void); DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // IMemInputPin STDMETHODIMP Receive(IMediaSample *pSample); // CBasePin HRESULT CheckMediaType(const CMediaType *mtIn); HRESULT SetMediaType(const CMediaType *pmt); HRESULT BreakConnect(); STDMETHODIMP BeginFlush(); STDMETHODIMP EndFlush(); HRESULT SetSubtitleConsumer(ISubRenderConsumer *pConsumer); // KsPropertySet STDMETHODIMP Set(REFGUID PropSet, ULONG Id, LPVOID InstanceData, ULONG InstanceLength, LPVOID PropertyData, ULONG DataLength); STDMETHODIMP QuerySupported(REFGUID PropSet, ULONG Id, ULONG *pTypeSupport); protected: CCritSec m_csReceive; ISubRenderConsumer *m_pConsumer = nullptr; CLAVSubtitleProvider *m_pProvider = nullptr; CLAVVideo *m_pLAVVideo = nullptr; }; ================================================ FILE: decoder/LAVVideo/subtitles/SubRenderOptionsImpl.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "SubRenderOptionsImpl.h" static const SubRenderOption *sropt_next(const SubRenderOption *options, const SubRenderOption *last) { if (!last && options[0].name) return options; if (last && last[1].name) return ++last; return nullptr; } static const SubRenderOption *sropt_find_option(const SubRenderOption *options, LPCSTR name, int flags) { const SubRenderOption *o = nullptr; while (o = sropt_next(options, o)) { if (!_stricmp(o->name, name) && !(o->flags & flags)) { return o; } } return nullptr; } #define GET_OPT_AND_VALIDATE(t) \ const SubRenderOption *o = sropt_find_option(options, field, 0); \ CheckPointer(value, E_POINTER); \ CheckPointer(o, E_INVALIDARG); \ if (o->type != t) \ return E_INVALIDARG; #define GET_VALUE memcpy(value, ((uint8_t *)context) + o->offset, sizeof(*value)); #define SET_OPT_AND_VALIDATE(t) \ const SubRenderOption *o = sropt_find_option(options, field, SROPT_FLAG_READONLY); \ CheckPointer(o, E_INVALIDARG); \ if (o->type != t) \ return E_INVALIDARG; #define SET_VALUE \ memcpy(((uint8_t *)context) + o->offset, &value, sizeof(value)); \ OnSubOptionSet(field); STDMETHODIMP CSubRenderOptionsImpl::GetBool(LPCSTR field, bool *value) { GET_OPT_AND_VALIDATE(SROPT_TYPE_BOOL) GET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::GetInt(LPCSTR field, int *value) { GET_OPT_AND_VALIDATE(SROPT_TYPE_INT) GET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::GetSize(LPCSTR field, SIZE *value) { GET_OPT_AND_VALIDATE(SROPT_TYPE_SIZE) GET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::GetRect(LPCSTR field, RECT *value) { GET_OPT_AND_VALIDATE(SROPT_TYPE_RECT) GET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::GetUlonglong(LPCSTR field, ULONGLONG *value) { GET_OPT_AND_VALIDATE(SROPT_TYPE_ULONGLONG) GET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::GetDouble(LPCSTR field, double *value) { GET_OPT_AND_VALIDATE(SROPT_TYPE_DOUBLE) GET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::GetString(LPCSTR field, LPWSTR *value, int *chars) { GET_OPT_AND_VALIDATE(SROPT_TYPE_STRING) CheckPointer(chars, E_POINTER); const LPWSTR string = *(LPWSTR *)(((uint8_t *)context) + o->offset); if (!string) { *value = nullptr; *chars = 0; return S_OK; } *chars = (int)wcslen(string); *value = (LPWSTR)LocalAlloc(0, sizeof(WCHAR) * (*chars + 1)); CheckPointer(*value, E_OUTOFMEMORY); wcscpy_s(*value, *chars + 1, string); return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::GetBin(LPCSTR field, LPVOID *value, int *size) { GET_OPT_AND_VALIDATE(SROPT_TYPE_BIN) CheckPointer(size, E_POINTER); return E_NOTIMPL; } STDMETHODIMP CSubRenderOptionsImpl::SetBool(LPCSTR field, bool value) { SET_OPT_AND_VALIDATE(SROPT_TYPE_BOOL) SET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::SetInt(LPCSTR field, int value) { SET_OPT_AND_VALIDATE(SROPT_TYPE_INT) SET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::SetSize(LPCSTR field, SIZE value) { SET_OPT_AND_VALIDATE(SROPT_TYPE_SIZE) SET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::SetRect(LPCSTR field, RECT value) { SET_OPT_AND_VALIDATE(SROPT_TYPE_RECT) SET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::SetUlonglong(LPCSTR field, ULONGLONG value) { SET_OPT_AND_VALIDATE(SROPT_TYPE_ULONGLONG) SET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::SetDouble(LPCSTR field, double value) { SET_OPT_AND_VALIDATE(SROPT_TYPE_DOUBLE) SET_VALUE return S_OK; } STDMETHODIMP CSubRenderOptionsImpl::SetString(LPCSTR field, LPWSTR value, int chars) { SET_OPT_AND_VALIDATE(SROPT_TYPE_STRING) return E_NOTIMPL; } STDMETHODIMP CSubRenderOptionsImpl::SetBin(LPCSTR field, LPVOID value, int size) { SET_OPT_AND_VALIDATE(SROPT_TYPE_BIN) return E_NOTIMPL; } ================================================ FILE: decoder/LAVVideo/subtitles/SubRenderOptionsImpl.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once /** Enum for the different types */ enum SubRenderOptionType { SROPT_TYPE_BOOL, SROPT_TYPE_INT, SROPT_TYPE_SIZE, SROPT_TYPE_RECT, SROPT_TYPE_ULONGLONG, SROPT_TYPE_DOUBLE, SROPT_TYPE_STRING, SROPT_TYPE_BIN }; typedef struct SubRenderOption { /** * Name of the field */ LPCSTR name; /** * The offset relative to the options structure */ int offset; /** * The type of the options */ enum SubRenderOptionType type; /** * Flags */ int flags; #define SROPT_FLAG_READONLY 1 } SubRenderOption; class CSubRenderOptionsImpl : public ISubRenderOptions { public: CSubRenderOptionsImpl(const struct SubRenderOption *options, void *context) : options(options) , context(context){}; virtual ~CSubRenderOptionsImpl(void){}; // ISubRenderOptions STDMETHODIMP GetBool(LPCSTR field, bool *value); STDMETHODIMP GetInt(LPCSTR field, int *value); STDMETHODIMP GetSize(LPCSTR field, SIZE *value); STDMETHODIMP GetRect(LPCSTR field, RECT *value); STDMETHODIMP GetUlonglong(LPCSTR field, ULONGLONG *value); STDMETHODIMP GetDouble(LPCSTR field, double *value); STDMETHODIMP GetString(LPCSTR field, LPWSTR *value, int *chars); STDMETHODIMP GetBin(LPCSTR field, LPVOID *value, int *size); STDMETHODIMP SetBool(LPCSTR field, bool value); STDMETHODIMP SetInt(LPCSTR field, int value); STDMETHODIMP SetSize(LPCSTR field, SIZE value); STDMETHODIMP SetRect(LPCSTR field, RECT value); STDMETHODIMP SetUlonglong(LPCSTR field, ULONGLONG value); STDMETHODIMP SetDouble(LPCSTR field, double value); STDMETHODIMP SetString(LPCSTR field, LPWSTR value, int chars); STDMETHODIMP SetBin(LPCSTR field, LPVOID value, int size); virtual STDMETHODIMP OnSubOptionSet(LPCSTR field) { return E_NOTIMPL; } private: const SubRenderOption *options = nullptr; void *context = nullptr; }; #define DECLARE_ISUBRENDEROPTIONS \ STDMETHODIMP GetBool(LPCSTR field, bool *value) { return CSubRenderOptionsImpl::GetBool(field, value); } \ STDMETHODIMP GetInt(LPCSTR field, int *value) { return CSubRenderOptionsImpl::GetInt(field, value); } \ STDMETHODIMP GetSize(LPCSTR field, SIZE *value) { return CSubRenderOptionsImpl::GetSize(field, value); } \ STDMETHODIMP GetRect(LPCSTR field, RECT *value) { return CSubRenderOptionsImpl::GetRect(field, value); } \ STDMETHODIMP GetUlonglong(LPCSTR field, ULONGLONG *value) \ { \ return CSubRenderOptionsImpl::GetUlonglong(field, value); \ } \ STDMETHODIMP GetDouble(LPCSTR field, double *value) { return CSubRenderOptionsImpl::GetDouble(field, value); } \ STDMETHODIMP GetString(LPCSTR field, LPWSTR *value, int *chars) \ { \ return CSubRenderOptionsImpl::GetString(field, value, chars); \ } \ STDMETHODIMP GetBin(LPCSTR field, LPVOID *value, int *size) \ { \ return CSubRenderOptionsImpl::GetBin(field, value, size); \ } \ \ STDMETHODIMP SetBool(LPCSTR field, bool value) { return CSubRenderOptionsImpl::SetBool(field, value); } \ STDMETHODIMP SetInt(LPCSTR field, int value) { return CSubRenderOptionsImpl::SetInt(field, value); } \ STDMETHODIMP SetSize(LPCSTR field, SIZE value) { return CSubRenderOptionsImpl::SetSize(field, value); } \ STDMETHODIMP SetRect(LPCSTR field, RECT value) { return CSubRenderOptionsImpl::SetRect(field, value); } \ STDMETHODIMP SetUlonglong(LPCSTR field, ULONGLONG value) \ { \ return CSubRenderOptionsImpl::SetUlonglong(field, value); \ } \ STDMETHODIMP SetDouble(LPCSTR field, double value) { return CSubRenderOptionsImpl::SetDouble(field, value); } \ STDMETHODIMP SetString(LPCSTR field, LPWSTR value, int chars) \ { \ return CSubRenderOptionsImpl::SetString(field, value, chars); \ } \ STDMETHODIMP SetBin(LPCSTR field, LPVOID value, int size) \ { \ return CSubRenderOptionsImpl::SetBin(field, value, size); \ } ================================================ FILE: decoder/LAVVideo/subtitles/blend/blend_generic.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "../LAVSubtitleConsumer.h" #define FAST_DIV255(x) ((((x) + 128) * 257) >> 16) DECLARE_BLEND_FUNC_IMPL(blend_rgb_c) { ASSERT(pixFmt == LAVPixFmt_RGB32 || pixFmt == LAVPixFmt_RGB24); BYTE *rgbOut = video[0]; const BYTE *subIn = subData[0]; const ptrdiff_t outStride = videoStride[0]; const ptrdiff_t inStride = subStride[0]; const ptrdiff_t dstep = (pixFmt == LAVPixFmt_RGB24) ? 3 : 4; for (int y = 0; y < size.cy; y++) { BYTE *dstLine = rgbOut + ((y + position.y) * outStride) + (position.x * dstep); const BYTE *srcLine = subIn + (y * inStride); for (int x = 0; x < size.cx; x++) { const BYTE a = srcLine[3]; switch (a) { case 0: break; case 255: dstLine[0] = srcLine[0]; dstLine[1] = srcLine[1]; dstLine[2] = srcLine[2]; break; default: dstLine[0] = av_clip_uint8(FAST_DIV255(dstLine[0] * (255 - a)) + srcLine[0]); dstLine[1] = av_clip_uint8(FAST_DIV255(dstLine[1] * (255 - a)) + srcLine[1]); dstLine[2] = av_clip_uint8(FAST_DIV255(dstLine[2] * (255 - a)) + srcLine[2]); break; } dstLine += dstep; srcLine += 4; } } return S_OK; } template DECLARE_BLEND_FUNC_IMPL(blend_yuv_c) { ASSERT(pixFmt == LAVPixFmt_YUV420 || pixFmt == LAVPixFmt_NV12 || pixFmt == LAVPixFmt_YUV422 || pixFmt == LAVPixFmt_YUV444 || pixFmt == LAVPixFmt_YUV420bX || pixFmt == LAVPixFmt_YUV422bX || pixFmt == LAVPixFmt_YUV444bX || pixFmt == LAVPixFmt_P016); BYTE *y = video[0]; BYTE *u = video[1]; BYTE *v = video[2]; const BYTE *subY = subData[0]; const BYTE *subU = subData[1]; const BYTE *subV = subData[2]; const BYTE *subA = subData[3]; const ptrdiff_t outStride = videoStride[0]; const ptrdiff_t outStrideUV = videoStride[1]; const ptrdiff_t inStride = subStride[0]; const ptrdiff_t inStrideUV = subStride[1]; int line, col; int w = size.cx, h = size.cy; int yPos = position.y; int xPos = position.x; const int hsub = nv12 || (pixFmt == LAVPixFmt_YUV420 || pixFmt == LAVPixFmt_YUV420bX || pixFmt == LAVPixFmt_NV12); const int vsub = nv12 || (pixFmt != LAVPixFmt_YUV444 && pixFmt != LAVPixFmt_YUV444bX); const int shift = sizeof(pixT) > 1 ? bpp - 8 : 0; for (line = 0; line < h; line++) { pixT *dstY = (pixT *)(y + ((line + yPos) * outStride)) + xPos; const BYTE *srcY = subY + (line * inStride); const BYTE *srcA = subA + (line * inStride); for (col = 0; col < w; col++) { switch (srcA[col]) { case 0: break; case 255: dstY[col] = srcY[col] << shift; break; default: dstY[col] = FAST_DIV255(dstY[col] * (255 - srcA[col]) + (srcY[col] << shift) * srcA[col]); break; } } } if (hsub) { w >>= 1; xPos >>= 1; } if (vsub) { h >>= 1; yPos >>= 1; } for (line = 0; line < h; line++) { pixT *dstUV = (pixT *)(u + (line + yPos) * outStrideUV) + (xPos << 1); pixT *dstU = (pixT *)(u + (line + yPos) * outStrideUV) + xPos; const BYTE *srcU = subU + line * inStrideUV; pixT *dstV = (pixT *)(v + (line + yPos) * outStrideUV) + xPos; const BYTE *srcV = subV + line * inStrideUV; const BYTE *srcA = subA + (line * inStride * (ptrdiff_t(1) << hsub)); for (col = 0; col < w; col++) { // Average Alpha int alpha; if (hsub && vsub && col + 1 < w && line + 1 < h) { alpha = (srcA[0] + srcA[inStride] + srcA[1] + srcA[inStride + 1]) >> 2; } else if (hsub || vsub) { int alpha_h = hsub && col + 1 < w ? (srcA[0] + srcA[1]) >> 1 : srcA[0]; int alpha_v = vsub && line + 1 < h ? (srcA[0] + srcA[inStride]) >> 1 : srcA[0]; alpha = (alpha_h + alpha_v) >> 1; } else { alpha = srcA[0]; } if (nv12) { switch (alpha) { case 0: break; case 255: dstUV[(col << 1) + 0] = srcU[col] << shift; dstUV[(col << 1) + 1] = srcV[col] << shift; break; default: dstUV[(col << 1) + 0] = FAST_DIV255(dstUV[(col << 1) + 0] * (255 - alpha) + (srcU[col] << shift) * alpha); dstUV[(col << 1) + 1] = FAST_DIV255(dstUV[(col << 1) + 1] * (255 - alpha) + (srcV[col] << shift) * alpha); break; } } else { switch (alpha) { case 0: break; case 255: dstU[col] = srcU[col] << shift; dstV[col] = srcV[col] << shift; break; default: dstU[col] = FAST_DIV255(dstU[col] * (255 - alpha) + (srcU[col] << shift) * alpha); dstV[col] = FAST_DIV255(dstV[col] * (255 - alpha) + (srcV[col] << shift) * alpha); break; } } srcA += ptrdiff_t(1) << vsub; } } return S_OK; } template HRESULT CLAVSubtitleConsumer::blend_yuv_c BLEND_FUNC_PARAMS; template HRESULT CLAVSubtitleConsumer::blend_yuv_c BLEND_FUNC_PARAMS; template HRESULT CLAVSubtitleConsumer::blend_yuv_c BLEND_FUNC_PARAMS; template HRESULT CLAVSubtitleConsumer::blend_yuv_c BLEND_FUNC_PARAMS; ================================================ FILE: demuxer/Demuxers/BDDemuxer.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "BDDemuxer.h" #include "libbluray/bdnav/mpls_data.h" extern "C" { #include "libavutil/avstring.h" }; #define BD_READ_BUFFER_SIZE (6144 * 20) int CBDDemuxer::BDByteStreamRead(void *opaque, uint8_t *buf, int buf_size) { CBDDemuxer *demux = (CBDDemuxer *)opaque; int ret = bd_read(demux->m_pBD, buf, buf_size); return (ret != 0) ? ret : AVERROR_EOF; } int64_t CBDDemuxer::BDByteStreamSeek(void *opaque, int64_t offset, int whence) { CBDDemuxer *demux = (CBDDemuxer *)opaque; BLURAY *bd = demux->m_pBD; int64_t pos = 0; if (whence == SEEK_SET) { pos = offset; } else if (whence == SEEK_CUR) { if (offset == 0) return bd_tell(bd); pos = bd_tell(bd) + offset; } else if (whence == SEEK_END) { pos = bd_get_title_size(bd) - offset; } else if (whence == AVSEEK_SIZE) { return bd_get_title_size(bd); } else return -1; if (pos < 0) pos = 0; int64_t achieved = bd_seek(bd, pos); if (pos > achieved) { offset = pos - achieved; DbgLog((LOG_TRACE, 10, L"BD Seek to %I64d, achieved %I64d, correcting target by %I64d", pos, achieved, offset)); uint8_t *dump_buffer = (uint8_t *)CoTaskMemAlloc(6144); while (offset > 0) { int to_read = (int)min(offset, 6144); int did_read = bd_read(bd, dump_buffer, to_read); offset -= did_read; if (did_read < to_read) { DbgLog((LOG_TRACE, 10, L"Reached EOF with %I64d offset remaining", offset)); break; } } CoTaskMemFree(dump_buffer); achieved = bd_tell(bd); } demux->ProcessBDEvents(); return achieved; } static inline REFERENCE_TIME Convert90KhzToDSTime(int64_t timestamp) { return av_rescale(timestamp, 1000, 9); } static inline int64_t ConvertDSTimeTo90Khz(REFERENCE_TIME timestamp) { return av_rescale(timestamp, 9, 1000); } #ifdef DEBUG static void bd_log(const char *log) { const char *path = __FILE__; const char *subpath = "libbluray\\src\\"; // skip the path these two have in common while (*log == *path) { log++; path++; } while (*log == *subpath) { log++; subpath++; } wchar_t line[4096] = {0}; size_t len = strlen(log); if (log[len - 1] == '\n') { len--; } SafeMultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, log, (int)len, line, 4096); DbgLog((LOG_TRACE, 40, L"[BD] %s", line)); } #endif CBDDemuxer::CBDDemuxer(CCritSec *pLock, ILAVFSettingsInternal *pSettings) : CBaseDemuxer(L"bluray demuxer", pLock) , m_pSettings(pSettings) { #ifdef DEBUG bd_set_debug_mask(DBG_FILE | DBG_BLURAY | DBG_DIR | DBG_NAV | DBG_CRIT); bd_set_debug_handler(&bd_log); #else bd_set_debug_mask(0); #endif } CBDDemuxer::~CBDDemuxer(void) { CloseMVCExtensionDemuxer(); if (m_pTitle) { bd_free_title_info(m_pTitle); m_pTitle = nullptr; } if (m_pBD) { bd_close(m_pBD); m_pBD = nullptr; } if (m_pb) { av_free(m_pb->buffer); av_free(m_pb); } SafeRelease(&m_lavfDemuxer); SAFE_CO_FREE(m_StreamClip); SAFE_CO_FREE(m_rtOffset); } STDMETHODIMP CBDDemuxer::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; if (m_lavfDemuxer && (riid == __uuidof(IKeyFrameInfo) || riid == __uuidof(ITrackInfo) || riid == __uuidof(IPropertyBag))) { return m_lavfDemuxer->QueryInterface(riid, ppv); } return QI2(IAMExtendedSeeking) __super::NonDelegatingQueryInterface(riid, ppv); } ///////////////////////////////////////////////////////////////////////////// // Demuxer Functions STDMETHODIMP CBDDemuxer::Open(LPCOLESTR pszFileName, LPCOLESTR pszUserAgent, LPCOLESTR pszReferrer) { CAutoLock lock(m_pLock); HRESULT hr = S_OK; int ret; // return code from C functions // Convert the filename from wchar to char for libbluray char fileName[4096]; ret = SafeWideCharToMultiByte(CP_UTF8, 0, pszFileName, -1, fileName, 4096, nullptr, nullptr); int iPlaylist = -1; DbgLog((LOG_TRACE, 10, L"Initializing BluRay Demuxer; Entry Point: %s", pszFileName)); size_t len = strlen(fileName); if (len > 16) { char *bd_path = fileName; if (_strcmpi(bd_path + strlen(bd_path) - 16, "\\BDMV\\index.bdmv") == 0) { bd_path[strlen(bd_path) - 15] = 0; } else if (len > 22 && _strcmpi(bd_path + strlen(bd_path) - 22, "\\BDMV\\MovieObject.bdmv") == 0) { bd_path[strlen(bd_path) - 21] = 0; } else if (len > 25 && _strnicmp(bd_path + strlen(bd_path) - 25, "\\BDMV\\PLAYLIST\\", 15) == 0) { char *playlist = &bd_path[strlen(bd_path) - 10]; bd_path[strlen(bd_path) - 24] = 0; playlist[5] = 0; iPlaylist = atoi(playlist); } else { return E_FAIL; } // Open BluRay BLURAY *bd = bd_open(bd_path, nullptr); if (!bd) { return E_FAIL; } m_pBD = bd; strcpy_s(m_cBDRootPath, bd_path); uint32_t timelimit = (iPlaylist != -1) ? 0 : 180; uint8_t flags = (iPlaylist != -1) ? TITLES_ALL : TITLES_RELEVANT; // Fetch titles fetchtitles: m_nTitleCount = bd_get_titles(bd, flags, timelimit); if (m_nTitleCount <= 0) { if (timelimit > 0) { timelimit = 0; goto fetchtitles; } if (flags != TITLES_ALL) { flags = TITLES_ALL; goto fetchtitles; } return E_FAIL; } DbgLog((LOG_TRACE, 20, L"Found %d titles", m_nTitleCount)); DbgLog((LOG_TRACE, 20, L" ------ Begin Title Listing ------")); uint64_t longest_duration = 0; uint32_t title_id = 0; boolean found = false; for (uint32_t i = 0; i < m_nTitleCount; i++) { BLURAY_TITLE_INFO *info = bd_get_title_info(bd, i, 0); if (info) { DbgLog((LOG_TRACE, 20, L"Title %u, Playlist %u (%u clips, %u chapters), Duration %I64u (%I64u seconds)", i, info->playlist, info->clip_count, info->chapter_count, info->duration, Convert90KhzToDSTime(info->duration) / DSHOW_TIME_BASE)); if (iPlaylist != -1 && info->playlist == iPlaylist) { title_id = i; found = true; } else if (iPlaylist == -1 && info->duration > longest_duration) { title_id = i; longest_duration = info->duration; } bd_free_title_info(info); } if (found) break; } DbgLog((LOG_TRACE, 20, L" ------ End Title Listing ------")); hr = SetTitle(title_id); } return hr; } STDMETHODIMP CBDDemuxer::Start() { HRESULT hr = m_lavfDemuxer->Start(); if (m_MVCPlayback && !m_lavfDemuxer->m_bH264MVCCombine) { CloseMVCExtensionDemuxer(); m_MVCPlayback = FALSE; } return hr; } REFERENCE_TIME CBDDemuxer::GetDuration() const { if (m_pTitle) { return av_rescale(m_pTitle->duration, 1000, 9); } return m_lavfDemuxer->GetDuration(); } void CBDDemuxer::ProcessBDEvents() { // Check for clip change BD_EVENT event; while (bd_get_event(m_pBD, &event)) { if (event.event == BD_EVENT_PLAYITEM) { uint64_t clip_start, clip_in, bytepos; int ret = bd_get_clip_infos(m_pBD, event.param, &clip_start, &clip_in, &bytepos, nullptr); if (ret && m_lavfDemuxer->GetStartTime() != AV_NOPTS_VALUE) { m_rtNewOffset = Convert90KhzToDSTime(clip_start - clip_in) + m_lavfDemuxer->GetStartTime(); m_bNewOffsetPos = bytepos - 4; m_NewClip = event.param; DbgLog((LOG_TRACE, 10, L"New clip! offset: %I64d bytepos: %I64u", m_rtNewOffset, bytepos)); } m_EndOfStreamPacketFlushProtection = FALSE; } else if (event.event == BD_EVENT_END_OF_TITLE) { m_EndOfStreamPacketFlushProtection = TRUE; } else if (event.event == BD_EVENT_SEEK) { m_EndOfStreamPacketFlushProtection = FALSE; } } } STDMETHODIMP CBDDemuxer::ProcessPacket(Packet *pPacket) { ProcessBDEvents(); if (pPacket && pPacket->rtStart != Packet::INVALID_TIME) { REFERENCE_TIME rtOffset = m_rtOffset[pPacket->StreamId]; if (m_StreamClip[pPacket->StreamId] != m_NewClip && pPacket->bPosition != -1 && pPacket->bPosition >= m_bNewOffsetPos) { DbgLog((LOG_TRACE, 10, L"Actual clip change detected in stream %d; time: %I64d, old offset: %I64d, new offset: %I64d", pPacket->StreamId, pPacket->rtStart, rtOffset, m_rtNewOffset)); rtOffset = m_rtOffset[pPacket->StreamId] = m_rtNewOffset; m_StreamClip[pPacket->StreamId] = m_NewClip; // Flush MVC extensions on stream change, it'll re-fill automatically if (m_MVCPlayback && pPacket->StreamId == m_lavfDemuxer->m_nH264MVCBaseStream && m_MVCExtensionClip != m_NewClip) { m_lavfDemuxer->FlushMVCExtensionQueue(); CloseMVCExtensionDemuxer(); OpenMVCExtensionDemuxer(m_NewClip); } } // DbgLog((LOG_TRACE, 10, L"Frame: stream: %d, start: %I64d, corrected: %I64d, bytepos: %I64d", // pPacket->StreamId, pPacket->rtStart, pPacket->rtStart + rtOffset, pPacket->bPosition)); pPacket->rtStart += rtOffset; pPacket->rtStop += rtOffset; } if (m_EndOfStreamPacketFlushProtection && pPacket && pPacket->bPosition != -1) { if (pPacket->bPosition < m_bNewOffsetPos) { DbgLog(( LOG_TRACE, 10, L"Dropping packet from a previous segment (pos %I64d, segment started at %I64d) at EOS, from stream %d", pPacket->bPosition, m_bNewOffsetPos, pPacket->StreamId)); return S_FALSE; } } return S_OK; } void CBDDemuxer::CloseMVCExtensionDemuxer() { if (m_MVCFormatContext) avformat_close_input(&m_MVCFormatContext); m_MVCExtensionClip = -1; } STDMETHODIMP CBDDemuxer::OpenMVCExtensionDemuxer(int playItem) { int ret; MPLS_PL *pl = bd_get_title_mpls(m_pBD); if (!pl) return E_FAIL; const char *clip_id = pl->ext_sub_path[m_MVCExtensionSubPathIndex].sub_play_item[playItem].clip->clip_id; char *fileName = av_asprintf("%sBDMV\\STREAM\\%s.m2ts", m_cBDRootPath, clip_id); DbgLog((LOG_TRACE, 10, "CBDDemuxer::OpenMVCExtensionDemuxer(): Opening MVC extension stream at %s", fileName)); // Try to open the MVC stream const AVInputFormat *format = av_find_input_format("mpegts"); ret = avformat_open_input(&m_MVCFormatContext, fileName, format, nullptr); if (ret < 0) { DbgLog((LOG_TRACE, 10, "-> Opening MVC demuxing context failed (%d)", ret)); goto fail; } av_opt_set_int(m_MVCFormatContext, "correct_ts_overflow", 0, 0); // Find the streams ret = avformat_find_stream_info(m_MVCFormatContext, nullptr); if (ret < 0) { DbgLog((LOG_TRACE, 10, "-> avformat_find_stream_info failed (%d)", ret)); goto fail; } // Find and select our MVC stream DbgLog((LOG_TRACE, 10, "-> MVC m2ts has %d streams", m_MVCFormatContext->nb_streams)); for (unsigned i = 0; i < m_MVCFormatContext->nb_streams; i++) { if (m_MVCFormatContext->streams[i]->codecpar->codec_id == AV_CODEC_ID_H264_MVC && m_MVCFormatContext->streams[i]->codecpar->extradata_size > 0) { m_MVCStreamIndex = i; break; } else { m_MVCFormatContext->streams[i]->discard = AVDISCARD_ALL; } } if (m_MVCStreamIndex < 0) { DbgLog((LOG_TRACE, 10, "-> MVC Stream not found")); goto fail; } m_MVCExtensionClip = playItem; return S_OK; fail: CloseMVCExtensionDemuxer(); return E_FAIL; } #define MVC_DEMUX_COUNT 100 STDMETHODIMP CBDDemuxer::FillMVCExtensionQueue(REFERENCE_TIME rtBase) { if (!m_MVCFormatContext) return E_FAIL; int ret, count = 0; bool found = (rtBase == Packet::INVALID_TIME); AVPacket *pMVCPacket = av_packet_alloc(); while (count < MVC_DEMUX_COUNT) { av_packet_unref(pMVCPacket); ret = av_read_frame(m_MVCFormatContext, pMVCPacket); if (ret == AVERROR(EINTR) || ret == AVERROR(EAGAIN)) { continue; } else if (ret == AVERROR_EOF) { DbgLog((LOG_TRACE, 10, L"EOF reading MVC extension data")); break; } else if (pMVCPacket->size <= 0 || pMVCPacket->stream_index != m_MVCStreamIndex) { continue; } else { AVStream *stream = m_MVCFormatContext->streams[pMVCPacket->stream_index]; REFERENCE_TIME rtDTS = m_lavfDemuxer->ConvertTimestampToRT(pMVCPacket->dts, stream->time_base.num, stream->time_base.den); REFERENCE_TIME rtPTS = m_lavfDemuxer->ConvertTimestampToRT(pMVCPacket->pts, stream->time_base.num, stream->time_base.den); if (rtBase == Packet::INVALID_TIME || rtDTS == Packet::INVALID_TIME) { // do nothing, can't compare timestamps when they are not set } else if (rtDTS < rtBase) { DbgLog((LOG_TRACE, 10, L"CBDDemuxer::FillMVCExtensionQueue(): Dropping MVC extension at %I64d, base is %I64d", rtDTS, rtBase)); continue; } else if (rtDTS == rtBase) { found = true; } Packet *pPacket = new Packet(); if (!pPacket) { av_packet_free(&pMVCPacket); return E_OUTOFMEMORY; } pPacket->SetPacket(pMVCPacket); pPacket->rtDTS = rtDTS; pPacket->rtPTS = rtPTS; m_lavfDemuxer->QueueMVCExtension(pPacket); count++; } }; av_packet_free(&pMVCPacket); if (found) return S_OK; else if (count > 0) return S_FALSE; else return E_FAIL; } STDMETHODIMP CBDDemuxer::SetTitle(int idx) { HRESULT hr = S_OK; int ret; // return values if (m_pTitle) { bd_free_title_info(m_pTitle); } // Init Event Queue bd_get_event(m_pBD, nullptr); // Select title m_pTitle = bd_get_title_info(m_pBD, idx, 0); ret = bd_select_title(m_pBD, idx); if (ret == 0) { return E_FAIL; } MPLS_PL *mpls = bd_get_title_mpls(m_pBD); if (mpls) { for (int i = 0; i < mpls->ext_sub_count; i++) { if (mpls->ext_sub_path[i].type == 8 && mpls->ext_sub_path[i].sub_playitem_count == mpls->list_count) { DbgLog((LOG_TRACE, 20, L"CBDDemuxer::SetTitle(): Enabling BD3D MVC demuxing")); DbgLog((LOG_TRACE, 20, L" -> MVC_Base_view_R_flag: %d", m_pTitle->mvc_base_view_r_flag)); m_MVCPlayback = TRUE; m_MVCExtensionSubPathIndex = i; break; } } } CloseMVCExtensionDemuxer(); if (m_pb) { av_free(m_pb->buffer); av_free(m_pb); } uint8_t *buffer = (uint8_t *)av_mallocz(BD_READ_BUFFER_SIZE + AV_INPUT_BUFFER_PADDING_SIZE); m_pb = avio_alloc_context(buffer, BD_READ_BUFFER_SIZE, 0, this, BDByteStreamRead, nullptr, BDByteStreamSeek); SafeRelease(&m_lavfDemuxer); SAFE_CO_FREE(m_StreamClip); SAFE_CO_FREE(m_rtOffset); m_lavfDemuxer = new CLAVFDemuxer(m_pLock, m_pSettings); m_lavfDemuxer->AddRef(); m_lavfDemuxer->SetBluRay(this); if (FAILED(hr = m_lavfDemuxer->OpenInputStream(m_pb, nullptr, "mpegts", TRUE))) { SafeRelease(&m_lavfDemuxer); return hr; } if (m_MVCPlayback && !m_lavfDemuxer->m_bH264MVCCombine) { DbgLog((LOG_TRACE, 10, L"CBDDemuxer::SetTitle(): MVC demuxing was requested, but main demuxer did not activate MVC mode, " L"disabling.")); CloseMVCExtensionDemuxer(); m_MVCPlayback = FALSE; } m_lavfDemuxer->SeekByte(0, 0); // Process any events that occurred during opening ProcessBDEvents(); // Reset EOS protection m_EndOfStreamPacketFlushProtection = FALSE; // space for storing stream offsets m_StreamClip = (uint16_t *)CoTaskMemAlloc(sizeof(*m_StreamClip) * m_lavfDemuxer->GetNumStreams()); if (!m_StreamClip) return E_OUTOFMEMORY; memset(m_StreamClip, -1, sizeof(*m_StreamClip) * m_lavfDemuxer->GetNumStreams()); m_rtOffset = (REFERENCE_TIME *)CoTaskMemAlloc(sizeof(*m_rtOffset) * m_lavfDemuxer->GetNumStreams()); if (!m_rtOffset) return E_OUTOFMEMORY; memset(m_rtOffset, 0, sizeof(*m_rtOffset) * m_lavfDemuxer->GetNumStreams()); DbgLog((LOG_TRACE, 20, L"Opened BD title with %d clips and %d chapters", m_pTitle->clip_count, m_pTitle->chapter_count)); return S_OK; } void CBDDemuxer::ProcessBluRayMetadata() { if (m_MVCPlayback) { HRESULT hr = OpenMVCExtensionDemuxer(m_NewClip); if (SUCCEEDED(hr)) { AVStream *mvcStream = m_MVCFormatContext->streams[m_MVCStreamIndex]; // Create a fake stream and set the appropriate properties m_lavfDemuxer->AddMPEGTSStream(mvcStream->id, 0x20); AVStream *avstream = m_lavfDemuxer->GetAVStreamByPID(mvcStream->id); if (avstream) { avstream->codecpar->codec_id = AV_CODEC_ID_H264_MVC; avstream->codecpar->extradata = (BYTE *)av_mallocz(mvcStream->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); avstream->codecpar->extradata_size = mvcStream->codecpar->extradata_size; memcpy(avstream->codecpar->extradata, mvcStream->codecpar->extradata, mvcStream->codecpar->extradata_size); } } else { m_MVCPlayback = FALSE; } } ASSERT(m_pTitle->clip_count >= 1 && m_pTitle->clips); int64_t max_clip_duration = 0; for (uint32_t i = 0; i < m_pTitle->clip_count; ++i) { int64_t clip_duration = (m_pTitle->clips[i].out_time - m_pTitle->clips[i].in_time); bool overwrite_info = false; if (clip_duration > max_clip_duration) { overwrite_info = true; max_clip_duration = clip_duration; } CLPI_CL *clpi = bd_get_clpi(m_pBD, i); ProcessClipInfo(clpi, overwrite_info); bd_free_clpi(clpi); } MPLS_PL *mpls = bd_get_title_mpls(m_pBD); if (mpls) { // Read the PG offsets and store them as metadata std::list pg_sequences; for (int i = 0; i < mpls->play_item[0].stn.num_pg; i++) { AVStream *avstream = m_lavfDemuxer->GetAVStreamByPID(mpls->play_item[0].stn.pg[i].pid); if (mpls->play_item[0].stn.pg[i].ss_offset_sequence_id != 0xFF) { pg_sequences.push_back(mpls->play_item[0].stn.pg[i].ss_offset_sequence_id); if (avstream) { char offset[4]; _itoa_s(mpls->play_item[0].stn.pg[i].ss_offset_sequence_id, offset, 10); av_dict_set(&avstream->metadata, "3d-plane", offset, 0); } } } // export the list of pg sequences if (pg_sequences.size() > 0) { // strip duplicate entries pg_sequences.sort(); pg_sequences.unique(); size_t size = pg_sequences.size() * 4; char *offsets = new char[size]; offsets[0] = 0; // Append all offsets to the string for (auto it = pg_sequences.begin(); it != pg_sequences.end(); it++) { size_t len = strlen(offsets); if (len > 0) { offsets[len] = ','; len++; } _itoa_s(*it, offsets + len, size - len, 10); } av_dict_set(&m_lavfDemuxer->m_avFormat->metadata, "pg_offset_sequences", offsets, 0); delete[] offsets; } // Export a list of all IG offsets if (mpls->play_item[0].stn.num_ig > 0) { std::list ig_sequences; for (int i = 0; i < mpls->play_item[0].stn.num_ig; i++) { if (mpls->play_item[0].stn.ig[i].ss_offset_sequence_id != 0xFF) { ig_sequences.push_back(mpls->play_item[0].stn.ig[i].ss_offset_sequence_id); } } if (ig_sequences.size() > 0) { // strip duplicate entries ig_sequences.unique(); size_t size = ig_sequences.size() * 4; char *offsets = new char[size]; offsets[0] = 0; // Append all offsets to the string for (auto it = ig_sequences.begin(); it != ig_sequences.end(); it++) { size_t len = strlen(offsets); if (len > 0) { offsets[len] = ','; len++; } _itoa_s(*it, offsets + len, size - len, 10); } av_dict_set(&m_lavfDemuxer->m_avFormat->metadata, "ig_offset_sequences", offsets, 0); delete[] offsets; } } } } /*STDMETHODIMP_(int) CBDDemuxer::GetNumTitles() { return m_nTitleCount; } STDMETHODIMP CBDDemuxer::GetTitleInfo(int idx, REFERENCE_TIME *rtDuration, WCHAR **ppszName) { if (idx >= m_nTitleCount) { return E_FAIL; } BLURAY_TITLE_INFO *info = bd_get_title_info(m_pBD, idx, 0); if (info) { if (rtDuration) { *rtDuration = Convert90KhzToDSTime(info->duration); } if (ppszName) { WCHAR buffer[80]; swprintf_s(buffer, L"Title %d", idx + 1); size_t size = (wcslen(buffer) + 1) * sizeof(WCHAR); *ppszName = (WCHAR *)CoTaskMemAlloc(size); if (*ppszName) memcpy(*ppszName, buffer, size); } return S_OK; } return E_FAIL; }*/ void CBDDemuxer::ProcessClipInfo(CLPI_CL *clpi, bool overwrite) { if (!clpi) { return; } for (int k = 0; k < clpi->program.num_prog; k++) { for (int i = 0; i < clpi->program.progs[k].num_streams; i++) { CLPI_PROG_STREAM *stream = &clpi->program.progs[k].streams[i]; AVStream *avstream = m_lavfDemuxer->GetAVStreamByPID(stream->pid); if (!avstream) { DbgLog((LOG_TRACE, 10, "CBDDemuxer::ProcessStreams(): Stream with PID 0x%04x not found, trying to add it..", stream->pid)); m_lavfDemuxer->AddMPEGTSStream(stream->pid, stream->coding_type); avstream = m_lavfDemuxer->GetAVStreamByPID(stream->pid); } if (avstream) { if (stream->lang[0] != 0) av_dict_set(&avstream->metadata, "language", (const char *)stream->lang, overwrite ? 0 : AV_DICT_DONT_OVERWRITE); if (avstream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (avstream->codecpar->width == 0 || avstream->codecpar->height == 0) { switch (stream->format) { case BLURAY_VIDEO_FORMAT_480I: case BLURAY_VIDEO_FORMAT_480P: avstream->codecpar->width = 720; avstream->codecpar->height = 480; break; case BLURAY_VIDEO_FORMAT_576I: case BLURAY_VIDEO_FORMAT_576P: avstream->codecpar->width = 720; avstream->codecpar->height = 576; break; case BLURAY_VIDEO_FORMAT_720P: avstream->codecpar->width = 1280; avstream->codecpar->height = 720; break; case BLURAY_VIDEO_FORMAT_1080I: case BLURAY_VIDEO_FORMAT_1080P: default: avstream->codecpar->width = 1920; avstream->codecpar->height = 1080; break; case BLURAY_VIDEO_FORMAT_2160P: avstream->codecpar->width = 3840; avstream->codecpar->height = 2160; break; } } if (m_MVCPlayback && stream->coding_type == BLURAY_STREAM_TYPE_VIDEO_H264) { av_dict_set(&avstream->metadata, "stereo_mode", m_pTitle->mvc_base_view_r_flag ? "mvc_rl" : "mvc_lr", 0); } } else if (avstream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if (avstream->codecpar->ch_layout.nb_channels == 0) { av_channel_layout_default(&avstream->codecpar->ch_layout, (stream->format == BLURAY_AUDIO_FORMAT_MONO) ? 1 : (stream->format == BLURAY_AUDIO_FORMAT_STEREO) ? 2 : 6); avstream->codecpar->sample_rate = (stream->rate == BLURAY_AUDIO_RATE_96 || stream->rate == BLURAY_AUDIO_RATE_96_COMBO) ? 96000 : (stream->rate == BLURAY_AUDIO_RATE_192 || stream->rate == BLURAY_AUDIO_RATE_192_COMBO) ? 192000 : 48000; if (avstream->codecpar->codec_id == AV_CODEC_ID_DTS) { if (stream->coding_type == BLURAY_STREAM_TYPE_AUDIO_DTSHD) avstream->codecpar->profile = AV_PROFILE_DTS_HD_HRA; else if (stream->coding_type == BLURAY_STREAM_TYPE_AUDIO_DTSHD_MASTER) avstream->codecpar->profile = AV_PROFILE_DTS_HD_MA; } } } } } } } STDMETHODIMP CBDDemuxer::Seek(REFERENCE_TIME rTime) { int64_t prev = bd_tell(m_pBD); int64_t target = bd_find_seek_point(m_pBD, ConvertDSTimeTo90Khz(rTime)); m_EndOfStreamPacketFlushProtection = FALSE; DbgLog((LOG_TRACE, 1, "Seek Request: %I64u (time); %I64u (byte), %I64u (prev byte)", rTime, target, prev)); HRESULT hr = m_lavfDemuxer->SeekByte(target + 4, AVSEEK_FLAG_BACKWARD); if (m_MVCPlayback && m_MVCFormatContext) { // Re-open to switch clip if needed CloseMVCExtensionDemuxer(); if (FAILED(OpenMVCExtensionDemuxer(m_NewClip))) return E_FAIL; // Adjust for clip offset int64_t seek_pts = 0; if (rTime > 0) { AVStream *stream = m_MVCFormatContext->streams[m_MVCStreamIndex]; rTime -= m_rtNewOffset; rTime -= 10000000; // seek one second before the target to ensure the MVC queue isn't out of sync for too long seek_pts = m_lavfDemuxer->ConvertRTToTimestamp(rTime, stream->time_base.num, stream->time_base.den); } if (seek_pts < 0) seek_pts = 0; av_seek_frame(m_MVCFormatContext, m_MVCStreamIndex, seek_pts, AVSEEK_FLAG_BACKWARD); } return hr; } const char *CBDDemuxer::GetContainerFormat() const { return "mpegts"; } ///////////////////////////////////////////////////////////////////////////// // IAMExtendedSeeking STDMETHODIMP CBDDemuxer::get_ExSeekCapabilities(long *pExCapabilities) { CheckPointer(pExCapabilities, E_POINTER); *pExCapabilities = AM_EXSEEK_CANSEEK; if (m_pTitle && m_pTitle->chapter_count > 1) *pExCapabilities |= AM_EXSEEK_MARKERSEEK; return S_OK; } STDMETHODIMP CBDDemuxer::get_MarkerCount(long *pMarkerCount) { CheckPointer(pMarkerCount, E_POINTER); CheckPointer(m_pTitle, E_UNEXPECTED); *pMarkerCount = (long)m_pTitle->chapter_count; return S_OK; } STDMETHODIMP CBDDemuxer::get_CurrentMarker(long *pCurrentMarker) { CheckPointer(pCurrentMarker, E_POINTER); CheckPointer(m_pBD, E_UNEXPECTED); *pCurrentMarker = bd_get_current_chapter(m_pBD) + 1; return E_FAIL; } STDMETHODIMP CBDDemuxer::GetMarkerTime(long MarkerNum, double *pMarkerTime) { CheckPointer(pMarkerTime, E_POINTER); // Chapters go by a 1-based index, doh unsigned int index = MarkerNum - 1; if (index >= m_pTitle->chapter_count) { return E_FAIL; } REFERENCE_TIME rt = Convert90KhzToDSTime(m_pTitle->chapters[index].start); *pMarkerTime = (double)rt / DSHOW_TIME_BASE; return S_OK; } STDMETHODIMP CBDDemuxer::GetMarkerName(long MarkerNum, BSTR *pbstrMarkerName) { CheckPointer(pbstrMarkerName, E_POINTER); // Chapters go by a 1-based index, doh unsigned int index = MarkerNum - 1; if (index >= m_pTitle->chapter_count) { return E_FAIL; } // Get the title, or generate one OLECHAR wTitle[128]; swprintf_s(wTitle, L"Chapter %d", MarkerNum); *pbstrMarkerName = SysAllocString(wTitle); return S_OK; } ================================================ FILE: demuxer/Demuxers/BDDemuxer.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "BaseDemuxer.h" #include "LAVFDemuxer.h" class CBDDemuxer : public CBaseDemuxer , public IAMExtendedSeeking { public: CBDDemuxer(CCritSec *pLock, ILAVFSettingsInternal *pSettings); ~CBDDemuxer(void); // IUnknown DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // IDispatch STDMETHODIMP GetTypeInfoCount(UINT *pctinfo) { return E_NOTIMPL; } STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo **pptinfo) { return E_NOTIMPL; } STDMETHODIMP GetIDsOfNames(REFIID riid, OLECHAR **rgszNames, UINT cNames, LCID lcid, DISPID *rgdispid) { return E_NOTIMPL; } STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pdispparams, VARIANT *pvarResult, EXCEPINFO *pexcepinfo, UINT *puArgErr) { return E_NOTIMPL; } // CBaseDemuxer STDMETHODIMP Open(LPCOLESTR pszFileName, LPCOLESTR pszUserAgent = NULL, LPCOLESTR pszReferrer = NULL); STDMETHODIMP Start(); REFERENCE_TIME GetDuration() const; STDMETHODIMP GetNextPacket(Packet **ppPacket) { return m_lavfDemuxer->GetNextPacket(ppPacket); } STDMETHODIMP Seek(REFERENCE_TIME rTime); STDMETHODIMP Reset() { return E_NOTIMPL; } const char *GetContainerFormat() const; virtual DWORD GetContainerFlags() { return LAVFMT_TS_DISCONT | LAVFMT_TS_DISCONT_NO_DOWNSTREAM; } CStreamList *GetStreams(StreamType type) { if (m_lavfDemuxer) return m_lavfDemuxer->GetStreams(type); else return __super::GetStreams(type); } HRESULT SetActiveStream(StreamType type, int pid) { if (m_lavfDemuxer) { m_lavfDemuxer->SetActiveStream(type, pid); return S_OK; } else return E_FAIL; } void SettingsChanged(ILAVFSettingsInternal *pSettings) { if (m_lavfDemuxer) m_lavfDemuxer->SettingsChanged(pSettings); } STDMETHODIMP_(DWORD) GetStreamFlags(DWORD dwStream) { if (m_lavfDemuxer) return m_lavfDemuxer->GetStreamFlags(dwStream); return 0; } STDMETHODIMP_(int) GetPixelFormat(DWORD dwStream) { if (m_lavfDemuxer) return m_lavfDemuxer->GetPixelFormat(dwStream); return AV_PIX_FMT_NONE; } STDMETHODIMP_(int) GetHasBFrames(DWORD dwStream) { if (m_lavfDemuxer) return m_lavfDemuxer->GetHasBFrames(dwStream); return -1; } const stream *SelectVideoStream() { return m_lavfDemuxer->SelectVideoStream(); } const stream *SelectAudioStream(std::list prefLanguages) { return m_lavfDemuxer->SelectAudioStream(prefLanguages); } const stream *SelectSubtitleStream(std::list subtitleSelectors, std::string audioLanguage) { return m_lavfDemuxer->SelectSubtitleStream(subtitleSelectors, audioLanguage); } STDMETHODIMP SetTitle(int idx); /*STDMETHODIMP GetTitleInfo(int idx, REFERENCE_TIME *rtDuration, WCHAR **ppszName); STDMETHODIMP GetNumTitles(int *count);*/ // IAMExtendedSeeking STDMETHODIMP get_ExSeekCapabilities(long *pExCapabilities); STDMETHODIMP get_MarkerCount(long *pMarkerCount); STDMETHODIMP get_CurrentMarker(long *pCurrentMarker); STDMETHODIMP GetMarkerTime(long MarkerNum, double *pMarkerTime); STDMETHODIMP GetMarkerName(long MarkerNum, BSTR *pbstrMarkerName); STDMETHODIMP put_PlaybackSpeed(double Speed) { return E_NOTIMPL; } STDMETHODIMP get_PlaybackSpeed(double *pSpeed) { return E_NOTIMPL; } void ProcessBluRayMetadata(); STDMETHODIMP ProcessPacket(Packet *pPacket); STDMETHODIMP FillMVCExtensionQueue(REFERENCE_TIME rtBase); private: void ProcessClipInfo(struct clpi_cl *clpi, bool overwrite); void ProcessBDEvents(); void CloseMVCExtensionDemuxer(); STDMETHODIMP OpenMVCExtensionDemuxer(int playItem); static int BDByteStreamRead(void *opaque, uint8_t *buf, int buf_size); static int64_t CBDDemuxer::BDByteStreamSeek(void *opaque, int64_t offset, int whence); private: BLURAY *m_pBD = nullptr; AVIOContext *m_pb = nullptr; char m_cBDRootPath[4096] = {0}; ILAVFSettingsInternal *m_pSettings = nullptr; CLAVFDemuxer *m_lavfDemuxer = nullptr; BLURAY_TITLE_INFO *m_pTitle = nullptr; uint32_t m_nTitleCount = 0; uint16_t *m_StreamClip = nullptr; uint16_t m_NewClip = 0; REFERENCE_TIME *m_rtOffset = nullptr; REFERENCE_TIME m_rtNewOffset = 0; int64_t m_bNewOffsetPos = 0; BOOL m_MVCPlayback = FALSE; int m_MVCExtensionSubPathIndex = 0; int m_MVCExtensionClip = -1; AVFormatContext *m_MVCFormatContext = nullptr; int m_MVCStreamIndex = -1; BOOL m_EndOfStreamPacketFlushProtection = FALSE; }; ================================================ FILE: demuxer/Demuxers/BaseDemuxer.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "BaseDemuxer.h" #include "moreuuids.h" CBaseDemuxer::CBaseDemuxer(LPCTSTR pName, CCritSec *pLock) : CUnknown(pName, nullptr) , m_pLock(pLock) { for (int i = 0; i < unknown; ++i) { m_dActiveStreams[i] = -1; } } void CBaseDemuxer::CreateNoSubtitleStream() { stream s; s.pid = NO_SUBTITLE_PID; s.streamInfo = new CStreamInfo(); s.language = "und"; // Create the media type CMediaType mtype; mtype.majortype = MEDIATYPE_Subtitle; mtype.subtype = MEDIASUBTYPE_UTF8; mtype.formattype = FORMAT_SubtitleInfo; SUBTITLEINFO *subInfo = (SUBTITLEINFO *)mtype.AllocFormatBuffer(sizeof(SUBTITLEINFO)); memset(subInfo, 0, mtype.FormatLength()); wcscpy_s(subInfo->TrackName, NO_SUB_STRING); strcpy_s(subInfo->IsoLang, "und"); subInfo->dwOffset = sizeof(SUBTITLEINFO); s.streamInfo->mtypes.push_back(mtype); // Append it to the list m_streams[subpic].push_back(s); } void CBaseDemuxer::CreatePGSForcedSubtitleStream() { stream s; s.pid = FORCED_SUBTITLE_PID; s.streamInfo = new CStreamInfo(); s.language = "und"; // Create the media type CMediaType mtype; mtype.majortype = MEDIATYPE_Subtitle; mtype.subtype = MEDIASUBTYPE_HDMVSUB; mtype.formattype = FORMAT_SubtitleInfo; SUBTITLEINFO *subInfo = (SUBTITLEINFO *)mtype.AllocFormatBuffer(sizeof(SUBTITLEINFO)); memset(subInfo, 0, mtype.FormatLength()); wcscpy_s(subInfo->TrackName, FORCED_SUB_STRING); subInfo->dwOffset = sizeof(SUBTITLEINFO); s.streamInfo->mtypes.push_back(mtype); // Append it to the list m_streams[subpic].push_back(s); } // CStreamList const WCHAR *CBaseDemuxer::CStreamList::ToStringW(int type) { return type == video ? L"Video" : type == audio ? L"Audio" : type == subpic ? L"Subtitle" : L"Unknown"; } const CHAR *CBaseDemuxer::CStreamList::ToString(int type) { return type == video ? "Video" : type == audio ? "Audio" : type == subpic ? "Subtitle" : "Unknown"; } CBaseDemuxer::stream *CBaseDemuxer::CStreamList::FindStream(DWORD pid) { std::deque::iterator it; for (it = begin(); it != end(); ++it) { if ((*it).pid == pid) { return &(*it); } } return nullptr; } void CBaseDemuxer::CStreamList::Clear() { std::deque::iterator it; for (it = begin(); it != end(); ++it) { delete (*it).streamInfo; } __super::clear(); } CBaseDemuxer::stream *CBaseDemuxer::FindStream(DWORD pid) { for (int i = 0; i < StreamType::unknown; i++) { stream *pStream = m_streams[i].FindStream(pid); if (pStream) return pStream; } return nullptr; } ================================================ FILE: demuxer/Demuxers/BaseDemuxer.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #include "StreamInfo.h" #include "Packet.h" #include "IMediaSideDataFFmpeg.h" #define DSHOW_TIME_BASE 10000000 // DirectShow times are in 100ns units #define NO_SUBTITLE_PID DWORD_MAX #define FORCED_SUBTITLE_PID (NO_SUBTITLE_PID - 1) #define NO_SUB_STRING L"No subtitles" #define FORCED_SUB_STRING L"Forced Subtitles (auto)" struct ILAVFSettingsInternal; typedef struct CSubtitleSelector { std::string audioLanguage; std::string subtitleLanguage; std::string subtitleTrackName; #define SUBTITLE_FLAG_DEFAULT 0x0001 #define SUBTITLE_FLAG_FORCED 0x0002 #define SUBTITLE_FLAG_NORMAL 0x0004 #define SUBTITLE_FLAG_IMPAIRED 0x0008 #define SUBTITLE_FLAG_VIRTUAL 0x0080 // Values above 0xFF are special #define SUBTITLE_FLAG_PGS 0x8000 DWORD dwFlagsSet; DWORD dwFlagsNot; } CSubtitleSelector; class CBaseDemuxer : public CUnknown { public: enum StreamType { video, audio, subpic, unknown }; typedef struct stream { CStreamInfo *streamInfo; DWORD pid; std::string language; std::string trackName; LCID lcid; MediaSideDataFFMpeg SideData; struct stream() { streamInfo = nullptr; pid = 0; lcid = 0; memset(&SideData, 0, sizeof(SideData)); } operator DWORD() const { return pid; } bool operator==(const struct stream &s) const { return (DWORD) * this == (DWORD)s; } } stream; DECLARE_IUNKNOWN // Demuxing Methods (pure virtual) // Open the file virtual STDMETHODIMP Open(LPCOLESTR pszFileName, LPCOLESTR pszUserAgent = NULL, LPCOLESTR pszReferrer = NULL) = 0; // Start the demuxer virtual STDMETHODIMP Start() { return E_NOTIMPL; } // Abort opening the file virtual STDMETHODIMP AbortOpening(int mode = 1, int timeout = 0) { return E_NOTIMPL; } // Get Duration virtual REFERENCE_TIME GetDuration() const = 0; // Get the next packet from the file virtual STDMETHODIMP GetNextPacket(Packet **ppPacket) = 0; // Seek to the given position virtual STDMETHODIMP Seek(REFERENCE_TIME rTime) = 0; // Reset the demuxer, start reading at position 0 virtual STDMETHODIMP Reset() = 0; // Get the container format virtual const char *GetContainerFormat() const = 0; // Get Container Flags #define LAVFMT_TS_DISCONT 0x0001 #define LAVFMT_TS_DISCONT_NO_DOWNSTREAM 0x0002 virtual DWORD GetContainerFlags() { return 0; } // Select the active title virtual STDMETHODIMP SetTitle(int idx) { return E_NOTIMPL; } // Query the active title virtual STDMETHODIMP_(int) GetTitle() { return 0; } // Get Title Info virtual STDMETHODIMP GetTitleInfo(int idx, REFERENCE_TIME *rtDuration, WCHAR **ppszName) { return E_NOTIMPL; } // Title count virtual STDMETHODIMP_(int) GetNumTitles() { return 0; } // Set the currently active stream of one type // The demuxers can use this to filter packets before returning back to the caller on GetNextPacket // This functionality is optional however, so the caller should not rely on only receiving packets // for active streams. virtual HRESULT SetActiveStream(StreamType type, int pid) { m_dActiveStreams[type] = pid; return S_OK; } // Called when the settings of the splitter change virtual void SettingsChanged(ILAVFSettingsInternal *pSettings){}; virtual STDMETHODIMP_(DWORD) GetStreamFlags(DWORD dwStream) { return 0; } virtual STDMETHODIMP_(int) GetPixelFormat(DWORD dwStream) { return AV_PIX_FMT_NONE; } virtual STDMETHODIMP_(int) GetHasBFrames(DWORD dwStream) { return -1; } virtual STDMETHODIMP GetSideData(DWORD dwStream, GUID guidType, const BYTE **pData, size_t *pSize) { return E_NOTIMPL; } public: class CStreamList : public std::deque { public: ~CStreamList() { Clear(); } static const WCHAR *ToStringW(int type); static const CHAR *ToString(int type); stream *FindStream(DWORD pid); void Clear(); }; stream *FindStream(DWORD pid); protected: CBaseDemuxer(LPCTSTR pName, CCritSec *pLock); void CreateNoSubtitleStream(); void CreatePGSForcedSubtitleStream(); public: // Get the StreamList of the corresponding type virtual CStreamList *GetStreams(StreamType type) { return &m_streams[type]; } // Select the best video stream virtual const stream *SelectVideoStream() = 0; // Select the best audio stream virtual const stream *SelectAudioStream(std::list prefLanguages) = 0; // Select the best subtitle stream virtual const stream *SelectSubtitleStream(std::list subtitleSelectors, std::string audioLanguage) = 0; protected: CCritSec *m_pLock = nullptr; CStreamList m_streams[unknown]; int m_dActiveStreams[unknown]; }; ================================================ FILE: demuxer/Demuxers/Demuxers.vcxproj ================================================  Debug Win32 Debug x64 Release Win32 Release x64 {E2012DB5-33CB-44A7-B521-04287F6D0D80} Win32Proj Demuxers StaticLibrary true Unicode StaticLibrary false true Unicode demuxersd demuxers WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions) WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions) Create {e8a3f6fa-ae1c-4c8e-a0b6-9c8480324eaa} {0a058024-41f4-4509-97d2-803a1806ce86} ================================================ FILE: demuxer/Demuxers/Demuxers.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files ================================================ FILE: demuxer/Demuxers/ExtradataParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "ExtradataParser.h" #define MARKER \ if (BitRead(1) != 1) \ { \ ASSERT(0); \ return 0; \ } CExtradataParser::CExtradataParser(BYTE *pExtradata, size_t extra_len) : CByteParser(pExtradata, extra_len) { } CExtradataParser::~CExtradataParser() { } bool CExtradataParser::NextMPEGStartCode(BYTE &code) { BitByteAlign(); DWORD dw = (DWORD)-1; do { if (!Remaining()) return false; dw = (dw << 8) | (BYTE)BitRead(8); } while ((dw & 0xffffff00) != 0x00000100); code = (BYTE)(dw & 0xff); return true; } size_t CExtradataParser::ParseMPEGSequenceHeader(BYTE *pTarget) { BYTE id = 0; while (Remaining() && id != 0xb3) { if (!NextMPEGStartCode(id)) { return 0; } } if (id != 0xb3) { return 0; } size_t shpos = Pos() - 4; BitRead(12); // Width BitRead(12); // Height BitRead(4); // AR BitRead(4); // FPS BitRead(18); // Bitrate MARKER; BitRead(10); // VBV BitRead(1); // Constrained Flag // intra quantisizer matrix if (BitRead(1)) { for (uint8_t i = 0; i < 64; i++) { BitRead(8); } } // non-intra quantisizer matrix if (BitRead(1)) { for (uint8_t i = 0; i < 64; i++) { BitRead(8); } } size_t shlen = Pos() - shpos; size_t shextpos = 0; size_t shextlen = 0; if (NextMPEGStartCode(id) && id == 0xb5) { // sequence header ext shextpos = Pos() - 4; int startcode = BitRead(4); // Start Code Id; TODO: DIfferent start code ids mean different length of da2a ASSERT(startcode == 1); BitRead(1); // Profile Level Escape BitRead(3); // Profile BitRead(4); // Level BitRead(1); // Progressive BitRead(2); // Chroma BitRead(2); // Width Extension BitRead(2); // Height Extension BitRead(12); // Bitrate Extension MARKER; BitRead(8); // VBV Buffer Size Extension BitRead(1); // Low Delay BitRead(2); // FPS Extension n BitRead(5); // FPS Extension d shextlen = Pos() - shextpos; } memcpy(pTarget, Start() + shpos, shlen); if (shextpos) { memcpy(pTarget + shlen, Start() + shextpos, shextlen); } return shlen + shextlen; } ================================================ FILE: demuxer/Demuxers/ExtradataParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "byteparser.h" class CExtradataParser : protected CByteParser { public: CExtradataParser(BYTE *pExtradata, size_t extra_len); ~CExtradataParser(); size_t ParseMPEGSequenceHeader(BYTE *pTarget); private: bool NextMPEGStartCode(BYTE &code); }; ================================================ FILE: demuxer/Demuxers/LAVFAudioHelper.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #include "stdafx.h" #include "moreuuids.h" #include "BaseDemuxer.h" #include "LAVFAudioHelper.h" #include "LAVFUtils.h" #include "ExtradataParser.h" #include CLAVFAudioHelper g_AudioHelper; // Map codec ids to media subtypes // clang-format off static FormatMapping audio_map[] = { { AV_CODEC_ID_AC3, &MEDIASUBTYPE_DOLBY_AC3, WAVE_FORMAT_DOLBY_AC3, nullptr }, { AV_CODEC_ID_AAC, &MEDIASUBTYPE_AAC, WAVE_FORMAT_AAC, nullptr }, { AV_CODEC_ID_AAC_LATM, &MEDIASUBTYPE_LATM_AAC, WAVE_FORMAT_LATM_AAC, nullptr }, { AV_CODEC_ID_DTS, &MEDIASUBTYPE_WAVE_DTS, 0, nullptr }, { AV_CODEC_ID_EAC3, &MEDIASUBTYPE_DOLBY_DDPLUS, 0, nullptr }, { AV_CODEC_ID_TRUEHD, &MEDIASUBTYPE_DOLBY_TRUEHD, 0, nullptr }, { AV_CODEC_ID_MLP, &MEDIASUBTYPE_MLP, WAVE_FORMAT_MLP, nullptr }, { AV_CODEC_ID_VORBIS, &MEDIASUBTYPE_Vorbis2, 0, &FORMAT_VorbisFormat2 }, { AV_CODEC_ID_MP1, &MEDIASUBTYPE_MPEG1AudioPayload, WAVE_FORMAT_MPEG, nullptr }, { AV_CODEC_ID_MP2, &MEDIASUBTYPE_MPEG2_AUDIO, WAVE_FORMAT_MPEG, nullptr }, { AV_CODEC_ID_MP3, &MEDIASUBTYPE_MP3, WAVE_FORMAT_MPEGLAYER3, nullptr }, { AV_CODEC_ID_PCM_BLURAY, &MEDIASUBTYPE_BD_LPCM_AUDIO, 0, nullptr }, { AV_CODEC_ID_PCM_DVD, &MEDIASUBTYPE_DVD_LPCM_AUDIO, 0, nullptr }, { AV_CODEC_ID_PCM_S16LE, &MEDIASUBTYPE_PCM, WAVE_FORMAT_PCM, nullptr }, { AV_CODEC_ID_PCM_S24LE, &MEDIASUBTYPE_PCM, WAVE_FORMAT_PCM, nullptr }, { AV_CODEC_ID_PCM_S32LE, &MEDIASUBTYPE_PCM, WAVE_FORMAT_PCM, nullptr }, { AV_CODEC_ID_PCM_F32LE, &MEDIASUBTYPE_IEEE_FLOAT, WAVE_FORMAT_IEEE_FLOAT, nullptr }, { AV_CODEC_ID_PCM_S16LE_PLANAR, &MEDIASUBTYPE_PCM, WAVE_FORMAT_PCM, nullptr }, { AV_CODEC_ID_PCM_S24LE_PLANAR, &MEDIASUBTYPE_PCM, WAVE_FORMAT_PCM, nullptr }, { AV_CODEC_ID_PCM_S32LE_PLANAR, &MEDIASUBTYPE_PCM, WAVE_FORMAT_PCM, nullptr }, { AV_CODEC_ID_WMAV1, &MEDIASUBTYPE_MSAUDIO1, WAVE_FORMAT_MSAUDIO1, nullptr }, { AV_CODEC_ID_WMAV2, &MEDIASUBTYPE_WMAUDIO2, WAVE_FORMAT_WMAUDIO2, nullptr }, { AV_CODEC_ID_WMAPRO, &MEDIASUBTYPE_WMAUDIO3, WAVE_FORMAT_WMAUDIO3, nullptr }, { AV_CODEC_ID_ADPCM_IMA_AMV, &MEDIASUBTYPE_IMA_AMV, 0, nullptr }, { AV_CODEC_ID_FLAC, &MEDIASUBTYPE_FLAC_FRAMED, WAVE_FORMAT_FLAC, nullptr }, { AV_CODEC_ID_COOK, &MEDIASUBTYPE_COOK, WAVE_FORMAT_COOK, nullptr }, { AV_CODEC_ID_SIPR, &MEDIASUBTYPE_SIPR, WAVE_FORMAT_SIPR, nullptr }, { AV_CODEC_ID_RA_288, &MEDIASUBTYPE_28_8, WAVE_FORMAT_28_8, nullptr }, { AV_CODEC_ID_RA_144, &MEDIASUBTYPE_14_4, WAVE_FORMAT_14_4, nullptr }, { AV_CODEC_ID_RALF, &MEDIASUBTYPE_RALF, WAVE_FORMAT_RALF, nullptr }, { AV_CODEC_ID_ALAC, &MEDIASUBTYPE_ALAC, 0, nullptr }, { AV_CODEC_ID_MP4ALS, &MEDIASUBTYPE_ALS, 0, nullptr }, { AV_CODEC_ID_OPUS, &MEDIASUBTYPE_OPUS, WAVE_FORMAT_OPUS, nullptr }, { AV_CODEC_ID_NELLYMOSER, &MEDIASUBTYPE_NELLYMOSER, 0, nullptr }, { AV_CODEC_ID_PCM_ALAW, &MEDIASUBTYPE_ALAW, WAVE_FORMAT_ALAW, nullptr }, { AV_CODEC_ID_PCM_MULAW, &MEDIASUBTYPE_MULAW, WAVE_FORMAT_MULAW, nullptr }, { AV_CODEC_ID_GSM_MS, &MEDIASUBTYPE_MSGSM610, WAVE_FORMAT_GSM610, nullptr }, { AV_CODEC_ID_ADPCM_MS, &MEDIASUBTYPE_ADPCM_MS, WAVE_FORMAT_ADPCM, nullptr }, { AV_CODEC_ID_TRUESPEECH, &MEDIASUBTYPE_TRUESPEECH, WAVE_FORMAT_DSPGROUP_TRUESPEECH, nullptr }, { AV_CODEC_ID_TAK, &MEDIASUBTYPE_TAK, 0, nullptr }, { AV_CODEC_ID_S302M, &MEDIASUBTYPE_AES3, 0, nullptr }, { AV_CODEC_ID_PCM_S16BE, &MEDIASUBTYPE_PCM_TWOS, 0, nullptr }, { AV_CODEC_ID_PCM_S16BE_PLANAR, &MEDIASUBTYPE_PCM_TWOS, 0, nullptr }, { AV_CODEC_ID_PCM_S24BE, &MEDIASUBTYPE_PCM_IN24, 0, nullptr }, { AV_CODEC_ID_PCM_S32BE, &MEDIASUBTYPE_PCM_IN32, 0, nullptr }, { AV_CODEC_ID_QDM2, &MEDIASUBTYPE_QDM2, WAVE_FORMAT_QDESIGN_MUSIC, nullptr }, { AV_CODEC_ID_ATRAC1, &MEDIASUBTYPE_ATRC, WAVE_FORMAT_ATRC, nullptr }, { AV_CODEC_ID_ATRAC3, &MEDIASUBTYPE_ATRC, WAVE_FORMAT_ATRC, nullptr }, { AV_CODEC_ID_ATRAC3P, &MEDIASUBTYPE_ATRAC3P, WAVE_FORMAT_ATRAC3P, nullptr }, { AV_CODEC_ID_DSD_LSBF, &MEDIASUBTYPE_DSDL, 0, nullptr }, { AV_CODEC_ID_DSD_MSBF, &MEDIASUBTYPE_DSDM, 0, nullptr }, { AV_CODEC_ID_DSD_LSBF_PLANAR, &MEDIASUBTYPE_DSD1, 0, nullptr }, { AV_CODEC_ID_DSD_MSBF_PLANAR, &MEDIASUBTYPE_DSD8, 0, nullptr }, }; // clang-format on CMediaType CLAVFAudioHelper::initAudioType(AVCodecParameters *codecpar, unsigned int &codecTag, std::string container) { CMediaType mediaType; mediaType.InitMediaType(); mediaType.majortype = MEDIATYPE_Audio; mediaType.subtype = FOURCCMap(codecTag); mediaType.formattype = FORMAT_WaveFormatEx; // default value mediaType.SetSampleSize(256000); // Check against values from the map above for (unsigned i = 0; i < countof(audio_map); ++i) { if (audio_map[i].codec == codecpar->codec_id) { if (audio_map[i].subtype) mediaType.subtype = *audio_map[i].subtype; if (audio_map[i].codecTag) codecTag = audio_map[i].codecTag; if (audio_map[i].format) mediaType.formattype = *audio_map[i].format; break; } } // special cases switch (codecpar->codec_id) { case AV_CODEC_ID_PCM_F64LE: // Qt PCM if (codecTag == MKTAG('f', 'l', '6', '4')) mediaType.subtype = MEDIASUBTYPE_PCM_FL64_le; break; } return mediaType; } WAVEFORMATEX *CLAVFAudioHelper::CreateWVFMTEX(const AVStream *avstream, ULONG *size) { WAVEFORMATEX *wvfmt = (WAVEFORMATEX *)CoTaskMemAlloc(sizeof(WAVEFORMATEX) + avstream->codecpar->extradata_size); if (!wvfmt) return nullptr; memset(wvfmt, 0, sizeof(WAVEFORMATEX)); wvfmt->wFormatTag = avstream->codecpar->codec_tag; wvfmt->nChannels = avstream->codecpar->ch_layout.nb_channels ? avstream->codecpar->ch_layout.nb_channels : 2; wvfmt->nSamplesPerSec = avstream->codecpar->sample_rate ? avstream->codecpar->sample_rate : 48000; wvfmt->nAvgBytesPerSec = (DWORD)(avstream->codecpar->bit_rate / 8); if (avstream->codecpar->codec_id == AV_CODEC_ID_AAC || avstream->codecpar->codec_id == AV_CODEC_ID_AAC_LATM) { wvfmt->wBitsPerSample = 0; wvfmt->nBlockAlign = 1; } else { wvfmt->wBitsPerSample = get_bits_per_sample(avstream->codecpar); if (avstream->codecpar->block_align > 0) { wvfmt->nBlockAlign = avstream->codecpar->block_align; } else { if (wvfmt->wBitsPerSample == 0) { DbgOutString(L"BitsPerSample is 0, no good!"); } wvfmt->nBlockAlign = (WORD)(wvfmt->nChannels * av_get_bytes_per_sample((AVSampleFormat)avstream->codecpar->format)); } } if (!wvfmt->nAvgBytesPerSec) wvfmt->nAvgBytesPerSec = (wvfmt->nSamplesPerSec * wvfmt->nChannels * wvfmt->wBitsPerSample) >> 3; if (avstream->codecpar->extradata_size > 0) { wvfmt->cbSize = avstream->codecpar->extradata_size; memcpy((BYTE *)wvfmt + sizeof(WAVEFORMATEX), avstream->codecpar->extradata, avstream->codecpar->extradata_size); } *size = sizeof(WAVEFORMATEX) + avstream->codecpar->extradata_size; return wvfmt; } WAVEFORMATEXFFMPEG *CLAVFAudioHelper::CreateWVFMTEX_FF(const AVStream *avstream, ULONG *size) { WAVEFORMATEX *wvfmt = CreateWVFMTEX(avstream, size); if (!wvfmt) return nullptr; const size_t diff_size = sizeof(WAVEFORMATEXFFMPEG) - sizeof(WAVEFORMATEX); WAVEFORMATEXFFMPEG *wfex_ff = (WAVEFORMATEXFFMPEG *)CoTaskMemAlloc(diff_size + *size); if (!wfex_ff) return nullptr; memset(wfex_ff, 0, sizeof(WAVEFORMATEXFFMPEG)); memcpy(&wfex_ff->wfex, wvfmt, *size); wfex_ff->nCodecId = avstream->codecpar->codec_id; CoTaskMemFree(wvfmt); *size = sizeof(WAVEFORMATEXFFMPEG) + wfex_ff->wfex.cbSize; return wfex_ff; } WAVEFORMATEXFFMPEG *CLAVFAudioHelper::CreateWFMTEX_RAW_PCM_FF(const AVStream *avstream, ULONG *size, const GUID subtype, ULONG *samplesize) { WAVEFORMATEXTENSIBLE *wvfmt = CreateWFMTEX_RAW_PCM(avstream, size, subtype, samplesize); if (!wvfmt) return nullptr; const size_t diff_size = sizeof(WAVEFORMATEXFFMPEG) - sizeof(WAVEFORMATEX); WAVEFORMATEXFFMPEG *wfex_ff = (WAVEFORMATEXFFMPEG *)CoTaskMemAlloc(diff_size + *size); if (!wfex_ff) return nullptr; memset(wfex_ff, 0, sizeof(WAVEFORMATEXFFMPEG)); memcpy(&wfex_ff->wfex, wvfmt, *size); wfex_ff->nCodecId = avstream->codecpar->codec_id; CoTaskMemFree(wvfmt); *size = sizeof(WAVEFORMATEXFFMPEG) + wfex_ff->wfex.cbSize; return wfex_ff; } WAVEFORMATEX_HDMV_LPCM *CLAVFAudioHelper::CreateWVFMTEX_LPCM(const AVStream *avstream, ULONG *size) { WAVEFORMATEX *wvfmt = CreateWVFMTEX(avstream, size); WAVEFORMATEX_HDMV_LPCM *lpcm = (WAVEFORMATEX_HDMV_LPCM *)CoTaskMemAlloc(sizeof(WAVEFORMATEX_HDMV_LPCM)); memset(lpcm, 0, sizeof(WAVEFORMATEX_HDMV_LPCM)); memcpy(lpcm, wvfmt, sizeof(WAVEFORMATEX)); lpcm->cbSize = sizeof(WAVEFORMATEX_HDMV_LPCM) - sizeof(WAVEFORMATEX); BYTE channel_conf = 0; if (avstream->codecpar->ch_layout.order == AV_CHANNEL_ORDER_NATIVE) { switch (avstream->codecpar->ch_layout.u.mask) { case AV_CH_LAYOUT_MONO: channel_conf = 1; break; case AV_CH_LAYOUT_STEREO: channel_conf = 3; break; case AV_CH_LAYOUT_SURROUND: channel_conf = 4; break; case AV_CH_LAYOUT_2_1: channel_conf = 5; break; case AV_CH_LAYOUT_4POINT0: channel_conf = 6; break; case AV_CH_LAYOUT_2_2: channel_conf = 7; break; case AV_CH_LAYOUT_5POINT0: channel_conf = 8; break; case AV_CH_LAYOUT_5POINT1: channel_conf = 9; break; case AV_CH_LAYOUT_7POINT0: channel_conf = 10; break; case AV_CH_LAYOUT_7POINT1: channel_conf = 11; break; default: channel_conf = 0; } } lpcm->channel_conf = channel_conf; CoTaskMemFree(wvfmt); *size = sizeof(WAVEFORMATEX_HDMV_LPCM); return lpcm; } WAVEFORMATEXTENSIBLE *CLAVFAudioHelper::CreateWFMTEX_RAW_PCM(const AVStream *avstream, ULONG *size, const GUID subtype, ULONG *samplesize) { WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE)); if (!wfex) return nullptr; memset(wfex, 0, sizeof(*wfex)); WAVEFORMATEX *wfe = &wfex->Format; wfe->wFormatTag = (WORD)subtype.Data1; wfe->nChannels = avstream->codecpar->ch_layout.nb_channels; wfe->nSamplesPerSec = avstream->codecpar->sample_rate; if (avstream->codecpar->format == AV_SAMPLE_FMT_S32 && avstream->codecpar->bits_per_raw_sample > 0) { wfe->wBitsPerSample = avstream->codecpar->bits_per_raw_sample > 24 ? 32 : (avstream->codecpar->bits_per_raw_sample > 16 ? 24 : 16); } else { wfe->wBitsPerSample = av_get_bytes_per_sample((AVSampleFormat)avstream->codecpar->format) << 3; } wfe->nBlockAlign = wfe->nChannels * wfe->wBitsPerSample / 8; wfe->nAvgBytesPerSec = wfe->nSamplesPerSec * wfe->nBlockAlign; bool bUseExtensible = false; DWORD dwChannelMask = 0; if (wfe->nChannels > 2) { bUseExtensible = true; if (avstream->codecpar->ch_layout.order == AV_CHANNEL_ORDER_NATIVE) dwChannelMask = (DWORD)avstream->codecpar->ch_layout.u.mask; if (!dwChannelMask) { AVChannelLayout Layout{}; av_channel_layout_default(&Layout, wfe->nChannels); dwChannelMask = (DWORD)Layout.u.mask; } if (dwChannelMask && av_popcount(dwChannelMask) != wfe->nChannels) dwChannelMask = 0; } else if ((wfe->wBitsPerSample > 16 || wfe->nSamplesPerSec > 48000) && wfe->nChannels <= 2) { bUseExtensible = true; dwChannelMask = wfe->nChannels == 2 ? (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT) : SPEAKER_FRONT_CENTER; } if (bUseExtensible) { wfex->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; wfex->Format.cbSize = sizeof(*wfex) - sizeof(wfex->Format); wfex->dwChannelMask = dwChannelMask; if (avstream->codecpar->format == AV_SAMPLE_FMT_S32 && avstream->codecpar->bits_per_raw_sample > 0) { wfex->Samples.wValidBitsPerSample = avstream->codecpar->bits_per_raw_sample; } else { wfex->Samples.wValidBitsPerSample = wfex->Format.wBitsPerSample; } wfex->SubFormat = subtype; *size = sizeof(WAVEFORMATEXTENSIBLE); } else { *size = sizeof(WAVEFORMATEX); } *samplesize = wfe->wBitsPerSample * wfe->nChannels / 8; return wfex; } MPEG1WAVEFORMAT *CLAVFAudioHelper::CreateMP1WVFMT(const AVStream *avstream, ULONG *size) { WAVEFORMATEX *wvfmt = CreateWVFMTEX(avstream, size); if (!wvfmt) return nullptr; MPEG1WAVEFORMAT *mpwvfmt = (MPEG1WAVEFORMAT *)CoTaskMemAlloc(sizeof(MPEG1WAVEFORMAT)); if (!mpwvfmt) return nullptr; memset(mpwvfmt, 0, sizeof(MPEG1WAVEFORMAT)); memcpy(&mpwvfmt->wfx, wvfmt, sizeof(WAVEFORMATEX)); mpwvfmt->dwHeadBitrate = (DWORD)avstream->codecpar->bit_rate; mpwvfmt->fwHeadMode = avstream->codecpar->ch_layout.nb_channels == 1 ? ACM_MPEG_SINGLECHANNEL : ACM_MPEG_DUALCHANNEL; mpwvfmt->fwHeadLayer = (avstream->codecpar->codec_id == AV_CODEC_ID_MP1) ? ACM_MPEG_LAYER1 : ACM_MPEG_LAYER2; if (avstream->codecpar->sample_rate == 0) { avstream->codecpar->sample_rate = 48000; } mpwvfmt->wfx.wFormatTag = WAVE_FORMAT_MPEG; mpwvfmt->wfx.nBlockAlign = WORD((avstream->codecpar->codec_id == AV_CODEC_ID_MP1) ? (12 * avstream->codecpar->bit_rate / avstream->codecpar->sample_rate) * 4 : 144 * avstream->codecpar->bit_rate / avstream->codecpar->sample_rate); mpwvfmt->wfx.cbSize = sizeof(MPEG1WAVEFORMAT) - sizeof(WAVEFORMATEX); CoTaskMemFree(wvfmt); *size = sizeof(MPEG1WAVEFORMAT); return mpwvfmt; } VORBISFORMAT *CLAVFAudioHelper::CreateVorbis(const AVStream *avstream, ULONG *size) { VORBISFORMAT *vfmt = (VORBISFORMAT *)CoTaskMemAlloc(sizeof(VORBISFORMAT)); if (!vfmt) return nullptr; memset(vfmt, 0, sizeof(VORBISFORMAT)); vfmt->nChannels = avstream->codecpar->ch_layout.nb_channels; vfmt->nSamplesPerSec = avstream->codecpar->sample_rate; vfmt->nAvgBitsPerSec = (DWORD)avstream->codecpar->bit_rate; vfmt->nMinBitsPerSec = vfmt->nMaxBitsPerSec = (DWORD)-1; *size = sizeof(VORBISFORMAT); return vfmt; } VORBISFORMAT2 *CLAVFAudioHelper::CreateVorbis2(const AVStream *avstream, ULONG *size) { BYTE *p = avstream->codecpar->extradata; std::vector sizes; // read the number of blocks, and then the sizes of the individual blocks for (BYTE n = *p++; n > 0; n--) { int size = 0; // Xiph Lacing do { size += *p; } while (*p++ == 0xFF); sizes.push_back(size); } int totalsize = 0; for (unsigned int i = 0; i < sizes.size(); i++) totalsize += sizes[i]; // Get the size of the last block sizes.push_back(avstream->codecpar->extradata_size - (int)(p - avstream->codecpar->extradata) - totalsize); totalsize += sizes[sizes.size() - 1]; // 3 blocks is the currently valid Vorbis format if (sizes.size() == 3) { VORBISFORMAT2 *pvf2 = (VORBISFORMAT2 *)CoTaskMemAlloc(sizeof(VORBISFORMAT2) + totalsize); if (!pvf2) return nullptr; memset(pvf2, 0, sizeof(VORBISFORMAT2)); pvf2->Channels = avstream->codecpar->ch_layout.nb_channels; pvf2->SamplesPerSec = avstream->codecpar->sample_rate; pvf2->BitsPerSample = get_bits_per_sample(avstream->codecpar); BYTE *p2 = (BYTE *)pvf2 + sizeof(VORBISFORMAT2); for (unsigned int i = 0; i < sizes.size(); p += sizes[i], p2 += sizes[i], i++) { memcpy(p2, p, pvf2->HeaderSize[i] = sizes[i]); } *size = sizeof(VORBISFORMAT2) + totalsize; return pvf2; } *size = 0; return nullptr; } ================================================ FILE: demuxer/Demuxers/LAVFAudioHelper.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #pragma once #include "dvdmedia.h" #include "moreuuids.h" // clang-format off const AVCodecTag mp_wav_tags[] = { { AV_CODEC_ID_WAVPACK, 0x5756 }, { AV_CODEC_ID_TTA, 0x77A1 }, { AV_CODEC_ID_ADPCM_4XM, MKTAG('4', 'X', 'M', 'A')}, { AV_CODEC_ID_ADPCM_ADX, MKTAG('S', 'a', 'd', 'x')}, { AV_CODEC_ID_ADPCM_EA, MKTAG('A', 'D', 'E', 'A')}, { AV_CODEC_ID_ADPCM_EA_MAXIS_XA, MKTAG('A', 'D', 'X', 'A')}, { AV_CODEC_ID_ADPCM_IMA_WS, MKTAG('A', 'I', 'W', 'S')}, { AV_CODEC_ID_ADPCM_THP, MKTAG('T', 'H', 'P', 'A')}, { AV_CODEC_ID_ADPCM_XA, MKTAG('P', 'S', 'X', 'A')}, { AV_CODEC_ID_AMR_NB, MKTAG('n', 'b', 0, 0)}, { AV_CODEC_ID_BINKAUDIO_DCT, MKTAG('B', 'A', 'U', '1')}, { AV_CODEC_ID_BINKAUDIO_RDFT, MKTAG('B', 'A', 'U', '2')}, { AV_CODEC_ID_COOK, MKTAG('c', 'o', 'o', 'k')}, { AV_CODEC_ID_DSICINAUDIO, MKTAG('D', 'C', 'I', 'A')}, { AV_CODEC_ID_EAC3, MKTAG('E', 'A', 'C', '3')}, { AV_CODEC_ID_INTERPLAY_DPCM, MKTAG('I', 'N', 'P', 'A')}, { AV_CODEC_ID_MLP, MKTAG('M', 'L', 'P', ' ')}, { AV_CODEC_ID_MP1, 0x50}, { AV_CODEC_ID_MP4ALS, MKTAG('A', 'L', 'S', ' ')}, { AV_CODEC_ID_MUSEPACK7, MKTAG('M', 'P', 'C', ' ')}, { AV_CODEC_ID_MUSEPACK8, MKTAG('M', 'P', 'C', '8')}, { AV_CODEC_ID_NELLYMOSER, MKTAG('N', 'E', 'L', 'L')}, { AV_CODEC_ID_QCELP, MKTAG('Q', 'c', 'l', 'p')}, { AV_CODEC_ID_QDM2, MKTAG('Q', 'D', 'M', '2')}, { AV_CODEC_ID_RA_144, MKTAG('1', '4', '_', '4')}, { AV_CODEC_ID_RA_288, MKTAG('2', '8', '_', '8')}, { AV_CODEC_ID_ROQ_DPCM, MKTAG('R', 'o', 'Q', 'A')}, { AV_CODEC_ID_SHORTEN, MKTAG('s', 'h', 'r', 'n')}, { AV_CODEC_ID_SPEEX, MKTAG('s', 'p', 'x', ' ')}, { AV_CODEC_ID_TWINVQ, MKTAG('T', 'W', 'I', '2')}, { AV_CODEC_ID_WESTWOOD_SND1, MKTAG('S', 'N', 'D', '1')}, { AV_CODEC_ID_XAN_DPCM, MKTAG('A', 'x', 'a', 'n')}, { AV_CODEC_ID_MP4ALS, MKTAG('A', 'L', 'S', ' ')}, { AV_CODEC_ID_NONE, 0} }; // clang-format on const struct AVCodecTag *const mp_wav_taglists[] = {avformat_get_riff_audio_tags(), mp_wav_tags, 0}; class CLAVFAudioHelper { public: CLAVFAudioHelper(){}; CMediaType initAudioType(AVCodecParameters *codecpar, unsigned int &codecTag, std::string container); WAVEFORMATEX *CreateWVFMTEX(const AVStream *avstream, ULONG *size); WAVEFORMATEXFFMPEG *CreateWVFMTEX_FF(const AVStream *avstream, ULONG *size); WAVEFORMATEX_HDMV_LPCM *CreateWVFMTEX_LPCM(const AVStream *avstream, ULONG *size); WAVEFORMATEXTENSIBLE *CreateWFMTEX_RAW_PCM(const AVStream *avstream, ULONG *size, const GUID subtype, ULONG *samplesize); WAVEFORMATEXFFMPEG *CreateWFMTEX_RAW_PCM_FF(const AVStream *avstream, ULONG *size, const GUID subtype, ULONG *samplesize); MPEG1WAVEFORMAT *CreateMP1WVFMT(const AVStream *avstream, ULONG *size); VORBISFORMAT *CreateVorbis(const AVStream *avstream, ULONG *size); VORBISFORMAT2 *CreateVorbis2(const AVStream *avstream, ULONG *size); }; extern CLAVFAudioHelper g_AudioHelper; ================================================ FILE: demuxer/Demuxers/LAVFDemuxer.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVFDemuxer.h" #include "LAVFUtils.h" #include "LAVFStreamInfo.h" #include "ILAVPinInfo.h" #include "LAVFVideoHelper.h" #include "ExtradataParser.h" #include "IMediaSideDataFFmpeg.h" #include "LAVSplitterSettingsInternal.h" #include "moreuuids.h" extern "C" { typedef struct CodecMime { char str[32]; enum AVCodecID id; } CodecMime; #include "libavformat/mpegts.h" #include "libavformat/matroska.h" #include "libavutil/avstring.h" enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags); #include "libavformat/isom.h" #include "libavformat/demux.h" } #ifdef DEBUG #include "lavf_log.h" #endif #include "BDDemuxer.h" #include "CueSheet.h" #define AVFORMAT_OPEN_TIMEOUT 20 extern void lavf_get_iformat_infos(const AVInputFormat *pFormat, const char **pszName, const char **pszDescription); static const AVRational AV_RATIONAL_TIMEBASE = {1, AV_TIME_BASE}; std::set CLAVFDemuxer::GetFormatList() { std::set formats; const AVInputFormat *f = nullptr; void *state = NULL; while (f = av_demuxer_iterate(&state)) { FormatInfo format; lavf_get_iformat_infos(f, &format.strName, &format.strDescription); if (format.strName) formats.insert(format); } return formats; } CLAVFDemuxer::CLAVFDemuxer(CCritSec *pLock, ILAVFSettingsInternal *settings) : CBaseDemuxer(L"lavf demuxer", pLock) { #ifdef DEBUG DbgSetModuleLevel(LOG_CUSTOM1, DWORD_MAX); // FFMPEG messages use custom1 av_log_set_callback(lavf_log_callback); #else av_log_set_callback(nullptr); #endif m_bSubStreams = settings->GetSubstreamsEnabled(); m_pSettings = settings; WCHAR fileName[1024]; GetModuleFileName(nullptr, fileName, 1024); const WCHAR *file = PathFindFileName(fileName); if (_wcsicmp(file, L"zplayer.exe") == 0) { m_bEnableTrackInfo = FALSE; // TrackInfo is only properly handled in ZoomPlayer 8.0.0.74 and above DWORD dwVersionSize = GetFileVersionInfoSize(fileName, nullptr); if (dwVersionSize > 0) { void *versionInfo = CoTaskMemAlloc(dwVersionSize); if (!versionInfo) return; GetFileVersionInfo(fileName, 0, dwVersionSize, versionInfo); VS_FIXEDFILEINFO *info; unsigned cbInfo; BOOL bInfoPresent = VerQueryValue(versionInfo, TEXT("\\"), (LPVOID *)&info, &cbInfo); if (bInfoPresent) { bInfoPresent = bInfoPresent; uint64_t version = info->dwFileVersionMS; version <<= 32; version += info->dwFileVersionLS; if (version >= 0x000800000000004A) m_bEnableTrackInfo = TRUE; } CoTaskMemFree(versionInfo); } } } CLAVFDemuxer::~CLAVFDemuxer() { CleanupAVFormat(); SAFE_DELETE(m_pFontInstaller); } STDMETHODIMP CLAVFDemuxer::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; return QI(IKeyFrameInfo) m_bEnableTrackInfo && QI(ITrackInfo) QI2(IAMExtendedSeeking) QI2(IAMMediaContent) QI(IPropertyBag) QI(IDSMResourceBag) __super::NonDelegatingQueryInterface(riid, ppv); } ///////////////////////////////////////////////////////////////////////////// // Demuxer Functions STDMETHODIMP CLAVFDemuxer::Open(LPCOLESTR pszFileName, LPCOLESTR pszUserAgent, LPCOLESTR pszReferrer) { return OpenInputStream(nullptr, pszFileName, nullptr, TRUE, false, pszUserAgent, pszReferrer); } STDMETHODIMP CLAVFDemuxer::Start() { if (m_bH264MVCCombine) { CMediaType *pmt = m_pSettings->GetOutputMediatype(m_nH264MVCBaseStream); if (pmt) { if (pmt->subtype != MEDIASUBTYPE_AMVC && pmt->subtype != MEDIASUBTYPE_MVC1) { DbgLog( (LOG_TRACE, 10, L"CLAVFDemuxer::Start(): Disabling MVC demuxing, downstream did not select an appropriate type")); m_bH264MVCCombine = FALSE; m_nH264MVCBaseStream = -1; m_nH264MVCExtensionStream = -1; } } } if (m_avFormat) av_read_play(m_avFormat); return S_OK; } STDMETHODIMP CLAVFDemuxer::AbortOpening(int mode, int timeout) { m_Abort = mode; m_timeAbort = timeout ? time(nullptr) + timeout : 0; return S_OK; } int CLAVFDemuxer::avio_interrupt_cb(void *opaque) { CLAVFDemuxer *demux = (CLAVFDemuxer *)opaque; // Check for file opening timeout time_t now = time(nullptr); if (demux->m_timeOpening && now > (demux->m_timeOpening + AVFORMAT_OPEN_TIMEOUT)) return 1; if (demux->m_Abort && now > demux->m_timeAbort) return 1; return 0; } static LPCWSTR wszImageExtensions[] = { L".png", L".mng", L".pns", // PNG L".tif", L".tiff", // TIFF L".jpeg", L".jpg", L".jps", // JPEG L".tga", // TGA L".bmp", // BMP L".j2c", // JPEG2000 L".webp", // WebP }; static LPCWSTR wszBlockedExtensions[] = {L".ifo", L".bup"}; static std::pair rtmpParametersTranslate[] = { std::make_pair("app", "rtmp_app"), std::make_pair("buffer", "rtmp_buffer"), std::make_pair("conn", "rtmp_conn"), std::make_pair("flashVer", "rtmp_flashver"), std::make_pair("rtmp_flush_interval", "rtmp_flush_interval"), std::make_pair("live", "rtmp_live"), std::make_pair("pageUrl", "rtmp_pageurl"), std::make_pair("playpath", "rtmp_playpath"), std::make_pair("subscribe", "rtmp_subscribe"), std::make_pair("swfHash", "rtmp_swfhash"), std::make_pair("swfSize", "rtmp_swfsize"), std::make_pair("swfUrl", "rtmp_swfurl"), std::make_pair("swfVfy", "rtmp_swfverify"), std::make_pair("tcUrl", "rtmp_tcurl")}; STDMETHODIMP CLAVFDemuxer::OpenInputStream(AVIOContext *byteContext, LPCOLESTR pszFileName, const char *format, BOOL bForce, BOOL bFileSource, LPCOLESTR pszUserAgent, LPCOLESTR pszReferrer) { CAutoLock lock(m_pLock); HRESULT hr = S_OK; int ret; // return code from avformat functions // Convert the filename from wchar to char for avformat char *fileName = NULL; if (pszFileName) fileName = CoTaskGetMultiByteFromWideChar(CP_UTF8, 0, pszFileName, -1); if (fileName == NULL) { fileName = (char *)CoTaskMemAlloc(1); *fileName = 0; } // handle pipe, we only support stdin pipes if (_strnicmp("pipe://", fileName, 7) == 0) { // convert pipe://stdin to pipe:0 fileName[5] = '0'; fileName[6] = 0; } if (_strnicmp("mms:", fileName, 4) == 0) { memmove(fileName + 1, fileName, strlen(fileName)); memcpy(fileName, "mmsh", 4); } // replace "icyx" protocol by http if (_strnicmp("icyx:", fileName, 5) == 0) { memcpy(fileName, "http", 4); } char *rtmp_prameters = nullptr; const char *rtsp_transport = nullptr; // check for rtsp transport protocol options if (_strnicmp("rtsp", fileName, 4) == 0) { if (_strnicmp("rtspu:", fileName, 6) == 0) { rtsp_transport = "udp"; } else if (_strnicmp("rtspm:", fileName, 6) == 0) { rtsp_transport = "udp_multicast"; } else if (_strnicmp("rtspt:", fileName, 6) == 0) { rtsp_transport = "tcp"; } else if (_strnicmp("rtsph:", fileName, 6) == 0) { rtsp_transport = "http"; } // replace "rtsp[u|m|t|h]" protocol by rtsp if (rtsp_transport != nullptr) { memmove(fileName + 4, fileName + 5, strlen(fileName) - 4); } } else if (_strnicmp("rtmp", fileName, 4) == 0) { rtmp_prameters = strchr(fileName, ' '); if (rtmp_prameters) { *rtmp_prameters = '\0'; // Trim not supported part form fileName } } AVIOInterruptCB cb = {avio_interrupt_cb, this}; trynoformat: // Create the avformat_context m_avFormat = avformat_alloc_context(); m_avFormat->pb = byteContext; m_avFormat->interrupt_callback = cb; if (m_avFormat->pb) m_avFormat->flags |= AVFMT_FLAG_CUSTOM_IO; LPWSTR extension = pszFileName ? PathFindExtensionW(pszFileName) : nullptr; const AVInputFormat *inputFormat = nullptr; if (format) { inputFormat = av_find_input_format(format); } else if (pszFileName) { LPWSTR extension = PathFindExtensionW(pszFileName); for (int i = 0; i < countof(wszImageExtensions); i++) { if (_wcsicmp(extension, wszImageExtensions[i]) == 0) { if (byteContext) { inputFormat = av_find_input_format("image2pipe"); } else { inputFormat = av_find_input_format("image2"); } break; } } if (byteContext == nullptr || bFileSource) { for (int i = 0; i < countof(wszBlockedExtensions); i++) { if (_wcsicmp(extension, wszBlockedExtensions[i]) == 0) { goto done; } } } } // Disable loading of external mkv segments, if required if (!m_pSettings->GetLoadMatroskaExternalSegments()) m_avFormat->flags |= AVFMT_FLAG_NOEXTERNAL; // demuxer/protocol options AVDictionary *options = nullptr; av_dict_set(&options, "icy", "1", 0); // request ICY metadata av_dict_set(&options, "advanced_editlist", "0", 0); // disable broken mov editlist handling av_dict_set(&options, "reconnect", "1", 0); // for http, reconnect if we get disconnected av_dict_set(&options, "skip_clear", "1", 0); // mpegts program handling av_dict_set(&options, "max_reload", "7", 0); // playlist reloading for HLS av_dict_set(&options, "extension_picky", "0", 0); // less strict HLS parsing if (pszUserAgent) { char *strUserAgent = CoTaskGetMultiByteFromWideChar(CP_UTF8, 0, pszUserAgent, -1); if (strUserAgent && *strUserAgent) // if valid, and non-empty av_dict_set(&options, "user_agent", strUserAgent, 0); SAFE_CO_FREE(strUserAgent); } if (pszReferrer != NULL) { char *strReferrer = CoTaskGetMultiByteFromWideChar(CP_UTF8, 0, pszReferrer, -1); if (strReferrer && *strReferrer) // if valid, and non-empty av_dict_set(&options, "referer", strReferrer, 0); SAFE_CO_FREE(strReferrer); } else { av_dict_set(&options, "referer", fileName, 0); // for http, send self as referer if none was specified explicitly } if (rtsp_transport != nullptr) { av_dict_set(&options, "rtsp_transport", rtsp_transport, 0); } if (rtmp_prameters != nullptr) { char buff[4100]; char *next_token = nullptr; bool bSwfVerify = false; strcpy_s(buff, rtmp_prameters + 1); const char *token = strtok_s(buff, " ", &next_token); while (token) { for (size_t i = 0; i < _countof(rtmpParametersTranslate); i++) { const size_t len = strlen(rtmpParametersTranslate[i].first); if (_strnicmp(token, rtmpParametersTranslate[i].first, len) == 0) { if (strlen(token) > len + 1 && token[len] == '=') { if (_strnicmp("swfVfy", rtmpParametersTranslate[i].first, len) == 0) { bSwfVerify = token[len + 1] == '1'; continue; } else if (_strnicmp("live", rtmpParametersTranslate[i].first, len) == 0) { if (token[len + 1] == '1') { av_dict_set(&options, rtmpParametersTranslate[i].second, "live", 0); } else if (token[len + 1] == '0') { av_dict_set(&options, rtmpParametersTranslate[i].second, "recorded", 0); } continue; } av_dict_set(&options, rtmpParametersTranslate[i].second, token + len + 1, 0); } } } token = strtok_s(nullptr, " ", &next_token); } if (bSwfVerify) { const AVDictionaryEntry *swfUrlEntry = av_dict_get(options, "rtmp_swfurl", nullptr, 0); if (swfUrlEntry) { av_dict_set(&options, "rtmp_swfverify", swfUrlEntry->value, 0); } } } m_timeOpening = time(nullptr); ret = avformat_open_input(&m_avFormat, fileName, inputFormat, &options); av_dict_free(&options); if (ret < 0) { DbgLog((LOG_ERROR, 0, TEXT("::OpenInputStream(): avformat_open_input failed (%d)"), ret)); if (format) { DbgLog((LOG_ERROR, 0, TEXT(" -> trying again without specific format"))); format = nullptr; avformat_close_input(&m_avFormat); goto trynoformat; } goto done; } DbgLog((LOG_TRACE, 10, TEXT("::OpenInputStream(): avformat_open_input opened file of type '%S' (took %I64d seconds)"), m_avFormat->iformat->name, time(nullptr) - m_timeOpening)); m_timeOpening = 0; CHECK_HR(hr = InitAVFormat(pszFileName, bForce)); SAFE_CO_FREE(fileName); return S_OK; done: CleanupAVFormat(); SAFE_CO_FREE(fileName); return E_FAIL; } void CLAVFDemuxer::AddMPEGTSStream(int pid, uint32_t stream_type) { if (m_avFormat) { int program = -1; if (m_avFormat->nb_programs > 0) { unsigned nb_streams = 0; for (unsigned i = 0; i < m_avFormat->nb_programs; i++) { if (m_avFormat->programs[i]->nb_stream_indexes > nb_streams) program = i; } } avpriv_mpegts_add_stream(m_avFormat, pid, stream_type, program >= 0 ? m_avFormat->programs[program]->id : -1); } } HRESULT CLAVFDemuxer::CheckBDM2TSCPLI(LPCOLESTR pszFileName) { size_t len = wcslen(pszFileName); if (len <= 23 || (_wcsnicmp(pszFileName + len - 23, L"\\BDMV\\STREAM\\", 13) != 0 && (len <= 28 || _wcsnicmp(pszFileName + len - 28, L"\\BDMV\\STREAM\\SSIF\\", 18) != 0))) return E_FAIL; // Get the base file name (should be a number, like 00000) const WCHAR *file = pszFileName + (len - 10); WCHAR basename[6]; wcsncpy_s(basename, file, 5); basename[5] = 0; // Convert to UTF-8 path size_t a_len = WideCharToMultiByte(CP_UTF8, 0, pszFileName, -1, nullptr, 0, nullptr, nullptr); a_len += 2; // one extra char because CLIPINF is 7 chars and STREAM is 6, and one for the terminating-zero char *path = (char *)CoTaskMemAlloc(a_len * sizeof(char)); if (!path) return E_OUTOFMEMORY; WideCharToMultiByte(CP_UTF8, 0, pszFileName, -1, path, (int)a_len, nullptr, nullptr); // Remove file name itself PathRemoveFileSpecA(path); // Remove SSIF if appropriate BOOL bSSIF = FALSE; if (_strnicmp(path + strlen(path) - 5, "\\SSIF", 5) == 0) { bSSIF = TRUE; PathRemoveFileSpecA(path); } // Remove STREAM folder PathRemoveFileSpecA(path); // Write new path sprintf_s(path + strlen(path), a_len - strlen(path), "\\CLIPINF\\%S.clpi", basename); CLPI_CL *cl = bd_read_clpi(path); if (!cl) return E_FAIL; // Clip Info was found, add the language metadata to the AVStreams for (unsigned i = 0; i < cl->program.num_prog; ++i) { CLPI_PROG *p = &cl->program.progs[i]; for (unsigned k = 0; k < p->num_streams; ++k) { CLPI_PROG_STREAM *s = &p->streams[k]; AVStream *avstream = GetAVStreamByPID(s->pid); if (avstream) { if (s->lang[0] != 0) av_dict_set(&avstream->metadata, "language", (const char *)s->lang, 0); } } } // Free the clip bd_free_clpi(cl); cl = nullptr; if (bSSIF) { uint32_t clip_id = _wtoi(basename); // Remove filename PathRemoveFileSpecA(path); // Remove CLIPINF PathRemoveFileSpecA(path); // Remove BDMV PathRemoveFileSpecA(path); BLURAY *bd = bd_open(path, nullptr); if (!bd) return S_FALSE; uint32_t nTitles = bd_get_titles(bd, TITLES_RELEVANT, 0); BOOL found = FALSE; for (uint32_t n = 0; n < nTitles && !found; n++) { BLURAY_TITLE_INFO *TitleInfo = bd_get_title_info(bd, n, 0); if (TitleInfo) { for (uint32_t i = 0; i < TitleInfo->clip_count; i++) { BLURAY_CLIP_INFO *Clip = &TitleInfo->clips[i]; if (Clip->idx == clip_id) { AVStream *avstream = nullptr; for (uint8_t c = 0; c < Clip->video_stream_count && !avstream; c++) { if (Clip->video_streams[c].coding_type == BLURAY_STREAM_TYPE_VIDEO_H264) avstream = GetAVStreamByPID(Clip->video_streams[c].pid); } if (avstream) av_dict_set(&avstream->metadata, "stereo_mode", TitleInfo->mvc_base_view_r_flag ? "mvc_rl" : "mvc_lr", 0); found = TRUE; break; } } bd_free_title_info(TitleInfo); } } bd_close(bd); } return S_OK; } inline static int init_parser(AVFormatContext *s, AVStream *st) { if (av_lav_stream_parser_get_needed(st) && !(s->flags & AVFMT_FLAG_NOPARSE)) { av_lav_stream_parser_init(st); } return 0; } void CLAVFDemuxer::UpdateParserFlags(AVStream *st) { int flags = av_lav_stream_parser_get_flags(st); if ((st->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO || st->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO) && _stricmp(m_pszInputFormat, "mpegvideo") != 0) { flags |= PARSER_FLAG_NO_TIMESTAMP_MANGLING; } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { flags |= PARSER_FLAG_NO_TIMESTAMP_MANGLING; } else if (st->codecpar->codec_id == AV_CODEC_ID_VC1) { if (m_bVC1Correction) { flags &= ~PARSER_FLAG_NO_TIMESTAMP_MANGLING; } else { flags |= PARSER_FLAG_NO_TIMESTAMP_MANGLING; } } av_lav_stream_parser_update_flags(st, flags); } static struct sCoverMimeTypes { AVCodecID codec; LPCWSTR mime; LPCWSTR ext; } CoverMimeTypes[] = { {AV_CODEC_ID_MJPEG, L"image/jpeg", L".jpg"}, {AV_CODEC_ID_PNG, L"image/png", L".png"}, {AV_CODEC_ID_GIF, L"image/gif", L".gif"}, {AV_CODEC_ID_BMP, L"image/bmp", L".bmp"}, {AV_CODEC_ID_TIFF, L"image/tiff", L".tiff"}, }; STDMETHODIMP CLAVFDemuxer::InitAVFormat(LPCOLESTR pszFileName, BOOL bForce) { HRESULT hr = S_OK; const char *format = nullptr; lavf_get_iformat_infos(m_avFormat->iformat, &format, nullptr); if (!bForce && (!format || !m_pSettings->IsFormatEnabled(format))) { DbgLog((LOG_TRACE, 20, L"::InitAVFormat() - format of type '%S' disabled, failing", format ? format : m_avFormat->iformat->name)); return E_FAIL; } m_pszInputFormat = format ? format : m_avFormat->iformat->name; m_bVC1SeenTimestamp = FALSE; LPWSTR extension = pszFileName ? PathFindExtensionW(pszFileName) : nullptr; m_bMatroska = (_strnicmp(m_pszInputFormat, "matroska", 8) == 0); m_bOgg = (_strnicmp(m_pszInputFormat, "ogg", 3) == 0); m_bAVI = (_strnicmp(m_pszInputFormat, "avi", 3) == 0); m_bMPEGTS = (_strnicmp(m_pszInputFormat, "mpegts", 6) == 0); m_bMPEGPS = (_stricmp(m_pszInputFormat, "mpeg") == 0); m_bRM = (_stricmp(m_pszInputFormat, "rm") == 0); m_bPMP = (_stricmp(m_pszInputFormat, "pmp") == 0); m_bMP4 = (_stricmp(m_pszInputFormat, "mp4") == 0); m_bTSDiscont = (m_avFormat->iformat->flags & AVFMT_TS_DISCONT) || m_bRM || (_stricmp(m_pszInputFormat, "dash") == 0); WCHAR szProt[24] = L"file"; if (pszFileName) { DWORD dwNumChars = 24; hr = UrlGetPart(pszFileName, szProt, &dwNumChars, URL_PART_SCHEME, 0); if (SUCCEEDED(hr) && dwNumChars && (_wcsicmp(szProt, L"file") != 0)) { m_avFormat->flags |= AVFMT_FLAG_NETWORK; DbgLog((LOG_TRACE, 10, TEXT("::InitAVFormat(): detected network protocol: %s"), szProt)); } } // TODO: make both durations below configurable // decrease analyze duration for network streams if (m_avFormat->flags & AVFMT_FLAG_NETWORK || (m_avFormat->flags & AVFMT_FLAG_CUSTOM_IO && !m_avFormat->pb->seekable)) { // require at least 0.2 seconds av_opt_set_int(m_avFormat, "analyzeduration", max(m_pSettings->GetNetworkStreamAnalysisDuration() * 1000, 200000), 0); } else { av_opt_set_int(m_avFormat, "analyzeduration", 7500000, 0); // And increase it for mpeg-ts/ps files if (m_bMPEGTS || m_bMPEGPS) { av_opt_set_int(m_avFormat, "analyzeduration", 30000000, 0); av_opt_set_int(m_avFormat, "probesize", 75000000, 0); } } av_opt_set_int(m_avFormat, "correct_ts_overflow", !m_pBluRay, 0); m_timeOpening = time(nullptr); int ret = avformat_find_stream_info(m_avFormat, nullptr); if (ret < 0) { DbgLog((LOG_ERROR, 0, TEXT("::InitAVFormat(): av_find_stream_info failed (%d)"), ret)); goto done; } DbgLog((LOG_TRACE, 10, TEXT("::InitAVFormat(): avformat_find_stream_info finished, took %I64d seconds"), time(nullptr) - m_timeOpening)); m_timeOpening = 0; // Check if this is a m2ts in a BD structure, and if it is, read some extra stream properties out of the CLPI files if (m_pBluRay) { m_pBluRay->ProcessBluRayMetadata(); } else if (pszFileName && m_bMPEGTS) { CheckBDM2TSCPLI(pszFileName); } char *icy_headers = nullptr; if (av_opt_get(m_avFormat, "icy_metadata_headers", AV_OPT_SEARCH_CHILDREN, (uint8_t **)&icy_headers) >= 0 && icy_headers && strlen(icy_headers) > 0) { std::string icyHeaders(icy_headers); std::stringstream icyHeaderStream(icyHeaders); std::string line; while (std::getline(icyHeaderStream, line)) { size_t seperatorIdx = line.find_first_of(":"); std::string token = line.substr(0, seperatorIdx); std::string value = line.substr(seperatorIdx + 1); if (_stricmp(token.c_str(), "icy-name") == 0) { // not entirely correct, but this way it gets exported through IAMMediaContent av_dict_set(&m_avFormat->metadata, "artist", value.c_str(), 0); } else if (_stricmp(token.c_str(), "icy-description") == 0) { av_dict_set(&m_avFormat->metadata, "comment", value.c_str(), 0); } else if (_stricmp(token.c_str(), "icy-genre") == 0) { av_dict_set(&m_avFormat->metadata, "genre", value.c_str(), 0); } } ParseICYMetadataPacket(); } av_freep(&icy_headers); SAFE_CO_FREE(m_stOrigParser); m_stOrigParser = (enum AVStreamParseType *)CoTaskMemAlloc(m_avFormat->nb_streams * sizeof(enum AVStreamParseType)); if (!m_stOrigParser) return E_OUTOFMEMORY; for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx) { AVStream *st = m_avFormat->streams[idx]; // Disable full stream parsing for these formats if (av_lav_stream_parser_get_needed(st) == AVSTREAM_PARSE_FULL) { if (st->codecpar->codec_id == AV_CODEC_ID_DVB_SUBTITLE) { av_lav_stream_parser_set_needed(st, AVSTREAM_PARSE_NONE); } } if (m_bOgg && st->codecpar->codec_id == AV_CODEC_ID_H264) { av_lav_stream_parser_set_needed(st, AVSTREAM_PARSE_FULL); } // Create the parsers with the appropriate flags init_parser(m_avFormat, st); UpdateParserFlags(st); #ifdef DEBUG AVProgram *streamProg = av_find_program_from_stream(m_avFormat, nullptr, idx); DbgLog((LOG_TRACE, 30, L"Stream %d (pid %d) - program: %d, codec: %S; parsing: %S;", idx, st->id, streamProg ? streamProg->pmt_pid : -1, avcodec_get_name(st->codecpar->codec_id), lavf_get_parsing_string(av_lav_stream_parser_get_needed(st)))); #endif m_stOrigParser[idx] = av_lav_stream_parser_get_needed(st); if ((st->codecpar->codec_id == AV_CODEC_ID_DTS && st->codecpar->codec_tag == 0xA2) || (st->codecpar->codec_id == AV_CODEC_ID_EAC3 && st->codecpar->codec_tag == 0xA1)) st->disposition |= LAVF_DISPOSITION_SECONDARY_AUDIO; UpdateSubStreams(); if (st->codecpar->codec_type == AVMEDIA_TYPE_ATTACHMENT) { const AVDictionaryEntry *attachFilename = av_dict_get(st->metadata, "filename", nullptr, 0); const AVDictionaryEntry *attachMimeType = av_dict_get(st->metadata, "mimetype", nullptr, 0); const AVDictionaryEntry *attachDescription = av_dict_get(st->metadata, "comment", nullptr, 0); if (attachFilename && attachMimeType) { LPWSTR chFilename = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachFilename->value, -1); LPWSTR chMimetype = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachMimeType->value, -1); LPWSTR chDescription = nullptr; if (attachDescription) chDescription = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachDescription->value, -1); if (chFilename && chMimetype) ResAppend(chFilename, chDescription, chMimetype, st->codecpar->extradata, (DWORD)st->codecpar->extradata_size); SAFE_CO_FREE(chFilename); SAFE_CO_FREE(chMimetype); SAFE_CO_FREE(chDescription); } else { DbgLog((LOG_TRACE, 10, L" -> Unknown attachment, missing filename or mimetype")); } // Try to guess the codec id for fonts only listed by name if (st->codecpar->codec_id == AV_CODEC_ID_NONE && attachFilename) { char *dot = strrchr(attachFilename->value, '.'); if (dot && !_stricmp(dot, ".ttf")) st->codecpar->codec_id = AV_CODEC_ID_TTF; else if (dot && !_stricmp(dot, ".otf")) st->codecpar->codec_id = AV_CODEC_ID_OTF; } if (st->codecpar->codec_id == AV_CODEC_ID_TTF || st->codecpar->codec_id == AV_CODEC_ID_OTF) { if (!m_pFontInstaller) { m_pFontInstaller = new CFontInstaller(); } m_pFontInstaller->InstallFont(st->codecpar->extradata, st->codecpar->extradata_size); } } else if (st->disposition & AV_DISPOSITION_ATTACHED_PIC && st->attached_pic.data && st->attached_pic.size > 0) { LPWSTR chFilename = nullptr; LPWSTR chMimeType = nullptr; LPWSTR chDescription = nullptr; // gather a filename const AVDictionaryEntry *attachFilename = av_dict_get(st->metadata, "filename", nullptr, 0); if (attachFilename) chFilename = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachFilename->value, -1); // gather a mimetype const AVDictionaryEntry *attachMimeType = av_dict_get(st->metadata, "mimetype", nullptr, 0); if (attachMimeType) chMimeType = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachMimeType->value, -1); // gather description const AVDictionaryEntry *attachDescription = av_dict_get(st->metadata, "comment", nullptr, 0); if (attachDescription) chDescription = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, attachDescription->value, -1); for (int c = 0; c < countof(CoverMimeTypes); c++) { if (CoverMimeTypes[c].codec == st->codecpar->codec_id) { if (chFilename == nullptr) { size_t size = wcslen(CoverMimeTypes[c].ext) + 15; chFilename = (LPWSTR)CoTaskMemAlloc(size * sizeof(wchar_t)); wcscpy_s(chFilename, size, L"EmbeddedCover"); wcscat_s(chFilename, size, CoverMimeTypes[c].ext); } if (chMimeType == nullptr) { size_t size = wcslen(CoverMimeTypes[c].mime) + 1; chMimeType = (LPWSTR)CoTaskMemAlloc(size * sizeof(wchar_t)); wcscpy_s(chMimeType, size, CoverMimeTypes[c].mime); } break; } } // Export embedded cover-art through IDSMResourceBag interface if (chFilename && chMimeType) { ResAppend(chFilename, chDescription, chMimeType, st->attached_pic.data, (DWORD)st->attached_pic.size); } else { DbgLog((LOG_TRACE, 10, L" -> Unknown attachment, missing filename or mimetype")); } SAFE_CO_FREE(chFilename); SAFE_CO_FREE(chMimeType); SAFE_CO_FREE(chDescription); } } if (AVDictionaryEntry *cue = av_dict_get(m_avFormat->metadata, "CUESHEET", nullptr, 0)) { CCueSheet cueSheet; if (SUCCEEDED(cueSheet.Parse(cue->value))) { // Metadata if (!cueSheet.m_Title.empty() && !av_dict_get(m_avFormat->metadata, "title", nullptr, 0)) av_dict_set(&m_avFormat->metadata, "title", cueSheet.m_Title.c_str(), 0); if (!cueSheet.m_Performer.empty() && !av_dict_get(m_avFormat->metadata, "artist", nullptr, 0)) av_dict_set(&m_avFormat->metadata, "artist", cueSheet.m_Performer.c_str(), 0); // Free old chapters while (m_avFormat->nb_chapters--) { av_dict_free(&m_avFormat->chapters[m_avFormat->nb_chapters]->metadata); av_freep(&m_avFormat->chapters[m_avFormat->nb_chapters]); } av_freep(&m_avFormat->chapters); m_avFormat->nb_chapters = 0; for (CCueSheet::Track track : cueSheet.m_Tracks) { avpriv_new_chapter(m_avFormat, track.index, AVRational{1, DSHOW_TIME_BASE}, track.Time, track.Time, cueSheet.FormatTrack(track).c_str()); } } } CHECK_HR(hr = CreateStreams()); return S_OK; done: CleanupAVFormat(); return E_FAIL; } void CLAVFDemuxer::CleanupAVFormat() { FlushMVCExtensionQueue(); if (m_avFormat) { // Override abort timer to ensure the close function in network protocols can actually close the stream AbortOpening(1, 5); avformat_close_input(&m_avFormat); } SAFE_CO_FREE(m_stOrigParser); } AVStream *CLAVFDemuxer::GetAVStreamByPID(int pid) { if (!m_avFormat) return nullptr; for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx) { if (m_avFormat->streams[idx]->id == pid && !(m_avFormat->streams[idx]->disposition & LAVF_DISPOSITION_SUB_STREAM)) return m_avFormat->streams[idx]; } return nullptr; } HRESULT CLAVFDemuxer::SetActiveStream(StreamType type, int pid) { HRESULT hr = S_OK; if (type == audio) UpdateForcedSubtitleStream(pid); hr = __super::SetActiveStream(type, pid); // Usually selecting an audio stream would set the forced substream (since it uses the audio stream language) // but in case there is no audio stream, do a fallback selection of any PGS stream here. if (type == subpic && pid == FORCED_SUBTITLE_PID && m_ForcedSubStream == -1) { std::list selectors; CSubtitleSelector selector; selector.audioLanguage = "*"; selector.subtitleLanguage = "*"; selector.dwFlagsSet = SUBTITLE_FLAG_PGS; selector.dwFlagsNot = 0; selectors.push_back(selector); const stream *subst = SelectSubtitleStream(selectors, ""); if (subst) m_ForcedSubStream = subst->pid; } for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx) { AVStream *st = m_avFormat->streams[idx]; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { st->discard = (m_dActiveStreams[video] == idx) ? AVDISCARD_DEFAULT : AVDISCARD_ALL; // don't discard h264 mvc streams if (m_bH264MVCCombine && st->codecpar->codec_id == AV_CODEC_ID_H264_MVC) st->discard = AVDISCARD_DEFAULT; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { st->discard = (m_dActiveStreams[audio] == idx) ? AVDISCARD_DEFAULT : AVDISCARD_ALL; // If the stream is a sub stream, make sure to activate the main stream as well if (m_bMPEGTS && (st->disposition & LAVF_DISPOSITION_SUB_STREAM) && st->discard == AVDISCARD_DEFAULT) { for (unsigned int idx2 = 0; idx2 < m_avFormat->nb_streams; ++idx2) { AVStream *mst = m_avFormat->streams[idx2]; if (mst->id == st->id) { mst->discard = AVDISCARD_DEFAULT; break; } } } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { st->discard = (m_dActiveStreams[subpic] == idx || (m_dActiveStreams[subpic] == FORCED_SUBTITLE_PID && m_ForcedSubStream == idx)) ? AVDISCARD_DEFAULT : AVDISCARD_ALL; } else { st->discard = AVDISCARD_ALL; } } return hr; } void CLAVFDemuxer::UpdateSubStreams() { for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx) { AVStream *st = m_avFormat->streams[idx]; // Find and flag the AC-3 substream if (m_bMPEGTS && st->codecpar->codec_id == AV_CODEC_ID_TRUEHD) { int id = st->id; AVStream *sub_st = nullptr; for (unsigned int i = 0; i < m_avFormat->nb_streams; ++i) { AVStream *sst = m_avFormat->streams[i]; if (idx != i && sst->id == id) { sub_st = sst; break; } } if (sub_st) { sub_st->disposition = st->disposition | LAVF_DISPOSITION_SUB_STREAM; av_dict_copy(&sub_st->metadata, st->metadata, 0); } } } } STDMETHODIMP CLAVFDemuxer::SetTitle(int idx) { if (!m_bMatroska) return E_NOTIMPL; av_mkv_set_next_edition(m_avFormat, idx); // Update duration AVEdition *editions = nullptr; av_mkv_get_editions(m_avFormat, &editions); m_avFormat->duration = editions[idx].duration; return S_OK; } STDMETHODIMP_(int) CLAVFDemuxer::GetTitle() { if (!m_bMatroska) return 0; return av_mkv_get_edition(m_avFormat); } STDMETHODIMP CLAVFDemuxer::GetTitleInfo(int idx, REFERENCE_TIME *rtDuration, WCHAR **ppszName) { if (!m_bMatroska) return E_NOTIMPL; AVEdition *editions = nullptr; av_mkv_get_editions(m_avFormat, &editions); AVEdition *current_edition = &editions[idx]; if (rtDuration) *rtDuration = av_rescale(current_edition->duration, DSHOW_TIME_BASE, AV_TIME_BASE); if (ppszName) { char *title = nullptr; int total_seconds = (int)(current_edition->duration / AV_TIME_BASE); int seconds = total_seconds % 60; int minutes = total_seconds / 60 % 60; int hours = total_seconds / 3600; if (current_edition->title) { title = av_asprintf("E: %s [%02d:%02d:%02d]", current_edition->title, hours, minutes, seconds); } else { title = av_asprintf("E: Edition %d [%02d:%02d:%02d]", idx + 1, hours, minutes, seconds); } *ppszName = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, title, -1); av_freep(&title); } return S_OK; } STDMETHODIMP_(int) CLAVFDemuxer::GetNumTitles() { if (!m_bMatroska || !m_avFormat || !m_avFormat->priv_data || !m_avFormat->iformat || strcmp(m_avFormat->iformat->name, "matroska") != 0) return 0; return av_mkv_get_num_editions(m_avFormat); } void CLAVFDemuxer::SettingsChanged(ILAVFSettingsInternal *pSettings) { int vc1Mode = pSettings->GetVC1TimestampMode(); if (vc1Mode == 1 || strcmp(m_pszInputFormat, "rawvideo") == 0) { m_bVC1Correction = true; } else if (vc1Mode == 2) { BOOL bReq = pSettings->IsVC1CorrectionRequired(); m_bVC1Correction = m_bMatroska ? !bReq : bReq; } else { m_bVC1Correction = false; } for (unsigned int idx = 0; idx < m_avFormat->nb_streams; ++idx) { AVStream *st = m_avFormat->streams[idx]; if (st->codecpar->codec_id == AV_CODEC_ID_VC1) { UpdateParserFlags(st); } else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { av_lav_stream_parser_set_needed(st, m_stOrigParser[idx]); } } m_bPGSNoParsing = !pSettings->GetPGSOnlyForced(); } REFERENCE_TIME CLAVFDemuxer::GetDuration() const { int64_t iLength = 0; if (m_avFormat->duration == (int64_t)AV_NOPTS_VALUE || m_avFormat->duration < 0LL) { // no duration is available for us // try to calculate it // TODO /*if (m_rtCurrent != Packet::INVALID_TIME && m_avFormat->file_size > 0 && m_avFormat->pb && m_avFormat->pb->pos > 0) { iLength = (((m_rtCurrent * m_avFormat->file_size) / m_avFormat->pb->pos) / 1000) & 0xFFFFFFFF; }*/ // DbgLog((LOG_ERROR, 1, TEXT("duration is not available"))); return -1; } else { iLength = m_avFormat->duration; } return ConvertTimestampToRT(iLength, 1, AV_TIME_BASE, 0); } #define VC1_CODE_RES0 0x00000100 #define IS_VC1_MARKER(x) (((x) & ~0xFF) == VC1_CODE_RES0) STDMETHODIMP CLAVFDemuxer::CreatePacketMediaType(Packet *pPacket, enum AVCodecID codec_id, BYTE *extradata, int extradata_size, BYTE *paramchange, int paramchange_size) { CMediaType *pmt = m_pSettings->GetOutputMediatype(pPacket->StreamId); if (pmt) { if (extradata && extradata_size) { if (codec_id == AV_CODEC_ID_H264) { MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->ReallocFormatBuffer(sizeof(MPEG2VIDEOINFO) + extradata_size); int ret = g_VideoHelper.ProcessH264Extradata(extradata, extradata_size, mp2vi, FALSE); if (ret < 0) { mp2vi->cbSequenceHeader = extradata_size; memcpy(&mp2vi->dwSequenceHeader[0], extradata, extradata_size); } else { int mp2visize = SIZE_MPEG2VIDEOINFO(mp2vi); memset((BYTE *)mp2vi + mp2visize, 0, pmt->cbFormat - mp2visize); } } else if (codec_id == AV_CODEC_ID_MPEG2VIDEO) { MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->ReallocFormatBuffer(sizeof(MPEG2VIDEOINFO) + extradata_size); CExtradataParser parser = CExtradataParser(extradata, extradata_size); mp2vi->cbSequenceHeader = (DWORD)parser.ParseMPEGSequenceHeader((BYTE *)&mp2vi->dwSequenceHeader[0]); } else if (codec_id == AV_CODEC_ID_VC1) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)pmt->ReallocFormatBuffer(sizeof(VIDEOINFOHEADER2) + extradata_size + 1); int i = 0; for (i = 0; i < (extradata_size - 4); i++) { uint32_t code = AV_RB32(extradata + i); if (IS_VC1_MARKER(code)) break; } if (i == 0) { *((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2)) = 0; memcpy((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2) + 1, extradata, extradata_size); } else { memcpy((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2), extradata, extradata_size); } } else if (codec_id == AV_CODEC_ID_ASS) { SUBTITLEINFO *sif = (SUBTITLEINFO *)pmt->ReallocFormatBuffer(sizeof(SUBTITLEINFO) + extradata_size); memcpy((BYTE *)sif + sizeof(SUBTITLEINFO), extradata, extradata_size); } else { if (pmt->formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER *vih = (VIDEOINFOHEADER *)pmt->ReallocFormatBuffer(sizeof(VIDEOINFOHEADER) + extradata_size); vih->bmiHeader.biSize = sizeof(BITMAPINFOHEADER) + extradata_size; memcpy((BYTE *)vih + sizeof(VIDEOINFOHEADER), extradata, extradata_size); } else if (pmt->formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)pmt->ReallocFormatBuffer(sizeof(VIDEOINFOHEADER2) + extradata_size); vih2->bmiHeader.biSize = sizeof(BITMAPINFOHEADER) + extradata_size; memcpy((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2), extradata, extradata_size); } else if (pmt->formattype == FORMAT_WaveFormatEx) { WAVEFORMATEX *wfex = (WAVEFORMATEX *)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEX) + extradata_size); wfex->cbSize = extradata_size; memcpy((BYTE *)wfex + sizeof(WAVEFORMATEX), extradata, extradata_size); } else if (pmt->formattype == FORMAT_WaveFormatExFFMPEG) { WAVEFORMATEXFFMPEG *wfex = (WAVEFORMATEXFFMPEG *)pmt->ReallocFormatBuffer(sizeof(WAVEFORMATEXFFMPEG) + extradata_size); wfex->wfex.cbSize = extradata_size; memcpy((BYTE *)wfex + sizeof(WAVEFORMATEXFFMPEG), extradata, extradata_size); } else if (pmt->formattype == FORMAT_VorbisFormat2) { BYTE *p = extradata; std::vector sizes; for (BYTE n = *p++; n > 0; n--) { int size = 0; // Xiph Lacing do { size += *p; } while (*p++ == 0xFF); sizes.push_back(size); } int totalsize = 0; for (size_t i = 0; i < sizes.size(); i++) totalsize += sizes[i]; sizes.push_back(extradata_size - (int)(p - extradata) - totalsize); totalsize += sizes[sizes.size() - 1]; // 3 blocks is the currently valid Vorbis format if (sizes.size() == 3) { VORBISFORMAT2 *pvf2 = (VORBISFORMAT2 *)pmt->ReallocFormatBuffer(sizeof(VORBISFORMAT2) + totalsize); BYTE *p2 = (BYTE *)pvf2 + sizeof(VORBISFORMAT2); for (unsigned int i = 0; i < sizes.size(); p += sizes[i], p2 += sizes[i], i++) { memcpy(p2, p, pvf2->HeaderSize[i] = sizes[i]); } } } else { DbgLog((LOG_TRACE, 10, L"::GetNextPacket() - Unsupported PMT change on codec %S", avcodec_get_name(codec_id))); } } } if (paramchange) { uint32_t flags = AV_RL32(paramchange); int channels = 0, sample_rate = 0, width = 0, height = 0, aspect_num = 0, aspect_den = 0; paramchange += 4; if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_COUNT) { channels = AV_RL32(paramchange); paramchange += 4; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_CHANNEL_LAYOUT) { paramchange += 8; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_SAMPLE_RATE) { sample_rate = AV_RL32(paramchange); paramchange += 4; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_DIMENSIONS) { width = AV_RL32(paramchange); height = AV_RL32(paramchange + 4); paramchange += 8; } if (flags & AV_SIDE_DATA_PARAM_CHANGE_ASPECTRATIO) { aspect_num = AV_RL32(paramchange); aspect_den = AV_RL32(paramchange + 4); paramchange += 8; } if (pmt->majortype == MEDIATYPE_Video) { if ((pmt->formattype == FORMAT_VideoInfo || pmt->formattype == FORMAT_MPEGVideo) && width && height) { VIDEOINFOHEADER *vih = (VIDEOINFOHEADER *)pmt->pbFormat; vih->bmiHeader.biWidth = width; vih->bmiHeader.biHeight = height; vih->rcTarget.right = vih->rcSource.right = width; vih->rcTarget.bottom = vih->rcSource.bottom = height; } else if ((pmt->formattype == FORMAT_VideoInfo2 || pmt->formattype == FORMAT_MPEG2Video) && ((width && height) || (aspect_num && aspect_den))) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)pmt->pbFormat; if (width && height) { vih2->bmiHeader.biWidth = width; vih2->bmiHeader.biHeight = height; vih2->rcTarget.right = vih2->rcSource.right = width; vih2->rcTarget.bottom = vih2->rcSource.bottom = height; } if (aspect_num && aspect_den) { int num = vih2->bmiHeader.biWidth, den = vih2->bmiHeader.biHeight; av_reduce(&num, &den, (int64_t)aspect_num * num, (int64_t)aspect_den * den, INT_MAX); vih2->dwPictAspectRatioX = num; vih2->dwPictAspectRatioY = den; } } } else if (pmt->majortype == MEDIATYPE_Audio) { if ((pmt->formattype == FORMAT_WaveFormatEx || pmt->formattype == FORMAT_WaveFormatExFFMPEG) && (channels || sample_rate)) { WAVEFORMATEX *wfex = nullptr; if (pmt->formattype == FORMAT_WaveFormatExFFMPEG) { WAVEFORMATEXFFMPEG *wfexff = (WAVEFORMATEXFFMPEG *)pmt->pbFormat; wfex = &wfexff->wfex; } else { wfex = (WAVEFORMATEX *)pmt->pbFormat; } if (channels) wfex->nChannels = channels; if (sample_rate) wfex->nSamplesPerSec = sample_rate; } } } if (pmt) { pPacket->pmt = CreateMediaType(pmt); SAFE_DELETE(pmt); } } return S_OK; } STDMETHODIMP CLAVFDemuxer::ParseICYMetadataPacket() { char *icy_data = nullptr; if (av_opt_get(m_avFormat, "icy_metadata_packet", AV_OPT_SEARCH_CHILDREN, (uint8_t **)&icy_data) >= 0 && icy_data && strlen(icy_data) > 0) { std::string icyData(icy_data); size_t idx = icyData.find("StreamTitle"); if (idx != std::string::npos) { // strip StreamTitle token and = std::string value = icyData.substr(idx + 12); idx = value.find_first_of(";"); if (idx != std::string::npos) value = value.substr(0, idx); if (value[0] == '\'' || value[0] == '"') value = value.substr(1); if (value[value.length() - 1] == '\'' || value[value.length() - 1] == '"') value = value.substr(0, value.length() - 1); if (value.length() > 0) { av_dict_set(&m_avFormat->metadata, "title", value.c_str(), 0); } } // clear value, and only read again when its send again av_opt_set(m_avFormat, "icy_metadata_packet", "", AV_OPT_SEARCH_CHILDREN); } av_freep(&icy_data); return S_OK; } STDMETHODIMP CLAVFDemuxer::GetNextPacket(Packet **ppPacket) { CheckPointer(ppPacket, E_POINTER); // If true, S_FALSE is returned, indicating a soft-failure bool bReturnEmpty = false; // Read packet AVPacket pkt; Packet *pPacket = nullptr; // assume we are not eof if (m_avFormat->pb) { m_avFormat->pb->eof_reached = 0; } int result = 0; try { DBG_TIMING("av_read_frame", 30, result = av_read_frame(m_avFormat, &pkt)) } catch (...) { // ignore.. } if (result == AVERROR(EINTR) || result == AVERROR(EAGAIN)) { // timeout, probably no real error, return empty packet bReturnEmpty = true; } else if (result == AVERROR_EOF) { DbgLog((LOG_TRACE, 10, L"::GetNextPacket(): End of File reached")); } else if (result < 0) { // meh, fail } else if (pkt.size <= 0 || pkt.stream_index < 0 || (unsigned)pkt.stream_index >= m_avFormat->nb_streams) { // XXX, in some cases ffmpeg returns a zero or negative packet size if (m_avFormat->pb && !m_avFormat->pb->eof_reached) { bReturnEmpty = true; } av_packet_unref(&pkt); } else { // Check right here if the stream is active, we can drop the package otherwise. AVStream *stream = m_avFormat->streams[pkt.stream_index]; BOOL streamActive = FALSE; BOOL forcedSubStream = FALSE; for (int i = 0; i < unknown; ++i) { if (m_dActiveStreams[i] == pkt.stream_index) { streamActive = TRUE; break; } } // Accept it if its the forced subpic stream if (m_dActiveStreams[subpic] == FORCED_SUBTITLE_PID && pkt.stream_index == m_ForcedSubStream) { forcedSubStream = streamActive = TRUE; } // Accept H264 MVC streams, as they get combined with the base stream later if (m_bH264MVCCombine && stream->codecpar->codec_id == AV_CODEC_ID_H264_MVC) streamActive = TRUE; if (!streamActive) { av_packet_unref(&pkt); return S_FALSE; } pPacket = new Packet(); if (!pPacket) return E_OUTOFMEMORY; // Convert timestamps to reference time and set them on the packet REFERENCE_TIME pts = ConvertTimestampToRT(pkt.pts, stream->time_base.num, stream->time_base.den); REFERENCE_TIME dts = ConvertTimestampToRT(pkt.dts, stream->time_base.num, stream->time_base.den); REFERENCE_TIME duration = ConvertTimestampToRT(pkt.duration, stream->time_base.num, stream->time_base.den, 0); pPacket->rtPTS = pts; pPacket->rtDTS = dts; pPacket->StreamId = (DWORD)pkt.stream_index; pPacket->bPosition = pkt.pos; if (stream->codecpar->codec_id == AV_CODEC_ID_H264) { if (m_bMatroska || m_bOgg) { if (!stream->codecpar->extradata_size || stream->codecpar->extradata[0] != 1 || AV_RB32(pkt.data) == 0x00000001) { pPacket->dwFlags |= LAV_PACKET_H264_ANNEXB; } else { // No DTS for H264 in native format dts = Packet::INVALID_TIME; } } else if (!m_bPMP && !m_bAVI) { // For most formats, DTS timestamps for h.264 are no fun dts = Packet::INVALID_TIME; } } if (m_bAVI && stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { // AVI's always have borked pts, specially if m_pFormatContext->flags includes // AVFMT_FLAG_GENPTS so always use dts pts = Packet::INVALID_TIME; } if (stream->codecpar->codec_id == AV_CODEC_ID_RV10 || stream->codecpar->codec_id == AV_CODEC_ID_RV20 || stream->codecpar->codec_id == AV_CODEC_ID_RV30 || stream->codecpar->codec_id == AV_CODEC_ID_RV40) { pts = Packet::INVALID_TIME; } // Never use DTS for these formats if (!m_bAVI && (stream->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO || stream->codecpar->codec_id == AV_CODEC_ID_MPEG1VIDEO)) dts = Packet::INVALID_TIME; if (pkt.data) { result = pPacket->SetPacket(&pkt); if (result < 0) { SAFE_DELETE(pPacket); return E_OUTOFMEMORY; } } // Select the appropriate timestamps REFERENCE_TIME rt = Packet::INVALID_TIME; // Try the different times set, pts first, dts when pts is not valid if (pts != Packet::INVALID_TIME) { rt = pts; } else if (dts != Packet::INVALID_TIME) { rt = dts; } if (stream->codecpar->codec_id == AV_CODEC_ID_VC1) { if (m_bMatroska && m_bVC1Correction) { rt = pts; if (!m_bVC1SeenTimestamp) { if (rt == Packet::INVALID_TIME && dts != Packet::INVALID_TIME) rt = dts; m_bVC1SeenTimestamp = (pts != Packet::INVALID_TIME); } } else if (m_bVC1Correction) { rt = dts; pPacket->dwFlags |= LAV_PACKET_PARSED; } } else if (stream->codecpar->codec_id == AV_CODEC_ID_MOV_TEXT) { pPacket->dwFlags |= LAV_PACKET_MOV_TEXT; } // Mark the packet as parsed, so the forced subtitle parser doesn't hit it if (stream->codecpar->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE && m_bPGSNoParsing) { pPacket->dwFlags |= LAV_PACKET_PARSED; } pPacket->rtStart = pPacket->rtStop = rt; if (rt != Packet::INVALID_TIME) { pPacket->rtStop += (duration > 0 || stream->codecpar->codec_id == AV_CODEC_ID_TRUEHD) ? duration : 1; } if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { pPacket->bDiscontinuity = TRUE; if (forcedSubStream) { pPacket->dwFlags |= LAV_PACKET_FORCED_SUBTITLE; pPacket->dwFlags &= ~LAV_PACKET_PARSED; } if (stream->codecpar->codec_id == AV_CODEC_ID_SRT) { pPacket->dwFlags |= LAV_PACKET_SRT; } } if (stream->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE_PLANAR || stream->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE_PLANAR || stream->codecpar->codec_id == AV_CODEC_ID_PCM_S24LE_PLANAR || stream->codecpar->codec_id == AV_CODEC_ID_PCM_S32LE_PLANAR) pPacket->dwFlags |= LAV_PACKET_PLANAR_PCM; if (stream->codecpar->codec_id == AV_CODEC_ID_WEBVTT) { size_t id_size = 0, settings_size = 0; uint8_t *id = NULL, *settings = NULL; id = av_packet_get_side_data(&pkt, AV_PKT_DATA_WEBVTT_IDENTIFIER, &id_size); settings = av_packet_get_side_data(&pkt, AV_PKT_DATA_WEBVTT_SETTINGS, &settings_size); int text_size = pPacket->GetDataSize(); // allocate size for id/settings int pkt_size = text_size + (int)id_size + 2 + (int)settings_size + 2; pPacket->SetDataSize(pkt_size); uint8_t *data = pPacket->GetData(); // offset data memmove(data + id_size + 2 + settings_size + 2, data, text_size); // write id if (id && id_size > 0) memcpy(data, id, id_size); data[id_size + 0] = '\r'; data[id_size + 1] = '\n'; // write settings if (settings && settings_size > 0) memcpy(data + id_size + 2, settings, settings_size); data[id_size + 2 + settings_size + 0] = '\r'; data[id_size + 2 + settings_size + 1] = '\n'; } // Update extradata and send new mediatype, when required size_t sidedata_size = 0; uint8_t *sidedata = av_packet_get_side_data(&pkt, AV_PKT_DATA_NEW_EXTRADATA, &sidedata_size); size_t paramchange_size = 0; uint8_t *paramchange = av_packet_get_side_data(&pkt, AV_PKT_DATA_PARAM_CHANGE, ¶mchange_size); if ((sidedata && sidedata_size) || (paramchange && paramchange_size)) { CreatePacketMediaType(pPacket, stream->codecpar->codec_id, sidedata, (int)sidedata_size, paramchange, (int)paramchange_size); } pPacket->bSyncPoint = pkt.flags & AV_PKT_FLAG_KEY; pPacket->bDiscontinuity = !m_pBluRay && (pkt.flags & AV_PKT_FLAG_CORRUPT); #ifdef DEBUG if (pkt.flags & AV_PKT_FLAG_CORRUPT) DbgLog((LOG_TRACE, 10, L"::GetNextPacket() - Signaling Discontinuinty because of corrupt package")); #endif if (pPacket->rtStart != AV_NOPTS_VALUE) m_rtCurrent = pPacket->rtStart; av_packet_unref(&pkt); } if (m_pBluRay && pPacket) { HRESULT hr = m_pBluRay->ProcessPacket(pPacket); if (hr != S_OK) { SAFE_DELETE(pPacket); bReturnEmpty = bReturnEmpty || hr == S_FALSE; } } if (m_bH264MVCCombine && pPacket && pPacket->StreamId == m_nH264MVCExtensionStream) { if (FAILED(QueueMVCExtension(pPacket))) { SAFE_DELETE(pPacket); return E_FAIL; } return S_FALSE; } if (m_bH264MVCCombine && pPacket && pPacket->StreamId == m_nH264MVCBaseStream) { HRESULT hr = CombineMVCBaseExtension(pPacket); if (hr != S_OK) { SAFE_DELETE(pPacket); // S_FALSE indicates a skipped packet, not a hard failure if (hr == S_FALSE) bReturnEmpty = true; } } if (bReturnEmpty && !pPacket) { return S_FALSE; } if (!pPacket) { return E_FAIL; } ParseICYMetadataPacket(); *ppPacket = pPacket; return S_OK; } STDMETHODIMP CLAVFDemuxer::QueueMVCExtension(Packet *pPacket) { m_MVCExtensionQueue.push_back(pPacket); return S_OK; } STDMETHODIMP CLAVFDemuxer::FlushMVCExtensionQueue() { for (auto it = m_MVCExtensionQueue.begin(); it != m_MVCExtensionQueue.end(); it++) { delete (*it); } m_MVCExtensionQueue.clear(); return S_OK; } STDMETHODIMP CLAVFDemuxer::CombineMVCBaseExtension(Packet *pBasePacket) { while (!m_MVCExtensionQueue.empty()) { Packet *pExtensionPacket = m_MVCExtensionQueue.front(); if (pExtensionPacket->rtDTS == pBasePacket->rtDTS || pBasePacket->rtDTS == Packet::INVALID_TIME || pExtensionPacket->rtDTS == Packet::INVALID_TIME) { if (pBasePacket->Append(pExtensionPacket) < 0) return E_FAIL; m_MVCExtensionQueue.pop_front(); delete pExtensionPacket; return S_OK; } else if (pExtensionPacket->rtDTS < pBasePacket->rtDTS) { DbgLog((LOG_TRACE, 10, L"CLAVFDemuxer::CombineMVCBaseExtension(): Dropping extension %I64d, base is %I64d", pExtensionPacket->rtDTS, pBasePacket->rtDTS)); m_MVCExtensionQueue.pop_front(); delete pExtensionPacket; } else if (pExtensionPacket->rtDTS > pBasePacket->rtDTS) { DbgLog((LOG_TRACE, 10, L"CLAVFDemuxer::CombineMVCBaseExtension(): Dropping base %I64d, next extension is %I64d", pBasePacket->rtDTS, pExtensionPacket->rtDTS)); return S_FALSE; } } if (m_pBluRay && m_MVCExtensionQueue.empty()) { HRESULT hr = m_pBluRay->FillMVCExtensionQueue(pBasePacket->rtDTS); if (hr == S_OK) return CombineMVCBaseExtension(pBasePacket); else if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"CLAVFDemuxer::CombineMVCBaseExtension(): Filling MVC extension queue failed")); return hr; } } DbgLog((LOG_TRACE, 10, L"CLAVFDemuxer::CombineMVCBaseExtension(): Ran out of extension packets for base %I64d", pBasePacket->rtDTS)); return S_FALSE; } STDMETHODIMP CLAVFDemuxer::Seek(REFERENCE_TIME rTime) { int seekStreamId = m_dActiveStreams[video]; int64_t seek_pts = 0; retry: // If we have a video stream, seek on that one. If we don't, well, then don't! if (rTime > 0) { if (seekStreamId != -1) { AVStream *stream = m_avFormat->streams[seekStreamId]; seek_pts = ConvertRTToTimestamp(rTime, stream->time_base.num, stream->time_base.den); } else { seek_pts = ConvertRTToTimestamp(rTime, 1, AV_TIME_BASE); } } if (seek_pts < 0) seek_pts = 0; if (strcmp(m_pszInputFormat, "rawvideo") == 0 && seek_pts == 0) return SeekByte(0, AVSEEK_FLAG_BACKWARD); int flags = AVSEEK_FLAG_BACKWARD; int ret = av_seek_frame(m_avFormat, seekStreamId, seek_pts, flags); if (ret < 0) { DbgLog((LOG_CUSTOM1, 1, L"::Seek() -- Key-Frame Seek failed")); ret = av_seek_frame(m_avFormat, seekStreamId, seek_pts, flags | AVSEEK_FLAG_ANY); if (ret < 0) { DbgLog((LOG_ERROR, 1, L"::Seek() -- Inaccurate Seek failed as well")); if (seekStreamId == m_dActiveStreams[video] && seekStreamId != -1 && m_dActiveStreams[audio] != -1) { DbgLog((LOG_ERROR, 1, L"::Seek() -- retrying seek on audio stream")); seekStreamId = m_dActiveStreams[audio]; goto retry; } if (seek_pts == 0) { DbgLog((LOG_ERROR, 1, L" -> attempting byte seek to position 0")); return SeekByte(0, AVSEEK_FLAG_BACKWARD); } } } for (unsigned i = 0; i < m_avFormat->nb_streams; i++) { init_parser(m_avFormat, m_avFormat->streams[i]); UpdateParserFlags(m_avFormat->streams[i]); } m_bVC1SeenTimestamp = FALSE; // Flush MVC extensions on seek (no-op if empty) FlushMVCExtensionQueue(); return S_OK; } STDMETHODIMP CLAVFDemuxer::SeekByte(int64_t pos, int flags) { int ret = av_seek_frame(m_avFormat, -1, pos, flags | AVSEEK_FLAG_BYTE); if (ret < 0) { DbgLog((LOG_ERROR, 1, L"::SeekByte() -- Seek failed")); } for (unsigned i = 0; i < m_avFormat->nb_streams; i++) { init_parser(m_avFormat, m_avFormat->streams[i]); UpdateParserFlags(m_avFormat->streams[i]); } m_bVC1SeenTimestamp = FALSE; // Flush MVC extensions on seek (no-op if empty) FlushMVCExtensionQueue(); return S_OK; } STDMETHODIMP CLAVFDemuxer::Reset() { return SeekByte(0, AVSEEK_FLAG_ANY); } const char *CLAVFDemuxer::GetContainerFormat() const { return m_pszInputFormat; } ///////////////////////////////////////////////////////////////////////////// // IAMExtendedSeeking STDMETHODIMP CLAVFDemuxer::get_ExSeekCapabilities(long *pExCapabilities) { CheckPointer(pExCapabilities, E_POINTER); *pExCapabilities = AM_EXSEEK_CANSEEK; if (m_avFormat && m_avFormat->nb_chapters > 0) *pExCapabilities |= AM_EXSEEK_MARKERSEEK; return S_OK; } STDMETHODIMP CLAVFDemuxer::get_MarkerCount(long *pMarkerCount) { CheckPointer(pMarkerCount, E_POINTER); CheckPointer(m_avFormat, E_UNEXPECTED); *pMarkerCount = (long)m_avFormat->nb_chapters; return S_OK; } STDMETHODIMP CLAVFDemuxer::get_CurrentMarker(long *pCurrentMarker) { CheckPointer(pCurrentMarker, E_POINTER); CheckPointer(m_avFormat, E_UNEXPECTED); *pCurrentMarker = 0; REFERENCE_TIME rtCurrent = m_rtCurrent; IFilterGraph *pGraph = m_pSettings->GetFilterGraph(); if (pGraph) { IMediaSeeking *pSeeking = nullptr; if (SUCCEEDED(pGraph->QueryInterface(&pSeeking))) { if (FAILED(pSeeking->GetCurrentPosition(&rtCurrent))) { DbgLog((LOG_TRACE, 10, L"get_CurrentMarker: Obtaining current playback position failed")); rtCurrent = m_rtCurrent; } SafeRelease(&pSeeking); } SafeRelease(&pGraph); } // Can the time_base change in between chapters? // Anyhow, we do the calculation in the loop, just to be safe for (unsigned int i = 0; i < m_avFormat->nb_chapters; ++i) { int64_t pts = ConvertRTToTimestamp(rtCurrent, m_avFormat->chapters[i]->time_base.num, m_avFormat->chapters[i]->time_base.den); // Check if the pts is in between the bounds of the chapter if (pts >= m_avFormat->chapters[i]->start) { *pCurrentMarker = (i + 1); // Many files only have chapter start points and no end times if (pts <= m_avFormat->chapters[i]->end) return S_OK; } } return *pCurrentMarker > 0 ? S_OK : E_FAIL; } STDMETHODIMP CLAVFDemuxer::GetMarkerTime(long MarkerNum, double *pMarkerTime) { CheckPointer(pMarkerTime, E_POINTER); // Chapters go by a 1-based index, doh unsigned int index = MarkerNum - 1; if (index >= m_avFormat->nb_chapters) { return E_FAIL; } REFERENCE_TIME rt = ConvertTimestampToRT(m_avFormat->chapters[index]->start, m_avFormat->chapters[index]->time_base.num, m_avFormat->chapters[index]->time_base.den); *pMarkerTime = (double)rt / DSHOW_TIME_BASE; return S_OK; } STDMETHODIMP CLAVFDemuxer::GetMarkerName(long MarkerNum, BSTR *pbstrMarkerName) { CheckPointer(pbstrMarkerName, E_POINTER); // Chapters go by a 1-based index, doh unsigned int index = MarkerNum - 1; if (index >= m_avFormat->nb_chapters) { return E_FAIL; } // Get the title, or generate one if (AVDictionaryEntry *dictEntry = av_dict_get(m_avFormat->chapters[index]->metadata, "title", nullptr, 0)) { *pbstrMarkerName = ConvertCharToBSTR(dictEntry->value); } else { OLECHAR wTitle[128]; swprintf_s(wTitle, L"Chapter %d", MarkerNum); *pbstrMarkerName = SysAllocString(wTitle); } return S_OK; } ///////////////////////////////////////////////////////////////////////////// // IKeyFrameInfo STDMETHODIMP CLAVFDemuxer::GetKeyFrameCount(UINT &nKFs) { if (m_dActiveStreams[video] < 0) { return E_NOTIMPL; } if (!m_bMatroska && !m_bAVI && !m_bMP4) { return E_FAIL; } // No reliable info for fragmented mp4 files if (m_bMP4) { MOVContext *mov = (MOVContext *)m_avFormat->priv_data; if (mov->frag_index.nb_items) return S_FALSE; } nKFs = 0; AVStream *stream = m_avFormat->streams[m_dActiveStreams[video]]; int nb_indexes = avformat_index_get_entries_count(stream); for (int i = 0; i < nb_indexes; i++) { const AVIndexEntry *entry = avformat_index_get_entry(stream, i); if (entry && (entry->flags & AVINDEX_KEYFRAME)) nKFs++; } return (nKFs == stream->nb_frames) ? S_FALSE : S_OK; } STDMETHODIMP CLAVFDemuxer::GetKeyFrames(const GUID *pFormat, REFERENCE_TIME *pKFs, UINT &nKFs) { CheckPointer(pFormat, E_POINTER); CheckPointer(pKFs, E_POINTER); if (m_dActiveStreams[video] < 0) { return E_NOTIMPL; } if (!m_bMatroska && !m_bAVI && !m_bMP4) { return E_FAIL; } // No reliable info for fragmented mp4 files if (m_bMP4) { MOVContext *mov = (MOVContext *)m_avFormat->priv_data; if (mov->frag_index.nb_items) return S_FALSE; } if (*pFormat != TIME_FORMAT_MEDIA_TIME) return E_INVALIDARG; UINT nKFsMax = nKFs; nKFs = 0; // CTTS counter for MP4 int ctts_sample_counter = 0; uint32_t ctts_index = 0; AVStream *stream = m_avFormat->streams[m_dActiveStreams[video]]; int nb_indexes = avformat_index_get_entries_count(stream); for (int i = 0; i < nb_indexes && nKFs < nKFsMax; i++) { const AVIndexEntry *entry = avformat_index_get_entry(stream, i); if (entry && (entry->flags & AVINDEX_KEYFRAME)) { int64_t timestamp = entry->timestamp; // MP4 index timestamps are DTS, seeking expects PTS however, so offset them accordingly to ensure seeking // works as expected if (m_bMP4) { MOVStreamContext *sc = (MOVStreamContext *)stream->priv_data; if (i < sc->sample_offsets_count) timestamp += (sc->sample_offsets[i] + sc->dts_shift); else if (sc->tts_count) { // find the next CTTS entry, if needed while (ctts_sample_counter <= i && ctts_index < sc->tts_count) { ctts_sample_counter += sc->tts_data[ctts_index++].count; } // apply the CTTS offset to the timestamp if (ctts_sample_counter > i) timestamp += (sc->tts_data[ctts_index - 1].offset + sc->dts_shift); else timestamp += (sc->min_corrected_pts + sc->dts_shift); } else timestamp += (sc->min_corrected_pts + sc->dts_shift); } pKFs[nKFs] = ConvertTimestampToRT(timestamp, stream->time_base.num, stream->time_base.den); nKFs++; } } return S_OK; } int CLAVFDemuxer::GetStreamIdxFromTotalIdx(size_t index) const { const stream *st = GetStreamFromTotalIdx(index); if (st) return st->pid; return -1; } const CBaseDemuxer::stream *CLAVFDemuxer::GetStreamFromTotalIdx(size_t index) const { int type = video; size_t count_v = m_streams[video].size(); size_t count_a = m_streams[audio].size(); size_t count_s = m_streams[subpic].size(); if (index >= count_v) { index -= count_v; type = audio; if (index >= count_a) { index -= count_a; type = subpic; if (index >= count_s) return nullptr; } } return &m_streams[type][index]; } ///////////////////////////////////////////////////////////////////////////// // ITrackInfo STDMETHODIMP_(UINT) CLAVFDemuxer::GetTrackCount() { if (!m_avFormat) return 0; size_t count = m_streams[video].size() + m_streams[audio].size() + m_streams[subpic].size(); return (UINT)count; } // \param aTrackIdx the track index (from 0 to GetTrackCount()-1) STDMETHODIMP_(BOOL) CLAVFDemuxer::GetTrackInfo(UINT aTrackIdx, struct TrackElement *pStructureToFill) { DbgLog((LOG_TRACE, 20, L"ITrackInfo::GetTrackInfo(): index %d, struct: %p", aTrackIdx, pStructureToFill)); if (!m_avFormat || !pStructureToFill) return FALSE; ZeroMemory(pStructureToFill, sizeof(*pStructureToFill)); pStructureToFill->Size = sizeof(*pStructureToFill); const stream *st = GetStreamFromTotalIdx(aTrackIdx); if (!st || st->pid < 0 || st->pid == NO_SUBTITLE_PID) return FALSE; if (st->pid == FORCED_SUBTITLE_PID) { pStructureToFill->FlagDefault = 0; pStructureToFill->FlagForced = 1; pStructureToFill->Type = TypeSubtitle; strcpy_s(pStructureToFill->Language, "und"); } else { const AVStream *avst = m_avFormat->streams[st->pid]; // Fill structure pStructureToFill->FlagDefault = (avst->disposition & AV_DISPOSITION_DEFAULT); pStructureToFill->FlagForced = (avst->disposition & AV_DISPOSITION_FORCED); strncpy_s(pStructureToFill->Language, st->language.c_str(), _TRUNCATE); pStructureToFill->Language[3] = '\0'; pStructureToFill->Type = (avst->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) ? TypeVideo : (avst->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) ? TypeAudio : (avst->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) ? TypeSubtitle : 0; } // The following flags are not exported via avformat pStructureToFill->FlagLacing = 0; pStructureToFill->MaxCache = 0; pStructureToFill->MinCache = 0; return TRUE; } // Get an extended information struct relative to the track type STDMETHODIMP_(BOOL) CLAVFDemuxer::GetTrackExtendedInfo(UINT aTrackIdx, void *pStructureToFill) { if (!m_avFormat || !pStructureToFill) return FALSE; int id = GetStreamIdxFromTotalIdx(aTrackIdx); if (id < 0 || (unsigned)id >= m_avFormat->nb_streams) return FALSE; const AVStream *st = m_avFormat->streams[id]; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { TrackExtendedInfoVideo *pTEIV = (TrackExtendedInfoVideo *)pStructureToFill; ZeroMemory(pTEIV, sizeof(*pTEIV)); pTEIV->Size = sizeof(*pTEIV); pTEIV->DisplayUnit = 0; // always pixels pTEIV->DisplayWidth = st->codecpar->width; pTEIV->DisplayHeight = st->codecpar->height; pTEIV->PixelWidth = st->codecpar->width; pTEIV->PixelHeight = st->codecpar->height; pTEIV->AspectRatioType = 0; pTEIV->Interlaced = 0; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { TrackExtendedInfoAudio *pTEIA = (TrackExtendedInfoAudio *)pStructureToFill; ZeroMemory(pTEIA, sizeof(*pTEIA)); pTEIA->Size = sizeof(*pTEIA); pTEIA->BitDepth = st->codecpar->bits_per_coded_sample; pTEIA->Channels = st->codecpar->ch_layout.nb_channels; pTEIA->OutputSamplingFrequency = (FLOAT)st->codecpar->sample_rate; pTEIA->SamplingFreq = (FLOAT)st->codecpar->sample_rate; } return TRUE; } STDMETHODIMP_(BSTR) CLAVFDemuxer::GetTrackName(UINT aTrackIdx) { const stream *st = GetStreamFromTotalIdx(aTrackIdx); if (!st) return nullptr; BSTR trackName = nullptr; if (!st->trackName.empty()) { trackName = ConvertCharToBSTR(st->trackName.c_str()); } return trackName; } STDMETHODIMP_(BSTR) CLAVFDemuxer::GetTrackCodecName(UINT aTrackIdx) { if (!m_avFormat) return nullptr; int id = GetStreamIdxFromTotalIdx(aTrackIdx); if (id < 0 || (unsigned)id >= m_avFormat->nb_streams) return FALSE; const AVStream *st = m_avFormat->streams[id]; BSTR codecName = nullptr; std::string codec = get_codec_name(st->codecpar); if (!codec.empty()) { codecName = ConvertCharToBSTR(codec.c_str()); } return codecName; } ///////////////////////////////////////////////////////////////////////////// // IPropertyBag static struct { const char *original; const char *map; int stream; // 0 = none, 1 = video, 2 = audio, 3 = sub } mappedPropertys[] = { {"rotation", "rotate", 1}, {"rotate", nullptr, 1}, {"stereoscopic3dmode", "stereo_mode", 1}, {"stereo_mode", nullptr, 1}, {"stereo_subtitle_offset_id", "3d-plane", 3}, {"stereo_subtitle_offset_ids", "pg_offset_sequences", 0}, {"stereo_interactive_offset_ids", "ig_offset_sequences", 0}, }; STDMETHODIMP CLAVFDemuxer::Read(LPCOLESTR pszPropName, VARIANT *pVar, IErrorLog *pErrorLog) { CheckPointer(pszPropName, E_INVALIDARG); CheckPointer(pVar, E_INVALIDARG); int stream = -1; // Verify type if (pVar->vt != VT_EMPTY && pVar->vt != VT_BSTR) return E_FAIL; ATL::CW2A propNameConv(pszPropName); const char *propName = propNameConv; // Map property names for (int i = 0; i < countof(mappedPropertys); i++) { if (_stricmp(propName, mappedPropertys[i].original) == 0) { if (mappedPropertys[i].map) propName = mappedPropertys[i].map; if (mappedPropertys[i].stream) { int nStreamType = mappedPropertys[i].stream - 1; stream = m_dActiveStreams[nStreamType]; if (nStreamType == subpic && stream == FORCED_SUBTITLE_PID) stream = m_ForcedSubStream; } break; } } BSTR bstrValue = nullptr; HRESULT hr = GetBSTRMetadata(propName, &bstrValue, stream); if (SUCCEEDED(hr)) { VariantClear(pVar); pVar->vt = VT_BSTR; pVar->bstrVal = bstrValue; } return hr; } STDMETHODIMP CLAVFDemuxer::Write(LPCOLESTR pszPropName, VARIANT *pVar) { return E_NOTIMPL; } ///////////////////////////////////////////////////////////////////////////// // Internal Functions STDMETHODIMP CLAVFDemuxer::AddStream(int streamId) { HRESULT hr = S_OK; AVStream *pStream = m_avFormat->streams[streamId]; if (pStream->codecpar->codec_type == AVMEDIA_TYPE_UNKNOWN || pStream->discard == AVDISCARD_ALL || (pStream->codecpar->codec_id == AV_CODEC_ID_NONE && pStream->codecpar->codec_tag == 0) || (!m_bSubStreams && (pStream->disposition & LAVF_DISPOSITION_SUB_STREAM)) || (pStream->disposition & AV_DISPOSITION_ATTACHED_PIC)) { pStream->discard = AVDISCARD_ALL; return S_FALSE; } stream s; s.pid = streamId; // Extract language const char *lang = nullptr; if (AVDictionaryEntry *dictEntry = av_dict_get(pStream->metadata, "language", nullptr, 0)) { lang = dictEntry->value; } if (lang) { s.language = ProbeForISO6392(lang); s.lcid = ProbeLangForLCID(s.language.c_str()); } else { s.language = "und"; s.lcid = 0; } const char *title = lavf_get_stream_title(pStream); if (title) s.trackName = title; s.streamInfo = new CLAVFStreamInfo(m_avFormat, pStream, m_pszInputFormat, hr); if (hr != S_OK) { delete s.streamInfo; pStream->discard = AVDISCARD_ALL; return hr; } switch (pStream->codecpar->codec_type) { case AVMEDIA_TYPE_VIDEO: m_streams[video].push_back(s); break; case AVMEDIA_TYPE_AUDIO: m_streams[audio].push_back(s); break; case AVMEDIA_TYPE_SUBTITLE: m_streams[subpic].push_back(s); break; default: // unsupported stream // Normally this should be caught while creating the stream info already. delete s.streamInfo; return E_FAIL; } return S_OK; } // Pin creation STDMETHODIMP CLAVFDemuxer::CreateStreams() { DbgLog((LOG_TRACE, 10, L"CLAVFDemuxer::CreateStreams()")); CAutoLock lock(m_pLock); for (int i = 0; i < countof(m_streams); ++i) { m_streams[i].Clear(); } m_program = UINT_MAX; if (m_avFormat->nb_programs && !m_pBluRay) { DbgLog( (LOG_TRACE, 10, L" -> File has %d programs, trying to detect the correct one..", m_avFormat->nb_programs)); // Use a scoring system to select the best available program // A "good" program at least has a valid video and audio stream // We'll try here to detect these streams and decide on the best program // Every present stream gets one point, if it appears to be valid, it gets 4 // Every present video stream has also video resolution score: width x height. // Valid video streams have a width and height, valid audio streams have a channel count. // Total program bitrate is used as a tiebreaker. // We search for "good" program with highest score. DWORD dwScore = 0; // Stream found: 1, stream valid: 4 DWORD dwVideoResolutionProgramScore = 0; // Score = width x height DWORD dwProgramBitrate = 0; // Total bitrate of the program for (unsigned int i = 0; i < m_avFormat->nb_programs; ++i) { AVProgram *program = m_avFormat->programs[i]; if (program->nb_stream_indexes > 0) { DWORD dwVideoScore = 0; DWORD dwVideoResolutionScore = 0; DWORD dwAudioScore = 0; DWORD dwBitrate = 0; for (unsigned k = 0; k < program->nb_stream_indexes; ++k) { unsigned streamIdx = program->stream_index[k]; AVStream *st = m_avFormat->streams[streamIdx]; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (st->codecpar->width != 0 && st->codecpar->height != 0) { dwVideoScore = 4; DWORD dwResolutionScore = st->codecpar->width * st->codecpar->height; if (dwResolutionScore > dwVideoResolutionScore) dwVideoResolutionScore = dwResolutionScore; } else if (dwVideoScore == 0) dwVideoScore = 1; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && dwAudioScore < 4) { if (st->codecpar->ch_layout.nb_channels != 0) dwAudioScore = 4; else dwAudioScore = 1; } } AVDictionaryEntry *dict = av_dict_get(program->metadata, "variant_bitrate", nullptr, 0); if (dict && dict->value) dwBitrate = atol(dict->value); // Check the score of the previously found stream // In addition, we always require a valid video stream (or none), a invalid one is not allowed. DbgLog((LOG_TRACE, 10, L" -> Program %d with score: %ld (video), %ld (video resolution), %ld (audio), %ld (bitrate)", i, dwVideoScore, dwVideoResolutionScore, dwAudioScore, dwBitrate)); DWORD dwVideoAndAudioScore = dwVideoScore + dwAudioScore; if (dwVideoScore != 1 && (dwVideoAndAudioScore > dwScore || (dwVideoAndAudioScore == dwScore && dwVideoResolutionScore > dwVideoResolutionProgramScore) || (dwVideoAndAudioScore == dwScore && dwVideoResolutionScore == dwVideoResolutionProgramScore && dwBitrate > dwProgramBitrate))) { dwScore = dwVideoAndAudioScore; dwVideoResolutionProgramScore = dwVideoResolutionScore; dwProgramBitrate = dwBitrate; m_program = i; } } } DbgLog((LOG_TRACE, 10, L" -> Using Program %d", m_program)); } // File has programs bool bProgram = (m_program < m_avFormat->nb_programs); // Discard unwanted programs if (bProgram) { for (unsigned int i = 0; i < m_avFormat->nb_programs; ++i) { if (i != m_program) m_avFormat->programs[i]->discard = AVDISCARD_ALL; } } // Re-compute the overall file duration based on video and audio durations int64_t duration = INT64_MIN; int64_t st_duration = 0; int64_t start_time = INT64_MAX; int64_t st_start_time = 0; // Number of streams (either in file or in program) unsigned int nbIndex = bProgram ? m_avFormat->programs[m_program]->nb_stream_indexes : m_avFormat->nb_streams; // File has PGS streams bool bHasPGS = false; // add streams from selected program, or all streams if no program was selected for (unsigned int i = 0; i < nbIndex; ++i) { int streamIdx = bProgram ? m_avFormat->programs[m_program]->stream_index[i] : i; if (S_OK != AddStream(streamIdx)) continue; AVStream *st = m_avFormat->streams[streamIdx]; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if (st->duration != AV_NOPTS_VALUE) { st_duration = av_rescale_q(st->duration, st->time_base, AV_RATIONAL_TIMEBASE); if (st_duration > duration) duration = st_duration; } if (st->start_time != AV_NOPTS_VALUE) { st_start_time = av_rescale_q(st->start_time, st->time_base, AV_RATIONAL_TIMEBASE); if (st_start_time < start_time) start_time = st_start_time; } } if (st->codecpar->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE) bHasPGS = true; } if ((m_bTSDiscont || m_avFormat->duration == AV_NOPTS_VALUE) && duration != INT64_MIN) { DbgLog( (LOG_TRACE, 10, L" -> Changing duration to %I64d (from %I64d, diff %.3fs)", duration, m_avFormat->duration, m_avFormat->duration == AV_NOPTS_VALUE ? 0.0f : (float)(duration - m_avFormat->duration) / (float)AV_TIME_BASE)); m_avFormat->duration = duration; } if ((m_bTSDiscont || m_avFormat->start_time == AV_NOPTS_VALUE) && start_time != INT64_MAX) { DbgLog((LOG_TRACE, 10, L" -> Changing start_time to %I64d (from %I64d, diff %.3fs)", start_time, m_avFormat->start_time, m_avFormat->start_time == AV_NOPTS_VALUE ? 0.0f : (float)(start_time - m_avFormat->start_time) / (float)AV_TIME_BASE)); m_avFormat->start_time = start_time; } if (bHasPGS && m_pSettings->GetPGSForcedStream()) { CreatePGSForcedSubtitleStream(); } // Create fake subtitle pin if (!m_streams[subpic].empty()) { CreateNoSubtitleStream(); } if (m_bMPEGTS) { m_bH264MVCCombine = GetH264MVCStreamIndices(m_avFormat, &m_nH264MVCBaseStream, &m_nH264MVCExtensionStream); } if (m_bMatroska) { std::list pg_sequences; for (unsigned i = 0; i < m_avFormat->nb_streams; i++) { if (m_avFormat->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { AVDictionaryEntry *e = av_dict_get(m_avFormat->streams[i]->metadata, "3d-plane", nullptr, AV_DICT_IGNORE_SUFFIX); if (e && e->value) { pg_sequences.push_back(std::string(e->value)); } } } // export the list of pg sequences if (pg_sequences.size() > 0) { // strip duplicate entries pg_sequences.sort(); pg_sequences.unique(); size_t size = pg_sequences.size() * 4; char *offsets = new char[size]; offsets[0] = 0; // Append all offsets to the string for (auto it = pg_sequences.begin(); it != pg_sequences.end(); it++) { size_t len = strlen(offsets); if (len > 0) { offsets[len] = ','; len++; } strcpy_s(offsets + len, size - len, it->c_str()); } av_dict_set(&m_avFormat->metadata, "pg_offset_sequences", offsets, 0); delete[] offsets; } } return S_OK; } REFERENCE_TIME CLAVFDemuxer::GetStartTime() const { return av_rescale(m_avFormat->start_time, DSHOW_TIME_BASE, AV_TIME_BASE); } // Converts the lavf pts timestamp to a DShow REFERENCE_TIME // Based on DVDDemuxFFMPEG REFERENCE_TIME CLAVFDemuxer::ConvertTimestampToRT(int64_t pts, int num, int den, int64_t starttime) const { if (pts == (int64_t)AV_NOPTS_VALUE) { return Packet::INVALID_TIME; } if (starttime == AV_NOPTS_VALUE) { if (m_avFormat->start_time != AV_NOPTS_VALUE) { starttime = av_rescale(m_avFormat->start_time, den, (int64_t)AV_TIME_BASE * num); } else { starttime = 0; } } if (starttime != 0) { pts -= starttime; } // Let av_rescale do the work, its smart enough to not overflow REFERENCE_TIME timestamp = av_rescale(pts, (int64_t)num * DSHOW_TIME_BASE, den); return timestamp; } // Converts the lavf pts timestamp to a DShow REFERENCE_TIME // Based on DVDDemuxFFMPEG int64_t CLAVFDemuxer::ConvertRTToTimestamp(REFERENCE_TIME timestamp, int num, int den, int64_t starttime) const { if (timestamp == Packet::INVALID_TIME) { return (int64_t)AV_NOPTS_VALUE; } if (starttime == AV_NOPTS_VALUE) { if (m_avFormat->start_time != AV_NOPTS_VALUE) { starttime = av_rescale(m_avFormat->start_time, den, (int64_t)AV_TIME_BASE * num); } else { starttime = 0; } } int64_t pts = av_rescale(timestamp, den, (int64_t)num * DSHOW_TIME_BASE); if (starttime != 0) { pts += starttime; } return pts; } HRESULT CLAVFDemuxer::UpdateForcedSubtitleStream(unsigned audio_pid) { if (!m_avFormat || audio_pid >= m_avFormat->nb_streams) return E_UNEXPECTED; stream *audiost = GetStreams(audio)->FindStream(audio_pid); if (!audiost) return E_FAIL; // Build CSubtitleSelector for this special case std::list selectors; CSubtitleSelector selector; selector.audioLanguage = "*"; selector.subtitleLanguage = audiost->language; selector.dwFlagsSet = SUBTITLE_FLAG_PGS; selector.dwFlagsNot = 0; selectors.push_back(selector); selector.subtitleLanguage = "*"; selectors.push_back(selector); const stream *subst = SelectSubtitleStream(selectors, audiost->language); if (subst) { m_ForcedSubStream = subst->pid; CStreamList *streams = GetStreams(subpic); stream *forced = streams->FindStream(FORCED_SUBTITLE_PID); if (forced) { CMediaType mtype = forced->streamInfo->mtypes.back(); forced->streamInfo->mtypes.pop_back(); forced->language = audiost->language; forced->lcid = audiost->lcid; SUBTITLEINFO *subInfo = (SUBTITLEINFO *)mtype.Format(); strncpy_s(subInfo->IsoLang, audiost->language.c_str(), 3); subInfo->IsoLang[3] = 0; forced->streamInfo->mtypes.push_back(mtype); } } return subst ? S_OK : S_FALSE; } // Select the best video stream const CBaseDemuxer::stream *CLAVFDemuxer::SelectVideoStream() { const stream *best = nullptr; CStreamList *streams = GetStreams(video); std::deque::iterator it; for (it = streams->begin(); it != streams->end(); ++it) { stream *check = &*it; if (!best) { best = check; continue; } // if the best stream is an unknown codec, prefer any other if (m_avFormat->streams[best->pid]->codecpar->codec_id == AV_CODEC_ID_NONE && m_avFormat->streams[check->pid]->codecpar->codec_id != AV_CODEC_ID_NONE) { best = check; continue; } // prefer default streams bool checkDefault = m_avFormat->streams[check->pid]->disposition & AV_DISPOSITION_DEFAULT; bool bestDefault = m_avFormat->streams[best->pid]->disposition & AV_DISPOSITION_DEFAULT; if (checkDefault != bestDefault) { if (checkDefault) best = check; continue; } uint64_t bestPixels = (uint64_t)m_avFormat->streams[best->pid]->codecpar->width * m_avFormat->streams[best->pid]->codecpar->height; uint64_t checkPixels = (uint64_t)m_avFormat->streams[check->pid]->codecpar->width * m_avFormat->streams[check->pid]->codecpar->height; int check_nb_f = av_lav_stream_codec_info_nb_frames(m_avFormat->streams[check->pid]); int best_nb_f = av_lav_stream_codec_info_nb_frames(m_avFormat->streams[best->pid]); if (m_bRM && (check_nb_f > 0 && best_nb_f <= 0)) { best = check; } else if (m_bMP4 && m_avFormat->streams[check->pid]->nb_frames == 1 && m_avFormat->streams[best->pid]->nb_frames > 1) { // avoid selecting a video stream with only one frame } else if (m_bMP4 && m_avFormat->streams[best->pid]->nb_frames == 1 && m_avFormat->streams[check->pid]->nb_frames > 1) { // prefer a stream with more then one frame, if available best = check; } else if (!m_bRM || check_nb_f > 0) { if (checkPixels > bestPixels) { best = check; } else if (checkPixels == bestPixels) { int64_t best_rate = m_avFormat->streams[best->pid]->codecpar->bit_rate; int64_t check_rate = m_avFormat->streams[check->pid]->codecpar->bit_rate; if (best_rate && check_rate && check_rate > best_rate) best = check; } } } return best; } static int audio_codec_priority(const AVCodecParameters *par) { int priority = 0; const AVCodecDescriptor *desc = avcodec_descriptor_get(par->codec_id); // lossless codecs have highest priority if (desc && ((desc->props & (AV_CODEC_PROP_LOSSLESS | AV_CODEC_PROP_LOSSY)) == AV_CODEC_PROP_LOSSLESS)) { priority = 10; } else if (desc && (desc->props & AV_CODEC_PROP_LOSSLESS)) { priority = 8; if (par->codec_id == AV_CODEC_ID_DTS) { priority = 7; if (par->profile == AV_PROFILE_DTS_EXPRESS) { priority -= 1; } else if (par->profile == AV_PROFILE_DTS_HD_MA) { priority += 3; } else if (par->profile == AV_PROFILE_DTS_HD_HRA) { priority += 2; } else if (par->profile >= AV_PROFILE_DTS_ES) { priority += 1; } } } else { switch (par->codec_id) { case AV_CODEC_ID_EAC3: priority = 7; break; case AV_CODEC_ID_AC3: case AV_CODEC_ID_AAC: case AV_CODEC_ID_AAC_LATM: priority = 5; break; case AV_CODEC_ID_MP3: priority = 3; break; } // WAVE_FORMAT_EXTENSIBLE is multi-channel PCM, which doesn't have a proper tag otherwise if (par->codec_tag == WAVE_FORMAT_EXTENSIBLE) { priority = 10; } } // low priority for S302M with non-pcm content if (par->codec_id == AV_CODEC_ID_S302M && par->codec_tag != -1) priority = -1; return priority; } // Select the best audio stream const CBaseDemuxer::stream *CLAVFDemuxer::SelectAudioStream(std::list prefLanguages) { const stream *best = nullptr; CStreamList *streams = GetStreams(audio); std::deque checkedStreams; // Filter for language if (!prefLanguages.empty()) { std::list::iterator it; for (it = prefLanguages.begin(); it != prefLanguages.end(); ++it) { std::string checkLanguage = ProbeForISO6392(it->c_str()); std::deque::iterator sit; for (sit = streams->begin(); sit != streams->end(); ++sit) { std::string language = sit->language; // check if the language matches if (language == checkLanguage) { checkedStreams.push_back(&*sit); } } // First language that has any streams is a match if (!checkedStreams.empty()) { break; } } } // If no language was set, or no matching streams were found // Put all streams in there if (checkedStreams.empty()) { std::deque::iterator sit; for (sit = streams->begin(); sit != streams->end(); ++sit) { checkedStreams.push_back(&*sit); } } // Check for a stream with a default flag // If in our current set is one, that one prevails std::deque::iterator sit; for (sit = checkedStreams.begin(); sit != checkedStreams.end(); ++sit) { if (m_avFormat->streams[(*sit)->pid]->disposition & AV_DISPOSITION_DEFAULT) { best = *sit; break; } } BOOL bCheckQuality = m_pSettings->GetPreferHighQualityAudioStreams(); BOOL bImpaired = m_pSettings->GetUseAudioForHearingVisuallyImpaired(); #define DISPO_IMPAIRED (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED) if (!best && !checkedStreams.empty()) { // If only one stream is left, just use that one if (checkedStreams.size() == 1) { best = checkedStreams.at(0); } else { // Check for quality std::deque::iterator sit; for (sit = checkedStreams.begin(); sit != checkedStreams.end(); ++sit) { if (!best) { best = *sit; continue; } AVStream *old_stream = m_avFormat->streams[best->pid]; AVStream *new_stream = m_avFormat->streams[(*sit)->pid]; // ignore streams with an unknown codec or no decoder if (new_stream->codecpar->codec_id == AV_CODEC_ID_NONE || avcodec_find_decoder(new_stream->codecpar->codec_id) == NULL) continue; else if (old_stream->codecpar->codec_id == AV_CODEC_ID_NONE || avcodec_find_decoder(old_stream->codecpar->codec_id) == NULL) { best = *sit; continue; } int check_nb_f = av_lav_stream_codec_info_nb_frames(new_stream); int best_nb_f = av_lav_stream_codec_info_nb_frames(old_stream); if (m_bRM && (check_nb_f > 0 && best_nb_f <= 0)) { best = *sit; } else if (!m_bRM || check_nb_f > 0) { if (!(old_stream->disposition & DISPO_IMPAIRED) != !(new_stream->disposition & DISPO_IMPAIRED)) { if ((bImpaired && !(old_stream->disposition & DISPO_IMPAIRED)) || (!bImpaired && !(new_stream->disposition & DISPO_IMPAIRED))) { best = *sit; } continue; } if (!bCheckQuality) continue; // First, check number of channels int old_num_chans = old_stream->codecpar->ch_layout.nb_channels; int new_num_chans = new_stream->codecpar->ch_layout.nb_channels; if (new_num_chans > old_num_chans) { best = *sit; } else if (new_num_chans == old_num_chans) { // Same number of channels, check codec int old_priority = audio_codec_priority(old_stream->codecpar); int new_priority = audio_codec_priority(new_stream->codecpar); if (new_priority > old_priority) { best = *sit; } } } } } } return best; } static inline bool does_language_match(std::string selector, std::string selectee) { return (selector == "*" || selector == selectee); } // ugly hack to only convert ascii to lower case, as there is no proper unicode function for utf-8 in std::string static inline char asciitolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } // Select the best subtitle stream const CBaseDemuxer::stream *CLAVFDemuxer::SelectSubtitleStream(std::list subtitleSelectors, std::string audioLanguage) { const stream *best = nullptr; CStreamList *streams = GetStreams(subpic); std::deque checkedStreams; std::list::iterator it = subtitleSelectors.begin(); for (it = subtitleSelectors.begin(); it != subtitleSelectors.end() && checkedStreams.empty(); it++) { if (!does_language_match(it->audioLanguage, audioLanguage)) continue; if (it->subtitleLanguage == "off") break; // lower-case version of the trackname query std::string subtitleTrackNameQueryLower = it->subtitleTrackName; if (subtitleTrackNameQueryLower.empty() == false) std::transform(subtitleTrackNameQueryLower.begin(), subtitleTrackNameQueryLower.end(), subtitleTrackNameQueryLower.begin(), asciitolower); std::deque::iterator sit; for (sit = streams->begin(); sit != streams->end(); sit++) { if (sit->pid == NO_SUBTITLE_PID) continue; if (!subtitleTrackNameQueryLower.empty()) { // create lowercase version of the track name std::string trackNameLower = sit->trackName; std::transform(trackNameLower.begin(), trackNameLower.end(), trackNameLower.begin(), asciitolower); if (trackNameLower.find(subtitleTrackNameQueryLower) == std::string::npos) continue; } if (sit->pid == FORCED_SUBTITLE_PID) { if ((it->dwFlagsSet == 0 || it->dwFlagsSet & SUBTITLE_FLAG_VIRTUAL) && does_language_match(it->subtitleLanguage, audioLanguage)) checkedStreams.push_back(&*sit); continue; } bool streamIsDefault = m_avFormat->streams[sit->pid]->disposition & AV_DISPOSITION_DEFAULT; bool streamIsForced = m_avFormat->streams[sit->pid]->disposition & AV_DISPOSITION_FORCED; bool streamIsImpaired = m_avFormat->streams[sit->pid]->disposition & (AV_DISPOSITION_HEARING_IMPAIRED | AV_DISPOSITION_VISUAL_IMPAIRED); bool streamIsNormal = !streamIsDefault && !streamIsForced && !streamIsImpaired; bool streamIsPgsFormat = (m_avFormat->streams[sit->pid]->codecpar->codec_id == AV_CODEC_ID_HDMV_PGS_SUBTITLE); bool flagsSetMatch = ((it->dwFlagsSet == 0) || ((it->dwFlagsSet & SUBTITLE_FLAG_DEFAULT) && streamIsDefault) || ((it->dwFlagsSet & SUBTITLE_FLAG_FORCED) && streamIsForced) || ((it->dwFlagsSet & SUBTITLE_FLAG_IMPAIRED) && streamIsImpaired) || ((it->dwFlagsSet & SUBTITLE_FLAG_PGS) && streamIsPgsFormat) || ((it->dwFlagsSet & SUBTITLE_FLAG_NORMAL) && streamIsNormal) ); bool flagsNotMatch = (!((it->dwFlagsNot & SUBTITLE_FLAG_DEFAULT) && streamIsDefault) && !((it->dwFlagsNot & SUBTITLE_FLAG_FORCED) && streamIsForced) && !((it->dwFlagsNot & SUBTITLE_FLAG_IMPAIRED) && streamIsImpaired) && !((it->dwFlagsNot & SUBTITLE_FLAG_NORMAL) && streamIsNormal) ); if (flagsSetMatch && flagsNotMatch) { std::string streamLanguage = sit->language; if (does_language_match(it->subtitleLanguage, streamLanguage)) checkedStreams.push_back(&*sit); } } } if (!checkedStreams.empty()) best = streams->FindStream(checkedStreams.front()->pid); else best = streams->FindStream(NO_SUBTITLE_PID); return best; } #include "libavformat/isom.h" STDMETHODIMP_(DWORD) CLAVFDemuxer::GetStreamFlags(DWORD dwStream) { if (!m_avFormat || dwStream >= m_avFormat->nb_streams) return 0; DWORD dwFlags = 0; AVStream *st = m_avFormat->streams[dwStream]; if (strcmp(m_pszInputFormat, "rawvideo") == 0) dwFlags |= LAV_STREAM_FLAG_ONLY_DTS; if (st->codecpar->codec_id == AV_CODEC_ID_H264 && (m_bAVI || m_bPMP || (m_bMatroska && (!st->codecpar->extradata_size || st->codecpar->extradata[0] != 1)) || (m_bMP4 && st->priv_data && ((MOVStreamContext *)st->priv_data)->ctts_count == 0))) dwFlags |= LAV_STREAM_FLAG_ONLY_DTS; if (st->codecpar->codec_id == AV_CODEC_ID_HEVC && (m_bAVI || (m_bMP4 && st->priv_data && ((MOVStreamContext *)st->priv_data)->ctts_count == 0))) dwFlags |= LAV_STREAM_FLAG_ONLY_DTS; if (st->codecpar->codec_id == AV_CODEC_ID_VVC && (m_bAVI || (m_bMP4 && st->priv_data && ((MOVStreamContext *)st->priv_data)->ctts_count == 0))) dwFlags |= LAV_STREAM_FLAG_ONLY_DTS; if (m_bMatroska && (st->codecpar->codec_id == AV_CODEC_ID_RV30 || st->codecpar->codec_id == AV_CODEC_ID_RV40)) dwFlags |= LAV_STREAM_FLAG_RV34_MKV; if (m_avFormat->flags & AVFMT_FLAG_NETWORK) dwFlags |= LAV_STREAM_FLAG_LIVE; return dwFlags; } STDMETHODIMP_(int) CLAVFDemuxer::GetPixelFormat(DWORD dwStream) { if (!m_avFormat || dwStream >= m_avFormat->nb_streams) return AV_PIX_FMT_NONE; return m_avFormat->streams[dwStream]->codecpar->format; } STDMETHODIMP_(int) CLAVFDemuxer::GetHasBFrames(DWORD dwStream) { if (!m_avFormat || dwStream >= m_avFormat->nb_streams) return -1; return m_avFormat->streams[dwStream]->codecpar->video_delay; } STDMETHODIMP CLAVFDemuxer::GetSideData(DWORD dwStream, GUID guidType, const BYTE **pData, size_t *pSize) { if (!m_avFormat || dwStream >= m_avFormat->nb_streams) return E_INVALIDARG; if (guidType == IID_MediaSideDataFFMpeg) { CBaseDemuxer::stream *pStream = FindStream(dwStream); if (!pStream) return E_FAIL; pStream->SideData.side_data = m_avFormat->streams[dwStream]->codecpar->coded_side_data; pStream->SideData.side_data_elems = m_avFormat->streams[dwStream]->codecpar->nb_coded_side_data; *pData = (BYTE *)&pStream->SideData; *pSize = sizeof(pStream->SideData); return S_OK; } return E_INVALIDARG; } STDMETHODIMP CLAVFDemuxer::GetBSTRMetadata(const char *key, BSTR *pbstrValue, int stream) { if (!m_avFormat) return VFW_E_NOT_FOUND; if (stream >= (int)m_avFormat->nb_streams) return E_INVALIDARG; if (_stricmp(key, "rotate") == 0 && stream >= 0) { const AVPacketSideData *sd = av_packet_side_data_get( m_avFormat->streams[stream]->codecpar->coded_side_data, m_avFormat->streams[stream]->codecpar->nb_coded_side_data, AV_PKT_DATA_DISPLAYMATRIX); if (sd && sd->size == (9*sizeof(int32_t))) { double dRotation = av_display_rotation_get((const int32_t *)sd->data); int nRotation = -lrint(dRotation); // normalize rotation to 0-360 while (nRotation < 0) nRotation += 360; while (nRotation >= 360) nRotation -= 360; char buf[34] = {0}; sprintf_s(buf, "%d", nRotation); *pbstrValue = ConvertCharToBSTR(buf); if (*pbstrValue == nullptr) return E_OUTOFMEMORY; return S_OK; } } AVDictionaryEntry *entry = av_dict_get(stream >= 0 ? m_avFormat->streams[stream]->metadata : m_avFormat->metadata, key, nullptr, AV_DICT_IGNORE_SUFFIX); if (!entry || !entry->value || entry->value[0] == '\0') return VFW_E_NOT_FOUND; *pbstrValue = ConvertCharToBSTR(entry->value); if (*pbstrValue == nullptr) return E_OUTOFMEMORY; return S_OK; } ================================================ FILE: demuxer/Demuxers/LAVFDemuxer.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #include #include #include #include "BaseDemuxer.h" #include "IKeyFrameInfo.h" #include "ITrackInfo.h" #include "FontInstaller.h" #include "DSMResourceBag.h" #define SUBMODE_FORCED_PGS_ONLY 0xFF class FormatInfo; class CBDDemuxer; #define FFMPEG_FILE_BUFFER_SIZE 32768 // default reading size for ffmpeg class CLAVFDemuxer : public CBaseDemuxer , public CDSMResourceBag , public IAMExtendedSeeking , public IKeyFrameInfo , public ITrackInfo , public IAMMediaContent , public IPropertyBag { public: CLAVFDemuxer(CCritSec *pLock, ILAVFSettingsInternal *settings); ~CLAVFDemuxer(); static std::set GetFormatList(); // IUnknown DECLARE_IUNKNOWN STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // IDispatch STDMETHODIMP GetTypeInfoCount(UINT *pctinfo) { return E_NOTIMPL; } STDMETHODIMP GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo **pptinfo) { return E_NOTIMPL; } STDMETHODIMP GetIDsOfNames(REFIID riid, OLECHAR **rgszNames, UINT cNames, LCID lcid, DISPID *rgdispid) { return E_NOTIMPL; } STDMETHODIMP Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS *pdispparams, VARIANT *pvarResult, EXCEPINFO *pexcepinfo, UINT *puArgErr) { return E_NOTIMPL; } // CBaseDemuxer STDMETHODIMP Open(LPCOLESTR pszFileName, LPCOLESTR pszUserAgent = NULL, LPCOLESTR pszReferrer = NULL); STDMETHODIMP Start(); STDMETHODIMP AbortOpening(int mode = 1, int timeout = 0); REFERENCE_TIME GetDuration() const; STDMETHODIMP GetNextPacket(Packet **ppPacket); STDMETHODIMP Seek(REFERENCE_TIME rTime); STDMETHODIMP Reset(); const char *GetContainerFormat() const; virtual DWORD GetContainerFlags() { return m_bTSDiscont ? LAVFMT_TS_DISCONT : 0; } STDMETHODIMP SetTitle(int idx); STDMETHODIMP_(int) GetTitle(); STDMETHODIMP GetTitleInfo(int idx, REFERENCE_TIME *rtDuration, WCHAR **ppszName); STDMETHODIMP_(int) GetNumTitles(); void SettingsChanged(ILAVFSettingsInternal *pSettings); // Select the best video stream const stream *SelectVideoStream(); // Select the best audio stream const stream *SelectAudioStream(std::list prefLanguages); // Select the best subtitle stream const stream *SelectSubtitleStream(std::list subtitleSelectors, std::string audioLanguage); HRESULT SetActiveStream(StreamType type, int pid); STDMETHODIMP_(DWORD) GetStreamFlags(DWORD dwStream); STDMETHODIMP_(int) GetPixelFormat(DWORD dwStream); STDMETHODIMP_(int) GetHasBFrames(DWORD dwStream); STDMETHODIMP GetSideData(DWORD dwStream, GUID guidType, const BYTE **pData, size_t *pSize); // IAMExtendedSeeking STDMETHODIMP get_ExSeekCapabilities(long *pExCapabilities); STDMETHODIMP get_MarkerCount(long *pMarkerCount); STDMETHODIMP get_CurrentMarker(long *pCurrentMarker); STDMETHODIMP GetMarkerTime(long MarkerNum, double *pMarkerTime); STDMETHODIMP GetMarkerName(long MarkerNum, BSTR *pbstrMarkerName); STDMETHODIMP put_PlaybackSpeed(double Speed) { return E_NOTIMPL; } STDMETHODIMP get_PlaybackSpeed(double *pSpeed) { return E_NOTIMPL; } // IKeyFrameInfo STDMETHODIMP GetKeyFrameCount(UINT &nKFs); STDMETHODIMP GetKeyFrames(const GUID *pFormat, REFERENCE_TIME *pKFs, UINT &nKFs); // ITrackInfo STDMETHODIMP_(UINT) GetTrackCount(); // \param aTrackIdx the track index (from 0 to GetTrackCount()-1) STDMETHODIMP_(BOOL) GetTrackInfo(UINT aTrackIdx, struct TrackElement *pStructureToFill); // Get an extended information struct relative to the track type STDMETHODIMP_(BOOL) GetTrackExtendedInfo(UINT aTrackIdx, void *pStructureToFill); STDMETHODIMP_(BSTR) GetTrackCodecID(UINT aTrackIdx) { return nullptr; } STDMETHODIMP_(BSTR) GetTrackName(UINT aTrackIdx); STDMETHODIMP_(BSTR) GetTrackCodecName(UINT aTrackIdx); STDMETHODIMP_(BSTR) GetTrackCodecInfoURL(UINT aTrackIdx) { return nullptr; } STDMETHODIMP_(BSTR) GetTrackCodecDownloadURL(UINT aTrackIdx) { return nullptr; } // IAMMediaContent STDMETHODIMP get_AuthorName(BSTR *pbstrAuthorName) { return GetBSTRMetadata("artist", pbstrAuthorName); } STDMETHODIMP get_Title(BSTR *pbstrTitle) { return GetBSTRMetadata("title", pbstrTitle); } STDMETHODIMP get_Rating(BSTR *pbstrRating) { return E_NOTIMPL; } STDMETHODIMP get_Description(BSTR *pbstrDescription) { HRESULT hr = GetBSTRMetadata("comment", pbstrDescription); if (hr == VFW_E_NOT_FOUND) hr = GetBSTRMetadata("description", pbstrDescription); return hr; } STDMETHODIMP get_Copyright(BSTR *pbstrCopyright) { return GetBSTRMetadata("copyright", pbstrCopyright); } STDMETHODIMP get_BaseURL(BSTR *pbstrBaseURL) { return E_NOTIMPL; } STDMETHODIMP get_LogoURL(BSTR *pbstrLogoURL) { return E_NOTIMPL; } STDMETHODIMP get_LogoIconURL(BSTR *pbstrLogoURL) { return E_NOTIMPL; } STDMETHODIMP get_WatermarkURL(BSTR *pbstrWatermarkURL) { return E_NOTIMPL; } STDMETHODIMP get_MoreInfoURL(BSTR *pbstrMoreInfoURL) { return E_NOTIMPL; } STDMETHODIMP get_MoreInfoBannerImage(BSTR *pbstrMoreInfoBannerImage) { return E_NOTIMPL; } STDMETHODIMP get_MoreInfoBannerURL(BSTR *pbstrMoreInfoBannerURL) { return E_NOTIMPL; } STDMETHODIMP get_MoreInfoText(BSTR *pbstrMoreInfoText) { return E_NOTIMPL; } // IPropertyBag STDMETHODIMP Read(LPCOLESTR pszPropName, VARIANT *pVar, IErrorLog *pErrorLog); STDMETHODIMP Write(LPCOLESTR pszPropName, VARIANT *pVar); STDMETHODIMP OpenInputStream(AVIOContext *byteContext, LPCOLESTR pszFileName = nullptr, const char *format = nullptr, BOOL bForce = FALSE, BOOL bFileSource = FALSE, LPCOLESTR pszUserAgent = NULL, LPCOLESTR pszReferrer = NULL); STDMETHODIMP SeekByte(int64_t pos, int flags); AVStream *GetAVStreamByPID(int pid); void UpdateSubStreams(); unsigned int GetNumStreams() const { return m_avFormat->nb_streams; } REFERENCE_TIME GetStartTime() const; void SetBluRay(CBDDemuxer *pBluRay) { m_pBluRay = pBluRay; } void AddMPEGTSStream(int pid, uint32_t stream_type); private: STDMETHODIMP AddStream(int streamId); STDMETHODIMP CreateStreams(); STDMETHODIMP InitAVFormat(LPCOLESTR pszFileName, BOOL bForce); void CleanupAVFormat(); void UpdateParserFlags(AVStream *st); REFERENCE_TIME ConvertTimestampToRT(int64_t pts, int num, int den, int64_t starttime = (int64_t)AV_NOPTS_VALUE) const; int64_t ConvertRTToTimestamp(REFERENCE_TIME timestamp, int num, int den, int64_t starttime = (int64_t)AV_NOPTS_VALUE) const; int GetStreamIdxFromTotalIdx(size_t index) const; const CBaseDemuxer::stream *GetStreamFromTotalIdx(size_t index) const; HRESULT CheckBDM2TSCPLI(LPCOLESTR pszFileName); HRESULT UpdateForcedSubtitleStream(unsigned audio_pid); static int avio_interrupt_cb(void *opaque); STDMETHODIMP GetBSTRMetadata(const char *key, BSTR *pbstrValue, int stream = -1); STDMETHODIMP CreatePacketMediaType(Packet *pPacket, enum AVCodecID codec_id, BYTE *extradata, int extradata_size, BYTE *paramchange, int paramchange_size); STDMETHODIMP ParseICYMetadataPacket(); STDMETHODIMP QueueMVCExtension(Packet *pPacket); STDMETHODIMP FlushMVCExtensionQueue(); STDMETHODIMP CombineMVCBaseExtension(Packet *pBasePacket); private: friend class CBDDemuxer; AVFormatContext *m_avFormat = nullptr; const char *m_pszInputFormat = nullptr; BOOL m_bMatroska = FALSE; BOOL m_bOgg = FALSE; BOOL m_bAVI = FALSE; BOOL m_bMPEGTS = FALSE; BOOL m_bMPEGPS = FALSE; BOOL m_bRM = FALSE; BOOL m_bPMP = FALSE; BOOL m_bMP4 = FALSE; BOOL m_bTSDiscont = FALSE; BOOL m_bSubStreams = FALSE; BOOL m_bVC1Correction = FALSE; BOOL m_bVC1SeenTimestamp = FALSE; BOOL m_bPGSNoParsing = FALSE; BOOL m_bH264MVCCombine = FALSE; int m_nH264MVCBaseStream = -1; int m_nH264MVCExtensionStream = -1; std::deque m_MVCExtensionQueue; int m_ForcedSubStream = -1; unsigned int m_program = 0; REFERENCE_TIME m_rtCurrent = 0; AVStreamParseType *m_stOrigParser = nullptr; CFontInstaller *m_pFontInstaller = nullptr; ILAVFSettingsInternal *m_pSettings = nullptr; BOOL m_bEnableTrackInfo = TRUE; CBDDemuxer *m_pBluRay = nullptr; int m_Abort = 0; time_t m_timeAbort = 0; time_t m_timeOpening = 0; }; ================================================ FILE: demuxer/Demuxers/LAVFInputFormats.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" static const char *RAW_VIDEO = "rawvideo"; static const char *RAW_VIDEO_DESC = "raw video files"; static const char *RAW_AUDIO = "rawaudio"; static const char *RAW_AUDIO_DESC = "raw audio files"; struct lavf_iformat_map { const char *orig_format; const char *new_format; const char *new_description; } lavf_input_formats[] = { // Shorten these formats {"matroska,webm", "matroska", nullptr}, {"mov,mp4,m4a,3gp,3g2,mj2", "mp4", "MPEG-4/QuickTime format"}, {"yuv4mpegpipe", "y4m", "YUV4MPEG"}, {"asf_o", "asf", nullptr}, // Raw Video formats (grouped into "rawvideo") {"dirac", RAW_VIDEO, RAW_VIDEO_DESC}, {"dnxhd", RAW_VIDEO, RAW_VIDEO_DESC}, {"h261", RAW_VIDEO, RAW_VIDEO_DESC}, {"h263", RAW_VIDEO, RAW_VIDEO_DESC}, {"h264", RAW_VIDEO, RAW_VIDEO_DESC}, {"hevc", RAW_VIDEO, RAW_VIDEO_DESC}, {"ingenient", RAW_VIDEO, RAW_VIDEO_DESC}, {"mjpeg", RAW_VIDEO, RAW_VIDEO_DESC}, {"vc1", RAW_VIDEO, RAW_VIDEO_DESC}, // Raw Audio Formats (grouped into "rawaudio") {"f32be", RAW_AUDIO, RAW_AUDIO_DESC}, {"f32le", RAW_AUDIO, RAW_AUDIO_DESC}, {"f64be", RAW_AUDIO, RAW_AUDIO_DESC}, {"f64le", RAW_AUDIO, RAW_AUDIO_DESC}, {"g722", RAW_AUDIO, RAW_AUDIO_DESC}, {"gsm", RAW_AUDIO, RAW_AUDIO_DESC}, {"s16be", RAW_AUDIO, RAW_AUDIO_DESC}, {"s16le", RAW_AUDIO, RAW_AUDIO_DESC}, {"s24be", RAW_AUDIO, RAW_AUDIO_DESC}, {"s24le", RAW_AUDIO, RAW_AUDIO_DESC}, {"s32be", RAW_AUDIO, RAW_AUDIO_DESC}, {"s32le", RAW_AUDIO, RAW_AUDIO_DESC}, {"s8", RAW_AUDIO, RAW_AUDIO_DESC}, {"u16be", RAW_AUDIO, RAW_AUDIO_DESC}, {"u16le", RAW_AUDIO, RAW_AUDIO_DESC}, {"u24be", RAW_AUDIO, RAW_AUDIO_DESC}, {"u24le", RAW_AUDIO, RAW_AUDIO_DESC}, {"u32be", RAW_AUDIO, RAW_AUDIO_DESC}, {"u32le", RAW_AUDIO, RAW_AUDIO_DESC}, {"u8", RAW_AUDIO, RAW_AUDIO_DESC}, {"image2", "image2", "Image Files"}, {"image2pipe", "image2", "Image Files"}, // Disabled Formats {"ffm", nullptr, nullptr}, {"ffmetadata", nullptr, nullptr}, {"mpegtsraw", nullptr, nullptr}, {"spdif", nullptr, nullptr}, {"tty", nullptr, nullptr}, {"vc1test", nullptr, nullptr}, }; void lavf_get_iformat_infos(const AVInputFormat *pFormat, const char **pszName, const char **pszDescription) { const char *name = pFormat->name; const char *desc = pFormat->long_name; for (int i = 0; i < countof(lavf_input_formats); ++i) { if (strcmp(lavf_input_formats[i].orig_format, name) == 0) { name = lavf_input_formats[i].new_format; if (lavf_input_formats[i].new_description) desc = lavf_input_formats[i].new_description; break; } } if (pszName) *pszName = name; if (pszDescription) *pszDescription = desc; } ================================================ FILE: demuxer/Demuxers/LAVFStreamInfo.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #include "stdafx.h" #include "LAVFStreamInfo.h" #include "LAVFVideoHelper.h" #include "LAVFAudioHelper.h" #include "LAVFUtils.h" #include "moreuuids.h" #include "H264Nalu.h" #include #include CLAVFStreamInfo::CLAVFStreamInfo(AVFormatContext *avctx, AVStream *avstream, const char *containerFormat, HRESULT &hr) : CStreamInfo() , m_containerFormat(containerFormat) { switch (avstream->codecpar->codec_type) { case AVMEDIA_TYPE_AUDIO: hr = CreateAudioMediaType(avctx, avstream); break; case AVMEDIA_TYPE_VIDEO: hr = CreateVideoMediaType(avctx, avstream); break; case AVMEDIA_TYPE_SUBTITLE: hr = CreateSubtitleMediaType(avctx, avstream); break; default: hr = E_FAIL; break; } codecInfo = lavf_get_stream_description(avstream); } CLAVFStreamInfo::~CLAVFStreamInfo() { } STDMETHODIMP CLAVFStreamInfo::CreateAudioMediaType(AVFormatContext *avctx, AVStream *avstream) { // if no codec tag is set, or the tag is set to PCM (which is often wrong), lookup a new tag if (avstream->codecpar->codec_tag == 0 || avstream->codecpar->codec_tag == 1) { avstream->codecpar->codec_tag = av_codec_get_tag(mp_wav_taglists, avstream->codecpar->codec_id); } if (avstream->codecpar->ch_layout.nb_channels == 0 || avstream->codecpar->sample_rate == 0) { if (avstream->codecpar->codec_id == AV_CODEC_ID_AAC && avstream->codecpar->bit_rate) { if (!avstream->codecpar->ch_layout.nb_channels) { avstream->codecpar->ch_layout.order = AV_CHANNEL_ORDER_UNSPEC; avstream->codecpar->ch_layout.nb_channels = 2; } if (!avstream->codecpar->sample_rate) avstream->codecpar->sample_rate = 48000; } else return E_FAIL; } // use the variant bitrate for the stream if only one stream is available (applies to some radio streams) if (avstream->codecpar->bit_rate == 0 && avctx->nb_streams == 1) { AVDictionaryEntry *dict = av_dict_get(avstream->metadata, "variant_bitrate", nullptr, 0); if (dict && dict->value) avstream->codecpar->bit_rate = atoi(dict->value); } CMediaType mtype = g_AudioHelper.initAudioType(avstream->codecpar, avstream->codecpar->codec_tag, m_containerFormat); // The Raw PCM type is used for PCM streams which do not already have their own Extensible header // If the codec_tag already equals extensible, it'll be used copied as-is and we assume a valid extensible header // exists in extradata bool bUseRawPCMType = (mtype.subtype == MEDIASUBTYPE_PCM || mtype.subtype == MEDIASUBTYPE_IEEE_FLOAT) && (avstream->codecpar->codec_tag != WAVE_FORMAT_EXTENSIBLE || avstream->codecpar->extradata_size < 22); if (mtype.formattype == FORMAT_WaveFormatEx) { // Special Logic for the MPEG1 Audio Formats (MP1, MP2) if (mtype.subtype == MEDIASUBTYPE_MPEG1AudioPayload) { mtype.pbFormat = (BYTE *)g_AudioHelper.CreateMP1WVFMT(avstream, &mtype.cbFormat); } else if (mtype.subtype == MEDIASUBTYPE_BD_LPCM_AUDIO) { mtype.pbFormat = (BYTE *)g_AudioHelper.CreateWVFMTEX_LPCM(avstream, &mtype.cbFormat); mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_HDMV_LPCM_AUDIO; } else if (bUseRawPCMType) { // Create raw PCM media type mtype.pbFormat = (BYTE *)g_AudioHelper.CreateWFMTEX_RAW_PCM(avstream, &mtype.cbFormat, mtype.subtype, &mtype.lSampleSize); } else { WAVEFORMATEX *wvfmt = g_AudioHelper.CreateWVFMTEX(avstream, &mtype.cbFormat); if (avstream->codecpar->codec_tag == WAVE_FORMAT_EXTENSIBLE && avstream->codecpar->extradata_size >= 22) { // The WAVEFORMATEXTENSIBLE GUID is not recognized by the audio renderers // Set the actual subtype as GUID WAVEFORMATEXTENSIBLE *wvfmtex = (WAVEFORMATEXTENSIBLE *)wvfmt; mtype.subtype = wvfmtex->SubFormat; } mtype.pbFormat = (BYTE *)wvfmt; if (avstream->codecpar->codec_id == AV_CODEC_ID_FLAC) { // These are required to block accidental connection to ReClock wvfmt->nAvgBytesPerSec = (wvfmt->nSamplesPerSec * wvfmt->nChannels * wvfmt->wBitsPerSample) >> 3; wvfmt->nBlockAlign = 1; mtype.subtype = MEDIASUBTYPE_FLAC_FRAMED; mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_FLAC; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_EAC3) { mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_DOLBY_DDPLUS_ARCSOFT; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_DTS) { wvfmt->wFormatTag = WAVE_FORMAT_DTS2; if (avstream->codecpar->profile >= AV_PROFILE_DTS_HD_HRA) { mtype.subtype = MEDIASUBTYPE_DTS_HD; mtypes.push_back(mtype); } mtype.subtype = MEDIASUBTYPE_WAVE_DTS; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_TRUEHD) { // wvfmt->wFormatTag = (WORD)WAVE_FORMAT_TRUEHD; mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_DOLBY_TRUEHD_ARCSOFT; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_AAC) { wvfmt->wFormatTag = (WORD)MEDIASUBTYPE_AAC_ADTS.Data1; CMediaType adtsMtype = mtype; adtsMtype.subtype = MEDIASUBTYPE_AAC_ADTS; mtypes.push_back(adtsMtype); // if we have extradata, use ordinary AAC type if (avstream->codecpar->extradata_size) { mtype.subtype = MEDIASUBTYPE_AAC; } else { // else, use ADTS type mtype.subtype = MEDIASUBTYPE_MPEG_ADTS_AAC; } wvfmt->wFormatTag = (WORD)mtype.subtype.Data1; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_AAC_LATM) { mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_MPEG_LOAS; wvfmt->wFormatTag = (WORD)mtype.subtype.Data1; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_OPUS) { mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_OPUS_OLD; wvfmt->wFormatTag = (WORD)WAVE_FORMAT_OPUS_OLD; } } } else if (mtype.formattype == FORMAT_VorbisFormat2 && mtype.subtype == MEDIASUBTYPE_Vorbis2) { // With Matroska and Ogg we know how to split up the extradata // and put it into a VorbisFormat2 if ((m_containerFormat == "matroska" || m_containerFormat == "ogg") && avstream->codecpar->extradata_size > 0) { BYTE *vorbis2 = (BYTE *)g_AudioHelper.CreateVorbis2(avstream, &mtype.cbFormat); if (vorbis2) { mtype.pbFormat = vorbis2; mtypes.push_back(mtype); } } // Old vorbis header without extradata mtype.subtype = MEDIASUBTYPE_Vorbis; mtype.formattype = FORMAT_VorbisFormat; mtype.pbFormat = (BYTE *)g_AudioHelper.CreateVorbis(avstream, &mtype.cbFormat); } mtypes.push_back(mtype); // Create our special media type CMediaType ff_mtype; ff_mtype.InitMediaType(); ff_mtype.SetSampleSize(256000); ff_mtype.majortype = MEDIATYPE_Audio; ff_mtype.subtype = MEDIASUBTYPE_FFMPEG_AUDIO; ff_mtype.formattype = FORMAT_WaveFormatExFFMPEG; if (bUseRawPCMType) ff_mtype.pbFormat = (BYTE *)g_AudioHelper.CreateWFMTEX_RAW_PCM_FF(avstream, &ff_mtype.cbFormat, mtype.subtype, &ff_mtype.lSampleSize); else ff_mtype.pbFormat = (BYTE *)g_AudioHelper.CreateWVFMTEX_FF(avstream, &ff_mtype.cbFormat); mtypes.push_back(ff_mtype); return S_OK; } static bool h264_is_annexb(std::string format, AVStream *avstream) { ASSERT(avstream->codecpar->codec_id == AV_CODEC_ID_H264 || avstream->codecpar->codec_id == AV_CODEC_ID_H264_MVC); if (avstream->codecpar->extradata_size < 4) return true; if (avstream->codecpar->extradata[0] == 1) return false; if (format == "avi") { BYTE *src = avstream->codecpar->extradata; unsigned startcode = AV_RB32(src); if (startcode == 0x00000001 || (startcode & 0xffffff00) == 0x00000100) return true; if (avstream->codecpar->codec_tag == MKTAG('A', 'V', 'C', '1') || avstream->codecpar->codec_tag == MKTAG('a', 'v', 'c', '1')) return false; } return true; } static bool hevc_is_annexb(std::string format, AVStream *avstream) { ASSERT(avstream->codecpar->codec_id == AV_CODEC_ID_HEVC); if (avstream->codecpar->extradata_size < 23) return true; if (avstream->codecpar->extradata[0] || avstream->codecpar->extradata[1] || avstream->codecpar->extradata[2] > 1) return false; /*if (format == "avi") { BYTE *src = avstream->codec->extradata; unsigned startcode = AV_RB32(src); if (startcode == 0x00000001 || (startcode & 0xffffff00) == 0x00000100) return true; }*/ return true; } static int get_vpcC_chroma(AVCodecParameters *codecpar) { int chroma_w = 0, chroma_h = 0; if (av_pix_fmt_get_chroma_sub_sample((AVPixelFormat)codecpar->format, &chroma_w, &chroma_h) == 0) { if (chroma_w == 1 && chroma_h == 1) { return (codecpar->chroma_location == AVCHROMA_LOC_LEFT) ? 0 : 1; } else if (chroma_w == 1 && chroma_h == 0) { return 2; } else if (chroma_w == 0 && chroma_h == 0) { return 3; } } return 0; } static int get_pixel_bitdepth(AVPixelFormat pix_fmt) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc == NULL) { DbgLog((LOG_TRACE, 10, "Unknown pixel format")); return 8; } return desc->comp[0].depth; } static bool is_monochrome(AVPixelFormat pix_fmt) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc == NULL) { DbgLog((LOG_TRACE, 10, "Unknown pixel format")); return false; } return desc->nb_components == 1; } static int chroma_x(AVPixelFormat pix_fmt) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc == NULL) { DbgLog((LOG_TRACE, 10, "Unknown pixel format")); return 1; } return desc->log2_chroma_w; } static int chroma_y(AVPixelFormat pix_fmt) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(pix_fmt); if (desc == NULL) { DbgLog((LOG_TRACE, 10, "Unknown pixel format")); return 1; } return desc->log2_chroma_h; } STDMETHODIMP CLAVFStreamInfo::CreateVideoMediaType(AVFormatContext *avctx, AVStream *avstream) { unsigned int origCodecTag = avstream->codecpar->codec_tag; if (avstream->codecpar->codec_tag == 0 && avstream->codecpar->codec_id != AV_CODEC_ID_DVVIDEO) { avstream->codecpar->codec_tag = av_codec_get_tag(mp_bmp_taglists, avstream->codecpar->codec_id); } if (avstream->codecpar->codec_id == AV_CODEC_ID_H264_MVC) { // Don't create media types for MVC extension streams, they are handled specially return S_FALSE; } if (avstream->codecpar->width == 0 || avstream->codecpar->height == 0) return E_FAIL; CMediaType mtype = g_VideoHelper.initVideoType(avstream->codecpar->codec_id, avstream->codecpar->codec_tag, m_containerFormat); mtype.SetTemporalCompression(TRUE); mtype.SetVariableSize(); // Somewhat hackish to force VIH for AVI content. // TODO: Figure out why exactly this is required if (m_containerFormat == "avi" && avstream->codecpar->codec_id != AV_CODEC_ID_H264) { mtype.formattype = FORMAT_VideoInfo; } // Native MPEG4 in Matroska needs a special formattype if (m_containerFormat == "matroska" && avstream->codecpar->codec_id == AV_CODEC_ID_MPEG4) { if (AVDictionaryEntry *mkvCodecId = av_dict_get(avstream->metadata, "mkv-codec-id", nullptr, 0)) { if (strcmp(mkvCodecId->value, "V_MS/VFW/FOURCC") != 0) mtype.formattype = FORMAT_MPEG2Video; } } // If we need aspect info, we switch to VIH2 AVRational r = avstream->sample_aspect_ratio; AVRational rc = avstream->codecpar->sample_aspect_ratio; if (mtype.formattype == FORMAT_VideoInfo && ((r.den > 0 && r.num > 0 && (r.den > 1 || r.num > 1)) || (rc.den > 0 && rc.num > 0 && (rc.den > 1 || rc.num > 1)))) { mtype.formattype = FORMAT_VideoInfo2; } if (mtype.formattype == FORMAT_VideoInfo) { mtype.pbFormat = (BYTE *)g_VideoHelper.CreateVIH(avstream, &mtype.cbFormat, m_containerFormat); } else if (mtype.formattype == FORMAT_VideoInfo2) { mtype.pbFormat = (BYTE *)g_VideoHelper.CreateVIH2(avstream, &mtype.cbFormat, m_containerFormat); if (mtype.subtype == MEDIASUBTYPE_WVC1) { // If we send the cyberlink subtype first, it'll work with it, and with ffdshow, dmo and mpc-hc internal VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)mtype.pbFormat; if (*((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2)) == 0) { mtype.subtype = MEDIASUBTYPE_WVC1_CYBERLINK; mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_WVC1_ARCSOFT; mtypes.push_back(mtype); } mtype.subtype = MEDIASUBTYPE_WVC1; } else if (mtype.subtype == MEDIASUBTYPE_WMVA) { mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_WVC1; VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)mtype.pbFormat; vih2->bmiHeader.biCompression = mtype.subtype.Data1; } else if (mtype.subtype == MEDIASUBTYPE_VP90) { // generate extradata for VP9 streams mtype.ReallocFormatBuffer(sizeof(VIDEOINFOHEADER2) + 16); VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)mtype.pbFormat; vih2->bmiHeader.biSize = sizeof(BITMAPINFOHEADER) + 16; BYTE *extra = mtype.pbFormat + sizeof(VIDEOINFOHEADER2); AV_WB32(extra, MKBETAG('v', 'p', 'c', 'C')); AV_WB8(extra + 4, 1); // version AV_WB24(extra + 5, 0); // flags AV_WB8(extra + 8, avstream->codecpar->profile); AV_WB8(extra + 9, avstream->codecpar->level == AV_LEVEL_UNKNOWN ? 0 : avstream->codecpar->level); AV_WB8(extra + 10, get_pixel_bitdepth((AVPixelFormat)avstream->codecpar->format) << 4 | get_vpcC_chroma(avstream->codecpar) << 1 | (avstream->codecpar->color_range == AVCOL_RANGE_JPEG)); AV_WB8(extra + 11, avstream->codecpar->color_primaries); AV_WB8(extra + 12, avstream->codecpar->color_trc); AV_WB8(extra + 13, avstream->codecpar->color_space); AV_WB16(extra + 14, 0); // no codec init data } else if (mtype.subtype == MEDIASUBTYPE_AV01) { VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)mtype.pbFormat; // check if extradata is missing, and we have some basic information to share if ((vih2->bmiHeader.biSize <= sizeof(BITMAPINFOHEADER) + 4 || ((mtype.pbFormat + sizeof(VIDEOINFOHEADER2))[0] != 0x81)) && avstream->codecpar->profile != AV_PROFILE_UNKNOWN) { // if not, generate some mtype.ReallocFormatBuffer(sizeof(VIDEOINFOHEADER2) + 4); vih2 = (VIDEOINFOHEADER2 *)mtype.pbFormat; vih2->bmiHeader.biSize = sizeof(BITMAPINFOHEADER) + 4; BYTE *extra = mtype.pbFormat + sizeof(VIDEOINFOHEADER2); AV_WB8(extra, 0x81); // version AV_WB8(extra + 1, (avstream->codecpar->profile == AV_PROFILE_UNKNOWN ? 0 : avstream->codecpar->profile) << 5 | (avstream->codecpar->level == AV_LEVEL_UNKNOWN ? 0 : avstream->codecpar->level)); int bpp = get_pixel_bitdepth((AVPixelFormat)avstream->codecpar->format); AV_WB8(extra + 2, (0 << 7) | // seq_tier ((bpp > 8) << 6) | // high_bitdepth ((bpp == 12) << 5) | // twelve bit (is_monochrome((AVPixelFormat)avstream->codecpar->format) << 4) | // monochrome (chroma_x((AVPixelFormat)avstream->codecpar->format) << 3) | (chroma_y((AVPixelFormat)avstream->codecpar->format) << 2) | (0 << 1) // chroma sample position ); AV_WB8(extra + 3, 0); // reserved, unusued fields } } } else if (mtype.formattype == FORMAT_MPEGVideo) { mtype.pbFormat = (BYTE *)g_VideoHelper.CreateMPEG1VI(avstream, &mtype.cbFormat, m_containerFormat); } else if (mtype.formattype == FORMAT_MPEG2Video) { mtype.pbFormat = (BYTE *)g_VideoHelper.CreateMPEG2VI(avstream, &mtype.cbFormat, m_containerFormat, FALSE); MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)mtype.pbFormat; if (avstream->codecpar->codec_id == AV_CODEC_ID_H264) { if (h264_is_annexb(m_containerFormat, avstream)) { mtype.subtype = MEDIASUBTYPE_H264; } else { mtype.subtype = MEDIASUBTYPE_AVC1; if (mp2vi->dwFlags == 0) mp2vi->dwFlags = 4; } mp2vi->hdr.bmiHeader.biCompression = mtype.subtype.Data1; // Create a second AVC1 compat type for mpegts // This should only ever be used by "legacy" decoders if (mtype.subtype == MEDIASUBTYPE_H264 && m_containerFormat == "mpegts") { mtypes.push_back(mtype); mtype.ResetFormatBuffer(); mtype.subtype = MEDIASUBTYPE_AVC1; mtype.pbFormat = (BYTE *)g_VideoHelper.CreateMPEG2VI(avstream, &mtype.cbFormat, m_containerFormat, TRUE); MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)mtype.pbFormat; mp2vi->hdr.bmiHeader.biCompression = mtype.subtype.Data1; } } else if (avstream->codecpar->codec_id == AV_CODEC_ID_HEVC) { if (hevc_is_annexb(m_containerFormat, avstream)) { mtype.subtype = MEDIASUBTYPE_HEVC; } else { mtype.subtype = MEDIASUBTYPE_HVC1; } mp2vi->hdr.bmiHeader.biCompression = mtype.subtype.Data1; } } // Detect MVC extensions and adjust the type appropriately if (avstream->codecpar->codec_id == AV_CODEC_ID_H264) { if (h264_is_annexb(m_containerFormat, avstream)) { if (m_containerFormat == "mpegts") { int nBaseStream = -1, nExtensionStream = -1; if (GetH264MVCStreamIndices(avctx, &nBaseStream, &nExtensionStream) && nBaseStream == avstream->index) { CMediaType mvcType = mtypes.front(); AVStream *mvcStream = avctx->streams[nExtensionStream]; MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)mvcType.ReallocFormatBuffer( sizeof(MPEG2VIDEOINFO) + avstream->codecpar->extradata_size + mvcStream->codecpar->extradata_size); size_t ExtradataSize = 0; // clear the extradata storage memset(&mp2vi->dwSequenceHeader[0], 0, avstream->codecpar->extradata_size + mvcStream->codecpar->extradata_size); // assemble the extradata in the correct order, first the SPS+SPS Subset, then any PPS CH264Nalu nalParser; // main SPS from the base stream nalParser.SetBuffer(avstream->codecpar->extradata, avstream->codecpar->extradata_size, 0); while (nalParser.ReadNext()) { if (nalParser.GetType() == NALU_TYPE_SPS) { memcpy((BYTE *)&mp2vi->dwSequenceHeader[0] + ExtradataSize, nalParser.GetNALBuffer(), nalParser.GetLength()); ExtradataSize += nalParser.GetLength(); } } // subset SPS from the extension stream nalParser.SetBuffer(mvcStream->codecpar->extradata, mvcStream->codecpar->extradata_size, 0); while (nalParser.ReadNext()) { if (nalParser.GetType() == NALU_TYPE_SPS || nalParser.GetType() == NALU_TYPE_SPS_SUB) { memcpy((BYTE *)&mp2vi->dwSequenceHeader[0] + ExtradataSize, nalParser.GetNALBuffer(), nalParser.GetLength()); ExtradataSize += nalParser.GetLength(); } // extract profile info from the subset SPS if (nalParser.GetType() == NALU_TYPE_SPS_SUB) { const BYTE *pData = nalParser.GetDataBuffer(); mp2vi->dwProfile = avstream->codecpar->profile = pData[1]; mp2vi->dwLevel = avstream->codecpar->level = pData[3]; } } // PPS from the main stream nalParser.SetBuffer(avstream->codecpar->extradata, avstream->codecpar->extradata_size, 0); while (nalParser.ReadNext()) { if (nalParser.GetType() == NALU_TYPE_PPS) { memcpy((BYTE *)&mp2vi->dwSequenceHeader[0] + ExtradataSize, nalParser.GetNALBuffer(), nalParser.GetLength()); ExtradataSize += nalParser.GetLength(); } } // PPS from the extension stream nalParser.SetBuffer(mvcStream->codecpar->extradata, mvcStream->codecpar->extradata_size, 0); while (nalParser.ReadNext()) { if (nalParser.GetType() == NALU_TYPE_PPS) { memcpy((BYTE *)&mp2vi->dwSequenceHeader[0] + ExtradataSize, nalParser.GetNALBuffer(), nalParser.GetLength()); ExtradataSize += nalParser.GetLength(); } } // update mediatype mp2vi->cbSequenceHeader = (DWORD)ExtradataSize; mvcType.cbFormat = SIZE_MPEG2VIDEOINFO(mp2vi); mvcType.subtype = MEDIASUBTYPE_AMVC; mp2vi->hdr.bmiHeader.biCompression = mvcType.subtype.Data1; mtypes.push_front(mvcType); } } } else { CMediaType mvcType = mtype; MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)mvcType.ReallocFormatBuffer(sizeof(MPEG2VIDEOINFO) + avstream->codecpar->extradata_size); HRESULT hr = g_VideoHelper.ProcessH264MVCExtradata(avstream->codecpar->extradata, avstream->codecpar->extradata_size, mp2vi); if (hr == S_OK) { mvcType.cbFormat = SIZE_MPEG2VIDEOINFO(mp2vi); mvcType.subtype = MEDIASUBTYPE_MVC1; mp2vi->hdr.bmiHeader.biCompression = mvcType.subtype.Data1; mtypes.push_front(mvcType); // update stream profile/level appropriately if (mp2vi->dwProfile != 0) avstream->codecpar->profile = mp2vi->dwProfile; if (mp2vi->dwLevel != 0) avstream->codecpar->level = mp2vi->dwLevel; } } } if (avstream->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { BITMAPINFOHEADER *pBMI = nullptr; videoFormatTypeHandler(mtype.pbFormat, &mtype.formattype, &pBMI, nullptr, nullptr, nullptr); mtype.bFixedSizeSamples = TRUE; mtype.bTemporalCompression = FALSE; mtype.lSampleSize = pBMI->biSizeImage; if (!avstream->codecpar->codec_tag || avstream->codecpar->codec_tag == MKTAG('r', 'a', 'w', ' ')) { switch (avstream->codecpar->format) { case AV_PIX_FMT_BGRA: mtype.subtype = MEDIASUBTYPE_ARGB32; mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_RGB32; break; case AV_PIX_FMT_BGR24: mtype.subtype = MEDIASUBTYPE_RGB24; break; default: DbgLog((LOG_TRACE, 10, L"::CreateVideoMediaType(): Unsupported raw video pixel format")); } } else { switch (avstream->codecpar->codec_tag) { case MKTAG('B', 'G', 'R', 'A'): { pBMI->biHeight = -pBMI->biHeight; mtype.subtype = MEDIASUBTYPE_ARGB32; mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_RGB32; } break; default: DbgLog((LOG_TRACE, 10, L"::CreateVideoMediaType(): Unsupported raw video codec tag format")); } } mtypes.push_back(mtype); mtype.subtype = MEDIASUBTYPE_LAV_RAWVIDEO; size_t hdrsize = 0, extrasize = 0; if (mtype.formattype == FORMAT_VideoInfo) { hdrsize = sizeof(VIDEOINFOHEADER); } else if (mtype.formattype == FORMAT_VideoInfo2) { hdrsize = sizeof(VIDEOINFOHEADER2); } else { ASSERT(0); } extrasize = mtype.cbFormat - hdrsize; mtype.ReallocFormatBuffer((ULONG)(hdrsize + extrasize + sizeof(avstream->codecpar->format))); if (extrasize) { memmove(mtype.pbFormat + hdrsize + sizeof(avstream->codecpar->format), mtype.pbFormat + hdrsize, extrasize); } *(int *)(mtype.pbFormat + hdrsize) = avstream->codecpar->format; videoFormatTypeHandler(mtype.pbFormat, &mtype.formattype, &pBMI, nullptr, nullptr, nullptr); pBMI->biSize = (DWORD)(sizeof(BITMAPINFOHEADER) + sizeof(avstream->codecpar->format) + extrasize); mtypes.push_back(mtype); } if (avstream->codecpar->codec_id == AV_CODEC_ID_MJPEG) { BITMAPINFOHEADER *pBMI = nullptr; videoFormatTypeHandler(mtype.pbFormat, &mtype.formattype, &pBMI, nullptr, nullptr, nullptr); DWORD fourCC = MKTAG('M', 'J', 'P', 'G'); // If the original fourcc is different to MJPG, add this one if (fourCC != pBMI->biCompression) { mtypes.push_back(mtype); mtype.subtype = FOURCCMap(fourCC); pBMI->biCompression = fourCC; } } mtypes.push_back(mtype); return S_OK; } enum AVCodecID ff_get_pcm_codec_id(int bps, int flt, int be, int sflags); #include "libavformat/isom.h" static std::string CreateVOBSubHeaderFromMP4(int vidW, int vidH, MOVStreamContext *context, const char *buffer, int buf_size) { std::ostringstream header; if (buffer && buf_size) { int w = context && context->width ? context->width : vidW; int h = context && context->height ? context->height : vidH; header << "# VobSub index file, v7 (do not modify this line!)\n"; // ffmpeg might provide us with the size already if (strncmp(buffer, "size:", 5) != 0) { header << "size: " << w << "x" << h << "\n"; } header.write(buffer, buf_size); } return header.str(); } static std::string GetDefaultVOBSubHeader(int w, int h) { std::ostringstream header; header << "# VobSub index file, v7 (do not modify this line!)\n"; header << "size: " << w << "x" << h << "\n"; header << "palette: "; // header << "000000,f0f0f0,cccccc,999999,"; header << "000000,e0e0e0,808080,202020,"; header << "3333fa,1111bb,fa3333,bb1111,"; header << "33fa33,11bb11,fafa33,bbbb11,"; header << "fa33fa,bb11bb,33fafa,11bbbb\n"; return header.str(); } // Map codec ids to media subtypes // clang-format off static FormatMapping subtitle_format_map[] = { { AV_CODEC_ID_TEXT, &MEDIASUBTYPE_UTF8 }, { AV_CODEC_ID_SRT, &MEDIASUBTYPE_UTF8 }, { AV_CODEC_ID_SUBRIP, &MEDIASUBTYPE_UTF8 }, { AV_CODEC_ID_MOV_TEXT, &MEDIASUBTYPE_UTF8 }, { AV_CODEC_ID_ASS, &MEDIASUBTYPE_ASS }, { AV_CODEC_ID_SSA, &MEDIASUBTYPE_ASS }, { AV_CODEC_ID_HDMV_PGS_SUBTITLE, &MEDIASUBTYPE_HDMVSUB }, { AV_CODEC_ID_DVD_SUBTITLE, &MEDIASUBTYPE_VOBSUB }, { AV_CODEC_ID_DVB_SUBTITLE, &MEDIASUBTYPE_DVB_SUBTITLES }, { AV_CODEC_ID_WEBVTT, &MEDIASUBTYPE_WEBVTT }, }; // clang-format on STDMETHODIMP CLAVFStreamInfo::CreateSubtitleMediaType(AVFormatContext *avctx, AVStream *avstream) { CMediaType mtype; mtype.majortype = MEDIATYPE_Subtitle; mtype.formattype = FORMAT_SubtitleInfo; mtype.subtype = MEDIASUBTYPE_NULL; int extra = avstream->codecpar->extradata_size; // parse flags from mov tx3g atom if (avstream->codecpar->codec_id == AV_CODEC_ID_MOV_TEXT && avstream->codecpar->codec_tag == MKTAG('t', 'x', '3', 'g') && extra >= 4) { uint32_t flags = AV_RB32(avstream->codecpar->extradata); if (flags & 0x80000000) avstream->disposition |= AV_DISPOSITION_FORCED; } if (avstream->codecpar->codec_id == AV_CODEC_ID_MOV_TEXT || avstream->codecpar->codec_id == AV_CODEC_ID_TEXT || avstream->codecpar->codec_id == AV_CODEC_ID_SUBRIP) { extra = 0; } // create format info SUBTITLEINFO *subInfo = (SUBTITLEINFO *)mtype.AllocFormatBuffer(sizeof(SUBTITLEINFO) + extra); memset(subInfo, 0, mtype.FormatLength()); if (AVDictionaryEntry *dictEntry = av_dict_get(avstream->metadata, "language", nullptr, 0)) { char *lang = dictEntry->value; strncpy_s(subInfo->IsoLang, 4, lang, _TRUNCATE); } else { strncpy_s(subInfo->IsoLang, 4, "und", _TRUNCATE); } if (AVDictionaryEntry *dictEntry = av_dict_get(avstream->metadata, "title", nullptr, 0)) { // read metadata char *title = dictEntry->value; // convert to wchar SafeMultiByteToWideChar(CP_UTF8, 0, title, -1, subInfo->TrackName, 256); } subInfo->dwOffset = sizeof(SUBTITLEINFO); // Find first video stream AVStream *vidStream = nullptr; for (unsigned i = 0; i < avctx->nb_streams; i++) { if (avctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { vidStream = avctx->streams[i]; break; } } // Extradata if (m_containerFormat == "mp4" && avstream->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) { std::string strVobSubHeader = CreateVOBSubHeaderFromMP4( vidStream ? vidStream->codecpar->width : 720, vidStream ? vidStream->codecpar->height : 576, (MOVStreamContext *)avstream->priv_data, (char *)avstream->codecpar->extradata, extra); size_t len = strVobSubHeader.length(); mtype.ReallocFormatBuffer((ULONG)(sizeof(SUBTITLEINFO) + len)); memcpy(mtype.pbFormat + sizeof(SUBTITLEINFO), strVobSubHeader.c_str(), len); } else if (m_containerFormat == "mpeg" && avstream->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) { // And a VobSub type std::string strVobSubHeader = GetDefaultVOBSubHeader(vidStream ? vidStream->codecpar->width : 720, vidStream ? vidStream->codecpar->height : 576); size_t len = strVobSubHeader.length(); mtype.ReallocFormatBuffer((ULONG)(sizeof(SUBTITLEINFO) + len)); memcpy(mtype.pbFormat + sizeof(SUBTITLEINFO), strVobSubHeader.c_str(), len); mtype.subtype = MEDIASUBTYPE_VOBSUB; mtypes.push_back(mtype); // Offer the DVD subtype CMediaType dvdmtype; dvdmtype.majortype = MEDIATYPE_Video; dvdmtype.subtype = MEDIASUBTYPE_DVD_SUBPICTURE; dvdmtype.formattype = FORMAT_MPEG2_VIDEO; MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)dvdmtype.AllocFormatBuffer(sizeof(MPEG2VIDEOINFO)); ZeroMemory(mp2vi, sizeof(MPEG2VIDEOINFO)); mp2vi->hdr.bmiHeader.biWidth = vidStream ? vidStream->codecpar->width : 720; mp2vi->hdr.bmiHeader.biHeight = vidStream ? vidStream->codecpar->height : 576; mtypes.push_back(dvdmtype); return S_OK; } else if (avstream->codecpar->extradata && extra > 0) { memcpy(mtype.pbFormat + sizeof(SUBTITLEINFO), avstream->codecpar->extradata, extra); } // Check against values from the map above for (unsigned i = 0; i < countof(subtitle_format_map); ++i) { if (subtitle_format_map[i].codec == avstream->codecpar->codec_id) { if (subtitle_format_map[i].subtype) mtype.subtype = *subtitle_format_map[i].subtype; break; } } // not type found if (mtype.subtype == MEDIASUBTYPE_NULL) return E_FAIL; mtypes.push_back(mtype); return S_OK; } ================================================ FILE: demuxer/Demuxers/LAVFStreamInfo.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #pragma once #include #include "StreamInfo.h" class CLAVFStreamInfo : public CStreamInfo { public: CLAVFStreamInfo(AVFormatContext *avctx, AVStream *avstream, const char *containerFormat, HRESULT &hr); ~CLAVFStreamInfo(); STDMETHODIMP CreateAudioMediaType(AVFormatContext *avctx, AVStream *avstream); STDMETHODIMP CreateVideoMediaType(AVFormatContext *avctx, AVStream *avstream); STDMETHODIMP CreateSubtitleMediaType(AVFormatContext *avctx, AVStream *avstream); private: std::string m_containerFormat; }; ================================================ FILE: demuxer/Demuxers/LAVFUtils.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "lavfutils.h" #include static int64_t get_bit_rate(const AVCodecParameters *par) { int64_t bit_rate; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_DATA: case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_ATTACHMENT: bit_rate = par->bit_rate; break; case AVMEDIA_TYPE_AUDIO: bit_rate = par->bit_rate ? par->bit_rate : par->sample_rate * par->ch_layout.nb_channels * av_get_bits_per_sample(par->codec_id); break; default: bit_rate = 0; break; } return bit_rate; } const char *get_stream_language(const AVStream *pStream) { char *lang = nullptr; if (AVDictionaryEntry *dictEntry = av_dict_get(pStream->metadata, "language", nullptr, 0)) { lang = dictEntry->value; } // Don't bother with undetermined languages (fallback value in some containers) if (lang && strncmp(lang, "und", 3)) return lang; return nullptr; } struct s_id_map { int id; const char *name; }; struct s_id_map nice_codec_names[] = { // Video {AV_CODEC_ID_H264, "h264"}, // XXX: Do not remove, required for custom profile/level formatting {AV_CODEC_ID_HEVC, "hevc"}, // XXX: Do not remove, required for custom profile/level formatting {AV_CODEC_ID_VC1, "vc-1"}, // XXX: Do not remove, required for custom profile/level formatting {AV_CODEC_ID_MPEG2VIDEO, "mpeg2"}, // Audio {AV_CODEC_ID_DTS, "dts"}, {AV_CODEC_ID_AAC_LATM, "aac (latm)"}, // Subs {AV_CODEC_ID_TEXT, "txt"}, {AV_CODEC_ID_MOV_TEXT, "tx3g"}, {AV_CODEC_ID_SRT, "srt"}, {AV_CODEC_ID_HDMV_PGS_SUBTITLE, "pgs"}, {AV_CODEC_ID_DVD_SUBTITLE, "vobsub"}, {AV_CODEC_ID_DVB_SUBTITLE, "dvbsub"}, {AV_CODEC_ID_SSA, "ssa/ass"}, {AV_CODEC_ID_XSUB, "xsub"}, }; // Uppercase the given string static std::string tolower(const char *str) { size_t len = strlen(str); std::string ret(len, char()); for (size_t i = 0; i < len; ++i) { ret[i] = (str[i] <= 'Z' && str[i] >= 'A') ? str[i] + ('a' - 'A') : str[i]; } return ret; } std::string get_codec_name(const AVCodecParameters *par) { AVCodecID id = par->codec_id; // Grab the codec const AVCodec *p = avcodec_find_decoder(id); const AVCodecDescriptor *desc = avcodec_descriptor_get(id); const char *profile = avcodec_profile_name(id, par->profile); std::ostringstream codec_name; const char *nice_name = nullptr; for (int i = 0; i < countof(nice_codec_names); ++i) { if (nice_codec_names[i].id == id) { nice_name = nice_codec_names[i].name; break; } } if (id == AV_CODEC_ID_DTS && par->codec_tag == 0xA2) { profile = "DTS Express"; } else if (id == AV_CODEC_ID_EAC3 && par->profile == AV_PROFILE_EAC3_DDP_ATMOS) { profile = "atmos"; } else if (id == AV_CODEC_ID_TRUEHD && par->profile == AV_PROFILE_TRUEHD_ATMOS) { profile = "atmos"; } if (id == AV_CODEC_ID_H264 && profile) { codec_name << nice_name << " " << tolower(profile); if (par->level && par->level != AV_LEVEL_UNKNOWN && par->level < 1000) { char l_buf[5]; sprintf_s(l_buf, "%.1f", par->level / 10.0); codec_name << " L" << l_buf; } } else if (id == AV_CODEC_ID_HEVC && profile) { codec_name << nice_name << " " << tolower(profile); if (par->level && par->level != AV_LEVEL_UNKNOWN && par->level < 1000) { char l_buf[5]; sprintf_s(l_buf, "%.1f", par->level / 30.0); codec_name << " L" << l_buf; } } else if (id == AV_CODEC_ID_VC1 && profile) { codec_name << nice_name << " " << tolower(profile); if (par->level != AV_LEVEL_UNKNOWN) { codec_name << " L" << par->level; } } else if (id == AV_CODEC_ID_DTS && profile) { codec_name << tolower(profile); } else if (id == AV_CODEC_ID_JPEG2000 && profile) { codec_name << tolower(profile); } else if (nice_name) { codec_name << nice_name; if (profile) codec_name << " " << tolower(profile); } else if (desc && desc->name) { codec_name << desc->name; if (profile) codec_name << " " << tolower(profile); } else if (p && p->name) { codec_name << p->name; if (profile) codec_name << " " << tolower(profile); } else { /* output avi tags */ char buf[AV_FOURCC_MAX_STRING_SIZE] = {0}; codec_name << av_fourcc_make_string(buf, par->codec_tag); sprintf_s(buf, "0x%04X", par->codec_tag); codec_name << " / " << buf; } return codec_name.str(); } #define SUPPORTED_FLAGS \ (AV_DISPOSITION_FORCED | AV_DISPOSITION_DEFAULT | AV_DISPOSITION_HEARING_IMPAIRED | \ AV_DISPOSITION_VISUAL_IMPAIRED | LAVF_DISPOSITION_SUB_STREAM | LAVF_DISPOSITION_SECONDARY_AUDIO) static std::string format_flags(int flags) { std::ostringstream out; #define FLAG_TAG(f, s) \ if (flags & f) \ { \ if (!first) \ out << ","; \ out << s; \ first = false; \ } if (flags & SUPPORTED_FLAGS) { bool first = true; out << " ["; FLAG_TAG(AV_DISPOSITION_DEFAULT, "default"); FLAG_TAG(AV_DISPOSITION_FORCED, "forced"); FLAG_TAG(AV_DISPOSITION_HEARING_IMPAIRED, "hearing impaired"); FLAG_TAG(AV_DISPOSITION_VISUAL_IMPAIRED, "visual impaired"); FLAG_TAG(LAVF_DISPOSITION_SUB_STREAM, "sub"); FLAG_TAG(LAVF_DISPOSITION_SECONDARY_AUDIO, "secondary"); out << "]"; } return out.str(); } static bool show_sample_fmt(const AVCodecParameters *par) { AVCodecID codec_id = par->codec_id; // PCM Codecs if (codec_id >= 0x10000 && codec_id < 0x12000) { return true; } // Lossless Codecs if (codec_id == AV_CODEC_ID_MLP || codec_id == AV_CODEC_ID_TRUEHD || codec_id == AV_CODEC_ID_FLAC || codec_id == AV_CODEC_ID_WMALOSSLESS || codec_id == AV_CODEC_ID_WAVPACK || codec_id == AV_CODEC_ID_MP4ALS || codec_id == AV_CODEC_ID_ALAC) { return true; } // Lossless DTS if (codec_id == AV_CODEC_ID_DTS && par->profile == AV_PROFILE_DTS_HD_MA) return true; return false; } const char *lavf_get_stream_title(const AVStream *pStream) { char *title = nullptr; if (AVDictionaryEntry *dictEntry = av_dict_get(pStream->metadata, "title", nullptr, 0)) { title = dictEntry->value; } else if (AVDictionaryEntry *dictEntry = av_dict_get(pStream->metadata, "handler_name", nullptr, 0)) { title = dictEntry->value; if (title && strstr(title, "Handle") != nullptr) title = nullptr; } return title; } std::string lavf_get_stream_description(const AVStream *pStream) { AVCodecParameters *par = pStream->codecpar; std::string codec_name = get_codec_name(par); const char *lang = get_stream_language(pStream); std::string sLanguage; if (lang) { sLanguage = ProbeLangForLanguage(lang); if (sLanguage.empty()) { sLanguage = lang; } } const char *title = lavf_get_stream_title(pStream); // Empty titles are rather useless if (title && strlen(title) == 0) title = nullptr; int64_t bitrate = get_bit_rate(par); std::ostringstream buf; switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: buf << "V: "; // Title/Language if (title && lang) { buf << title << " [" << lang << "] ("; } else if (title) { // Print either title or lang buf << title << " ("; } else if (lang) { buf << sLanguage << " [" << lang << "] ("; } // Codec buf << codec_name; // Pixel Format if (const char *pix_fmt = av_get_pix_fmt_name((AVPixelFormat)par->format)) { buf << ", " << pix_fmt; } // Dimensions if (par->width) { buf << ", " << par->width << "x" << par->height; } // Bitrate if (bitrate > 0) { buf << ", " << (bitrate / 1000) << " kb/s"; } if (par->codec_id == AV_CODEC_ID_H264 && par->profile == AV_PROFILE_H264_STEREO_HIGH) { AVDictionaryEntry *entry = av_dict_get(pStream->metadata, "stereo_mode", nullptr, 0); if (entry && strcmp(entry->value, "mvc_lr") == 0) buf << ", lr"; else if (entry && strcmp(entry->value, "mvc_rl") == 0) buf << ", rl"; } // Closing tag if (title || lang) { buf << ")"; } buf << format_flags(pStream->disposition); break; case AVMEDIA_TYPE_AUDIO: buf << "A: "; // Title/Language if (title && lang) { buf << title << " [" << lang << "] ("; } else if (title) { // Print either title or lang buf << title << " ("; } else if (lang) { buf << sLanguage << " [" << lang << "] ("; } // Codec buf << codec_name; // Sample Rate if (par->sample_rate) { buf << ", " << par->sample_rate << " Hz"; } if (par->ch_layout.nb_channels) { // Get channel layout char channel[64] = {0}; av_channel_layout_describe(&par->ch_layout, channel, sizeof(channel)); buf << ", " << channel; } // Sample Format if (show_sample_fmt(par) && get_bits_per_sample(par, true)) { if (par->format == AV_SAMPLE_FMT_FLT || par->format == AV_SAMPLE_FMT_DBL) { buf << ", fp"; } else { buf << ", s"; } buf << get_bits_per_sample(par, true); } // Bitrate if (bitrate > 0) { buf << ", " << (bitrate / 1000) << " kb/s"; } // Closing tag if (title || lang) { buf << ")"; } // Flags buf << format_flags(pStream->disposition); break; case AVMEDIA_TYPE_SUBTITLE: buf << "S: "; // Title/Language if (title && lang) { buf << title << " [" << lang << "] ("; } else if (title) { // Print either title or lang buf << title << " ("; } else if (lang) { buf << sLanguage << " [" << lang << "] ("; } // Codec buf << codec_name; if (title || lang) { buf << ")"; } // Subtitle flags buf << format_flags(pStream->disposition); break; default: buf << "Unknown: Stream #" << pStream->index; break; } return buf.str(); } bool GetH264MVCStreamIndices(AVFormatContext *fmt, int *nBaseIndex, int *nExtensionIndex) { bool bResult = true; *nBaseIndex = -1; *nExtensionIndex = -1; for (unsigned int i = 0; i < fmt->nb_streams; i++) { AVStream *st = fmt->streams[i]; if (st->codecpar->codec_id == AV_CODEC_ID_H264_MVC && st->codecpar->extradata_size > 0) { if (*nExtensionIndex == -1) *nExtensionIndex = i; else { DbgLog((LOG_TRACE, 10, L" -> Multiple H264 MVC extension streams, unsupported.")); bResult = false; } } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { if ((st->codecpar->width == 1920 && st->codecpar->height == 1080) || (st->codecpar->width == 1280 && st->codecpar->height == 720)) { if (*nBaseIndex == -1) *nBaseIndex = i; else { AVProgram *pBaseProgram = av_find_program_from_stream(fmt, nullptr, *nBaseIndex); AVProgram *pNewProgram = av_find_program_from_stream(fmt, nullptr, i); if (!pBaseProgram && pNewProgram) { *nBaseIndex = i; continue; } else if (!pNewProgram && pBaseProgram) { continue; } DbgLog((LOG_TRACE, 10, L" -> Multiple H264 MVC base streams, unsupported.")); bResult = false; } } } } bResult = bResult && *nBaseIndex >= 0 && *nExtensionIndex >= 0; return bResult; } #ifdef DEBUG #define LAVF_PARSE_TYPE(x) \ case x: return #x; const char *lavf_get_parsing_string(enum AVStreamParseType parsing) { switch (parsing) { LAVF_PARSE_TYPE(AVSTREAM_PARSE_NONE); LAVF_PARSE_TYPE(AVSTREAM_PARSE_FULL); LAVF_PARSE_TYPE(AVSTREAM_PARSE_HEADERS); LAVF_PARSE_TYPE(AVSTREAM_PARSE_TIMESTAMPS); LAVF_PARSE_TYPE(AVSTREAM_PARSE_FULL_ONCE); }; return "unknown"; } #endif ================================================ FILE: demuxer/Demuxers/LAVFUtils.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once struct FormatMapping { AVCodecID codec; const GUID *subtype; unsigned codecTag; const GUID *format; }; const char *get_stream_language(const AVStream *pStream); std::string get_codec_name(const AVCodecParameters *par); const char *lavf_get_stream_title(const AVStream *pStream); std::string lavf_get_stream_description(const AVStream *pStream); #define LAVF_DISPOSITION_SUB_STREAM 0x10000 #define LAVF_DISPOSITION_SECONDARY_AUDIO 0x20000 inline int get_bits_per_sample(AVCodecParameters *par, bool bRaw = false) { int bits = av_get_bits_per_sample(par->codec_id); if (!bits || bRaw) { bits = par->bits_per_coded_sample; if (!bits || bRaw) { if ((par->format == AV_SAMPLE_FMT_S32 || par->format == AV_SAMPLE_FMT_S32P) && par->bits_per_raw_sample) { bits = par->bits_per_raw_sample; } else { bits = av_get_bytes_per_sample((AVSampleFormat)par->format) << 3; } } } return bits; } bool GetH264MVCStreamIndices(AVFormatContext *fmt, int *nBaseIndex, int *nExtensionIndex); #ifdef DEBUG const char *lavf_get_parsing_string(enum AVStreamParseType parsing); #endif ================================================ FILE: demuxer/Demuxers/LAVFVideoHelper.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #include "stdafx.h" #include "LAVFUtils.h" #include "LAVFVideoHelper.h" #include "moreuuids.h" #include "BaseDemuxer.h" #include "ExtradataParser.h" #include "H264Nalu.h" // 250fps is the highest we accept as "sane" #define MIN_TIME_PER_FRAME 40000 // 8fps is the lowest that is "sane" in our definition #define MAX_TIME_PER_FRAME 1250000 CLAVFVideoHelper g_VideoHelper; // Map codec ids to media subtypes // clang-format off static FormatMapping video_map[] = { { AV_CODEC_ID_H263, &MEDIASUBTYPE_H263, 0, nullptr }, { AV_CODEC_ID_H263I, &MEDIASUBTYPE_I263, 0, nullptr }, { AV_CODEC_ID_H264, &MEDIASUBTYPE_AVC1, 0, &FORMAT_MPEG2Video }, { AV_CODEC_ID_HEVC, &MEDIASUBTYPE_HEVC, 0, &FORMAT_MPEG2Video }, { AV_CODEC_ID_MPEG1VIDEO, &MEDIASUBTYPE_MPEG1Payload, 0, &FORMAT_MPEGVideo }, { AV_CODEC_ID_MPEG2VIDEO, &MEDIASUBTYPE_MPEG2_VIDEO, 0, &FORMAT_MPEG2Video }, { AV_CODEC_ID_RV10, &MEDIASUBTYPE_RV10, MKTAG('R','V','1','0'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_RV20, &MEDIASUBTYPE_RV20, MKTAG('R','V','2','0'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_RV30, &MEDIASUBTYPE_RV30, MKTAG('R','V','3','0'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_RV40, &MEDIASUBTYPE_RV40, MKTAG('R','V','4','0'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_AMV, &MEDIASUBTYPE_AMVV, MKTAG('A','M','V','V'), nullptr }, { AV_CODEC_ID_TIFF, &MEDIASUBTYPE_TIFF, MKTAG('T','I','F','F'), nullptr }, { AV_CODEC_ID_PNG, &MEDIASUBTYPE_PNG, MKTAG('P','N','G',' '), nullptr }, { AV_CODEC_ID_BMP, &MEDIASUBTYPE_BMP, MKTAG('B','M','P',' '), nullptr }, { AV_CODEC_ID_GIF, &MEDIASUBTYPE_GIF, MKTAG('G','I','F',' '), nullptr }, { AV_CODEC_ID_TARGA, &MEDIASUBTYPE_TGA, MKTAG('T','G','A',' '), nullptr }, { AV_CODEC_ID_VP8, &MEDIASUBTYPE_VP80, MKTAG('V','P','8','0'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_VP9, &MEDIASUBTYPE_VP90, MKTAG('V','P','9','0'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_AV1, &MEDIASUBTYPE_AV01, MKTAG('A','V','0','1'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_CFHD, &MEDIASUBTYPE_CFHD, MKTAG('C','F','H','D'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_VVC, &MEDIASUBTYPE_VVC1, MKTAG('V','V','C','1'), &FORMAT_MPEG2Video }, { AV_CODEC_ID_WEBP, &MEDIASUBTYPE_WEBP, MKTAG('W','E','B','P'), &FORMAT_VideoInfo2 }, { AV_CODEC_ID_APV, &MEDIASUBTYPE_APV1, MKTAG('A','P','V','1'), &FORMAT_VideoInfo2 }, }; // clang-format on CMediaType CLAVFVideoHelper::initVideoType(AVCodecID codecId, unsigned int &codecTag, std::string container) { CMediaType mediaType; mediaType.InitMediaType(); mediaType.majortype = MEDIATYPE_Video; mediaType.subtype = FOURCCMap(codecTag); mediaType.formattype = FORMAT_VideoInfo; // default value // Check against values from the map above for (unsigned i = 0; i < countof(video_map); ++i) { if (video_map[i].codec == codecId) { if (video_map[i].subtype) mediaType.subtype = *video_map[i].subtype; if (video_map[i].codecTag) codecTag = video_map[i].codecTag; if (video_map[i].format) mediaType.formattype = *video_map[i].format; break; } } switch (codecId) { // All these codecs should use VideoInfo2 case AV_CODEC_ID_ASV1: case AV_CODEC_ID_ASV2: case AV_CODEC_ID_FLV1: case AV_CODEC_ID_HUFFYUV: case AV_CODEC_ID_WMV3: mediaType.formattype = FORMAT_VideoInfo2; break; case AV_CODEC_ID_MPEG4: if (container == "mp4") { mediaType.formattype = FORMAT_MPEG2Video; } else if (container == "mpegts") { mediaType.formattype = FORMAT_VideoInfo2; mediaType.subtype = MEDIASUBTYPE_MP4V; } else { mediaType.formattype = FORMAT_VideoInfo2; } break; case AV_CODEC_ID_VC1: if (codecTag != MKTAG('W', 'M', 'V', 'A')) codecTag = MKTAG('W', 'V', 'C', '1'); mediaType.formattype = FORMAT_VideoInfo2; mediaType.subtype = FOURCCMap(codecTag); break; case AV_CODEC_ID_DVVIDEO: if (codecTag == 0) mediaType.subtype = MEDIASUBTYPE_DVCP; break; } return mediaType; } DWORD avc_quant(BYTE *src, BYTE *dst, int extralen) { DWORD cb = 0; BYTE *src_end = (BYTE *)src + extralen; BYTE *dst_end = (BYTE *)dst + extralen; src += 5; // Two runs, for sps and pps for (int i = 0; i < 2; i++) { for (int n = *(src++) & 0x1f; n > 0; n--) { unsigned len = (((unsigned)src[0] << 8) | src[1]) + 2; if (src + len > src_end || dst + len > dst_end) { ASSERT(0); break; } memcpy(dst, src, len); src += len; dst += len; cb += len; } } return cb; } size_t avc_parse_annexb(BYTE *extra, int extrasize, BYTE *dst) { size_t dstSize = 0; CH264Nalu Nalu; Nalu.SetBuffer(extra, extrasize, 0); while (Nalu.ReadNext()) { if (Nalu.GetType() == NALU_TYPE_SPS || Nalu.GetType() == NALU_TYPE_PPS) { size_t len = Nalu.GetDataLength(); AV_WB16(dst + dstSize, (uint16_t)len); dstSize += 2; memcpy(dst + dstSize, Nalu.GetDataBuffer(), Nalu.GetDataLength()); dstSize += Nalu.GetDataLength(); } } return dstSize; } VIDEOINFOHEADER *CLAVFVideoHelper::CreateVIH(const AVStream *avstream, ULONG *size, std::string container) { VIDEOINFOHEADER *pvi = (VIDEOINFOHEADER *)CoTaskMemAlloc(ULONG(sizeof(VIDEOINFOHEADER) + avstream->codecpar->extradata_size)); if (!pvi) return nullptr; memset(pvi, 0, sizeof(VIDEOINFOHEADER)); REFERENCE_TIME r_avg = 0, avg_avg = 0, codec_avg = 0; if (avstream->r_frame_rate.den > 0 && avstream->r_frame_rate.num > 0) { r_avg = av_rescale(DSHOW_TIME_BASE, avstream->r_frame_rate.den, avstream->r_frame_rate.num); } if (avstream->avg_frame_rate.den > 0 && avstream->avg_frame_rate.num > 0) { avg_avg = av_rescale(DSHOW_TIME_BASE, avstream->avg_frame_rate.den, avstream->avg_frame_rate.num); } if (avstream->codecpar->framerate.den > 0 && avstream->codecpar->framerate.num > 0) { codec_avg = av_rescale(DSHOW_TIME_BASE, avstream->codecpar->framerate.den, avstream->codecpar->framerate.num); } DbgLog((LOG_TRACE, 10, L"CreateVIH: r_avg: %I64d, avg_avg: %I64d, tb_avg: %I64d", r_avg, avg_avg, codec_avg)); if (avg_avg >= MIN_TIME_PER_FRAME && avg_avg <= MAX_TIME_PER_FRAME) { // prefer the more accurate r_avg when its close to the average if (abs(r_avg - avg_avg) < 10000) pvi->AvgTimePerFrame = r_avg; else pvi->AvgTimePerFrame = avg_avg; } else if (r_avg >= MIN_TIME_PER_FRAME && r_avg <= MAX_TIME_PER_FRAME) pvi->AvgTimePerFrame = r_avg; else if (codec_avg >= MIN_TIME_PER_FRAME && codec_avg <= MAX_TIME_PER_FRAME) pvi->AvgTimePerFrame = codec_avg; else pvi->AvgTimePerFrame = r_avg; if ((container == "matroska" || container == "mp4") && r_avg && codec_avg && (avstream->codecpar->codec_id == AV_CODEC_ID_H264 || avstream->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO)) { float factor = (float)r_avg / (float)codec_avg; if ((factor > 0.4 && factor < 0.6) || (factor > 1.9 && factor < 2.1)) { pvi->AvgTimePerFrame = codec_avg; } } pvi->dwBitErrorRate = 0; pvi->dwBitRate = (DWORD)avstream->codecpar->bit_rate; RECT empty_tagrect = {0, 0, 0, 0}; pvi->rcSource = empty_tagrect; // Some codecs like wmv are setting that value to the video current value pvi->rcTarget = empty_tagrect; pvi->rcTarget.right = pvi->rcSource.right = avstream->codecpar->width; pvi->rcTarget.bottom = pvi->rcSource.bottom = avstream->codecpar->height; memcpy((BYTE *)&pvi->bmiHeader + sizeof(BITMAPINFOHEADER), avstream->codecpar->extradata, avstream->codecpar->extradata_size); pvi->bmiHeader.biSize = ULONG(sizeof(BITMAPINFOHEADER) + avstream->codecpar->extradata_size); pvi->bmiHeader.biWidth = avstream->codecpar->width; pvi->bmiHeader.biHeight = avstream->codecpar->height; pvi->bmiHeader.biBitCount = avstream->codecpar->bits_per_coded_sample; // Validate biBitCount is set to something useful if ((pvi->bmiHeader.biBitCount == 0 || avstream->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) && avstream->codecpar->format != AV_PIX_FMT_NONE) { const AVPixFmtDescriptor *pixdecs = av_pix_fmt_desc_get((AVPixelFormat)avstream->codecpar->format); if (pixdecs) pvi->bmiHeader.biBitCount = av_get_bits_per_pixel(pixdecs); } pvi->bmiHeader.biSizeImage = DIBSIZE(pvi->bmiHeader); // Calculating this value doesn't really make alot of sense, // but apparently some decoders freak out if its 0 pvi->bmiHeader.biCompression = avstream->codecpar->codec_tag; // TOFIX The bitplanes is depending on the subtype pvi->bmiHeader.biPlanes = 1; pvi->bmiHeader.biClrUsed = 0; pvi->bmiHeader.biClrImportant = 0; pvi->bmiHeader.biYPelsPerMeter = 0; pvi->bmiHeader.biXPelsPerMeter = 0; *size = sizeof(VIDEOINFOHEADER) + avstream->codecpar->extradata_size; return pvi; } #define VC1_CODE_RES0 0x00000100 #define IS_VC1_MARKER(x) (((x) & ~0xFF) == VC1_CODE_RES0) VIDEOINFOHEADER2 *CLAVFVideoHelper::CreateVIH2(const AVStream *avstream, ULONG *size, std::string container) { int extra = 0; BYTE *extradata = nullptr; BOOL bZeroPad = FALSE; if (avstream->codecpar->codec_id == AV_CODEC_ID_VC1 && avstream->codecpar->extradata_size) { int i = 0; for (i = 0; i < (avstream->codecpar->extradata_size - 4); i++) { uint32_t code = AV_RB32(avstream->codecpar->extradata + i); if (IS_VC1_MARKER(code)) break; } if (i == 0) { bZeroPad = TRUE; } else if (i > 1) { DbgLog((LOG_TRACE, 10, L"CLAVFVideoHelper::CreateVIH2(): VC-1 extradata does not start at position 0/1, but %d", i)); } } // Create a VIH that we'll convert VIDEOINFOHEADER *vih = CreateVIH(avstream, size, container); if (!vih) return nullptr; if (avstream->codecpar->extradata_size > 0) { extra = avstream->codecpar->extradata_size; // increase extra size by one, because VIH2 requires one 0 byte between header and extra data if (bZeroPad) { extra++; } extradata = avstream->codecpar->extradata; } VIDEOINFOHEADER2 *vih2 = (VIDEOINFOHEADER2 *)CoTaskMemAlloc(sizeof(VIDEOINFOHEADER2) + extra); if (!vih2) return nullptr; memset(vih2, 0, sizeof(VIDEOINFOHEADER2)); vih2->rcSource = vih->rcSource; vih2->rcTarget = vih->rcTarget; vih2->dwBitRate = vih->dwBitRate; vih2->dwBitErrorRate = vih->dwBitErrorRate; vih2->AvgTimePerFrame = vih->AvgTimePerFrame; // Calculate aspect ratio AVRational r = avstream->sample_aspect_ratio; AVRational rc = avstream->codecpar->sample_aspect_ratio; int num = vih->bmiHeader.biWidth, den = vih->bmiHeader.biHeight; if (r.den > 0 && r.num > 0) { av_reduce(&num, &den, (int64_t)r.num * num, (int64_t)r.den * den, UINT16_MAX); } else if (rc.den > 0 && rc.num > 0) { av_reduce(&num, &den, (int64_t)rc.num * num, (int64_t)rc.den * den, UINT16_MAX); } else { av_reduce(&num, &den, num, den, num); } vih2->dwPictAspectRatioX = num; vih2->dwPictAspectRatioY = den; memcpy(&vih2->bmiHeader, &vih->bmiHeader, sizeof(BITMAPINFOHEADER)); vih2->bmiHeader.biSize = sizeof(BITMAPINFOHEADER) + extra; vih2->dwInterlaceFlags = 0; vih2->dwCopyProtectFlags = 0; vih2->dwControlFlags = 0; vih2->dwReserved2 = 0; if (extra) { // The first byte after the infoheader has to be 0 in mpeg-ts if (bZeroPad) { *((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2)) = 0; // after that, the extradata .. size reduced by one again memcpy((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2) + 1, extradata, extra - 1); } else { memcpy((BYTE *)vih2 + sizeof(VIDEOINFOHEADER2), extradata, extra); } } // Free the VIH that we converted CoTaskMemFree(vih); *size = sizeof(VIDEOINFOHEADER2) + extra; return vih2; } MPEG1VIDEOINFO *CLAVFVideoHelper::CreateMPEG1VI(const AVStream *avstream, ULONG *size, std::string container) { int extra = 0; BYTE *extradata = nullptr; // Create a VIH that we'll convert VIDEOINFOHEADER *vih = CreateVIH(avstream, size, container); if (!vih) return nullptr; if (avstream->codecpar->extradata_size > 0) { extra = avstream->codecpar->extradata_size; extradata = avstream->codecpar->extradata; } MPEG1VIDEOINFO *mp1vi = (MPEG1VIDEOINFO *)CoTaskMemAlloc(sizeof(MPEG1VIDEOINFO) + extra); if (!mp1vi) return nullptr; memset(mp1vi, 0, sizeof(MPEG1VIDEOINFO)); // The MPEG1VI is a thin wrapper around a VIH, so its easy! memcpy(&mp1vi->hdr, vih, sizeof(VIDEOINFOHEADER)); mp1vi->hdr.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); mp1vi->dwStartTimeCode = 0; // is this not 0 anywhere..? mp1vi->hdr.bmiHeader.biPlanes = 1; mp1vi->hdr.bmiHeader.biCompression = 0; // copy extradata over if (extra) { CExtradataParser parser = CExtradataParser(extradata, extra); mp1vi->cbSequenceHeader = (DWORD)parser.ParseMPEGSequenceHeader(mp1vi->bSequenceHeader); } // Free the VIH that we converted CoTaskMemFree(vih); *size = SIZE_MPEG1VIDEOINFO(mp1vi); return mp1vi; } MPEG2VIDEOINFO *CLAVFVideoHelper::CreateMPEG2VI(const AVStream *avstream, ULONG *size, std::string container, BOOL bConvertToAVC1) { int extra = 0; BYTE *extradata = nullptr; // Create a VIH that we'll convert VIDEOINFOHEADER2 *vih2 = CreateVIH2(avstream, size, container); if (!vih2) return nullptr; if (avstream->codecpar->extradata_size > 0) { extra = avstream->codecpar->extradata_size; extradata = avstream->codecpar->extradata; } MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)CoTaskMemAlloc(sizeof(MPEG2VIDEOINFO) + max(extra - 4, 0)); if (!mp2vi) return nullptr; memset(mp2vi, 0, sizeof(MPEG2VIDEOINFO)); memcpy(&mp2vi->hdr, vih2, sizeof(VIDEOINFOHEADER2)); mp2vi->hdr.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); // Set profile/level if we know them mp2vi->dwProfile = (avstream->codecpar->profile != AV_PROFILE_UNKNOWN) ? avstream->codecpar->profile : 0; mp2vi->dwLevel = (avstream->codecpar->level != AV_LEVEL_UNKNOWN) ? avstream->codecpar->level : 0; // mp2vi->dwFlags = 4; // where do we get flags otherwise..? if (extra > 0) { BOOL bCopyUntouched = FALSE; if (avstream->codecpar->codec_id == AV_CODEC_ID_H264) { int ret = ProcessH264Extradata(extradata, extra, mp2vi, bConvertToAVC1); if (ret < 0) bCopyUntouched = TRUE; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_HEVC) { int ret = ProcessHEVCExtradata(extradata, extra, mp2vi); if (ret < 0) bCopyUntouched = TRUE; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_VVC) { int ret = ProcessVVCExtradata(extradata, extra, mp2vi); if (ret < 0) bCopyUntouched = TRUE; } else if (avstream->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO) { CExtradataParser parser = CExtradataParser(extradata, extra); mp2vi->cbSequenceHeader = (DWORD)parser.ParseMPEGSequenceHeader((BYTE *)&mp2vi->dwSequenceHeader[0]); mp2vi->hdr.bmiHeader.biPlanes = 1; mp2vi->hdr.bmiHeader.biCompression = 0; } else { bCopyUntouched = TRUE; } if (bCopyUntouched) { mp2vi->cbSequenceHeader = extra; memcpy(&mp2vi->dwSequenceHeader[0], extradata, extra); } } // Free the VIH2 that we converted CoTaskMemFree(vih2); *size = SIZE_MPEG2VIDEOINFO(mp2vi); return mp2vi; } HRESULT CLAVFVideoHelper::ProcessH264Extradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi, BOOL bAnnexB) { if (*(char *)extradata == 1) { if (extradata[1]) mp2vi->dwProfile = extradata[1]; if (extradata[3]) mp2vi->dwLevel = extradata[3]; mp2vi->dwFlags = (extradata[4] & 3) + 1; mp2vi->cbSequenceHeader = avc_quant(extradata, (BYTE *)(&mp2vi->dwSequenceHeader[0]), extradata_size); } else { // MPEG-TS gets converted for improved compat.. for now! if (bAnnexB) { mp2vi->dwFlags = 4; mp2vi->cbSequenceHeader = (DWORD)avc_parse_annexb(extradata, extradata_size, (BYTE *)(&mp2vi->dwSequenceHeader[0])); } else { return -1; } } return 0; } HRESULT CLAVFVideoHelper::ProcessH264MVCExtradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi) { if (*(char *)extradata == 1) { // Find "mvcC" atom uint32_t state = -1; int i = 0; for (; i < extradata_size; i++) { state = (state << 8) | extradata[i]; if (state == MKBETAG('m', 'v', 'c', 'C')) break; } if (i == extradata_size || i < 8) return E_FAIL; // Update pointers to the start of the mvcC atom extradata = extradata + i - 7; extradata_size = extradata_size - i + 7; int sizeAtom = AV_RB32(extradata); // verify size atom and actual size if ((sizeAtom + 4) > extradata_size || extradata_size < 14) return E_FAIL; // Skip atom headers extradata += 8; extradata_size -= 8; // Process as a normal "avcC" record ProcessH264Extradata(extradata, extradata_size, mp2vi, FALSE); return S_OK; } return E_FAIL; } HRESULT CLAVFVideoHelper::ProcessHEVCExtradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi) { if (extradata[0] || extradata[1] || extradata[2] > 1 && extradata_size > 25) { mp2vi->dwFlags = (extradata[21] & 3) + 1; } return -1; } HRESULT CLAVFVideoHelper::ProcessVVCExtradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi) { if (extradata[0] || extradata[1] || extradata[2] > 1 && extradata_size > 25) { mp2vi->dwFlags = (extradata[21] & 3) + 1; } return -1; } ================================================ FILE: demuxer/Demuxers/LAVFVideoHelper.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #pragma once #include "dvdmedia.h" // clang-format off const AVCodecTag mp_bmp_tags[] = { { AV_CODEC_ID_AMV, MKTAG('A', 'M', 'V', 'V')}, { AV_CODEC_ID_BETHSOFTVID, MKTAG('B', 'E', 'T', 'H')}, { AV_CODEC_ID_BFI, MKTAG('B', 'F', 'I', 'V')}, { AV_CODEC_ID_C93, MKTAG('C', '9', '3', 'V')}, { AV_CODEC_ID_CDGRAPHICS, MKTAG('C', 'D', 'G', 'R')}, { AV_CODEC_ID_DNXHD, MKTAG('A', 'V', 'd', 'n')}, { AV_CODEC_ID_DSICINVIDEO, MKTAG('D', 'C', 'I', 'V')}, { AV_CODEC_ID_DXA, MKTAG('D', 'X', 'A', '1')}, { AV_CODEC_ID_FLIC, MKTAG('F', 'L', 'I', 'C')}, { AV_CODEC_ID_IDCIN, MKTAG('I', 'D', 'C', 'I')}, { AV_CODEC_ID_INTERPLAY_VIDEO, MKTAG('I', 'N', 'P', 'V')}, { AV_CODEC_ID_MDEC, MKTAG('M', 'D', 'E', 'C')}, { AV_CODEC_ID_MOTIONPIXELS, MKTAG('M', 'V', 'I', '1')}, { AV_CODEC_ID_NUV, MKTAG('N', 'U', 'V', '1')}, { AV_CODEC_ID_RL2, MKTAG('R', 'L', '2', 'V')}, { AV_CODEC_ID_ROQ, MKTAG('R', 'o', 'Q', 'V')}, { AV_CODEC_ID_RV10, MKTAG('R', 'V', '1', '0')}, { AV_CODEC_ID_RV20, MKTAG('R', 'V', '2', '0')}, { AV_CODEC_ID_RV30, MKTAG('R', 'V', '3', '0')}, { AV_CODEC_ID_RV40, MKTAG('R', 'V', '4', '0')}, { AV_CODEC_ID_TGV, MKTAG('f', 'V', 'G', 'T')}, { AV_CODEC_ID_THP, MKTAG('T', 'H', 'P', 'V')}, { AV_CODEC_ID_TIERTEXSEQVIDEO, MKTAG('T', 'S', 'E', 'Q')}, { AV_CODEC_ID_TXD, MKTAG('T', 'X', 'D', 'V')}, { AV_CODEC_ID_VP6A, MKTAG('V', 'P', '6', 'A')}, { AV_CODEC_ID_VMDVIDEO, MKTAG('V', 'M', 'D', 'V')}, { AV_CODEC_ID_WS_VQA, MKTAG('V', 'Q', 'A', 'V')}, { AV_CODEC_ID_XAN_WC3, MKTAG('W', 'C', '3', 'V')}, { AV_CODEC_ID_WEBP, MKTAG('W', 'E', 'B', 'P')}, { AV_CODEC_ID_NONE, 0} }; // clang-format on const struct AVCodecTag *const mp_bmp_taglists[] = {avformat_get_riff_video_tags(), mp_bmp_tags, 0}; class CLAVFVideoHelper { public: CLAVFVideoHelper(){}; CMediaType initVideoType(AVCodecID codecId, unsigned int &codecTag, std::string container); VIDEOINFOHEADER *CreateVIH(const AVStream *avstream, ULONG *size, std::string container); VIDEOINFOHEADER2 *CreateVIH2(const AVStream *avstream, ULONG *size, std::string container); MPEG1VIDEOINFO *CreateMPEG1VI(const AVStream *avstream, ULONG *size, std::string container); MPEG2VIDEOINFO *CreateMPEG2VI(const AVStream *avstream, ULONG *size, std::string container, BOOL bConvertToAVC1 = FALSE); HRESULT ProcessH264Extradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi, BOOL bConvertToAVC1); HRESULT ProcessH264MVCExtradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi); HRESULT ProcessHEVCExtradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi); HRESULT ProcessVVCExtradata(BYTE *extradata, int extradata_size, MPEG2VIDEOINFO *mp2vi); }; extern CLAVFVideoHelper g_VideoHelper; ================================================ FILE: demuxer/Demuxers/Packet.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include #include "Packet.h" Packet::Packet() { } Packet::~Packet() { DeleteMediaType(pmt); av_packet_free(&m_Packet); } int Packet::SetDataSize(int len) { if (len < 0) return -1; if (len <= GetDataSize()) { av_shrink_packet(m_Packet, len); return 0; } if (!m_Packet) { m_Packet = av_packet_alloc(); if (av_new_packet(m_Packet, len) < 0) return -1; } else { if (av_grow_packet(m_Packet, (len - m_Packet->size)) < 0) return -1; } return 0; } int Packet::SetData(const void *ptr, int len) { if (!ptr || len < 0) return -1; int ret = SetDataSize(len); if (ret < 0) return ret; memcpy(m_Packet->data, ptr, len); return 0; } int Packet::SetPacket(AVPacket *pkt) { ASSERT(!m_Packet); m_Packet = av_packet_alloc(); if (!m_Packet) return -1; return av_packet_ref(m_Packet, pkt); } int Packet::Append(Packet *ptr) { return AppendData(ptr->GetData(), ptr->GetDataSize()); } int Packet::AppendData(const void *ptr, int len) { int prevSize = GetDataSize(); int ret = SetDataSize(prevSize + len); if (ret < 0) return ret; memcpy(m_Packet->data + prevSize, ptr, len); return 0; } int Packet::RemoveHead(int count) { m_Packet->data += count; m_Packet->size -= (int)count; return 0; } bool Packet::CopyProperties(const Packet *src) { StreamId = src->StreamId; bDiscontinuity = src->bDiscontinuity; bSyncPoint = src->bSyncPoint; bPosition = src->bPosition; rtStart = src->rtStart; rtStop = src->rtStop; rtPTS = src->rtPTS; rtDTS = src->rtDTS; if (src->pmt) pmt = CreateMediaType(src->pmt); dwFlags = src->dwFlags; return true; } ================================================ FILE: demuxer/Demuxers/Packet.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // Data Packet for queue storage class Packet { public: static const REFERENCE_TIME INVALID_TIME = _I64_MIN; Packet(); ~Packet(); int GetDataSize() const { return m_Packet ? m_Packet->size : 0; } BYTE *GetData() { return m_Packet ? m_Packet->data : nullptr; } int GetNumSideData() const { return m_Packet ? m_Packet->side_data_elems : 0; } AVPacketSideData *GetSideData() { return m_Packet ? m_Packet->side_data : nullptr; } int SetDataSize(int len); int SetData(const void *ptr, int len); int SetPacket(AVPacket *pkt); // Append the data of the package to our data buffer int Append(Packet *ptr); int AppendData(const void *ptr, int len); // Remove count bytes from position index int RemoveHead(int count); bool CopyProperties(const Packet *src); public: DWORD StreamId = 0; BOOL bDiscontinuity = FALSE; BOOL bSyncPoint = FALSE; LONGLONG bPosition = -1; REFERENCE_TIME rtStart = INVALID_TIME; REFERENCE_TIME rtStop = INVALID_TIME; REFERENCE_TIME rtPTS = INVALID_TIME; REFERENCE_TIME rtDTS = INVALID_TIME; AM_MEDIA_TYPE *pmt = nullptr; #define LAV_PACKET_PARSED 0x0001 #define LAV_PACKET_MOV_TEXT 0x0002 #define LAV_PACKET_FORCED_SUBTITLE 0x0004 #define LAV_PACKET_H264_ANNEXB 0x0008 #define LAV_PACKET_SRT 0x0010 #define LAV_PACKET_PLANAR_PCM 0x0020 DWORD dwFlags = 0; private: AVPacket *m_Packet = nullptr; }; ================================================ FILE: demuxer/Demuxers/StreamInfo.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "StreamInfo.h" CStreamInfo::CStreamInfo() { } CStreamInfo::~CStreamInfo() { } ================================================ FILE: demuxer/Demuxers/StreamInfo.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include class CStreamInfo { public: CStreamInfo(); virtual ~CStreamInfo(); std::deque mtypes; std::string codecInfo; }; ================================================ FILE: demuxer/Demuxers/stdafx.cpp ================================================ // stdafx.cpp : source file that includes just the standard includes // Demuxers.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file ================================================ FILE: demuxer/Demuxers/stdafx.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "common_defines.h" #include #include #include "streams.h" #pragma warning(push) #pragma warning(disable : 4244) extern "C" { #define __STDC_CONSTANT_MACROS #include "libavcodec/avcodec.h" #include "libavformat/avformat.h" #include "libavutil/channel_layout.h" #include "libavutil/display.h" #include "libavutil/intreadwrite.h" #include "libavutil/pixdesc.h" #include "libavutil/opt.h" #include "libbluray/bluray.h" #include "libbluray/bdnav/clpi_parse.h" } #pragma warning(pop) #define AVFORMAT_INTERNAL_H typedef struct AVCodecTag { enum AVCodecID id; unsigned int tag; } AVCodecTag; #include "util/log_control.h" #include "DShowUtil.h" #include #include // TODO: reference additional headers your program requires here ================================================ FILE: demuxer/LAVSplitter/InputPin.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "InputPin.h" #include "LAVSplitter.h" #define READ_BUFFER_SIZE 131072 CLAVInputPin::CLAVInputPin(TCHAR *pName, CLAVSplitter *pFilter, CCritSec *pLock, HRESULT *phr) : CBasePin(pName, pFilter, pLock, phr, L"Input", PINDIR_INPUT) { } CLAVInputPin::~CLAVInputPin(void) { if (m_pAVIOContext) { av_free(m_pAVIOContext->buffer); av_free(m_pAVIOContext); m_pAVIOContext = nullptr; } } STDMETHODIMP CLAVInputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); return __super::NonDelegatingQueryInterface(riid, ppv); } HRESULT CLAVInputPin::CheckMediaType(const CMediaType *pmt) { // return pmt->majortype == MEDIATYPE_Stream ? S_OK : VFW_E_TYPE_NOT_ACCEPTED; return S_OK; } HRESULT CLAVInputPin::CheckConnect(IPin *pPin) { HRESULT hr; if (FAILED(hr = __super::CheckConnect(pPin))) { return hr; } IAsyncReader *pReader = nullptr; if (FAILED(hr = pPin->QueryInterface(&pReader)) || pReader == nullptr) { return E_FAIL; } SafeRelease(&pReader); return S_OK; } HRESULT CLAVInputPin::BreakConnect() { HRESULT hr; if (FAILED(hr = __super::BreakConnect())) { return hr; } if (FAILED(hr = (static_cast(m_pFilter))->BreakInputConnection())) { return hr; } SafeRelease(&m_pAsyncReader); SafeRelease(&m_pStreamControl); if (m_pAVIOContext) { av_free(m_pAVIOContext->buffer); av_free(m_pAVIOContext); m_pAVIOContext = nullptr; } return S_OK; } HRESULT CLAVInputPin::CompleteConnect(IPin *pPin) { HRESULT hr; if (FAILED(hr = __super::CompleteConnect(pPin))) { return hr; } CheckPointer(pPin, E_POINTER); if (FAILED(hr = pPin->QueryInterface(&m_pAsyncReader)) || m_pAsyncReader == nullptr) { return E_FAIL; } m_llPos = 0; m_bURLSource = false; if (FAILED(pPin->QueryInterface(&m_pStreamControl))) m_pStreamControl = nullptr; PIN_INFO pinInfo = {0}; if (SUCCEEDED(pPin->QueryPinInfo(&pinInfo)) && pinInfo.pFilter) { CLSID clsidFilter = GUID_NULL; if (SUCCEEDED(pinInfo.pFilter->GetClassID(&clsidFilter))) { m_bURLSource = (clsidFilter == CLSID_URLReader); } if (m_pStreamControl == nullptr) if (FAILED(pinInfo.pFilter->QueryInterface(&m_pStreamControl))) m_pStreamControl = nullptr; SafeRelease(&(pinInfo.pFilter)); } if (FAILED(hr = (static_cast(m_pFilter))->CompleteInputConnection())) { return hr; } return S_OK; } int CLAVInputPin::Read(void *opaque, uint8_t *buf, int buf_size) { CLAVInputPin *pin = static_cast(opaque); CAutoLock lock(pin); // The URL source doesn't properly signal EOF in all cases, so make sure no stale data is in the buffer if (pin->m_bURLSource) memset(buf, 0, buf_size); HRESULT hr = pin->m_pAsyncReader->SyncRead(pin->m_llPos, buf_size, buf); if (FAILED(hr)) { DbgLog((LOG_TRACE, 10, L"Read failed at pos: %I64d, hr: 0x%X", pin->m_llPos, hr)); return AVERROR_EOF; } // The URL source can return S_OK even on incomplete reads, so run the length logic by it at all times if (hr == S_OK && pin->m_bURLSource) { LONGLONG total = 0, available = 0; int read = buf_size; if (S_OK == pin->m_pAsyncReader->Length(&total, &available) && total >= pin->m_llPos && total <= (pin->m_llPos + buf_size)) { read = (int)(total - pin->m_llPos); DbgLog((LOG_TRACE, 10, L"At EOF, pos: %I64d, size: %I64d, remainder: %d", pin->m_llPos, total, read)); } pin->m_llPos += read; return read > 0 ? read : AVERROR_EOF; } if (hr == S_FALSE) { LONGLONG total = 0, available = 0; int read = 0; if (S_OK == pin->m_pAsyncReader->Length(&total, &available) && total >= pin->m_llPos && total <= (pin->m_llPos + buf_size)) { read = (int)(total - pin->m_llPos); DbgLog((LOG_TRACE, 10, L"At EOF, pos: %I64d, size: %I64d, remainder: %d", pin->m_llPos, total, read)); } else { DbgLog((LOG_TRACE, 10, L"We're at EOF (pos: %I64d), but Length seems unreliable, trying reading manually", pin->m_llPos)); do { hr = pin->m_pAsyncReader->SyncRead(pin->m_llPos, 1, buf + read); } while (hr == S_OK && (++read) < buf_size); DbgLog((LOG_TRACE, 10, L"-> Read %d bytes", read)); } pin->m_llPos += read; return read > 0 ? read : AVERROR_EOF; } pin->m_llPos += buf_size; return buf_size; } int64_t CLAVInputPin::Seek(void *opaque, int64_t offset, int whence) { CLAVInputPin *pin = static_cast(opaque); CAutoLock lock(pin); LONGLONG total = 0; LONGLONG available = 0; pin->m_pAsyncReader->Length(&total, &available); if (whence == SEEK_SET) { pin->m_llPos = offset; } else if (whence == SEEK_CUR) { pin->m_llPos += offset; } else if (whence == SEEK_END) { pin->m_llPos = total - offset; } else if (whence == AVSEEK_SIZE) { return total; } else return -1; if (pin->m_llPos > available) pin->m_llPos = available; else if (pin->m_llPos < 0) pin->m_llPos = 0; return pin->m_llPos; } HRESULT CLAVInputPin::GetAVIOContext(AVIOContext **ppContext) { CheckPointer(m_pAsyncReader, E_UNEXPECTED); CheckPointer(ppContext, E_POINTER); if (!m_pAVIOContext) { uint8_t *buffer = (uint8_t *)av_mallocz(READ_BUFFER_SIZE + AV_INPUT_BUFFER_PADDING_SIZE); m_pAVIOContext = avio_alloc_context(buffer, READ_BUFFER_SIZE, 0, this, Read, nullptr, Seek); LONGLONG total = 0; LONGLONG available = 0; HRESULT hr = m_pAsyncReader->Length(&total, &available); if (FAILED(hr) || total == 0) { DbgLog((LOG_TRACE, 10, L"CLAVInputPin::GetAVIOContext(): getting file length failed, disabling seeking")); m_pAVIOContext->seekable = 0; m_pAVIOContext->seek = nullptr; m_pAVIOContext->buffer_size = READ_BUFFER_SIZE / 4; } } *ppContext = m_pAVIOContext; return S_OK; } STDMETHODIMP CLAVInputPin::BeginFlush() { return E_UNEXPECTED; } STDMETHODIMP CLAVInputPin::EndFlush() { return E_UNEXPECTED; } STDMETHODIMP CLAVInputPin::SeekStream(REFERENCE_TIME rtPosition) { CheckPointer(m_pStreamControl, E_NOTIMPL); HRESULT hr = m_pStreamControl->SeekStream(rtPosition); if (SUCCEEDED(hr)) { // flush the avio context to remove any buffered data if (m_pAVIOContext) { avio_flush(m_pAVIOContext); m_pAVIOContext->pos = 0; } } return hr; } ================================================ FILE: demuxer/LAVSplitter/InputPin.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "IStreamSourceControl.h" class CLAVSplitter; class CLAVInputPin : public CBasePin , public CCritSec , public IStreamSourceControl { public: CLAVInputPin(TCHAR *pName, CLAVSplitter *pFilter, CCritSec *pLock, HRESULT *phr); ~CLAVInputPin(void); HRESULT GetAVIOContext(AVIOContext **ppContext); DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); HRESULT CheckMediaType(const CMediaType *pmt); HRESULT CheckConnect(IPin *pPin); HRESULT BreakConnect(); HRESULT CompleteConnect(IPin *pPin); STDMETHODIMP BeginFlush(); STDMETHODIMP EndFlush(); CMediaType &CurrentMediaType() { return m_mt; } // IStreamSourceControl STDMETHODIMP GetStreamDuration(REFERENCE_TIME *prtDuration) { CheckPointer(m_pStreamControl, E_NOTIMPL); return m_pStreamControl->GetStreamDuration(prtDuration); } STDMETHODIMP SeekStream(REFERENCE_TIME rtPosition); protected: static int Read(void *opaque, uint8_t *buf, int buf_size); static int64_t Seek(void *opaque, int64_t offset, int whence); LONGLONG m_llPos = 0; private: IAsyncReader *m_pAsyncReader = nullptr; AVIOContext *m_pAVIOContext = nullptr; IStreamSourceControl *m_pStreamControl = nullptr; BOOL m_bURLSource = false; }; ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #include "stdafx.h" #include "LAVSplitter.h" #include "OutputPin.h" #include "InputPin.h" #include "BaseDemuxer.h" #include "LAVFDemuxer.h" #include "BDDemuxer.h" #include #include #include #include #include "registry.h" #include "IGraphRebuildDelegate.h" CLAVSplitter::CLAVSplitter(LPUNKNOWN pUnk, HRESULT *phr) : CBaseFilter(NAME("lavf dshow source filter"), pUnk, this, __uuidof(this), phr) { WCHAR fileName[1024]; GetModuleFileName(nullptr, fileName, 1024); m_processName = PathFindFileName(fileName); m_InputFormats.clear(); std::set lavf_formats = CLAVFDemuxer::GetFormatList(); m_InputFormats.insert(lavf_formats.begin(), lavf_formats.end()); LoadSettings(); m_pInput = new CLAVInputPin(NAME("LAV Input Pin"), this, this, phr); m_ePlaybackInit.Set(); #ifdef DEBUG DbgSetModuleLevel(LOG_TRACE, DWORD_MAX); DbgSetModuleLevel(LOG_ERROR, DWORD_MAX); #endif } CLAVSplitter::~CLAVSplitter() { SAFE_DELETE(m_pInput); SAFE_DELETE(m_pTrayIcon); Close(); // delete old pins for (CLAVOutputPin *pPin : m_pRetiredPins) { delete pPin; } m_pRetiredPins.clear(); SafeRelease(&m_pSite); } STDMETHODIMP CLAVSplitter::Close() { CAutoLock cAutoLock(this); AbortOperation(); CAMThread::CallWorker(CMD_EXIT); CAMThread::Close(); m_State = State_Stopped; DeleteOutputs(); SafeRelease(&m_pDemuxer); return S_OK; } STDMETHODIMP CLAVSplitter::CreateTrayIcon() { CAutoLock cObjectLock(m_pLock); if (m_pTrayIcon) return E_UNEXPECTED; if (CBaseTrayIcon::ProcessBlackList()) return S_FALSE; m_pTrayIcon = new CLAVSplitterTrayIcon(this, TEXT(LAV_SPLITTER), IDI_ICON1); return S_OK; } STDMETHODIMP CLAVSplitter::JoinFilterGraph(IFilterGraph *pGraph, LPCWSTR pName) { CAutoLock cObjectLock(m_pLock); HRESULT hr = __super::JoinFilterGraph(pGraph, pName); if (pGraph && !m_pTrayIcon && m_settings.TrayIcon) { CreateTrayIcon(); } else if (!pGraph && m_pTrayIcon) { SAFE_DELETE(m_pTrayIcon); } return hr; } // Default overrides for input formats static BOOL get_iformat_default(std::string name) { return TRUE; } STDMETHODIMP CLAVSplitter::LoadDefaults() { m_settings.TrayIcon = FALSE; m_settings.prefAudioLangs = L""; m_settings.prefSubLangs = L""; m_settings.subtitleAdvanced = L""; m_settings.subtitleMode = LAVSubtitleMode_Default; m_settings.PGSForcedStream = TRUE; m_settings.PGSOnlyForced = FALSE; m_settings.vc1Mode = 2; m_settings.substreams = TRUE; m_settings.MatroskaExternalSegments = TRUE; m_settings.StreamSwitchReselectSubs = FALSE; m_settings.StreamSwitchRemoveAudio = FALSE; m_settings.ImpairedAudio = FALSE; m_settings.PreferHighQualityAudio = TRUE; m_settings.QueueMaxPackets = 350; m_settings.QueueMaxMemSize = 256; m_settings.NetworkAnalysisDuration = 1000; for (const FormatInfo &fmt : m_InputFormats) { m_settings.formats[std::string(fmt.strName)] = get_iformat_default(fmt.strName); } return S_OK; } STDMETHODIMP CLAVSplitter::LoadSettings() { LoadDefaults(); if (m_bRuntimeConfig) return S_FALSE; ReadSettings(HKEY_LOCAL_MACHINE); return ReadSettings(HKEY_CURRENT_USER); } STDMETHODIMP CLAVSplitter::ReadSettings(HKEY rootKey) { HRESULT hr; DWORD dwVal; BOOL bFlag; std::wstring strVal; CRegistry reg = CRegistry(rootKey, LAVF_REGISTRY_KEY, hr, TRUE); if (SUCCEEDED(hr)) { bFlag = reg.ReadBOOL(L"TrayIcon", hr); if (SUCCEEDED(hr)) m_settings.TrayIcon = bFlag; // Language preferences strVal = reg.ReadString(L"prefAudioLangs", hr); if (SUCCEEDED(hr)) m_settings.prefAudioLangs = strVal; strVal = reg.ReadString(L"prefSubLangs", hr); if (SUCCEEDED(hr)) m_settings.prefSubLangs = strVal; strVal = reg.ReadString(L"subtitleAdvanced", hr); if (SUCCEEDED(hr)) m_settings.subtitleAdvanced = strVal; // Subtitle mode, defaults to all subtitles dwVal = reg.ReadDWORD(L"subtitleMode", hr); if (SUCCEEDED(hr)) m_settings.subtitleMode = (LAVSubtitleMode)dwVal; bFlag = reg.ReadBOOL(L"PGSForcedStream", hr); if (SUCCEEDED(hr)) m_settings.PGSForcedStream = bFlag; bFlag = reg.ReadBOOL(L"PGSOnlyForced", hr); if (SUCCEEDED(hr)) m_settings.PGSOnlyForced = bFlag; dwVal = reg.ReadDWORD(L"vc1TimestampMode", hr); if (SUCCEEDED(hr)) m_settings.vc1Mode = dwVal; bFlag = reg.ReadDWORD(L"substreams", hr); if (SUCCEEDED(hr)) m_settings.substreams = bFlag; bFlag = reg.ReadDWORD(L"MatroskaExternalSegments", hr); if (SUCCEEDED(hr)) m_settings.MatroskaExternalSegments = bFlag; bFlag = reg.ReadDWORD(L"StreamSwitchReselectSubs", hr); if (SUCCEEDED(hr)) m_settings.StreamSwitchReselectSubs = bFlag; bFlag = reg.ReadDWORD(L"StreamSwitchRemoveAudio", hr); if (SUCCEEDED(hr)) m_settings.StreamSwitchRemoveAudio = bFlag; bFlag = reg.ReadDWORD(L"PreferHighQualityAudio", hr); if (SUCCEEDED(hr)) m_settings.PreferHighQualityAudio = bFlag; bFlag = reg.ReadDWORD(L"ImpairedAudio", hr); if (SUCCEEDED(hr)) m_settings.ImpairedAudio = bFlag; dwVal = reg.ReadDWORD(L"QueueMaxSize", hr); if (SUCCEEDED(hr)) m_settings.QueueMaxMemSize = dwVal; dwVal = reg.ReadDWORD(L"NetworkAnalysisDuration", hr); if (SUCCEEDED(hr)) m_settings.NetworkAnalysisDuration = dwVal; dwVal = reg.ReadDWORD(L"QueueMaxPackets", hr); if (SUCCEEDED(hr)) m_settings.QueueMaxPackets = dwVal; } CRegistry regF = CRegistry(rootKey, LAVF_REGISTRY_KEY_FORMATS, hr, TRUE); if (SUCCEEDED(hr)) { WCHAR wBuffer[80]; for (const FormatInfo &fmt : m_InputFormats) { SafeMultiByteToWideChar(CP_UTF8, 0, fmt.strName, -1, wBuffer, 80); bFlag = regF.ReadBOOL(wBuffer, hr); if (SUCCEEDED(hr)) m_settings.formats[std::string(fmt.strName)] = bFlag; } } return S_OK; } STDMETHODIMP CLAVSplitter::SaveSettings() { if (m_bRuntimeConfig) { if (m_pDemuxer) m_pDemuxer->SettingsChanged(static_cast(this)); return S_FALSE; } HRESULT hr; CreateRegistryKey(HKEY_CURRENT_USER, LAVF_REGISTRY_KEY); CRegistry reg = CRegistry(HKEY_CURRENT_USER, LAVF_REGISTRY_KEY, hr); if (SUCCEEDED(hr)) { reg.WriteBOOL(L"TrayIcon", m_settings.TrayIcon); reg.WriteString(L"prefAudioLangs", m_settings.prefAudioLangs.c_str()); reg.WriteString(L"prefSubLangs", m_settings.prefSubLangs.c_str()); reg.WriteString(L"subtitleAdvanced", m_settings.subtitleAdvanced.c_str()); reg.WriteDWORD(L"subtitleMode", m_settings.subtitleMode); reg.WriteBOOL(L"PGSForcedStream", m_settings.PGSForcedStream); reg.WriteBOOL(L"PGSOnlyForced", m_settings.PGSOnlyForced); reg.WriteDWORD(L"vc1TimestampMode", m_settings.vc1Mode); reg.WriteBOOL(L"substreams", m_settings.substreams); reg.WriteBOOL(L"MatroskaExternalSegments", m_settings.MatroskaExternalSegments); reg.WriteBOOL(L"StreamSwitchReselectSubs", m_settings.StreamSwitchReselectSubs); reg.WriteBOOL(L"StreamSwitchRemoveAudio", m_settings.StreamSwitchRemoveAudio); reg.WriteBOOL(L"PreferHighQualityAudio", m_settings.PreferHighQualityAudio); reg.WriteBOOL(L"ImpairedAudio", m_settings.ImpairedAudio); reg.WriteDWORD(L"QueueMaxSize", m_settings.QueueMaxMemSize); reg.WriteDWORD(L"NetworkAnalysisDuration", m_settings.NetworkAnalysisDuration); reg.WriteDWORD(L"QueueMaxPackets", m_settings.QueueMaxPackets); } CreateRegistryKey(HKEY_CURRENT_USER, LAVF_REGISTRY_KEY_FORMATS); CRegistry regF = CRegistry(HKEY_CURRENT_USER, LAVF_REGISTRY_KEY_FORMATS, hr); if (SUCCEEDED(hr)) { WCHAR wBuffer[80]; for (const FormatInfo &fmt : m_InputFormats) { SafeMultiByteToWideChar(CP_UTF8, 0, fmt.strName, -1, wBuffer, 80); regF.WriteBOOL(wBuffer, m_settings.formats[std::string(fmt.strName)]); } } if (m_pDemuxer) { m_pDemuxer->SettingsChanged(static_cast(this)); } return S_OK; } STDMETHODIMP CLAVSplitter::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; if (m_pDemuxer && (riid == __uuidof(IKeyFrameInfo) || riid == __uuidof(ITrackInfo) || riid == IID_IAMExtendedSeeking || riid == IID_IAMMediaContent || riid == IID_IPropertyBag || riid == __uuidof(IDSMResourceBag))) { return m_pDemuxer->QueryInterface(riid, ppv); } return QI(IMediaSeeking) QI(IAMStreamSelect) QI(ISpecifyPropertyPages) QI(ISpecifyPropertyPages2) QI2(ILAVFSettings) QI2(ILAVFSettingsInternal) QI(IObjectWithSite) QI(IBufferInfo) __super::NonDelegatingQueryInterface(riid, ppv); } // ISpecifyPropertyPages2 STDMETHODIMP CLAVSplitter::GetPages(CAUUID *pPages) { CheckPointer(pPages, E_POINTER); pPages->cElems = 2; pPages->pElems = (GUID *)CoTaskMemAlloc(sizeof(GUID) * pPages->cElems); if (pPages->pElems == nullptr) { return E_OUTOFMEMORY; } pPages->pElems[0] = CLSID_LAVSplitterSettingsProp; pPages->pElems[1] = CLSID_LAVSplitterFormatsProp; return S_OK; } STDMETHODIMP CLAVSplitter::CreatePage(const GUID &guid, IPropertyPage **ppPage) { CheckPointer(ppPage, E_POINTER); HRESULT hr = S_OK; if (*ppPage != nullptr) return E_INVALIDARG; if (guid == CLSID_LAVSplitterSettingsProp) *ppPage = new CLAVSplitterSettingsProp(nullptr, &hr); else if (guid == CLSID_LAVSplitterFormatsProp) *ppPage = new CLAVSplitterFormatsProp(nullptr, &hr); if (SUCCEEDED(hr) && *ppPage) { (*ppPage)->AddRef(); return S_OK; } else { SAFE_DELETE(*ppPage); return E_FAIL; } } // IObjectWithSite STDMETHODIMP CLAVSplitter::SetSite(IUnknown *pUnkSite) { // AddRef to store it for later pUnkSite->AddRef(); // Release the old one SafeRelease(&m_pSite); // Store the new one m_pSite = pUnkSite; return S_OK; } STDMETHODIMP CLAVSplitter::GetSite(REFIID riid, void **ppvSite) { CheckPointer(ppvSite, E_POINTER); *ppvSite = nullptr; if (!m_pSite) { return E_FAIL; } IUnknown *pSite = nullptr; HRESULT hr = m_pSite->QueryInterface(riid, (void **)&pSite); if (SUCCEEDED(hr) && pSite) { pSite->AddRef(); *ppvSite = pSite; return S_OK; } return E_NOINTERFACE; } // IBufferInfo STDMETHODIMP_(int) CLAVSplitter::GetCount() { CAutoLock pinLock(&m_csPins); return (int)m_pPins.size(); } STDMETHODIMP CLAVSplitter::GetStatus(int i, int &samples, int &size) { CAutoLock pinLock(&m_csPins); if ((size_t)i >= m_pPins.size()) return E_FAIL; CLAVOutputPin *pPin = m_pPins.at(i); if (!pPin) return E_FAIL; return pPin->GetQueueSize(samples, size); } STDMETHODIMP_(DWORD) CLAVSplitter::GetPriority() { return 0; } // IAMOpenProgress STDMETHODIMP CLAVSplitter::QueryProgress(LONGLONG *pllTotal, LONGLONG *pllCurrent) { return E_NOTIMPL; } STDMETHODIMP CLAVSplitter::AbortOperation() { if (m_pDemuxer) return m_pDemuxer->AbortOpening(); else return E_UNEXPECTED; } // CBaseSplitter int CLAVSplitter::GetPinCount() { CAutoLock lock(&m_csPins); int count = (int)m_pPins.size(); if (m_pInput) count++; return count; } CBasePin *CLAVSplitter::GetPin(int n) { CAutoLock lock(&m_csPins); if (n < 0 || n >= GetPinCount()) return nullptr; if (m_pInput) { if (n == 0) return m_pInput; else n--; } return m_pPins[n]; } STDMETHODIMP CLAVSplitter::GetClassID(CLSID *pClsID) { CheckPointer(pClsID, E_POINTER); if (m_bFakeASFReader) { *pClsID = CLSID_WMAsfReader; return S_OK; } else { return __super::GetClassID(pClsID); } } CLAVOutputPin *CLAVSplitter::GetOutputPin(DWORD streamId, BOOL bActiveOnly) { CAutoLock lock(&m_csPins); auto &vec = bActiveOnly ? m_pActivePins : m_pPins; for (CLAVOutputPin *pPin : vec) { if (pPin->GetStreamId() == streamId) { return pPin; } } return nullptr; } STDMETHODIMP CLAVSplitter::CompleteInputConnection() { HRESULT hr = S_OK; BOOL bFileInput = FALSE; // Check if blacklisted if (!m_bRuntimeConfig && CheckApplicationBlackList(LAVF_REGISTRY_KEY L"\\Blacklist")) return E_FAIL; SAFE_DELETE(m_pDemuxer); AVIOContext *pContext = nullptr; if (FAILED(hr = m_pInput->GetAVIOContext(&pContext))) { return hr; } LPOLESTR pszFileName = nullptr; PIN_INFO info; hr = m_pInput->GetConnected()->QueryPinInfo(&info); if (SUCCEEDED(hr) && info.pFilter) { IFileSourceFilter *pSource = nullptr; if (SUCCEEDED(info.pFilter->QueryInterface(&pSource)) && pSource) { pSource->GetCurFile(&pszFileName, nullptr); SafeRelease(&pSource); } CLSID inputCLSID; if (SUCCEEDED(info.pFilter->GetClassID(&inputCLSID))) { bFileInput = (inputCLSID == CLSID_AsyncReader); } SafeRelease(&info.pFilter); } const char *format = nullptr; if (m_pInput->CurrentMediaType().subtype == MEDIASUBTYPE_MPEG2_TRANSPORT) { format = "mpegts"; } CLAVFDemuxer *pDemux = new CLAVFDemuxer(this, this); if (FAILED(hr = pDemux->OpenInputStream(pContext, pszFileName, format, FALSE, bFileInput))) { SAFE_DELETE(pDemux); return hr; } m_pDemuxer = pDemux; m_pDemuxer->AddRef(); SAFE_CO_FREE(pszFileName); return InitDemuxer(); } STDMETHODIMP CLAVSplitter::BreakInputConnection() { return Close(); } // IFileSourceFilter STDMETHODIMP CLAVSplitter::Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE *pmt) { return LoadURL(pszFileName, NULL, NULL); } STDMETHODIMP CLAVSplitter::LoadURL(LPCOLESTR pszURL, LPCOLESTR pszUserAgent, LPCOLESTR pszReferrer) { CheckPointer(pszURL, E_POINTER); if (m_State != State_Stopped) return E_UNEXPECTED; // Check if blacklisted if (!m_bRuntimeConfig && CheckApplicationBlackList(LAVF_REGISTRY_KEY L"\\Blacklist")) return E_FAIL; // Close, just in case we're being re-used Close(); m_fileName = std::wstring(pszURL); HRESULT hr = S_OK; SAFE_DELETE(m_pDemuxer); LPWSTR extension = PathFindExtensionW(pszURL); DbgLog((LOG_TRACE, 10, L"::Load(): Opening file '%s' (extension: %s)", pszURL, extension)); // BDMV uses the BD demuxer, everything else LAVF if (_wcsicmp(extension, L".bdmv") == 0 || _wcsicmp(extension, L".mpls") == 0) { m_pDemuxer = new CBDDemuxer(this, this); } else { m_pDemuxer = new CLAVFDemuxer(this, this); } if (FAILED(hr = m_pDemuxer->Open(pszURL, pszUserAgent, pszReferrer))) { SAFE_DELETE(m_pDemuxer); return hr; } m_pDemuxer->AddRef(); return InitDemuxer(); } // Get the currently loaded file STDMETHODIMP CLAVSplitter::GetCurFile(LPOLESTR *ppszFileName, AM_MEDIA_TYPE *pmt) { CheckPointer(ppszFileName, E_POINTER); size_t strlen = m_fileName.length() + 1; *ppszFileName = (LPOLESTR)CoTaskMemAlloc(sizeof(wchar_t) * strlen); if (!(*ppszFileName)) return E_OUTOFMEMORY; wcsncpy_s(*ppszFileName, strlen, m_fileName.c_str(), _TRUNCATE); return S_OK; } STDMETHODIMP CLAVSplitter::InitDemuxer() { HRESULT hr = S_OK; // Disable subtitles in applications known to fail with them (explorer thumbnail generator, power point, basically // all applications using MCI) bool bNoSubtitles = _wcsicmp(m_processName.c_str(), L"dllhost.exe") == 0 || _wcsicmp(m_processName.c_str(), L"explorer.exe") == 0 || _wcsicmp(m_processName.c_str(), L"powerpnt.exe") == 0 || _wcsicmp(m_processName.c_str(), L"pptview.exe") == 0; m_rtStart = m_rtNewStart = m_rtCurrent = 0; m_rtStop = m_rtNewStop = m_pDemuxer->GetDuration(); m_bPlaybackStarted = FALSE; const CBaseDemuxer::stream *videoStream = m_pDemuxer->SelectVideoStream(); if (videoStream) { CLAVOutputPin *pPin = new CLAVOutputPin(videoStream->streamInfo->mtypes, CBaseDemuxer::CStreamList::ToStringW(CBaseDemuxer::video), this, this, &hr, CBaseDemuxer::video, m_pDemuxer->GetContainerFormat()); if (SUCCEEDED(hr)) { pPin->SetStreamId(videoStream->pid); m_pPins.push_back(pPin); m_pDemuxer->SetActiveStream(CBaseDemuxer::video, videoStream->pid); } else { delete pPin; } } std::list audioLangs = GetPreferredAudioLanguageList(); const CBaseDemuxer::stream *audioStream = m_pDemuxer->SelectAudioStream(audioLangs); if (audioStream) { CLAVOutputPin *pPin = new CLAVOutputPin(audioStream->streamInfo->mtypes, CBaseDemuxer::CStreamList::ToStringW(CBaseDemuxer::audio), this, this, &hr, CBaseDemuxer::audio, m_pDemuxer->GetContainerFormat()); if (SUCCEEDED(hr)) { pPin->SetStreamId(audioStream->pid); m_pPins.push_back(pPin); m_pDemuxer->SetActiveStream(CBaseDemuxer::audio, audioStream->pid); } else { delete pPin; } } std::string audioLanguage = audioStream ? audioStream->language : std::string(); std::list subtitleSelectors = GetSubtitleSelectors(); const CBaseDemuxer::stream *subtitleStream = m_pDemuxer->SelectSubtitleStream(subtitleSelectors, audioLanguage); if (subtitleStream && !bNoSubtitles) { CLAVOutputPin *pPin = new CLAVOutputPin(subtitleStream->streamInfo->mtypes, CBaseDemuxer::CStreamList::ToStringW(CBaseDemuxer::subpic), this, this, &hr, CBaseDemuxer::subpic, m_pDemuxer->GetContainerFormat()); if (SUCCEEDED(hr)) { pPin->SetStreamId(subtitleStream->pid); m_pPins.push_back(pPin); m_pDemuxer->SetActiveStream(CBaseDemuxer::subpic, subtitleStream->pid); } else { delete pPin; } } if (SUCCEEDED(hr)) { // If there are no pins, what good are we? return !m_pPins.empty() ? S_OK : E_FAIL; } else { return hr; } } STDMETHODIMP CLAVSplitter::DeleteOutputs() { CAutoLock lock(this); if (m_State != State_Stopped) return VFW_E_NOT_STOPPED; CAutoLock pinLock(&m_csPins); // Release pins for (CLAVOutputPin *pPin : m_pPins) { if (IPin *pPinTo = pPin->GetConnected()) pPinTo->Disconnect(); pPin->Disconnect(); m_pRetiredPins.push_back(pPin); } m_pPins.clear(); return S_OK; } bool CLAVSplitter::IsAnyPinDrying() { // MPC changes thread priority here // TODO: Investigate if that is needed for (CLAVOutputPin *pPin : m_pActivePins) { if (pPin->IsConnected() && !pPin->IsDiscontinuous() && pPin->QueueCount() < pPin->GetQueueLowLimit()) { return true; } } return false; } // Worker Thread DWORD CLAVSplitter::ThreadProc() { std::vector::iterator pinIter; CheckPointer(m_pDemuxer, 0); SetThreadName(-1, "CLAVSplitter Demux"); m_pDemuxer->Start(); m_fFlushing = false; m_eEndFlush.Set(); for (DWORD cmd = (DWORD)-1;; cmd = GetRequest()) { if (cmd == CMD_EXIT) { Reply(S_OK); m_ePlaybackInit.Set(); return 0; } m_ePlaybackInit.Reset(); m_rtStart = m_rtNewStart; m_rtStop = m_rtNewStop; if (m_bPlaybackStarted || m_rtStart != 0 || cmd == CMD_SEEK) { HRESULT hr = S_FALSE; if (m_pInput) { hr = m_pInput->SeekStream(m_rtStart); if (SUCCEEDED(hr)) m_pDemuxer->Reset(); } if (hr != S_OK) DemuxSeek(m_rtStart); } if (cmd != (DWORD)-1) Reply(S_OK); // Wait for the end of any flush m_eEndFlush.Wait(); m_pActivePins.clear(); for (pinIter = m_pPins.begin(); pinIter != m_pPins.end() && !m_fFlushing; ++pinIter) { if ((*pinIter)->IsConnected()) { (*pinIter)->DeliverNewSegment(m_rtStart, m_rtStop, m_dRate); m_pActivePins.push_back(*pinIter); } } m_rtOffset = AV_NOPTS_VALUE; m_bDiscontinuitySent.clear(); m_bPlaybackStarted = TRUE; m_ePlaybackInit.Set(); HRESULT hr = S_OK; while (SUCCEEDED(hr) && !CheckRequest(&cmd)) { hr = DemuxNextPacket(); } // If we didnt exit by request, deliver end-of-stream if (!CheckRequest(&cmd)) { for (pinIter = m_pActivePins.begin(); pinIter != m_pActivePins.end(); ++pinIter) { (*pinIter)->QueueEndOfStream(); } } } ASSERT(0); // we should only exit via CMD_EXIT return 0; } // Seek to the specified time stamp // Based on DVDDemuxFFMPEG HRESULT CLAVSplitter::DemuxSeek(REFERENCE_TIME rtStart) { if (rtStart < 0) { rtStart = 0; } return m_pDemuxer->Seek(rtStart); } // Demux the next packet and deliver it to the output pins // Based on DVDDemuxFFMPEG HRESULT CLAVSplitter::DemuxNextPacket() { Packet *pPacket; HRESULT hr = S_OK; hr = m_pDemuxer->GetNextPacket(&pPacket); // Only S_OK indicates we have a proper packet // S_FALSE is a "soft error", don't deliver the packet if (hr != S_OK) { return hr; } return DeliverPacket(pPacket); } HRESULT CLAVSplitter::DeliverPacket(Packet *pPacket) { HRESULT hr = S_FALSE; if (pPacket->dwFlags & LAV_PACKET_FORCED_SUBTITLE) pPacket->StreamId = FORCED_SUBTITLE_PID; CLAVOutputPin *pPin = GetOutputPin(pPacket->StreamId, TRUE); if (!pPin || !pPin->IsConnected()) { delete pPacket; return S_FALSE; } if (pPacket->rtStart != Packet::INVALID_TIME) { m_rtCurrent = pPacket->rtStop; if (m_bStopValid && m_rtStop && pPacket->rtStart > m_rtStop) { DbgLog((LOG_TRACE, 10, L"::DeliverPacket(): Reached the designated stop time of %I64d at %I64d", m_rtStop, pPacket->rtStart)); delete pPacket; return E_FAIL; } pPacket->rtStart -= m_rtStart; pPacket->rtStop -= m_rtStart; ASSERT(pPacket->rtStart <= pPacket->rtStop); // Filter PTS values // This will try to compensate for timestamp discontinuities in the stream if (m_pDemuxer->GetContainerFlags() & LAVFMT_TS_DISCONT) { if (!pPin->IsSubtitlePin()) { // Initialize on the first stream coming in if (pPin->m_rtPrev == AV_NOPTS_VALUE && m_rtOffset == AV_NOPTS_VALUE) { pPin->m_rtPrev = 0; m_rtOffset = 0; } REFERENCE_TIME rt = pPacket->rtStart + m_rtOffset; if (pPin->m_rtPrev != AV_NOPTS_VALUE && _abs64(rt - pPin->m_rtPrev) > MAX_PTS_SHIFT) { m_rtOffset += pPin->m_rtPrev - rt; if (!(m_pDemuxer->GetContainerFlags() & LAVFMT_TS_DISCONT_NO_DOWNSTREAM)) m_bDiscontinuitySent.clear(); DbgLog((LOG_TRACE, 10, L"::DeliverPacket(): MPEG-TS/PS discontinuity detected, adjusting offset to %I64d (stream: " L"%d, prev: %I64d, now: %I64d)", m_rtOffset, pPacket->StreamId, pPin->m_rtPrev, rt)); } } pPacket->rtStart += m_rtOffset; pPacket->rtStop += m_rtOffset; pPin->m_rtPrev = pPacket->rtStart; } pPacket->rtStart = (REFERENCE_TIME)(pPacket->rtStart / m_dRate); pPacket->rtStop = (REFERENCE_TIME)(pPacket->rtStop / m_dRate); } if (m_bDiscontinuitySent.find(pPacket->StreamId) == m_bDiscontinuitySent.end()) { pPacket->bDiscontinuity = TRUE; } BOOL bDiscontinuity = pPacket->bDiscontinuity; DWORD streamId = pPacket->StreamId; hr = pPin->QueuePacket(pPacket); if (hr != S_OK) { // Find a iterator pointing to the pin std::vector::iterator it = std::find(m_pActivePins.begin(), m_pActivePins.end(), pPin); // Remove it from the vector m_pActivePins.erase(it); // Fail if no active pins remain, otherwise resume demuxing return m_pActivePins.empty() ? E_FAIL : S_OK; } if (bDiscontinuity) { m_bDiscontinuitySent.insert(streamId); } return hr; } STDMETHODIMP_(CMediaType *) CLAVSplitter::GetOutputMediatype(int stream) { CLAVOutputPin *pPin = GetOutputPin(stream, FALSE); if (!pPin || !pPin->IsConnected()) return nullptr; CMediaType *pmt = new CMediaType(pPin->GetActiveMediaType()); return pmt; } // State Control STDMETHODIMP CLAVSplitter::Stop() { CAutoLock cAutoLock(this); // Wait for playback to finish initializing m_ePlaybackInit.Wait(); // Ask network operations to exit if (m_pDemuxer) m_pDemuxer->AbortOpening(1); DeliverBeginFlush(); CAMThread::CallWorker(CMD_EXIT); CAMThread::Close(); DeliverEndFlush(); if (m_pDemuxer) m_pDemuxer->AbortOpening(0); HRESULT hr; if (FAILED(hr = __super::Stop())) { return hr; } return S_OK; } STDMETHODIMP CLAVSplitter::Pause() { CAutoLock cAutoLock(this); CheckPointer(m_pDemuxer, E_UNEXPECTED); FILTER_STATE fs = m_State; HRESULT hr; if (FAILED(hr = __super::Pause())) { return hr; } // The filter graph will set us to pause before running // So if we were stopped before, create the thread // Note that the splitter will always be running, // and even in pause mode fill up the buffers if (fs == State_Stopped) { // At this point, the graph is hopefully finished, tell the demuxer about all the cool things m_pDemuxer->SettingsChanged(static_cast(this)); // Create demuxing thread if (!ThreadExists()) m_ePlaybackInit.Reset(); Create(); } return S_OK; } STDMETHODIMP CLAVSplitter::Run(REFERENCE_TIME tStart) { CAutoLock cAutoLock(this); HRESULT hr; if (FAILED(hr = __super::Run(tStart))) { return hr; } return S_OK; } // Flushing void CLAVSplitter::DeliverBeginFlush() { m_fFlushing = true; // flush all pins for (CLAVOutputPin *pPin : m_pPins) { pPin->DeliverBeginFlush(); } } void CLAVSplitter::DeliverEndFlush() { // flush all pins for (CLAVOutputPin *pPin : m_pPins) { pPin->DeliverEndFlush(); } m_fFlushing = false; m_eEndFlush.Set(); } // IMediaSeeking STDMETHODIMP CLAVSplitter::GetCapabilities(DWORD *pCapabilities) { CheckPointer(pCapabilities, E_POINTER); *pCapabilities = AM_SEEKING_CanGetStopPos | AM_SEEKING_CanGetDuration | AM_SEEKING_CanSeekAbsolute | AM_SEEKING_CanSeekForwards | AM_SEEKING_CanSeekBackwards; return S_OK; } STDMETHODIMP CLAVSplitter::CheckCapabilities(DWORD *pCapabilities) { CheckPointer(pCapabilities, E_POINTER); // capabilities is empty, all is good if (*pCapabilities == 0) return S_OK; // read caps DWORD caps; GetCapabilities(&caps); // Store the caps that we wanted DWORD wantCaps = *pCapabilities; // Update pCapabilities with what we have *pCapabilities = caps & wantCaps; // if nothing matches, its a disaster! if (*pCapabilities == 0) return E_FAIL; // if all matches, its all good if (*pCapabilities == wantCaps) return S_OK; // otherwise, a partial match return S_FALSE; } STDMETHODIMP CLAVSplitter::IsFormatSupported(const GUID *pFormat) { return !pFormat ? E_POINTER : *pFormat == TIME_FORMAT_MEDIA_TIME ? S_OK : S_FALSE; } STDMETHODIMP CLAVSplitter::QueryPreferredFormat(GUID *pFormat) { return GetTimeFormat(pFormat); } STDMETHODIMP CLAVSplitter::GetTimeFormat(GUID *pFormat) { return pFormat ? *pFormat = TIME_FORMAT_MEDIA_TIME, S_OK : E_POINTER; } STDMETHODIMP CLAVSplitter::IsUsingTimeFormat(const GUID *pFormat) { return IsFormatSupported(pFormat); } STDMETHODIMP CLAVSplitter::SetTimeFormat(const GUID *pFormat) { return S_OK == IsFormatSupported(pFormat) ? S_OK : E_INVALIDARG; } STDMETHODIMP CLAVSplitter::GetDuration(LONGLONG *pDuration) { REFERENCE_TIME rtDuration = -1; CheckPointer(pDuration, E_POINTER); CheckPointer(m_pDemuxer, E_UNEXPECTED); if (m_pInput) { if (FAILED(m_pInput->GetStreamDuration(&rtDuration))) rtDuration = -1; } if (rtDuration < 0) rtDuration = m_pDemuxer->GetDuration(); if (rtDuration < 0) return E_FAIL; *pDuration = rtDuration; return S_OK; } STDMETHODIMP CLAVSplitter::GetStopPosition(LONGLONG *pStop) { return GetDuration(pStop); } STDMETHODIMP CLAVSplitter::GetCurrentPosition(LONGLONG *pCurrent) { return E_NOTIMPL; } STDMETHODIMP CLAVSplitter::ConvertTimeFormat(LONGLONG *pTarget, const GUID *pTargetFormat, LONGLONG Source, const GUID *pSourceFormat) { return E_NOTIMPL; } STDMETHODIMP CLAVSplitter::SetPositions(LONGLONG *pCurrent, DWORD dwCurrentFlags, LONGLONG *pStop, DWORD dwStopFlags) { return SetPositionsInternal(this, pCurrent, dwCurrentFlags, pStop, dwStopFlags); } STDMETHODIMP CLAVSplitter::SetPositionsInternal(void *caller, LONGLONG *pCurrent, DWORD dwCurrentFlags, LONGLONG *pStop, DWORD dwStopFlags) { DbgLog((LOG_TRACE, 20, "::SetPositions() - seek request; caller: %p, current: %I64d; start: %I64d; flags: 0x%x, stop: %I64d; " "flags: 0x%x", caller, m_rtCurrent, pCurrent ? *pCurrent : -1, dwCurrentFlags, pStop ? *pStop : -1, dwStopFlags)); CAutoLock cAutoLock(this); if (!pCurrent && !pStop || (dwCurrentFlags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning && (dwStopFlags & AM_SEEKING_PositioningBitsMask) == AM_SEEKING_NoPositioning) { return S_OK; } REFERENCE_TIME rtCurrent = m_rtCurrent, rtStop = m_rtStop; if (pCurrent) { switch (dwCurrentFlags & AM_SEEKING_PositioningBitsMask) { case AM_SEEKING_NoPositioning: break; case AM_SEEKING_AbsolutePositioning: rtCurrent = *pCurrent; break; case AM_SEEKING_RelativePositioning: rtCurrent = rtCurrent + *pCurrent; break; case AM_SEEKING_IncrementalPositioning: rtCurrent = rtCurrent + *pCurrent; break; } } if (pStop) { switch (dwStopFlags & AM_SEEKING_PositioningBitsMask) { case AM_SEEKING_NoPositioning: break; case AM_SEEKING_AbsolutePositioning: rtStop = *pStop; m_bStopValid = TRUE; break; case AM_SEEKING_RelativePositioning: rtStop += *pStop; m_bStopValid = TRUE; break; case AM_SEEKING_IncrementalPositioning: rtStop = rtCurrent + *pStop; m_bStopValid = TRUE; break; } } if (m_rtLastStart == rtCurrent && m_rtLastStop == rtStop && m_LastSeekers.find(caller) == m_LastSeekers.end()) { m_LastSeekers.insert(caller); return S_OK; } m_rtLastStart = rtCurrent; m_rtLastStop = rtStop; m_LastSeekers.clear(); m_LastSeekers.insert(caller); m_rtNewStart = m_rtCurrent = rtCurrent; m_rtNewStop = rtStop; DbgLog((LOG_TRACE, 20, " -> Performing seek to %I64d", m_rtNewStart)); if (ThreadExists()) { DeliverBeginFlush(); CallWorker(CMD_SEEK); DeliverEndFlush(); } DbgLog((LOG_TRACE, 20, " -> Seek finished", m_rtNewStart)); return S_OK; } STDMETHODIMP CLAVSplitter::GetPositions(LONGLONG *pCurrent, LONGLONG *pStop) { if (pCurrent) *pCurrent = m_rtCurrent; if (pStop) *pStop = m_rtStop; return S_OK; } STDMETHODIMP CLAVSplitter::GetAvailable(LONGLONG *pEarliest, LONGLONG *pLatest) { if (pEarliest) *pEarliest = 0; return GetDuration(pLatest); } STDMETHODIMP CLAVSplitter::SetRate(double dRate) { return dRate > 0 ? m_dRate = dRate, S_OK : E_INVALIDARG; } STDMETHODIMP CLAVSplitter::GetRate(double *pdRate) { return pdRate ? *pdRate = m_dRate, S_OK : E_POINTER; } STDMETHODIMP CLAVSplitter::GetPreroll(LONGLONG *pllPreroll) { return pllPreroll ? *pllPreroll = 0, S_OK : E_POINTER; } STDMETHODIMP CLAVSplitter::UpdateForcedSubtitleMediaType() { CheckPointer(m_pDemuxer, E_UNEXPECTED); CLAVOutputPin *pPin = GetOutputPin(FORCED_SUBTITLE_PID); if (pPin) { CBaseDemuxer::CStreamList *streams = m_pDemuxer->GetStreams(CBaseDemuxer::subpic); const CBaseDemuxer::stream *s = streams->FindStream(FORCED_SUBTITLE_PID); CMediaType *mt = new CMediaType(s->streamInfo->mtypes.back()); pPin->SendMediaType(mt); } return S_OK; } STDMETHODIMP CLAVSplitter::ReselectSubs(int streamId) { CheckPointer(m_pDemuxer, E_UNEXPECTED); CBaseDemuxer::stream *audioStream = m_pDemuxer->GetStreams(CBaseDemuxer::StreamType::audio)->FindStream(streamId); std::string audioLanguage = audioStream ? audioStream->language : std::string(); std::list subtitleSelectors = GetSubtitleSelectors(); const CBaseDemuxer::stream *subtitleStream = m_pDemuxer->SelectSubtitleStream(subtitleSelectors, audioLanguage); if (subtitleStream) { long lIndex = (long)m_pDemuxer->GetStreams(CBaseDemuxer::StreamType::video)->size() + (long)m_pDemuxer->GetStreams(CBaseDemuxer::StreamType::audio)->size(); auto subpics = m_pDemuxer->GetStreams(CBaseDemuxer::StreamType::subpic); for (int i = 0; i < subpics->size(); i++) { if (subpics->at(i).pid == subtitleStream->pid) { lIndex += i; break; } } Enable(lIndex, AMSTREAMSELECTENABLE_ENABLE); return S_OK; } return E_FAIL; } static int QueryAcceptMediaTypes(IPin *pPin, std::deque pmts) { for (unsigned int i = 0; i < pmts.size(); i++) { if (S_OK == pPin->QueryAccept(&pmts[i])) { DbgLog((LOG_TRACE, 20, L"QueryAcceptMediaTypes() - IPin:QueryAccept succeeded on index %d", i)); return i; } } return -1; } STDMETHODIMP CLAVSplitter::RenameOutputPin(DWORD TrackNumSrc, DWORD TrackNumDst, std::deque pmts) { CheckPointer(m_pDemuxer, E_UNEXPECTED); if (TrackNumSrc == TrackNumDst) return S_OK; // WMP/WMC like to always enable the first track, overwriting any initial stream choice // So instead block it from doing anything here. if (!m_bPlaybackStarted && (m_processName == L"wmplayer.exe" || m_processName == L"ehshell.exe")) return S_OK; CLAVOutputPin *pPin = GetOutputPin(TrackNumSrc); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - Switching %s Stream %d to %d", CBaseDemuxer::CStreamList::ToStringW(pPin->GetPinType()), TrackNumSrc, TrackNumDst)); // Output Pin was found // Stop the Graph, remove the old filter, render the graph again, start it up again // This only works on pins that were connected before, or the filter graph could .. well, break if (pPin && pPin->IsConnected()) { bool reselectSubsAtEnd = false; HRESULT hr = S_OK; IMediaControl *pControl = nullptr; hr = m_pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl); FILTER_STATE oldState; // Get the graph state // If the graph is in transition, we'll get the next state, not the previous hr = pControl->GetState(10, (OAFilterState *)&oldState); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - IMediaControl::GetState returned %d (hr %x)", oldState, hr)); // Stop the filter graph hr = pControl->Stop(); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - IMediaControl::Stop (hr %x)", hr)); Lock(); // Update Output Pin pPin->SetStreamId(TrackNumDst); m_pDemuxer->SetActiveStream(pPin->GetPinType(), TrackNumDst); pPin->SetNewMediaTypes(pmts); // IGraphRebuildDelegate support // Query our Site for the appropriate interface, and if its present, delegate graph building there IGraphRebuildDelegate *pDelegate = nullptr; if (SUCCEEDED(GetSite(IID_IGraphRebuildDelegate, (void **)&pDelegate)) && pDelegate) { hr = pDelegate->RebuildPin(m_pGraph, pPin); if (hr == S_FALSE) { int mtIdx = QueryAcceptMediaTypes(pPin->GetConnected(), pmts); if (mtIdx == -1) { DbgLog((LOG_ERROR, 10, L"::RenameOutputPin(): No matching media type after rebuild delegation")); mtIdx = 0; } CMediaType *mt = new CMediaType(pmts[mtIdx]); pPin->SendMediaType(mt); } SafeRelease(&pDelegate); if (SUCCEEDED(hr)) { goto resumegraph; } DbgLog((LOG_TRACE, 10, L"::RenameOutputPin(): IGraphRebuildDelegate::RebuildPin failed")); } // Audio Filters get their connected filter removed // This way we make sure we reconnect to the proper filter // Other filters just disconnect and try to reconnect later on PIN_INFO pInfo; hr = pPin->GetConnected()->QueryPinInfo(&pInfo); if (FAILED(hr)) { DbgLog((LOG_ERROR, 10, L"::RenameOutputPin(): QueryPinInfo failed (hr %x)", hr)); } int mtIdx = QueryAcceptMediaTypes(pPin->GetConnected(), pmts); BOOL bMediaTypeFound = (mtIdx >= 0); if (!bMediaTypeFound) { DbgLog((LOG_TRACE, 10, L"::RenameOutputPin() - Filter does not accept our media types!")); mtIdx = 0; // Fallback type } CMediaType *pmt = &pmts[mtIdx]; if (!pPin->IsVideoPin() && SUCCEEDED(hr) && pInfo.pFilter) { BOOL bRemoveFilter = m_settings.StreamSwitchRemoveAudio || !bMediaTypeFound; if (bRemoveFilter && pPin->IsAudioPin()) { hr = m_pGraph->RemoveFilter(pInfo.pFilter); #ifdef DEBUG CLSID guidFilter; pInfo.pFilter->GetClassID(&guidFilter); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - IFilterGraph::RemoveFilter - %s (hr %x)", WStringFromGUID(guidFilter).c_str(), hr)); #endif // Use IGraphBuilder to rebuild the graph IGraphBuilder *pGraphBuilder = nullptr; if (SUCCEEDED(hr = m_pGraph->QueryInterface(__uuidof(IGraphBuilder), (void **)&pGraphBuilder))) { // Instruct the GraphBuilder to connect us again hr = pGraphBuilder->Render(pPin); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - IGraphBuilder::Render (hr %x)", hr)); pGraphBuilder->Release(); } } else { hr = ReconnectPin(pPin, pmt); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - ReconnectPin (hr %x)", hr)); } if (pPin->IsAudioPin() && m_settings.PGSForcedStream) UpdateForcedSubtitleMediaType(); if (pPin->IsAudioPin() && m_settings.StreamSwitchReselectSubs) { reselectSubsAtEnd = true; } } else { CMediaType *mt = new CMediaType(*pmt); pPin->SendMediaType(mt); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - Sending new Media Type")); } if (SUCCEEDED(hr) && pInfo.pFilter) { pInfo.pFilter->Release(); } resumegraph: Unlock(); // Re-start the graph if (oldState == State_Paused) { hr = pControl->Pause(); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - IMediaControl::Pause (hr %x)", hr)); } else if (oldState == State_Running) { hr = pControl->Run(); DbgLog((LOG_TRACE, 20, L"::RenameOutputPin() - IMediaControl::Run (hr %x)", hr)); } pControl->Release(); if (reselectSubsAtEnd) { ReselectSubs(TrackNumDst); } return hr; } else if (pPin) { CAutoLock lock(this); // In normal operations, this won't make much sense // However, in graphstudio it is now possible to change the stream before connecting pPin->SetStreamId(TrackNumDst); m_pDemuxer->SetActiveStream(pPin->GetPinType(), TrackNumDst); pPin->SetNewMediaTypes(pmts); return S_OK; } return E_FAIL; } // IAMStreamSelect STDMETHODIMP CLAVSplitter::Count(DWORD *pcStreams) { CheckPointer(pcStreams, E_POINTER); CheckPointer(m_pDemuxer, E_UNEXPECTED); *pcStreams = 0; for (int i = 0; i < CBaseDemuxer::unknown; i++) { CBaseDemuxer::CStreamList* pStreamList = m_pDemuxer->GetStreams((CBaseDemuxer::StreamType)i); if (pStreamList) *pcStreams += (DWORD)pStreamList->size(); } int num_titles = m_pDemuxer->GetNumTitles(); if (num_titles > 1) *pcStreams += num_titles; return S_OK; } STDMETHODIMP CLAVSplitter::Enable(long lIndex, DWORD dwFlags) { CheckPointer(m_pDemuxer, E_UNEXPECTED); if (!(dwFlags & AMSTREAMSELECTENABLE_ENABLE)) { return E_NOTIMPL; } int i, j; for (i = 0, j = 0; i < CBaseDemuxer::unknown; i++) { CBaseDemuxer::CStreamList *streams = m_pDemuxer->GetStreams((CBaseDemuxer::StreamType)i); if (!streams) continue; int cnt = (int)streams->size(); if (lIndex >= j && lIndex < j + cnt) { long idx = (lIndex - j); CBaseDemuxer::stream &to = streams->at(idx); std::deque::iterator it; for (it = streams->begin(); it != streams->end(); ++it) { if (!GetOutputPin(it->pid)) { continue; } HRESULT hr; if (FAILED(hr = RenameOutputPin(*it, to, to.streamInfo->mtypes))) { return hr; } return S_OK; } break; } j += cnt; } int idx = (lIndex - j); int num_titles = m_pDemuxer->GetNumTitles(); if (num_titles > 1 && idx >= 0 && idx < num_titles) { DbgLog((LOG_TRACE, 10, L"Setting title to %d", idx)); HRESULT hr = m_pDemuxer->SetTitle(idx); if (SUCCEEDED(hr)) { // Perform a seek to the start of the new title IMediaSeeking *pSeek = nullptr; hr = m_pGraph->QueryInterface(&pSeek); if (SUCCEEDED(hr)) { LONGLONG current = 0; pSeek->SetPositions(¤t, AM_SEEKING_AbsolutePositioning, nullptr, AM_SEEKING_NoPositioning); SafeRelease(&pSeek); } // Notify the player about the length change DbgLog((LOG_TRACE, 10, L"Title change complete, signaling player")); NotifyEvent(EC_LENGTH_CHANGED, 0, 0); } } return S_FALSE; } STDMETHODIMP CLAVSplitter::Info(long lIndex, AM_MEDIA_TYPE **ppmt, DWORD *pdwFlags, LCID *plcid, DWORD *pdwGroup, WCHAR **ppszName, IUnknown **ppObject, IUnknown **ppUnk) { CheckPointer(m_pDemuxer, E_UNEXPECTED); HRESULT hr = S_FALSE; int i, j; for (i = 0, j = 0; i < CBaseDemuxer::unknown; i++) { CBaseDemuxer::CStreamList *streams = m_pDemuxer->GetStreams((CBaseDemuxer::StreamType)i); int cnt = (int)streams->size(); if (lIndex >= j && lIndex < j + cnt) { long idx = (lIndex - j); CBaseDemuxer::stream &s = streams->at(idx); if (ppmt) *ppmt = CreateMediaType(&s.streamInfo->mtypes[0]); if (pdwFlags) *pdwFlags = GetOutputPin(s) ? (AMSTREAMSELECTINFO_ENABLED | AMSTREAMSELECTINFO_EXCLUSIVE) : 0; if (pdwGroup) *pdwGroup = i; if (ppObject) *ppObject = nullptr; if (ppUnk) *ppUnk = nullptr; // Special case for the "no subtitles" pin if (s.pid == NO_SUBTITLE_PID) { if (plcid) *plcid = LCID_NOSUBTITLES; if (ppszName) { WCHAR str[] = L"S: " NO_SUB_STRING; size_t len = wcslen(str) + 1; *ppszName = (WCHAR *)CoTaskMemAlloc(len * sizeof(WCHAR)); if (*ppszName) wcsncpy_s(*ppszName, len, str, _TRUNCATE); } } else if (s.pid == FORCED_SUBTITLE_PID) { if (plcid) { *plcid = s.lcid; } if (ppszName) { WCHAR str[] = L"S: " FORCED_SUB_STRING; size_t len = wcslen(str) + 1; *ppszName = (WCHAR *)CoTaskMemAlloc(len * sizeof(WCHAR)); if (*ppszName) wcsncpy_s(*ppszName, len, str, _TRUNCATE); } } else { if (plcid) { *plcid = s.lcid; } if (ppszName) { std::string info = s.streamInfo->codecInfo; *ppszName = CoTaskGetWideCharFromMultiByte(CP_UTF8, MB_ERR_INVALID_CHARS, info.c_str(), -1); } } hr = S_OK; break; } j += cnt; } if (hr == S_FALSE) { int idx = (lIndex - j); int num_titles = m_pDemuxer->GetNumTitles(); if (num_titles > 1 && idx >= 0 && idx < num_titles) { if (ppmt) *ppmt = nullptr; if (pdwFlags) *pdwFlags = m_pDemuxer->GetTitle() == idx ? (AMSTREAMSELECTINFO_ENABLED | AMSTREAMSELECTINFO_EXCLUSIVE) : 0; if (pdwGroup) *pdwGroup = 18; if (ppObject) *ppObject = nullptr; if (ppUnk) *ppUnk = nullptr; m_pDemuxer->GetTitleInfo(idx, nullptr, ppszName); hr = S_OK; } } return hr; } // setting helpers std::list CLAVSplitter::GetPreferredAudioLanguageList() { std::list list; char *buffer = CoTaskGetMultiByteFromWideChar(CP_UTF8, 0, m_settings.prefAudioLangs.c_str(), -1); if (!buffer) return list; split(std::string(buffer), std::string(",; "), list); SAFE_CO_FREE(buffer); return list; } std::list CLAVSplitter::GetSubtitleSelectors() { std::list selectorList; std::string separators = ",; "; std::list tokenList; if (m_settings.subtitleMode == LAVSubtitleMode_NoSubs) { // Do nothing } else if (m_settings.subtitleMode == LAVSubtitleMode_Default || m_settings.subtitleMode == LAVSubtitleMode_ForcedOnly) { // Convert to wide-char to utf8 char *buffer = CoTaskGetMultiByteFromWideChar(CP_UTF8, 0, m_settings.prefSubLangs.c_str(), -1); if (!buffer) return selectorList; std::list langList; split(std::string(buffer), separators, langList); SAFE_CO_FREE(buffer); // If no languages have been set, prefer the forced/default streams as specified by the audio languages bool bNoLanguage = false; if (langList.empty()) { langList = GetPreferredAudioLanguageList(); bNoLanguage = true; } for (const std::string &lang : langList) { std::string token = "*:" + lang; if (m_settings.subtitleMode == LAVSubtitleMode_ForcedOnly || bNoLanguage) { if (m_settings.subtitleMode == LAVSubtitleMode_Default) tokenList.push_back(token + "|d"); tokenList.push_back(token + "|f"); } else { tokenList.push_back(token + "|d"); tokenList.push_back(token + "|!hf"); tokenList.push_back(token + "|f"); } } // Add fallbacks (forced/default) if (m_settings.subtitleMode == LAVSubtitleMode_Default) tokenList.push_back("*:*|d"); tokenList.push_back("*:*|f"); } else if (m_settings.subtitleMode == LAVSubtitleMode_Advanced) { // Convert to wide-char to utf8 char *buffer = CoTaskGetMultiByteFromWideChar(CP_UTF8, 0, m_settings.subtitleAdvanced.c_str(), -1); if (!buffer) return selectorList; split(std::string(buffer), separators, tokenList); SAFE_CO_FREE(buffer); } // Add the "off" termination element tokenList.push_back("*:off"); std::regex advRegex("(?:(\\*|[[:alpha:]]+):)?" // audio language "(\\*|[[:alpha:]]+)" // subtitle language "(?:\\|([fdnh]*!?[fdnh]+))?" // flags "(?:@([^" + separators + "]+))?" // subtitle track name substring ); for (const std::string &token : tokenList) { std::cmatch res; bool found = std::regex_search(token.c_str(), res, advRegex); if (found) { CSubtitleSelector selector; selector.audioLanguage = res[1].str().empty() ? "*" : ProbeForISO6392(res[1].str().c_str()); selector.subtitleLanguage = ProbeForISO6392(res[2].str().c_str()); selector.dwFlagsSet = 0; selector.dwFlagsNot = 0; // Parse flags std::string flags = res[3]; std::string flagsSet; std::string flagsNot; if (flags.find('!') != flags.npos) { flagsSet = flags.substr(0, flags.find('!')); flagsNot = flags.substr(flags.find('!')+1); } else { flagsSet = flags; flagsNot = ""; } if (flagsSet.length() > 0) { if (flagsSet.find('d') != std::string::npos) selector.dwFlagsSet |= SUBTITLE_FLAG_DEFAULT; if (flagsSet.find('f') != std::string::npos) selector.dwFlagsSet |= SUBTITLE_FLAG_FORCED; if (flagsSet.find('n') != std::string::npos) selector.dwFlagsSet |= SUBTITLE_FLAG_NORMAL; if (flagsSet.find('h') != std::string::npos) selector.dwFlagsSet |= SUBTITLE_FLAG_IMPAIRED; if (m_settings.subtitleMode == LAVSubtitleMode_Default) { if (selector.subtitleLanguage == "*" && (selector.dwFlagsSet & SUBTITLE_FLAG_DEFAULT)) selector.dwFlagsSet |= SUBTITLE_FLAG_VIRTUAL; } else { if (selector.dwFlagsSet & SUBTITLE_FLAG_FORCED) selector.dwFlagsSet |= SUBTITLE_FLAG_VIRTUAL; } } if (flagsNot.length() > 0) { if (flagsNot.find('d') != std::string::npos) selector.dwFlagsNot |= SUBTITLE_FLAG_DEFAULT; if (flagsNot.find('f') != std::string::npos) selector.dwFlagsNot |= SUBTITLE_FLAG_FORCED; if (flagsNot.find('n') != std::string::npos) selector.dwFlagsNot |= SUBTITLE_FLAG_NORMAL; if (flagsNot.find('h') != std::string::npos) selector.dwFlagsNot |= SUBTITLE_FLAG_IMPAIRED; } selector.subtitleTrackName = res[4]; selectorList.push_back(selector); DbgLog((LOG_TRACE, 10, L"::GetSubtitleSelectors(): Parsed selector \"%S\" to: %S -> %S (flagsSet: 0x%x, flagsNot: 0x%x, match: %S)", token.c_str(), selector.audioLanguage.c_str(), selector.subtitleLanguage.c_str(), selector.dwFlagsSet, selector.dwFlagsNot, selector.subtitleTrackName.c_str())); } else { DbgLog((LOG_ERROR, 10, L"::GetSubtitleSelectors(): Selector string \"%S\" could not be parsed", token.c_str())); } } return selectorList; } // Settings // ILAVAudioSettings HRESULT CLAVSplitter::SetRuntimeConfig(BOOL bRuntimeConfig) { m_bRuntimeConfig = bRuntimeConfig; LoadSettings(); // Tray Icon is disabled by default SAFE_DELETE(m_pTrayIcon); return S_OK; } STDMETHODIMP CLAVSplitter::GetPreferredLanguages(LPWSTR *ppLanguages) { CheckPointer(ppLanguages, E_POINTER); size_t len = m_settings.prefAudioLangs.length() + 1; if (len > 1) { *ppLanguages = (WCHAR *)CoTaskMemAlloc(sizeof(WCHAR) * len); if (*ppLanguages) wcsncpy_s(*ppLanguages, len, m_settings.prefAudioLangs.c_str(), _TRUNCATE); } else { *ppLanguages = nullptr; } return S_OK; } STDMETHODIMP CLAVSplitter::SetPreferredLanguages(LPCWSTR pLanguages) { m_settings.prefAudioLangs = std::wstring(pLanguages); return SaveSettings(); } STDMETHODIMP CLAVSplitter::GetPreferredSubtitleLanguages(LPWSTR *ppLanguages) { CheckPointer(ppLanguages, E_POINTER); size_t len = m_settings.prefSubLangs.length() + 1; if (len > 1) { *ppLanguages = (WCHAR *)CoTaskMemAlloc(sizeof(WCHAR) * len); if (*ppLanguages) wcsncpy_s(*ppLanguages, len, m_settings.prefSubLangs.c_str(), _TRUNCATE); } else { *ppLanguages = nullptr; } return S_OK; } STDMETHODIMP CLAVSplitter::SetPreferredSubtitleLanguages(LPCWSTR pLanguages) { m_settings.prefSubLangs = std::wstring(pLanguages); return SaveSettings(); } STDMETHODIMP_(LAVSubtitleMode) CLAVSplitter::GetSubtitleMode() { return m_settings.subtitleMode; } STDMETHODIMP CLAVSplitter::SetSubtitleMode(LAVSubtitleMode mode) { m_settings.subtitleMode = mode; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetSubtitleMatchingLanguage() { return FALSE; } STDMETHODIMP CLAVSplitter::SetSubtitleMatchingLanguage(BOOL dwMode) { return E_FAIL; } STDMETHODIMP_(BOOL) CLAVSplitter::GetPGSForcedStream() { return m_settings.PGSForcedStream; } STDMETHODIMP CLAVSplitter::SetPGSForcedStream(BOOL bFlag) { m_settings.PGSForcedStream = bFlag; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetPGSOnlyForced() { return m_settings.PGSOnlyForced; } STDMETHODIMP CLAVSplitter::SetPGSOnlyForced(BOOL bForced) { m_settings.PGSOnlyForced = bForced; return SaveSettings(); } STDMETHODIMP_(int) CLAVSplitter::GetVC1TimestampMode() { return m_settings.vc1Mode; } STDMETHODIMP CLAVSplitter::SetVC1TimestampMode(int iMode) { m_settings.vc1Mode = iMode; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::IsVC1CorrectionRequired() { return FilterInGraph(CLSID_LAVVideo, m_pGraph) || (FilterInGraph(CLSID_LAVCUVID, m_pGraph) && (_strnicmp(m_pDemuxer->GetContainerFormat(), "matroska", 8) == 0)) || FilterInGraph(CLSID_MPCVideoDec, m_pGraph) || FilterInGraph(CLSID_ffdshowDXVA, m_pGraph) || FilterInGraphWithInputSubtype(CLSID_madVR, m_pGraph, MEDIASUBTYPE_WVC1) || FilterInGraphWithInputSubtype(CLSID_DMOWrapperFilter, m_pGraph, MEDIASUBTYPE_WVC1); } STDMETHODIMP CLAVSplitter::SetSubstreamsEnabled(BOOL bSubStreams) { m_settings.substreams = bSubStreams; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetSubstreamsEnabled() { return m_settings.substreams; } STDMETHODIMP CLAVSplitter::SetVideoParsingEnabled(BOOL bEnabled) { return E_FAIL; } STDMETHODIMP_(BOOL) CLAVSplitter::GetVideoParsingEnabled() { return TRUE; } STDMETHODIMP CLAVSplitter::SetFixBrokenHDPVR(BOOL bEnabled) { return E_FAIL; } STDMETHODIMP_(BOOL) CLAVSplitter::GetFixBrokenHDPVR() { return TRUE; } STDMETHODIMP_(BOOL) CLAVSplitter::IsFormatEnabled(LPCSTR strFormat) { std::string format(strFormat); if (m_settings.formats.find(format) != m_settings.formats.end()) { return m_settings.formats[format]; } return FALSE; } STDMETHODIMP_(HRESULT) CLAVSplitter::SetFormatEnabled(LPCSTR strFormat, BOOL bEnabled) { std::string format(strFormat); if (m_settings.formats.find(format) != m_settings.formats.end()) { m_settings.formats[format] = bEnabled; return SaveSettings(); } return E_FAIL; } STDMETHODIMP CLAVSplitter::SetStreamSwitchRemoveAudio(BOOL bEnabled) { m_settings.StreamSwitchRemoveAudio = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetStreamSwitchRemoveAudio() { return m_settings.StreamSwitchRemoveAudio; } STDMETHODIMP CLAVSplitter::GetAdvancedSubtitleConfig(LPWSTR *ppAdvancedConfig) { CheckPointer(ppAdvancedConfig, E_POINTER); size_t len = m_settings.subtitleAdvanced.length() + 1; if (len > 1) { *ppAdvancedConfig = (WCHAR *)CoTaskMemAlloc(sizeof(WCHAR) * len); if (*ppAdvancedConfig) wcsncpy_s(*ppAdvancedConfig, len, m_settings.subtitleAdvanced.c_str(), _TRUNCATE); } else { *ppAdvancedConfig = nullptr; } return S_OK; } STDMETHODIMP CLAVSplitter::SetAdvancedSubtitleConfig(LPCWSTR pAdvancedConfig) { m_settings.subtitleAdvanced = std::wstring(pAdvancedConfig); return SaveSettings(); } STDMETHODIMP CLAVSplitter::SetUseAudioForHearingVisuallyImpaired(BOOL bEnabled) { m_settings.ImpairedAudio = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetUseAudioForHearingVisuallyImpaired() { return m_settings.ImpairedAudio; } STDMETHODIMP CLAVSplitter::SetMaxQueueMemSize(DWORD dwMaxSize) { m_settings.QueueMaxMemSize = dwMaxSize; for (auto it = m_pPins.begin(); it != m_pPins.end(); it++) { (*it)->SetQueueSizes(); } return SaveSettings(); } STDMETHODIMP_(DWORD) CLAVSplitter::GetMaxQueueMemSize() { return m_settings.QueueMaxMemSize; } STDMETHODIMP CLAVSplitter::SetStreamSwitchReselectSubtitles(BOOL bEnabled) { m_settings.StreamSwitchReselectSubs = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetStreamSwitchReselectSubtitles() { return m_settings.StreamSwitchReselectSubs; } STDMETHODIMP CLAVSplitter::SetTrayIcon(BOOL bEnabled) { m_settings.TrayIcon = bEnabled; // The tray icon is created if not yet done so, however its not removed on the fly // Removing the icon on the fly can cause deadlocks if the config is changed from the icons thread if (bEnabled && m_pGraph && !m_pTrayIcon) { CreateTrayIcon(); } return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetTrayIcon() { return m_settings.TrayIcon; } STDMETHODIMP CLAVSplitter::SetPreferHighQualityAudioStreams(BOOL bEnabled) { m_settings.PreferHighQualityAudio = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetPreferHighQualityAudioStreams() { return m_settings.PreferHighQualityAudio; } STDMETHODIMP CLAVSplitter::SetLoadMatroskaExternalSegments(BOOL bEnabled) { m_settings.MatroskaExternalSegments = bEnabled; return SaveSettings(); } STDMETHODIMP_(BOOL) CLAVSplitter::GetLoadMatroskaExternalSegments() { return m_settings.MatroskaExternalSegments; } STDMETHODIMP CLAVSplitter::GetFormats(LPSTR **formats, UINT *nFormats) { CheckPointer(formats, E_POINTER); CheckPointer(nFormats, E_POINTER); *nFormats = (UINT)m_InputFormats.size(); *formats = (LPSTR *)CoTaskMemAlloc(sizeof(LPSTR) * *nFormats); CheckPointer(*formats, E_OUTOFMEMORY); size_t i = 0; for (auto it = m_InputFormats.begin(); it != m_InputFormats.end(); it++, i++) { size_t len = strlen(it->strName) + 1; (*formats)[i] = (LPSTR)CoTaskMemAlloc(sizeof(CHAR) * len); if (!(*formats)[i]) { break; } strcpy_s((*formats)[i], len, it->strName); } if (i != *nFormats) { for (size_t j = 0; j < i; j++) { CoTaskMemFree((*formats)[i]); } CoTaskMemFree(*formats); *formats = nullptr; return E_OUTOFMEMORY; } return S_OK; } STDMETHODIMP CLAVSplitter::SetNetworkStreamAnalysisDuration(DWORD dwDuration) { m_settings.NetworkAnalysisDuration = dwDuration; return SaveSettings(); } STDMETHODIMP_(DWORD) CLAVSplitter::GetNetworkStreamAnalysisDuration() { return m_settings.NetworkAnalysisDuration; } STDMETHODIMP CLAVSplitter::SetMaxQueueSize(DWORD dwMaxSize) { m_settings.QueueMaxPackets = dwMaxSize; for (auto it = m_pPins.begin(); it != m_pPins.end(); it++) { (*it)->SetQueueSizes(); } return SaveSettings(); } STDMETHODIMP_(DWORD) CLAVSplitter::GetMaxQueueSize() { return m_settings.QueueMaxPackets; } STDMETHODIMP_(std::set &) CLAVSplitter::GetInputFormats() { return m_InputFormats; } CLAVSplitterSource::CLAVSplitterSource(LPUNKNOWN pUnk, HRESULT *phr) : CLAVSplitter(pUnk, phr) { m_clsid = __uuidof(CLAVSplitterSource); SAFE_DELETE(m_pInput); } CLAVSplitterSource::~CLAVSplitterSource() { } STDMETHODIMP CLAVSplitterSource::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); *ppv = nullptr; return QI(IFileSourceFilter) QI(IURLSourceFilterLAV) QI(IAMOpenProgress) __super::NonDelegatingQueryInterface(riid, ppv); } ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.def ================================================ ; LAVFDShowSplitter.def ; declares the exports LIBRARY "LAVSplitter.ax" EXPORTS DllGetClassObject PRIVATE DllCanUnloadNow PRIVATE DllRegisterServer PRIVATE DllUnregisterServer PRIVATE OpenConfiguration PRIVATE ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #pragma once #include #include #include #include #include #include "PacketQueue.h" #include "BaseDemuxer.h" #include "LAVSplitterSettingsInternal.h" #include "SettingsProp.h" #include "IBufferInfo.h" #include "IURLSourceFilterLAV.h" #include "ISpecifyPropertyPages2.h" #include "LAVSplitterTrayIcon.h" #define LAVF_REGISTRY_KEY L"Software\\LAV\\Splitter" #define LAVF_REGISTRY_KEY_FORMATS LAVF_REGISTRY_KEY L"\\Formats" #define LAVF_LOG_FILE L"LAVSplitter.txt" #define MAX_PTS_SHIFT 50000000i64 class CLAVOutputPin; class CLAVInputPin; #ifdef _MSC_VER #pragma warning(disable : 4355) #endif class __declspec(uuid("171252A0-8820-4AFE-9DF8-5C92B2D66B04")) CLAVSplitter : public CBaseFilter , public CCritSec , protected CAMThread , public IFileSourceFilter , public IURLSourceFilterLAV , public IMediaSeeking , public IAMStreamSelect , public IAMOpenProgress , public ILAVFSettingsInternal , public ISpecifyPropertyPages2 , public IObjectWithSite , public IBufferInfo { public: CLAVSplitter(LPUNKNOWN pUnk, HRESULT *phr); virtual ~CLAVSplitter(); // IUnknown DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // CBaseFilter methods int GetPinCount(); CBasePin *GetPin(int n); STDMETHODIMP GetClassID(CLSID *pClsID); STDMETHODIMP Stop(); STDMETHODIMP Pause(); STDMETHODIMP Run(REFERENCE_TIME tStart); STDMETHODIMP JoinFilterGraph(IFilterGraph *pGraph, LPCWSTR pName); // IFileSourceFilter STDMETHODIMP Load(LPCOLESTR pszFileName, const AM_MEDIA_TYPE *pmt); STDMETHODIMP GetCurFile(LPOLESTR *ppszFileName, AM_MEDIA_TYPE *pmt); // IURLSourceFilterLAV STDMETHODIMP LoadURL(LPCOLESTR pszURL, LPCOLESTR pszUserAgent, LPCOLESTR pszReferrer); // IMediaSeeking STDMETHODIMP GetCapabilities(DWORD *pCapabilities); STDMETHODIMP CheckCapabilities(DWORD *pCapabilities); STDMETHODIMP IsFormatSupported(const GUID *pFormat); STDMETHODIMP QueryPreferredFormat(GUID *pFormat); STDMETHODIMP GetTimeFormat(GUID *pFormat); STDMETHODIMP IsUsingTimeFormat(const GUID *pFormat); STDMETHODIMP SetTimeFormat(const GUID *pFormat); STDMETHODIMP GetDuration(LONGLONG *pDuration); STDMETHODIMP GetStopPosition(LONGLONG *pStop); STDMETHODIMP GetCurrentPosition(LONGLONG *pCurrent); STDMETHODIMP ConvertTimeFormat(LONGLONG *pTarget, const GUID *pTargetFormat, LONGLONG Source, const GUID *pSourceFormat); STDMETHODIMP SetPositions(LONGLONG *pCurrent, DWORD dwCurrentFlags, LONGLONG *pStop, DWORD dwStopFlags); STDMETHODIMP GetPositions(LONGLONG *pCurrent, LONGLONG *pStop); STDMETHODIMP GetAvailable(LONGLONG *pEarliest, LONGLONG *pLatest); STDMETHODIMP SetRate(double dRate); STDMETHODIMP GetRate(double *pdRate); STDMETHODIMP GetPreroll(LONGLONG *pllPreroll); // IAMStreamSelect STDMETHODIMP Count(DWORD *pcStreams); STDMETHODIMP Enable(long lIndex, DWORD dwFlags); STDMETHODIMP Info(long lIndex, AM_MEDIA_TYPE **ppmt, DWORD *pdwFlags, LCID *plcid, DWORD *pdwGroup, WCHAR **ppszName, IUnknown **ppObject, IUnknown **ppUnk); // IAMOpenProgress STDMETHODIMP QueryProgress(LONGLONG *pllTotal, LONGLONG *pllCurrent); STDMETHODIMP AbortOperation(); // ISpecifyPropertyPages2 STDMETHODIMP GetPages(CAUUID *pPages); STDMETHODIMP CreatePage(const GUID &guid, IPropertyPage **ppPage); // IObjectWithSite STDMETHODIMP SetSite(IUnknown *pUnkSite); STDMETHODIMP GetSite(REFIID riid, void **ppvSite); // IBufferInfo STDMETHODIMP_(int) GetCount(); STDMETHODIMP GetStatus(int i, int &samples, int &size); STDMETHODIMP_(DWORD) GetPriority(); // ILAVFSettings STDMETHODIMP SetRuntimeConfig(BOOL bRuntimeConfig); STDMETHODIMP GetPreferredLanguages(LPWSTR *ppLanguages); STDMETHODIMP SetPreferredLanguages(LPCWSTR pLanguages); STDMETHODIMP GetPreferredSubtitleLanguages(LPWSTR *ppLanguages); STDMETHODIMP SetPreferredSubtitleLanguages(LPCWSTR pLanguages); STDMETHODIMP_(LAVSubtitleMode) GetSubtitleMode(); STDMETHODIMP SetSubtitleMode(LAVSubtitleMode mode); STDMETHODIMP_(BOOL) GetSubtitleMatchingLanguage(); STDMETHODIMP SetSubtitleMatchingLanguage(BOOL dwMode); STDMETHODIMP_(BOOL) GetPGSForcedStream(); STDMETHODIMP SetPGSForcedStream(BOOL bFlag); STDMETHODIMP_(BOOL) GetPGSOnlyForced(); STDMETHODIMP SetPGSOnlyForced(BOOL bForced); STDMETHODIMP_(int) GetVC1TimestampMode(); STDMETHODIMP SetVC1TimestampMode(int iMode); STDMETHODIMP SetSubstreamsEnabled(BOOL bSubStreams); STDMETHODIMP_(BOOL) GetSubstreamsEnabled(); STDMETHODIMP SetVideoParsingEnabled(BOOL bEnabled); STDMETHODIMP_(BOOL) GetVideoParsingEnabled(); STDMETHODIMP SetFixBrokenHDPVR(BOOL bEnabled); STDMETHODIMP_(BOOL) GetFixBrokenHDPVR(); STDMETHODIMP_(HRESULT) SetFormatEnabled(LPCSTR strFormat, BOOL bEnabled); STDMETHODIMP_(BOOL) IsFormatEnabled(LPCSTR strFormat); STDMETHODIMP SetStreamSwitchRemoveAudio(BOOL bEnabled); STDMETHODIMP_(BOOL) GetStreamSwitchRemoveAudio(); STDMETHODIMP GetAdvancedSubtitleConfig(LPWSTR *ppAdvancedConfig); STDMETHODIMP SetAdvancedSubtitleConfig(LPCWSTR pAdvancedConfig); STDMETHODIMP SetUseAudioForHearingVisuallyImpaired(BOOL bEnabled); STDMETHODIMP_(BOOL) GetUseAudioForHearingVisuallyImpaired(); STDMETHODIMP SetMaxQueueMemSize(DWORD dwMaxSize); STDMETHODIMP_(DWORD) GetMaxQueueMemSize(); STDMETHODIMP SetTrayIcon(BOOL bEnabled); STDMETHODIMP_(BOOL) GetTrayIcon(); STDMETHODIMP SetPreferHighQualityAudioStreams(BOOL bEnabled); STDMETHODIMP_(BOOL) GetPreferHighQualityAudioStreams(); STDMETHODIMP SetLoadMatroskaExternalSegments(BOOL bEnabled); STDMETHODIMP_(BOOL) GetLoadMatroskaExternalSegments(); STDMETHODIMP GetFormats(LPSTR **formats, UINT *nFormats); STDMETHODIMP SetNetworkStreamAnalysisDuration(DWORD dwDuration); STDMETHODIMP_(DWORD) GetNetworkStreamAnalysisDuration(); STDMETHODIMP SetMaxQueueSize(DWORD dwMaxSize); STDMETHODIMP_(DWORD) GetMaxQueueSize(); STDMETHODIMP SetStreamSwitchReselectSubtitles(BOOL bEnabled); STDMETHODIMP_(BOOL) GetStreamSwitchReselectSubtitles(); // ILAVSplitterSettingsInternal STDMETHODIMP_(LPCSTR) GetInputFormat() { if (m_pDemuxer) return m_pDemuxer->GetContainerFormat(); return nullptr; } STDMETHODIMP_(std::set &) GetInputFormats(); STDMETHODIMP_(BOOL) IsVC1CorrectionRequired(); STDMETHODIMP_(CMediaType *) GetOutputMediatype(int stream); STDMETHODIMP_(IFilterGraph *) GetFilterGraph() { if (m_pGraph) { m_pGraph->AddRef(); return m_pGraph; } return nullptr; } STDMETHODIMP_(DWORD) GetStreamFlags(DWORD dwStream) { if (m_pDemuxer) return m_pDemuxer->GetStreamFlags(dwStream); return 0; } STDMETHODIMP_(int) GetPixelFormat(DWORD dwStream) { if (m_pDemuxer) return m_pDemuxer->GetPixelFormat(dwStream); return AV_PIX_FMT_NONE; } STDMETHODIMP_(int) GetHasBFrames(DWORD dwStream) { if (m_pDemuxer) return m_pDemuxer->GetHasBFrames(dwStream); return -1; } STDMETHODIMP GetSideData(DWORD dwStream, GUID guidType, const BYTE **pData, size_t *pSize) { if (m_pDemuxer) return m_pDemuxer->GetSideData(dwStream, guidType, pData, pSize); else return E_FAIL; } // Settings helper std::list GetPreferredAudioLanguageList(); std::list GetSubtitleSelectors(); bool IsAnyPinDrying(); void SetFakeASFReader(BOOL bFlag) { m_bFakeASFReader = bFlag; } protected: // CAMThread enum { CMD_EXIT, CMD_SEEK }; DWORD ThreadProc(); HRESULT DemuxSeek(REFERENCE_TIME rtStart); HRESULT DemuxNextPacket(); HRESULT DeliverPacket(Packet *pPacket); void DeliverBeginFlush(); void DeliverEndFlush(); STDMETHODIMP Close(); STDMETHODIMP DeleteOutputs(); STDMETHODIMP InitDemuxer(); friend class CLAVOutputPin; STDMETHODIMP SetPositionsInternal(void *caller, LONGLONG *pCurrent, DWORD dwCurrentFlags, LONGLONG *pStop, DWORD dwStopFlags); public: CLAVOutputPin *GetOutputPin(DWORD streamId, BOOL bActiveOnly = FALSE); STDMETHODIMP RenameOutputPin(DWORD TrackNumSrc, DWORD TrackNumDst, std::deque pmts); STDMETHODIMP UpdateForcedSubtitleMediaType(); STDMETHODIMP ReselectSubs(int pid); STDMETHODIMP CompleteInputConnection(); STDMETHODIMP BreakInputConnection(); protected: STDMETHODIMP LoadDefaults(); STDMETHODIMP ReadSettings(HKEY rootKey); STDMETHODIMP LoadSettings(); STDMETHODIMP SaveSettings(); STDMETHODIMP CreateTrayIcon(); protected: CLAVInputPin *m_pInput; private: CCritSec m_csPins; std::vector m_pPins; std::vector m_pActivePins; std::vector m_pRetiredPins; std::set m_bDiscontinuitySent; std::wstring m_fileName; std::wstring m_processName; CBaseDemuxer *m_pDemuxer = nullptr; BOOL m_bPlaybackStarted = FALSE; BOOL m_bFakeASFReader = FALSE; // Times REFERENCE_TIME m_rtStart = 0; REFERENCE_TIME m_rtStop = 0; REFERENCE_TIME m_rtCurrent = 0; REFERENCE_TIME m_rtNewStart = 0; REFERENCE_TIME m_rtNewStop = 0; REFERENCE_TIME m_rtOffset = AV_NOPTS_VALUE; double m_dRate = 1.0; BOOL m_bStopValid = FALSE; // Seeking REFERENCE_TIME m_rtLastStart = _I64_MIN; REFERENCE_TIME m_rtLastStop = _I64_MIN; std::set m_LastSeekers; CAMEvent m_ePlaybackInit{TRUE}; // flushing bool m_fFlushing = FALSE; CAMEvent m_eEndFlush; std::set m_InputFormats; // Settings struct Settings { BOOL TrayIcon; std::wstring prefAudioLangs; std::wstring prefSubLangs; std::wstring subtitleAdvanced; LAVSubtitleMode subtitleMode; BOOL PGSForcedStream; BOOL PGSOnlyForced; int vc1Mode; BOOL substreams; BOOL MatroskaExternalSegments; BOOL StreamSwitchReselectSubs; BOOL StreamSwitchRemoveAudio; BOOL ImpairedAudio; BOOL PreferHighQualityAudio; DWORD QueueMaxPackets; DWORD QueueMaxMemSize; DWORD NetworkAnalysisDuration; std::map formats; } m_settings; BOOL m_bRuntimeConfig = FALSE; IUnknown *m_pSite = nullptr; CBaseTrayIcon *m_pTrayIcon = nullptr; }; class __declspec(uuid("B98D13E7-55DB-4385-A33D-09FD1BA26338")) CLAVSplitterSource : public CLAVSplitter { public: // construct only via class factory CLAVSplitterSource(LPUNKNOWN pUnk, HRESULT *phr); virtual ~CLAVSplitterSource(); // IUnknown DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); }; ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.manifest ================================================ ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.rc ================================================ // Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_ICON1 ICON "..\\..\\resources\\white.ico" #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""winres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n" "LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\r\n" "#pragma code_page(1252)\r\n" "#include ""LAVSplitter.rc2"" // non-Microsoft Visual C++ edited resources\r\n" "#endif\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Dialog // IDD_PROPPAGE_LAVFSETTINGS DIALOGEX 0, 0, 400, 274 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN LTEXT "Preferred Languages\nEnter your preferred languages as their 3-letter language codes, comma separated. (Example: ""eng,ger,fre"")",IDC_LBL_PREF_LANG,7,7,386,27 EDITTEXT IDC_PREF_LANG,7,35,386,14,ES_AUTOHSCROLL LTEXT "Audio:",IDC_LBL_PREF_LANG_AUDIO,7,25,31,8 EDITTEXT IDC_PREF_LANG_SUBS,7,65,386,14,ES_AUTOHSCROLL LTEXT "Subtitles:",IDC_LBL_PREF_LANG_SUBS,7,55,47,8 COMBOBOX IDC_SUBTITLE_MODE,99,104,121,100,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP LTEXT "Subtitle Selection Mode:",IDC_LBL_SUBMODE,7,107,83,8 LTEXT "",IDC_SUBTITLE_NOTE,7,83,386,19 GROUPBOX "Blu-ray Subtitles (PGS)",IDC_BD_SUBS,7,124,199,40 CONTROL "Enable Automatic Forced Subtitle Stream",IDC_BD_SEPARATE_FORCED_SUBS, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,137,146,10 CONTROL "Deliver only Forced Subtitles",IDC_BD_ONLY_FORCED_SUBS, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,150,159,10 GROUPBOX "Demuxer Settings",IDC_DEMUXER_SETTINGS,7,170,199,70 CONTROL "Demux sub-streams separately",IDC_SUBSTREAMS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,181,115,10 CONTROL "Remove Audio Decoder on Audio Stream Switch",IDC_STREAM_SWITCH_REMOVE_AUDIO, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,195,168,10 CONTROL "Prefer Audio Stream with the Highest Quality",IDC_SELECT_AUDIO_QUALITY, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,209,171,10 CONTROL "Prefer Audio Streams for the Hearing/Visually Impaired",IDC_IMPAIRED_AUDIO, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,223,188,10 GROUPBOX "Queue Settings",IDC_QUEUE_SETTINGS,214,124,179,44 LTEXT "Maximum Queue Memory (MB):",IDC_LBL_QUEUE_MEM,220,138,102,8 EDITTEXT IDC_QUEUE_MEM,323,136,54,13,ES_AUTOHSCROLL,WS_EX_RIGHT CONTROL "",IDC_QUEUE_MEM_SPIN,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_HOTTRACK,375,136,11,13 LTEXT "Maximum Queue Packets:",IDC_LBL_QUEUE_PACKETS,220,153,102,8 EDITTEXT IDC_QUEUE_PACKETS,323,151,54,13,ES_AUTOHSCROLL,WS_EX_RIGHT CONTROL "",IDC_QUEUE_PACKETS_SPIN,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_HOTTRACK,375,151,11,13 CONTROL "Enable System Tray Icon",IDC_TRAYICON,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,257,192,10 LTEXT "LAV Splitter x.xx",IDC_SPLITTER_FOOTER,285,259,108,8,0,WS_EX_RIGHT GROUPBOX "Format Settings",IDC_FMT_SETTINGS,214,173,179,42 CONTROL "Enable VC-1 Timestamp Correction",IDC_VC1TIMESTAMP, "Button",BS_AUTO3STATE | WS_TABSTOP,221,185,126,10 CONTROL "Load Matroska Segments from external files",IDC_MKV_EXTERNAL, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,221,199,156,10 GROUPBOX "Network Settings",IDC_NETWORK_SETTINGS,214,217,179,35 LTEXT "Stream Analysis Duration:",IDC_LBL_STREAM_BUFFER,220,231,102,8 EDITTEXT IDC_STREAM_ANADUR,323,229,54,13,ES_AUTOHSCROLL,WS_EX_RIGHT CONTROL "",IDC_STREAM_ANADUR_SPIN,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_HOTTRACK,375,229,11,13 CONTROL "Reselect Subtitles on every Audio Switch",IDC_STREAM_SWITCH_RESELECT_SUBS, "Button",BS_AUTOCHECKBOX | WS_TABSTOP,234,105,159,10 END IDD_PROPPAGE_FORMATS DIALOGEX 0, 0, 235, 283 STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD FONT 8, "MS Shell Dlg", 400, 0, 0x0 BEGIN CONTROL "",IDC_FORMATS,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,7,43,221,233 LTEXT "Current Input Format: ",IDC_LBL_INPUT,7,7,77,8 LTEXT "matroska",IDC_CUR_INPUT,85,7,117,8 LTEXT "Select which formats LAV Splitter will demux.\nNote: This has no effect when the file is opened directly by LAV, and only if LAV is loaded automatically in the graph!",IDC_LBL_FORMATS,7,16,221,25 END ///////////////////////////////////////////////////////////////////////////// // // DESIGNINFO // #ifdef APSTUDIO_INVOKED GUIDELINES DESIGNINFO BEGIN IDD_PROPPAGE_LAVFSETTINGS, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 393 TOPMARGIN, 7 BOTTOMMARGIN, 267 END IDD_PROPPAGE_FORMATS, DIALOG BEGIN LEFTMARGIN, 7 RIGHTMARGIN, 228 TOPMARGIN, 7 BOTTOMMARGIN, 276 END END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // String Table // STRINGTABLE BEGIN IDS_PAGE_TITLE "LAV Splitter" IDS_SUBMODE_NO_SUBS "No Subtitles" IDS_SUBMODE_FORCED_SUBS "Only Forced Subtitles" IDS_SUBMODE_DEFAULT "Default" IDS_SUBMODE_ADVANCED "Advanced" IDS_INPUT_FORMATS "Input Formats" END #endif // English (United States) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #include "LAVSplitter.rc2" // non-Microsoft Visual C++ edited resources #endif ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.rc2 ================================================ // // LAVSplitter.rc2 - resources Microsoft Visual C++ does not edit directly // #ifdef APSTUDIO_INVOKED #error This file is not editable by Microsoft Visual C++ #endif //APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // Add manually edited resources here... ///////////////////////////////////////////////////////////////////////////// #include "resource.h" #include "..\..\common\includes\version.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources ///////////////////////////////////////////////////////////////////////////// // Neutral (Sys. Default) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION LAV_VERSION_TAG PRODUCTVERSION LAV_VERSION_TAG FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904b0" BEGIN VALUE "CompanyName", "1f0.de - Hendrik Leppkes" VALUE "FileDescription", "LAV Splitter - DirectShow Media Splitter" VALUE "FileVersion", LAV_VERSION_STR VALUE "InternalName", "LAVSplitter.ax" VALUE "LegalCopyright", "Copyright (C) 2010-2021 Hendrik Leppkes" VALUE "OriginalFilename", "LAVSplitter.ax" VALUE "ProductName", "LAV Splitter" VALUE "ProductVersion", LAV_VERSION_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1200 END END #endif ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.vcxproj ================================================  Debug Win32 Debug x64 Release Win32 Release x64 {F475F86F-3F7F-4B1D-82A6-078339F599FD} Win32Proj LAVSplitter DynamicLibrary true Unicode DynamicLibrary false true Unicode .ax $(SolutionDir)bin_$(PlatformName)d\ .ax $(SolutionDir)bin_$(PlatformName)\$(ProjectName)\ Build WIN32;_DEBUG;_WINDOWS;_USRDLL;LAVSPLITTER_EXPORTS;%(PreprocessorDefinitions) ..\Demuxers;%(AdditionalIncludeDirectories) advapi32.lib;ole32.lib;winmm.lib;user32.lib;oleaut32.lib;Comctl32.lib;shell32.lib;version.lib;Shlwapi.lib;avformat-lav.lib;avutil-lav.lib;avcodec-lav.lib LAVSplitter.def $(ProjectDir)\$(ProjectName).manifest %(AdditionalManifestFiles) WIN32;NDEBUG;_WINDOWS;_USRDLL;LAVSPLITTER_EXPORTS;%(PreprocessorDefinitions) ..\Demuxers;%(AdditionalIncludeDirectories) advapi32.lib;ole32.lib;winmm.lib;user32.lib;oleaut32.lib;Comctl32.lib;shell32.lib;version.lib;Shlwapi.lib;avformat-lav.lib;avutil-lav.lib;avcodec-lav.lib LAVSplitter.def copy "$(TargetDir)\$(TargetName)$(TargetExt)" "$(OutDir).." $(OutDir)..\$(TargetFileName) $(TargetDir)\$(TargetName)$(TargetExt) $(ProjectDir)\$(ProjectName).manifest %(AdditionalManifestFiles) Create copy "%(FullPath)" "$(IntermediateOutputPath).." Copying Manifest file $(IntermediateOutputPath)..\%(Filename)%(Extension);%(Outputs) {e8a3f6fa-ae1c-4c8e-a0b6-9c8480324eaa} {0a058024-41f4-4509-97d2-803a1806ce86} {e1da1b95-71f1-4c21-a271-121176925062} {e2012db5-33cb-44a7-b521-04287f6d0d80} ================================================ FILE: demuxer/LAVSplitter/LAVSplitter.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {31a9533d-6d33-49b2-929c-40167cb6f0e8} Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files\common Header Files\common Header Files Header Files Header Files\common Header Files Header Files Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Header Files\common Resource Files Resource Files Resource Files Resource Files Resource Files ================================================ FILE: demuxer/LAVSplitter/LAVSplitterTrayIcon.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "LAVSplitterTrayIcon.h" #include "PopupMenu.h" #include #define STREAM_CMD_OFFSET 100 #define CHAPTER_CMD_OFFSET 500 CLAVSplitterTrayIcon::CLAVSplitterTrayIcon(IBaseFilter *pFilter, const WCHAR *wszName, int resIcon) : CBaseTrayIcon(pFilter, wszName, resIcon) { } CLAVSplitterTrayIcon::~CLAVSplitterTrayIcon(void) { } HMENU CLAVSplitterTrayIcon::GetPopupMenu() { CheckPointer(m_pFilter, nullptr); CPopupMenu menu; IAMStreamSelect *pStreamSelect = nullptr; if (SUCCEEDED(m_pFilter->QueryInterface(&pStreamSelect))) { DWORD dwStreams = 0; if (FAILED(pStreamSelect->Count(&dwStreams))) dwStreams = 0; DWORD dwLastGroup = DWORD_MAX; for (DWORD i = 0; i < dwStreams; i++) { DWORD dwFlags = 0, dwGroup = 0; LPWSTR pszName = nullptr; if (FAILED(pStreamSelect->Info(i, nullptr, &dwFlags, nullptr, &dwGroup, &pszName, nullptr, nullptr))) continue; if (dwGroup != dwLastGroup) { switch (dwGroup) { case 0: menu.AddItem(dwGroup, L"Video", FALSE, FALSE); break; case 1: menu.AddItem(dwGroup, L"Audio", FALSE, FALSE); break; case 2: menu.AddItem(dwGroup, L"Subtitles", FALSE, FALSE); break; case 18: menu.AddItem(dwGroup, L"Editions", FALSE, FALSE); break; default: menu.AddSeparator(); break; } dwLastGroup = dwGroup; } menu.AddItem(STREAM_CMD_OFFSET + i, pszName, dwFlags & AMSTREAMSELECTINFO_ENABLED); CoTaskMemFree(pszName); } if (dwStreams) menu.AddSeparator(); m_NumStreams = dwStreams; SafeRelease(&pStreamSelect); } // Chapters IAMExtendedSeeking *pExSeeking = nullptr; if (SUCCEEDED(m_pFilter->QueryInterface(IID_IAMExtendedSeeking, (void **)&pExSeeking))) { long count = 0, current = 0; if (FAILED(pExSeeking->get_MarkerCount(&count))) count = 0; if (FAILED(pExSeeking->get_CurrentMarker(¤t))) current = 0; CPopupMenu chapters; for (long i = 1; i <= count; i++) { double markerTime; if (FAILED(pExSeeking->GetMarkerTime(i, &markerTime))) continue; BSTR bstrName = nullptr; if (FAILED(pExSeeking->GetMarkerName(i, &bstrName))) continue; // Create compound chapter name int total_seconds = (int)(markerTime + 0.5); int seconds = total_seconds % 60; int minutes = total_seconds / 60 % 60; int hours = total_seconds / 3600; WCHAR chapterName[512]; _snwprintf_s(chapterName, _TRUNCATE, L"%s\t[%02d:%02d:%02d]", bstrName, hours, minutes, seconds); // Sanitize any tab chars in the chapter name (replace by space) // More then one tab in the string messes with the popup menu rendering WCHAR *nextMatch, *tabMatch = wcsstr(chapterName, L"\t"); while (nextMatch = wcsstr(tabMatch + 1, L"\t")) { *tabMatch = L' '; tabMatch = nextMatch; } chapters.AddItem(CHAPTER_CMD_OFFSET + i, chapterName, i == current); SysFreeString(bstrName); } if (count) { menu.AddSubmenu(chapters.Finish(), L"Chapters"); menu.AddSeparator(); } m_NumChapters = count; SafeRelease(&pExSeeking); } menu.AddItem(STREAM_CMD_OFFSET - 1, L"Properties"); HMENU hMenu = menu.Finish(); return hMenu; } HRESULT CLAVSplitterTrayIcon::ProcessMenuCommand(HMENU hMenu, int cmd) { CheckPointer(m_pFilter, E_FAIL); DbgLog((LOG_TRACE, 10, L"Menu Command %d", cmd)); if (cmd >= STREAM_CMD_OFFSET && cmd < m_NumStreams + STREAM_CMD_OFFSET) { IAMStreamSelect *pStreamSelect = nullptr; if (SUCCEEDED(m_pFilter->QueryInterface(&pStreamSelect))) { pStreamSelect->Enable(cmd - STREAM_CMD_OFFSET, AMSTREAMSELECTENABLE_ENABLE); SafeRelease(&pStreamSelect); } } else if (cmd > CHAPTER_CMD_OFFSET && cmd <= m_NumChapters + CHAPTER_CMD_OFFSET) { IAMExtendedSeeking *pExSeeking = nullptr; if (SUCCEEDED(m_pFilter->QueryInterface(IID_IAMExtendedSeeking, (void **)&pExSeeking))) { double markerTime; if (FAILED(pExSeeking->GetMarkerTime(cmd - CHAPTER_CMD_OFFSET, &markerTime))) goto failchapterseek; REFERENCE_TIME rtMarkerTime = (REFERENCE_TIME)(markerTime * 10000000.0); // Try to get the graph to seek on, its much safer than directly trying to seek on LAV FILTER_INFO info; if (FAILED(m_pFilter->QueryFilterInfo(&info)) || !info.pGraph) goto failchapterseek; IMediaSeeking *pSeeking = nullptr; if (SUCCEEDED(info.pGraph->QueryInterface(&pSeeking))) { pSeeking->SetPositions(&rtMarkerTime, AM_SEEKING_AbsolutePositioning, nullptr, AM_SEEKING_NoPositioning); SafeRelease(&pSeeking); } SafeRelease(&info.pGraph); failchapterseek: SafeRelease(&pExSeeking); } } else if (cmd == STREAM_CMD_OFFSET - 1) { OpenPropPage(); } else { return E_UNEXPECTED; } return S_OK; } ================================================ FILE: demuxer/LAVSplitter/LAVSplitterTrayIcon.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "BaseTrayIcon.h" class CLAVSplitterTrayIcon : public CBaseTrayIcon { public: CLAVSplitterTrayIcon(IBaseFilter *pFilter, const WCHAR *wszName, int resIcon); virtual ~CLAVSplitterTrayIcon(void); protected: HMENU GetPopupMenu(); HRESULT ProcessMenuCommand(HMENU hMenu, int cmd); private: int m_NumStreams = 0; int m_NumChapters = 0; }; ================================================ FILE: demuxer/LAVSplitter/OutputPin.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #include "stdafx.h" #include "BaseDemuxer.h" #include "OutputPin.h" #include "LAVSplitter.h" #include "moreuuids.h" #include "PacketAllocator.h" CLAVOutputPin::CLAVOutputPin(std::deque &mts, LPCWSTR pName, CBaseFilter *pFilter, CCritSec *pLock, HRESULT *phr, CBaseDemuxer::StreamType pinType, const char *container) : CBaseOutputPin(NAME("lavf dshow output pin"), pFilter, pLock, phr, pName) , m_mts(mts) , m_containerFormat(container) , m_pinType(pinType) , m_Parser(this, container) { SetQueueSizes(); } CLAVOutputPin::~CLAVOutputPin() { CAMThread::CallWorker(CMD_EXIT); CAMThread::Close(); SAFE_DELETE(m_newMT); } void CLAVOutputPin::SetQueueSizes() { size_t factor = 1; // Normalize common audio codecs to reach a base line of 20ms if (m_mts.begin()->subtype == MEDIASUBTYPE_DOLBY_TRUEHD) { DbgLog((LOG_TRACE, 10, L"Increasing Audio Queue size for TrueHD")); factor = 30; } else if (m_mts.begin()->subtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO || m_mts.begin()->subtype == MEDIASUBTYPE_BD_LPCM_AUDIO || m_mts.begin()->subtype == MEDIASUBTYPE_PCM) { factor = 4; } else if (m_mts.begin()->subtype == MEDIASUBTYPE_DTS || m_mts.begin()->subtype == MEDIASUBTYPE_WAVE_DTS) { factor = 2; } if (m_mts.begin()->majortype == MEDIATYPE_Audio) { factor *= 4; } m_nQueueLow = MIN_PACKETS_IN_QUEUE * factor; m_nQueueHigh = (size_t)(static_cast(m_pFilter))->GetMaxQueueSize() * factor; m_nQueueMaxMem = (size_t)(static_cast(m_pFilter))->GetMaxQueueMemSize() * 1024 * 1024; if (!m_nQueueMaxMem) { m_nQueueMaxMem = 256 * 1024 * 1024; } } HRESULT CLAVOutputPin::GetQueueSize(int &samples, int &size) { CAutoLock lock(&m_queue); samples = (int)m_queue.Size(); size = (int)m_queue.DataSize(); return S_OK; } STDMETHODIMP CLAVOutputPin::NonDelegatingQueryInterface(REFIID riid, void **ppv) { CheckPointer(ppv, E_POINTER); return QI(IMediaSeeking) QI(ILAVPinInfo) QI(IBitRateInfo) QI(IMediaSideData) __super::NonDelegatingQueryInterface(riid, ppv); } HRESULT CLAVOutputPin::DecideAllocator(IMemInputPin *pPin, IMemAllocator **ppAlloc) { HRESULT hr = NOERROR; *ppAlloc = nullptr; // get downstream prop request // the derived class may modify this in DecideBufferSize, but // we assume that he will consistently modify it the same way, // so we only get it once ALLOCATOR_PROPERTIES prop; ZeroMemory(&prop, sizeof(prop)); // whatever he returns, we assume prop is either all zeros // or he has filled it out. pPin->GetAllocatorRequirements(&prop); // if he doesn't care about alignment, then set it to 1 if (prop.cbAlign == 0) { prop.cbAlign = 1; } *ppAlloc = new CPacketAllocator(NAME("CPacketAllocator"), nullptr, &hr); (*ppAlloc)->AddRef(); if (SUCCEEDED(hr)) { DbgLog((LOG_TRACE, 10, L"Trying to use our CPacketAllocator")); m_bPacketAllocator = TRUE; hr = DecideBufferSize(*ppAlloc, &prop); if (SUCCEEDED(hr)) { DbgLog((LOG_TRACE, 10, L"-> DecideBufferSize Success")); hr = pPin->NotifyAllocator(*ppAlloc, TRUE); if (SUCCEEDED(hr)) { DbgLog((LOG_TRACE, 10, L"-> NotifyAllocator Success")); return NOERROR; } } } if (*ppAlloc) { (*ppAlloc)->Release(); *ppAlloc = nullptr; } m_bPacketAllocator = FALSE; /* Try the allocator provided by the input pin */ hr = pPin->GetAllocator(ppAlloc); if (SUCCEEDED(hr)) { hr = DecideBufferSize(*ppAlloc, &prop); if (SUCCEEDED(hr)) { hr = pPin->NotifyAllocator(*ppAlloc, FALSE); if (SUCCEEDED(hr)) { return NOERROR; } } } /* If the GetAllocator failed we may not have an interface */ if (*ppAlloc) { (*ppAlloc)->Release(); *ppAlloc = nullptr; } return hr; } HRESULT CLAVOutputPin::DecideBufferSize(IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *pProperties) { CheckPointer(pAlloc, E_POINTER); CheckPointer(pProperties, E_POINTER); HRESULT hr = S_OK; pProperties->cBuffers = max(pProperties->cBuffers, (m_bPacketAllocator ? 20 : m_nBuffers)); pProperties->cbBuffer = max(max(m_mt.lSampleSize, 256000), (ULONG)pProperties->cbBuffer); // Vorbis requires at least 2 buffers if (m_mt.subtype == MEDIASUBTYPE_Vorbis && m_mt.formattype == FORMAT_VorbisFormat) { pProperties->cBuffers = max(pProperties->cBuffers, 2); } // Sanity checks ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAlloc->SetProperties(pProperties, &Actual))) return hr; if (Actual.cbBuffer < pProperties->cbBuffer) return E_FAIL; ASSERT(Actual.cBuffers >= pProperties->cBuffers); return S_OK; } HRESULT CLAVOutputPin::CheckMediaType(const CMediaType *pmt) { for (auto it = m_mts.begin(); it != m_mts.end(); ++it) { if (*pmt == *it) return S_OK; } return E_INVALIDARG; } HRESULT CLAVOutputPin::GetMediaType(int iPosition, CMediaType *pmt) { DbgLog((LOG_TRACE, 10, L"CLAVOutputPin::GetMediaType(): %s, position: %d", CBaseDemuxer::CStreamList::ToStringW(m_pinType), iPosition)); CAutoLock cAutoLock(m_pLock); if (iPosition < 0) return E_INVALIDARG; if ((size_t)iPosition >= m_mts.size()) return VFW_S_NO_MORE_ITEMS; *pmt = m_mts[iPosition]; return S_OK; } HRESULT CLAVOutputPin::Active() { DbgLog((LOG_TRACE, 30, L"CLAVOutputPin::Active() - activated %s pin", CBaseDemuxer::CStreamList::ToStringW(m_pinType))); CAutoLock cAutoLock(m_pLock); if (m_Connected) Create(); return __super::Active(); } HRESULT CLAVOutputPin::Inactive() { DbgLog((LOG_TRACE, 30, L"CLAVOutputPin::Inactive() - de-activated %s pin", CBaseDemuxer::CStreamList::ToStringW(m_pinType))); CAutoLock cAutoLock(m_pLock); CAMThread::CallWorker(CMD_EXIT); CAMThread::Close(); // Clear queue when we're going inactive m_queue.Clear(); return __super::Inactive(); } STDMETHODIMP CLAVOutputPin::Connect(IPin *pReceivePin, const AM_MEDIA_TYPE *pmt) { HRESULT hr; PIN_INFO PinInfo; GUID FilterClsid; if (SUCCEEDED(pReceivePin->QueryPinInfo(&PinInfo))) { if (SUCCEEDED(PinInfo.pFilter->GetClassID(&FilterClsid))) { if (FilterClsid == CLSID_DMOWrapperFilter) { (static_cast(m_pFilter))->SetFakeASFReader(TRUE); } } PinInfo.pFilter->Release(); } hr = __super::Connect(pReceivePin, pmt); (static_cast(m_pFilter))->SetFakeASFReader(FALSE); return hr; } HRESULT CLAVOutputPin::CompleteConnect(IPin *pReceivePin) { m_StreamMT = m_mt; return __super::CompleteConnect(pReceivePin); } HRESULT CLAVOutputPin::DeliverBeginFlush() { DbgLog((LOG_TRACE, 20, L"::DeliverBeginFlush on %s Pin", CBaseDemuxer::CStreamList::ToStringW(m_pinType))); m_eEndFlush.Reset(); m_fFlushed = false; m_fFlushing = true; m_hrDeliver = S_FALSE; m_queue.Clear(); HRESULT hr = IsConnected() ? GetConnected()->BeginFlush() : S_OK; if (hr != S_OK) m_eEndFlush.Set(); return hr; } HRESULT CLAVOutputPin::DeliverEndFlush() { DbgLog((LOG_TRACE, 20, L"::DeliverEndFlush on %s Pin", CBaseDemuxer::CStreamList::ToStringW(m_pinType))); HRESULT hr = IsConnected() ? GetConnected()->EndFlush() : S_OK; m_Parser.Flush(); m_hrDeliver = S_OK; m_fFlushing = false; m_fFlushed = true; m_eEndFlush.Set(); return hr; } HRESULT CLAVOutputPin::DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate) { HRESULT hr = S_OK; DbgLog((LOG_TRACE, 20, L"::DeliverNewSegment on %s Pin (rtStart: %I64d; rtStop: %I64d)", CBaseDemuxer::CStreamList::ToStringW(m_pinType), tStart, tStop)); m_rtPrev = AV_NOPTS_VALUE; if (m_fFlushing) return S_FALSE; if (!ThreadExists()) return S_FALSE; m_BitRate.rtLastDeliverTime = Packet::INVALID_TIME; hr = __super::DeliverNewSegment(tStart, tStop, dRate); if (hr != S_OK) return hr; MakeISCRHappy(); return hr; } void CLAVOutputPin::MakeISCRHappy() { if (IsSubtitlePin() && FilterInGraphSafe(this, CLSID_ISCR)) { Packet *p = new Packet(); p->StreamId = m_streamId; p->rtStart = -1; p->rtStop = 0; p->bSyncPoint = FALSE; p->SetData(" ", 2); QueueFromParser(p); } } size_t CLAVOutputPin::QueueCount() { return m_queue.Size(); } HRESULT CLAVOutputPin::QueueEndOfStream() { return QueuePacket(nullptr); // nullptr means EndOfStream } HRESULT CLAVOutputPin::QueuePacket(Packet *pPacket) { if (!ThreadExists()) { SAFE_DELETE(pPacket); return S_FALSE; } CLAVSplitter *pSplitter = static_cast(m_pFilter); // While everything is good AND no pin is drying AND the queue is full .. sleep // The queue has a "soft" limit of MAX_PACKETS_IN_QUEUE, and a hard limit of MAX_PACKETS_IN_QUEUE * 16 (and a memory limit) // That means, even if one pin is drying, we'll never exceed MAX_PACKETS_IN_QUEUE * 16 while (S_OK == m_hrDeliver && (m_queue.DataSize() > m_nQueueMaxMem || m_queue.Size() > 16 * m_nQueueHigh || (m_queue.Size() > m_nQueueHigh && !pSplitter->IsAnyPinDrying()))) Sleep(10); if (S_OK != m_hrDeliver) { SAFE_DELETE(pPacket); return m_hrDeliver; } { CAutoLock lock(&m_csMT); if (m_newMT && pPacket) { DbgLog((LOG_TRACE, 10, L"::QueuePacket() - Found new Media Type")); pPacket->pmt = CreateMediaType(m_newMT); SetStreamMediaType(m_newMT); SAFE_DELETE(m_newMT); } } m_Parser.Parse(m_StreamMT.subtype, pPacket); return m_hrDeliver; } bool CLAVOutputPin::IsDiscontinuous() { return m_mt.majortype == MEDIATYPE_Text || m_mt.majortype == MEDIATYPE_ScriptCommand || m_mt.majortype == MEDIATYPE_Subtitle || m_mt.subtype == MEDIASUBTYPE_DVD_SUBPICTURE || m_mt.subtype == MEDIASUBTYPE_CVD_SUBPICTURE || m_mt.subtype == MEDIASUBTYPE_SVCD_SUBPICTURE; } DWORD CLAVOutputPin::ThreadProc() { std::string name = "CLAVOutputPin " + std::string(CBaseDemuxer::CStreamList::ToString(m_pinType)); SetThreadName(-1, name.c_str()); m_hrDeliver = S_OK; m_fFlushing = m_fFlushed = false; m_eEndFlush.Set(); bool bFailFlush = false; while (1) { Sleep(1); DWORD cmd; if (CheckRequest(&cmd)) { cmd = GetRequest(); Reply(S_OK); ASSERT(cmd == CMD_EXIT); return 0; } size_t cnt = 0; do { Packet *pPacket = nullptr; // Get a packet from the queue (scoped for lock) { CAutoLock cAutoLock(&m_queue); if ((cnt = m_queue.Size()) > 0) { pPacket = m_queue.Get(); } } // We need to check cnt instead of pPacket, since it can be nullptr for EndOfStream if (m_hrDeliver == S_OK && cnt > 0) { ASSERT(!m_fFlushing); m_fFlushed = false; // flushing can still start here, to release a blocked deliver call HRESULT hr = pPacket ? DeliverPacket(pPacket) : DeliverEndOfStream(); // .. so, wait until flush finished m_eEndFlush.Wait(); if (hr != S_OK && !m_fFlushed) { DbgLog((LOG_TRACE, 10, L"OutputPin::ThreadProc(): Delivery failed on %s pin, hr: %0#.8x", CBaseDemuxer::CStreamList::ToStringW(GetPinType()), hr)); if (!bFailFlush && hr == S_FALSE) { DbgLog((LOG_TRACE, 10, L"OutputPin::ThreadProc(): Trying to revive it by flushing...")); GetConnected()->BeginFlush(); GetConnected()->EndFlush(); bFailFlush = true; } else { m_hrDeliver = hr; } break; } } else if (pPacket) { // in case of stream switches or other events, we may end up here SAFE_DELETE(pPacket); } } while (cnt > 1 && m_hrDeliver == S_OK); } return 0; } HRESULT CLAVOutputPin::DeliverPacket(Packet *pPacket) { HRESULT hr = S_OK; IMediaSample *pSample = nullptr; long nBytes = (long)pPacket->GetDataSize(); if (nBytes == 0) { goto done; } CHECK_HR(hr = GetDeliveryBuffer(&pSample, nullptr, nullptr, 0)); if (m_bPacketAllocator) { ILAVMediaSample *pLAVSample = nullptr; CHECK_HR(hr = pSample->QueryInterface(&pLAVSample)); CHECK_HR(hr = pLAVSample->SetPacket(pPacket)); SafeRelease(&pLAVSample); } else { // Resize buffer if it is too small // This can cause a playback hick-up, we should avoid this if possible by setting a big enough buffer size if (nBytes > pSample->GetSize()) { SafeRelease(&pSample); ALLOCATOR_PROPERTIES props, actual; CHECK_HR(hr = m_pAllocator->GetProperties(&props)); // Give us 2 times the requested size, so we don't resize every time props.cbBuffer = nBytes * 2; if (props.cBuffers > 1) { CHECK_HR(hr = __super::DeliverBeginFlush()); CHECK_HR(hr = __super::DeliverEndFlush()); } CHECK_HR(hr = m_pAllocator->Decommit()); CHECK_HR(hr = m_pAllocator->SetProperties(&props, &actual)); CHECK_HR(hr = m_pAllocator->Commit()); CHECK_HR(hr = GetDeliveryBuffer(&pSample, nullptr, nullptr, 0)); } // Fill the sample BYTE *pData = nullptr; if (FAILED(hr = pSample->GetPointer(&pData)) || !pData) goto done; memcpy(pData, pPacket->GetData(), nBytes); } if (pPacket->pmt) { DbgLog((LOG_TRACE, 10, L"::DeliverPacket() - sending new media type to decoder")); pSample->SetMediaType(pPacket->pmt); pPacket->bDiscontinuity = true; CAutoLock cAutoLock(m_pLock); CMediaType pmt = *(pPacket->pmt); m_mts.clear(); m_mts.push_back(pmt); pPacket->pmt = nullptr; SetMediaType(&pmt); } bool fTimeValid = pPacket->rtStart != Packet::INVALID_TIME; // IBitRateInfo m_BitRate.nBytesSinceLastDeliverTime += nBytes; if (fTimeValid) { if (m_BitRate.rtLastDeliverTime == Packet::INVALID_TIME) { m_BitRate.rtLastDeliverTime = pPacket->rtStart; m_BitRate.nBytesSinceLastDeliverTime = 0; } if (m_BitRate.rtLastDeliverTime + 10000000 < pPacket->rtStart) { REFERENCE_TIME rtDiff = pPacket->rtStart - m_BitRate.rtLastDeliverTime; double dSecs, dBits; dSecs = rtDiff / 10000000.0; dBits = 8.0 * m_BitRate.nBytesSinceLastDeliverTime; m_BitRate.nCurrentBitRate = (DWORD)(dBits / dSecs); m_BitRate.rtTotalTimeDelivered += rtDiff; m_BitRate.nTotalBytesDelivered += m_BitRate.nBytesSinceLastDeliverTime; dSecs = m_BitRate.rtTotalTimeDelivered / 10000000.0; dBits = 8.0 * m_BitRate.nTotalBytesDelivered; m_BitRate.nAverageBitRate = (DWORD)(dBits / dSecs); m_BitRate.rtLastDeliverTime = pPacket->rtStart; m_BitRate.nBytesSinceLastDeliverTime = 0; } } CHECK_HR(hr = pSample->SetActualDataLength(nBytes)); CHECK_HR(hr = pSample->SetTime(fTimeValid ? &pPacket->rtStart : nullptr, fTimeValid ? &pPacket->rtStop : nullptr)); CHECK_HR(hr = pSample->SetMediaTime(nullptr, nullptr)); CHECK_HR(hr = pSample->SetDiscontinuity(pPacket->bDiscontinuity)); CHECK_HR(hr = pSample->SetSyncPoint(pPacket->bSyncPoint)); CHECK_HR(hr = pSample->SetPreroll(fTimeValid && pPacket->rtStart < 0)); // Deliver CHECK_HR(hr = Deliver(pSample)); done: if (!m_bPacketAllocator || !pSample) SAFE_DELETE(pPacket); SafeRelease(&pSample); return hr; } // IMediaSeeking STDMETHODIMP CLAVOutputPin::GetCapabilities(DWORD *pCapabilities) { return (static_cast(m_pFilter))->GetCapabilities(pCapabilities); } STDMETHODIMP CLAVOutputPin::CheckCapabilities(DWORD *pCapabilities) { return (static_cast(m_pFilter))->CheckCapabilities(pCapabilities); } STDMETHODIMP CLAVOutputPin::IsFormatSupported(const GUID *pFormat) { return (static_cast(m_pFilter))->IsFormatSupported(pFormat); } STDMETHODIMP CLAVOutputPin::QueryPreferredFormat(GUID *pFormat) { return (static_cast(m_pFilter))->QueryPreferredFormat(pFormat); } STDMETHODIMP CLAVOutputPin::GetTimeFormat(GUID *pFormat) { return (static_cast(m_pFilter))->GetTimeFormat(pFormat); } STDMETHODIMP CLAVOutputPin::IsUsingTimeFormat(const GUID *pFormat) { return (static_cast(m_pFilter))->IsUsingTimeFormat(pFormat); } STDMETHODIMP CLAVOutputPin::SetTimeFormat(const GUID *pFormat) { return (static_cast(m_pFilter))->SetTimeFormat(pFormat); } STDMETHODIMP CLAVOutputPin::GetDuration(LONGLONG *pDuration) { return (static_cast(m_pFilter))->GetDuration(pDuration); } STDMETHODIMP CLAVOutputPin::GetStopPosition(LONGLONG *pStop) { return (static_cast(m_pFilter))->GetStopPosition(pStop); } STDMETHODIMP CLAVOutputPin::GetCurrentPosition(LONGLONG *pCurrent) { return (static_cast(m_pFilter))->GetCurrentPosition(pCurrent); } STDMETHODIMP CLAVOutputPin::ConvertTimeFormat(LONGLONG *pTarget, const GUID *pTargetFormat, LONGLONG Source, const GUID *pSourceFormat) { return (static_cast(m_pFilter))->ConvertTimeFormat(pTarget, pTargetFormat, Source, pSourceFormat); } STDMETHODIMP CLAVOutputPin::SetPositions(LONGLONG *pCurrent, DWORD dwCurrentFlags, LONGLONG *pStop, DWORD dwStopFlags) { return (static_cast(m_pFilter)) ->SetPositionsInternal(this, pCurrent, dwCurrentFlags, pStop, dwStopFlags); } STDMETHODIMP CLAVOutputPin::GetPositions(LONGLONG *pCurrent, LONGLONG *pStop) { return (static_cast(m_pFilter))->GetPositions(pCurrent, pStop); } STDMETHODIMP CLAVOutputPin::GetAvailable(LONGLONG *pEarliest, LONGLONG *pLatest) { return (static_cast(m_pFilter))->GetAvailable(pEarliest, pLatest); } STDMETHODIMP CLAVOutputPin::SetRate(double dRate) { return (static_cast(m_pFilter))->SetRate(dRate); } STDMETHODIMP CLAVOutputPin::GetRate(double *pdRate) { return (static_cast(m_pFilter))->GetRate(pdRate); } STDMETHODIMP CLAVOutputPin::GetPreroll(LONGLONG *pllPreroll) { return (static_cast(m_pFilter))->GetPreroll(pllPreroll); } STDMETHODIMP_(DWORD) CLAVOutputPin::GetStreamFlags() { return (static_cast(m_pFilter))->GetStreamFlags(m_streamId); } STDMETHODIMP_(int) CLAVOutputPin::GetPixelFormat() { return (static_cast(m_pFilter))->GetPixelFormat(m_streamId); } STDMETHODIMP_(int) CLAVOutputPin::GetHasBFrames() { return (static_cast(m_pFilter))->GetHasBFrames(m_streamId); } STDMETHODIMP CLAVOutputPin::GetSideData(GUID guidType, const BYTE **pData, size_t *pSize) { return (static_cast(m_pFilter))->GetSideData(m_streamId, guidType, pData, pSize); } ================================================ FILE: demuxer/LAVSplitter/OutputPin.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #pragma once #include #include #include "PacketQueue.h" #include "StreamParser.h" #include "moreuuids.h" #include "LAVSplitter.h" #include "ILAVPinInfo.h" #include "IBitRateInfo.h" #include "IMediaSideData.h" class CLAVOutputPin : public CBaseOutputPin , public ILAVPinInfo , public IBitRateInfo , public IMediaSideData , IMediaSeeking , protected CAMThread { public: CLAVOutputPin(std::deque &mts, LPCWSTR pName, CBaseFilter *pFilter, CCritSec *pLock, HRESULT *phr, CBaseDemuxer::StreamType pinType = CBaseDemuxer::unknown, const char *container = ""); virtual ~CLAVOutputPin(); DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // IQualityControl STDMETHODIMP Notify(IBaseFilter *pSender, Quality q) { return E_NOTIMPL; } // CBaseOutputPin HRESULT DecideAllocator(IMemInputPin *pPin, IMemAllocator **pAlloc); HRESULT DecideBufferSize(IMemAllocator *pAlloc, ALLOCATOR_PROPERTIES *pProperties); HRESULT CheckMediaType(const CMediaType *pmt); HRESULT GetMediaType(int iPosition, CMediaType *pmt); HRESULT Active(); HRESULT Inactive(); STDMETHODIMP Connect(IPin *pReceivePin, const AM_MEDIA_TYPE *pmt); HRESULT CompleteConnect(IPin *pReceivePin); // IMediaSeeking STDMETHODIMP GetCapabilities(DWORD *pCapabilities); STDMETHODIMP CheckCapabilities(DWORD *pCapabilities); STDMETHODIMP IsFormatSupported(const GUID *pFormat); STDMETHODIMP QueryPreferredFormat(GUID *pFormat); STDMETHODIMP GetTimeFormat(GUID *pFormat); STDMETHODIMP IsUsingTimeFormat(const GUID *pFormat); STDMETHODIMP SetTimeFormat(const GUID *pFormat); STDMETHODIMP GetDuration(LONGLONG *pDuration); STDMETHODIMP GetStopPosition(LONGLONG *pStop); STDMETHODIMP GetCurrentPosition(LONGLONG *pCurrent); STDMETHODIMP ConvertTimeFormat(LONGLONG *pTarget, const GUID *pTargetFormat, LONGLONG Source, const GUID *pSourceFormat); STDMETHODIMP SetPositions(LONGLONG *pCurrent, DWORD dwCurrentFlags, LONGLONG *pStop, DWORD dwStopFlags); STDMETHODIMP GetPositions(LONGLONG *pCurrent, LONGLONG *pStop); STDMETHODIMP GetAvailable(LONGLONG *pEarliest, LONGLONG *pLatest); STDMETHODIMP SetRate(double dRate); STDMETHODIMP GetRate(double *pdRate); STDMETHODIMP GetPreroll(LONGLONG *pllPreroll); // ILAVPinInfo STDMETHODIMP_(DWORD) GetStreamFlags(); STDMETHODIMP_(int) GetPixelFormat(); STDMETHODIMP_(int) GetVersion() { return 1; } STDMETHODIMP_(int) GetHasBFrames(); // IBitRateInfo STDMETHODIMP_(DWORD) GetCurrentBitRate() { return m_BitRate.nCurrentBitRate; } STDMETHODIMP_(DWORD) GetAverageBitRate() { return m_BitRate.nAverageBitRate; } // IMediaSideData STDMETHODIMP SetSideData(GUID guidType, const BYTE *pData, size_t size) { return E_NOTIMPL; } STDMETHODIMP GetSideData(GUID guidType, const BYTE **pData, size_t *pSize); size_t QueueCount(); HRESULT QueuePacket(Packet *pPacket); HRESULT QueueEndOfStream(); bool IsDiscontinuous(); size_t GetQueueLowLimit() const { return m_nQueueLow; } DWORD GetStreamId() { return m_streamId; }; void SetStreamId(DWORD newStreamId) { m_streamId = newStreamId; }; void SetNewMediaTypes(std::deque pmts) { CAutoLock lock(&m_csMT); m_mts = pmts; SetQueueSizes(); } void SendMediaType(CMediaType *mt) { CAutoLock lock(&m_csMT); m_newMT = mt; } void SetStreamMediaType(CMediaType *mt) { CAutoLock lock(&m_csMT); m_StreamMT = *mt; } CMediaType &GetActiveMediaType() { return m_mt; } BOOL IsVideoPin() { return m_pinType == CBaseDemuxer::video; } BOOL IsAudioPin() { return m_pinType == CBaseDemuxer::audio; } BOOL IsSubtitlePin() { return m_pinType == CBaseDemuxer::subpic; } CBaseDemuxer::StreamType GetPinType() { return m_pinType; } HRESULT QueueFromParser(Packet *pPacket) { m_queue.Queue(pPacket); return S_OK; } HRESULT GetQueueSize(int &samples, int &size); public: // Packet handling functions virtual HRESULT DeliverBeginFlush(); virtual HRESULT DeliverEndFlush(); virtual HRESULT DeliverNewSegment(REFERENCE_TIME tStart, REFERENCE_TIME tStop, double dRate); void SetQueueSizes(); REFERENCE_TIME m_rtPrev = AV_NOPTS_VALUE; protected: virtual HRESULT DeliverPacket(Packet *pPacket); private: enum { CMD_EXIT }; DWORD ThreadProc(); void MakeISCRHappy(); private: CCritSec m_csMT; std::deque m_mts; CPacketQueue m_queue; CMediaType m_StreamMT; std::string m_containerFormat; // Flush control bool m_fFlushing = false; bool m_fFlushed = false; CAMEvent m_eEndFlush{TRUE}; HRESULT m_hrDeliver = S_OK; int m_nBuffers = 1; size_t m_nQueueLow = MIN_PACKETS_IN_QUEUE; size_t m_nQueueHigh = 350; size_t m_nQueueMaxMem = 256 * 1024 * 1024; DWORD m_streamId = 0; CMediaType *m_newMT = nullptr; CBaseDemuxer::StreamType m_pinType; CStreamParser m_Parser; BOOL m_bPacketAllocator = FALSE; // IBitRateInfo struct BitRateInfo { UINT64 nTotalBytesDelivered = 0; REFERENCE_TIME rtTotalTimeDelivered = 0; UINT64 nBytesSinceLastDeliverTime = 0; REFERENCE_TIME rtLastDeliverTime = Packet::INVALID_TIME; DWORD nCurrentBitRate = 0; DWORD nAverageBitRate = 0; } m_BitRate; }; ================================================ FILE: demuxer/LAVSplitter/PacketAllocator.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #include "stdafx.h" #include "PacketAllocator.h" CMediaPacketSample::CMediaPacketSample(LPCTSTR pName, CBaseAllocator *pAllocator, HRESULT *phr) : CMediaSample(pName, pAllocator, phr) { } STDMETHODIMP CMediaPacketSample::QueryInterface(REFIID riid, void **ppv) { if (riid == __uuidof(ILAVMediaSample)) { return GetInterface((ILAVMediaSample *)this, ppv); } else if (riid == __uuidof(IMediaSideData)) { return GetInterface((IMediaSideData *)this, ppv); } return CMediaSample::QueryInterface(riid, ppv); } STDMETHODIMP_(ULONG) CMediaPacketSample::AddRef() { return CMediaSample::AddRef(); } STDMETHODIMP_(ULONG) CMediaPacketSample::Release() { /* Decrement our own private reference count */ LONG lRef; if (m_cRef == 1) { lRef = 0; m_cRef = 0; } else { lRef = InterlockedDecrement(&m_cRef); } ASSERT(lRef >= 0); DbgLog((LOG_MEMORY, 3, TEXT(" Unknown %X ref-- = %d"), this, m_cRef)); /* Did we release our final reference count */ if (lRef == 0) { /* Free all resources */ if (m_dwFlags & Sample_TypeChanged) { SetMediaType(nullptr); } ASSERT(m_pMediaType == nullptr); m_dwFlags = 0; m_dwTypeSpecificFlags = 0; m_dwStreamId = AM_STREAM_MEDIA; SAFE_DELETE(m_pPacket); SetPointer(nullptr, 0); SAFE_DELETE(m_pSideData); /* This may cause us to be deleted */ // Our refcount is reliably 0 thus no-one will mess with us m_pAllocator->ReleaseBuffer(this); } return (ULONG)lRef; } STDMETHODIMP CMediaPacketSample::SetPacket(Packet *pPacket) { SAFE_DELETE(m_pPacket); m_pPacket = pPacket; SetPointer(pPacket->GetData(), (LONG)pPacket->GetDataSize()); SAFE_DELETE(m_pSideData); if (pPacket->GetNumSideData() > 0) { m_pSideData = new MediaSideDataFFMpeg(); m_pSideData->side_data = pPacket->GetSideData(); m_pSideData->side_data_elems = pPacket->GetNumSideData(); } return S_OK; } STDMETHODIMP CMediaPacketSample::SetSideData(GUID guidType, const BYTE *pData, size_t size) { return E_NOTIMPL; } STDMETHODIMP CMediaPacketSample::GetSideData(GUID guidType, const BYTE **pData, size_t *pSize) { if (guidType == IID_MediaSideDataFFMpeg && m_pSideData) { *pData = (const BYTE *)m_pSideData; *pSize = sizeof(MediaSideDataFFMpeg); return S_OK; } return E_INVALIDARG; } CPacketAllocator::CPacketAllocator(LPCTSTR pName, LPUNKNOWN pUnk, HRESULT *phr) : CBaseAllocator(pName, pUnk, phr, TRUE, TRUE) { } CPacketAllocator::~CPacketAllocator(void) { Decommit(); ReallyFree(); } STDMETHODIMP CPacketAllocator::NonDelegatingQueryInterface(REFIID riid, __deref_out void **ppv) { if (riid == IID_ILAVDynamicAllocator) { return GetInterface((ILAVDynamicAllocator *)this, ppv); } else { return __super::NonDelegatingQueryInterface(riid, ppv); } } STDMETHODIMP CPacketAllocator::SetProperties(ALLOCATOR_PROPERTIES *pRequest, ALLOCATOR_PROPERTIES *pActual) { CheckPointer(pActual, E_POINTER); ValidateReadWritePtr(pActual, sizeof(ALLOCATOR_PROPERTIES)); CAutoLock cObjectLock(this); ZeroMemory(pActual, sizeof(ALLOCATOR_PROPERTIES)); ASSERT(pRequest->cbBuffer > 0); SYSTEM_INFO SysInfo; GetSystemInfo(&SysInfo); /* Check the alignment request is a power of 2 */ if ((-pRequest->cbAlign & pRequest->cbAlign) != pRequest->cbAlign) { DbgLog((LOG_ERROR, 1, TEXT("Alignment requested 0x%x not a power of 2!"), pRequest->cbAlign)); } /* Check the alignment requested */ if (pRequest->cbAlign == 0 || (SysInfo.dwAllocationGranularity & (pRequest->cbAlign - 1)) != 0) { DbgLog((LOG_ERROR, 1, TEXT("Invalid alignment 0x%x requested - granularity = 0x%x"), pRequest->cbAlign, SysInfo.dwAllocationGranularity)); return VFW_E_BADALIGN; } /* Can't do this if already committed, there is an argument that says we should not reject the SetProperties call if there are buffers still active. However this is called by the source filter, which is the same person who is holding the samples. Therefore it is not unreasonable for them to free all their samples before changing the requirements */ if (m_bCommitted == TRUE) { return VFW_E_ALREADY_COMMITTED; } /* Must be no outstanding buffers */ if (m_lFree.GetCount() < m_lAllocated) { return VFW_E_BUFFERS_OUTSTANDING; } /* There isn't any real need to check the parameters as they will just be rejected when the user finally calls Commit */ // round length up to alignment - remember that prefix is included in // the alignment LONG lSize = pRequest->cbBuffer + pRequest->cbPrefix; LONG lRemainder = lSize % pRequest->cbAlign; if (lRemainder != 0) { lSize = lSize - lRemainder + pRequest->cbAlign; } pActual->cbBuffer = m_lSize = (lSize - pRequest->cbPrefix); pActual->cBuffers = m_lCount = pRequest->cBuffers; pActual->cbAlign = m_lAlignment = pRequest->cbAlign; pActual->cbPrefix = m_lPrefix = pRequest->cbPrefix; m_bChanged = TRUE; return NOERROR; } HRESULT CPacketAllocator::Alloc(void) { CAutoLock lck(this); /* Check he has called SetProperties */ HRESULT hr = CBaseAllocator::Alloc(); if (FAILED(hr)) { return hr; } /* If the requirements haven't changed then don't reallocate */ if (hr == S_FALSE) { return NOERROR; } ASSERT(hr == S_OK); // we use this fact in the loop below /* Free the old resources */ if (m_bAllocated) { ReallyFree(); } /* Make sure we've got reasonable values */ if (m_lSize < 0 || m_lPrefix < 0 || m_lCount < 0) { return E_OUTOFMEMORY; } m_bAllocated = TRUE; CMediaPacketSample *pSample = nullptr; ASSERT(m_lAllocated == 0); // Create the initial set of samples for (; m_lAllocated < m_lCount; m_lAllocated++) { pSample = new CMediaPacketSample(NAME("LAV Package media sample"), this, &hr); ASSERT(SUCCEEDED(hr)); if (pSample == nullptr) { return E_OUTOFMEMORY; } // This CANNOT fail m_lFree.Add(pSample); } m_bChanged = FALSE; return NOERROR; } // get container for a sample. Blocking, synchronous call to get the // next free buffer (as represented by an IMediaSample interface). // on return, the time etc properties will be invalid, but the buffer // pointer and size will be correct. HRESULT CPacketAllocator::GetBuffer(__deref_out IMediaSample **ppBuffer, __in_opt REFERENCE_TIME *pStartTime, __in_opt REFERENCE_TIME *pEndTime, DWORD dwFlags) { UNREFERENCED_PARAMETER(pStartTime); UNREFERENCED_PARAMETER(pEndTime); UNREFERENCED_PARAMETER(dwFlags); CMediaSample *pSample; *ppBuffer = NULL; for (;;) { { // scope for lock CAutoLock cObjectLock(this); /* Check we are committed */ if (!m_bCommitted) { return VFW_E_NOT_COMMITTED; } pSample = (CMediaSample *)m_lFree.RemoveHead(); /* if no sample was available, allocate a new one */ if (pSample == NULL) { HRESULT hr = S_OK; pSample = new CMediaPacketSample(NAME("LAV Package media sample"), this, &hr); ASSERT(SUCCEEDED(hr)); if (pSample) { m_lAllocated++; DbgLog((LOG_TRACE, 10, "Allocated new sample, %d total", m_lAllocated)); } } } /* If we didn't get a sample then wait for the list to signal */ if (pSample) { break; } if (dwFlags & AM_GBF_NOWAIT) { return VFW_E_TIMEOUT; } ASSERT(m_hSem != NULL); WaitForSingleObject(m_hSem, INFINITE); } /* Addref the buffer up to one. On release back to zero instead of being deleted, it will requeue itself by calling the ReleaseBuffer member function. NOTE the owner of a media sample must always be derived from CBaseAllocator */ ASSERT(pSample->m_cRef == 0); pSample->m_cRef = 1; *ppBuffer = pSample; #ifdef DXMPERF PERFLOG_GETBUFFER((IMemAllocator *)this, pSample); #endif // DXMPERF return NOERROR; } // override this to free up any resources we have allocated. // called from the base class on Decommit when all buffers have been // returned to the free list. // // caller has already locked the object. // in our case, we keep the memory until we are deleted, so // we do nothing here. The memory is deleted in the destructor by // calling ReallyFree() void CPacketAllocator::Free(void) { return; } // called from the destructor (and from Alloc if changing size/count) to // actually free up the memory void CPacketAllocator::ReallyFree(void) { /* Should never be deleting this unless all buffers are freed */ ASSERT(m_lAllocated == m_lFree.GetCount()); /* Free up all the CMediaSamples */ CMediaSample *pSample; for (;;) { pSample = m_lFree.RemoveHead(); if (pSample != nullptr) { delete pSample; } else { break; } } m_lAllocated = 0; m_bAllocated = FALSE; } ================================================ FILE: demuxer/LAVSplitter/PacketAllocator.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 * Contributions by Ti-BEN from the XBMC DSPlayer Project, also under GPLv2 */ #pragma once #include "Packet.h" #include "IMediaSideData.h" #include "IMediaSideDataFFmpeg.h" #include "ILAVDynamicAllocator.h" interface __declspec(uuid("0B2EE323-0ED8-452D-B31E-B9B4DE2C0C39")) ILAVMediaSample : public IUnknown { STDMETHOD(SetPacket)(Packet * pPacket) PURE; }; class CMediaPacketSample : public CMediaSample , public ILAVMediaSample , public IMediaSideData { public: CMediaPacketSample(LPCTSTR pName, CBaseAllocator *pAllocator, HRESULT *phr); // IUnknown STDMETHODIMP QueryInterface(REFIID riid, void **ppv); STDMETHODIMP_(ULONG) AddRef(); STDMETHODIMP_(ULONG) Release(); // ILAVMediaSamples STDMETHODIMP SetPacket(Packet *pPacket); // IMediaSideData STDMETHODIMP SetSideData(GUID guidType, const BYTE *pData, size_t size); STDMETHODIMP GetSideData(GUID guidType, const BYTE **pData, size_t *pSize); protected: Packet *m_pPacket = nullptr; MediaSideDataFFMpeg *m_pSideData = nullptr; }; class CPacketAllocator : public CBaseAllocator , public ILAVDynamicAllocator { protected: BOOL m_bAllocated = FALSE; // override to free the memory when decommit completes // - we actually do nothing, and save the memory until deletion. void Free(void); // called from the destructor (and from Alloc if changing size/count) to // actually free up the memory void ReallyFree(void); // overridden to allocate the memory when commit called HRESULT Alloc(void); public: CPacketAllocator(LPCTSTR pName, LPUNKNOWN pUnk, HRESULT *phr); virtual ~CPacketAllocator(void); // CUnknown support DECLARE_IUNKNOWN; STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv); // CBaseAllocator overrides STDMETHODIMP SetProperties(ALLOCATOR_PROPERTIES *pRequest, ALLOCATOR_PROPERTIES *pActual); STDMETHODIMP GetBuffer(IMediaSample **ppBuffer, REFERENCE_TIME *pStartTime, REFERENCE_TIME *pEndTime, DWORD dwFlags); // ILAVDynamicAllocator STDMETHODIMP_(BOOL) IsDynamicAllocator() { return TRUE; } }; ================================================ FILE: demuxer/LAVSplitter/PacketQueue.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "PacketQueue.h" #include "BaseDemuxer.h" // Queue a new packet at the end of the list void CPacketQueue::Queue(Packet *pPacket) { CAutoLock cAutoLock(this); if (pPacket) m_dataSize += (size_t)pPacket->GetDataSize(); m_queue.push_back(pPacket); } // Get a packet from the beginning of the list Packet *CPacketQueue::Get() { CAutoLock cAutoLock(this); if (m_queue.size() == 0) { return nullptr; } Packet *pPacket = m_queue.front(); m_queue.pop_front(); if (pPacket) m_dataSize -= (size_t)pPacket->GetDataSize(); return pPacket; } // Get the size of the queue size_t CPacketQueue::Size() { CAutoLock cAutoLock(this); return m_queue.size(); } // Get the size of the queue size_t CPacketQueue::DataSize() { CAutoLock cAutoLock(this); return m_dataSize; } // Clear the List (all elements are free'ed) void CPacketQueue::Clear() { CAutoLock cAutoLock(this); DbgLog((LOG_TRACE, 10, L"CPacketQueue::Clear() - clearing queue with %d entries", m_queue.size())); std::deque::iterator it; for (it = m_queue.begin(); it != m_queue.end(); ++it) { delete *it; } m_queue.clear(); m_dataSize = 0; } ================================================ FILE: demuxer/LAVSplitter/PacketQueue.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include #define MIN_PACKETS_IN_QUEUE 50 // Below this is considered "drying pin" class Packet; // FIFO Packet Queue class CPacketQueue : public CCritSec { public: CPacketQueue(){}; // Queue a new packet at the end of the list void Queue(Packet *pPacket); // Get a packet from the beginning of the list Packet *Get(); // Get the size of the queue size_t Size(); // Get the size of the queue in bytes size_t DataSize(); // Clear the List (all elements are free'ed) void Clear(); // Get access to the internal queue std::deque *GetQueue() { return &m_queue; } bool IsEmpty() { CAutoLock cAutoLock(this); return m_queue.empty(); } private: // The actual storage class std::deque m_queue; size_t m_dataSize = 0; #ifdef DEBUG bool m_bWarnedFull = false; bool m_bWarnedExtreme = false; #endif }; ================================================ FILE: demuxer/LAVSplitter/SettingsProp.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include #include #include "SettingsProp.h" #include "DShowUtil.h" #include "version.h" CLAVSplitterSettingsProp::CLAVSplitterSettingsProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVF Settings"), pUnk, IDD_PROPPAGE_LAVFSETTINGS, IDS_PAGE_TITLE) { } CLAVSplitterSettingsProp::~CLAVSplitterSettingsProp(void) { SAFE_CO_FREE(m_pszPrefLang); SAFE_CO_FREE(m_pszPrefSubLang); SAFE_CO_FREE(m_pszAdvSubConfig); SafeRelease(&m_pLAVF); } HRESULT CLAVSplitterSettingsProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pLAVF == nullptr); return pUnk->QueryInterface(&m_pLAVF); } HRESULT CLAVSplitterSettingsProp::OnDisconnect() { SafeRelease(&m_pLAVF); return S_OK; } HRESULT CLAVSplitterSettingsProp::OnApplyChanges() { ASSERT(m_pLAVF != nullptr); HRESULT hr = S_OK; DWORD dwVal; BOOL bFlag; WCHAR buffer[LANG_BUFFER_SIZE]; // Save audio language SendDlgItemMessage(m_Dlg, IDC_PREF_LANG, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer); CHECK_HR(hr = m_pLAVF->SetPreferredLanguages(buffer)); // Save subtitle language SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer); if (m_selectedSubMode == LAVSubtitleMode_Advanced) { CHECK_HR(hr = m_pLAVF->SetPreferredSubtitleLanguages(m_subLangBuffer)); CHECK_HR(hr = m_pLAVF->SetAdvancedSubtitleConfig(buffer)); } else { CHECK_HR(hr = m_pLAVF->SetPreferredSubtitleLanguages(buffer)); CHECK_HR(hr = m_pLAVF->SetAdvancedSubtitleConfig(m_advSubBuffer)); } // Save subtitle mode dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_GETCURSEL, 0, 0); CHECK_HR(hr = m_pLAVF->SetSubtitleMode((LAVSubtitleMode)dwVal)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_SEPARATE_FORCED_SUBS, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetPGSForcedStream(bFlag)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_ONLY_FORCED_SUBS, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetPGSOnlyForced(bFlag)); int vc1flag = (int)SendDlgItemMessage(m_Dlg, IDC_VC1TIMESTAMP, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetVC1TimestampMode(vc1flag)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MKV_EXTERNAL, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetLoadMatroskaExternalSegments(bFlag)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SUBSTREAMS, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetSubstreamsEnabled(bFlag)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_REMOVE_AUDIO, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetStreamSwitchRemoveAudio(bFlag)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_RESELECT_SUBS, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetStreamSwitchReselectSubtitles(bFlag)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SELECT_AUDIO_QUALITY, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetPreferHighQualityAudioStreams(bFlag)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_IMPAIRED_AUDIO, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetUseAudioForHearingVisuallyImpaired(bFlag)); SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer); int maxMem = _wtoi(buffer); CHECK_HR(hr = m_pLAVF->SetMaxQueueMemSize(maxMem)); SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer); int maxPackets = _wtoi(buffer); CHECK_HR(hr = m_pLAVF->SetMaxQueueSize(maxPackets)); SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer); int duration = _wtoi(buffer); CHECK_HR(hr = m_pLAVF->SetNetworkStreamAnalysisDuration(duration)); bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_GETCHECK, 0, 0); CHECK_HR(hr = m_pLAVF->SetTrayIcon(bFlag)); LoadData(); done: return hr; } void CLAVSplitterSettingsProp::UpdateSubtitleMode(LAVSubtitleMode mode) { if (mode == LAVSubtitleMode_NoSubs) { WCHAR *note = L"No subtitles: Subtitles are disabled and will not be loaded by default."; SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_NOTE, WM_SETTEXT, 0, (LPARAM)note); } else if (mode == LAVSubtitleMode_ForcedOnly) { WCHAR *note = L"Only Forced Subtitles: Only subtitles marked as \"forced\" will be loaded."; SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_NOTE, WM_SETTEXT, 0, (LPARAM)note); } else if (mode == LAVSubtitleMode_Default) { WCHAR *note = L"Default Mode: Subtitles matching the preferred languages, as well as \"default\" and " L"\"forced\" subtitles will be loaded."; SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_NOTE, WM_SETTEXT, 0, (LPARAM)note); } else if (mode == LAVSubtitleMode_Advanced) { WCHAR *note = L"Advanced Mode: Refer to the README or the documentation on http://1f0.de for details."; SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_NOTE, WM_SETTEXT, 0, (LPARAM)note); } else { WCHAR *empty = L""; SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_NOTE, WM_SETTEXT, 0, (LPARAM)empty); } LAVSubtitleMode oldMode = m_selectedSubMode; m_selectedSubMode = mode; // Switch away from advanced if (oldMode != mode && oldMode == LAVSubtitleMode_Advanced) { SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&m_advSubBuffer); SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_SETTEXT, 0, (LPARAM)&m_subLangBuffer); // Switch to advanced } else if (oldMode != mode && mode == LAVSubtitleMode_Advanced) { SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&m_subLangBuffer); SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_SETTEXT, 0, (LPARAM)&m_advSubBuffer); } } HRESULT CLAVSplitterSettingsProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pLAVF != nullptr); const WCHAR *version = TEXT(LAV_SPLITTER) L" " TEXT(LAV_VERSION_STR); SendDlgItemMessage(m_Dlg, IDC_SPLITTER_FOOTER, WM_SETTEXT, 0, (LPARAM)version); hr = LoadData(); memset(m_subLangBuffer, 0, sizeof(m_advSubBuffer)); memset(m_advSubBuffer, 0, sizeof(m_advSubBuffer)); m_selectedSubMode = LAVSubtitleMode_Default; if (m_pszAdvSubConfig) wcsncpy_s(m_advSubBuffer, m_pszAdvSubConfig, _TRUNCATE); // Notify the UI about those settings SendDlgItemMessage(m_Dlg, IDC_PREF_LANG, WM_SETTEXT, 0, (LPARAM)m_pszPrefLang); SendDlgItemMessage(m_Dlg, IDC_PREF_LANG_SUBS, WM_SETTEXT, 0, (LPARAM)m_pszPrefSubLang); // Init the Combo Box SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_RESETCONTENT, 0, 0); WideStringFromResource(stringBuffer, IDS_SUBMODE_NO_SUBS); SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_SUBMODE_FORCED_SUBS); SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_SUBMODE_DEFAULT); SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); WideStringFromResource(stringBuffer, IDS_SUBMODE_ADVANCED); SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_ADDSTRING, 0, (LPARAM)stringBuffer); SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_SETCURSEL, m_subtitleMode, 0); addHint(IDC_SUBTITLE_MODE, L"Configure how subtitles are selected."); SendDlgItemMessage(m_Dlg, IDC_BD_SEPARATE_FORCED_SUBS, BM_SETCHECK, m_PGSForcedStream, 0); addHint(IDC_BD_SEPARATE_FORCED_SUBS, L"Enabling this causes the creation of a new \"Forced Subtitles\" stream, which will try to always display " L"forced subtitles matching your selected audio language.\n\nNOTE: This option may not work on all Blu-ray " L"discs.\nRequires restart to take effect."); SendDlgItemMessage(m_Dlg, IDC_BD_ONLY_FORCED_SUBS, BM_SETCHECK, m_PGSOnlyForced, 0); addHint(IDC_BD_ONLY_FORCED_SUBS, L"When enabled, all Blu-ray (PGS) subtitles will be filtered, and only forced subtitles will be sent to " L"the renderer.\n\nNOTE: When this option is active, you will not be able to get the \"full\" subtitles."); SendDlgItemMessage(m_Dlg, IDC_VC1TIMESTAMP, BM_SETCHECK, m_VC1Mode, 0); addHint(IDC_VC1TIMESTAMP, L"Checked - Frame timings will be corrected.\nUnchecked - Frame timings will be sent " L"untouched.\nIndeterminate (Auto) - Only enabled for decoders that rely on the splitter " L"doing the corrections.\n\nNOTE: Only for debugging, if unsure, set to \"Auto\"."); SendDlgItemMessage(m_Dlg, IDC_MKV_EXTERNAL, BM_SETCHECK, m_MKVExternal, 0); SendDlgItemMessage(m_Dlg, IDC_SUBSTREAMS, BM_SETCHECK, m_substreams, 0); addHint(IDC_SUBSTREAMS, L"Controls if sub-streams should be exposed as a separate stream.\nSub-streams are typically streams for " L"backwards compatibility, for example the AC3 part of TrueHD streams on Blu-rays."); SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_REMOVE_AUDIO, BM_SETCHECK, m_StreamSwitchRemoveAudio, 0); addHint(IDC_STREAM_SWITCH_REMOVE_AUDIO, L"Remove the old Audio Decoder from the Playback Chain before switching the audio stream, forcing " L"DirectShow to select a new one.\n\nThis option ensures that the preferred decoder is always used, " L"however it does not work properly with all players."); SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_RESELECT_SUBS, BM_SETCHECK, m_StreamSwitchReselectSubs, 0); addHint(IDC_STREAM_SWITCH_RESELECT_SUBS, L"Reapply the subtitle-selection rules when the audio-stream has changed. This automatically adjusts the " L"selected subtitle to the selected audio track.\nThe subtitle track can still be changed manually, " L"however it will be overridden again on the next audio track switch."); addHint(IDC_SELECT_AUDIO_QUALITY, L"Controls if the stream with the highest quality (matching your language preferences) should always be " L"used.\nIf disabled, the first stream is always used."); SendDlgItemMessage(m_Dlg, IDC_SELECT_AUDIO_QUALITY, BM_SETCHECK, m_PreferHighQualityAudio, 0); SendDlgItemMessage(m_Dlg, IDC_IMPAIRED_AUDIO, BM_SETCHECK, m_ImpairedAudio, 0); SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM_SPIN, UDM_SETRANGE32, 0, 2048); addHint(IDC_QUEUE_MEM, L"Set the maximum memory a frame queue can use for buffering (in megabytes).\nNote that this is the " L"maximum value, only very high bitrate files will usually even reach the default maximum value."); addHint(IDC_QUEUE_MEM_SPIN, L"Set the maximum memory a frame queue can use for buffering (in megabytes).\nNote that this is the " L"maximum value, only very high bitrate files will usually even reach the default maximum value."); swprintf_s(stringBuffer, L"%d", m_QueueMaxMem); SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM, WM_SETTEXT, 0, (LPARAM)stringBuffer); SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS_SPIN, UDM_SETRANGE32, 100, 100000); addHint(IDC_QUEUE_PACKETS, L"Set the maximum numbers of packets to buffer in the frame queue.\nNote that the frame " L"queue will never exceed the memory limited set above."); addHint(IDC_QUEUE_PACKETS_SPIN, L"Set the maximum numbers of packets to buffer in the frame queue.\nNote that the " L"frame queue will never exceed the memory limited set above."); swprintf_s(stringBuffer, L"%d", m_QueueMaxPackets); SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS, WM_SETTEXT, 0, (LPARAM)stringBuffer); SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR_SPIN, UDM_SETRANGE32, 200, 10000); addHint(IDC_STREAM_ANADUR, L"Set the duration (in milliseconds) a network stream is analyzed for before playback " L"starts.\nA longer duration ensures the stream parameters are properly detected, " L"however it will delay playback start.\n\nDefault: 1000 (1 second)"); addHint(IDC_STREAM_ANADUR_SPIN, L"Set the duration (in milliseconds) a network stream is analyzed for before " L"playback starts.\nA longer duration ensures the stream parameters are properly " L"detected, however it will delay playback start.\n\nDefault: 1000 (1 second)"); swprintf_s(stringBuffer, L"%d", m_NetworkAnalysisDuration); SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR, WM_SETTEXT, 0, (LPARAM)stringBuffer); UpdateSubtitleMode(m_subtitleMode); SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_SETCHECK, m_TrayIcon, 0); return hr; } HRESULT CLAVSplitterSettingsProp::LoadData() { HRESULT hr = S_OK; // Free old strings SAFE_CO_FREE(m_pszPrefLang); SAFE_CO_FREE(m_pszPrefSubLang); SAFE_CO_FREE(m_pszAdvSubConfig); // Query current settings CHECK_HR(hr = m_pLAVF->GetPreferredLanguages(&m_pszPrefLang)); CHECK_HR(hr = m_pLAVF->GetPreferredSubtitleLanguages(&m_pszPrefSubLang)); CHECK_HR(hr = m_pLAVF->GetAdvancedSubtitleConfig(&m_pszAdvSubConfig)); m_subtitleMode = m_pLAVF->GetSubtitleMode(); m_PGSForcedStream = m_pLAVF->GetPGSForcedStream(); m_PGSOnlyForced = m_pLAVF->GetPGSOnlyForced(); m_VC1Mode = m_pLAVF->GetVC1TimestampMode(); m_substreams = m_pLAVF->GetSubstreamsEnabled(); m_MKVExternal = m_pLAVF->GetLoadMatroskaExternalSegments(); m_StreamSwitchReselectSubs = m_pLAVF->GetStreamSwitchReselectSubtitles(); m_StreamSwitchRemoveAudio = m_pLAVF->GetStreamSwitchRemoveAudio(); m_PreferHighQualityAudio = m_pLAVF->GetPreferHighQualityAudioStreams(); m_ImpairedAudio = m_pLAVF->GetUseAudioForHearingVisuallyImpaired(); m_QueueMaxMem = m_pLAVF->GetMaxQueueMemSize(); m_QueueMaxPackets = m_pLAVF->GetMaxQueueSize(); m_NetworkAnalysisDuration = m_pLAVF->GetNetworkStreamAnalysisDuration(); m_TrayIcon = m_pLAVF->GetTrayIcon(); done: return hr; } INT_PTR CLAVSplitterSettingsProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_COMMAND: // Mark the page dirty if the text changed if (HIWORD(wParam) == EN_CHANGE && (LOWORD(wParam) == IDC_PREF_LANG || LOWORD(wParam) == IDC_PREF_LANG_SUBS)) { WCHAR buffer[LANG_BUFFER_SIZE]; SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, LANG_BUFFER_SIZE, (LPARAM)&buffer); int dirty = 0; WCHAR *source = nullptr; if (LOWORD(wParam) == IDC_PREF_LANG) { source = m_pszPrefLang; } else { source = (m_selectedSubMode == LAVSubtitleMode_Advanced) ? m_pszAdvSubConfig : m_pszPrefSubLang; } if (source) { dirty = _wcsicmp(buffer, source); } else { dirty = (int)wcslen(buffer); } if (dirty != 0) { SetDirty(); } } else if (HIWORD(wParam) == CBN_SELCHANGE && LOWORD(wParam) == IDC_SUBTITLE_MODE) { DWORD dwVal = (DWORD)SendDlgItemMessage(m_Dlg, IDC_SUBTITLE_MODE, CB_GETCURSEL, 0, 0); UpdateSubtitleMode((LAVSubtitleMode)dwVal); if (dwVal != m_subtitleMode) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_BD_SEPARATE_FORCED_SUBS) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_SEPARATE_FORCED_SUBS, BM_GETCHECK, 0, 0); if (bFlag != m_PGSForcedStream) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_BD_ONLY_FORCED_SUBS) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_BD_ONLY_FORCED_SUBS, BM_GETCHECK, 0, 0); if (bFlag != m_PGSOnlyForced) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_VC1TIMESTAMP) { int iFlag = (int)SendDlgItemMessage(m_Dlg, IDC_VC1TIMESTAMP, BM_GETCHECK, 0, 0); if (iFlag != m_VC1Mode) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_MKV_EXTERNAL) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_MKV_EXTERNAL, BM_GETCHECK, 0, 0); if (bFlag != m_MKVExternal) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_SUBSTREAMS) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SUBSTREAMS, BM_GETCHECK, 0, 0); if (bFlag != m_substreams) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_STREAM_SWITCH_REMOVE_AUDIO) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_REMOVE_AUDIO, BM_GETCHECK, 0, 0); if (bFlag != m_StreamSwitchRemoveAudio) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_STREAM_SWITCH_RESELECT_SUBS) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_STREAM_SWITCH_RESELECT_SUBS, BM_GETCHECK, 0, 0); if (bFlag != m_StreamSwitchReselectSubs) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_SELECT_AUDIO_QUALITY) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_SELECT_AUDIO_QUALITY, BM_GETCHECK, 0, 0); if (bFlag != m_PreferHighQualityAudio) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_IMPAIRED_AUDIO) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_IMPAIRED_AUDIO, BM_GETCHECK, 0, 0); if (bFlag != m_ImpairedAudio) { SetDirty(); } } else if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_TRAYICON) { BOOL bFlag = (BOOL)SendDlgItemMessage(m_Dlg, IDC_TRAYICON, BM_GETCHECK, 0, 0); if (bFlag != m_TrayIcon) { SetDirty(); } } else if (LOWORD(wParam) == IDC_QUEUE_MEM && HIWORD(wParam) == EN_CHANGE) { WCHAR buffer[100]; SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, 100, (LPARAM)&buffer); int maxMem = _wtoi(buffer); size_t len = wcslen(buffer); if (maxMem == 0 && (buffer[0] != L'0' || len > 1)) { SendDlgItemMessage(m_Dlg, LOWORD(wParam), EM_UNDO, 0, 0); } else { swprintf_s(buffer, L"%d", maxMem); if (wcslen(buffer) != len) SendDlgItemMessage(m_Dlg, IDC_QUEUE_MEM, WM_SETTEXT, 0, (LPARAM)buffer); if (maxMem != m_QueueMaxMem) SetDirty(); } } else if (LOWORD(wParam) == IDC_QUEUE_PACKETS && HIWORD(wParam) == EN_CHANGE) { WCHAR buffer[100]; SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, 100, (LPARAM)&buffer); int maxMem = _wtoi(buffer); size_t len = wcslen(buffer); if (maxMem == 0 && (buffer[0] != L'0' || len > 1)) { SendDlgItemMessage(m_Dlg, LOWORD(wParam), EM_UNDO, 0, 0); } else { swprintf_s(buffer, L"%d", maxMem); if (wcslen(buffer) != len) SendDlgItemMessage(m_Dlg, IDC_QUEUE_PACKETS, WM_SETTEXT, 0, (LPARAM)buffer); if (maxMem != m_QueueMaxPackets) SetDirty(); } } else if (LOWORD(wParam) == IDC_STREAM_ANADUR && HIWORD(wParam) == EN_CHANGE) { WCHAR buffer[100]; SendDlgItemMessage(m_Dlg, LOWORD(wParam), WM_GETTEXT, 100, (LPARAM)&buffer); int duration = _wtoi(buffer); size_t len = wcslen(buffer); if (duration == 0 && (buffer[0] != L'0' || len > 1)) { SendDlgItemMessage(m_Dlg, LOWORD(wParam), EM_UNDO, 0, 0); } else { swprintf_s(buffer, L"%d", duration); if (wcslen(buffer) != len) SendDlgItemMessage(m_Dlg, IDC_STREAM_ANADUR, WM_SETTEXT, 0, (LPARAM)buffer); if (duration != m_NetworkAnalysisDuration) SetDirty(); } } break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } CLAVSplitterFormatsProp::CLAVSplitterFormatsProp(LPUNKNOWN pUnk, HRESULT *phr) : CBaseDSPropPage(NAME("LAVF Settings"), pUnk, IDD_PROPPAGE_FORMATS, IDS_INPUT_FORMATS) { } CLAVSplitterFormatsProp::~CLAVSplitterFormatsProp(void) { SAFE_CO_FREE(m_bFormats); SafeRelease(&m_pLAVF); } HRESULT CLAVSplitterFormatsProp::OnConnect(IUnknown *pUnk) { if (pUnk == nullptr) { return E_POINTER; } ASSERT(m_pLAVF == nullptr); return pUnk->QueryInterface(&m_pLAVF); } HRESULT CLAVSplitterFormatsProp::OnDisconnect() { SafeRelease(&m_pLAVF); return S_OK; } HRESULT CLAVSplitterFormatsProp::OnApplyChanges() { HRESULT hr = S_OK; ASSERT(m_pLAVF != nullptr); HWND hlv = GetDlgItem(m_Dlg, IDC_FORMATS); int nItem = 0; std::set::const_iterator it; for (it = m_Formats.begin(); it != m_Formats.end(); ++it) { m_bFormats[nItem] = ListView_GetCheckState(hlv, nItem); m_pLAVF->SetFormatEnabled(it->strName, m_bFormats[nItem]); nItem++; } return hr; } HRESULT CLAVSplitterFormatsProp::OnActivate() { HRESULT hr = S_OK; INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(INITCOMMONCONTROLSEX); icc.dwICC = ICC_BAR_CLASSES | ICC_STANDARD_CLASSES; if (InitCommonControlsEx(&icc) == FALSE) { return E_FAIL; } ASSERT(m_pLAVF != nullptr); memset(stringBuffer, 0, sizeof(stringBuffer)); const char *pszInput = m_pLAVF->GetInputFormat(); if (pszInput) { _snwprintf_s(stringBuffer, _TRUNCATE, L"%S", pszInput); } SendDlgItemMessage(m_Dlg, IDC_CUR_INPUT, WM_SETTEXT, 0, (LPARAM)stringBuffer); m_Formats = m_pLAVF->GetInputFormats(); // Setup ListView control for format configuration SendDlgItemMessage(m_Dlg, IDC_FORMATS, CCM_DPISCALE, TRUE, 0); HWND hlv = GetDlgItem(m_Dlg, IDC_FORMATS); ListView_SetExtendedListViewStyle(hlv, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); int nCol = 1; LVCOLUMN lvc = {LVCF_WIDTH, 0, 20, 0}; ListView_InsertColumn(hlv, 0, &lvc); ListView_AddCol(hlv, nCol, 75, L"Format", false); ListView_AddCol(hlv, nCol, 210, L"Description", false); ListView_DeleteAllItems(hlv); ListView_SetItemCount(hlv, m_Formats.size()); SAFE_CO_FREE(m_bFormats); m_bFormats = (BOOL *)CoTaskMemAlloc(sizeof(BOOL) * m_Formats.size()); if (!m_bFormats) return E_OUTOFMEMORY; memset(m_bFormats, 0, sizeof(BOOL) * m_Formats.size()); // Create entries for the formats LVITEM lvi; memset(&lvi, 0, sizeof(lvi)); lvi.mask = LVIF_TEXT | LVIF_PARAM; int nItem = 0; std::set::const_iterator it; for (it = m_Formats.begin(); it != m_Formats.end(); ++it) { // Create main entry lvi.iItem = nItem + 1; ListView_InsertItem(hlv, &lvi); // Set sub item texts _snwprintf_s(stringBuffer, _TRUNCATE, L"%S", it->strName); ListView_SetItemText(hlv, nItem, 1, (LPWSTR)stringBuffer); _snwprintf_s(stringBuffer, _TRUNCATE, L"%S", it->strDescription); ListView_SetItemText(hlv, nItem, 2, (LPWSTR)stringBuffer); m_bFormats[nItem] = m_pLAVF->IsFormatEnabled(it->strName); ListView_SetCheckState(hlv, nItem, m_bFormats[nItem]); nItem++; } return hr; } INT_PTR CLAVSplitterFormatsProp::OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_NOTIFY: NMHDR *hdr = (LPNMHDR)lParam; if (hdr->idFrom == IDC_FORMATS) { switch (hdr->code) { case LVN_ITEMCHANGED: LPNMLISTVIEW nmlv = (LPNMLISTVIEW)lParam; BOOL check = ListView_GetCheckState(hdr->hwndFrom, nmlv->iItem); if (check != m_bFormats[nmlv->iItem]) { SetDirty(); } return TRUE; } } break; } // Let the parent class handle the message. return __super::OnReceiveMessage(hwnd, uMsg, wParam, lParam); } ================================================ FILE: demuxer/LAVSplitter/SettingsProp.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include "BaseDSPropPage.h" #include "LAVSplitterSettingsInternal.h" // GUID: a19de2f2-2f74-4927-8436-61129d26c141 DEFINE_GUID(CLSID_LAVSplitterSettingsProp, 0xa19de2f2, 0x2f74, 0x4927, 0x84, 0x36, 0x61, 0x12, 0x9d, 0x26, 0xc1, 0x41); // {56904B22-091C-4459-A2E6-B1F4F946B55F} DEFINE_GUID(CLSID_LAVSplitterFormatsProp, 0x56904b22, 0x91c, 0x4459, 0xa2, 0xe6, 0xb1, 0xf4, 0xf9, 0x46, 0xb5, 0x5f); #define LANG_BUFFER_SIZE 16384 class CLAVSplitterSettingsProp : public CBaseDSPropPage { public: CLAVSplitterSettingsProp(LPUNKNOWN pUnk, HRESULT *phr); virtual ~CLAVSplitterSettingsProp(void); HRESULT OnActivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); HRESULT OnApplyChanges(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: HRESULT LoadData(); void UpdateSubtitleMode(LAVSubtitleMode mode); void SetDirty() { m_bDirty = TRUE; if (m_pPageSite) { m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY); } } private: ILAVFSettingsInternal *m_pLAVF = nullptr; // Settings WCHAR *m_pszPrefLang = nullptr; WCHAR *m_pszPrefSubLang = nullptr; WCHAR *m_pszAdvSubConfig = nullptr; LAVSubtitleMode m_subtitleMode; BOOL m_PGSForcedStream; BOOL m_PGSOnlyForced; int m_VC1Mode; BOOL m_substreams; BOOL m_MKVExternal; BOOL m_StreamSwitchReselectSubs; BOOL m_StreamSwitchRemoveAudio; BOOL m_PreferHighQualityAudio; BOOL m_ImpairedAudio; DWORD m_QueueMaxMem; DWORD m_QueueMaxPackets; DWORD m_NetworkAnalysisDuration; BOOL m_TrayIcon; LAVSubtitleMode m_selectedSubMode; WCHAR m_subLangBuffer[LANG_BUFFER_SIZE]; WCHAR m_advSubBuffer[LANG_BUFFER_SIZE]; WCHAR stringBuffer[256]; }; class CLAVSplitterFormatsProp : public CBaseDSPropPage { public: CLAVSplitterFormatsProp(LPUNKNOWN pUnk, HRESULT *phr); virtual ~CLAVSplitterFormatsProp(void); HRESULT OnActivate(); HRESULT OnConnect(IUnknown *pUnk); HRESULT OnDisconnect(); HRESULT OnApplyChanges(); INT_PTR OnReceiveMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); private: void SetDirty() { m_bDirty = TRUE; if (m_pPageSite) { m_pPageSite->OnStatusChange(PROPPAGESTATUS_DIRTY); } } private: ILAVFSettingsInternal *m_pLAVF = nullptr; std::set m_Formats; BOOL *m_bFormats = nullptr; WCHAR stringBuffer[256]; }; ================================================ FILE: demuxer/LAVSplitter/StreamParser.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #include "stdafx.h" #include "StreamParser.h" #include "OutputPin.h" #include "H264Nalu.h" #pragma warning(push) #pragma warning(disable : 4101) #pragma warning(disable : 5033) extern "C" { #define AVCODEC_X86_MATHOPS_H #include "libavcodec/get_bits.h" } #pragma warning(pop) #define AAC_ADTS_HEADER_SIZE 7 //#define DEBUG_PGS_PARSER CStreamParser::CStreamParser(CLAVOutputPin *pPin, const char *szContainer) : m_pPin(pPin) , m_strContainer(szContainer) { } CStreamParser::~CStreamParser() { Flush(); } HRESULT CStreamParser::Parse(const GUID &gSubtype, Packet *pPacket) { if (gSubtype != m_gSubtype) { m_gSubtype = gSubtype; Flush(); } if (!pPacket || (pPacket->dwFlags & LAV_PACKET_PARSED)) { Queue(pPacket); } else if (m_gSubtype == MEDIASUBTYPE_AVC1 && (m_strContainer == "mpegts" || pPacket->dwFlags & LAV_PACKET_H264_ANNEXB)) { ParseH264AnnexB(pPacket); } else if (m_gSubtype == MEDIASUBTYPE_HDMVSUB) { ParsePGS(pPacket); } else if (m_gSubtype == MEDIASUBTYPE_HDMV_LPCM_AUDIO) { pPacket->RemoveHead(4); Queue(pPacket); } else if (m_gSubtype == MEDIASUBTYPE_DVD_LPCM_AUDIO) { pPacket->RemoveHead(3); Queue(pPacket); } else if (pPacket->dwFlags & LAV_PACKET_MOV_TEXT) { ParseMOVText(pPacket); } else if (m_gSubtype == MEDIASUBTYPE_AAC && (m_strContainer != "matroska" && m_strContainer != "mp4")) { ParseAAC(pPacket); } else if (m_gSubtype == MEDIASUBTYPE_UTF8 && (pPacket->dwFlags & LAV_PACKET_SRT)) { ParseSRT(pPacket); } else if ((m_gSubtype == MEDIASUBTYPE_PCM || m_gSubtype == MEDIASUBTYPE_PCM_TWOS) && (pPacket->dwFlags & LAV_PACKET_PLANAR_PCM)) { ParsePlanarPCM(pPacket); } else { Queue(pPacket); } return S_OK; } HRESULT CStreamParser::Flush() { DbgLog((LOG_TRACE, 10, L"CStreamParser::Flush()")); SAFE_DELETE(m_pPacketBuffer); m_queue.Clear(); m_bPGSDropState = FALSE; m_bHasAccessUnitDelimiters = false; return S_OK; } HRESULT CStreamParser::Queue(Packet *pPacket) const { return m_pPin->QueueFromParser(pPacket); } static Packet *InitPacket(Packet *pSource) { Packet *pNew = nullptr; pNew = new Packet(); pNew->StreamId = pSource->StreamId; pNew->bDiscontinuity = pSource->bDiscontinuity; pSource->bDiscontinuity = FALSE; pNew->bSyncPoint = pSource->bSyncPoint; pSource->bSyncPoint = FALSE; pNew->rtStart = pSource->rtStart; pSource->rtStart = Packet::INVALID_TIME; pNew->rtStop = pSource->rtStop; pSource->rtStop = Packet::INVALID_TIME; pNew->pmt = pSource->pmt; pSource->pmt = nullptr; return pNew; } #define MOVE_TO_H264_START_CODE(b, e) \ while (b <= e - 4 && !((*(DWORD *)b == 0x01000000) || ((*(DWORD *)b & 0x00FFFFFF) == 0x00010000))) \ b++; \ if ((b <= e - 4) && *(DWORD *)b == 0x01000000) \ b++; HRESULT CStreamParser::ParseH264AnnexB(Packet *pPacket) { if (!m_pPacketBuffer) { m_pPacketBuffer = InitPacket(pPacket); } m_pPacketBuffer->Append(pPacket); BYTE *start = m_pPacketBuffer->GetData(); BYTE *end = start + m_pPacketBuffer->GetDataSize(); MOVE_TO_H264_START_CODE(start, end); while (start <= end - 4) { BYTE *next = start + 1; MOVE_TO_H264_START_CODE(next, end); // End of buffer reached if (next >= end - 4) { break; } size_t size = next - start; CH264Nalu Nalu; Nalu.SetBuffer(start, (int)size, 0); Packet *p2 = nullptr; while (Nalu.ReadNext()) { Packet *p3 = new Packet(); p3->SetDataSize((int)Nalu.GetDataLength() + 4); // Write size of the NALU (Big Endian) AV_WB32(p3->GetData(), (uint32_t)Nalu.GetDataLength()); memcpy(p3->GetData() + 4, Nalu.GetDataBuffer(), Nalu.GetDataLength()); if (!p2) { p2 = p3; } else { p2->Append(p3); SAFE_DELETE(p3); } } if (!p2) break; p2->StreamId = m_pPacketBuffer->StreamId; p2->bDiscontinuity = m_pPacketBuffer->bDiscontinuity; m_pPacketBuffer->bDiscontinuity = FALSE; p2->bSyncPoint = m_pPacketBuffer->bSyncPoint; m_pPacketBuffer->bSyncPoint = FALSE; p2->rtStart = m_pPacketBuffer->rtStart; m_pPacketBuffer->rtStart = Packet::INVALID_TIME; p2->rtStop = m_pPacketBuffer->rtStop; m_pPacketBuffer->rtStop = Packet::INVALID_TIME; p2->pmt = m_pPacketBuffer->pmt; m_pPacketBuffer->pmt = nullptr; m_queue.Queue(p2); if (pPacket->rtStart != Packet::INVALID_TIME) { m_pPacketBuffer->rtStart = pPacket->rtStart; m_pPacketBuffer->rtStop = pPacket->rtStop; pPacket->rtStart = Packet::INVALID_TIME; } if (pPacket->bDiscontinuity) { m_pPacketBuffer->bDiscontinuity = pPacket->bDiscontinuity; pPacket->bDiscontinuity = FALSE; } if (pPacket->bSyncPoint) { m_pPacketBuffer->bSyncPoint = pPacket->bSyncPoint; pPacket->bSyncPoint = FALSE; } if (m_pPacketBuffer->pmt) { DeleteMediaType(m_pPacketBuffer->pmt); } m_pPacketBuffer->pmt = pPacket->pmt; pPacket->pmt = nullptr; start = next; } if (start > m_pPacketBuffer->GetData()) { m_pPacketBuffer->RemoveHead((int)(start - m_pPacketBuffer->GetData())); } SAFE_DELETE(pPacket); do { pPacket = nullptr; REFERENCE_TIME rtStart = Packet::INVALID_TIME, rtStop = rtStart = Packet::INVALID_TIME; std::deque::iterator it; for (it = m_queue.GetQueue()->begin(); it != m_queue.GetQueue()->end(); ++it) { // Skip the first if (it == m_queue.GetQueue()->begin()) { continue; } Packet *p = *it; BYTE *pData = p->GetData(); if ((pData[4] & 0x1f) == 0x09) { m_bHasAccessUnitDelimiters = true; } if ((pData[4] & 0x1f) == 0x09 || (!m_bHasAccessUnitDelimiters && p->rtStart != Packet::INVALID_TIME)) { pPacket = p; if (p->rtStart == Packet::INVALID_TIME && rtStart != Packet::INVALID_TIME) { p->rtStart = rtStart; p->rtStop = rtStop; } break; } if (rtStart == Packet::INVALID_TIME) { rtStart = p->rtStart; rtStop = p->rtStop; } } if (pPacket) { Packet *p = m_queue.Get(); Packet *p2 = nullptr; while ((p2 = m_queue.Get()) != pPacket) { p->Append(p2); SAFE_DELETE(p2); } // Return m_queue.GetQueue()->push_front(pPacket); Queue(p); } } while (pPacket != nullptr); return S_OK; } HRESULT CStreamParser::ParsePGS(Packet *pPacket) { const uint8_t *buf = pPacket->GetData(); const size_t buf_size = pPacket->GetDataSize(); const uint8_t *buf_end = buf + buf_size; uint8_t segment_type; size_t segment_length; if (buf_size < 3) { DbgLog((LOG_TRACE, 30, L"::ParsePGS(): Way too short PGS packet")); goto done; } m_pgsBuffer.SetSize(0); while ((buf + 3) <= buf_end) { const uint8_t *segment_start = buf; const size_t segment_buf_len = buf_end - buf; segment_type = AV_RB8(buf); segment_length = AV_RB16(buf + 1); if (segment_length > (segment_buf_len - 3)) { DbgLog((LOG_TRACE, 10, "::ParsePGS(): segment_length bigger then input buffer: %d (buffer: %d)", segment_length, segment_buf_len)); segment_length = segment_buf_len - 3; } buf += 3; #ifdef DEBUG_PGS_PARSER DbgLog((LOG_TRACE, 50, L"::ParsePGS(): segment_type: 0x%x, segment_length: %d", segment_type, segment_length)); #endif // Presentation segment if (segment_type == 0x16 && segment_length > 10) { // Segment Layout // 2 bytes width // 2 bytes height // 1 unknown byte // 2 bytes id // 1 byte composition state (0x00 = normal, 0x40 = ACQU_POINT (?), 0x80 = epoch start (new frame), 0xC0 = // epoch continue) 2 unknown bytes 1 byte object number uint8_t objectNumber = buf[10]; // 2 bytes object ref id if (objectNumber == 0) { m_bPGSDropState = FALSE; } else if (segment_length >= 0x13) { // 1 byte window_id // 1 byte object_cropped_flag: 0x80, forced_on_flag = 0x040, 6bit reserved uint8_t forced_flag = buf[14]; m_bPGSDropState = !(forced_flag & 0x40); // 2 bytes x // 2 bytes y // total length = 19 bytes } #ifdef DEBUG_PGS_PARSER DbgLog((LOG_TRACE, 50, L"::ParsePGS(): Presentation Segment! obj.num: %d; state: 0x%x; dropping: %d", objectNumber, buf[7], m_bPGSDropState)); #endif } if (!m_bPGSDropState) { m_pgsBuffer.Append(segment_start, (DWORD)(segment_length + 3)); } buf += segment_length; } if (m_pgsBuffer.GetCount() > 0) { pPacket->SetData(m_pgsBuffer.Ptr(), m_pgsBuffer.GetCount()); } else { delete pPacket; return S_OK; } done: return Queue(pPacket); } HRESULT CStreamParser::ParseMOVText(Packet *pPacket) { size_t avail = pPacket->GetDataSize(); BYTE *ptr = pPacket->GetData(); if (avail > 2) { unsigned size = (ptr[0] << 8) | ptr[1]; if (size <= avail - 2) { pPacket->RemoveHead(2); pPacket->SetDataSize(size); return Queue(pPacket); } } SAFE_DELETE(pPacket); return S_FALSE; } HRESULT CStreamParser::ParseAAC(Packet *pPacket) { BYTE *pData = pPacket->GetData(); GetBitContext gb; init_get_bits(&gb, pData, AAC_ADTS_HEADER_SIZE * 8); // Check if its really ADTS if (get_bits(&gb, 12) == 0xfff) { skip_bits1(&gb); /* id */ skip_bits(&gb, 2); /* layer */ int crc_abs = get_bits1(&gb); /* protection_absent */ pPacket->RemoveHead(AAC_ADTS_HEADER_SIZE + 2 * !crc_abs); } return Queue(pPacket); } static const char *read_srt_ts(const char *buf, int *ts_start, int *ts_end, int *x1, int *y1, int *x2, int *y2) { int i, hs, ms, ss, he, me, se; for (i = 0; i < 2; i++) { /* try to read timestamps in either the first or second line */ int c = sscanf_s(buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d" "%*[ ]X1:%u X2:%u Y1:%u Y2:%u", &hs, &ms, &ss, ts_start, &he, &me, &se, ts_end, x1, x2, y1, y2); buf += strcspn(buf, "\n") + 1; if (c >= 8) { *ts_start = 100 * (ss + 60 * (ms + 60 * hs)) + *ts_start / 10; *ts_end = 100 * (se + 60 * (me + 60 * he)) + *ts_end / 10; return buf; } } return nullptr; } HRESULT CStreamParser::ParseSRT(Packet *pPacket) { int ts_start, ts_end, x1 = -1, y1 = -1, x2 = -1, y2 = -1; const char *ptr = (const char *)pPacket->GetData(); const char *end = ptr + pPacket->GetDataSize(); if (pPacket->GetDataSize() == 0) return S_FALSE; while (ptr && end > ptr && *ptr) { // Read the embedded timestamp and find the start of the subtitle ptr = read_srt_ts(ptr, &ts_start, &ts_end, &x1, &y1, &x2, &y2); if (ptr) { const char *linestart = ptr; while (end > ptr) { if (*ptr != ' ' && *ptr != '\n' && *ptr != '\r') { ptr += strcspn(ptr, "\n") + 1; } else { if (*ptr++ == '\n') break; } } size_t size = ptr - linestart; Packet *p = new Packet(); p->pmt = pPacket->pmt; pPacket->pmt = nullptr; p->bDiscontinuity = pPacket->bDiscontinuity; p->bSyncPoint = pPacket->bSyncPoint; p->StreamId = pPacket->StreamId; p->rtStart = pPacket->rtStart; p->rtStop = pPacket->rtStop; p->AppendData(linestart, (int)size); Queue(p); } } SAFE_DELETE(pPacket); return S_FALSE; } HRESULT CStreamParser::ParsePlanarPCM(Packet *pPacket) { CMediaType mt = m_pPin->GetActiveMediaType(); WORD nChannels = 0, nBPS = 0, nBlockAlign = 0; audioFormatTypeHandler(mt.Format(), mt.FormatType(), nullptr, &nChannels, &nBPS, &nBlockAlign, nullptr, nullptr); // Mono needs no special handling if (nChannels == 1) return Queue(pPacket); Packet *out = new Packet(); out->CopyProperties(pPacket); out->SetDataSize(pPacket->GetDataSize()); int nBytesPerChannel = nBPS / 8; int nAudioBlocks = pPacket->GetDataSize() / nChannels; BYTE *out_data = out->GetData(); const BYTE *in_data = pPacket->GetData(); for (int i = 0; i < nAudioBlocks; i += nBytesPerChannel) { // interleave the channels into audio blocks for (int c = 0; c < nChannels; c++) { memcpy(out_data + (c * nBytesPerChannel), in_data + (nAudioBlocks * c), nBytesPerChannel); } // Skip to the next output block out_data += nChannels * nBytesPerChannel; // skip to the next input sample in_data += nBytesPerChannel; } return Queue(out); } ================================================ FILE: demuxer/LAVSplitter/StreamParser.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Initial design and concept by Gabest and the MPC-HC Team, copyright under GPLv2 */ #pragma once #include "PacketQueue.h" #include "growarray.h" class CLAVOutputPin; class CStreamParser { public: CStreamParser(CLAVOutputPin *pPin, const char *szContainer); ~CStreamParser(); HRESULT Parse(const GUID &gSubtype, Packet *pPacket); HRESULT Flush(); private: HRESULT ParseH264AnnexB(Packet *pPacket); HRESULT ParsePGS(Packet *pPacket); HRESULT ParseMOVText(Packet *pPacket); HRESULT ParseAAC(Packet *pPacket); HRESULT ParseSRT(Packet *pPacket); HRESULT ParsePlanarPCM(Packet *pPacket); HRESULT Queue(Packet *pPacket) const; private: CLAVOutputPin *const m_pPin = nullptr; std::string m_strContainer; GUID m_gSubtype = GUID_NULL; Packet *m_pPacketBuffer = nullptr; BOOL m_bPGSDropState = FALSE; GrowableArray m_pgsBuffer; CPacketQueue m_queue; bool m_bHasAccessUnitDelimiters = false; }; ================================================ FILE: demuxer/LAVSplitter/dllmain.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Based on the SampleParser Template by GDCL // -------------------------------------------------------------------------------- // Copyright (c) GDCL 2004. All Rights Reserved. // You are free to re-use this as the basis for your own filter development, // provided you retain this copyright notice in the source. // http://www.gdcl.co.uk // -------------------------------------------------------------------------------- #include "stdafx.h" // Initialize the GUIDs #include #include #include "LAVSplitter.h" #include "moreuuids.h" #include "registry.h" #include "IGraphRebuildDelegate.h" #include "IMediaSideDataFFmpeg.h" #include "ILAVDynamicAllocator.h" // The GUID we use to register the splitter media types DEFINE_GUID(MEDIATYPE_LAVSplitter, 0x9c53931c, 0x7d5a, 0x4a75, 0xb2, 0x6f, 0x4e, 0x51, 0x65, 0x4d, 0xb2, 0xc0); // --- COM factory table and registration code -------------- const AMOVIESETUP_MEDIATYPE sudMediaTypes[] = { {&MEDIATYPE_Stream, &MEDIASUBTYPE_NULL}, }; const AMOVIESETUP_PIN sudOutputPins[] = {{ L"Output", // pin name FALSE, // is rendered? TRUE, // is output? FALSE, // zero instances allowed? TRUE, // many instances allowed? &CLSID_NULL, // connects to filter (for bridge pins) nullptr, // connects to pin (for bridge pins) 0, // count of registered media types nullptr // list of registered media types }, { L"Input", // pin name FALSE, // is rendered? FALSE, // is output? FALSE, // zero instances allowed? FALSE, // many instances allowed? &CLSID_NULL, // connects to filter (for bridge pins) nullptr, // connects to pin (for bridge pins) 1, // count of registered media types &sudMediaTypes[0] // list of registered media types }}; const AMOVIESETUP_FILTER sudFilterReg = {&__uuidof(CLAVSplitter), // filter clsid L"LAV Splitter", // filter name MERIT_PREFERRED + 4, // merit 2, // count of registered pins sudOutputPins, // list of pins to register CLSID_LegacyAmFilterCategory}; const AMOVIESETUP_FILTER sudFilterRegSource = {&__uuidof(CLAVSplitterSource), // filter clsid L"LAV Splitter Source", // filter name MERIT_PREFERRED + 4, // merit 1, // count of registered pins sudOutputPins, // list of pins to register CLSID_LegacyAmFilterCategory}; // --- COM factory table and registration code -------------- // DirectShow base class COM factory requires this table, // declaring all the COM objects in this DLL CFactoryTemplate g_Templates[] = { // one entry for each CoCreate-able object {sudFilterReg.strName, sudFilterReg.clsID, CreateInstance, nullptr, &sudFilterReg}, {sudFilterRegSource.strName, sudFilterRegSource.clsID, CreateInstance, nullptr, &sudFilterRegSource}, // This entry is for the property page. {L"LAV Splitter Properties", &CLSID_LAVSplitterSettingsProp, CreateInstance, nullptr, nullptr}, {L"LAV Splitter Input Formats", &CLSID_LAVSplitterFormatsProp, CreateInstance, nullptr, nullptr}}; int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]); // self-registration entrypoint STDAPI DllRegisterServer() { std::list chkbytes; // BluRay chkbytes.clear(); chkbytes.push_back(L"0,4,,494E4458"); // INDX (index.bdmv) chkbytes.push_back(L"0,4,,4D4F424A"); // MOBJ (MovieObject.bdmv) chkbytes.push_back(L"0,4,,4D504C53"); // MPLS RegisterSourceFilter(__uuidof(CLAVSplitterSource), MEDIASUBTYPE_LAVBluRay, chkbytes, nullptr); // base classes will handle registration using the factory template table return AMovieDllRegisterServer2(true); } STDAPI DllUnregisterServer() { UnRegisterSourceFilter(MEDIASUBTYPE_LAVBluRay); // base classes will handle de-registration using the factory template table return AMovieDllRegisterServer2(false); } // if we declare the correct C runtime entrypoint and then forward it to the DShow base // classes we will be sure that both the C/C++ runtimes and the base classes are initialized // correctly extern "C" BOOL WINAPI DllEntryPoint(HINSTANCE, ULONG, LPVOID); BOOL WINAPI DllMain(HANDLE hDllHandle, DWORD dwReason, LPVOID lpReserved) { return DllEntryPoint(reinterpret_cast(hDllHandle), dwReason, lpReserved); } void CALLBACK OpenConfiguration(HWND hwnd, HINSTANCE hinst, LPSTR lpszCmdLine, int nCmdShow) { HRESULT hr = S_OK; CUnknown *pInstance = CreateInstance(nullptr, &hr); IBaseFilter *pFilter = nullptr; pInstance->NonDelegatingQueryInterface(IID_IBaseFilter, (void **)&pFilter); if (pFilter) { pFilter->AddRef(); CBaseDSPropPage::ShowPropPageDialog(pFilter); } delete pInstance; } ================================================ FILE: demuxer/LAVSplitter/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by LAVSplitter.rc // #define IDD_PROPPAGE_LAVFSETTINGS 9 #define IDD_PROPPAGE_FORMATS 10 #define IDS_PAGE_TITLE 101 #define IDS_SUBMODE_NO_SUBS 102 #define IDI_ICON1 103 #define IDS_SUBMODE_FORCED_SUBS 104 #define IDS_SUBMODE_DEFAULT 105 #define IDS_SUBMODE_ADVANCED 106 #define IDS_INPUT_FORMATS 107 #define IDC_LBL_PREF_LANG 1001 #define IDC_PREF_LANG 1002 #define IDC_LBL_PREF_LANG_AUDIO 1003 #define IDC_PREF_LANG_SUBS 1004 #define IDC_LBL_PREF_LANG_SUBS 1005 #define IDC_SUBTITLE_MODE 1006 #define IDC_LBL_SUBMODE 1007 #define IDC_VC1TIMESTAMP 1009 #define IDC_SUBSTREAMS 1010 #define IDC_DEMUXER_SETTINGS 1011 #define IDC_SPLITTER_FOOTER 1012 #define IDC_FORMATS 1016 #define IDC_LBL_INPUT 1017 #define IDC_CUR_INPUT 1018 #define IDC_LBL_FORMATS 1019 #define IDC_BD_SUBS 1020 #define IDC_BD_SEPARATE_FORCED_SUBS 1021 #define IDC_BD_ONLY_FORCED_SUBS 1022 #define IDC_STREAM_SWITCH_REMOVE_AUDIO 1024 #define IDC_SUBTITLE_NOTE 1025 #define IDC_IMPAIRED_AUDIO 1026 #define IDC_QUEUE_SETTINGS 1027 #define IDC_LBL_QUEUE_MEM 1028 #define IDC_QUEUE_MEM 1029 #define IDC_QUEUE_MEM_SPIN 1030 #define IDC_TRAYICON 1031 #define IDC_SELECT_AUDIO_QUALITY 1032 #define IDC_FMT_SETTINGS 1033 #define IDC_MKV_EXTERNAL 1034 #define IDC_NETWORK_SETTINGS 1035 #define IDC_LBL_STREAM_BUFFER 1036 #define IDC_STREAM_ANADUR 1037 #define IDC_STREAM_ANADUR_SPIN 1038 #define IDC_LBL_QUEUE_PACKETS 1039 #define IDC_QUEUE_PACKETS 1040 #define IDC_QUEUE_PACKETS_SPIN 1041 #define IDC_STREAM_SWITCH_RESELECT_SUBS 1042 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 108 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1043 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: demuxer/LAVSplitter/stdafx.cpp ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Pre-compiled header #include "stdafx.h" ================================================ FILE: demuxer/LAVSplitter/stdafx.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // pre-compiled header #pragma once // Support for Version 6.0 styles #pragma comment( \ linker, \ "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #include "common_defines.h" // include headers #include #include #pragma warning(push) #pragma warning(disable : 4244) extern "C" { #define __STDC_CONSTANT_MACROS #include "libavformat/avformat.h" #include "libbluray/bluray.h" #include "libavutil/intreadwrite.h" } #pragma warning(pop) #include "streams.h" #include "DShowUtil.h" #include "resource.h" ================================================ FILE: include/IBitRateInfo.h ================================================ /* * (C) 2003-2006 Gabest * (C) 2006-2013 MPC-HC Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ #pragma once interface __declspec(uuid("EB2CD9E6-BA08-4acb-AA0F-3D8D0DD521CA")) IBitRateInfo : public IUnknown { STDMETHOD_(DWORD, GetCurrentBitRate)() PURE; STDMETHOD_(DWORD, GetAverageBitRate)() PURE; }; ================================================ FILE: include/IBufferInfo.h ================================================ /* * $Id: IBufferInfo.h 2786 2010-12-17 16:42:55Z XhmikosR $ * * (C) 2003-2006 Gabest * (C) 2006-2010 see AUTHORS * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #pragma once interface __declspec(uuid("46070104-1318-4A82-8822-E99AB7CD15C1")) IBufferInfo : public IUnknown { // Number of Buffers STDMETHOD_(int, GetCount()) = 0; // Get Info about Buffer "i" (0-based index up to count) // samples: number of frames in the buffer // size: total size in bytes of the buffer STDMETHOD(GetStatus(int i, int &samples, int &size)) = 0; // Get priority of the demuxing thread STDMETHOD_(DWORD, GetPriority()) = 0; }; ================================================ FILE: include/ID3DVideoMemoryConfiguration.h ================================================ // ----------------------------------------------------------------- // ID3DVideoMemoryConfiguration interface and data structure definitions // ----------------------------------------------------------------- #pragma once // ----------------------------------------------------------------- // Control D3D11 Hardware Decoding between decoder and renderer // ----------------------------------------------------------------- // A video renderer can implement this interface on its input pin // to signal to a decoder that its capable of accepting D3D11 texture // samples directly, without copying to system memory. // // The decoder will create the D3D11 device and a mutex to protect it, // and share it with the renderer in this interface. // // To facilitate dynamic switching of the adapter used for decoding, the // renderer should disconnect the decoder and re-connect it. At that // point the decoder should query GetD3D11AdapterIndex() again and // create a new decoder on the new device, as appropriate. interface __declspec(uuid("2BB66002-46B7-4F13-9036-7053328742BE")) ID3D11DecoderConfiguration : public IUnknown { // Set the surface format the decoder is going to send. // If the renderer is not ready to accept this format, an error will be returned. virtual HRESULT STDMETHODCALLTYPE ActivateD3D11Decoding(ID3D11Device * pDevice, ID3D11DeviceContext * pContext, HANDLE hMutex, UINT nFlags) = 0; // Get the currently preferred D3D11 adapter index (to be used with IDXGIFactory1::EnumAdapters1) virtual UINT STDMETHODCALLTYPE GetD3D11AdapterIndex() = 0; }; // ----------------------------------------------------------------- // Media Sample to hold a D3D11 texture // ----------------------------------------------------------------- // D3D11 textures used for decoding are typically array-textures, // a single ID3D11Texture2D object containing an array of textures // individually addressable by the ArraySlice index. // // The texture lifetime is bound to the media samples lifetime. The // media sample can only be released when the texture is no longer in // use, otherwise the texture will be re-used by the decoder. // // The texture is AddRef'ed when retrieved through this interface, // and should be Released when no longer needed. interface __declspec(uuid("BC8753F5-0AC8-4806-8E5F-A12B2AFE153E")) IMediaSampleD3D11 : public IUnknown { // Get the D3D11 texture for the specified view. // 2D images with only one view always use view 0. For 3D, view 0 specifies the base view, view 1 the extension // view. virtual HRESULT STDMETHODCALLTYPE GetD3D11Texture(int nView, ID3D11Texture2D **ppTexture, UINT *pArraySlice) = 0; }; ================================================ FILE: include/IDSMResourceBag.h ================================================ /* * Copyright (C) 2003-2006 Gabest * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once interface __declspec(uuid("EBAFBCBE-BDE0-489A-9789-05D5692E3A93")) IDSMResourceBag : public IUnknown { STDMETHOD_(DWORD, ResGetCount)() PURE; STDMETHOD(ResGet)(DWORD iIndex, BSTR * ppName, BSTR * ppDesc, BSTR * ppMime, BYTE * *ppData, DWORD * pDataLen, DWORD_PTR * pTag) PURE; STDMETHOD(ResSet)(DWORD iIndex, LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, const BYTE *pData, DWORD len, DWORD_PTR tag) PURE; STDMETHOD(ResAppend)(LPCWSTR pName, LPCWSTR pDesc, LPCWSTR pMime, BYTE * pData, DWORD len, DWORD_PTR tag) PURE; STDMETHOD(ResRemoveAt)(DWORD iIndex) PURE; STDMETHOD(ResRemoveAll)(DWORD_PTR tag) PURE; }; ================================================ FILE: include/IGraphRebuildDelegate.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // {17989414-C927-4D73-AB6C-19DF37602AC4} DEFINE_GUID(IID_IGraphRebuildDelegate, 0x17989414, 0xc927, 0x4d73, 0xab, 0x6c, 0x19, 0xdf, 0x37, 0x60, 0x2a, 0xc4); interface __declspec(uuid("17989414-C927-4D73-AB6C-19DF37602AC4")) IGraphRebuildDelegate : public IUnknown { // Called by the splitter to let the player know that a certain pin needs to be rebuild. // // This function is called on any stream or title changes that would cause the content of the pin to change. // The Splitter will stop the graph prior to this call, and it will return the graph to its previous state // afterwards. // // When this function is called, the pin will already have the new media types set, so the usual functions to query // the media types can be used. EnmuMediaTypes is OK (or any wrappers of this in the base classes), // ConnectionMediaType is not OK, for obvious reasons. // // Following return values are supported: // S_OK - The player took complete control over the rebuild, the splitter will do no further actions regarding // the pin S_FALSE - The player may or may not have changed the pin, and the splitter is instructed to send a media // type with the next packet. E_FAIL - The player failed, and the splitter should try to rebuild the pin STDMETHOD(RebuildPin)(IFilterGraph * pGraph, IPin * pPin) = 0; }; ================================================ FILE: include/IKeyFrameInfo.h ================================================ /* * Copyright (C) 2003-2006 Gabest * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once interface __declspec(uuid("01A5BBD3-FE71-487C-A2EC-F585918A8724")) IKeyFrameInfo : public IUnknown { // Get the number of (known) keyframes in the file STDMETHOD(GetKeyFrameCount)(UINT & nKFs) = 0; // returns S_FALSE when every frame is a keyframe // Get the times of the key frames, if available. // // pFormat: GUID of the time format (see http://msdn.microsoft.com/en-us/library/dd407205(v=vs.85).aspx, usually // TIME_FORMAT_MEDIA_TIME) pKFs: Caller allocated memory for the timestamps of the keyframes (should be // sizeof(REFERENCE_TIME) * nKFs at least!) nKF: Number of keyframes requested/returned - no more then nKFs key // frames will be returned. STDMETHOD(GetKeyFrames)(const GUID *pFormat, REFERENCE_TIME *pKFs, UINT &nKFs /* in, out*/) = 0; }; ================================================ FILE: include/ILAVDynamicAllocator.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // {8FBB906B-D1DB-4528-9498-563241CCD43D} DEFINE_GUID(IID_ILAVDynamicAllocator, 0x8fbb906b, 0xd1db, 0x4528, 0x94, 0x98, 0x56, 0x32, 0x41, 0xcc, 0xd4, 0x3d); interface __declspec(uuid("8FBB906B-D1DB-4528-9498-563241CCD43D")) ILAVDynamicAllocator : public IUnknown { // Query wether this allocator is using dynamic allocation of samples and will not run out of samples STDMETHOD_(BOOL, IsDynamicAllocator)() PURE; }; ================================================ FILE: include/IMediaSample3D.h ================================================ // ----------------------------------------------------------------- // IMediaSample3D interface and data structure definitions // ----------------------------------------------------------------- #pragma once interface __declspec(uuid("E92D790E-BF54-43C4-B394-8CA0A41BF9EC")) IMediaSample3D : public IMediaSample2 { STDMETHOD(Enable3D)() = 0; STDMETHOD(GetPointer3D)(BYTE **ppBuffer) = 0; }; ================================================ FILE: include/IMediaSideData.h ================================================ // ----------------------------------------------------------------- // IMediaSideData interface and data structure definitions // ----------------------------------------------------------------- #pragma once #include // ----------------------------------------------------------------- // Interface to exchange binary side data // ----------------------------------------------------------------- // This interface should be implemented in IMediaSample objects and accessed through IUnknown // It allows binary side data to be attached to the media samples and delivered with them // Restrictions: Only one side data per type can be attached interface __declspec(uuid("F940AE7F-48EB-4377-806C-8FC48CAB2292")) IMediaSideData : public IUnknown { // Set the side data identified by guidType to the data provided // The provided data will be copied and stored internally STDMETHOD(SetSideData)(GUID guidType, const BYTE *pData, size_t size) PURE; // Get the side data identified by guidType // The caller receives pointers to the internal data, and the pointers shall stay // valid for the lifetime of the object STDMETHOD(GetSideData)(GUID guidType, const BYTE **pData, size_t *pSize) PURE; }; // ----------------------------------------------------------------- // High-Dynamic-Range (HDR) Side Data // ----------------------------------------------------------------- // {53820DBC-A7B8-49C4-B17B-E511591A790C} DEFINE_GUID(IID_MediaSideDataHDR, 0x53820dbc, 0xa7b8, 0x49c4, 0xb1, 0x7b, 0xe5, 0x11, 0x59, 0x1a, 0x79, 0xc); #pragma pack(push, 1) struct MediaSideDataHDR { // coordinates of the primaries, in G-B-R order double display_primaries_x[3]; double display_primaries_y[3]; // white point double white_point_x; double white_point_y; // luminance double max_display_mastering_luminance; double min_display_mastering_luminance; }; #pragma pack(pop) // {ED6AE576-7CBE-41A6-9DC3-07C35DC13EF9} DEFINE_GUID(IID_MediaSideDataHDRContentLightLevel, 0xed6ae576, 0x7cbe, 0x41a6, 0x9d, 0xc3, 0x7, 0xc3, 0x5d, 0xc1, 0x3e, 0xf9); #pragma pack(push, 1) struct MediaSideDataHDRContentLightLevel { // maximum content light level (cd/m2) unsigned int MaxCLL; // maximum frame average light level (cd/m2) unsigned int MaxFALL; }; #pragma pack(pop) // {183ED511-8910-4262-88F6-4946BC799C84} DEFINE_GUID(IID_MediaSideDataHDR10Plus, 0x183ed511, 0x8910, 0x4262, 0x88, 0xf6, 0x49, 0x46, 0xbc, 0x79, 0x9c, 0x84); #pragma pack(push, 1) // HDR10+ metadata according to SMPTE 2094-40 // Refer to the specification for the meaning of the fields // // All pixel values are kept as-is, rational values are normalized as double-precision floating point struct MediaSideDataHDR10Plus { // number of windows (1-3) unsigned int num_windows; // processing windows struct { unsigned int upper_left_corner_x; unsigned int upper_left_corner_y; unsigned int lower_right_corner_x; unsigned int lower_right_corner_y; unsigned int center_of_ellipse_x; unsigned int center_of_ellipse_y; unsigned int rotation_angle; unsigned int semimajor_axis_internal_ellipse; unsigned int semimajor_axis_external_ellipse; unsigned int semiminor_axis_external_ellipse; unsigned int overlap_process_option; double maxscl[3]; double average_maxrgb; unsigned int num_distribution_maxrgb_percentiles; struct { unsigned int percentage; double percentile; } distribution_maxrgb_percentiles[15]; double fraction_bright_pixels; unsigned int tone_mapping_flag; double knee_point_x; double knee_point_y; unsigned int num_bezier_curve_anchors; double bezier_curve_anchors[15]; unsigned int color_saturation_mapping_flag; double color_saturation_weight; } windows[3]; double targeted_system_display_maximum_luminance; unsigned int targeted_system_display_actual_peak_luminance_flag; unsigned int num_rows_targeted_system_display_actual_peak_luminance; unsigned int num_cols_targeted_system_display_actual_peak_luminance; double targeted_system_display_actual_peak_luminance[25][25]; unsigned int mastering_display_actual_peak_luminance_flag; unsigned int num_rows_mastering_display_actual_peak_luminance; unsigned int num_cols_mastering_display_actual_peak_luminance; double mastering_display_actual_peak_luminance[25][25]; }; #pragma pack(pop) // {BAE40E6C-5B93-4170-90CC-5D5F02A29638} DEFINE_GUID(IID_MediaSideDataDOVIRPU, 0xbae40e6c, 0x5b93, 0x4170, 0x90, 0xcc, 0x5d, 0x5f, 0x2, 0xa2, 0x96, 0x38); // {277EE779-13F4-434E-BDEC-3D6F8C0E15D2} DEFINE_GUID([[deprecated]] IID_MediaSideDataDOVIMetadata, 0x277ee779, 0x13f4, 0x434e, 0xbd, 0xec, 0x3d, 0x6f, 0x8c, 0xe, 0x15, 0xd2); // {F1949F1C-7474-4F0F-B110-FB734C08851D} DEFINE_GUID(IID_MediaSideDataDOVIMetadataV2, 0xf1949f1c, 0x7474, 0x4f0f, 0xb1, 0x10, 0xfb, 0x73, 0x4c, 0x8, 0x85, 0x1d); #pragma pack(push, 1) // Dolby Vision metadata // Refer to the specification for the meaning of the fields // Note: This structure may be extended towards the end if needed, do not rely on a fixed size, but rather a minimum size // Version History // - Version 1, Header/Mapping/ColorMetadata // - Version 2, Extensions (ensure the V2 metadata GUID is used above for this to be valid) struct MediaSideDataDOVIMetadata { struct { uint8_t rpu_type; uint16_t rpu_format; uint8_t vdr_rpu_profile; uint8_t vdr_rpu_level; uint8_t chroma_resampling_explicit_filter_flag; uint8_t coef_data_type; /* informative, lavc always converts to fixed */ uint8_t coef_log2_denom; uint8_t vdr_rpu_normalized_idc; uint8_t bl_video_full_range_flag; uint8_t bl_bit_depth; /* [8, 16] */ uint8_t el_bit_depth; /* [8, 16] */ uint8_t vdr_bit_depth; /* [8, 16] */ uint8_t spatial_resampling_filter_flag; uint8_t el_spatial_resampling_filter_flag; uint8_t disable_residual_flag; } Header; struct { uint8_t vdr_rpu_id; uint8_t mapping_color_space; uint8_t mapping_chroma_format_idc; struct { #define LAV_DOVI_MAX_PIECES 8 uint8_t num_pivots; /* [2, 9] */ uint16_t pivots[LAV_DOVI_MAX_PIECES + 1]; /* sorted ascending */ uint8_t mapping_idc[LAV_DOVI_MAX_PIECES]; /* 0 polynomial, 1 mmr */ /* polynomial */ uint8_t poly_order[LAV_DOVI_MAX_PIECES]; /* [1, 2] */ int64_t poly_coef[LAV_DOVI_MAX_PIECES][3]; /* x^0, x^1, x^2 */ /* mmr */ uint8_t mmr_order[LAV_DOVI_MAX_PIECES]; /* [1, 3] */ int64_t mmr_constant[LAV_DOVI_MAX_PIECES]; int64_t mmr_coef[LAV_DOVI_MAX_PIECES][3 /* order - 1 */][7]; } curves[3]; /* per component */ /* Non-linear inverse quantization */ uint8_t nlq_method_idc; // -1 none, 0 linear dz uint32_t num_x_partitions; uint32_t num_y_partitions; struct { uint16_t nlq_offset; uint64_t vdr_in_max; /* linear dz */ uint64_t linear_deadzone_slope; uint64_t linear_deadzone_threshold; } nlq[3]; /* per component */ } Mapping; struct { uint8_t dm_metadata_id; uint8_t scene_refresh_flag; /** * Coefficients of the custom Dolby Vision IPT-PQ matrices. These are to be * used instead of the matrices indicated by the frame's colorspace tags. * The output of rgb_to_lms_matrix is to be fed into a BT.2020 LMS->RGB * matrix based on a Hunt-Pointer-Estevez transform, but without any * crosstalk. (See the definition of the ICtCp colorspace for more * information.) */ double ycc_to_rgb_matrix[9]; /* before PQ linearization */ double ycc_to_rgb_offset[3]; /* input offset of neutral value */ double rgb_to_lms_matrix[9]; /* after PQ linearization */ /** * Extra signal metadata (see Dolby patents for more info). */ uint16_t signal_eotf; uint16_t signal_eotf_param0; uint16_t signal_eotf_param1; uint32_t signal_eotf_param2; uint8_t signal_bit_depth; uint8_t signal_color_space; uint8_t signal_chroma_format; uint8_t signal_full_range_flag; /* [0, 3] */ uint16_t source_min_pq; uint16_t source_max_pq; uint16_t source_diagonal; } ColorMetadata; #define LAV_DOVI_MAX_EXTENSIONS 32 struct { uint8_t level; union { struct { /* L1 Per-frame brightness metadata */ uint16_t min_pq; uint16_t max_pq; uint16_t avg_pq; } Level1; struct { uint16_t target_max_pq; uint16_t trim_slope; uint16_t trim_offset; uint16_t trim_power; uint16_t trim_chroma_weight; uint16_t trim_saturation_gain; int16_t ms_weight; } Level2; struct { uint16_t min_pq_offset; uint16_t max_pq_offset; uint16_t avg_pq_offset; } Level3; struct { uint16_t anchor_pq; uint16_t anchor_power; } Level4; struct { /* Active area definition */ uint16_t left_offset; uint16_t right_offset; uint16_t top_offset; uint16_t bottom_offset; } Level5; struct { /* Static HDR10 metadata */ uint16_t max_luminance; uint16_t min_luminance; uint16_t max_cll; uint16_t max_fall; } Level6; /* level 7 is currently unused */ struct { /* Extended version of level 2 */ uint8_t target_display_index; uint16_t trim_slope; uint16_t trim_offset; uint16_t trim_power; uint16_t trim_chroma_weight; uint16_t trim_saturation_gain; uint16_t ms_weight; uint16_t target_mid_contrast; uint16_t clip_trim; uint8_t saturation_vector_field[6]; uint8_t hue_vector_field[6]; } Level8; struct { /* Source display characteristics */ uint8_t source_primary_index; double white_point_x; double white_point_y; /* primaries are in R-G-B order */ double display_primaries_x[3]; double display_primaries_y[3]; } Level9; struct { /* Target display characteristics */ uint8_t target_display_index; uint16_t target_max_pq; uint16_t target_min_pq; uint8_t target_primary_index; double white_point_x; double white_point_y; /* primaries are in R-G-B order */ double display_primaries_x[3]; double display_primaries_y[3]; } Level10; struct { uint8_t content_type; uint8_t whitepoint; uint8_t reference_mode_flag; } Level11; struct { /* DMv2 info block, always present in samples with DMv2 metadata */ uint8_t dm_mode; uint8_t dm_version_index; } Level254; uint8_t Reserved[128]; /* reserve space for a fixed size of the extension block */ }; } Extensions[LAV_DOVI_MAX_EXTENSIONS]; }; #pragma pack(pop) // ----------------------------------------------------------------- // 3D Plane Offset Side Data // ----------------------------------------------------------------- // {F169B76C-75A3-49E6-A23A-14983EBF4370} DEFINE_GUID(IID_MediaSideData3DOffset, 0xf169b76c, 0x75a3, 0x49e6, 0xa2, 0x3a, 0x14, 0x98, 0x3e, 0xbf, 0x43, 0x70); #pragma pack(push, 1) struct MediaSideData3DOffset { // Number of valid offsets (up to 32) int offset_count; // Offset Value, can be positive or negative // positive values offset closer to the viewer (move right on the left view, left on the right view) // negative values offset further away from the viewer (move left on the left view, right on the right view) int offset[32]; }; #pragma pack(pop) // ----------------------------------------------------------------- // EIA-608/708 Closed Caption Data // ----------------------------------------------------------------- // {40FEFD7F-85DD-4335-A804-8A33B0BF7B81} DEFINE_GUID(IID_MediaSideDataEIA608CC, 0x40fefd7f, 0x85dd, 0x4335, 0xa8, 0x4, 0x8a, 0x33, 0xb0, 0xbf, 0x7b, 0x81); // There is no struct definition. The data is supplied as a list of 3 byte CC data packets (control byte + cc_data1/2) // ----------------------------------------------------------------- // Media Control Flags // ----------------------------------------------------------------- // {B5411CE3-3B21-4FD6-80A8-CE682969F795} DEFINE_GUID(IID_MediaSideDataControlFlags, 0xb5411ce3, 0x3b21, 0x4fd6, 0x80, 0xa8, 0xce, 0x68, 0x29, 0x69, 0xf7, 0x95); // No struct definition, just a single DWORD for additional flags enum MediaSideDataControlFlags { MediaSideDataControlFlags_EndOfSequence = (1 << 0), }; ================================================ FILE: include/IPinSegmentEx.h ================================================ #pragma once // ----------------------------------------------------------------- // IPin Segmenting Extension // ----------------------------------------------------------------- // This extension allows upstream filters to cleanly terminate segments, // indicating to downstream components that any data should be flushed // to the renderer. // This call should be followed by a call to IPin::NewSegment to start a // new segment afterwards. interface __declspec(uuid("8B81E022-52C7-4B89-9F11-ACFD063AABB4")) IPinSegmentEx : public IUnknown { virtual HRESULT STDMETHODCALLTYPE EndOfSegment(void) = 0; }; ================================================ FILE: include/ISpecifyPropertyPages2.h ================================================ /* * (C) 2003-2006 Gabest * (C) 2006-2010 MPC-HC Authors * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #pragma once #include interface __declspec(uuid("03481710-D73E-4674-839F-03EDE2D60ED8")) ISpecifyPropertyPages2 : public ISpecifyPropertyPages { STDMETHOD(CreatePage)(const GUID &guid, IPropertyPage **ppPage) = 0; }; ================================================ FILE: include/IStreamSourceControl.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // NOTICE: This interface is still experimental and may change in the future. Do NOT use it yet unless you absolutely // know what you are doing. // Interface for high-level streaming source filters // The source can implement proper seeking and duration retrieval based on its underlying protocol. // This interface should be exposed on the output pin or the filter itself of the streaming source, similar to the // IAsyncReader interface // {C0BE9565-4C05-4644-9492-57547A4048DC} DEFINE_GUID(IID_IStreamSourceControl, 0xc0be9565, 0x4c05, 0x4644, 0x94, 0x92, 0x57, 0x54, 0x7a, 0x40, 0x48, 0xdc); interface __declspec(uuid("C0BE9565-4C05-4644-9492-57547A4048DC")) IStreamSourceControl : public IUnknown { // Get the duration of the stream being played. // Duration is in DirectShow reference time, 100ns units. STDMETHOD(GetStreamDuration)(REFERENCE_TIME * prtDuration) PURE; // Seek the stream to a specified time // // Position is in DirectShow reference time, 100ns units. // // If the source returns a failure code, the demuxer will do byte-based seeking itself (ie. when the stream supports // this) On success, it'll re-open the stream and start reading from the start (byte position 0). STDMETHOD(SeekStream)(REFERENCE_TIME rtPosition) PURE; }; ================================================ FILE: include/ITrackInfo.h ================================================ /* * Copyright (C) 2003-2006 Gabest * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once typedef enum TrackType { TypeVideo = 1, TypeAudio = 2, TypeComplex = 3, TypeLogo = 0x10, TypeSubtitle = 0x11, TypeControl = 0x20 } TrackType; #pragma pack(push, 1) struct TrackElement { WORD Size; // Size of this structure BYTE Type; // See TrackType BOOL FlagDefault; // Set if the track is the default for its TrackType. BOOL FlagForced; // Set if that track MUST be used during playback. BOOL FlagLacing; // Set if the track may contain blocks using lacing. UINT MinCache; // The minimum number of frames a player should be able to cache during playback. UINT MaxCache; // The maximum cache size required to store referenced frames in and the current frame. 0 means no // cache is needed. CHAR Language[4]; // Specifies the language of the track, in the ISO-639-2 form. (end with '\0') }; struct TrackExtendedInfoVideo { WORD Size; // Size of this structure BOOL Interlaced; // Set if the video is interlaced. UINT PixelWidth; // Width of the encoded video frames in pixels. UINT PixelHeight; // Height of the encoded video frames in pixels. UINT DisplayWidth; // Width of the video frames to display. UINT DisplayHeight; // Height of the video frames to display. BYTE DisplayUnit; // Type of the unit for DisplayWidth/Height (0: pixels, 1: centimeters, 2: inches). BYTE AspectRatioType; // Specify the possible modifications to the aspect ratio (0: free resizing, 1: keep aspect // ratio, 2: fixed). }; struct TrackExtendedInfoAudio { WORD Size; // Size of this structure FLOAT SamplingFreq; // Sampling frequency in Hz. FLOAT OutputSamplingFrequency; // Real output sampling frequency in Hz (used for SBR techniques). UINT Channels; // Numbers of channels in the track. UINT BitDepth; // Bits per sample, mostly used for PCM. }; #pragma pack(pop) interface __declspec(uuid("03E98D51-DDE7-43aa-B70C-42EF84A3A23D")) ITrackInfo : public IUnknown { STDMETHOD_(UINT, GetTrackCount)() = 0; // \param aTrackIdx the track index (from 0 to GetTrackCount()-1) STDMETHOD_(BOOL, GetTrackInfo)(UINT aTrackIdx, struct TrackElement * pStructureToFill) = 0; // Get an extended information struct relative to the track type STDMETHOD_(BOOL, GetTrackExtendedInfo)(UINT aTrackIdx, void *pStructureToFill) = 0; STDMETHOD_(BSTR, GetTrackCodecID)(UINT aTrackIdx) = 0; STDMETHOD_(BSTR, GetTrackName)(UINT aTrackIdx) = 0; STDMETHOD_(BSTR, GetTrackCodecName)(UINT aTrackIdx) = 0; STDMETHOD_(BSTR, GetTrackCodecInfoURL)(UINT aTrackIdx) = 0; STDMETHOD_(BSTR, GetTrackCodecDownloadURL)(UINT aTrackIdx) = 0; }; ================================================ FILE: include/IURLSourceFilterLAV.h ================================================ /* * Copyright (C) 2024 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once interface __declspec(uuid("C8FF17F9-5365-4F32-8AD5-6C550342C2F7")) IURLSourceFilterLAV : public IUnknown { // Load a URL with the specified user agent and referrer // UserAgent and Referrer are optional, and either, both or none can be specified STDMETHOD(LoadURL)(LPCOLESTR pszURL, LPCOLESTR pszUserAgent, LPCOLESTR pszReferrer) = 0; }; ================================================ FILE: include/LAVAudioSettings.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // {4158A22B-6553-45D0-8069-24716F8FF171} DEFINE_GUID(IID_ILAVAudioSettings, 0x4158a22b, 0x6553, 0x45d0, 0x80, 0x69, 0x24, 0x71, 0x6f, 0x8f, 0xf1, 0x71); // {A668B8F2-BA87-4F63-9D41-768F7DE9C50E} DEFINE_GUID(IID_ILAVAudioStatus, 0xa668b8f2, 0xba87, 0x4f63, 0x9d, 0x41, 0x76, 0x8f, 0x7d, 0xe9, 0xc5, 0xe); // Codecs supported in the LAV Audio configuration // Codecs not listed here cannot be turned off. You can request codecs to be added to this list, if you wish. typedef enum LAVAudioCodec { Codec_AAC, Codec_AC3, Codec_EAC3, Codec_DTS, Codec_MP2, Codec_MP3, Codec_TRUEHD, Codec_FLAC, Codec_VORBIS, Codec_LPCM, Codec_PCM, Codec_WAVPACK, Codec_TTA, Codec_WMA2, Codec_WMAPRO, Codec_Cook, Codec_RealAudio, Codec_WMALL, Codec_ALAC, Codec_Opus, Codec_AMR, Codec_Nellymoser, Codec_MSPCM, Codec_Truespeech, Codec_TAK, Codec_ATRAC, Codec_ADPCM, Codec_IMC, Codec_AudioNB // Number of entries (do not use when dynamically linking) } LAVAudioCodec; // Bitstreaming Codecs supported in LAV Audio typedef enum LAVBitstreamCodec { Bitstream_AC3, Bitstream_EAC3, Bitstream_TRUEHD, Bitstream_DTS, Bitstream_DTSHD, Bitstream_NB // Number of entries (do not use when dynamically linking) } LAVBitstreamCodec; // Supported Sample Formats in LAV Audio typedef enum LAVAudioSampleFormat { SampleFormat_None = -1, SampleFormat_16, SampleFormat_24, SampleFormat_32, SampleFormat_U8, SampleFormat_FP32, SampleFormat_Bitstream, SampleFormat_NB // Number of entries (do not use when dynamically linking) } LAVAudioSampleFormat; typedef enum LAVAudioMixingMode { MatrixEncoding_None, MatrixEncoding_Dolby, MatrixEncoding_DPLII, MatrixEncoding_NB } LAVAudioMixingMode; // LAV Audio configuration interface interface __declspec(uuid("4158A22B-6553-45D0-8069-24716F8FF171")) ILAVAudioSettings : public IUnknown { // Switch to Runtime Config mode. This will reset all settings to default, and no changes to the settings will be // saved You can use this to programmatically configure LAV Audio without interfering with the users settings in the // registry. Subsequent calls to this function will reset all settings back to defaults, even if the mode does not // change. // // Note that calling this function during playback is not supported and may exhibit undocumented behaviour. // For smooth operations, it must be called before LAV Audio is connected to other filters. STDMETHOD(SetRuntimeConfig)(BOOL bRuntimeConfig) = 0; // Dynamic Range Compression // pbDRCEnabled: The state of DRC // piDRCLevel: The DRC strength (0-100, 100 is maximum) STDMETHOD(GetDRC)(BOOL * pbDRCEnabled, int *piDRCLevel) = 0; STDMETHOD(SetDRC)(BOOL bDRCEnabled, int iDRCLevel) = 0; // Configure which codecs are enabled // If aCodec is invalid (possibly a version difference), Get will return FALSE, and Set E_FAIL. STDMETHOD_(BOOL, GetFormatConfiguration)(LAVAudioCodec aCodec) = 0; STDMETHOD(SetFormatConfiguration)(LAVAudioCodec aCodec, BOOL bEnabled) = 0; // Control Bitstreaming // If bsCodec is invalid (possibly a version difference), Get will return FALSE, and Set E_FAIL. STDMETHOD_(BOOL, GetBitstreamConfig)(LAVBitstreamCodec bsCodec) = 0; STDMETHOD(SetBitstreamConfig)(LAVBitstreamCodec bsCodec, BOOL bEnabled) = 0; // Should "normal" DTS frames be encapsulated in DTS-HD frames when bitstreaming? STDMETHOD_(BOOL, GetDTSHDFraming)() = 0; STDMETHOD(SetDTSHDFraming)(BOOL bHDFraming) = 0; // Control Auto A/V syncing STDMETHOD_(BOOL, GetAutoAVSync)() = 0; STDMETHOD(SetAutoAVSync)(BOOL bAutoSync) = 0; // Convert all Channel Layouts to standard layouts // Standard are: Mono, Stereo, 5.1, 6.1, 7.1 STDMETHOD_(BOOL, GetOutputStandardLayout)() = 0; STDMETHOD(SetOutputStandardLayout)(BOOL bStdLayout) = 0; // Expand Mono to Stereo by simply doubling the audio STDMETHOD_(BOOL, GetExpandMono)() = 0; STDMETHOD(SetExpandMono)(BOOL bExpandMono) = 0; // Expand 6.1 to 7.1 by doubling the back center STDMETHOD_(BOOL, GetExpand61)() = 0; STDMETHOD(SetExpand61)(BOOL bExpand61) = 0; // Allow Raw PCM and SPDIF encoded input STDMETHOD_(BOOL, GetAllowRawSPDIFInput)() = 0; STDMETHOD(SetAllowRawSPDIFInput)(BOOL bAllow) = 0; // Configure which sample formats are enabled // Note: SampleFormat_Bitstream cannot be controlled by this STDMETHOD_(BOOL, GetSampleFormat)(LAVAudioSampleFormat format) = 0; STDMETHOD(SetSampleFormat)(LAVAudioSampleFormat format, BOOL bEnabled) = 0; // Configure a delay for the audio STDMETHOD(GetAudioDelay)(BOOL * pbEnabled, int *pDelay) = 0; STDMETHOD(SetAudioDelay)(BOOL bEnabled, int delay) = 0; // Enable/Disable Mixing STDMETHOD(SetMixingEnabled)(BOOL bEnabled) = 0; STDMETHOD_(BOOL, GetMixingEnabled)() = 0; // Control Mixing Layout STDMETHOD(SetMixingLayout)(DWORD dwLayout) = 0; STDMETHOD_(DWORD, GetMixingLayout)() = 0; #define LAV_MIXING_FLAG_UNTOUCHED_STEREO 0x0001 #define LAV_MIXING_FLAG_NORMALIZE_MATRIX 0x0002 #define LAV_MIXING_FLAG_CLIP_PROTECTION 0x0004 // Set Mixing Flags STDMETHOD(SetMixingFlags)(DWORD dwFlags) = 0; STDMETHOD_(DWORD, GetMixingFlags)() = 0; // Set Mixing Mode STDMETHOD(SetMixingMode)(LAVAudioMixingMode mixingMode) = 0; STDMETHOD_(LAVAudioMixingMode, GetMixingMode)() = 0; // Set Mixing Levels STDMETHOD(SetMixingLevels)(DWORD dwCenterLevel, DWORD dwSurroundLevel, DWORD dwLFELevel) = 0; STDMETHOD(GetMixingLevels)(DWORD * dwCenterLevel, DWORD * dwSurroundLevel, DWORD * dwLFELevel) = 0; // Toggle Tray Icon STDMETHOD(SetTrayIcon)(BOOL bEnabled) = 0; STDMETHOD_(BOOL, GetTrayIcon)() = 0; // Toggle Dithering for sample format conversion STDMETHOD(SetSampleConvertDithering)(BOOL bEnabled) = 0; STDMETHOD_(BOOL, GetSampleConvertDithering)() = 0; // Suppress sample format changes. This will allow channel count to increase, but not to reduce, instead adding // empty channels This option is NOT persistent STDMETHOD(SetSuppressFormatChanges)(BOOL bEnabled) = 0; STDMETHOD_(BOOL, GetSuppressFormatChanges)() = 0; // Use 5.1 legacy layout (using back channels instead of side) STDMETHOD_(BOOL, GetOutput51LegacyLayout)() = 0; STDMETHOD(SetOutput51LegacyLayout)(BOOL b51Legacy) = 0; // Fallback to audio decoding if bitstreaming is not supported by the audio renderer/hardware STDMETHOD_(BOOL, GetBitstreamingFallback)() = 0; STDMETHOD(SetBitstreamingFallback)(BOOL bBitstreamingFallback) = 0; }; // LAV Audio Status Interface // Get the current playback stats interface __declspec(uuid("A668B8F2-BA87-4F63-9D41-768F7DE9C50E")) ILAVAudioStatus : public IUnknown { // Check if the given sample format is supported by the current playback chain STDMETHOD_(BOOL, IsSampleFormatSupported)(LAVAudioSampleFormat sfCheck) = 0; // Get details about the current decoding format STDMETHOD(GetDecodeDetails) (LPCSTR * pCodec, LPCSTR * pDecodeFormat, int *pnChannels, int *pSampleRate, DWORD *pChannelMask) = 0; // Get details about the current output format STDMETHOD(GetOutputDetails)(LPCSTR * pOutputFormat, int *pnChannels, int *pSampleRate, DWORD *pChannelMask) = 0; // Enable Volume measurements STDMETHOD(EnableVolumeStats)() = 0; // Disable Volume measurements STDMETHOD(DisableVolumeStats)() = 0; // Get Volume Average for the given channel STDMETHOD(GetChannelVolumeAverage)(WORD nChannel, float *pfDb) = 0; }; ================================================ FILE: include/LAVSplitterSettings.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #include // IUnknown and GUID Macros // {774A919D-EA95-4A87-8A1E-F48ABE8499C7} DEFINE_GUID(IID_ILAVFSettings, 0x774a919d, 0xea95, 0x4a87, 0x8a, 0x1e, 0xf4, 0x8a, 0xbe, 0x84, 0x99, 0xc7); typedef enum LAVSubtitleMode { LAVSubtitleMode_NoSubs, LAVSubtitleMode_ForcedOnly, LAVSubtitleMode_Default, LAVSubtitleMode_Advanced } LAVSubtitleMode; interface __declspec(uuid("774A919D-EA95-4A87-8A1E-F48ABE8499C7")) ILAVFSettings : public IUnknown { // Switch to Runtime Config mode. This will reset all settings to default, and no changes to the settings will be // saved You can use this to programmatically configure LAV Splitter without interfering with the users settings in // the registry. Subsequent calls to this function will reset all settings back to defaults, even if the mode does // not change. // // Note that calling this function during playback is not supported and may exhibit undocumented behaviour. // For smooth operations, it must be called before LAV Splitter opens a file. STDMETHOD(SetRuntimeConfig)(BOOL bRuntimeConfig) = 0; // Retrieve the preferred languages as ISO 639-2 language codes, comma separated // If the result is NULL, no language has been set // Memory for the string will be allocated, and has to be free'ed by the caller with CoTaskMemFree STDMETHOD(GetPreferredLanguages)(LPWSTR * ppLanguages) = 0; // Set the preferred languages as ISO 639-2 language codes, comma separated // To reset to no preferred language, pass NULL or the empty string STDMETHOD(SetPreferredLanguages)(LPCWSTR pLanguages) = 0; // Retrieve the preferred subtitle languages as ISO 639-2 language codes, comma separated // If the result is NULL, no language has been set // If no subtitle language is set, the main language preference is used. // Memory for the string will be allocated, and has to be free'ed by the caller with CoTaskMemFree STDMETHOD(GetPreferredSubtitleLanguages)(LPWSTR * ppLanguages) = 0; // Set the preferred subtitle languages as ISO 639-2 language codes, comma separated // To reset to no preferred language, pass NULL or the empty string // If no subtitle language is set, the main language preference is used. STDMETHOD(SetPreferredSubtitleLanguages)(LPCWSTR pLanguages) = 0; // Get the current subtitle mode // See enum for possible values STDMETHOD_(LAVSubtitleMode, GetSubtitleMode)() = 0; // Set the current subtitle mode // See enum for possible values STDMETHOD(SetSubtitleMode)(LAVSubtitleMode mode) = 0; // Get the subtitle matching language flag // TRUE = Only subtitles with a language in the preferred list will be used; FALSE = All subtitles will be used // @deprecated - do not use anymore, deprecated and non-functional, replaced by advanced subtitle mode STDMETHOD_(BOOL, GetSubtitleMatchingLanguage)() = 0; // Set the subtitle matching language flag // TRUE = Only subtitles with a language in the preferred list will be used; FALSE = All subtitles will be used // @deprecated - do not use anymore, deprecated and non-functional, replaced by advanced subtitle mode STDMETHOD(SetSubtitleMatchingLanguage)(BOOL dwMode) = 0; // Control whether a special "Forced Subtitles" stream will be created for PGS subs STDMETHOD_(BOOL, GetPGSForcedStream)() = 0; // Control whether a special "Forced Subtitles" stream will be created for PGS subs STDMETHOD(SetPGSForcedStream)(BOOL bFlag) = 0; // Get the PGS forced subs config // TRUE = only forced PGS frames will be shown, FALSE = all frames will be shown STDMETHOD_(BOOL, GetPGSOnlyForced)() = 0; // Set the PGS forced subs config // TRUE = only forced PGS frames will be shown, FALSE = all frames will be shown STDMETHOD(SetPGSOnlyForced)(BOOL bForced) = 0; // Get the VC-1 Timestamp Processing mode // 0 - No Timestamp Correction, 1 - Always Timestamp Correction, 2 - Auto (Correction for Decoders that need it) STDMETHOD_(int, GetVC1TimestampMode)() = 0; // Set the VC-1 Timestamp Processing mode // 0 - No Timestamp Correction, 1 - Always Timestamp Correction, 2 - Auto (Correction for Decoders that need it) STDMETHOD(SetVC1TimestampMode)(int iMode) = 0; // Set whether substreams (AC3 in TrueHD, for example) should be shown as a separate stream STDMETHOD(SetSubstreamsEnabled)(BOOL bSubStreams) = 0; // Check whether substreams (AC3 in TrueHD, for example) should be shown as a separate stream STDMETHOD_(BOOL, GetSubstreamsEnabled)() = 0; // @deprecated - no longer required STDMETHOD(SetVideoParsingEnabled)(BOOL bEnabled) = 0; // @deprecated - no longer required STDMETHOD_(BOOL, GetVideoParsingEnabled)() = 0; // Set if LAV Splitter should try to fix broken HD-PVR streams // @deprecated - no longer required STDMETHOD(SetFixBrokenHDPVR)(BOOL bEnabled) = 0; // Query if LAV Splitter should try to fix broken HD-PVR streams // @deprecated - no longer required STDMETHOD_(BOOL, GetFixBrokenHDPVR)() = 0; // Control whether the given format is enabled STDMETHOD_(HRESULT, SetFormatEnabled)(LPCSTR strFormat, BOOL bEnabled) = 0; // Check if the given format is enabled STDMETHOD_(BOOL, IsFormatEnabled)(LPCSTR strFormat) = 0; // Set if LAV Splitter should always completely remove the filter connected to its Audio Pin when the audio stream // is changed STDMETHOD(SetStreamSwitchRemoveAudio)(BOOL bEnabled) = 0; // Query if LAV Splitter should always completely remove the filter connected to its Audio Pin when the audio stream // is changed STDMETHOD_(BOOL, GetStreamSwitchRemoveAudio)() = 0; // Advanced Subtitle configuration. Refer to the documentation for details. // If no advanced config exists, will be NULL. // Memory for the string will be allocated, and has to be free'ed by the caller with CoTaskMemFree STDMETHOD(GetAdvancedSubtitleConfig)(LPWSTR * ppAdvancedConfig) = 0; // Advanced Subtitle configuration. Refer to the documentation for details. // To reset the config, pass NULL or the empty string. // If no subtitle language is set, the main language preference is used. STDMETHOD(SetAdvancedSubtitleConfig)(LPCWSTR pAdvancedConfig) = 0; // Set if LAV Splitter should prefer audio streams for the hearing or visually impaired STDMETHOD(SetUseAudioForHearingVisuallyImpaired)(BOOL bEnabled) = 0; // Get if LAV Splitter should prefer audio streams for the hearing or visually impaired STDMETHOD_(BOOL, GetUseAudioForHearingVisuallyImpaired)() = 0; // Set the maximum queue size, in megabytes STDMETHOD(SetMaxQueueMemSize)(DWORD dwMaxSize) = 0; // Get the maximum queue size, in megabytes STDMETHOD_(DWORD, GetMaxQueueMemSize)() = 0; // Toggle Tray Icon STDMETHOD(SetTrayIcon)(BOOL bEnabled) = 0; // Get Tray Icon STDMETHOD_(BOOL, GetTrayIcon)() = 0; // Toggle whether higher quality audio streams are preferred STDMETHOD(SetPreferHighQualityAudioStreams)(BOOL bEnabled) = 0; // Toggle whether higher quality audio streams are preferred STDMETHOD_(BOOL, GetPreferHighQualityAudioStreams)() = 0; // Toggle whether Matroska Linked Segments should be loaded from other files STDMETHOD(SetLoadMatroskaExternalSegments)(BOOL bEnabled) = 0; // Get whether Matroska Linked Segments should be loaded from other files STDMETHOD_(BOOL, GetLoadMatroskaExternalSegments)() = 0; // Get the list of available formats // Memory for the string array will be allocated, and has to be free'ed by the caller with CoTaskMemFree STDMETHOD(GetFormats)(LPSTR * *formats, UINT * nFormats) = 0; // Set the duration (in ms) of analysis for network streams (to find the streams and codec parameters) STDMETHOD(SetNetworkStreamAnalysisDuration)(DWORD dwDuration) = 0; // Get the duration (in ms) of analysis for network streams (to find the streams and codec parameters) STDMETHOD_(DWORD, GetNetworkStreamAnalysisDuration)() = 0; // Set the maximum queue size, in number of packets STDMETHOD(SetMaxQueueSize)(DWORD dwMaxSize) = 0; // Get the maximum queue size, in number of packets STDMETHOD_(DWORD, GetMaxQueueSize)() = 0; // Set if LAV Splitter should reselect subs based on given rules when audio stream is changed STDMETHOD(SetStreamSwitchReselectSubtitles)(BOOL bEnabled) = 0; // Query if LAV Splitter should reselect subs based on given rules when audio stream is changed STDMETHOD_(BOOL, GetStreamSwitchReselectSubtitles)() = 0; }; ================================================ FILE: include/LAVVideoSettings.h ================================================ /* * Copyright (C) 2010-2021 Hendrik Leppkes * http://www.1f0.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once // {FA40D6E9-4D38-4761-ADD2-71A9EC5FD32F} DEFINE_GUID(IID_ILAVVideoSettings, 0xfa40d6e9, 0x4d38, 0x4761, 0xad, 0xd2, 0x71, 0xa9, 0xec, 0x5f, 0xd3, 0x2f); // {1CC2385F-36FA-41B1-9942-5024CE0235DC} DEFINE_GUID(IID_ILAVVideoStatus, 0x1cc2385f, 0x36fa, 0x41b1, 0x99, 0x42, 0x50, 0x24, 0xce, 0x2, 0x35, 0xdc); // Codecs supported in the LAV Video configuration // Codecs not listed here cannot be turned off. You can request codecs to be added to this list, if you wish. typedef enum LAVVideoCodec { Codec_H264, Codec_VC1, Codec_MPEG1, Codec_MPEG2, Codec_MPEG4, Codec_MSMPEG4, Codec_VP8, Codec_WMV3, Codec_WMV12, Codec_MJPEG, Codec_Theora, Codec_FLV1, Codec_VP6, Codec_SVQ, Codec_H261, Codec_H263, Codec_Indeo, Codec_TSCC, Codec_Fraps, Codec_HuffYUV, Codec_QTRle, Codec_DV, Codec_Bink, Codec_Smacker, Codec_RV12, Codec_RV34, Codec_Lagarith, Codec_Cinepak, Codec_Camstudio, Codec_QPEG, Codec_ZLIB, Codec_QTRpza, Codec_PNG, Codec_MSRLE, Codec_ProRes, Codec_UtVideo, Codec_Dirac, Codec_DNxHD, Codec_MSVideo1, Codec_8BPS, Codec_LOCO, Codec_ZMBV, Codec_VCR1, Codec_Snow, Codec_FFV1, Codec_v210, Codec_JPEG2000, Codec_VMNC, Codec_FLIC, Codec_G2M, Codec_ICOD, Codec_THP, Codec_HEVC, Codec_VP9, Codec_TrueMotion, Codec_VP7, Codec_H264MVC, Codec_CineformHD, Codec_MagicYUV, Codec_AV1, Codec_VVC, Codec_VP4, Codec_FIC, Codec_APV, Codec_VideoNB // Number of entries (do not use when dynamically linking) } LAVVideoCodec; // Codecs with hardware acceleration typedef enum LAVVideoHWCodec { HWCodec_H264 = Codec_H264, HWCodec_VC1 = Codec_VC1, HWCodec_MPEG2 = Codec_MPEG2, HWCodec_MPEG4 = Codec_MPEG4, HWCodec_MPEG2DVD_Deprecated, // disabled, DVD video is no longer supported in hardware decoding due to issues with menus and general stability HWCodec_HEVC, HWCodec_VP9, HWCodec_H264MVC, HWCodec_AV1, HWCodec_NB, } LAVVideoHWCodec; // Flags for HW Resolution support #define LAVHWResFlag_SD 0x0001 #define LAVHWResFlag_HD 0x0002 #define LAVHWResFlag_UHD 0x0004 // Type of hardware accelerations typedef enum LAVHWAccel { HWAccel_None, HWAccel_CUDA, HWAccel_QuickSync, HWAccel_DXVA2, HWAccel_DXVA2CopyBack = HWAccel_DXVA2, HWAccel_DXVA2Native, HWAccel_D3D11, HWAccel_NB, // Number of HWAccels } LAVHWAccel; // Deinterlace algorithms offered by the hardware decoders typedef enum LAVHWDeintModes { HWDeintMode_Weave, HWDeintMode_BOB, // Deprecated HWDeintMode_Hardware } LAVHWDeintModes; // Software deinterlacing algorithms typedef enum LAVSWDeintModes { SWDeintMode_None, SWDeintMode_YADIF, SWDeintMode_W3FDIF_Simple, SWDeintMode_W3FDIF_Complex, SWDeintMode_BWDIF, } LAVSWDeintModes; // Deinterlacing processing mode typedef enum LAVDeintMode { DeintMode_Auto, DeintMode_Aggressive, DeintMode_Force, DeintMode_Disable } LAVDeintMode; // Type of deinterlacing to perform // - FramePerField re-constructs one frame from every field, resulting in 50/60 fps. // - FramePer2Field re-constructs one frame from every 2 fields, resulting in 25/30 fps. // Note: Weave will always use FramePer2Field typedef enum LAVDeintOutput { DeintOutput_FramePerField, DeintOutput_FramePer2Field } LAVDeintOutput; // Control the field order of the deinterlacer typedef enum LAVDeintFieldOrder { DeintFieldOrder_Auto, DeintFieldOrder_TopFieldFirst, DeintFieldOrder_BottomFieldFirst, } LAVDeintFieldOrder; // Supported output pixel formats typedef enum LAVOutPixFmts { LAVOutPixFmt_None = -1, LAVOutPixFmt_YV12, // 4:2:0, 8bit, planar LAVOutPixFmt_NV12, // 4:2:0, 8bit, Y planar, U/V packed LAVOutPixFmt_YUY2, // 4:2:2, 8bit, packed LAVOutPixFmt_UYVY, // 4:2:2, 8bit, packed LAVOutPixFmt_AYUV, // 4:4:4, 8bit, packed LAVOutPixFmt_P010, // 4:2:0, 10bit, Y planar, U/V packed LAVOutPixFmt_P210, // 4:2:2, 10bit, Y planar, U/V packed LAVOutPixFmt_Y410, // 4:4:4, 10bit, packed LAVOutPixFmt_P016, // 4:2:0, 16bit, Y planar, U/V packed LAVOutPixFmt_P216, // 4:2:2, 16bit, Y planar, U/V packed LAVOutPixFmt_Y416, // 4:4:4, 16bit, packed LAVOutPixFmt_RGB32, // 32-bit RGB (BGRA) LAVOutPixFmt_RGB24, // 24-bit RGB (BGR) LAVOutPixFmt_v210, // 4:2:2, 10bit, packed LAVOutPixFmt_v410, // 4:4:4, 10bit, packed LAVOutPixFmt_YV16, // 4:2:2, 8-bit, planar LAVOutPixFmt_YV24, // 4:4:4, 8-bit, planar LAVOutPixFmt_RGB48, // 48-bit RGB (16-bit per pixel, BGR) LAVOutPixFmt_NB // Number of formats } LAVOutPixFmts; typedef enum LAVDitherMode { LAVDither_Ordered, LAVDither_Random } LAVDitherMode; // LAV Video configuration interface interface __declspec(uuid("FA40D6E9-4D38-4761-ADD2-71A9EC5FD32F")) ILAVVideoSettings : public IUnknown { // Switch to Runtime Config mode. This will reset all settings to default, and no changes to the settings will be // saved You can use this to programmatically configure LAV Video without interfering with the users settings in the // registry. Subsequent calls to this function will reset all settings back to defaults, even if the mode does not // change. // // Note that calling this function during playback is not supported and may exhibit undocumented behaviour. // For smooth operations, it must be called before LAV Video is connected to other filters. STDMETHOD(SetRuntimeConfig)(BOOL bRuntimeConfig) = 0; // Configure which codecs are enabled // If vCodec is invalid (possibly a version difference), Get will return FALSE, and Set E_FAIL. STDMETHOD_(BOOL, GetFormatConfiguration)(LAVVideoCodec vCodec) = 0; STDMETHOD(SetFormatConfiguration)(LAVVideoCodec vCodec, BOOL bEnabled) = 0; // Set the number of threads to use for Multi-Threaded decoding (where available) // 0 = Auto Detect (based on number of CPU cores) // 1 = 1 Thread -- No Multi-Threading // >1 = Multi-Threading with the specified number of threads STDMETHOD(SetNumThreads)(DWORD dwNum) = 0; // Get the number of threads to use for Multi-Threaded decoding (where available) // 0 = Auto Detect (based on number of CPU cores) // 1 = 1 Thread -- No Multi-Threading // >1 = Multi-Threading with the specified number of threads STDMETHOD_(DWORD, GetNumThreads)() = 0; // Set whether the aspect ratio encoded in the stream should be forwarded to the renderer, // or the aspect ratio specified by the source filter should be kept. // 0 = AR from the source filter // 1 = AR from the Stream // 2 = AR from stream if source is not reliable STDMETHOD(SetStreamAR)(DWORD bStreamAR) = 0; // Get whether the aspect ratio encoded in the stream should be forwarded to the renderer, // or the aspect ratio specified by the source filter should be kept. // 0 = AR from the source filter // 1 = AR from the Stream // 2 = AR from stream if source is not reliable STDMETHOD_(DWORD, GetStreamAR)() = 0; // Configure which pixel formats are enabled for output // If pixFmt is invalid, Get will return FALSE and Set E_FAIL STDMETHOD_(BOOL, GetPixelFormat)(LAVOutPixFmts pixFmt) = 0; STDMETHOD(SetPixelFormat)(LAVOutPixFmts pixFmt, BOOL bEnabled) = 0; // Set the RGB output range for the YUV->RGB conversion // 0 = Auto (same as input), 1 = Limited (16-235), 2 = Full (0-255) STDMETHOD(SetRGBOutputRange)(DWORD dwRange) = 0; // Get the RGB output range for the YUV->RGB conversion // 0 = Auto (same as input), 1 = Limited (16-235), 2 = Full (0-255) STDMETHOD_(DWORD, GetRGBOutputRange)() = 0; // Set the deinterlacing field order of the hardware decoder STDMETHOD(SetDeintFieldOrder)(LAVDeintFieldOrder fieldOrder) = 0; // get the deinterlacing field order of the hardware decoder STDMETHOD_(LAVDeintFieldOrder, GetDeintFieldOrder)() = 0; // DEPRECATED, use SetDeinterlacingMode STDMETHOD(SetDeintAggressive)(BOOL bAggressive) = 0; // DEPRECATED, use GetDeinterlacingMode STDMETHOD_(BOOL, GetDeintAggressive)() = 0; // DEPRECATED, use SetDeinterlacingMode STDMETHOD(SetDeintForce)(BOOL bForce) = 0; // DEPRECATED, use GetDeinterlacingMode STDMETHOD_(BOOL, GetDeintForce)() = 0; // Check if the specified HWAccel is supported // Note: This will usually only check the availability of the required libraries (ie. for NVIDIA if a recent enough // NVIDIA driver is installed) and not check actual hardware support Returns: 0 = Unsupported, 1 = Supported, 2 = // Currently running STDMETHOD_(DWORD, CheckHWAccelSupport)(LAVHWAccel hwAccel) = 0; // Set which HW Accel method is used // See LAVHWAccel for options. STDMETHOD(SetHWAccel)(LAVHWAccel hwAccel) = 0; // Get which HW Accel method is active STDMETHOD_(LAVHWAccel, GetHWAccel)() = 0; // Set which codecs should use HW Acceleration STDMETHOD(SetHWAccelCodec)(LAVVideoHWCodec hwAccelCodec, BOOL bEnabled) = 0; // Get which codecs should use HW Acceleration STDMETHOD_(BOOL, GetHWAccelCodec)(LAVVideoHWCodec hwAccelCodec) = 0; // Set the deinterlacing mode used by the hardware decoder STDMETHOD(SetHWAccelDeintMode)(LAVHWDeintModes deintMode) = 0; // Get the deinterlacing mode used by the hardware decoder STDMETHOD_(LAVHWDeintModes, GetHWAccelDeintMode)() = 0; // Set the deinterlacing output for the hardware decoder STDMETHOD(SetHWAccelDeintOutput)(LAVDeintOutput deintOutput) = 0; // Get the deinterlacing output for the hardware decoder STDMETHOD_(LAVDeintOutput, GetHWAccelDeintOutput)() = 0; // deprecated. HQ mode is only supported by NVIDIA CUVID/NVDEC and officially deprecated by NVIDIA STDMETHOD(SetHWAccelDeintHQ)(BOOL bHQ) = 0; STDMETHOD_(BOOL, GetHWAccelDeintHQ)() = 0; // Set the software deinterlacing mode used STDMETHOD(SetSWDeintMode)(LAVSWDeintModes deintMode) = 0; // Get the software deinterlacing mode used STDMETHOD_(LAVSWDeintModes, GetSWDeintMode)() = 0; // Set the software deinterlacing output STDMETHOD(SetSWDeintOutput)(LAVDeintOutput deintOutput) = 0; // Get the software deinterlacing output STDMETHOD_(LAVDeintOutput, GetSWDeintOutput)() = 0; // DEPRECATED, use SetDeinterlacingMode STDMETHOD(SetDeintTreatAsProgressive)(BOOL bEnabled) = 0; // DEPRECATED, use GetDeinterlacingMode STDMETHOD_(BOOL, GetDeintTreatAsProgressive)() = 0; // Set the dithering mode used STDMETHOD(SetDitherMode)(LAVDitherMode ditherMode) = 0; // Get the dithering mode used STDMETHOD_(LAVDitherMode, GetDitherMode)() = 0; // Set if the MS WMV9 DMO Decoder should be used for VC-1/WMV3 STDMETHOD(SetUseMSWMV9Decoder)(BOOL bEnabled) = 0; // Get if the MS WMV9 DMO Decoder should be used for VC-1/WMV3 STDMETHOD_(BOOL, GetUseMSWMV9Decoder)() = 0; // Set if DVD Video support is enabled STDMETHOD(SetDVDVideoSupport)(BOOL bEnabled) = 0; // Get if DVD Video support is enabled STDMETHOD_(BOOL, GetDVDVideoSupport)() = 0; // Set the HW Accel Resolution Flags // flags: bitmask of LAVHWResFlag flags STDMETHOD(SetHWAccelResolutionFlags)(DWORD dwResFlags) = 0; // Get the HW Accel Resolution Flags // flags: bitmask of LAVHWResFlag flags STDMETHOD_(DWORD, GetHWAccelResolutionFlags)() = 0; // Toggle Tray Icon STDMETHOD(SetTrayIcon)(BOOL bEnabled) = 0; // Get Tray Icon STDMETHOD_(BOOL, GetTrayIcon)() = 0; // Set the Deint Mode STDMETHOD(SetDeinterlacingMode)(LAVDeintMode deintMode) = 0; // Get the Deint Mode STDMETHOD_(LAVDeintMode, GetDeinterlacingMode)() = 0; // Set the index of the GPU to be used for hardware decoding // Only supported for CUVID and DXVA2 copy-back. If the device is not valid, it'll fallback to auto-detection // Must be called before an input is connected to LAV Video, and the setting is non-persistent // NOTE: For CUVID, the index defines the index of the CUDA capable device, while for DXVA2, the list includes all // D3D9 devices STDMETHOD(SetGPUDeviceIndex)(DWORD dwDevice) = 0; // Get the number of available devices for the specified HWAccel STDMETHOD_(DWORD, GetHWAccelNumDevices)(LAVHWAccel hwAccel) = 0; // Get a list of available HWAccel devices for the specified HWAccel STDMETHOD(GetHWAccelDeviceInfo) (LAVHWAccel hwAccel, DWORD dwIndex, BSTR * pstrDeviceName, DWORD * pdwDeviceIdentifier) = 0; // Get/Set the device for a specified HWAccel // In contrast to SetGPUDeviceIndex, this setting is hwaccel-specific and persistent // dwDeviceIdentifier is an optional parameter that identifies the selected device (ie. its device id), set to 0 if // not used #define LAVHWACCEL_DEVICE_DEFAULT ((DWORD)-1) STDMETHOD_(DWORD, GetHWAccelDeviceIndex)(LAVHWAccel hwAccel, DWORD * pdwDeviceIdentifier) = 0; STDMETHOD(SetHWAccelDeviceIndex)(LAVHWAccel hwAccel, DWORD dwIndex, DWORD dwDeviceIdentifier) = 0; // Temporary Override for players to disable H.264 MVC decoding // This is not a permanent setting and not saved, but can be used by players to offer a "Play in 2D" option, or // similar. A setting of FALSE disable MVC decoding temporarily Note that the override cannot force-enable the // option if its turned off through SetFormatConfiguration STDMETHOD(SetH264MVCDecodingOverride)(BOOL bEnabled) = 0; // Enable the creation of the Closed Caption output pin STDMETHOD(SetEnableCCOutputPin)(BOOL bEnabled) = 0; }; // LAV Video status interface interface __declspec(uuid("1CC2385F-36FA-41B1-9942-5024CE0235DC")) ILAVVideoStatus : public IUnknown { // Get the name of the active decoder (can return NULL if none is active) STDMETHOD_(LPCWSTR, GetActiveDecoderName)() = 0; // Get the name of the currently active hwaccel device STDMETHOD(GetHWAccelActiveDevice)(BSTR * pstrDeviceName) = 0; }; ================================================ FILE: include/README.txt ================================================ This directory contains header files of non-standard Interfaces that LAV Filters support. --------------------------------------------------------------------------------------------- ---------------------------------------------- IKeyFrameInfo - implemented by LAV Splitter --------------------------------------------- IKeyFrameInfo allows players to query the position of keyframes, so they can redirect seeking requests to those positions for very smooth seek events. Only fully supported on MKV files. ---------------------------------------------- ITrackInfo - implemented by LAV Splitter --------------------------------------------- ITrackInfo is an interface to obtain additional information about the streams in a file. The order to query the streams is the same as returned by IAMStreamSelect::Info ---------------------------------------------- IGraphRebuildDelegate --------------------------------------------- IGraphRebuildDelegate is not an interface implemented by LAV Splitter itself. It is designed to offer the ability to take over the graph-building process from the player's side. It only exports one function which LAV Splitter will call when a stream change happens on the user's requests, and then the player can take care of the graph changes itself instead of relying on LAV Splitter to do it. To use IGraphRebuildDelegate, the player needs to implement it, and share the implementing class with LAV Splitter through the "IObjectWithSite" interface, which is implemented by LAV Splitter. ---------------------------------------------- LAVSplitterSettings / LAVAudioSettings ---------------------------------------------- These interfaces are used to configure LAV programmatically, so the player can do configuration changes. ================================================ FILE: resources/LAVFilters.Dependencies.manifest ================================================ ================================================ FILE: thirdparty/32/include/avisynth/avisynth.h ================================================ // Avisynth v2.5. Copyright 2002 Ben Rudiak-Gould et al. // Avisynth v2.6. Copyright 2006 Klaus Post. // Avisynth v2.6. Copyright 2009 Ian Brabham. // Avisynth+ project // 20160613: new 16 bit planar pixel_type constants go live! // 20160725: pixel_type constants 10-12-14 bit + planar RGB + BRG48/64 // 20161005: Fallback of VideoInfo functions to defaults if no function exists // 20170117: global variables for VfW output OPT_xxxx // 20170310: new MT mode: MT_SPECIAL_MT // 20171103: (test with SIZETMOD define: Videoframe offsets to size_t, may affect x64) // 20171207: C++ Standard Conformance (no change for plugin writers) // 20180525: AVS_UNUSED define to supress parameter not used warnings // 2020xxxx: AVS_WINDOWS and AVS_POSIX option see avs/config.h // 20200305: ScriptEnvironment::VSprintf parameter (void *) changed back to va_list // 20200330: removed __stdcall from variadic argument functions (Sprintf) // (remove test SIZETMOD define for clarity) // Integrate Avisynth Neo structures and interface, PFunction, PDevice // 20200501: frame property support (NewVideoFrameP and other helpers) to legacy IScriptEnvironment. // move some former IScriptEnvironment2 functions to IScriptEnvironment: // GetEnvProperty (system prop), Allocate, Free (buffer pool) // GetVarTry, GetVarBool/Int/String/Double/Long // Invoke2, Invoke3, InvokeTry, Invoke2Try, Invoke3Try // Interface Version to 8 (classic 2.6 = 6) // 20200527 Add IScriptEnvironment_Avs25, used internally // 20200607 AVS frame property enums to match existing Avisynth enum style // 202112xx V9-MakePropertyWritable, IsPropertyWritable // 2023 V10 // prop_src parameter made as const in NewVideoFrameP (non-breaking cosmetics) // Add all enums of public C++ API a name // Add DEFAULT_PLANE as 0 to AvsPlane enum // Made `VideoFrameBuffer` destructor public // Introduce pixel_type to VideoFrame struct // VideoFrame::GetPixelType,VideoFrame::AmendPixelType // AVSValue::GetType // Add enum AvsChannelMask::MASK_SPEAKER_xxx, AvsImageTypeFlags::IT_SPEAKER_xxx // Audio channel mask support for VideoInfo: // Use 20 bits in VideoInfo::image_type for channel mask mapping // IsChannelMaskKnown, SetChannelMask, GetChannelMask in VideoInfo // http://www.avisynth.org // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making // a combined work based on Avisynth. Thus, the terms and conditions of // the GNU General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate // with Avisynth solely through the interfaces defined in avisynth.h, // regardless of the license terms of these independent modules, and to // copy and distribute the resulting combined work under terms of your // choice, provided that every copy of the combined work is accompanied // by a complete copy of the source code of Avisynth (the version of // Avisynth used to produce the combined work), being distributed under // the terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based on // Avisynth, such as 3rd-party filters, import and export plugins, or // graphical user interfaces. #ifndef __AVISYNTH_10_H__ #define __AVISYNTH_10_H__ #include "avs/config.h" #include "avs/capi.h" #include "avs/types.h" #ifdef AVS_POSIX # include "avs/posix.h" #endif #if defined(AVS_POSIX) #if defined(AVS_HAIKU) #undef __stdcall #undef __cdecl #endif #define __stdcall #define __cdecl #endif // Important note on AVISYNTH_INTERFACE_VERSION V6->V8 change: // Note 1: Those few plugins which were using earlier IScriptEnvironment2 despite the big Warning will crash have to be rebuilt. // Note 2: How to support earlier avisynth interface with an up-to-date avisynth.h: // Use the new frame property features adaptively after querying that at least v8 is supported // AviSynth property support can be queried (cpp iface example): // has_at_least_v8 = true; // try { env->CheckVersion(8); } catch (const AvisynthError&) { has_at_least_v8 = false; } // and use it: // if (has_at_least_v8) dst = env->NewVideoFrameP(vi, &src); else dst = env->NewVideoFrame(vi); enum AvsVersion { AVISYNTH_CLASSIC_INTERFACE_VERSION_25 = 3, AVISYNTH_CLASSIC_INTERFACE_VERSION_26BETA = 5, AVISYNTH_CLASSIC_INTERFACE_VERSION = 6, AVISYNTH_INTERFACE_VERSION = 10, AVISYNTHPLUS_INTERFACE_BUGFIX_VERSION = 0 // reset to zero whenever the normal interface version bumps }; /* Compiler-specific crap */ // Tell MSVC to stop precompiling here #if defined(_MSC_VER) && !defined(__clang__) #pragma hdrstop #endif // Set up debugging macros for MS compilers; for others, step down to the // standard interface #ifdef _MSC_VER #include #else #undef _RPT0 #undef _RPT1 #undef _RPT2 #undef _RPT3 #undef _RPT4 #undef _RPT5 #define _RPT0(a,b) ((void)0) #define _RPT1(a,b,c) ((void)0) #define _RPT2(a,b,c,d) ((void)0) #define _RPT3(a,b,c,d,e) ((void)0) #define _RPT4(a,b,c,d,e,f) ((void)0) #define _RPT5(a,b,c,d,e,f,g) ((void)0) #include #undef _ASSERTE #undef _ASSERT #define _ASSERTE(x) assert(x) #define _ASSERT(x) assert(x) #endif // I had problems with Premiere wanting 1-byte alignment for its structures, // so I now set the Avisynth struct alignment explicitly here. #pragma pack(push,8) // The VideoInfo struct holds global information about a clip (i.e. // information that does not depend on the frame number). The GetVideoInfo // method in IClip returns this struct. enum AvsSampleType { SAMPLE_INT8 = 1 << 0, SAMPLE_INT16 = 1 << 1, SAMPLE_INT24 = 1 << 2, // Int24 is a very stupid thing to code, but it's supported by some hardware. SAMPLE_INT32 = 1 << 3, SAMPLE_FLOAT = 1 << 4 }; enum AvsPlane { DEFAULT_PLANE = 0, PLANAR_Y = 1 << 0, PLANAR_U = 1 << 1, PLANAR_V = 1 << 2, PLANAR_ALIGNED = 1 << 3, PLANAR_Y_ALIGNED = PLANAR_Y | PLANAR_ALIGNED, PLANAR_U_ALIGNED = PLANAR_U | PLANAR_ALIGNED, PLANAR_V_ALIGNED = PLANAR_V | PLANAR_ALIGNED, PLANAR_A = 1 << 4, PLANAR_R = 1 << 5, PLANAR_G = 1 << 6, PLANAR_B = 1 << 7, PLANAR_A_ALIGNED = PLANAR_A | PLANAR_ALIGNED, PLANAR_R_ALIGNED = PLANAR_R | PLANAR_ALIGNED, PLANAR_G_ALIGNED = PLANAR_G | PLANAR_ALIGNED, PLANAR_B_ALIGNED = PLANAR_B | PLANAR_ALIGNED, }; class AvisynthError /* exception */ { public: const char* const msg; AvisynthError(const char* _msg) : msg(_msg) {} // Ensure AvisynthError cannot be publicly assigned! private: AvisynthError& operator=(const AvisynthError&); }; // end class AvisynthError enum AvsDeviceType { DEV_TYPE_NONE = 0, DEV_TYPE_CPU = 1, DEV_TYPE_CUDA = 2, DEV_TYPE_ANY = 0xFFFF }; enum AvsValueType { VALUE_TYPE_UNDEFINED = 'v', VALUE_TYPE_BOOL = 'b', VALUE_TYPE_INT = 'i', VALUE_TYPE_LONG = 'l', VALUE_TYPE_FLOAT = 'f', VALUE_TYPE_DOUBLE = 'd', VALUE_TYPE_STRING = 's', VALUE_TYPE_CLIP = 'c', VALUE_TYPE_FUNCTION = 'n', VALUE_TYPE_ARRAY = 'a' }; /* Forward references */ #if defined(MSVC) #define SINGLE_INHERITANCE __single_inheritance #else #define SINGLE_INHERITANCE #endif struct SINGLE_INHERITANCE VideoInfo; class SINGLE_INHERITANCE VideoFrameBuffer; class SINGLE_INHERITANCE VideoFrame; class IClip; class SINGLE_INHERITANCE PClip; class SINGLE_INHERITANCE PVideoFrame; class IScriptEnvironment; class SINGLE_INHERITANCE AVSValue; class INeoEnv; class IFunction; class SINGLE_INHERITANCE PFunction; class Device; class SINGLE_INHERITANCE PDevice; class AVSMap; /* * Avisynth C++ plugin API code function pointers. * * In order to maintain binary compatibility with * future version do not change the order of the * existing function pointers. It will be baked * into all existing plugins. * * Add new function pointers to the end of the * structure. The linkage macros generate some * protection code to ensure newer plugin do not * call non-existing functions in an older host. */ struct AVS_Linkage { int Size; /**********************************************************************/ // struct VideoInfo bool (VideoInfo::*HasVideo)() const; bool (VideoInfo::*HasAudio)() const; bool (VideoInfo::*IsRGB)() const; bool (VideoInfo::*IsRGB24)() const; bool (VideoInfo::*IsRGB32)() const; bool (VideoInfo::*IsYUV)() const; bool (VideoInfo::*IsYUY2)() const; bool (VideoInfo::*IsYV24)() const; bool (VideoInfo::*IsYV16)() const; bool (VideoInfo::*IsYV12)() const; bool (VideoInfo::*IsYV411)() const; bool (VideoInfo::*IsY8)() const; bool (VideoInfo::*IsColorSpace)(int c_space) const; bool (VideoInfo::*Is)(int property) const; bool (VideoInfo::*IsPlanar)() const; bool (VideoInfo::*IsFieldBased)() const; bool (VideoInfo::*IsParityKnown)() const; bool (VideoInfo::*IsBFF)() const; bool (VideoInfo::*IsTFF)() const; bool (VideoInfo::*IsVPlaneFirst)() const; int (VideoInfo::*BytesFromPixels)(int pixels) const; int (VideoInfo::*RowSize)(int plane) const; int (VideoInfo::*BMPSize)() const; int64_t (VideoInfo::*AudioSamplesFromFrames)(int frames) const; int (VideoInfo::*FramesFromAudioSamples)(int64_t samples) const; int64_t (VideoInfo::*AudioSamplesFromBytes)(int64_t bytes) const; int64_t (VideoInfo::*BytesFromAudioSamples)(int64_t samples) const; int (VideoInfo::*AudioChannels)() const; int (VideoInfo::*SampleType)() const; bool (VideoInfo::*IsSampleType)(int testtype) const; int (VideoInfo::*SamplesPerSecond)() const; int (VideoInfo::*BytesPerAudioSample)() const; void (VideoInfo::*SetFieldBased)(bool isfieldbased); void (VideoInfo::*Set)(int property); void (VideoInfo::*Clear)(int property); int (VideoInfo::*GetPlaneWidthSubsampling)(int plane) const; int (VideoInfo::*GetPlaneHeightSubsampling)(int plane) const; int (VideoInfo::*BitsPerPixel)() const; int (VideoInfo::*BytesPerChannelSample)() const; void (VideoInfo::*SetFPS)(unsigned numerator, unsigned denominator); void (VideoInfo::*MulDivFPS)(unsigned multiplier, unsigned divisor); bool (VideoInfo::*IsSameColorspace)(const VideoInfo& vi) const; // end struct VideoInfo /**********************************************************************/ // class VideoFrameBuffer const BYTE* (VideoFrameBuffer::*VFBGetReadPtr)() const; BYTE* (VideoFrameBuffer::*VFBGetWritePtr)(); int (VideoFrameBuffer::*GetDataSize)() const; int (VideoFrameBuffer::*GetSequenceNumber)() const; int (VideoFrameBuffer::*GetRefcount)() const; // end class VideoFrameBuffer /**********************************************************************/ // class VideoFrame int (VideoFrame::*GetPitch)(int plane) const; int (VideoFrame::*GetRowSize)(int plane) const; int (VideoFrame::*GetHeight)(int plane) const; VideoFrameBuffer* (VideoFrame::*GetFrameBuffer)() const; int (VideoFrame::*GetOffset)(int plane) const; const BYTE* (VideoFrame::*VFGetReadPtr)(int plane) const; bool (VideoFrame::*IsWritable)() const; BYTE* (VideoFrame::*VFGetWritePtr)(int plane) const; void (VideoFrame::*VideoFrame_DESTRUCTOR)(); // end class VideoFrame /**********************************************************************/ // class IClip /* nothing */ // end class IClip /**********************************************************************/ // class PClip void (PClip::*PClip_CONSTRUCTOR0)(); void (PClip::*PClip_CONSTRUCTOR1)(const PClip& x); void (PClip::*PClip_CONSTRUCTOR2)(IClip* x); void (PClip::*PClip_OPERATOR_ASSIGN0)(IClip* x); void (PClip::*PClip_OPERATOR_ASSIGN1)(const PClip& x); void (PClip::*PClip_DESTRUCTOR)(); // end class PClip /**********************************************************************/ // class PVideoFrame void (PVideoFrame::*PVideoFrame_CONSTRUCTOR0)(); void (PVideoFrame::*PVideoFrame_CONSTRUCTOR1)(const PVideoFrame& x); void (PVideoFrame::*PVideoFrame_CONSTRUCTOR2)(VideoFrame* x); void (PVideoFrame::*PVideoFrame_OPERATOR_ASSIGN0)(VideoFrame* x); void (PVideoFrame::*PVideoFrame_OPERATOR_ASSIGN1)(const PVideoFrame& x); void (PVideoFrame::*PVideoFrame_DESTRUCTOR)(); // end class PVideoFrame /**********************************************************************/ // class AVSValue void (AVSValue::*AVSValue_CONSTRUCTOR0)(); void (AVSValue::*AVSValue_CONSTRUCTOR1)(IClip* c); void (AVSValue::*AVSValue_CONSTRUCTOR2)(const PClip& c); void (AVSValue::*AVSValue_CONSTRUCTOR3)(bool b); void (AVSValue::*AVSValue_CONSTRUCTOR4)(int i); void (AVSValue::*AVSValue_CONSTRUCTOR5)(float f); void (AVSValue::*AVSValue_CONSTRUCTOR6)(double f); void (AVSValue::*AVSValue_CONSTRUCTOR7)(const char* s); void (AVSValue::*AVSValue_CONSTRUCTOR8)(const AVSValue* a, int size); void (AVSValue::*AVSValue_CONSTRUCTOR9)(const AVSValue& v); void (AVSValue::*AVSValue_DESTRUCTOR)(); AVSValue& (AVSValue::*AVSValue_OPERATOR_ASSIGN)(const AVSValue& v); const AVSValue& (AVSValue::*AVSValue_OPERATOR_INDEX)(int index) const; bool (AVSValue::*Defined)() const; bool (AVSValue::*IsClip)() const; bool (AVSValue::*IsBool)() const; bool (AVSValue::*IsInt)() const; bool (AVSValue::*IsFloat)() const; bool (AVSValue::*IsString)() const; bool (AVSValue::*IsArray)() const; PClip (AVSValue::*AsClip)() const; bool (AVSValue::*AsBool1)() const; int (AVSValue::*AsInt1)() const; const char* (AVSValue::*AsString1)() const; double (AVSValue::*AsFloat1)() const; bool (AVSValue::*AsBool2)(bool def) const; int (AVSValue::*AsInt2)(int def) const; double (AVSValue::*AsDblDef)(double def) const; double (AVSValue::*AsFloat2)(float def) const; const char* (AVSValue::*AsString2)(const char* def) const; int (AVSValue::*ArraySize)() const; // end class AVSValue /**********************************************************************/ // Reserve pointer space so that we can keep compatibility with Avs "classic" even if it adds functions on its own void (VideoInfo::*reserved[32])(); /**********************************************************************/ // AviSynth+ additions int (VideoInfo::*NumComponents)() const; int (VideoInfo::*ComponentSize)() const; int (VideoInfo::*BitsPerComponent)() const; bool (VideoInfo::*Is444)() const; bool (VideoInfo::*Is422)() const; bool (VideoInfo::*Is420)() const; bool (VideoInfo::*IsY)() const; bool (VideoInfo::*IsRGB48)() const; bool (VideoInfo::*IsRGB64)() const; bool (VideoInfo::*IsYUVA)() const; bool (VideoInfo::*IsPlanarRGB)() const; bool (VideoInfo::*IsPlanarRGBA)() const; /**********************************************************************/ // frame property access AVSMap& (VideoFrame::* getProperties)(); const AVSMap& (VideoFrame::* getConstProperties)(); void (VideoFrame::* setProperties)(const AVSMap& properties); // PFunction void (AVSValue::* AVSValue_CONSTRUCTOR11)(const PFunction& o); bool (AVSValue::* IsFunction)() const; void (PFunction::* PFunction_CONSTRUCTOR0)(); void (PFunction::* PFunction_CONSTRUCTOR1)(IFunction* p); void (PFunction::* PFunction_CONSTRUCTOR2)(const PFunction& p); PFunction& (PFunction::* PFunction_OPERATOR_ASSIGN0)(IFunction* other); PFunction& (PFunction::* PFunction_OPERATOR_ASSIGN1)(const PFunction& other); void (PFunction::* PFunction_DESTRUCTOR)(); // end PFunction // extra VideoFrame functions int (VideoFrame::* VideoFrame_CheckMemory)() const; PDevice (VideoFrame::* VideoFrame_GetDevice)() const; // class PDevice, even if only CPU device void (PDevice::* PDevice_CONSTRUCTOR0)(); void (PDevice::* PDevice_CONSTRUCTOR1)(Device* p); void (PDevice::* PDevice_CONSTRUCTOR2)(const PDevice& p); PDevice& (PDevice::* PDevice_OPERATOR_ASSIGN0)(Device* other); PDevice& (PDevice::* PDevice_OPERATOR_ASSIGN1)(const PDevice& other); void (PDevice::* PDevice_DESTRUCTOR)(); AvsDeviceType (PDevice::* PDevice_GetType)() const; int (PDevice::* PDevice_GetId)() const; int (PDevice::* PDevice_GetIndex)() const; const char* (PDevice::* PDevice_GetName)() const; // end class PDevice // V9: VideoFrame helper bool (VideoFrame::*IsPropertyWritable)() const; // V10 int (VideoFrame::*VideoFrame_GetPixelType)() const; void (VideoFrame::*VideoFrame_AmendPixelType)(int new_pixel_type); void (VideoFrameBuffer::*VideoFrameBuffer_DESTRUCTOR)(); AvsValueType (AVSValue::*AVSValue_GetType)() const; // V10.1 bool (VideoInfo::* IsChannelMaskKnown)() const; void (VideoInfo::* SetChannelMask)(bool isChannelMaskKnown, unsigned int dwChannelMask); unsigned int (VideoInfo::* GetChannelMask)() const; /**********************************************************************/ // Reserve pointer space for Avisynth+ void (VideoInfo::* reserved2[64 - 31])(); /**********************************************************************/ // AviSynth Neo additions INeoEnv* (__stdcall *GetNeoEnv)(IScriptEnvironment* env); // As of V8 most PDevice, PFunction linkage entries are moved to standard avs+ place. /**********************************************************************/ // This part should be identical with AVS_Linkage entries in interface.cpp }; #if defined(BUILDING_AVSCORE) || defined(AVS_STATIC_LIB) /* Macro resolution for code inside Avisynth.dll */ # define AVS_BakedCode(arg) ; # define AVS_LinkCall(arg) # define AVS_LinkCallV(arg) # define AVS_LinkCallOpt(arg, argOpt) AVSLinkCall(arg) # define AVS_LinkCallOptDefault(arg, argDefaultValue) AVSLinkCall(arg()) # define CALL_MEMBER_FN(object,ptrToMember) #else /* Macro resolution for code inside user plugin */ # ifdef AVS_LINKAGE_DLLIMPORT extern __declspec(dllimport) const AVS_Linkage* const AVS_linkage; # else extern const AVS_Linkage* AVS_linkage; # endif # ifndef offsetof # include # endif # define AVS_BakedCode(arg) { arg ; } # define AVS_LinkCall(arg) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? 0 : (this->*(AVS_linkage->arg)) # define AVS_LinkCall_Void(arg) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? (void)0 : (this->*(AVS_linkage->arg)) # define AVS_LinkCallV(arg) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? *this : (this->*(AVS_linkage->arg)) // Helper macros for fallback option when a function does not exists #define CALL_MEMBER_FN(object,ptrToMember) ((object)->*(ptrToMember)) #define AVS_LinkCallOpt(arg, argOpt) !AVS_linkage ? 0 : \ ( offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? \ (offsetof(AVS_Linkage, argOpt) >= (size_t)AVS_linkage->Size ? 0 : CALL_MEMBER_FN(this, AVS_linkage->argOpt)() ) : \ CALL_MEMBER_FN(this, AVS_linkage->arg)() ) // AVS_LinkCallOptDefault puts automatically () only after arg # define AVS_LinkCallOptDefault(arg, argDefaultValue) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? (argDefaultValue) : ((this->*(AVS_linkage->arg))()) #endif class PDevice { public: PDevice() AVS_BakedCode(AVS_LinkCall_Void(PDevice_CONSTRUCTOR0)()) PDevice(Device* p) AVS_BakedCode(AVS_LinkCall_Void(PDevice_CONSTRUCTOR1)(p)) PDevice(const PDevice& p) AVS_BakedCode(AVS_LinkCall_Void(PDevice_CONSTRUCTOR2)(p)) PDevice& operator=(Device* p) AVS_BakedCode(return AVS_LinkCallV(PDevice_OPERATOR_ASSIGN0)(p)) PDevice& operator=(const PDevice& p) AVS_BakedCode(return AVS_LinkCallV(PDevice_OPERATOR_ASSIGN1)(p)) ~PDevice() AVS_BakedCode(AVS_LinkCall_Void(PDevice_DESTRUCTOR)()) int operator!() const { return !e; } operator void*() const { return e; } Device* operator->() const { return e; } AvsDeviceType GetType() const AVS_BakedCode(return AVS_LinkCallOptDefault(PDevice_GetType, DEV_TYPE_NONE)) int GetId() const AVS_BakedCode(return AVS_LinkCall(PDevice_GetId)()) int GetIndex() const AVS_BakedCode(return AVS_LinkCall(PDevice_GetIndex)()) const char* GetName() const AVS_BakedCode(return AVS_LinkCall(PDevice_GetName)()) private: Device * e; #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(Device* p); void CONSTRUCTOR2(const PDevice& p); PDevice& OPERATOR_ASSIGN0(Device* p); PDevice& OPERATOR_ASSIGN1(const PDevice& p); void DESTRUCTOR(); #endif }; // Unshifted channel mask constants like in WAVEFORMATEXTENSIBLE // in AvsImageTypeFlags they are shifted by 4 bits enum AvsChannelMask { MASK_SPEAKER_FRONT_LEFT = 0x1, MASK_SPEAKER_FRONT_RIGHT = 0x2, MASK_SPEAKER_FRONT_CENTER = 0x4, MASK_SPEAKER_LOW_FREQUENCY = 0x8, MASK_SPEAKER_BACK_LEFT = 0x10, MASK_SPEAKER_BACK_RIGHT = 0x20, MASK_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40, MASK_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80, MASK_SPEAKER_BACK_CENTER = 0x100, MASK_SPEAKER_SIDE_LEFT = 0x200, MASK_SPEAKER_SIDE_RIGHT = 0x400, MASK_SPEAKER_TOP_CENTER = 0x800, MASK_SPEAKER_TOP_FRONT_LEFT = 0x1000, MASK_SPEAKER_TOP_FRONT_CENTER = 0x2000, MASK_SPEAKER_TOP_FRONT_RIGHT = 0x4000, MASK_SPEAKER_TOP_BACK_LEFT = 0x8000, MASK_SPEAKER_TOP_BACK_CENTER = 0x10000, MASK_SPEAKER_TOP_BACK_RIGHT = 0x20000, // Bit mask locations used up for the above positions MASK_SPEAKER_DEFINED = 0x0003FFFF, // Bit mask locations reserved for future use MASK_SPEAKER_RESERVED = 0x7FFC0000, // Used to specify that any possible permutation of speaker configurations // Due to lack of available bits this one is put differently into image_type MASK_SPEAKER_ALL = 0x80000000 }; struct VideoInfo { int width, height; // width 0 means no video unsigned fps_numerator, fps_denominator; int num_frames; // This is more extensible than previous versions. More properties can be added seamlessly. // Colorspace properties. /* Planar match mask 1111.1000.0000.0111.0000.0111.0000.0111 Planar signature 10xx.1000.0000.00xx.0000.00xx.00xx.00xx ? Planar signature 10xx.1000.0000.0xxx.0000.00xx.000x.x0xx ? *new Planar filter mask 1111.1111.1111.1111.1111.1111.1110.0111 (typo from old header fixed) pixel_type mapping ================== pixel_type bit-map PIYB.Z000.0???.0SSS.0000.0???.????.???? planar YUV CCC HHH.000u.vWWW planar RGB(A) CCC AR nonplanar CCC 000.00wx xyAR Legend ====== Planar YUV: Code Bits Remark W 0-2 Planar Width Subsampling bits Use (X+1) & 3 for GetPlaneWidthSubsampling 000 => 1 YV12, YV16, YUV420, YUV422 001 => 2 YV411, YUV9 010 => reserved 011 => 0 YV24, YUV444, RGBP 1xx => reserved v 3 VPlaneFirst YV12, YV16, YV24, YV411, YUV9 u 4 UPlaneFirst I420 H 7-9 Planar Height Subsampling bits Use ((X>>8)+1) & 3 for GetPlaneHeightSubsampling 000 => 1 YV12, YUV420 001 => 2 YUV9 010 => reserved 011 => 0 YV16, YV24, YV411, YUV422, YUV444, RGBP 1xx => reserved Planar RGB Code Bits Remark R 0 BGR, (with SSS bits for 8/16 bit/sample or float) A 1 BGRA, (with SSS bits for 8/16 bit/sample or float) Not Planar, Interleaved (I flag) Code Bits Remark R 0 BGR24, and BGRx in future (with SSS bits for 8/16 bit/sample or float) A 1 BGR32, and BGRAx in future (with SSS bits for 8/16 bit/sample or float) y 2 YUY2 x 3-4 reserved w 5 Raw32 General Code Bits Remark S 16-18 Sample resolution bits 000 => 8 001 => 16 010 => 32 (float) 011,100 => reserved 101 => 10 bits 110 => 12 bits 111 => 14 bits for packed RGB(A): only 8 and 16 bits are valid Other YV12 specific (will never be used) C 20-23 Chroma Placement values 0-4; see CS_xxx_CHROMA_PLACEMENT Color family and layout Packed Planar Planar Planar Code Bits Remark RGB/RGBA YUV YUY2 Y_Grey RGB/RGBA YUVA R 0 1/0 - 0 - 1/0 - A 1 0/1 - 0 - 0/1 - y 2 - - 1 - 0 - Z 27 YUVA 0 0 0 0 1 1 B 28 BGR 1 0 0 0 1* 0 Y 29 YUV 0 1 1 1 0 0 I 30 Interleaved 1 0 1 1 0 0 P 31 Planar 0 1 0 1 1 1 * Planar RGB plane order: G,B,R(,A) */ enum AvsColorFormat { CS_YUVA = 1 << 27, CS_BGR = 1 << 28, CS_YUV = 1 << 29, CS_INTERLEAVED = 1 << 30, CS_PLANAR = 1 << 31, CS_Shift_Sub_Width = 0, CS_Shift_Sub_Height = 8, CS_Shift_Sample_Bits = 16, CS_Sub_Width_Mask = 7 << CS_Shift_Sub_Width, CS_Sub_Width_1 = 3 << CS_Shift_Sub_Width, // YV24 CS_Sub_Width_2 = 0 << CS_Shift_Sub_Width, // YV12, I420, YV16 CS_Sub_Width_4 = 1 << CS_Shift_Sub_Width, // YUV9, YV411 CS_VPlaneFirst = 1 << 3, // YV12, YV16, YV24, YV411, YUV9 CS_UPlaneFirst = 1 << 4, // I420 CS_Sub_Height_Mask = 7 << CS_Shift_Sub_Height, CS_Sub_Height_1 = 3 << CS_Shift_Sub_Height, // YV16, YV24, YV411 CS_Sub_Height_2 = 0 << CS_Shift_Sub_Height, // YV12, I420 CS_Sub_Height_4 = 1 << CS_Shift_Sub_Height, // YUV9 CS_Sample_Bits_Mask = 7 << CS_Shift_Sample_Bits, CS_Sample_Bits_8 = 0 << CS_Shift_Sample_Bits, CS_Sample_Bits_10 = 5 << CS_Shift_Sample_Bits, CS_Sample_Bits_12 = 6 << CS_Shift_Sample_Bits, CS_Sample_Bits_14 = 7 << CS_Shift_Sample_Bits, CS_Sample_Bits_16 = 1 << CS_Shift_Sample_Bits, CS_Sample_Bits_32 = 2 << CS_Shift_Sample_Bits, CS_PLANAR_MASK = CS_PLANAR | CS_INTERLEAVED | CS_YUV | CS_BGR | CS_YUVA | CS_Sample_Bits_Mask | CS_Sub_Width_Mask | CS_Sub_Height_Mask, CS_PLANAR_FILTER = ~(CS_VPlaneFirst | CS_UPlaneFirst), CS_RGB_TYPE = 1 << 0, CS_RGBA_TYPE = 1 << 1, // Specific colorformats CS_UNKNOWN = 0, CS_BGR24 = CS_RGB_TYPE | CS_BGR | CS_INTERLEAVED, CS_BGR32 = CS_RGBA_TYPE | CS_BGR | CS_INTERLEAVED, CS_YUY2 = 1 << 2 | CS_YUV | CS_INTERLEAVED, // CS_YV12 = 1 << 3 Reserved // CS_I420 = 1 << 4 Reserved CS_RAW32 = 1 << 5 | CS_INTERLEAVED, // YV12 must be 0xA0000008. v2.5 Baked API will see all new planar as YV12. // I420 must be 0xA0000010. CS_GENERIC_YUV444 = CS_PLANAR | CS_YUV | CS_VPlaneFirst | CS_Sub_Width_1 | CS_Sub_Height_1, // 4:4:4 planar CS_GENERIC_YUV422 = CS_PLANAR | CS_YUV | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_1, // 4:2:2 planar CS_GENERIC_YUV420 = CS_PLANAR | CS_YUV | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_2, // 4:2:0 planar CS_GENERIC_Y = CS_PLANAR | CS_INTERLEAVED | CS_YUV, // Y only (4:0:0) CS_GENERIC_RGBP = CS_PLANAR | CS_BGR | CS_RGB_TYPE, // planar RGB. Though name is RGB but plane order G,B,R CS_GENERIC_RGBAP = CS_PLANAR | CS_BGR | CS_RGBA_TYPE, // planar RGBA CS_GENERIC_YUVA444 = CS_PLANAR | CS_YUVA | CS_VPlaneFirst | CS_Sub_Width_1 | CS_Sub_Height_1, // 4:4:4:A planar CS_GENERIC_YUVA422 = CS_PLANAR | CS_YUVA | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_1, // 4:2:2:A planar CS_GENERIC_YUVA420 = CS_PLANAR | CS_YUVA | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_2, // 4:2:0:A planar CS_YV24 = CS_GENERIC_YUV444 | CS_Sample_Bits_8, // YVU 4:4:4 planar CS_YV16 = CS_GENERIC_YUV422 | CS_Sample_Bits_8, // YVU 4:2:2 planar CS_YV12 = CS_GENERIC_YUV420 | CS_Sample_Bits_8, // YVU 4:2:0 planar CS_I420 = CS_PLANAR | CS_YUV | CS_Sample_Bits_8 | CS_UPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_2, // YUV 4:2:0 planar CS_IYUV = CS_I420, CS_YUV9 = CS_PLANAR | CS_YUV | CS_Sample_Bits_8 | CS_VPlaneFirst | CS_Sub_Width_4 | CS_Sub_Height_4, // YUV 4:1:0 planar CS_YV411 = CS_PLANAR | CS_YUV | CS_Sample_Bits_8 | CS_VPlaneFirst | CS_Sub_Width_4 | CS_Sub_Height_1, // YUV 4:1:1 planar CS_Y8 = CS_GENERIC_Y | CS_Sample_Bits_8, // Y 4:0:0 planar //------------------------- // AVS16: new planar constants go live! Experimental PF 160613 // 10-12-14 bit + planar RGB + BRG48/64 160725 CS_YUV444P10 = CS_GENERIC_YUV444 | CS_Sample_Bits_10, // YUV 4:4:4 10bit samples CS_YUV422P10 = CS_GENERIC_YUV422 | CS_Sample_Bits_10, // YUV 4:2:2 10bit samples CS_YUV420P10 = CS_GENERIC_YUV420 | CS_Sample_Bits_10, // YUV 4:2:0 10bit samples CS_Y10 = CS_GENERIC_Y | CS_Sample_Bits_10, // Y 4:0:0 10bit samples CS_YUV444P12 = CS_GENERIC_YUV444 | CS_Sample_Bits_12, // YUV 4:4:4 12bit samples CS_YUV422P12 = CS_GENERIC_YUV422 | CS_Sample_Bits_12, // YUV 4:2:2 12bit samples CS_YUV420P12 = CS_GENERIC_YUV420 | CS_Sample_Bits_12, // YUV 4:2:0 12bit samples CS_Y12 = CS_GENERIC_Y | CS_Sample_Bits_12, // Y 4:0:0 12bit samples CS_YUV444P14 = CS_GENERIC_YUV444 | CS_Sample_Bits_14, // YUV 4:4:4 14bit samples CS_YUV422P14 = CS_GENERIC_YUV422 | CS_Sample_Bits_14, // YUV 4:2:2 14bit samples CS_YUV420P14 = CS_GENERIC_YUV420 | CS_Sample_Bits_14, // YUV 4:2:0 14bit samples CS_Y14 = CS_GENERIC_Y | CS_Sample_Bits_14, // Y 4:0:0 14bit samples CS_YUV444P16 = CS_GENERIC_YUV444 | CS_Sample_Bits_16, // YUV 4:4:4 16bit samples CS_YUV422P16 = CS_GENERIC_YUV422 | CS_Sample_Bits_16, // YUV 4:2:2 16bit samples CS_YUV420P16 = CS_GENERIC_YUV420 | CS_Sample_Bits_16, // YUV 4:2:0 16bit samples CS_Y16 = CS_GENERIC_Y | CS_Sample_Bits_16, // Y 4:0:0 16bit samples // 32 bit samples (float) CS_YUV444PS = CS_GENERIC_YUV444 | CS_Sample_Bits_32, // YUV 4:4:4 32bit samples CS_YUV422PS = CS_GENERIC_YUV422 | CS_Sample_Bits_32, // YUV 4:2:2 32bit samples CS_YUV420PS = CS_GENERIC_YUV420 | CS_Sample_Bits_32, // YUV 4:2:0 32bit samples CS_Y32 = CS_GENERIC_Y | CS_Sample_Bits_32, // Y 4:0:0 32bit samples // RGB packed CS_BGR48 = CS_RGB_TYPE | CS_BGR | CS_INTERLEAVED | CS_Sample_Bits_16, // BGR 3x16 bit CS_BGR64 = CS_RGBA_TYPE | CS_BGR | CS_INTERLEAVED | CS_Sample_Bits_16, // BGR 4x16 bit // no packed 32 bit (float) support for these legacy types // RGB planar CS_RGBP = CS_GENERIC_RGBP | CS_Sample_Bits_8, // Planar RGB 8 bit samples CS_RGBP8 = CS_GENERIC_RGBP | CS_Sample_Bits_8, // Planar RGB 8 bit samples CS_RGBP10 = CS_GENERIC_RGBP | CS_Sample_Bits_10, // Planar RGB 10bit samples CS_RGBP12 = CS_GENERIC_RGBP | CS_Sample_Bits_12, // Planar RGB 12bit samples CS_RGBP14 = CS_GENERIC_RGBP | CS_Sample_Bits_14, // Planar RGB 14bit samples CS_RGBP16 = CS_GENERIC_RGBP | CS_Sample_Bits_16, // Planar RGB 16bit samples CS_RGBPS = CS_GENERIC_RGBP | CS_Sample_Bits_32, // Planar RGB 32bit samples // RGBA planar CS_RGBAP = CS_GENERIC_RGBAP | CS_Sample_Bits_8, // Planar RGBA 8 bit samples CS_RGBAP8 = CS_GENERIC_RGBAP | CS_Sample_Bits_8, // Planar RGBA 8 bit samples CS_RGBAP10 = CS_GENERIC_RGBAP | CS_Sample_Bits_10, // Planar RGBA 10bit samples CS_RGBAP12 = CS_GENERIC_RGBAP | CS_Sample_Bits_12, // Planar RGBA 12bit samples CS_RGBAP14 = CS_GENERIC_RGBAP | CS_Sample_Bits_14, // Planar RGBA 14bit samples CS_RGBAP16 = CS_GENERIC_RGBAP | CS_Sample_Bits_16, // Planar RGBA 16bit samples CS_RGBAPS = CS_GENERIC_RGBAP | CS_Sample_Bits_32, // Planar RGBA 32bit samples // Planar YUVA CS_YUVA444 = CS_GENERIC_YUVA444 | CS_Sample_Bits_8, // YUVA 4:4:4 8bit samples CS_YUVA422 = CS_GENERIC_YUVA422 | CS_Sample_Bits_8, // YUVA 4:2:2 8bit samples CS_YUVA420 = CS_GENERIC_YUVA420 | CS_Sample_Bits_8, // YUVA 4:2:0 8bit samples CS_YUVA444P10 = CS_GENERIC_YUVA444 | CS_Sample_Bits_10, // YUVA 4:4:4 10bit samples CS_YUVA422P10 = CS_GENERIC_YUVA422 | CS_Sample_Bits_10, // YUVA 4:2:2 10bit samples CS_YUVA420P10 = CS_GENERIC_YUVA420 | CS_Sample_Bits_10, // YUVA 4:2:0 10bit samples CS_YUVA444P12 = CS_GENERIC_YUVA444 | CS_Sample_Bits_12, // YUVA 4:4:4 12bit samples CS_YUVA422P12 = CS_GENERIC_YUVA422 | CS_Sample_Bits_12, // YUVA 4:2:2 12bit samples CS_YUVA420P12 = CS_GENERIC_YUVA420 | CS_Sample_Bits_12, // YUVA 4:2:0 12bit samples CS_YUVA444P14 = CS_GENERIC_YUVA444 | CS_Sample_Bits_14, // YUVA 4:4:4 14bit samples CS_YUVA422P14 = CS_GENERIC_YUVA422 | CS_Sample_Bits_14, // YUVA 4:2:2 14bit samples CS_YUVA420P14 = CS_GENERIC_YUVA420 | CS_Sample_Bits_14, // YUVA 4:2:0 14bit samples CS_YUVA444P16 = CS_GENERIC_YUVA444 | CS_Sample_Bits_16, // YUVA 4:4:4 16bit samples CS_YUVA422P16 = CS_GENERIC_YUVA422 | CS_Sample_Bits_16, // YUVA 4:2:2 16bit samples CS_YUVA420P16 = CS_GENERIC_YUVA420 | CS_Sample_Bits_16, // YUVA 4:2:0 16bit samples CS_YUVA444PS = CS_GENERIC_YUVA444 | CS_Sample_Bits_32, // YUVA 4:4:4 32bit samples CS_YUVA422PS = CS_GENERIC_YUVA422 | CS_Sample_Bits_32, // YUVA 4:2:2 32bit samples CS_YUVA420PS = CS_GENERIC_YUVA420 | CS_Sample_Bits_32, // YUVA 4:2:0 32bit samples }; int pixel_type; // changed to int as of 2.5 int audio_samples_per_second; // 0 means no audio int sample_type; // as of 2.5 int64_t num_audio_samples; // changed as of 2.5 int nchannels; // as of 2.5 // BFF, TFF, FIELDBASED. Also used for storing Channel Mask int image_type; enum AvsImageTypeFlags { IT_BFF = 1 << 0, IT_TFF = 1 << 1, IT_FIELDBASED = 1 << 2, // Audio channel mask support IT_HAS_CHANNELMASK = 1 << 3, // shifted by 4 bits compared to WAVEFORMATEXTENSIBLE dwChannelMask // otherwise same as AvsChannelMask IT_SPEAKER_FRONT_LEFT = 0x1 << 4, IT_SPEAKER_FRONT_RIGHT = 0x2 << 4, IT_SPEAKER_FRONT_CENTER = 0x4 << 4, IT_SPEAKER_LOW_FREQUENCY = 0x8 << 4, IT_SPEAKER_BACK_LEFT = 0x10 << 4, IT_SPEAKER_BACK_RIGHT = 0x20 << 4, IT_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40 << 4, IT_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80 << 4, IT_SPEAKER_BACK_CENTER = 0x100 << 4, IT_SPEAKER_SIDE_LEFT = 0x200 << 4, IT_SPEAKER_SIDE_RIGHT = 0x400 << 4, IT_SPEAKER_TOP_CENTER = 0x800 << 4, IT_SPEAKER_TOP_FRONT_LEFT = 0x1000 << 4, IT_SPEAKER_TOP_FRONT_CENTER = 0x2000 << 4, IT_SPEAKER_TOP_FRONT_RIGHT = 0x4000 << 4, IT_SPEAKER_TOP_BACK_LEFT = 0x8000 << 4, IT_SPEAKER_TOP_BACK_CENTER = 0x10000 << 4, IT_SPEAKER_TOP_BACK_RIGHT = 0x20000 << 4, // End of officially defined speaker bits // The next one is special, since cannot shift SPEAKER_ALL 0x80000000 further. // Set mask and get mask handles it. IT_SPEAKER_ALL = 0x40000 << 4, // Mask for the defined 18 bits + SPEAKER_ALL IT_SPEAKER_BITS_MASK = (AvsChannelMask::MASK_SPEAKER_DEFINED << 4) | IT_SPEAKER_ALL, IT_NEXT_AVAILABLE = 1 << 23 }; // Chroma placement bits 20 -> 23 ::FIXME:: Really want a Class to support this enum AvsChromaPlacement { CS_UNKNOWN_CHROMA_PLACEMENT = 0 << 20, CS_MPEG1_CHROMA_PLACEMENT = 1 << 20, CS_MPEG2_CHROMA_PLACEMENT = 2 << 20, CS_YUY2_CHROMA_PLACEMENT = 3 << 20, CS_TOPLEFT_CHROMA_PLACEMENT = 4 << 20 }; // useful functions of the above bool HasVideo() const AVS_BakedCode(return AVS_LinkCall(HasVideo)()) bool HasAudio() const AVS_BakedCode(return AVS_LinkCall(HasAudio)()) bool IsRGB() const AVS_BakedCode(return AVS_LinkCall(IsRGB)()) bool IsRGB24() const AVS_BakedCode(return AVS_LinkCall(IsRGB24)()) bool IsRGB32() const AVS_BakedCode(return AVS_LinkCall(IsRGB32)()) bool IsYUV() const AVS_BakedCode(return AVS_LinkCall(IsYUV)()) bool IsYUY2() const AVS_BakedCode(return AVS_LinkCall(IsYUY2)()) bool IsYV24() const AVS_BakedCode(return AVS_LinkCall(IsYV24)()) bool IsYV16() const AVS_BakedCode(return AVS_LinkCall(IsYV16)()) bool IsYV12() const AVS_BakedCode(return AVS_LinkCall(IsYV12)()) bool IsYV411() const AVS_BakedCode(return AVS_LinkCall(IsYV411)()) //bool IsYUV9() const; bool IsY8() const AVS_BakedCode(return AVS_LinkCall(IsY8)()) bool IsColorSpace(int c_space) const AVS_BakedCode(return AVS_LinkCall(IsColorSpace)(c_space)) bool Is(int property) const AVS_BakedCode(return AVS_LinkCall(Is)(property)) bool IsPlanar() const AVS_BakedCode(return AVS_LinkCall(IsPlanar)()) bool IsFieldBased() const AVS_BakedCode(return AVS_LinkCall(IsFieldBased)()) bool IsParityKnown() const AVS_BakedCode(return AVS_LinkCall(IsParityKnown)()) bool IsBFF() const AVS_BakedCode(return AVS_LinkCall(IsBFF)()) bool IsTFF() const AVS_BakedCode(return AVS_LinkCall(IsTFF)()) bool IsVPlaneFirst() const AVS_BakedCode(return AVS_LinkCall(IsVPlaneFirst)()) // Don't use this // Will not work on planar images, but will return only luma planes int BytesFromPixels(int pixels) const AVS_BakedCode(return AVS_LinkCall(BytesFromPixels)(pixels)) int RowSize(int plane = DEFAULT_PLANE) const AVS_BakedCode(return AVS_LinkCall(RowSize)(plane)) int BMPSize() const AVS_BakedCode(return AVS_LinkCall(BMPSize)()) int64_t AudioSamplesFromFrames(int frames) const AVS_BakedCode(return AVS_LinkCall(AudioSamplesFromFrames)(frames)) int FramesFromAudioSamples(int64_t samples) const AVS_BakedCode(return AVS_LinkCall(FramesFromAudioSamples)(samples)) int64_t AudioSamplesFromBytes(int64_t bytes) const AVS_BakedCode(return AVS_LinkCall(AudioSamplesFromBytes)(bytes)) int64_t BytesFromAudioSamples(int64_t samples) const AVS_BakedCode(return AVS_LinkCall(BytesFromAudioSamples)(samples)) int AudioChannels() const AVS_BakedCode(return AVS_LinkCall(AudioChannels)()) int SampleType() const AVS_BakedCode(return AVS_LinkCall(SampleType)()) bool IsSampleType(int testtype) const AVS_BakedCode(return AVS_LinkCall(IsSampleType)(testtype)) int SamplesPerSecond() const AVS_BakedCode(return AVS_LinkCall(SamplesPerSecond)()) int BytesPerAudioSample() const AVS_BakedCode(return AVS_LinkCall(BytesPerAudioSample)()) void SetFieldBased(bool isfieldbased) AVS_BakedCode(AVS_LinkCall_Void(SetFieldBased)(isfieldbased)) void Set(int property) AVS_BakedCode(AVS_LinkCall_Void(Set)(property)) void Clear(int property) AVS_BakedCode(AVS_LinkCall_Void(Clear)(property)) // Subsampling in bitshifts! int GetPlaneWidthSubsampling(int plane) const AVS_BakedCode(return AVS_LinkCall(GetPlaneWidthSubsampling)(plane)) int GetPlaneHeightSubsampling(int plane) const AVS_BakedCode(return AVS_LinkCall(GetPlaneHeightSubsampling)(plane)) int BitsPerPixel() const AVS_BakedCode(return AVS_LinkCall(BitsPerPixel)()) int BytesPerChannelSample() const AVS_BakedCode(return AVS_LinkCall(BytesPerChannelSample)()) // useful mutator void SetFPS(unsigned numerator, unsigned denominator) AVS_BakedCode(AVS_LinkCall_Void(SetFPS)(numerator, denominator)) // Range protected multiply-divide of FPS void MulDivFPS(unsigned multiplier, unsigned divisor) AVS_BakedCode(AVS_LinkCall_Void(MulDivFPS)(multiplier, divisor)) // Test for same colorspace bool IsSameColorspace(const VideoInfo& vi) const AVS_BakedCode(return AVS_LinkCall(IsSameColorspace)(vi)) // AVS+ extensions // 20161005: // Mapping of AVS+ extensions to classic 2.6 functions. // In order to use these extended AVS+ functions for plugins that should work // either with AVS+ or with Classic (8 bit) Avs 2.6 ans earlier AVS+ versions, there is an // automatic fallback mechanism. // From AVS+'s point of view these are not "baked" codes, the primary functions should exist. // Examples: // Is444() is mapped to IsYV24() for classic AVS2.6 // ComponentSize() returns constant 1 (1 bytes per pixel component) // BitsPerComponent() returns constant 8 (Classic AVS2.6 is 8 bit only) // Returns the number of color channels or planes in a frame int NumComponents() const AVS_BakedCode(return AVS_LinkCallOptDefault(NumComponents, (((AVS_LinkCall(IsYUV)()) && !(AVS_LinkCall(IsY8)())) ? 3 : AVS_LinkCall(BytesFromPixels)(1)) ) ) // Returns the size in bytes of a single component of a pixel int ComponentSize() const AVS_BakedCode(return AVS_LinkCallOptDefault(ComponentSize, 1)) // Returns the bit depth of a single component of a pixel int BitsPerComponent() const AVS_BakedCode(return AVS_LinkCallOptDefault(BitsPerComponent, 8)) // like IsYV24, but bit-depth independent also for YUVA bool Is444() const AVS_BakedCode(return AVS_LinkCallOpt(Is444, IsYV24) ) // like IsYV16, but bit-depth independent also for YUVA bool Is422() const AVS_BakedCode(return AVS_LinkCallOpt(Is422, IsYV16) ) // like IsYV12, but bit-depth independent also for YUVA bool Is420() const AVS_BakedCode( return AVS_LinkCallOpt(Is420, IsYV12) ) // like IsY8, but bit-depth independent bool IsY() const AVS_BakedCode( return AVS_LinkCallOpt(IsY, IsY8) ) // like IsRGB24 for 16 bit samples bool IsRGB48() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsRGB48, false) ) // like IsRGB32 for 16 bit samples bool IsRGB64() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsRGB64, false) ) // YUVA? bool IsYUVA() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsYUVA, false) ) // Planar RGB? bool IsPlanarRGB() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsPlanarRGB, false) ) // Planar RGBA? bool IsPlanarRGBA() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsPlanarRGBA, false) ) // v10.1 interface: audio channel masks bool IsChannelMaskKnown() const AVS_BakedCode(return AVS_LinkCallOptDefault(IsChannelMaskKnown, false) ) void SetChannelMask(bool isChannelMaskKnown, unsigned int dwChannelMask) AVS_BakedCode(AVS_LinkCall_Void(SetChannelMask)(isChannelMaskKnown, dwChannelMask)) unsigned int GetChannelMask() const AVS_BakedCode(return AVS_LinkCallOptDefault(GetChannelMask, 0) ) }; // end struct VideoInfo // VideoFrameBuffer holds information about a memory block which is used // for video data. For efficiency, instances of this class are not deleted // when the refcount reaches zero; instead they're stored in a linked list // to be reused. The instances are deleted when the corresponding AVS // file is closed. class VideoFrameBuffer { BYTE* data; int data_size; // sequence_number is incremented every time the buffer is changed, so // that stale views can tell they're no longer valid. volatile long sequence_number; friend class VideoFrame; friend class Cache; friend class ScriptEnvironment; volatile long refcount; // AVS+CUDA extension, does not break plugins if appended here Device* device; protected: VideoFrameBuffer(int size, int margin, Device* device); VideoFrameBuffer(); public: ~VideoFrameBuffer() AVS_BakedCode(AVS_LinkCall_Void(VideoFrameBuffer_DESTRUCTOR)()) const BYTE* GetReadPtr() const AVS_BakedCode( return AVS_LinkCall(VFBGetReadPtr)() ) BYTE* GetWritePtr() AVS_BakedCode( return AVS_LinkCall(VFBGetWritePtr)() ) int GetDataSize() const AVS_BakedCode( return AVS_LinkCall(GetDataSize)() ) int GetSequenceNumber() const AVS_BakedCode( return AVS_LinkCall(GetSequenceNumber)() ) int GetRefcount() const AVS_BakedCode( return AVS_LinkCall(GetRefcount)() ) // Ensure VideoFrameBuffer cannot be publicly assigned private: VideoFrameBuffer& operator=(const VideoFrameBuffer&); #ifdef BUILDING_AVSCORE public: void DESTRUCTOR(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ #endif }; // end class VideoFrameBuffer // smart pointer to VideoFrame class PVideoFrame { VideoFrame* p; void Init(VideoFrame* x); void Set(VideoFrame* x); public: PVideoFrame() AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_CONSTRUCTOR0)()) PVideoFrame(const PVideoFrame& x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_CONSTRUCTOR1)(x)) PVideoFrame(VideoFrame* x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_CONSTRUCTOR2)(x)) void operator=(VideoFrame* x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_OPERATOR_ASSIGN0)(x)) void operator=(const PVideoFrame& x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_OPERATOR_ASSIGN1)(x)) VideoFrame* operator->() const { return p; } // for conditional expressions operator void*() const { return p; } bool operator!() const { return !p; } ~PVideoFrame() AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_DESTRUCTOR)()) #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(const PVideoFrame& x); void CONSTRUCTOR2(VideoFrame* x); void OPERATOR_ASSIGN0(VideoFrame* x); void OPERATOR_ASSIGN1(const PVideoFrame& x); void DESTRUCTOR(); #endif }; // end class PVideoFrame // VideoFrame holds a "window" into a VideoFrameBuffer. Operator new // is overloaded to recycle class instances. class VideoFrame { volatile long refcount; VideoFrameBuffer* vfb; // Due to technical reasons these members are not const, but should be treated as such. // That means do not modify them once the class has been constructed. int offset; int pitch, row_size, height; int offsetU, offsetV; // U&V offsets are from top of picture. int pitchUV, row_sizeUV, heightUV; // for Planar RGB offsetU, offsetV is for the 2nd and 3rd Plane. // for Planar RGB pitchUV and row_sizeUV = 0, because when no VideoInfo (MakeWriteable) // the decision on existance of UV is checked by zero pitch // AVS+ extension, does not break plugins if appended here int offsetA; int pitchA, row_sizeA; // 4th alpha plane support, pitch and row_size is 0 is none AVSMap *properties; // this one is changable by AmendPixelType in rare cases int pixel_type; // V10 - Copy from VideoInfo friend class PVideoFrame; void AddRef(); void Release(); friend class ScriptEnvironment; friend class Cache; VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height, int _pixel_type); VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height, int _offsetU, int _offsetV, int _pitchUV, int _row_sizeUV, int _heightUV, int _pixel_type); // for Alpha VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height, int _offsetU, int _offsetV, int _pitchUV, int _row_sizeUV, int _heightUV, int _offsetA, int _pixel_type); void* operator new(size_t size); // TESTME: OFFSET U/V may be switched to what could be expected from AVI standard! public: int GetPitch(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetPitch)(plane) ) int GetRowSize(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetRowSize)(plane) ) int GetHeight(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetHeight)(plane) ) // generally you shouldn't use these three VideoFrameBuffer* GetFrameBuffer() const AVS_BakedCode( return AVS_LinkCall(GetFrameBuffer)() ) int GetOffset(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetOffset)(plane) ) // in plugins use env->SubFrame() -- because implementation code is only available inside avisynth.dll. Doh! VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height) const; VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int pitchUV) const; // for Alpha VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int pitchUV, int rel_offsetA) const; const BYTE* GetReadPtr(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(VFGetReadPtr)(plane) ) bool IsWritable() const AVS_BakedCode( return AVS_LinkCall(IsWritable)() ) BYTE* GetWritePtr(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(VFGetWritePtr)(plane) ) AVSMap& getProperties() AVS_BakedCode(return AVS_LinkCallOptDefault(getProperties, (AVSMap&)*(AVSMap*)0)) const AVSMap& getConstProperties() AVS_BakedCode(return AVS_LinkCallOptDefault(getConstProperties, (const AVSMap&)*(const AVSMap*)0)) void setProperties(const AVSMap & _properties) AVS_BakedCode(AVS_LinkCall_Void(setProperties)(_properties)) PDevice GetDevice() const AVS_BakedCode(return AVS_LinkCall(VideoFrame_GetDevice)()) // 0: OK, 1: NG, -1: disabled or non CPU frame int CheckMemory() const AVS_BakedCode(return AVS_LinkCall(VideoFrame_CheckMemory)()) bool IsPropertyWritable() const AVS_BakedCode(return AVS_LinkCall(IsPropertyWritable)()) ~VideoFrame() AVS_BakedCode( AVS_LinkCall_Void(VideoFrame_DESTRUCTOR)() ) int GetPixelType() const AVS_BakedCode(return AVS_LinkCall(VideoFrame_GetPixelType)()) // Changes the color format metadata on this frame. Using it on a frame that isn't writable leads // to an inconsistent state, because other filters depend on it. So, use MakeWritable() before. // Only for rare cases where a plugin makes frame bytes pose as another color format. void AmendPixelType(int new_pixel_type) AVS_BakedCode(return AVS_LinkCall_Void(VideoFrame_AmendPixelType)(new_pixel_type)) #ifdef BUILDING_AVSCORE public: void DESTRUCTOR(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ #endif // Ensure VideoFrame cannot be publicly assigned private: VideoFrame& operator=(const VideoFrame&); }; // end class VideoFrame enum CachePolicyHint { // Values 0 to 5 are reserved for old 2.5 plugins // do not use them in new plugins // New 2.6 explicitly defined cache hints. CACHE_NOTHING = 10, // Do not cache video. CACHE_WINDOW = 11, // Hard protect upto X frames within a range of X from the current frame N. CACHE_GENERIC = 12, // LRU cache upto X frames. CACHE_FORCE_GENERIC = 13, // LRU cache upto X frames, override any previous CACHE_WINDOW. CACHE_GET_POLICY = 30, // Get the current policy. CACHE_GET_WINDOW = 31, // Get the current window h_span. CACHE_GET_RANGE = 32, // Get the current generic frame range. // Set Audio cache mode and answers to CACHE_GETCHILD_AUDIO_MODE CACHE_AUDIO = 50, // Explicitly cache audio, X byte cache. CACHE_AUDIO_NOTHING = 51, // Explicitly do not cache audio. CACHE_AUDIO_NONE = 52, // Audio cache off (auto mode), X byte initial cache. CACHE_AUDIO_AUTO_START_OFF = 52, // synonym CACHE_AUDIO_AUTO = 53, // Audio cache on (auto mode), X byte initial cache. CACHE_AUDIO_AUTO_START_ON = 53, // synonym // These just returns actual value if clip is cached CACHE_GET_AUDIO_POLICY = 70, // Get the current audio policy. CACHE_GET_AUDIO_SIZE = 71, // Get the current audio cache size. CACHE_PREFETCH_FRAME = 100, // n/a Queue request to prefetch frame N. CACHE_PREFETCH_GO = 101, // n/a Action video prefetches. CACHE_PREFETCH_AUDIO_BEGIN = 120, // n/a Begin queue request transaction to prefetch audio (take critical section). CACHE_PREFETCH_AUDIO_STARTLO = 121, // n/a Set low 32 bits of start. CACHE_PREFETCH_AUDIO_STARTHI = 122, // n/a Set high 32 bits of start. CACHE_PREFETCH_AUDIO_COUNT = 123, // n/a Set low 32 bits of length. CACHE_PREFETCH_AUDIO_COMMIT = 124, // n/a Enqueue request transaction to prefetch audio (release critical section). CACHE_PREFETCH_AUDIO_GO = 125, // n/a Action audio prefetches. CACHE_GETCHILD_CACHE_MODE = 200, // n/a Cache ask Child for desired video cache mode. CACHE_GETCHILD_CACHE_SIZE = 201, // n/a Cache ask Child for desired video cache size. // Filters are queried about their desired audio cache mode. // Child can answer them with CACHE_AUDIO_xxx CACHE_GETCHILD_AUDIO_MODE = 202, // Cache ask Child for desired audio cache mode. CACHE_GETCHILD_AUDIO_SIZE = 203, // Cache ask Child for desired audio cache size. CACHE_GETCHILD_COST = 220, // n/a Cache ask Child for estimated processing cost. CACHE_COST_ZERO = 221, // n/a Child response of zero cost (ptr arithmetic only). CACHE_COST_UNIT = 222, // n/a Child response of unit cost (less than or equal 1 full frame blit). CACHE_COST_LOW = 223, // n/a Child response of light cost. (Fast) CACHE_COST_MED = 224, // n/a Child response of medium cost. (Real time) CACHE_COST_HI = 225, // n/a Child response of heavy cost. (Slow) CACHE_GETCHILD_THREAD_MODE = 240, // n/a Cache ask Child for thread safetyness. CACHE_THREAD_UNSAFE = 241, // n/a Only 1 thread allowed for all instances. 2.5 filters default! CACHE_THREAD_CLASS = 242, // n/a Only 1 thread allowed for each instance. 2.6 filters default! CACHE_THREAD_SAFE = 243, // n/a Allow all threads in any instance. CACHE_THREAD_OWN = 244, // n/a Safe but limit to 1 thread, internally threaded. CACHE_GETCHILD_ACCESS_COST = 260, // n/a Cache ask Child for preferred access pattern. CACHE_ACCESS_RAND = 261, // n/a Filter is access order agnostic. CACHE_ACCESS_SEQ0 = 262, // n/a Filter prefers sequential access (low cost) CACHE_ACCESS_SEQ1 = 263, // n/a Filter needs sequential access (high cost) CACHE_AVSPLUS_CONSTANTS = 500, // Smaller values are reserved for classic Avisynth CACHE_DONT_CACHE_ME, // Filters that don't need caching (eg. trim, cache etc.) should return 1 to this request CACHE_SET_MIN_CAPACITY, CACHE_SET_MAX_CAPACITY, CACHE_GET_MIN_CAPACITY, CACHE_GET_MAX_CAPACITY, CACHE_GET_SIZE, CACHE_GET_REQUESTED_CAP, CACHE_GET_CAPACITY, CACHE_GET_MTMODE, // Filters specify their desired MT mode, see enum MtMode // By returning IS_CACHE_ANS to IS_CACHE_REQ, we tell the caller we are a cache CACHE_IS_CACHE_REQ, CACHE_IS_CACHE_ANS, // By returning IS_MTGUARD_ANS to IS_MTGUARD_REQ, we tell the caller we are an mt guard CACHE_IS_MTGUARD_REQ, CACHE_IS_MTGUARD_ANS, CACHE_AVSPLUS_CUDA_CONSTANTS = 600, CACHE_GET_DEV_TYPE, // Device types a filter can return CACHE_GET_CHILD_DEV_TYPE, // Device types a filter can receive CACHE_USER_CONSTANTS = 1000 // Smaller values are reserved for the core }; // Base class for all filters. class IClip { friend class PClip; friend class AVSValue; volatile long refcnt; void AddRef(); #if BUILDING_AVSCORE public: #endif void Release(); public: IClip() : refcnt(0) {} virtual int __stdcall GetVersion() { return AVISYNTH_INTERFACE_VERSION; } virtual PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env) = 0; virtual bool __stdcall GetParity(int n) = 0; // return field parity if field_based, else parity of first field in frame virtual void __stdcall GetAudio(void* buf, int64_t start, int64_t count, IScriptEnvironment* env) = 0; // start and count are in samples /* Need to check GetVersion first, pre v5 will return random crap from EAX reg. */ virtual int __stdcall SetCacheHints(int cachehints,int frame_range) = 0 ; // We do not pass cache requests upwards, only to the next filter. virtual const VideoInfo& __stdcall GetVideoInfo() = 0; virtual ~IClip() {} }; // end class IClip // smart pointer to IClip class PClip { IClip* p; IClip* GetPointerWithAddRef() const; friend class AVSValue; friend class VideoFrame; void Init(IClip* x); void Set(IClip* x); public: PClip() AVS_BakedCode( AVS_LinkCall_Void(PClip_CONSTRUCTOR0)() ) PClip(const PClip& x) AVS_BakedCode( AVS_LinkCall_Void(PClip_CONSTRUCTOR1)(x) ) PClip(IClip* x) AVS_BakedCode( AVS_LinkCall_Void(PClip_CONSTRUCTOR2)(x) ) void operator=(IClip* x) AVS_BakedCode( AVS_LinkCall_Void(PClip_OPERATOR_ASSIGN0)(x) ) void operator=(const PClip& x) AVS_BakedCode( AVS_LinkCall_Void(PClip_OPERATOR_ASSIGN1)(x) ) IClip* operator->() const { return p; } // useful in conditional expressions operator void*() const { return p; } bool operator!() const { return !p; } ~PClip() AVS_BakedCode( AVS_LinkCall_Void(PClip_DESTRUCTOR)() ) #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(const PClip& x); void CONSTRUCTOR2(IClip* x); void OPERATOR_ASSIGN0(IClip* x); void OPERATOR_ASSIGN1(const PClip& x); void DESTRUCTOR(); #endif }; // end class PClip // enums for frame property functions enum AVSPropTypes { PROPTYPE_UNSET = 'u', // ptUnset PROPTYPE_INT = 'i', // peType PROPTYPE_FLOAT = 'f', // ptFloat PROPTYPE_DATA = 's', // ptData PROPTYPE_CLIP = 'c', // ptClip PROPTYPE_FRAME = 'v' // ptFrame // ptFunction = 'm' }; enum AVSGetPropErrors { GETPROPERROR_UNSET = 1, // peUnset GETPROPERROR_TYPE = 2, // peType GETPROPERROR_INDEX = 4 // peIndex }; enum AVSPropAppendMode { PROPAPPENDMODE_REPLACE = 0, // paReplace PROPAPPENDMODE_APPEND = 1, // paAppend PROPAPPENDMODE_TOUCH = 2 // paTouch }; class AVSValue { public: AVSValue() AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR0)() ) AVSValue(IClip* c) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR1)(c) ) AVSValue(const PClip& c) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR2)(c) ) AVSValue(bool b) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR3)(b) ) AVSValue(int i) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR4)(i) ) // AVSValue(int64_t l); AVSValue(float f) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR5)(f) ) AVSValue(double f) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR6)(f) ) AVSValue(const char* s) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR7)(s) ) AVSValue(const AVSValue* a, int size) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR8)(a, size) ) AVSValue(const AVSValue& a, int size) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR8)(&a, size) ) AVSValue(const AVSValue& v) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR9)(v) ) AVSValue(const PFunction& n) AVS_BakedCode(AVS_LinkCall_Void(AVSValue_CONSTRUCTOR11)(n)) ~AVSValue() AVS_BakedCode( AVS_LinkCall_Void(AVSValue_DESTRUCTOR)() ) AVSValue& operator=(const AVSValue& v) AVS_BakedCode( return AVS_LinkCallV(AVSValue_OPERATOR_ASSIGN)(v) ) // Note that we transparently allow 'int' to be treated as 'float'. // There are no int<->bool conversions, though. bool Defined() const AVS_BakedCode( return AVS_LinkCall(Defined)() ) bool IsClip() const AVS_BakedCode( return AVS_LinkCall(IsClip)() ) bool IsBool() const AVS_BakedCode( return AVS_LinkCall(IsBool)() ) bool IsInt() const AVS_BakedCode( return AVS_LinkCall(IsInt)() ) // bool IsLong() const; bool IsFloat() const AVS_BakedCode( return AVS_LinkCall(IsFloat)() ) bool IsString() const AVS_BakedCode( return AVS_LinkCall(IsString)() ) bool IsArray() const AVS_BakedCode( return AVS_LinkCall(IsArray)() ) bool IsFunction() const AVS_BakedCode( return AVS_LinkCall(IsFunction)() ) PClip AsClip() const AVS_BakedCode( return AVS_LinkCall(AsClip)() ) bool AsBool() const AVS_BakedCode( return AVS_LinkCall(AsBool1)() ) int AsInt() const AVS_BakedCode( return AVS_LinkCall(AsInt1)() ) // int AsLong() const; const char* AsString() const AVS_BakedCode( return AVS_LinkCall(AsString1)() ) double AsFloat() const AVS_BakedCode( return AVS_LinkCall(AsFloat1)() ) float AsFloatf() const AVS_BakedCode( return float( AVS_LinkCall(AsFloat1)() ) ) bool AsBool(bool def) const AVS_BakedCode( return AVS_LinkCall(AsBool2)(def) ) int AsInt(int def) const AVS_BakedCode( return AVS_LinkCall(AsInt2)(def) ) double AsDblDef(double def) const AVS_BakedCode( return AVS_LinkCall(AsDblDef)(def) ) // Value is still a float double AsFloat(float def) const AVS_BakedCode( return AVS_LinkCall(AsFloat2)(def) ) float AsFloatf(float def) const AVS_BakedCode( return float( AVS_LinkCall(AsFloat2)(def) ) ) const char* AsString(const char* def) const AVS_BakedCode( return AVS_LinkCall(AsString2)(def) ) PFunction AsFunction() const; // internal use only int ArraySize() const AVS_BakedCode( return AVS_LinkCall(ArraySize)() ) const AVSValue& operator[](int index) const AVS_BakedCode( return AVS_LinkCallV(AVSValue_OPERATOR_INDEX)(index) ) private: short type; // 'a'rray, 'c'lip, 'b'ool, 'i'nt, 'f'loat, 's'tring, 'v'oid, fu'n'ction, or RFU: 'l'ong ('d'ouble) short array_size; union { IClip* clip; bool boolean; int integer; float floating_pt; const char* string; const AVSValue* array; IFunction* function; #ifdef X86_64 // if ever, only x64 will support. It breaks struct size on 32 bit int64_t longlong; // 8 bytes double double_pt; // 8 bytes #endif }; void Assign(const AVSValue* src, bool init); public: AvsValueType GetType() const AVS_BakedCode( return AVS_LinkCallOptDefault(AVSValue_GetType, VALUE_TYPE_UNDEFINED) ) #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(IClip* c); void CONSTRUCTOR2(const PClip& c); void CONSTRUCTOR3(bool b); void CONSTRUCTOR4(int i); void CONSTRUCTOR5(float f); void CONSTRUCTOR6(double f); void CONSTRUCTOR7(const char* s); void CONSTRUCTOR8(const AVSValue* a, int size); void CONSTRUCTOR9(const AVSValue& v); void CONSTRUCTOR11(const PFunction& n); void DESTRUCTOR(); AVSValue& OPERATOR_ASSIGN(const AVSValue& v); const AVSValue& OPERATOR_INDEX(int index) const; bool AsBool1() const; int AsInt1() const; const char* AsString1() const; double AsFloat1() const; bool AsBool2(bool def) const; int AsInt2(int def) const; double AsFloat2(float def) const; const char* AsString2(const char* def) const; void MarkArrayAsC(); // for C interface, no deep-copy and deep-free void CONSTRUCTOR10(const AVSValue& v, bool c_arrays); AVSValue(const AVSValue& v, bool c_arrays); void Assign2(const AVSValue* src, bool init, bool c_arrays); #endif }; // end class AVSValue #define AVS_UNUSED(x) (void)(x) // instantiable null filter class GenericVideoFilter : public IClip { protected: PClip child; VideoInfo vi; public: GenericVideoFilter(PClip _child) : child(_child) { vi = child->GetVideoInfo(); } PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env) { return child->GetFrame(n, env); } void __stdcall GetAudio(void* buf, int64_t start, int64_t count, IScriptEnvironment* env) { child->GetAudio(buf, start, count, env); } const VideoInfo& __stdcall GetVideoInfo() { return vi; } bool __stdcall GetParity(int n) { return child->GetParity(n); } int __stdcall SetCacheHints(int cachehints, int frame_range) { AVS_UNUSED(cachehints); AVS_UNUSED(frame_range); return 0; } // We do not pass cache requests upwards, only to the next filter. }; class PFunction { public: PFunction() AVS_BakedCode(AVS_LinkCall_Void(PFunction_CONSTRUCTOR0)()) PFunction(IFunction* p) AVS_BakedCode(AVS_LinkCall_Void(PFunction_CONSTRUCTOR1)(p)) PFunction(const PFunction& p) AVS_BakedCode(AVS_LinkCall_Void(PFunction_CONSTRUCTOR2)(p)) PFunction& operator=(IFunction* p) AVS_BakedCode(return AVS_LinkCallV(PFunction_OPERATOR_ASSIGN0)(p)) PFunction& operator=(const PFunction& p) AVS_BakedCode(return AVS_LinkCallV(PFunction_OPERATOR_ASSIGN1)(p)) ~PFunction() AVS_BakedCode(AVS_LinkCall_Void(PFunction_DESTRUCTOR)()) int operator!() const { return !e; } operator void*() const { return e; } IFunction* operator->() const { return e; } private: IFunction * e; friend class AVSValue; IFunction * GetPointerWithAddRef() const; void Init(IFunction* p); void Set(IFunction* p); #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(IFunction* p); void CONSTRUCTOR2(const PFunction& p); PFunction& OPERATOR_ASSIGN0(IFunction* p); PFunction& OPERATOR_ASSIGN1(const PFunction& p); void DESTRUCTOR(); #endif }; #undef CALL_MEMBER_FN #undef AVS_LinkCallOptDefault #undef AVS_LinkCallOpt #undef AVS_LinkCallV #undef AVS_LinkCall #undef AVS_BakedCode #include "avs/cpuid.h" // IScriptEnvironment GetEnvProperty enum AvsEnvProperty { AEP_PHYSICAL_CPUS = 1, AEP_LOGICAL_CPUS = 2, AEP_THREADPOOL_THREADS = 3, AEP_FILTERCHAIN_THREADS = 4, AEP_THREAD_ID = 5, AEP_VERSION = 6, AEP_HOST_SYSTEM_ENDIANNESS = 7, AEP_INTERFACE_VERSION = 8, AEP_INTERFACE_BUGFIX = 9, // Neo additionals AEP_NUM_DEVICES = 901, AEP_FRAME_ALIGN = 902, AEP_PLANE_ALIGN = 903, AEP_SUPPRESS_THREAD = 921, AEP_GETFRAME_RECURSIVE = 922, }; // IScriptEnvironment::Allocate() enum AvsAllocType { AVS_NORMAL_ALLOC = 1, AVS_POOLED_ALLOC = 2 }; // Important note (Windows, MSVC): // When extending IScriptEnvironment, do not declare existing names again // with different parameters. Methods with the same name will be grouped // together in the vtable. This results in shifting all vtable method pointers // after such grouping and breaks all plugins who expect the old order. // E.g. ApplyMessage will be called instead of GetAVSLinkage. // As long as the declaration is compatible with COM interop, the order of // declaration is sequential. But if not, overloads in the same class are grouped // together in the vtable in the reverse order of declaration. class IScriptEnvironment { public: virtual ~IScriptEnvironment() {} virtual /*static*/ int __stdcall GetCPUFlags() = 0; virtual char* __stdcall SaveString(const char* s, int length = -1) = 0; virtual char* Sprintf(const char* fmt, ...) = 0; // note: val is really a va_list; I hope everyone typedefs va_list to a pointer // 20200305: (void *) changed back to va_list virtual char* __stdcall VSprintf(const char* fmt, va_list val) = 0; #ifdef AVS_WINDOWS __declspec(noreturn) virtual void ThrowError(const char* fmt, ...) = 0; #else virtual void ThrowError(const char* fmt, ...) = 0; #endif class NotFound /*exception*/ {}; // thrown by Invoke and GetVar typedef AVSValue (__cdecl *ApplyFunc)(AVSValue args, void* user_data, IScriptEnvironment* env); virtual void __stdcall AddFunction(const char* name, const char* params, ApplyFunc apply, void* user_data) = 0; virtual bool __stdcall FunctionExists(const char* name) = 0; virtual AVSValue __stdcall Invoke(const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall GetVar(const char* name) = 0; virtual bool __stdcall SetVar(const char* name, const AVSValue& val) = 0; virtual bool __stdcall SetGlobalVar(const char* name, const AVSValue& val) = 0; virtual void __stdcall PushContext(int level = 0) = 0; virtual void __stdcall PopContext() = 0; // note v8: use NewVideoFrameP is possible virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, int align = FRAME_ALIGN) = 0; virtual bool __stdcall MakeWritable(PVideoFrame* pvf) = 0; virtual void __stdcall BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height) = 0; typedef void (__cdecl *ShutdownFunc)(void* user_data, IScriptEnvironment* env); virtual void __stdcall AtExit(ShutdownFunc function, void* user_data) = 0; virtual void __stdcall CheckVersion(int version = AVISYNTH_INTERFACE_VERSION) = 0; virtual PVideoFrame __stdcall Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height) = 0; virtual int __stdcall SetMemoryMax(int mem) = 0; virtual int __stdcall SetWorkingDir(const char * newdir) = 0; virtual void* __stdcall ManageCache(int key, void* data) = 0; enum PlanarChromaAlignmentMode { PlanarChromaAlignmentOff, PlanarChromaAlignmentOn, PlanarChromaAlignmentTest }; virtual bool __stdcall PlanarChromaAlignment(PlanarChromaAlignmentMode key) = 0; virtual PVideoFrame __stdcall SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV) = 0; // **** AVISYNTH_INTERFACE_VERSION 5 **** defined since classic Avisynth 2.6 beta virtual void __stdcall DeleteScriptEnvironment() = 0; virtual void __stdcall ApplyMessage(PVideoFrame* frame, const VideoInfo& vi, const char* message, int size, int textcolor, int halocolor, int bgcolor) = 0; virtual const AVS_Linkage* __stdcall GetAVSLinkage() = 0; // **** AVISYNTH_INTERFACE_VERSION 6 **** defined since classic Avisynth 2.6 // noThrow version of GetVar virtual AVSValue __stdcall GetVarDef(const char* name, const AVSValue& def = AVSValue()) = 0; // **** AVISYNTH_INTERFACE_VERSION 8 **** AviSynth+ 3.6.0- virtual PVideoFrame __stdcall SubframePlanarA(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA) = 0; virtual void __stdcall copyFrameProps(const PVideoFrame& src, PVideoFrame& dst) = 0; virtual const AVSMap* __stdcall getFramePropsRO(const PVideoFrame& frame) = 0; virtual AVSMap* __stdcall getFramePropsRW(PVideoFrame& frame) = 0; virtual int __stdcall propNumKeys(const AVSMap* map) = 0; virtual const char* __stdcall propGetKey(const AVSMap* map, int index) = 0; virtual int __stdcall propNumElements(const AVSMap* map, const char* key) = 0; virtual char __stdcall propGetType(const AVSMap* map, const char* key) = 0; virtual int64_t __stdcall propGetInt(const AVSMap* map, const char* key, int index, int* error) = 0; virtual double __stdcall propGetFloat(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const char* __stdcall propGetData(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propGetDataSize(const AVSMap* map, const char* key, int index, int* error) = 0; virtual PClip __stdcall propGetClip(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const PVideoFrame __stdcall propGetFrame(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propDeleteKey(AVSMap* map, const char* key) = 0; virtual int __stdcall propSetInt(AVSMap* map, const char* key, int64_t i, int append) = 0; virtual int __stdcall propSetFloat(AVSMap* map, const char* key, double d, int append) = 0; virtual int __stdcall propSetData(AVSMap* map, const char* key, const char* d, int length, int append) = 0; virtual int __stdcall propSetClip(AVSMap* map, const char* key, PClip& clip, int append) = 0; virtual int __stdcall propSetFrame(AVSMap* map, const char* key, const PVideoFrame& frame, int append) = 0; virtual const int64_t* __stdcall propGetIntArray(const AVSMap* map, const char* key, int* error) = 0; virtual const double* __stdcall propGetFloatArray(const AVSMap* map, const char* key, int* error) = 0; virtual int __stdcall propSetIntArray(AVSMap* map, const char* key, const int64_t* i, int size) = 0; virtual int __stdcall propSetFloatArray(AVSMap* map, const char* key, const double* d, int size) = 0; virtual AVSMap* __stdcall createMap() = 0; virtual void __stdcall freeMap(AVSMap* map) = 0; virtual void __stdcall clearMap(AVSMap* map) = 0; // NewVideoFrame with frame property source. virtual PVideoFrame __stdcall NewVideoFrameP(const VideoInfo& vi, const PVideoFrame* prop_src, int align = FRAME_ALIGN) = 0; // Generic query to ask for various system properties virtual size_t __stdcall GetEnvProperty(AvsEnvProperty prop) = 0; // Support functions virtual void* __stdcall Allocate(size_t nBytes, size_t alignment, AvsAllocType type) = 0; virtual void __stdcall Free(void* ptr) = 0; // these GetVar versions (renamed differently) were moved from IScriptEnvironment2 // Returns TRUE and the requested variable. If the method fails, returns FALSE and does not touch 'val'. virtual bool __stdcall GetVarTry(const char* name, AVSValue* val) const = 0; // ex virtual bool __stdcall GetVar(const char* name, AVSValue* val) const = 0; // Return the value of the requested variable. // If the variable was not found or had the wrong type, // return the supplied default value. virtual bool __stdcall GetVarBool(const char* name, bool def) const = 0; virtual int __stdcall GetVarInt(const char* name, int def) const = 0; virtual double __stdcall GetVarDouble(const char* name, double def) const = 0; virtual const char* __stdcall GetVarString(const char* name, const char* def) const = 0; // brand new in v8 - though no real int64 support yet virtual int64_t __stdcall GetVarLong(const char* name, int64_t def) const = 0; // 'Invoke' functions moved here from internal ScriptEnvironments are renamed in order to keep vtable order // Invoke functions with 'Try' will return false instead of throwing NotFound(). // ex-IScriptEnvironment2 virtual bool __stdcall InvokeTry(AVSValue* result, const char* name, const AVSValue& args, const char* const* arg_names = 0) = 0; // Since V8 virtual AVSValue __stdcall Invoke2(const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; // Ex-INeo virtual bool __stdcall Invoke2Try(AVSValue* result, const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall Invoke3(const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; virtual bool __stdcall Invoke3Try(AVSValue* result, const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; // V9 virtual bool __stdcall MakePropertyWritable(PVideoFrame* pvf) = 0; }; // end class IScriptEnvironment. Order is important. Avoid overloads with the same name. // used internally class IScriptEnvironment_Avs25 { public: virtual ~IScriptEnvironment_Avs25() {} virtual /*static*/ int __stdcall GetCPUFlags() = 0; virtual char* __stdcall SaveString(const char* s, int length = -1) = 0; virtual char* Sprintf(const char* fmt, ...) = 0; virtual char* __stdcall VSprintf(const char* fmt, va_list val) = 0; #ifdef AVS_WINDOWS __declspec(noreturn) virtual void ThrowError(const char* fmt, ...) = 0; #else virtual void ThrowError(const char* fmt, ...) = 0; #endif class NotFound /*exception*/ {}; // thrown by Invoke and GetVar typedef AVSValue(__cdecl* ApplyFunc)(AVSValue args, void* user_data, IScriptEnvironment* env); virtual void __stdcall AddFunction25(const char* name, const char* params, ApplyFunc apply, void* user_data) = 0; virtual bool __stdcall FunctionExists(const char* name) = 0; virtual AVSValue __stdcall Invoke25(const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall GetVar(const char* name) = 0; virtual bool __stdcall SetVar(const char* name, const AVSValue& val) = 0; virtual bool __stdcall SetGlobalVar(const char* name, const AVSValue& val) = 0; virtual void __stdcall PushContext(int level = 0) = 0; virtual void __stdcall PopContext() = 0; virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, int align = FRAME_ALIGN) = 0; virtual bool __stdcall MakeWritable(PVideoFrame* pvf) = 0; virtual void __stdcall BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height) = 0; typedef void(__cdecl* ShutdownFunc)(void* user_data, IScriptEnvironment* env); virtual void __stdcall AtExit(ShutdownFunc function, void* user_data) = 0; virtual void __stdcall CheckVersion(int version = AVISYNTH_CLASSIC_INTERFACE_VERSION_25) = 0; virtual PVideoFrame __stdcall Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height) = 0; virtual int __stdcall SetMemoryMax(int mem) = 0; virtual int __stdcall SetWorkingDir(const char* newdir) = 0; // specially returns 1 for key MC_QueryAvs25 to check if called from AVS2.5 interface virtual void* __stdcall ManageCache25(int key, void* data) = 0; enum PlanarChromaAlignmentMode { PlanarChromaAlignmentOff, PlanarChromaAlignmentOn, PlanarChromaAlignmentTest }; virtual bool __stdcall PlanarChromaAlignment(IScriptEnvironment::PlanarChromaAlignmentMode key) = 0; virtual PVideoFrame __stdcall SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV) = 0; // Despite the name, we provide entries up to V6 in case someone requests // a V3 interface and still wants to use V5-V6 functions // **** AVISYNTH_INTERFACE_VERSION 5 **** defined since classic Avisynth 2.6 beta virtual void __stdcall DeleteScriptEnvironment() = 0; virtual void __stdcall ApplyMessage(PVideoFrame* frame, const VideoInfo& vi, const char* message, int size, int textcolor, int halocolor, int bgcolor) = 0; virtual const AVS_Linkage* __stdcall GetAVSLinkage() = 0; // **** AVISYNTH_INTERFACE_VERSION 6 **** defined since classic Avisynth 2.6 // noThrow version of GetVar virtual AVSValue __stdcall GetVarDef(const char* name, const AVSValue& def = AVSValue()) = 0; }; // end class IScriptEnvironment_Avs25. Order is important. enum MtMode { MT_INVALID = 0, MT_NICE_FILTER = 1, MT_MULTI_INSTANCE = 2, MT_SERIALIZED = 3, MT_SPECIAL_MT = 4, MT_MODE_COUNT = 5 }; class IJobCompletion { public: virtual ~IJobCompletion() {} virtual void __stdcall Wait() = 0; virtual AVSValue __stdcall Get(size_t i) = 0; virtual size_t __stdcall Size() const = 0; virtual size_t __stdcall Capacity() const = 0; virtual void __stdcall Reset() = 0; virtual void __stdcall Destroy() = 0; }; class IScriptEnvironment2; class Prefetcher; typedef AVSValue (*ThreadWorkerFuncPtr)(IScriptEnvironment2* env, void* data); /* ----------------------------------------------------------------------------- Note to plugin authors: The interface in IScriptEnvironment2 is preliminary / under construction / only for testing / non-final etc.! As long as you see this note here, IScriptEnvironment2 might still change, in which case your plugin WILL break. This also means that you are welcome to test it and give your feedback about any ideas, improvements, or issues you might have. ----------------------------------------------------------------------------- */ class IScriptEnvironment2 : public IScriptEnvironment{ public: virtual ~IScriptEnvironment2() {} // V8: SubframePlanarA, GetEnvProperty, GetVar versions, Allocate, Free, no-throw Invoke moved to IScriptEnvironment // Plugin functions virtual bool __stdcall LoadPlugin(const char* filePath, bool throwOnError, AVSValue *result) = 0; virtual void __stdcall AddAutoloadDir(const char* dirPath, bool toFront) = 0; virtual void __stdcall ClearAutoloadDirs() = 0; virtual void __stdcall AutoloadPlugins() = 0; virtual void __stdcall AddFunction(const char* name, const char* params, ApplyFunc apply, void* user_data, const char *exportVar) = 0; virtual bool __stdcall InternalFunctionExists(const char* name) = 0; // Threading virtual void __stdcall SetFilterMTMode(const char* filter, MtMode mode, bool force) = 0; // If filter is "DEFAULT_MT_MODE", sets the default MT mode virtual IJobCompletion* __stdcall NewCompletion(size_t capacity) = 0; virtual void __stdcall ParallelJob(ThreadWorkerFuncPtr jobFunc, void* jobData, IJobCompletion* completion) = 0; // These lines are needed so that we can overload the older functions from IScriptEnvironment. using IScriptEnvironment::Invoke; using IScriptEnvironment::AddFunction; }; // end class IScriptEnvironment2 // To allow Avisynth+ add functions to IScriptEnvironment2, // Neo defines another new interface, INeoEnv. // INeoEnv and the legacy interfaces (IScriptEnvironment/IScriptEnvironment2) // share the same ScriptEnvironment instance. The function with the same signature // is exactly identical and there is no limitation to switch interfaces. // You can use any interface you like. // Note to plugin authors : The interface is not stable, see comments in IScriptEnvironment2 class INeoEnv { public: virtual ~INeoEnv() {} typedef IScriptEnvironment::NotFound NotFound; typedef IScriptEnvironment::ApplyFunc ApplyFunc; typedef IScriptEnvironment::ShutdownFunc ShutdownFunc; virtual void __stdcall DeleteScriptEnvironment() = 0; virtual const AVS_Linkage* __stdcall GetAVSLinkage() = 0; // Get legacy interface (Avisynth+) virtual IScriptEnvironment2* __stdcall GetEnv2() = 0; // Get compatibility interface for AVS CPP 2.5 plugins virtual IScriptEnvironment_Avs25* __stdcall GetEnv25() = 0; // Generic system to ask for various properties virtual size_t __stdcall GetEnvProperty(AvsEnvProperty prop) = 0; virtual int __stdcall GetCPUFlags() = 0; // Plugin functions virtual bool __stdcall LoadPlugin(const char* filePath, bool throwOnError, AVSValue *result) = 0; virtual void __stdcall AddAutoloadDir(const char* dirPath, bool toFront) = 0; virtual void __stdcall ClearAutoloadDirs() = 0; virtual void __stdcall AutoloadPlugins() = 0; virtual void __stdcall AddFunction( const char* name, const char* params, ApplyFunc apply, void* user_data) = 0; virtual void __stdcall AddFunction( const char* name, const char* params, ApplyFunc apply, void* user_data, const char *exportVar) = 0; virtual bool __stdcall FunctionExists(const char* name) = 0; virtual bool __stdcall InternalFunctionExists(const char* name) = 0; // Invoke function. Throws NotFound exception when the specified function does not exist. virtual AVSValue __stdcall Invoke( const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall Invoke2( const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall Invoke3( const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; // These versions of Invoke will return false instead of throwing NotFound(). virtual bool __stdcall InvokeTry( AVSValue* result, const char* name, const AVSValue& args, const char* const* arg_names = 0) = 0; virtual bool __stdcall Invoke2Try( AVSValue* result, const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual bool __stdcall Invoke3Try( AVSValue* result, const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; // V9 virtual bool __stdcall MakePropertyWritable(PVideoFrame* pvf) = 0; // Throws exception when the requested variable is not found. virtual AVSValue __stdcall GetVar(const char* name) = 0; // noThrow version of GetVar virtual AVSValue __stdcall GetVarDef(const char* name, const AVSValue& def = AVSValue()) = 0; // Returns TRUE and the requested variable. If the method fails, returns FALSE and does not touch 'val'. virtual bool __stdcall GetVarTry(const char* name, AVSValue* val) const = 0; // Return the value of the requested variable. // If the variable was not found or had the wrong type, // return the supplied default value. virtual bool __stdcall GetVarBool(const char* name, bool def) const = 0; virtual int __stdcall GetVarInt(const char* name, int def) const = 0; virtual double __stdcall GetVarDouble(const char* name, double def) const = 0; virtual const char* __stdcall GetVarString(const char* name, const char* def) const = 0; virtual int64_t __stdcall GetVarLong(const char* name, int64_t def) const = 0; virtual bool __stdcall SetVar(const char* name, const AVSValue& val) = 0; virtual bool __stdcall SetGlobalVar(const char* name, const AVSValue& val) = 0; // Switch local variables virtual void __stdcall PushContext(int level = 0) = 0; virtual void __stdcall PopContext() = 0; // Global variable frame support virtual void __stdcall PushContextGlobal() = 0; virtual void __stdcall PopContextGlobal() = 0; // Allocate new video frame // in PNeoEnv: align parameter is no longer supported virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi) = 0; // current device is used virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, const PDevice& device) = 0; // as above but with property sources virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, const PVideoFrame *prop_src) = 0; // current device is used + frame property source virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, const PDevice& device, const PVideoFrame* prop_src) = 0; // current device is used + frame property source // Frame related operations virtual bool __stdcall MakeWritable(PVideoFrame* pvf) = 0; virtual void __stdcall BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height) = 0; virtual PVideoFrame __stdcall Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height) = 0; virtual PVideoFrame __stdcall SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV) = 0; virtual PVideoFrame __stdcall SubframePlanarA(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA) = 0; // frame properties support virtual void __stdcall copyFrameProps(const PVideoFrame& src, PVideoFrame& dst) = 0; virtual const AVSMap* __stdcall getFramePropsRO(const PVideoFrame& frame) = 0; virtual AVSMap* __stdcall getFramePropsRW(PVideoFrame& frame) = 0; virtual int __stdcall propNumKeys(const AVSMap* map) = 0; virtual const char* __stdcall propGetKey(const AVSMap* map, int index) = 0; virtual int __stdcall propNumElements(const AVSMap* map, const char* key) = 0; virtual char __stdcall propGetType(const AVSMap* map, const char* key) = 0; virtual int64_t __stdcall propGetInt(const AVSMap* map, const char* key, int index, int* error) = 0; virtual double __stdcall propGetFloat(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const char* __stdcall propGetData(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propGetDataSize(const AVSMap* map, const char* key, int index, int* error) = 0; virtual PClip __stdcall propGetClip(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const PVideoFrame __stdcall propGetFrame(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propDeleteKey(AVSMap* map, const char* key) = 0; virtual int __stdcall propSetInt(AVSMap* map, const char* key, int64_t i, int append) = 0; virtual int __stdcall propSetFloat(AVSMap* map, const char* key, double d, int append) = 0; virtual int __stdcall propSetData(AVSMap* map, const char* key, const char* d, int length, int append) = 0; virtual int __stdcall propSetClip(AVSMap* map, const char* key, PClip& clip, int append) = 0; virtual int __stdcall propSetFrame(AVSMap* map, const char* key, const PVideoFrame& frame, int append) = 0; virtual const int64_t *__stdcall propGetIntArray(const AVSMap* map, const char* key, int* error) = 0; virtual const double *__stdcall propGetFloatArray(const AVSMap* map, const char* key, int* error) = 0; virtual int __stdcall propSetIntArray(AVSMap* map, const char* key, const int64_t* i, int size) = 0; virtual int __stdcall propSetFloatArray(AVSMap* map, const char* key, const double* d, int size) = 0; virtual AVSMap* __stdcall createMap() = 0; virtual void __stdcall freeMap(AVSMap* map) = 0; virtual void __stdcall clearMap(AVSMap* map) = 0; // Support functions virtual void* __stdcall Allocate(size_t nBytes, size_t alignment, AvsAllocType type) = 0; virtual void __stdcall Free(void* ptr) = 0; virtual char* __stdcall SaveString(const char* s, int length = -1) = 0; virtual char* __stdcall SaveString(const char* s, int length, bool escape) = 0; virtual char* Sprintf(const char* fmt, ...) = 0; virtual char* __stdcall VSprintf(const char* fmt, va_list val) = 0; __declspec(noreturn) virtual void ThrowError(const char* fmt, ...) = 0; virtual void __stdcall ApplyMessage(PVideoFrame* frame, const VideoInfo& vi, const char* message, int size, int textcolor, int halocolor, int bgcolor) = 0; // Setting virtual int __stdcall SetMemoryMax(int mem) = 0; virtual int __stdcall SetMemoryMax(AvsDeviceType type, int index, int mem) = 0; virtual bool __stdcall PlanarChromaAlignment(IScriptEnvironment::PlanarChromaAlignmentMode key) = 0; virtual int __stdcall SetWorkingDir(const char * newdir) = 0; virtual void* __stdcall ManageCache(int key, void* data) = 0; virtual void __stdcall AtExit(ShutdownFunc function, void* user_data) = 0; virtual void __stdcall CheckVersion(int version = AVISYNTH_INTERFACE_VERSION) = 0; // Threading virtual void __stdcall SetFilterMTMode(const char* filter, MtMode mode, bool force) = 0; virtual IJobCompletion* __stdcall NewCompletion(size_t capacity) = 0; virtual void __stdcall ParallelJob(ThreadWorkerFuncPtr jobFunc, void* jobData, IJobCompletion* completion) = 0; // CUDA Support virtual PDevice __stdcall GetDevice(AvsDeviceType dev_type, int dev_index) const = 0; virtual PDevice __stdcall GetDevice() const = 0; // get current device virtual AvsDeviceType __stdcall GetDeviceType() const = 0; virtual int __stdcall GetDeviceId() const = 0; virtual int __stdcall GetDeviceIndex() const = 0; virtual void* __stdcall GetDeviceStream() const = 0; virtual void __stdcall DeviceAddCallback(void(*cb)(void*), void* user_data) = 0; virtual PVideoFrame __stdcall GetFrame(PClip c, int n, const PDevice& device) = 0; }; // support interface conversion struct PNeoEnv { INeoEnv* p; PNeoEnv() : p() { } PNeoEnv(IScriptEnvironment* env) #if defined(BUILDING_AVSCORE) || defined(AVS_STATIC_LIB) ; #else : p(!AVS_linkage || offsetof(AVS_Linkage, GetNeoEnv) >= (size_t)AVS_linkage->Size ? 0 : AVS_linkage->GetNeoEnv(env)) { } #endif int operator!() const { return !p; } operator void*() const { return p; } INeoEnv* operator->() const { return p; } #ifdef BUILDING_AVSCORE inline operator IScriptEnvironment2*(); inline operator IScriptEnvironment_Avs25* (); #else operator IScriptEnvironment2*() { return p->GetEnv2(); } operator IScriptEnvironment_Avs25* () { return p->GetEnv25(); } #endif }; // avisynth.dll exports this; it's a way to use it as a library, without // writing an AVS script or without going through AVIFile. AVSC_API(IScriptEnvironment*, CreateScriptEnvironment)(int version = AVISYNTH_INTERFACE_VERSION); // These are some global variables you can set in your script to change AviSynth's behavior. #define VARNAME_AllowFloatAudio "OPT_AllowFloatAudio" // Allow WAVE_FORMAT_IEEE_FLOAT audio output #define VARNAME_VDubPlanarHack "OPT_VDubPlanarHack" // Hack YV16 and YV24 chroma plane order for old VDub's #define VARNAME_AVIPadScanlines "OPT_AVIPadScanlines" // Have scanlines mod4 padded in all pixel formats #define VARNAME_UseWaveExtensible "OPT_UseWaveExtensible" // Use WAVEFORMATEXTENSIBLE when describing audio to Windows #define VARNAME_dwChannelMask "OPT_dwChannelMask" // Integer audio channel mask. See description of WAVEFORMATEXTENSIBLE for more info. #define VARNAME_Enable_V210 "OPT_Enable_V210" // AVS+ use V210 instead of P210 (VfW) #define VARNAME_Enable_Y3_10_10 "OPT_Enable_Y3_10_10" // AVS+ use Y3[10][10] instead of P210 (VfW) #define VARNAME_Enable_Y3_10_16 "OPT_Enable_Y3_10_16" // AVS+ use Y3[10][16] instead of P216 (VfW) #define VARNAME_Enable_b64a "OPT_Enable_b64a" // AVS+ use b64a instead of BRA[64] (VfW) #define VARNAME_Enable_PlanarToPackedRGB "OPT_Enable_PlanarToPackedRGB" // AVS+ convert Planar RGB to packed RGB (VfW) // C exports #include "avs/capi.h" AVSC_API(IScriptEnvironment2*, CreateScriptEnvironment2)(int version = AVISYNTH_INTERFACE_VERSION); #ifndef BUILDING_AVSCORE #undef AVS_UNUSED #endif #pragma pack(pop) #endif //__AVISYNTH_10_H__ ================================================ FILE: thirdparty/32/include/avisynth/avisynth_c.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // Copyright 2020 AviSynth+ project // Actual C Interface version follows the global Avisynth+ IF version numbers. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301 USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. // NOTE: this is a partial update of the Avisynth C interface to recognize // new color spaces and interface elements added in Avisynth 2.60 and AviSynth+. // This interface is not 100% Avisynth+ CPP interface equivalent. // 170103: added new CPU constants (FMA4, AVX512xx) // 171102: define SIZETMOD. do not use yet, experimental. Offsets are size_t instead of int. Affects x64. // 171106: avs_get_row_size calls into avs_get_row_size_p, instead of direct field access // 171106: avs_get_height calls into avs_get_row_size_p, instead of direct field access // 180524: AVSC_EXPORT to dllexport in capi.h for avisynth_c_plugin_init // 180524: avs_is_same_colorspace VideoInfo parameters to const // 181230: Readability: functions regrouped to mix less AVSC_API and AVSC_INLINE, put together Avisynth+ specific stuff // 181230: use #ifndef AVSC_NO_DECLSPEC for AVSC_INLINE functions which are calling API functions // 181230: comments on avs_load_library (helper for loading API entries dynamically into a struct using AVSC_NO_DECLSPEC define) // 181230: define alias AVS_FRAME_ALIGN as FRAME_ALIGN // 181230: remove unused form of avs_get_rowsize and avs_get_height (kept earlier for reference) // 190104: avs_load_library: smart fallback mechanism for Avisynth+ specific functions: // if they are not loadable, they will work in a classic Avisynth compatible mode // Example#1: e.g. avs_is_444 will call the existing avs_is_yv24 instead // Example#2: avs_bits_per_component will return 8 for all colorspaces (Classic Avisynth supports only 8 bits/pixel) // Thus the Avisynth+ specific API functions are safely callable even when connected to classic Avisynth DLL // 2002xx non-Windows friendly additions // 200305 avs_vsprintf parameter type change: (void *) to va_list // 200330: (remove test SIZETMOD define for clarity) // 200513: user must use explicite #define AVS26_FALLBACK_SIMULATION for having fallback helpers in dynamic loaded library section // 200513: Follow AviSynth+ V8 interface additions // AVS_VideoFrame struct extended with placeholder for frame property pointer // avs_subframe_planar_a // avs_copy_frame_props // avs_get_frame_props_ro, avs_get_frame_props_rw // avs_prop_num_keys, avs_prop_get_key, avs_prop_num_elements, avs_prop_get_type, avs_prop_get_data_size // avs_prop_get_int, avs_prop_get_float, avs_prop_get_data, avs_prop_get_clip, avs_prop_get_frame, avs_prop_get_int_array, avs_prop_get_float_array // avs_prop_set_int, avs_prop_set_float, avs_prop_set_data, avs_prop_set_clip, avs_prop_set_frame, avs_prop_set_int_array, avs_prop_set_float_array // avs_prop_delete_key, avs_clear_map // avs_new_video_frame_p, avs_new_video_frame_p_a // avs_get_env_property (internal system properties), AVS_AEP_xxx (AvsEnvProperty) enums // avs_get_var_try, avs_get_var_bool, avs_get_var_int, avs_get_var_double, avs_get_var_string, avs_get_var_long // avs_pool_allocate, avs_pool_free // 2021: Follow AviSynth+ V9 interface additions // avs_is_property_writable, avs_make_property_writable // Add enum AVISYNTHPLUS_INTERFACE_BUGFIX_VERSION (AVISYNTH_INTERFACE_VERSION still exists) // Add enum AVS_AEP_HOST_SYSTEM_ENDIANNESS to system property request types (avs_get_env_property) // Add enums AVS_AEP_INTERFACE_VERSION and AVS_AEP_INTERFACE_BUGFIX for direct interface version system property request types (avs_get_env_property) // Bugfix 9.1: fix avs_prop_get_data // 2023: Follow AviSynth+ V10 interface additions // Add enum AVS_DEFAULT_PLANE (as 0) to plane constants // prop_src argument now const in avs_new_video_frame_p and avs_new_video_frame_p_a (no change in use) // Add pixel_type to struct AVS_VideoFrame // Add avs_video_frame_get_pixel_type and avs_video_frame_amend_pixel_type for getting and setting AVS_VideoFrame pixel_type // Additional AviSynth+ V10 interface additions: // Add enum AVS_SPEAKER_xxx, AVS_IT_SPEAKER_xxx // audio channel mask support avs_is_channel_mask_known, avs_set_channel_mask, avs_get_channel_mask #ifndef __AVISYNTH_C__ #define __AVISYNTH_C__ #include "avs/config.h" #include "avs/capi.h" #include "avs/types.h" #define AVS_FRAME_ALIGN FRAME_ALIGN ///////////////////////////////////////////////////////////////////// // // Constants // #ifndef __AVISYNTH_10_H__ enum { AVISYNTH_INTERFACE_CLASSIC_VERSION = 6, AVISYNTH_INTERFACE_VERSION = 10, AVISYNTHPLUS_INTERFACE_BUGFIX_VERSION = 0 // reset to zero whenever the normal interface version bumps }; #endif enum { AVS_SAMPLE_INT8 = 1 << 0, AVS_SAMPLE_INT16 = 1 << 1, AVS_SAMPLE_INT24 = 1 << 2, AVS_SAMPLE_INT32 = 1 << 3, AVS_SAMPLE_FLOAT = 1 << 4 }; enum { AVS_DEFAULT_PLANE = 0, AVS_PLANAR_Y = 1 << 0, AVS_PLANAR_U = 1 << 1, AVS_PLANAR_V = 1 << 2, AVS_PLANAR_ALIGNED = 1 << 3, AVS_PLANAR_Y_ALIGNED = AVS_PLANAR_Y | AVS_PLANAR_ALIGNED, AVS_PLANAR_U_ALIGNED = AVS_PLANAR_U | AVS_PLANAR_ALIGNED, AVS_PLANAR_V_ALIGNED = AVS_PLANAR_V | AVS_PLANAR_ALIGNED, AVS_PLANAR_A = 1 << 4, AVS_PLANAR_R = 1 << 5, AVS_PLANAR_G = 1 << 6, AVS_PLANAR_B = 1 << 7, AVS_PLANAR_A_ALIGNED = AVS_PLANAR_A | AVS_PLANAR_ALIGNED, AVS_PLANAR_R_ALIGNED = AVS_PLANAR_R | AVS_PLANAR_ALIGNED, AVS_PLANAR_G_ALIGNED = AVS_PLANAR_G | AVS_PLANAR_ALIGNED, AVS_PLANAR_B_ALIGNED = AVS_PLANAR_B | AVS_PLANAR_ALIGNED }; // Colorspace properties. enum { AVS_CS_YUVA = 1 << 27, AVS_CS_BGR = 1 << 28, AVS_CS_YUV = 1 << 29, AVS_CS_INTERLEAVED = 1 << 30, AVS_CS_PLANAR = 1 << 31, AVS_CS_SHIFT_SUB_WIDTH = 0, AVS_CS_SHIFT_SUB_HEIGHT = 8, AVS_CS_SHIFT_SAMPLE_BITS = 16, AVS_CS_SUB_WIDTH_MASK = 7 << AVS_CS_SHIFT_SUB_WIDTH, AVS_CS_SUB_WIDTH_1 = 3 << AVS_CS_SHIFT_SUB_WIDTH, // YV24 AVS_CS_SUB_WIDTH_2 = 0 << AVS_CS_SHIFT_SUB_WIDTH, // YV12, I420, YV16 AVS_CS_SUB_WIDTH_4 = 1 << AVS_CS_SHIFT_SUB_WIDTH, // YUV9, YV411 AVS_CS_VPLANEFIRST = 1 << 3, // YV12, YV16, YV24, YV411, YUV9 AVS_CS_UPLANEFIRST = 1 << 4, // I420 AVS_CS_SUB_HEIGHT_MASK = 7 << AVS_CS_SHIFT_SUB_HEIGHT, AVS_CS_SUB_HEIGHT_1 = 3 << AVS_CS_SHIFT_SUB_HEIGHT, // YV16, YV24, YV411 AVS_CS_SUB_HEIGHT_2 = 0 << AVS_CS_SHIFT_SUB_HEIGHT, // YV12, I420 AVS_CS_SUB_HEIGHT_4 = 1 << AVS_CS_SHIFT_SUB_HEIGHT, // YUV9 AVS_CS_SAMPLE_BITS_MASK = 7 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_8 = 0 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_10 = 5 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_12 = 6 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_14 = 7 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_16 = 1 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_32 = 2 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_PLANAR_MASK = AVS_CS_PLANAR | AVS_CS_INTERLEAVED | AVS_CS_YUV | AVS_CS_BGR | AVS_CS_YUVA | AVS_CS_SAMPLE_BITS_MASK | AVS_CS_SUB_WIDTH_MASK | AVS_CS_SUB_HEIGHT_MASK, AVS_CS_PLANAR_FILTER = ~(AVS_CS_VPLANEFIRST | AVS_CS_UPLANEFIRST), AVS_CS_RGB_TYPE = 1 << 0, AVS_CS_RGBA_TYPE = 1 << 1, AVS_CS_GENERIC_YUV444 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_1 | AVS_CS_SUB_HEIGHT_1, // 4:4:4 planar AVS_CS_GENERIC_YUV422 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_1, // 4:2:2 planar AVS_CS_GENERIC_YUV420 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_2, // 4:2:0 planar AVS_CS_GENERIC_Y = AVS_CS_PLANAR | AVS_CS_INTERLEAVED | AVS_CS_YUV, // Y only (4:0:0) AVS_CS_GENERIC_RGBP = AVS_CS_PLANAR | AVS_CS_BGR | AVS_CS_RGB_TYPE, // planar RGB AVS_CS_GENERIC_RGBAP = AVS_CS_PLANAR | AVS_CS_BGR | AVS_CS_RGBA_TYPE, // planar RGBA AVS_CS_GENERIC_YUVA444 = AVS_CS_PLANAR | AVS_CS_YUVA | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_1 | AVS_CS_SUB_HEIGHT_1, // 4:4:4:A planar AVS_CS_GENERIC_YUVA422 = AVS_CS_PLANAR | AVS_CS_YUVA | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_1, // 4:2:2:A planar AVS_CS_GENERIC_YUVA420 = AVS_CS_PLANAR | AVS_CS_YUVA | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_2 // 4:2:0:A planar }; // Specific color formats enum { AVS_CS_UNKNOWN = 0, AVS_CS_BGR24 = AVS_CS_RGB_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED, AVS_CS_BGR32 = AVS_CS_RGBA_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED, AVS_CS_YUY2 = 1 << 2 | AVS_CS_YUV | AVS_CS_INTERLEAVED, // AVS_CS_YV12 = 1 << 3 Reserved // AVS_CS_I420 = 1 << 4 Reserved AVS_CS_RAW32 = 1 << 5 | AVS_CS_INTERLEAVED, AVS_CS_YV24 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_8, // YUV 4:4:4 planar AVS_CS_YV16 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_8, // YUV 4:2:2 planar AVS_CS_YV12 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_8, // YUV 4:2:0 planar AVS_CS_I420 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_SAMPLE_BITS_8 | AVS_CS_UPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_2, // YUV 4:2:0 planar AVS_CS_IYUV = AVS_CS_I420, AVS_CS_YV411 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_SAMPLE_BITS_8 | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_4 | AVS_CS_SUB_HEIGHT_1, // YUV 4:1:1 planar AVS_CS_YUV9 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_SAMPLE_BITS_8 | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_4 | AVS_CS_SUB_HEIGHT_4, // YUV 4:1:0 planar AVS_CS_Y8 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_8, // Y 4:0:0 planar //------------------------- // AVS16: new planar constants go live! Experimental PF 160613 // 10-12-14-16 bit + planar RGB + BGR48/64 160725 AVS_CS_YUV444P10 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_10, // YUV 4:4:4 10bit samples AVS_CS_YUV422P10 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_10, // YUV 4:2:2 10bit samples AVS_CS_YUV420P10 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_10, // YUV 4:2:0 10bit samples AVS_CS_Y10 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_10, // Y 4:0:0 10bit samples AVS_CS_YUV444P12 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_12, // YUV 4:4:4 12bit samples AVS_CS_YUV422P12 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_12, // YUV 4:2:2 12bit samples AVS_CS_YUV420P12 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_12, // YUV 4:2:0 12bit samples AVS_CS_Y12 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_12, // Y 4:0:0 12bit samples AVS_CS_YUV444P14 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_14, // YUV 4:4:4 14bit samples AVS_CS_YUV422P14 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_14, // YUV 4:2:2 14bit samples AVS_CS_YUV420P14 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_14, // YUV 4:2:0 14bit samples AVS_CS_Y14 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_14, // Y 4:0:0 14bit samples AVS_CS_YUV444P16 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_16, // YUV 4:4:4 16bit samples AVS_CS_YUV422P16 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_16, // YUV 4:2:2 16bit samples AVS_CS_YUV420P16 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_16, // YUV 4:2:0 16bit samples AVS_CS_Y16 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_16, // Y 4:0:0 16bit samples // 32 bit samples (float) AVS_CS_YUV444PS = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_32, // YUV 4:4:4 32bit samples AVS_CS_YUV422PS = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_32, // YUV 4:2:2 32bit samples AVS_CS_YUV420PS = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_32, // YUV 4:2:0 32bit samples AVS_CS_Y32 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_32, // Y 4:0:0 32bit samples // RGB packed AVS_CS_BGR48 = AVS_CS_RGB_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED | AVS_CS_SAMPLE_BITS_16, // BGR 3x16 bit AVS_CS_BGR64 = AVS_CS_RGBA_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED | AVS_CS_SAMPLE_BITS_16, // BGR 4x16 bit // no packed 32 bit (float) support for these legacy types // RGB planar AVS_CS_RGBP = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_8, // Planar RGB 8 bit samples AVS_CS_RGBP10 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_10, // Planar RGB 10bit samples AVS_CS_RGBP12 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_12, // Planar RGB 12bit samples AVS_CS_RGBP14 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_14, // Planar RGB 14bit samples AVS_CS_RGBP16 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_16, // Planar RGB 16bit samples AVS_CS_RGBPS = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_32, // Planar RGB 32bit samples // RGBA planar AVS_CS_RGBAP = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_8, // Planar RGBA 8 bit samples AVS_CS_RGBAP10 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_10, // Planar RGBA 10bit samples AVS_CS_RGBAP12 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_12, // Planar RGBA 12bit samples AVS_CS_RGBAP14 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_14, // Planar RGBA 14bit samples AVS_CS_RGBAP16 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_16, // Planar RGBA 16bit samples AVS_CS_RGBAPS = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_32, // Planar RGBA 32bit samples // Planar YUVA AVS_CS_YUVA444 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_8, // YUVA 4:4:4 8bit samples AVS_CS_YUVA422 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_8, // YUVA 4:2:2 8bit samples AVS_CS_YUVA420 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_8, // YUVA 4:2:0 8bit samples AVS_CS_YUVA444P10 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_10, // YUVA 4:4:4 10bit samples AVS_CS_YUVA422P10 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_10, // YUVA 4:2:2 10bit samples AVS_CS_YUVA420P10 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_10, // YUVA 4:2:0 10bit samples AVS_CS_YUVA444P12 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_12, // YUVA 4:4:4 12bit samples AVS_CS_YUVA422P12 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_12, // YUVA 4:2:2 12bit samples AVS_CS_YUVA420P12 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_12, // YUVA 4:2:0 12bit samples AVS_CS_YUVA444P14 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_14, // YUVA 4:4:4 14bit samples AVS_CS_YUVA422P14 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_14, // YUVA 4:2:2 14bit samples AVS_CS_YUVA420P14 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_14, // YUVA 4:2:0 14bit samples AVS_CS_YUVA444P16 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_16, // YUVA 4:4:4 16bit samples AVS_CS_YUVA422P16 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_16, // YUVA 4:2:2 16bit samples AVS_CS_YUVA420P16 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_16, // YUVA 4:2:0 16bit samples AVS_CS_YUVA444PS = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_32, // YUVA 4:4:4 32bit samples AVS_CS_YUVA422PS = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_32, // YUVA 4:2:2 32bit samples AVS_CS_YUVA420PS = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_32, // YUVA 4:2:0 32bit samples }; // AvsChannelMask enum: Unshifted channel mask constants like in WAVEFORMATEXTENSIBLE // in AvsImageTypeFlags they are shifted by 4 bits enum { AVS_MASK_SPEAKER_FRONT_LEFT = 0x1, AVS_MASK_SPEAKER_FRONT_RIGHT = 0x2, AVS_MASK_SPEAKER_FRONT_CENTER = 0x4, AVS_MASK_SPEAKER_LOW_FREQUENCY = 0x8, AVS_MASK_SPEAKER_BACK_LEFT = 0x10, AVS_MASK_SPEAKER_BACK_RIGHT = 0x20, AVS_MASK_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40, AVS_MASK_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80, AVS_MASK_SPEAKER_BACK_CENTER = 0x100, AVS_MASK_SPEAKER_SIDE_LEFT = 0x200, AVS_MASK_SPEAKER_SIDE_RIGHT = 0x400, AVS_MASK_SPEAKER_TOP_CENTER = 0x800, AVS_MASK_SPEAKER_TOP_FRONT_LEFT = 0x1000, AVS_MASK_SPEAKER_TOP_FRONT_CENTER = 0x2000, AVS_MASK_SPEAKER_TOP_FRONT_RIGHT = 0x4000, AVS_MASK_SPEAKER_TOP_BACK_LEFT = 0x8000, AVS_MASK_SPEAKER_TOP_BACK_CENTER = 0x10000, AVS_MASK_SPEAKER_TOP_BACK_RIGHT = 0x20000, // Bit mask locations used up for the above positions AVS_MASK_SPEAKER_DEFINED = 0x0003FFFF, // Bit mask locations reserved for future use AVS_MASK_SPEAKER_RESERVED = 0x7FFC0000, // Used to specify that any possible permutation of speaker configurations // Due to lack of available bits this one is put differently into image_type AVS_MASK_SPEAKER_ALL = 0x80000000 }; // AvsImageTypeFlags enum { AVS_IT_BFF = 1 << 0, AVS_IT_TFF = 1 << 1, AVS_IT_FIELDBASED = 1 << 2, // Audio channel mask support AVS_IT_HAS_CHANNELMASK = 1 << 3, // shifted by 4 bits compared to WAVEFORMATEXTENSIBLE dwChannelMask // otherwise same as AvsChannelMask AVS_IT_SPEAKER_FRONT_LEFT = 0x1 << 4, AVS_IT_SPEAKER_FRONT_RIGHT = 0x2 << 4, AVS_IT_SPEAKER_FRONT_CENTER = 0x4 << 4, AVS_IT_SPEAKER_LOW_FREQUENCY = 0x8 << 4, AVS_IT_SPEAKER_BACK_LEFT = 0x10 << 4, AVS_IT_SPEAKER_BACK_RIGHT = 0x20 << 4, AVS_IT_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40 << 4, AVS_IT_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80 << 4, AVS_IT_SPEAKER_BACK_CENTER = 0x100 << 4, AVS_IT_SPEAKER_SIDE_LEFT = 0x200 << 4, AVS_IT_SPEAKER_SIDE_RIGHT = 0x400 << 4, AVS_IT_SPEAKER_TOP_CENTER = 0x800 << 4, AVS_IT_SPEAKER_TOP_FRONT_LEFT = 0x1000 << 4, AVS_IT_SPEAKER_TOP_FRONT_CENTER = 0x2000 << 4, AVS_IT_SPEAKER_TOP_FRONT_RIGHT = 0x4000 << 4, AVS_IT_SPEAKER_TOP_BACK_LEFT = 0x8000 << 4, AVS_IT_SPEAKER_TOP_BACK_CENTER = 0x10000 << 4, AVS_IT_SPEAKER_TOP_BACK_RIGHT = 0x20000 << 4, // End of officially defined speaker bits // The next one is special, since cannot shift SPEAKER_ALL 0x80000000 further. // Set mask and get mask handles it. AVS_IT_SPEAKER_ALL = 0x40000 << 4, // Mask for the defined 18 bits + SPEAKER_ALL AVS_IT_SPEAKER_BITS_MASK = (AVS_MASK_SPEAKER_DEFINED << 4) | AVS_IT_SPEAKER_ALL, AVS_IT_NEXT_AVAILABLE = 1 << 23 }; enum { AVS_FILTER_TYPE = 1, AVS_FILTER_INPUT_COLORSPACE = 2, AVS_FILTER_OUTPUT_TYPE = 9, AVS_FILTER_NAME = 4, AVS_FILTER_AUTHOR = 5, AVS_FILTER_VERSION = 6, AVS_FILTER_ARGS = 7, AVS_FILTER_ARGS_INFO = 8, AVS_FILTER_ARGS_DESCRIPTION = 10, AVS_FILTER_DESCRIPTION = 11 }; enum { // SUBTYPES AVS_FILTER_TYPE_AUDIO = 1, AVS_FILTER_TYPE_VIDEO = 2, AVS_FILTER_OUTPUT_TYPE_SAME = 3, AVS_FILTER_OUTPUT_TYPE_DIFFERENT = 4 }; enum { // New 2.6 explicitly defined cache hints. AVS_CACHE_NOTHING = 10, // Do not cache video. AVS_CACHE_WINDOW = 11, // Hard protect up to X frames within a range of X from the current frame N. AVS_CACHE_GENERIC = 12, // LRU cache up to X frames. AVS_CACHE_FORCE_GENERIC = 13, // LRU cache up to X frames, override any previous CACHE_WINDOW. AVS_CACHE_GET_POLICY = 30, // Get the current policy. AVS_CACHE_GET_WINDOW = 31, // Get the current window h_span. AVS_CACHE_GET_RANGE = 32, // Get the current generic frame range. // Set Audio cache mode and answers to CACHE_GETCHILD_AUDIO_MODE AVS_CACHE_AUDIO = 50, // Explicitly do cache audio, X byte cache. AVS_CACHE_AUDIO_NOTHING = 51, // Explicitly do not cache audio. AVS_CACHE_AUDIO_NONE = 52, // Audio cache off (auto mode), X byte initial cache. AVS_CACHE_AUDIO_AUTO_START_OFF = 52, // synonym AVS_CACHE_AUDIO_AUTO = 53, // Audio cache on (auto mode), X byte initial cache. AVS_CACHE_AUDIO_AUTO_START_ON = 53, // synonym // These just returns actual value if clip is cached AVS_CACHE_GET_AUDIO_POLICY = 70, // Get the current audio policy. AVS_CACHE_GET_AUDIO_SIZE = 71, // Get the current audio cache size. AVS_CACHE_PREFETCH_FRAME = 100, // n/a Queue request to prefetch frame N. AVS_CACHE_PREFETCH_GO = 101, // n/a Action video prefetches. AVS_CACHE_PREFETCH_AUDIO_BEGIN = 120, // n/a Begin queue request transaction to prefetch audio (take critical section). AVS_CACHE_PREFETCH_AUDIO_STARTLO = 121, // n/a Set low 32 bits of start. AVS_CACHE_PREFETCH_AUDIO_STARTHI = 122, // n/a Set high 32 bits of start. AVS_CACHE_PREFETCH_AUDIO_COUNT = 123, // n/a Set low 32 bits of length. AVS_CACHE_PREFETCH_AUDIO_COMMIT = 124, // n/a Enqueue request transaction to prefetch audio (release critical section). AVS_CACHE_PREFETCH_AUDIO_GO = 125, // n/a Action audio prefetches. AVS_CACHE_GETCHILD_CACHE_MODE = 200, // n/a Cache ask Child for desired video cache mode. AVS_CACHE_GETCHILD_CACHE_SIZE = 201, // n/a Cache ask Child for desired video cache size. // Filters are queried about their desired audio cache mode. // Child can answer them with CACHE_AUDIO_xxx AVS_CACHE_GETCHILD_AUDIO_MODE = 202, // Cache ask Child for desired audio cache mode. AVS_CACHE_GETCHILD_AUDIO_SIZE = 203, // Cache ask Child for desired audio cache size. AVS_CACHE_GETCHILD_COST = 220, // n/a Cache ask Child for estimated processing cost. AVS_CACHE_COST_ZERO = 221, // n/a Child response of zero cost (ptr arithmetic only). AVS_CACHE_COST_UNIT = 222, // n/a Child response of unit cost (less than or equal 1 full frame blit). AVS_CACHE_COST_LOW = 223, // n/a Child response of light cost. (Fast) AVS_CACHE_COST_MED = 224, // n/a Child response of medium cost. (Real time) AVS_CACHE_COST_HI = 225, // n/a Child response of heavy cost. (Slow) AVS_CACHE_GETCHILD_THREAD_MODE = 240, // n/a Cache ask Child for thread safety. AVS_CACHE_THREAD_UNSAFE = 241, // n/a Only 1 thread allowed for all instances. 2.5 filters default! AVS_CACHE_THREAD_CLASS = 242, // n/a Only 1 thread allowed for each instance. 2.6 filters default! AVS_CACHE_THREAD_SAFE = 243, // n/a Allow all threads in any instance. AVS_CACHE_THREAD_OWN = 244, // n/a Safe but limit to 1 thread, internally threaded. AVS_CACHE_GETCHILD_ACCESS_COST = 260, // Cache ask Child for preferred access pattern. AVS_CACHE_ACCESS_RAND = 261, // Filter is access order agnostic. AVS_CACHE_ACCESS_SEQ0 = 262, // Filter prefers sequential access (low cost) AVS_CACHE_ACCESS_SEQ1 = 263, // Filter needs sequential access (high cost) AVS_CACHE_AVSPLUS_CONSTANTS = 500, // Smaller values are reserved for classic Avisynth AVS_CACHE_DONT_CACHE_ME = 501, // Filters that don't need caching (eg. trim, cache etc.) should return 1 to this request AVS_CACHE_SET_MIN_CAPACITY = 502, AVS_CACHE_SET_MAX_CAPACITY = 503, AVS_CACHE_GET_MIN_CAPACITY = 504, AVS_CACHE_GET_MAX_CAPACITY = 505, AVS_CACHE_GET_SIZE = 506, AVS_CACHE_GET_REQUESTED_CAP = 507, AVS_CACHE_GET_CAPACITY = 508, AVS_CACHE_GET_MTMODE = 509, // Filters specify their desired MT mode, see enum MtMode // By returning IS_CACHE_ANS to IS_CACHE_REQ, we tell the caller we are a cache AVS_CACHE_IS_CACHE_REQ = 510, AVS_CACHE_IS_CACHE_ANS = 511, // By returning IS_MTGUARD_ANS to IS_MTGUARD_REQ, we tell the caller we are an mt guard AVS_CACHE_IS_MTGUARD_REQ = 512, AVS_CACHE_IS_MTGUARD_ANS = 513, AVS_CACHE_AVSPLUS_CUDA_CONSTANTS = 600, AVS_CACHE_GET_DEV_TYPE = 601, // Device types a filter can return AVS_CACHE_GET_CHILD_DEV_TYPE = 602, // Device types a fitler can receive AVS_CACHE_USER_CONSTANTS = 1000 // Smaller values are reserved for the core }; // enums for frame property functions // AVSPropTypes enum { AVS_PROPTYPE_UNSET = 'u', AVS_PROPTYPE_INT = 'i', AVS_PROPTYPE_FLOAT = 'f', AVS_PROPTYPE_DATA = 's', AVS_PROPTYPE_CLIP = 'c', AVS_PROPTYPE_FRAME = 'v' }; // AVSGetPropErrors for avs_prop_get_... enum { AVS_GETPROPERROR_UNSET = 1, AVS_GETPROPERROR_TYPE = 2, AVS_GETPROPERROR_INDEX = 4 }; // AVSPropAppendMode for avs_prop_set_... enum { AVS_PROPAPPENDMODE_REPLACE = 0, AVS_PROPAPPENDMODE_APPEND = 1, AVS_PROPAPPENDMODE_TOUCH = 2 }; // AvsEnvProperty for avs_get_env_property enum { AVS_AEP_PHYSICAL_CPUS = 1, AVS_AEP_LOGICAL_CPUS = 2, AVS_AEP_THREADPOOL_THREADS = 3, AVS_AEP_FILTERCHAIN_THREADS = 4, AVS_AEP_THREAD_ID = 5, AVS_AEP_VERSION = 6, AVS_AEP_HOST_SYSTEM_ENDIANNESS = 7, AVS_AEP_INTERFACE_VERSION = 8, AVS_AEP_INTERFACE_BUGFIX = 9, // Neo additionals AVS_AEP_NUM_DEVICES = 901, AVS_AEP_FRAME_ALIGN = 902, AVS_AEP_PLANE_ALIGN = 903, AVS_AEP_SUPPRESS_THREAD = 921, AVS_AEP_GETFRAME_RECURSIVE = 922 }; // enum AvsAllocType for avs_allocate enum { AVS_ALLOCTYPE_NORMAL_ALLOC = 1, AVS_ALLOCTYPE_POOLED_ALLOC = 2 }; #ifdef BUILDING_AVSCORE AVSValue create_c_video_filter(AVSValue args, void * user_data, IScriptEnvironment * e0); struct AVS_ScriptEnvironment { IScriptEnvironment * env; const char * error; AVS_ScriptEnvironment(IScriptEnvironment * e = 0) : env(e), error(0) {} }; #endif typedef struct AVS_Clip AVS_Clip; typedef struct AVS_ScriptEnvironment AVS_ScriptEnvironment; ///////////////////////////////////////////////////////////////////// // // AVS_VideoInfo // // AVS_VideoInfo is laid out identically to VideoInfo typedef struct AVS_VideoInfo { int width, height; // width=0 means no video unsigned fps_numerator, fps_denominator; int num_frames; int pixel_type; int audio_samples_per_second; // 0 means no audio int sample_type; int64_t num_audio_samples; int nchannels; // Image type properties // BFF, TFF, FIELDBASED. Also used for storing Channel Mask // Manipulate it through the channelmask interface calls int image_type; } AVS_VideoInfo; // useful functions of the above AVSC_INLINE int avs_has_video(const AVS_VideoInfo * p) { return (p->width!=0); } AVSC_INLINE int avs_has_audio(const AVS_VideoInfo * p) { return (p->audio_samples_per_second!=0); } AVSC_INLINE int avs_is_rgb(const AVS_VideoInfo * p) { return !!(p->pixel_type&AVS_CS_BGR); } AVSC_INLINE int avs_is_rgb24(const AVS_VideoInfo * p) { return ((p->pixel_type&AVS_CS_BGR24)==AVS_CS_BGR24) && ((p->pixel_type & AVS_CS_SAMPLE_BITS_MASK) == AVS_CS_SAMPLE_BITS_8); } AVSC_INLINE int avs_is_rgb32(const AVS_VideoInfo * p) { return ((p->pixel_type&AVS_CS_BGR32)==AVS_CS_BGR32) && ((p->pixel_type & AVS_CS_SAMPLE_BITS_MASK) == AVS_CS_SAMPLE_BITS_8); } AVSC_INLINE int avs_is_yuv(const AVS_VideoInfo * p) { return !!(p->pixel_type&AVS_CS_YUV ); } AVSC_INLINE int avs_is_yuy2(const AVS_VideoInfo * p) { return (p->pixel_type & AVS_CS_YUY2) == AVS_CS_YUY2; } AVSC_API(int, avs_is_yv24)(const AVS_VideoInfo * p); // avs+: for generic 444 check, use avs_is_yuv444 AVSC_API(int, avs_is_yv16)(const AVS_VideoInfo * p); // avs+: for generic 422 check, use avs_is_yuv422 AVSC_API(int, avs_is_yv12)(const AVS_VideoInfo * p) ; // avs+: for generic 420 check, use avs_is_yuv420 AVSC_API(int, avs_is_yv411)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_y8)(const AVS_VideoInfo * p); // avs+: for generic grayscale, use avs_is_y AVSC_API(int, avs_get_plane_width_subsampling)(const AVS_VideoInfo * p, int plane); AVSC_API(int, avs_get_plane_height_subsampling)(const AVS_VideoInfo * p, int plane); AVSC_API(int, avs_bits_per_pixel)(const AVS_VideoInfo * p); AVSC_API(int, avs_bytes_from_pixels)(const AVS_VideoInfo * p, int pixels); AVSC_API(int, avs_row_size)(const AVS_VideoInfo * p, int plane); AVSC_API(int, avs_bmp_size)(const AVS_VideoInfo * vi); AVSC_API(int, avs_is_color_space)(const AVS_VideoInfo * p, int c_space); // no API for these, inline helper functions AVSC_INLINE int avs_is_property(const AVS_VideoInfo * p, int property) { return ((p->image_type & property) == property); } AVSC_INLINE int avs_is_planar(const AVS_VideoInfo * p) { return !!(p->pixel_type & AVS_CS_PLANAR); } AVSC_INLINE int avs_is_field_based(const AVS_VideoInfo * p) { return !!(p->image_type & AVS_IT_FIELDBASED); } AVSC_INLINE int avs_is_parity_known(const AVS_VideoInfo * p) { return ((p->image_type & AVS_IT_FIELDBASED) && (p->image_type & (AVS_IT_BFF | AVS_IT_TFF))); } AVSC_INLINE int avs_is_bff(const AVS_VideoInfo * p) { return !!(p->image_type & AVS_IT_BFF); } AVSC_INLINE int avs_is_tff(const AVS_VideoInfo * p) { return !!(p->image_type & AVS_IT_TFF); } AVSC_INLINE int avs_samples_per_second(const AVS_VideoInfo * p) { return p->audio_samples_per_second; } AVSC_INLINE int avs_bytes_per_channel_sample(const AVS_VideoInfo * p) { switch (p->sample_type) { case AVS_SAMPLE_INT8: return sizeof(signed char); case AVS_SAMPLE_INT16: return sizeof(signed short); case AVS_SAMPLE_INT24: return 3; case AVS_SAMPLE_INT32: return sizeof(signed int); case AVS_SAMPLE_FLOAT: return sizeof(float); default: return 0; } } AVSC_INLINE int avs_bytes_per_audio_sample(const AVS_VideoInfo * p) { return p->nchannels*avs_bytes_per_channel_sample(p);} AVSC_INLINE int64_t avs_audio_samples_from_frames(const AVS_VideoInfo * p, int64_t frames) { return ((int64_t)(frames) * p->audio_samples_per_second * p->fps_denominator / p->fps_numerator); } AVSC_INLINE int avs_frames_from_audio_samples(const AVS_VideoInfo * p, int64_t samples) { return (int)(samples * (int64_t)p->fps_numerator / (int64_t)p->fps_denominator / (int64_t)p->audio_samples_per_second); } AVSC_INLINE int64_t avs_audio_samples_from_bytes(const AVS_VideoInfo * p, int64_t bytes) { return bytes / avs_bytes_per_audio_sample(p); } AVSC_INLINE int64_t avs_bytes_from_audio_samples(const AVS_VideoInfo * p, int64_t samples) { return samples * avs_bytes_per_audio_sample(p); } AVSC_INLINE int avs_audio_channels(const AVS_VideoInfo * p) { return p->nchannels; } AVSC_INLINE int avs_sample_type(const AVS_VideoInfo * p) { return p->sample_type;} // useful mutator // Note: these are video format properties, neither frame properties, nor system properties AVSC_INLINE void avs_set_property(AVS_VideoInfo * p, int property) { p->image_type|=property; } AVSC_INLINE void avs_clear_property(AVS_VideoInfo * p, int property) { p->image_type&=~property; } AVSC_INLINE void avs_set_field_based(AVS_VideoInfo * p, int isfieldbased) { if (isfieldbased) p->image_type|=AVS_IT_FIELDBASED; else p->image_type&=~AVS_IT_FIELDBASED; } AVSC_INLINE void avs_set_fps(AVS_VideoInfo * p, unsigned numerator, unsigned denominator) { unsigned x=numerator, y=denominator; while (y) { // find gcd unsigned t = x%y; x = y; y = t; } p->fps_numerator = numerator/x; p->fps_denominator = denominator/x; } #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_is_same_colorspace(const AVS_VideoInfo * x, const AVS_VideoInfo * y) { return (x->pixel_type == y->pixel_type) || (avs_is_yv12(x) && avs_is_yv12(y)); } #endif // AviSynth+ extensions AVSC_API(int, avs_is_rgb48)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_rgb64)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_yuv444p16)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv444 AVSC_API(int, avs_is_yuv422p16)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv422 AVSC_API(int, avs_is_yuv420p16)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv420 AVSC_API(int, avs_is_y16)(const AVS_VideoInfo * p); // deprecated, use avs_is_y AVSC_API(int, avs_is_yuv444ps)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv444 AVSC_API(int, avs_is_yuv422ps)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv422 AVSC_API(int, avs_is_yuv420ps)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv420 AVSC_API(int, avs_is_y32)(const AVS_VideoInfo * p); // deprecated, use avs_is_y AVSC_API(int, avs_is_444)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_422)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_420)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_y)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_yuva)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_planar_rgb)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_planar_rgba)(const AVS_VideoInfo * p); AVSC_API(int, avs_num_components)(const AVS_VideoInfo * p); AVSC_API(int, avs_component_size)(const AVS_VideoInfo * p); AVSC_API(int, avs_bits_per_component)(const AVS_VideoInfo * p); // V10 AVSC_API(bool, avs_is_channel_mask_known)(const AVS_VideoInfo* p); AVSC_API(void, avs_set_channel_mask)(const AVS_VideoInfo* p, bool isChannelMaskKnown, unsigned int dwChannelMask); AVSC_API(unsigned int, avs_get_channel_mask)(const AVS_VideoInfo* p); // end of Avisynth+ specific ///////////////////////////////////////////////////////////////////// // // AVS_VideoFrame // // VideoFrameBuffer holds information about a memory block which is used // for video data. For efficiency, instances of this class are not deleted // when the refcount reaches zero; instead they're stored in a linked list // to be reused. The instances are deleted when the corresponding AVS // file is closed. // AVS_VideoFrameBuffer is laid out identically to VideoFrameBuffer // DO NOT USE THIS STRUCTURE DIRECTLY typedef struct AVS_VideoFrameBuffer { BYTE * data; int data_size; // sequence_number is incremented every time the buffer is changed, so // that stale views can tell they're no longer valid. volatile long sequence_number; volatile long refcount; void* device; // avs+ } AVS_VideoFrameBuffer; // VideoFrame holds a "window" into a VideoFrameBuffer. // AVS_VideoFrame is laid out identically to VideoFrame // DO NOT USE THIS STRUCTURE DIRECTLY typedef struct AVS_VideoFrame { volatile long refcount; AVS_VideoFrameBuffer * vfb; int offset; // DO NOT USE THEM DIRECTLY // Use avs_get_pitch_p, avs_get_row_size_p, avs_get_height_p int pitch, row_size, height; int offsetU, offsetV; int pitchUV; // U&V offsets are from top of picture. int row_sizeUV, heightUV; // for Planar RGB offsetU, offsetV is for the 2nd and 3rd Plane. // for Planar RGB pitchUV and row_sizeUV = 0, because when no VideoInfo (MakeWriteable) // the decision on existence of UV is checked by zero pitch // AVS+ extension, avisynth.h: class does not break plugins if appended here int offsetA; int pitchA, row_sizeA; // 4th alpha plane support, pitch and row_size is 0 is none void* properties; // interface V8: frame properties // DO NOT USE DIRECTLY // Use avs_video_frame_get_pixel_type (and avs_video_frame_amend_pixel_type in special cases) int pixel_type; // Interface V10: an automatically maintained copy from AVS_VideoInfo } AVS_VideoFrame; // Access functions for AVS_VideoFrame AVSC_API(int, avs_get_pitch_p)(const AVS_VideoFrame * p, int plane); AVSC_API(int, avs_get_row_size_p)(const AVS_VideoFrame * p, int plane); AVSC_API(int, avs_get_height_p)(const AVS_VideoFrame * p, int plane); AVSC_API(const BYTE *, avs_get_read_ptr_p)(const AVS_VideoFrame * p, int plane); AVSC_API(int, avs_is_writable)(const AVS_VideoFrame * p); // V9 AVSC_API(int, avs_is_property_writable)(const AVS_VideoFrame* p); AVSC_API(BYTE *, avs_get_write_ptr_p)(const AVS_VideoFrame * p, int plane); AVSC_API(void, avs_release_video_frame)(AVS_VideoFrame *); // makes a shallow copy of a video frame AVSC_API(AVS_VideoFrame *, avs_copy_video_frame)(AVS_VideoFrame *); // V10 AVSC_API(int, avs_video_frame_get_pixel_type)(const AVS_VideoFrame* p); // V10 AVSC_API(void, avs_video_frame_amend_pixel_type)(AVS_VideoFrame* p, int new_pixel_type); // no API for these, inline helper functions #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_get_pitch(const AVS_VideoFrame * p) { return avs_get_pitch_p(p, 0); } #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_get_row_size(const AVS_VideoFrame * p) { return avs_get_row_size_p(p, 0); } #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_get_height(const AVS_VideoFrame * p) { return avs_get_height_p(p, 0); } #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE const BYTE* avs_get_read_ptr(const AVS_VideoFrame * p) { return avs_get_read_ptr_p(p, 0);} #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE BYTE* avs_get_write_ptr(const AVS_VideoFrame * p) { return avs_get_write_ptr_p(p, 0);} #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE void avs_release_frame(AVS_VideoFrame * f) {avs_release_video_frame(f);} #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE AVS_VideoFrame * avs_copy_frame(AVS_VideoFrame * f) {return avs_copy_video_frame(f);} #endif // Interface V8: frame properties // AVS_Map is just a placeholder for AVSMap typedef struct AVS_Map { void* data; } AVS_Map; ///////////////////////////////////////////////////////////////////// // // AVS_Value // // Treat AVS_Value as a fat pointer. That is use avs_copy_value // and avs_release_value appropriately as you would if AVS_Value was // a pointer. // To maintain source code compatibility with future versions of the // avisynth_c API don't use the AVS_Value directly. Use the helper // functions below. // AVS_Value is laid out identically to AVSValue typedef struct AVS_Value AVS_Value; struct AVS_Value { short type; // 'a'rray, 'c'lip, 'b'ool, 'i'nt, 'f'loat, 's'tring, 'v'oid, or 'l'ong, or fu'n'ction // for some function e'rror short array_size; union { void * clip; // do not use directly, use avs_take_clip char boolean; int integer; float floating_pt; const char * string; const AVS_Value * array; void * function; // not supported on C interface #ifdef X86_64 // if ever, only x64 will support. It breaks struct size on 32 bit int64_t longlong; // 8 bytes double double_pt; // 8 bytes #endif } d; }; // AVS_Value should be initialized with avs_void. // Should also set to avs_void after the value is released // with avs_copy_value. Consider it the equivalent of setting // a pointer to NULL static const AVS_Value avs_void = {'v'}; AVSC_API(void, avs_copy_value)(AVS_Value * dest, AVS_Value src); AVSC_API(void, avs_release_value)(AVS_Value); AVSC_API(AVS_Clip *, avs_take_clip)(AVS_Value, AVS_ScriptEnvironment *); AVSC_API(void, avs_set_to_clip)(AVS_Value *, AVS_Clip *); // no API for these, inline helper functions AVSC_INLINE int avs_defined(AVS_Value v) { return v.type != 'v'; } AVSC_INLINE int avs_is_clip(AVS_Value v) { return v.type == 'c'; } AVSC_INLINE int avs_is_bool(AVS_Value v) { return v.type == 'b'; } AVSC_INLINE int avs_is_int(AVS_Value v) { return v.type == 'i'; } AVSC_INLINE int avs_is_float(AVS_Value v) { return v.type == 'f' || v.type == 'i'; } AVSC_INLINE int avs_is_string(AVS_Value v) { return v.type == 's'; } AVSC_INLINE int avs_is_array(AVS_Value v) { return v.type == 'a'; } AVSC_INLINE int avs_is_error(AVS_Value v) { return v.type == 'e'; } AVSC_INLINE int avs_as_bool(AVS_Value v) { return v.d.boolean; } AVSC_INLINE int avs_as_int(AVS_Value v) { return v.d.integer; } AVSC_INLINE const char * avs_as_string(AVS_Value v) { return avs_is_error(v) || avs_is_string(v) ? v.d.string : 0; } AVSC_INLINE double avs_as_float(AVS_Value v) { return avs_is_int(v) ? v.d.integer : v.d.floating_pt; } AVSC_INLINE const char * avs_as_error(AVS_Value v) { return avs_is_error(v) ? v.d.string : 0; } AVSC_INLINE const AVS_Value * avs_as_array(AVS_Value v) { return v.d.array; } AVSC_INLINE int avs_array_size(AVS_Value v) { return avs_is_array(v) ? v.array_size : 1; } AVSC_INLINE AVS_Value avs_array_elt(AVS_Value v, int index) { return avs_is_array(v) ? v.d.array[index] : v; } // only use these functions on an AVS_Value that does not already have // an active value. Remember, treat AVS_Value as a fat pointer. AVSC_INLINE AVS_Value avs_new_value_bool(int v0) { AVS_Value v; v.type = 'b'; v.d.boolean = v0 == 0 ? 0 : 1; return v; } AVSC_INLINE AVS_Value avs_new_value_int(int v0) { AVS_Value v; v.type = 'i'; v.d.integer = v0; return v; } AVSC_INLINE AVS_Value avs_new_value_string(const char * v0) { AVS_Value v; v.type = 's'; v.d.string = v0; return v; } AVSC_INLINE AVS_Value avs_new_value_float(float v0) { AVS_Value v; v.type = 'f'; v.d.floating_pt = v0; return v;} AVSC_INLINE AVS_Value avs_new_value_error(const char * v0) { AVS_Value v; v.type = 'e'; v.d.string = v0; return v; } #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE AVS_Value avs_new_value_clip(AVS_Clip * v0) { AVS_Value v; avs_set_to_clip(&v, v0); return v; } #endif AVSC_INLINE AVS_Value avs_new_value_array(AVS_Value * v0, int size) { AVS_Value v; v.type = 'a'; v.d.array = v0; v.array_size = (short)size; return v; } // end of inline helper functions ///////////////////////////////////////////////////////////////////// // // AVS_Clip // AVSC_API(void, avs_release_clip)(AVS_Clip *); AVSC_API(AVS_Clip *, avs_copy_clip)(AVS_Clip *); AVSC_API(const char *, avs_clip_get_error)(AVS_Clip *); // return 0 if no error AVSC_API(const AVS_VideoInfo *, avs_get_video_info)(AVS_Clip *); AVSC_API(int, avs_get_version)(AVS_Clip *); AVSC_API(AVS_VideoFrame *, avs_get_frame)(AVS_Clip *, int n); // The returned video frame must be released with avs_release_video_frame AVSC_API(int, avs_get_parity)(AVS_Clip *, int n); // return field parity if field_based, else parity of first field in frame AVSC_API(int, avs_get_audio)(AVS_Clip *, void * buf, int64_t start, int64_t count); // start and count are in samples AVSC_API(int, avs_set_cache_hints)(AVS_Clip *, int cachehints, int frame_range); // This is the callback type used by avs_add_function typedef AVS_Value (AVSC_CC * AVS_ApplyFunc) (AVS_ScriptEnvironment *, AVS_Value args, void * user_data); typedef struct AVS_FilterInfo AVS_FilterInfo; struct AVS_FilterInfo { // these members should not be modified outside of the AVS_ApplyFunc callback AVS_Clip * child; AVS_VideoInfo vi; AVS_ScriptEnvironment * env; AVS_VideoFrame * (AVSC_CC * get_frame)(AVS_FilterInfo *, int n); int (AVSC_CC * get_parity)(AVS_FilterInfo *, int n); int (AVSC_CC * get_audio)(AVS_FilterInfo *, void * buf, int64_t start, int64_t count); int (AVSC_CC * set_cache_hints)(AVS_FilterInfo *, int cachehints, int frame_range); void (AVSC_CC * free_filter)(AVS_FilterInfo *); // Should be set when ever there is an error to report. // It is cleared before any of the above methods are called const char * error; // this is to store whatever and may be modified at will void * user_data; }; // Create a new filter // fi is set to point to the AVS_FilterInfo so that you can // modify it once it is initialized. // store_child should generally be set to true. If it is not // set than ALL methods (the function pointers) must be defined // If it is set than you do not need to worry about freeing the child // clip. AVSC_API(AVS_Clip *, avs_new_c_filter)(AVS_ScriptEnvironment * e, AVS_FilterInfo * * fi, AVS_Value child, int store_child); ///////////////////////////////////////////////////////////////////// // // AVS_ScriptEnvironment // // For GetCPUFlags. These are backwards-compatible with those in VirtualDub. enum { /* slowest CPU to support extension */ AVS_CPU_FORCE = 0x01, // N/A AVS_CPU_FPU = 0x02, // 386/486DX AVS_CPU_MMX = 0x04, // P55C, K6, PII AVS_CPU_INTEGER_SSE = 0x08, // PIII, Athlon AVS_CPU_SSE = 0x10, // PIII, Athlon XP/MP AVS_CPU_SSE2 = 0x20, // PIV, Hammer AVS_CPU_3DNOW = 0x40, // K6-2 AVS_CPU_3DNOW_EXT = 0x80, // Athlon AVS_CPU_X86_64 = 0xA0, // Hammer (note: equiv. to 3DNow + SSE2, // which only Hammer will have anyway) AVS_CPUF_SSE3 = 0x100, // PIV+, K8 Venice AVS_CPUF_SSSE3 = 0x200, // Core 2 AVS_CPUF_SSE4 = 0x400, // Penryn, Wolfdale, Yorkfield AVS_CPUF_SSE4_1 = 0x400, AVS_CPUF_AVX = 0x800, // Sandy Bridge, Bulldozer AVS_CPUF_SSE4_2 = 0x1000, // Nehalem // AVS+ AVS_CPUF_AVX2 = 0x2000, // Haswell AVS_CPUF_FMA3 = 0x4000, AVS_CPUF_F16C = 0x8000, AVS_CPUF_MOVBE = 0x10000, // Big Endian Move AVS_CPUF_POPCNT = 0x20000, AVS_CPUF_AES = 0x40000, AVS_CPUF_FMA4 = 0x80000, AVS_CPUF_AVX512F = 0x100000, // AVX-512 Foundation. AVS_CPUF_AVX512DQ = 0x200000, // AVX-512 DQ (Double/Quad granular) Instructions AVS_CPUF_AVX512PF = 0x400000, // AVX-512 Prefetch AVS_CPUF_AVX512ER = 0x800000, // AVX-512 Exponential and Reciprocal AVS_CPUF_AVX512CD = 0x1000000, // AVX-512 Conflict Detection AVS_CPUF_AVX512BW = 0x2000000, // AVX-512 BW (Byte/Word granular) Instructions AVS_CPUF_AVX512VL = 0x4000000, // AVX-512 VL (128/256 Vector Length) Extensions AVS_CPUF_AVX512IFMA = 0x8000000, // AVX-512 IFMA integer 52 bit AVS_CPUF_AVX512VBMI = 0x10000000 // AVX-512 VBMI }; AVSC_API(const char *, avs_get_error)(AVS_ScriptEnvironment *); // return 0 if no error AVSC_API(int, avs_get_cpu_flags)(AVS_ScriptEnvironment *); AVSC_API(int, avs_check_version)(AVS_ScriptEnvironment *, int version); AVSC_API(char *, avs_save_string)(AVS_ScriptEnvironment *, const char* s, int length); AVSC_API(char *, avs_sprintf)(AVS_ScriptEnvironment *, const char * fmt, ...); AVSC_API(char *, avs_vsprintf)(AVS_ScriptEnvironment *, const char * fmt, va_list val); AVSC_API(int, avs_add_function)(AVS_ScriptEnvironment *, const char * name, const char * params, AVS_ApplyFunc apply, void * user_data); AVSC_API(int, avs_function_exists)(AVS_ScriptEnvironment *, const char * name); AVSC_API(AVS_Value, avs_invoke)(AVS_ScriptEnvironment *, const char * name, AVS_Value args, const char** arg_names); // The returned value must be be released with avs_release_value AVSC_API(AVS_Value, avs_get_var)(AVS_ScriptEnvironment *, const char* name); // The returned value must be be released with avs_release_value AVSC_API(int, avs_set_var)(AVS_ScriptEnvironment *, const char* name, AVS_Value val); AVSC_API(int, avs_set_global_var)(AVS_ScriptEnvironment *, const char* name, const AVS_Value val); //void avs_push_context(AVS_ScriptEnvironment *, int level=0); //void avs_pop_context(AVS_ScriptEnvironment *); // partially deprecated, from V8 use avs_new_video_frame_p_a (frame property copy) AVSC_API(AVS_VideoFrame *, avs_new_video_frame_a)(AVS_ScriptEnvironment *, const AVS_VideoInfo * vi, int align); // align should be at least 16 for classic Avisynth // Avisynth+: any value, Avs+ ensures a minimum alignment if too small align is provided // no API for these, inline helper functions #ifndef AVSC_NO_DECLSPEC // partially deprecated, from V8 use avs_new_video_frame_p (frame property copy) // this inline function is calling an API function AVSC_INLINE AVS_VideoFrame * avs_new_video_frame(AVS_ScriptEnvironment * env, const AVS_VideoInfo * vi) {return avs_new_video_frame_a(env,vi,AVS_FRAME_ALIGN);} // an older compatibility alias // this inline function is calling an API function AVSC_INLINE AVS_VideoFrame * avs_new_frame(AVS_ScriptEnvironment * env, const AVS_VideoInfo * vi) {return avs_new_video_frame_a(env,vi,AVS_FRAME_ALIGN);} #endif // end of inline helper functions AVSC_API(int, avs_make_writable)(AVS_ScriptEnvironment *, AVS_VideoFrame * * pvf); // V9 AVSC_API(int, avs_make_property_writable)(AVS_ScriptEnvironment*, AVS_VideoFrame** pvf); AVSC_API(void, avs_bit_blt)(AVS_ScriptEnvironment *, BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height); typedef void (AVSC_CC *AVS_ShutdownFunc)(void* user_data, AVS_ScriptEnvironment * env); AVSC_API(void, avs_at_exit)(AVS_ScriptEnvironment *, AVS_ShutdownFunc function, void * user_data); AVSC_API(AVS_VideoFrame *, avs_subframe)(AVS_ScriptEnvironment *, AVS_VideoFrame * src, int rel_offset, int new_pitch, int new_row_size, int new_height); // The returned video frame must be be released AVSC_API(AVS_VideoFrame*, avs_subframe_planar)(AVS_ScriptEnvironment*, AVS_VideoFrame* src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV); // The returned video frame must be be released // see also avs_subframe_planar_a in interface V8 AVSC_API(int, avs_set_memory_max)(AVS_ScriptEnvironment *, int mem); AVSC_API(int, avs_set_working_dir)(AVS_ScriptEnvironment *, const char * newdir); // avisynth.dll exports this; it's a way to use it as a library, without // writing an AVS script or without going through AVIFile. AVSC_API(AVS_ScriptEnvironment *, avs_create_script_environment)(int version); // this symbol is the entry point for the plugin and must // be defined AVSC_EXPORT const char * AVSC_CC avisynth_c_plugin_init(AVS_ScriptEnvironment* env); AVSC_API(void, avs_delete_script_environment)(AVS_ScriptEnvironment *); /////////////////////////////////////////////////////////////////////////////// // // Avisynth+ V8 interface elements // AVSC_API(AVS_VideoFrame*, avs_subframe_planar_a)(AVS_ScriptEnvironment*, AVS_VideoFrame* src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA); // The returned video frame must be be released AVSC_API(void, avs_copy_frame_props)(AVS_ScriptEnvironment* p, const AVS_VideoFrame* src, AVS_VideoFrame* dst); AVSC_API(const AVS_Map*, avs_get_frame_props_ro)(AVS_ScriptEnvironment* p, const AVS_VideoFrame* frame); AVSC_API(AVS_Map*, avs_get_frame_props_rw)(AVS_ScriptEnvironment* p, AVS_VideoFrame* frame); AVSC_API(int, avs_prop_num_keys)(AVS_ScriptEnvironment* p, const AVS_Map* map); AVSC_API(const char*, avs_prop_get_key)(AVS_ScriptEnvironment* p, const AVS_Map* map, int index); AVSC_API(int, avs_prop_num_elements)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key); // see AVS_PROPTYPE_... enums AVSC_API(char, avs_prop_get_type)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key); // see AVS_GETPROPERROR_... enums AVSC_API(int64_t, avs_prop_get_int)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(double, avs_prop_get_float)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); // Note: avs_prop_get_data was fixed in interface V9.1 AVSC_API(const char*, avs_prop_get_data)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(int, avs_prop_get_data_size)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(AVS_Clip*, avs_prop_get_clip)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(const AVS_VideoFrame*, avs_prop_get_frame)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(int, avs_prop_delete_key)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key); // see AVS_PROPAPPENDMODE_... enums AVSC_API(int, avs_prop_set_int)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, int64_t i, int append); AVSC_API(int, avs_prop_set_float)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, double d, int append); AVSC_API(int, avs_prop_set_data)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const char* d, int length, int append); AVSC_API(int, avs_prop_set_clip)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, AVS_Clip* clip, int append); AVSC_API(int, avs_prop_set_frame)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const AVS_VideoFrame* frame, int append); AVSC_API(const int64_t*, avs_prop_get_int_array)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int* error); AVSC_API(const double*, avs_prop_get_float_array)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int* error); AVSC_API(int, avs_prop_set_int_array)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const int64_t* i, int size); AVSC_API(int, avs_prop_set_float_array)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const double* d, int size); AVSC_API(void, avs_clear_map)(AVS_ScriptEnvironment* p, AVS_Map* map); // with frame property source AVSC_API(AVS_VideoFrame*, avs_new_video_frame_p)(AVS_ScriptEnvironment*, const AVS_VideoInfo* vi, const AVS_VideoFrame* prop_src); // with frame property source AVSC_API(AVS_VideoFrame*, avs_new_video_frame_p_a)(AVS_ScriptEnvironment*, const AVS_VideoInfo* vi, const AVS_VideoFrame* prop_src, int align); // Generic query to ask for various system properties, see AVS_AEP_xxx enums AVSC_API(size_t, avs_get_env_property)(AVS_ScriptEnvironment*, int avs_aep_prop); // buffer pool, see AVS_ALLOCTYPE enums AVSC_API(void *, avs_pool_allocate)(AVS_ScriptEnvironment*, size_t nBytes, size_t alignment, int avs_alloc_type); AVSC_API(void, avs_pool_free)(AVS_ScriptEnvironment*, void *ptr); // Interface V8 // Returns TRUE (1) and the requested variable. If the method fails, returns 0 (FALSE) and does not touch 'val'. // The returned AVS_Value *val value must be be released with avs_release_value only on success // AVS_Value *val is not caller allocated AVSC_API(int, avs_get_var_try)(AVS_ScriptEnvironment*, const char* name, AVS_Value* val); // Interface V8 // Return the value of the requested variable. // If the variable was not found or had the wrong type, // return the supplied default value. AVSC_API(int, avs_get_var_bool)(AVS_ScriptEnvironment*, const char* name, int def); AVSC_API(int, avs_get_var_int)(AVS_ScriptEnvironment*, const char* name, int def); AVSC_API(double, avs_get_var_double)(AVS_ScriptEnvironment*, const char* name, double def); AVSC_API(const char*, avs_get_var_string)(AVS_ScriptEnvironment*, const char* name, const char* def); AVSC_API(int64_t, avs_get_var_long)(AVS_ScriptEnvironment*, const char* name, int64_t def); #if defined(AVS_WINDOWS) // The following stuff is only relevant for Windows DLL handling; Linux does it completely differently. #ifdef AVSC_NO_DECLSPEC // This part uses LoadLibrary and related functions to dynamically load Avisynth instead of declspec(dllimport) // When AVSC_NO_DECLSPEC is defined, you can use avs_load_library to populate API functions into a struct // AVSC_INLINE functions which call onto an API functions should be treated specially (todo) /* The following functions needs to have been declared, probably from windows.h void* malloc(size_t) void free(void*); HMODULE LoadLibraryA(const char*); void* GetProcAddress(HMODULE, const char*); FreeLibrary(HMODULE); */ typedef struct AVS_Library AVS_Library; #define AVSC_DECLARE_FUNC(name) name##_func name // AVSC_DECLARE_FUNC helps keeping naming convention: type is xxxxx_func, function name is xxxxx // e.g. "AVSC_DECLARE_FUNC(avs_add_function);" // is a shortcut for "avs_add_function_func avs_add_function;" // Note: AVSC_INLINE functions, which call into API, // are guarded by #ifndef AVSC_NO_DECLSPEC. // They should call the appropriate library-> API entry. struct AVS_Library { HMODULE handle; AVSC_DECLARE_FUNC(avs_add_function); AVSC_DECLARE_FUNC(avs_at_exit); AVSC_DECLARE_FUNC(avs_bit_blt); AVSC_DECLARE_FUNC(avs_check_version); AVSC_DECLARE_FUNC(avs_clip_get_error); AVSC_DECLARE_FUNC(avs_copy_clip); AVSC_DECLARE_FUNC(avs_copy_value); AVSC_DECLARE_FUNC(avs_copy_video_frame); AVSC_DECLARE_FUNC(avs_create_script_environment); AVSC_DECLARE_FUNC(avs_delete_script_environment); AVSC_DECLARE_FUNC(avs_function_exists); AVSC_DECLARE_FUNC(avs_get_audio); AVSC_DECLARE_FUNC(avs_get_cpu_flags); AVSC_DECLARE_FUNC(avs_get_frame); AVSC_DECLARE_FUNC(avs_get_parity); AVSC_DECLARE_FUNC(avs_get_var); AVSC_DECLARE_FUNC(avs_get_version); AVSC_DECLARE_FUNC(avs_get_video_info); AVSC_DECLARE_FUNC(avs_invoke); AVSC_DECLARE_FUNC(avs_make_writable); AVSC_DECLARE_FUNC(avs_new_c_filter); AVSC_DECLARE_FUNC(avs_new_video_frame_a); AVSC_DECLARE_FUNC(avs_release_clip); AVSC_DECLARE_FUNC(avs_release_value); AVSC_DECLARE_FUNC(avs_release_video_frame); AVSC_DECLARE_FUNC(avs_save_string); AVSC_DECLARE_FUNC(avs_set_cache_hints); AVSC_DECLARE_FUNC(avs_set_global_var); AVSC_DECLARE_FUNC(avs_set_memory_max); AVSC_DECLARE_FUNC(avs_set_to_clip); AVSC_DECLARE_FUNC(avs_set_var); AVSC_DECLARE_FUNC(avs_set_working_dir); AVSC_DECLARE_FUNC(avs_sprintf); AVSC_DECLARE_FUNC(avs_subframe); AVSC_DECLARE_FUNC(avs_subframe_planar); AVSC_DECLARE_FUNC(avs_take_clip); AVSC_DECLARE_FUNC(avs_vsprintf); AVSC_DECLARE_FUNC(avs_get_error); AVSC_DECLARE_FUNC(avs_is_yv24); AVSC_DECLARE_FUNC(avs_is_yv16); AVSC_DECLARE_FUNC(avs_is_yv12); AVSC_DECLARE_FUNC(avs_is_yv411); AVSC_DECLARE_FUNC(avs_is_y8); AVSC_DECLARE_FUNC(avs_is_color_space); AVSC_DECLARE_FUNC(avs_get_plane_width_subsampling); AVSC_DECLARE_FUNC(avs_get_plane_height_subsampling); AVSC_DECLARE_FUNC(avs_bits_per_pixel); AVSC_DECLARE_FUNC(avs_bytes_from_pixels); AVSC_DECLARE_FUNC(avs_row_size); AVSC_DECLARE_FUNC(avs_bmp_size); AVSC_DECLARE_FUNC(avs_get_pitch_p); AVSC_DECLARE_FUNC(avs_get_row_size_p); AVSC_DECLARE_FUNC(avs_get_height_p); AVSC_DECLARE_FUNC(avs_get_read_ptr_p); AVSC_DECLARE_FUNC(avs_is_writable); AVSC_DECLARE_FUNC(avs_get_write_ptr_p); // Avisynth+ specific // Note: these functions are simulated/use fallback to existing functions AVSC_DECLARE_FUNC(avs_is_rgb48); AVSC_DECLARE_FUNC(avs_is_rgb64); AVSC_DECLARE_FUNC(avs_is_yuv444p16); AVSC_DECLARE_FUNC(avs_is_yuv422p16); AVSC_DECLARE_FUNC(avs_is_yuv420p16); AVSC_DECLARE_FUNC(avs_is_y16); AVSC_DECLARE_FUNC(avs_is_yuv444ps); AVSC_DECLARE_FUNC(avs_is_yuv422ps); AVSC_DECLARE_FUNC(avs_is_yuv420ps); AVSC_DECLARE_FUNC(avs_is_y32); AVSC_DECLARE_FUNC(avs_is_444); AVSC_DECLARE_FUNC(avs_is_422); AVSC_DECLARE_FUNC(avs_is_420); AVSC_DECLARE_FUNC(avs_is_y); AVSC_DECLARE_FUNC(avs_is_yuva); AVSC_DECLARE_FUNC(avs_is_planar_rgb); AVSC_DECLARE_FUNC(avs_is_planar_rgba); AVSC_DECLARE_FUNC(avs_num_components); AVSC_DECLARE_FUNC(avs_component_size); AVSC_DECLARE_FUNC(avs_bits_per_component); /////////////////////////////////////////////////////////////////////////////// // Avisynth+ new interface elements from interface version 8 // avs_subframe_planar with alpha support AVSC_DECLARE_FUNC(avs_subframe_planar_a); // frame properties AVSC_DECLARE_FUNC(avs_copy_frame_props); AVSC_DECLARE_FUNC(avs_get_frame_props_ro); AVSC_DECLARE_FUNC(avs_get_frame_props_rw); AVSC_DECLARE_FUNC(avs_prop_num_keys); AVSC_DECLARE_FUNC(avs_prop_get_key); AVSC_DECLARE_FUNC(avs_prop_num_elements); AVSC_DECLARE_FUNC(avs_prop_get_type); AVSC_DECLARE_FUNC(avs_prop_get_int); AVSC_DECLARE_FUNC(avs_prop_get_float); AVSC_DECLARE_FUNC(avs_prop_get_data); AVSC_DECLARE_FUNC(avs_prop_get_data_size); AVSC_DECLARE_FUNC(avs_prop_get_clip); AVSC_DECLARE_FUNC(avs_prop_get_frame); AVSC_DECLARE_FUNC(avs_prop_delete_key); AVSC_DECLARE_FUNC(avs_prop_set_int); AVSC_DECLARE_FUNC(avs_prop_set_float); AVSC_DECLARE_FUNC(avs_prop_set_data); AVSC_DECLARE_FUNC(avs_prop_set_clip); AVSC_DECLARE_FUNC(avs_prop_set_frame); AVSC_DECLARE_FUNC(avs_prop_get_int_array); AVSC_DECLARE_FUNC(avs_prop_get_float_array); AVSC_DECLARE_FUNC(avs_prop_set_int_array); AVSC_DECLARE_FUNC(avs_prop_set_float_array); AVSC_DECLARE_FUNC(avs_clear_map); // NewVideoFrame with frame properties AVSC_DECLARE_FUNC(avs_new_video_frame_p); AVSC_DECLARE_FUNC(avs_new_video_frame_p_a); AVSC_DECLARE_FUNC(avs_get_env_property); AVSC_DECLARE_FUNC(avs_get_var_try); AVSC_DECLARE_FUNC(avs_get_var_bool); AVSC_DECLARE_FUNC(avs_get_var_int); AVSC_DECLARE_FUNC(avs_get_var_double); AVSC_DECLARE_FUNC(avs_get_var_string); AVSC_DECLARE_FUNC(avs_get_var_long); AVSC_DECLARE_FUNC(avs_pool_allocate); AVSC_DECLARE_FUNC(avs_pool_free); // V9 AVSC_DECLARE_FUNC(avs_is_property_writable); AVSC_DECLARE_FUNC(avs_make_property_writable); // V10 AVSC_DECLARE_FUNC(avs_video_frame_get_pixel_type); AVSC_DECLARE_FUNC(avs_video_frame_amend_pixel_type); // V10 AVSC_DECLARE_FUNC(avs_is_channel_mask_known); AVSC_DECLARE_FUNC(avs_set_channel_mask); AVSC_DECLARE_FUNC(avs_get_channel_mask); }; #undef AVSC_DECLARE_FUNC #ifdef AVS26_FALLBACK_SIMULATION // Helper functions for fallback simulation // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_is_xx_fallback_return_false(const AVS_VideoInfo * p) { return 0; } // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_num_components_fallback(const AVS_VideoInfo * p) { switch (p->pixel_type) { case AVS_CS_UNKNOWN: return 0; case AVS_CS_RAW32: case AVS_CS_Y8: return 1; case AVS_CS_BGR32: return 4; // not planar but return the count default: return 3; } } // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_component_size_fallback(const AVS_VideoInfo * p) { return 1; } // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_bits_per_component_fallback(const AVS_VideoInfo * p) { return 8; } // End of helper functions for fallback simulation #endif // AVS26_FALLBACK_SIMULATION // avs_load_library() allocates an array for API procedure entries // reads and fills the entries with live procedure addresses. // AVSC_INLINE helpers which are calling into API procedures are not treated here (todo) AVSC_INLINE AVS_Library * avs_load_library() { AVS_Library *library = (AVS_Library *)malloc(sizeof(AVS_Library)); if (library == NULL) return NULL; library->handle = LoadLibraryA("avisynth"); if (library->handle == NULL) goto fail; #define __AVSC_STRINGIFY(x) #x #define AVSC_STRINGIFY(x) __AVSC_STRINGIFY(x) #define AVSC_LOAD_FUNC(name) {\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name));\ if (library->name == NULL)\ goto fail;\ } #ifdef AVS26_FALLBACK_SIMULATION // When an API function is not loadable, let's try a replacement // Missing Avisynth+ functions will be substituted with classic Avisynth compatible methods /* Avisynth+ When method is missing (classic Avisynth) avs_is_rgb48 constant false avs_is_rgb64 constant false avs_is_444 avs_is_yv24 avs_is_422 avs_is_yv16 avs_is_420 avs_is_yv12 avs_is_y avs_is_y8 avs_is_yuva constant false avs_is_planar_rgb constant false avs_is_planar_rgba constant false avs_num_components special: avs_num_components_fake Y8:1 RGB32:4 else 3 avs_component_size constant 1 (1 bytes/component) avs_bits_per_component constant 8 (8 bits/component) */ // try to load an alternative function #define AVSC_LOAD_FUNC_FALLBACK(name,name2) {\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name));\ if (library->name == NULL)\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name2));\ if (library->name == NULL)\ goto fail;\ } // try to assign a replacement function #define AVSC_LOAD_FUNC_FALLBACK_SIMULATED(name,name2) {\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name));\ if (library->name == NULL)\ library->name = name2;\ if (library->name == NULL)\ goto fail;\ } #endif // AVS26_FALLBACK_SIMULATION AVSC_LOAD_FUNC(avs_add_function); AVSC_LOAD_FUNC(avs_at_exit); AVSC_LOAD_FUNC(avs_bit_blt); AVSC_LOAD_FUNC(avs_check_version); AVSC_LOAD_FUNC(avs_clip_get_error); AVSC_LOAD_FUNC(avs_copy_clip); AVSC_LOAD_FUNC(avs_copy_value); AVSC_LOAD_FUNC(avs_copy_video_frame); AVSC_LOAD_FUNC(avs_create_script_environment); AVSC_LOAD_FUNC(avs_delete_script_environment); AVSC_LOAD_FUNC(avs_function_exists); AVSC_LOAD_FUNC(avs_get_audio); AVSC_LOAD_FUNC(avs_get_cpu_flags); AVSC_LOAD_FUNC(avs_get_frame); AVSC_LOAD_FUNC(avs_get_parity); AVSC_LOAD_FUNC(avs_get_var); AVSC_LOAD_FUNC(avs_get_version); AVSC_LOAD_FUNC(avs_get_video_info); AVSC_LOAD_FUNC(avs_invoke); AVSC_LOAD_FUNC(avs_make_writable); AVSC_LOAD_FUNC(avs_new_c_filter); AVSC_LOAD_FUNC(avs_new_video_frame_a); AVSC_LOAD_FUNC(avs_release_clip); AVSC_LOAD_FUNC(avs_release_value); AVSC_LOAD_FUNC(avs_release_video_frame); AVSC_LOAD_FUNC(avs_save_string); AVSC_LOAD_FUNC(avs_set_cache_hints); AVSC_LOAD_FUNC(avs_set_global_var); AVSC_LOAD_FUNC(avs_set_memory_max); AVSC_LOAD_FUNC(avs_set_to_clip); AVSC_LOAD_FUNC(avs_set_var); AVSC_LOAD_FUNC(avs_set_working_dir); AVSC_LOAD_FUNC(avs_sprintf); AVSC_LOAD_FUNC(avs_subframe); AVSC_LOAD_FUNC(avs_subframe_planar); AVSC_LOAD_FUNC(avs_take_clip); AVSC_LOAD_FUNC(avs_vsprintf); AVSC_LOAD_FUNC(avs_get_error); AVSC_LOAD_FUNC(avs_is_yv24); AVSC_LOAD_FUNC(avs_is_yv16); AVSC_LOAD_FUNC(avs_is_yv12); AVSC_LOAD_FUNC(avs_is_yv411); AVSC_LOAD_FUNC(avs_is_y8); AVSC_LOAD_FUNC(avs_is_color_space); AVSC_LOAD_FUNC(avs_get_plane_width_subsampling); AVSC_LOAD_FUNC(avs_get_plane_height_subsampling); AVSC_LOAD_FUNC(avs_bits_per_pixel); AVSC_LOAD_FUNC(avs_bytes_from_pixels); AVSC_LOAD_FUNC(avs_row_size); AVSC_LOAD_FUNC(avs_bmp_size); AVSC_LOAD_FUNC(avs_get_pitch_p); AVSC_LOAD_FUNC(avs_get_row_size_p); AVSC_LOAD_FUNC(avs_get_height_p); AVSC_LOAD_FUNC(avs_get_read_ptr_p); AVSC_LOAD_FUNC(avs_is_writable); AVSC_LOAD_FUNC(avs_get_write_ptr_p); // Avisynth+ specific #ifdef AVS26_FALLBACK_SIMULATION // replace with fallback fn when does not exist AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_rgb48, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_rgb64, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK(avs_is_444, avs_is_yv24); AVSC_LOAD_FUNC_FALLBACK(avs_is_422, avs_is_yv16); AVSC_LOAD_FUNC_FALLBACK(avs_is_420, avs_is_yv12); AVSC_LOAD_FUNC_FALLBACK(avs_is_y, avs_is_y8); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_yuva, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_planar_rgb, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_planar_rgba, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_num_components, avs_num_components_fallback); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_component_size, avs_component_size_fallback); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_bits_per_component, avs_bits_per_component_fallback); #else // Avisynth+ specific AVSC_LOAD_FUNC(avs_is_rgb48); AVSC_LOAD_FUNC(avs_is_rgb64); AVSC_LOAD_FUNC(avs_is_444); AVSC_LOAD_FUNC(avs_is_422); AVSC_LOAD_FUNC(avs_is_420); AVSC_LOAD_FUNC(avs_is_y); AVSC_LOAD_FUNC(avs_is_yuva); AVSC_LOAD_FUNC(avs_is_planar_rgb); AVSC_LOAD_FUNC(avs_is_planar_rgba); AVSC_LOAD_FUNC(avs_num_components); AVSC_LOAD_FUNC(avs_component_size); AVSC_LOAD_FUNC(avs_bits_per_component); #endif // Avisynth+ interface V8, no backward compatible simulation AVSC_LOAD_FUNC(avs_subframe_planar_a); // frame properties AVSC_LOAD_FUNC(avs_copy_frame_props); AVSC_LOAD_FUNC(avs_get_frame_props_ro); AVSC_LOAD_FUNC(avs_get_frame_props_rw); AVSC_LOAD_FUNC(avs_prop_num_keys); AVSC_LOAD_FUNC(avs_prop_get_key); AVSC_LOAD_FUNC(avs_prop_num_elements); AVSC_LOAD_FUNC(avs_prop_get_type); AVSC_LOAD_FUNC(avs_prop_get_int); AVSC_LOAD_FUNC(avs_prop_get_float); AVSC_LOAD_FUNC(avs_prop_get_data); AVSC_LOAD_FUNC(avs_prop_get_data_size); AVSC_LOAD_FUNC(avs_prop_get_clip); AVSC_LOAD_FUNC(avs_prop_get_frame); AVSC_LOAD_FUNC(avs_prop_delete_key); AVSC_LOAD_FUNC(avs_prop_set_int); AVSC_LOAD_FUNC(avs_prop_set_float); AVSC_LOAD_FUNC(avs_prop_set_data); AVSC_LOAD_FUNC(avs_prop_set_clip); AVSC_LOAD_FUNC(avs_prop_set_frame); AVSC_LOAD_FUNC(avs_prop_get_int_array); AVSC_LOAD_FUNC(avs_prop_get_float_array); AVSC_LOAD_FUNC(avs_prop_set_int_array); AVSC_LOAD_FUNC(avs_prop_set_float_array); AVSC_LOAD_FUNC(avs_clear_map); // NewVideoFrame with frame properties AVSC_LOAD_FUNC(avs_new_video_frame_p); AVSC_LOAD_FUNC(avs_new_video_frame_p_a); AVSC_LOAD_FUNC(avs_get_env_property); AVSC_LOAD_FUNC(avs_get_var_try); AVSC_LOAD_FUNC(avs_get_var_bool); AVSC_LOAD_FUNC(avs_get_var_int); AVSC_LOAD_FUNC(avs_get_var_double); AVSC_LOAD_FUNC(avs_get_var_string); AVSC_LOAD_FUNC(avs_get_var_long); AVSC_LOAD_FUNC(avs_pool_allocate); AVSC_LOAD_FUNC(avs_pool_free); // V9 AVSC_LOAD_FUNC(avs_make_property_writable); AVSC_LOAD_FUNC(avs_is_property_writable); // V10 AVSC_LOAD_FUNC(avs_video_frame_get_pixel_type); AVSC_LOAD_FUNC(avs_video_frame_amend_pixel_type); // V10 AVSC_LOAD_FUNC(avs_is_channel_mask_known); AVSC_LOAD_FUNC(avs_set_channel_mask); AVSC_LOAD_FUNC(avs_get_channel_mask); #undef __AVSC_STRINGIFY #undef AVSC_STRINGIFY #undef AVSC_LOAD_FUNC #undef AVSC_LOAD_FUNC_FALLBACK #undef AVSC_LOAD_FUNC_FALLBACK_SIMULATED return library; fail: free(library); return NULL; } AVSC_INLINE void avs_free_library(AVS_Library *library) { if (library == NULL) return; FreeLibrary(library->handle); free(library); } #endif #endif // AVS_WINDOWS #endif ================================================ FILE: thirdparty/32/include/avisynth/avs/alignment.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_ALIGNMENT_H #define AVS_ALIGNMENT_H // Functions and macros to help work with alignment requirements. // Tells if a number is a power of two. #define IS_POWER2(n) ((n) && !((n) & ((n) - 1))) // Tells if the pointer "ptr" is aligned to "align" bytes. #define IS_PTR_ALIGNED(ptr, align) (((uintptr_t)ptr & ((uintptr_t)(align-1))) == 0) // Rounds up the number "n" to the next greater multiple of "align" #define ALIGN_NUMBER(n, align) (((n) + (align)-1) & (~((align)-1))) // Rounds up the pointer address "ptr" to the next greater multiple of "align" #define ALIGN_POINTER(ptr, align) (((uintptr_t)(ptr) + (align)-1) & (~(uintptr_t)((align)-1))) #ifdef __cplusplus #include #include #include #include "config.h" #if defined(MSVC) && _MSC_VER<1400 // needed for VS2013, otherwise C++11 'alignas' works #define avs_alignas(x) __declspec(align(x)) #else // assumes C++11 support #define avs_alignas(x) alignas(x) #endif template static bool IsPtrAligned(T* ptr, size_t align) { assert(IS_POWER2(align)); return (bool)IS_PTR_ALIGNED(ptr, align); } template static T AlignNumber(T n, T align) { assert(IS_POWER2(align)); return ALIGN_NUMBER(n, align); } template static T* AlignPointer(T* ptr, size_t align) { assert(IS_POWER2(align)); return (T*)ALIGN_POINTER(ptr, align); } extern "C" { #else #include #endif // __cplusplus // Returns a new buffer that is at least the size "nbytes". // The buffer will be aligned to "align" bytes. // Returns NULL on error. On successful allocation, // the returned buffer must be freed using "avs_free". inline void* avs_malloc(size_t nbytes, size_t align) { if (!IS_POWER2(align)) return NULL; size_t offset = sizeof(void*) + align - 1; void *orig = malloc(nbytes + offset); if (orig == NULL) return NULL; void **aligned = (void**)(((uintptr_t)orig + (uintptr_t)offset) & (~(uintptr_t)(align-1))); aligned[-1] = orig; return aligned; } // Buffers allocated using "avs_malloc" must be freed // using "avs_free" instead of "free". inline void avs_free(void *ptr) { // Mirroring free()'s semantic requires us to accept NULLs if (ptr == NULL) return; free(((void**)ptr)[-1]); } #ifdef __cplusplus } // extern "C" // The point of these undef's is to force using the template functions // if we are in C++ mode. For C, the user can rely only on the macros. #undef IS_PTR_ALIGNED #undef ALIGN_NUMBER #undef ALIGN_POINTER #endif // __cplusplus #endif //AVS_ALIGNMENT_H ================================================ FILE: thirdparty/32/include/avisynth/avs/arch.h ================================================ #ifndef _AVS_ARCH_H_ #define _AVS_ARCH_H_ #define AVS_ARCH i386 // e.g. i386 #endif // _AVS_ARCH_H_ ================================================ FILE: thirdparty/32/include/avisynth/avs/capi.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_CAPI_H #define AVS_CAPI_H #include "config.h" #ifdef AVS_POSIX // this is also defined in avs/posix.h #ifndef AVS_HAIKU #define __declspec(x) #endif #endif #ifdef __cplusplus # define EXTERN_C extern "C" #else # define EXTERN_C #endif #ifdef AVS_WINDOWS #ifdef BUILDING_AVSCORE # if defined(GCC) && defined(X86_32) # define AVSC_CC # else // MSVC builds and 64-bit GCC # ifndef AVSC_USE_STDCALL # define AVSC_CC __cdecl # else # define AVSC_CC __stdcall # endif # endif #else // needed for programs that talk to AviSynth+ # ifndef AVSC_WIN32_GCC32 // see comment below # ifndef AVSC_USE_STDCALL # define AVSC_CC __cdecl # else # define AVSC_CC __stdcall # endif # else # define AVSC_CC # endif #endif # else # define AVSC_CC #endif // On 64-bit Windows, there's only one calling convention, // so there is no difference between MSVC and GCC. On 32-bit, // this isn't true. The convention that GCC needs to use to // even build AviSynth+ as 32-bit makes anything that uses // it incompatible with 32-bit MSVC builds of AviSynth+. // The AVSC_WIN32_GCC32 define is meant to provide a user // switchable way to make builds of FFmpeg to test 32-bit // GCC builds of AviSynth+ without having to screw around // with alternate headers, while still default to the usual // situation of using 32-bit MSVC builds of AviSynth+. // Hopefully, this situation will eventually be resolved // and a broadly compatible solution will arise so the // same 32-bit FFmpeg build can handle either MSVC or GCC // builds of AviSynth+. #define AVSC_INLINE static __inline #ifdef BUILDING_AVSCORE #ifdef AVS_WINDOWS # ifndef AVS_STATIC_LIB # define AVSC_EXPORT __declspec(dllexport) # else # define AVSC_EXPORT # endif # define AVSC_API(ret, name) EXTERN_C AVSC_EXPORT ret AVSC_CC name #else # define AVSC_EXPORT EXTERN_C # define AVSC_API(ret, name) EXTERN_C ret AVSC_CC name #endif #else # define AVSC_EXPORT EXTERN_C __declspec(dllexport) # ifndef AVS_STATIC_LIB # define AVSC_IMPORT __declspec(dllimport) # else # define AVSC_IMPORT # endif # ifndef AVSC_NO_DECLSPEC # define AVSC_API(ret, name) EXTERN_C AVSC_IMPORT ret AVSC_CC name # else # define AVSC_API(ret, name) typedef ret (AVSC_CC *name##_func) # endif #endif #endif //AVS_CAPI_H ================================================ FILE: thirdparty/32/include/avisynth/avs/config.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_CONFIG_H #define AVS_CONFIG_H // Undefine this to get cdecl calling convention #define AVSC_USE_STDCALL 1 // NOTE TO PLUGIN AUTHORS: // Because FRAME_ALIGN can be substantially higher than the alignment // a plugin actually needs, plugins should not use FRAME_ALIGN to check for // alignment. They should always request the exact alignment value they need. // This is to make sure that plugins work over the widest range of AviSynth // builds possible. #define FRAME_ALIGN 64 #if defined(_M_AMD64) || defined(__x86_64) # define X86_64 #elif defined(_M_IX86) || defined(__i386__) # define X86_32 // VS2017 introduced _M_ARM64 #elif defined(_M_ARM64) || defined(__aarch64__) # define ARM64 #elif defined(_M_ARM) || defined(__arm__) # define ARM32 #elif defined(__PPC64__) # define PPC64 #elif defined(_M_PPC) || defined(__PPC__) || defined(__POWERPC__) # define PPC32 #elif defined(__riscv) # define RISCV #elif defined(__sparc_v9__) # define SPARC #elif defined(__mips__) # define MIPS #else # error Unsupported CPU architecture. #endif // VC++ LLVM-Clang-cl MinGW-Gnu // MSVC x x // MSVC_PURE x // CLANG x // GCC x #if defined(__clang__) // Check clang first. clang-cl also defines __MSC_VER // We set MSVC because they are mostly compatible # define CLANG #if defined(_MSC_VER) # define MSVC # define AVS_FORCEINLINE __attribute__((always_inline)) #else # define AVS_FORCEINLINE __attribute__((always_inline)) inline #endif #elif defined(_MSC_VER) # define MSVC # define MSVC_PURE # define AVS_FORCEINLINE __forceinline #elif defined(__GNUC__) # define GCC # define AVS_FORCEINLINE __attribute__((always_inline)) inline #elif defined(__INTEL_COMPILER) || defined(__INTEL_LLVM_COMPILER) // Intel C++ Compilers with MSVC command line interface will not appear here rather at _MSC_VER # define AVS_FORCEINLINE inline # undef __forceinline # define __forceinline inline #else # error Unsupported compiler. # define AVS_FORCEINLINE inline # undef __forceinline # define __forceinline inline #endif #if defined(_WIN32) # define AVS_WINDOWS #elif defined(__linux__) # define AVS_LINUX # define AVS_POSIX #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) # define AVS_BSD # define AVS_POSIX #elif defined(__APPLE__) # define AVS_MACOS # define AVS_POSIX #elif defined(__HAIKU__) # define AVS_HAIKU # define AVS_POSIX #else # error Operating system unsupported. #endif // useful warnings disabler macros for supported compilers #if defined(_MSC_VER) #define DISABLE_WARNING_PUSH __pragma(warning( push )) #define DISABLE_WARNING_POP __pragma(warning( pop )) #define DISABLE_WARNING(warningNumber) __pragma(warning( disable : warningNumber )) #define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE DISABLE_WARNING(4101) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(4505) // other warnings you want to deactivate... #elif defined(__GNUC__) || defined(__clang__) #define DO_PRAGMA(X) _Pragma(#X) #define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) #define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) #define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) #define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE DISABLE_WARNING(-Wunused-variable) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(-Wunused-function) // other warnings you want to deactivate... #else #define DISABLE_WARNING_PUSH #define DISABLE_WARNING_POP #define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE #define DISABLE_WARNING_UNREFERENCED_FUNCTION // other warnings you want to deactivate... #endif #if defined(AVS_WINDOWS) && defined(_USING_V110_SDK71_) // Windows XP does not have proper initialization for // thread local variables. // Use workaround instead __declspec(thread) #define XP_TLS #endif #ifndef MSVC // GCC and Clang can be used on big endian systems, MSVC can't. # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define AVS_ENDIANNESS "little" # elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ # define AVS_ENDIANNESS "big" # else # define AVS_ENDIANNESS "middle" # endif #else #define AVS_ENDIANNESS "little" #endif #endif //AVS_CONFIG_H ================================================ FILE: thirdparty/32/include/avisynth/avs/cpuid.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifndef AVSCORE_CPUID_H #define AVSCORE_CPUID_H // For GetCPUFlags. These are backwards-compatible with those in VirtualDub. // ending with SSE4_2 // For emulation see https://software.intel.com/en-us/articles/intel-software-development-emulator enum { /* oldest CPU to support extension */ CPUF_FORCE = 0x01, // N/A CPUF_FPU = 0x02, // 386/486DX CPUF_MMX = 0x04, // P55C, K6, PII CPUF_INTEGER_SSE = 0x08, // PIII, Athlon CPUF_SSE = 0x10, // PIII, Athlon XP/MP CPUF_SSE2 = 0x20, // PIV, K8 CPUF_3DNOW = 0x40, // K6-2 CPUF_3DNOW_EXT = 0x80, // Athlon CPUF_X86_64 = 0xA0, // Hammer (note: equiv. to 3DNow + SSE2, which // only Hammer will have anyway) CPUF_SSE3 = 0x100, // PIV+, K8 Venice CPUF_SSSE3 = 0x200, // Core 2 CPUF_SSE4 = 0x400, CPUF_SSE4_1 = 0x400, // Penryn, Wolfdale, Yorkfield CPUF_AVX = 0x800, // Sandy Bridge, Bulldozer CPUF_SSE4_2 = 0x1000, // Nehalem // AVS+ CPUF_AVX2 = 0x2000, // Haswell CPUF_FMA3 = 0x4000, CPUF_F16C = 0x8000, CPUF_MOVBE = 0x10000, // Big Endian move CPUF_POPCNT = 0x20000, CPUF_AES = 0x40000, CPUF_FMA4 = 0x80000, CPUF_AVX512F = 0x100000, // AVX-512 Foundation. CPUF_AVX512DQ = 0x200000, // AVX-512 DQ (Double/Quad granular) Instructions CPUF_AVX512PF = 0x400000, // AVX-512 Prefetch CPUF_AVX512ER = 0x800000, // AVX-512 Exponential and Reciprocal CPUF_AVX512CD = 0x1000000, // AVX-512 Conflict Detection CPUF_AVX512BW = 0x2000000, // AVX-512 BW (Byte/Word granular) Instructions CPUF_AVX512VL = 0x4000000, // AVX-512 VL (128/256 Vector Length) Extensions CPUF_AVX512IFMA = 0x8000000, // AVX-512 IFMA integer 52 bit CPUF_AVX512VBMI = 0x10000000,// AVX-512 VBMI }; #ifdef BUILDING_AVSCORE int GetCPUFlags(); void SetMaxCPU(int new_flags); #endif #endif // AVSCORE_CPUID_H ================================================ FILE: thirdparty/32/include/avisynth/avs/filesystem.h ================================================ #pragma once // Snippet copied from filesystem/README.md #if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include) #if __has_include() #define GHC_USE_STD_FS #include namespace fs = std::filesystem; #endif #endif #ifndef GHC_USE_STD_FS #include namespace fs = ghc::filesystem; #endif ================================================ FILE: thirdparty/32/include/avisynth/avs/minmax.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifndef AVSCORE_MINMAX_H #define AVSCORE_MINMAX_H template T min(T v1, T v2) { return v1 < v2 ? v1 : v2; } template T max(T v1, T v2) { return v1 > v2 ? v1 : v2; } template T clamp(T n, T min, T max) { n = n > max ? max : n; return n < min ? min : n; } #endif // AVSCORE_MINMAX_H ================================================ FILE: thirdparty/32/include/avisynth/avs/posix.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifdef AVS_POSIX #ifndef AVSCORE_POSIX_H #define AVSCORE_POSIX_H #ifdef __cplusplus #include #endif #include #include // Define these MSVC-extension used in Avisynth #define __single_inheritance // These things don't exist in Linux #if defined(AVS_HAIKU) #undef __declspec #endif #define __declspec(x) #define lstrlen strlen #define lstrcmp strcmp #define lstrcmpi strcasecmp #define _stricmp strcasecmp #define _strnicmp strncasecmp #define _strdup strdup #define SetCurrentDirectory(x) chdir(x) #define SetCurrentDirectoryW(x) chdir(x) #define GetCurrentDirectoryW(x) getcwd(x) #define _putenv putenv #define _alloca alloca // Borrowing some compatibility macros from AvxSynth, slightly modified #define UInt32x32To64(a, b) ((uint64_t)(((uint64_t)((uint32_t)(a))) * ((uint32_t)(b)))) #define Int64ShrlMod32(a, b) ((uint64_t)((uint64_t)(a) >> (b))) #define Int32x32To64(a, b) ((int64_t)(((int64_t)((long)(a))) * ((long)(b)))) #define InterlockedIncrement(x) __sync_add_and_fetch((x), 1) #define InterlockedDecrement(x) __sync_sub_and_fetch((x), 1) #define InterlockedExchangeAdd(x, v) __sync_add_and_fetch((x), (v)) #define MulDiv(nNumber, nNumerator, nDenominator) (int32_t) (((int64_t) (nNumber) * (int64_t) (nNumerator) + (int64_t) ((nDenominator)/2)) / (int64_t) (nDenominator)) #ifndef TRUE #define TRUE true #endif #ifndef FALSE #define FALSE false #endif #define S_FALSE (0x00000001) #define E_FAIL (0x80004005) #define FAILED(hr) ((hr) & 0x80000000) #define SUCCEEDED(hr) (!FAILED(hr)) // Statuses copied from comments in exception.cpp #define STATUS_GUARD_PAGE_VIOLATION 0x80000001 #define STATUS_DATATYPE_MISALIGNMENT 0x80000002 #define STATUS_BREAKPOINT 0x80000003 #define STATUS_SINGLE_STEP 0x80000004 #define STATUS_ACCESS_VIOLATION 0xc0000005 #define STATUS_IN_PAGE_ERROR 0xc0000006 #define STATUS_INVALID_HANDLE 0xc0000008 #define STATUS_NO_MEMORY 0xc0000017 #define STATUS_ILLEGAL_INSTRUCTION 0xc000001d #define STATUS_NONCONTINUABLE_EXCEPTION 0xc0000025 #define STATUS_INVALID_DISPOSITION 0xc0000026 #define STATUS_ARRAY_BOUNDS_EXCEEDED 0xc000008c #define STATUS_FLOAT_DENORMAL_OPERAND 0xc000008d #define STATUS_FLOAT_DIVIDE_BY_ZERO 0xc000008e #define STATUS_FLOAT_INEXACT_RESULT 0xc000008f #define STATUS_FLOAT_INVALID_OPERATION 0xc0000090 #define STATUS_FLOAT_OVERFLOW 0xc0000091 #define STATUS_FLOAT_STACK_CHECK 0xc0000092 #define STATUS_FLOAT_UNDERFLOW 0xc0000093 #define STATUS_INTEGER_DIVIDE_BY_ZERO 0xc0000094 #define STATUS_INTEGER_OVERFLOW 0xc0000095 #define STATUS_PRIVILEGED_INSTRUCTION 0xc0000096 #define STATUS_STACK_OVERFLOW 0xc00000fd // Calling convension #ifndef AVS_HAIKU #define __stdcall #define __cdecl #endif // PowerPC OS X is really niche these days, but this painless equivocation // of the function/macro names used in posix_get_available_memory() // is all it takes to let it work. The G5 was 64-bit, and if 10.5 Leopard // can run in native 64-bit, it probably uses the names in that block as-is. #ifdef AVS_MACOS #ifdef PPC32 #define vm_statistics64_data_t vm_statistics_data_t #define HOST_VM_INFO64_COUNT HOST_VM_INFO_COUNT #define HOST_VM_INFO64 HOST_VM_INFO #define host_statistics64 host_statistics #endif // PPC32 #endif // AVS_MACOS #endif // AVSCORE_POSIX_H #endif // AVS_POSIX ================================================ FILE: thirdparty/32/include/avisynth/avs/types.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_TYPES_H #define AVS_TYPES_H // Define all types necessary for interfacing with avisynth.dll #include #include #ifdef __cplusplus #include #include #else #include #include #endif // Raster types used by VirtualDub & Avisynth typedef uint32_t Pixel32; typedef uint8_t BYTE; // Audio Sample information typedef float SFLOAT; #endif //AVS_TYPES_H ================================================ FILE: thirdparty/32/include/avisynth/avs/version.h ================================================ #ifndef _AVS_VERSION_H_ #define _AVS_VERSION_H_ #include "arch.h" #define AVS_PPSTR_(x) #x #define AVS_PPSTR(x) AVS_PPSTR_(x) #define AVS_PROJECT AviSynth+ #define AVS_MAJOR_VER 3 #define AVS_MINOR_VER 7 #define AVS_BUGFIX_VER 3 #ifdef RELEASE_TARBALL #define AVS_FULLVERSION AVS_PPSTR(AVS_PROJECT) " " AVS_PPSTR(AVS_MAJOR_VER) "." AVS_PPSTR(AVS_MINOR_VER) "." AVS_PPSTR(AVS_BUGFIX_VER) " (" AVS_PPSTR(AVS_ARCH) ")" #else #define AVS_DEVNEXT_REV #define AVS_DEV_REVDATE #define AVS_DEV_GITHASH #define AVS_SEQREV // e.g. 1576 #define AVS_BRANCH // e.g. master #define AVS_FULLVERSION AVS_PPSTR(AVS_PROJECT) " " AVS_PPSTR(AVS_MAJOR_VER) "." AVS_PPSTR(AVS_MINOR_VER) "." AVS_PPSTR(AVS_BUGFIX_VER) " (r" AVS_PPSTR(AVS_SEQREV) ", " AVS_PPSTR(AVS_BRANCH) ", " AVS_PPSTR(AVS_ARCH) ")" #endif #endif // _AVS_VERSION_H_ ================================================ FILE: thirdparty/32/include/avisynth/avs/win.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifndef AVSCORE_WIN_H #define AVSCORE_WIN_H // Whenever you need windows headers, start by including this file, then the rest. // WWUUT? We require XP now? #if !defined(NTDDI_VERSION) && !defined(_WIN32_WINNT) #define NTDDI_VERSION 0x05020000 #define _WIN32_WINNT 0x0502 #endif #define WIN32_LEAN_AND_MEAN #define STRICT #if !defined(NOMINMAX) #define NOMINMAX #endif #include // Provision for UTF-8 max 4 bytes per code point #define AVS_MAX_PATH MAX_PATH*4 #endif // AVSCORE_WIN_H ================================================ FILE: thirdparty/32/include/dav1d/common.h ================================================ /* * Copyright © 2018, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_COMMON_H #define DAV1D_COMMON_H #include #include #include #ifdef __cplusplus extern "C" { #endif #ifndef DAV1D_API #if defined _WIN32 #if defined DAV1D_BUILDING_DLL #define DAV1D_API __declspec(dllexport) #else #define DAV1D_API #endif #else #if __GNUC__ >= 4 #define DAV1D_API __attribute__ ((visibility ("default"))) #else #define DAV1D_API #endif #endif #endif #if EPERM > 0 #define DAV1D_ERR(e) (-(e)) ///< Negate POSIX error code. #else #define DAV1D_ERR(e) (e) #endif /** * A reference-counted object wrapper for a user-configurable pointer. */ typedef struct Dav1dUserData { const uint8_t *data; ///< data pointer struct Dav1dRef *ref; ///< allocation origin } Dav1dUserData; /** * Input packet metadata which are copied from the input data used to * decode each image into the matching structure of the output image * returned back to the user. Since these are metadata fields, they * can be used for other purposes than the documented ones, they will * still be passed from input data to output picture without being * used internally. */ typedef struct Dav1dDataProps { int64_t timestamp; ///< container timestamp of input data, INT64_MIN if unknown (default) int64_t duration; ///< container duration of input data, 0 if unknown (default) int64_t offset; ///< stream offset of input data, -1 if unknown (default) size_t size; ///< packet size, default Dav1dData.sz struct Dav1dUserData user_data; ///< user-configurable data, default NULL members } Dav1dDataProps; /** * Release reference to a Dav1dDataProps. */ DAV1D_API void dav1d_data_props_unref(Dav1dDataProps *props); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_COMMON_H */ ================================================ FILE: thirdparty/32/include/dav1d/data.h ================================================ /* * Copyright © 2018, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_DATA_H #define DAV1D_DATA_H #include #include #include "common.h" #ifdef __cplusplus extern "C" { #endif typedef struct Dav1dData { const uint8_t *data; ///< data pointer size_t sz; ///< data size struct Dav1dRef *ref; ///< allocation origin Dav1dDataProps m; ///< user provided metadata passed to the output picture } Dav1dData; /** * Allocate data. * * @param data Input context. * @param sz Size of the data that should be allocated. * * @return Pointer to the allocated buffer on success. NULL on error. */ DAV1D_API uint8_t * dav1d_data_create(Dav1dData *data, size_t sz); /** * Wrap an existing data array. * * @param data Input context. * @param buf The data to be wrapped. * @param sz Size of the data. * @param free_callback Function to be called when we release our last * reference to this data. In this callback, $buf will be * the $buf argument to this function, and $cookie will * be the $cookie input argument to this function. * @param cookie Opaque parameter passed to free_callback(). * * @return 0 on success. A negative DAV1D_ERR value on error. */ DAV1D_API int dav1d_data_wrap(Dav1dData *data, const uint8_t *buf, size_t sz, void (*free_callback)(const uint8_t *buf, void *cookie), void *cookie); /** * Wrap a user-provided data pointer into a reference counted object. * * data->m.user_data field will initialized to wrap the provided $user_data * pointer. * * $free_callback will be called on the same thread that released the last * reference. If frame threading is used, make sure $free_callback is * thread-safe. * * @param data Input context. * @param user_data The user data to be wrapped. * @param free_callback Function to be called when we release our last * reference to this data. In this callback, $user_data * will be the $user_data argument to this function, and * $cookie will be the $cookie input argument to this * function. * @param cookie Opaque parameter passed to $free_callback. * * @return 0 on success. A negative DAV1D_ERR value on error. */ DAV1D_API int dav1d_data_wrap_user_data(Dav1dData *data, const uint8_t *user_data, void (*free_callback)(const uint8_t *user_data, void *cookie), void *cookie); /** * Free the data reference. * * The reference count for data->m.user_data will be decremented (if it has been * initialized with dav1d_data_wrap_user_data). The $data object will be memset * to 0. * * @param data Input context. */ DAV1D_API void dav1d_data_unref(Dav1dData *data); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_DATA_H */ ================================================ FILE: thirdparty/32/include/dav1d/dav1d.h ================================================ /* * Copyright © 2018-2021, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_H #define DAV1D_H #include #include #include "common.h" #include "picture.h" #include "data.h" #include "version.h" #ifdef __cplusplus extern "C" { #endif typedef struct Dav1dContext Dav1dContext; typedef struct Dav1dRef Dav1dRef; #define DAV1D_MAX_THREADS 256 #define DAV1D_MAX_FRAME_DELAY 256 typedef struct Dav1dLogger { void *cookie; ///< Custom data to pass to the callback. /** * Logger callback. May be NULL to disable logging. * * @param cookie Custom pointer passed to all calls. * @param format The vprintf compatible format string. * @param ap List of arguments referenced by the format string. */ void (*callback)(void *cookie, const char *format, va_list ap); } Dav1dLogger; enum Dav1dInloopFilterType { DAV1D_INLOOPFILTER_NONE = 0, DAV1D_INLOOPFILTER_DEBLOCK = 1 << 0, DAV1D_INLOOPFILTER_CDEF = 1 << 1, DAV1D_INLOOPFILTER_RESTORATION = 1 << 2, DAV1D_INLOOPFILTER_ALL = DAV1D_INLOOPFILTER_DEBLOCK | DAV1D_INLOOPFILTER_CDEF | DAV1D_INLOOPFILTER_RESTORATION, }; enum Dav1dDecodeFrameType { DAV1D_DECODEFRAMETYPE_ALL = 0, ///< decode and return all frames DAV1D_DECODEFRAMETYPE_REFERENCE = 1,///< decode and return frames referenced by other frames only DAV1D_DECODEFRAMETYPE_INTRA = 2, ///< decode and return intra frames only (includes keyframes) DAV1D_DECODEFRAMETYPE_KEY = 3, ///< decode and return keyframes only }; typedef struct Dav1dSettings { int n_threads; ///< number of threads (0 = number of logical cores in host system, default 0) int max_frame_delay; ///< Set to 1 for low-latency decoding (0 = ceil(sqrt(n_threads)), default 0) int apply_grain; ///< whether to apply film grain on output frames (default 1) int operating_point; ///< select an operating point for scalable AV1 bitstreams (0 - 31, default 0) int all_layers; ///< output all spatial layers of a scalable AV1 biststream (default 1) unsigned frame_size_limit; ///< maximum frame size, in pixels (0 = unlimited, default 0) Dav1dPicAllocator allocator; ///< Picture allocator callback. Dav1dLogger logger; ///< Logger callback. int strict_std_compliance; ///< whether to abort decoding on standard compliance violations ///< that don't affect actual bitstream decoding (e.g. inconsistent ///< or invalid metadata, default 0) int output_invisible_frames; ///< output invisibly coded frames (in coding order) in addition ///< to all visible frames. Because of show-existing-frame, this ///< means some frames may appear twice (once when coded, ///< once when shown, default 0) enum Dav1dInloopFilterType inloop_filters; ///< postfilters to enable during decoding (default ///< DAV1D_INLOOPFILTER_ALL) enum Dav1dDecodeFrameType decode_frame_type; ///< frame types to decode (default ///< DAV1D_DECODEFRAMETYPE_ALL) uint8_t reserved[16]; ///< reserved for future use } Dav1dSettings; /** * Get library version. */ DAV1D_API const char *dav1d_version(void); /** * Get library API version. * * @return A value in the format 0x00XXYYZZ, where XX is the major version, * YY the minor version, and ZZ the patch version. * @see DAV1D_API_MAJOR, DAV1D_API_MINOR, DAV1D_API_PATCH */ DAV1D_API unsigned dav1d_version_api(void); /** * Initialize settings to default values. * * @param s Input settings context. */ DAV1D_API void dav1d_default_settings(Dav1dSettings *s); /** * Allocate and open a decoder instance. * * @param c_out The decoder instance to open. *c_out will be set to the * allocated context. * @param s Input settings context. * * @note The context must be freed using dav1d_close() when decoding is * finished. * * @return 0 on success, or < 0 (a negative DAV1D_ERR code) on error. */ DAV1D_API int dav1d_open(Dav1dContext **c_out, const Dav1dSettings *s); /** * Parse a Sequence Header OBU from bitstream data. * * @param out Output Sequence Header. * @param buf The data to be parser. * @param sz Size of the data. * * @return * 0: Success, and out is filled with the parsed Sequence Header * OBU parameters. * DAV1D_ERR(ENOENT): No Sequence Header OBUs were found in the buffer. * Other negative DAV1D_ERR codes: Invalid data in the buffer, invalid passed-in * arguments, and other errors during parsing. * * @note It is safe to feed this function data containing other OBUs than a * Sequence Header, as they will simply be ignored. If there is more than * one Sequence Header OBU present, only the last will be returned. */ DAV1D_API int dav1d_parse_sequence_header(Dav1dSequenceHeader *out, const uint8_t *buf, const size_t sz); /** * Feed bitstream data to the decoder, in the form of one or multiple AV1 * Open Bitstream Units (OBUs). * * @param c Input decoder instance. * @param in Input bitstream data. On success, ownership of the reference is * passed to the library. * * @return * 0: Success, and the data was consumed. * DAV1D_ERR(EAGAIN): The data can't be consumed. dav1d_get_picture() should * be called to get one or more frames before the function * can consume new data. * Other negative DAV1D_ERR codes: Error during decoding or because of invalid * passed-in arguments. The reference remains * owned by the caller. */ DAV1D_API int dav1d_send_data(Dav1dContext *c, Dav1dData *in); /** * Return a decoded picture. * * @param c Input decoder instance. * @param out Output frame. The caller assumes ownership of the returned * reference. * * @return * 0: Success, and a frame is returned. * DAV1D_ERR(EAGAIN): Not enough data to output a frame. dav1d_send_data() * should be called with new input. * Other negative DAV1D_ERR codes: Error during decoding or because of invalid * passed-in arguments. * * @note To drain buffered frames from the decoder (i.e. on end of stream), * call this function until it returns DAV1D_ERR(EAGAIN). * * @code{.c} * Dav1dData data = { 0 }; * Dav1dPicture p = { 0 }; * int res; * * read_data(&data); * do { * res = dav1d_send_data(c, &data); * // Keep going even if the function can't consume the current data * packet. It eventually will after one or more frames have been * returned in this loop. * if (res < 0 && res != DAV1D_ERR(EAGAIN)) * free_and_abort(); * res = dav1d_get_picture(c, &p); * if (res < 0) { * if (res != DAV1D_ERR(EAGAIN)) * free_and_abort(); * } else * output_and_unref_picture(&p); * // Stay in the loop as long as there's data to consume. * } while (data.sz || read_data(&data) == SUCCESS); * * // Handle EOS by draining all buffered frames. * do { * res = dav1d_get_picture(c, &p); * if (res < 0) { * if (res != DAV1D_ERR(EAGAIN)) * free_and_abort(); * } else * output_and_unref_picture(&p); * } while (res == 0); * @endcode */ DAV1D_API int dav1d_get_picture(Dav1dContext *c, Dav1dPicture *out); /** * Apply film grain to a previously decoded picture. If the picture contains no * film grain metadata, then this function merely returns a new reference. * * @param c Input decoder instance. * @param out Output frame. The caller assumes ownership of the returned * reference. * @param in Input frame. No ownership is transferred. * * @return * 0: Success, and a frame is returned. * Other negative DAV1D_ERR codes: Error due to lack of memory or because of * invalid passed-in arguments. * * @note If `Dav1dSettings.apply_grain` is true, film grain was already applied * by `dav1d_get_picture`, and so calling this function leads to double * application of film grain. Users should only call this when needed. */ DAV1D_API int dav1d_apply_grain(Dav1dContext *c, Dav1dPicture *out, const Dav1dPicture *in); /** * Close a decoder instance and free all associated memory. * * @param c_out The decoder instance to close. *c_out will be set to NULL. */ DAV1D_API void dav1d_close(Dav1dContext **c_out); /** * Flush all delayed frames in decoder and clear internal decoder state, * to be used when seeking. * * @param c Input decoder instance. * * @note Decoding will start only after a valid sequence header OBU is * delivered to dav1d_send_data(). * */ DAV1D_API void dav1d_flush(Dav1dContext *c); enum Dav1dEventFlags { /** * The last returned picture contains a reference to a new Sequence Header, * either because it's the start of a new coded sequence, or the decoder was * flushed before it was generated. */ DAV1D_EVENT_FLAG_NEW_SEQUENCE = 1 << 0, /** * The last returned picture contains a reference to a Sequence Header with * new operating parameters information for the current coded sequence. */ DAV1D_EVENT_FLAG_NEW_OP_PARAMS_INFO = 1 << 1, }; /** * Fetch a combination of DAV1D_EVENT_FLAG_* event flags generated by the decoding * process. * * @param c Input decoder instance. * @param flags Where to write the flags. * * @return 0 on success, or < 0 (a negative DAV1D_ERR code) on error. * * @note Calling this function will clear all the event flags currently stored in * the decoder. * */ DAV1D_API int dav1d_get_event_flags(Dav1dContext *c, enum Dav1dEventFlags *flags); /** * Retrieve the user-provided metadata associated with the input data packet * for the last decoding error reported to the user, i.e. a negative return * value (not EAGAIN) from dav1d_send_data() or dav1d_get_picture(). * * @param c Input decoder instance. * @param out Output Dav1dDataProps. On success, the caller assumes ownership of * the returned reference. * * @return 0 on success, or < 0 (a negative DAV1D_ERR code) on error. */ DAV1D_API int dav1d_get_decode_error_data_props(Dav1dContext *c, Dav1dDataProps *out); /** * Get the decoder delay, which is the number of internally buffered frames, not * including reference frames. * This value is guaranteed to be >= 1 and <= max_frame_delay. * * @param s Input settings context. * * @return Decoder frame delay on success, or < 0 (a negative DAV1D_ERR code) on * error. * * @note The returned delay is valid only for a Dav1dContext initialized with the * provided Dav1dSettings. */ DAV1D_API int dav1d_get_frame_delay(const Dav1dSettings *s); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_H */ ================================================ FILE: thirdparty/32/include/dav1d/headers.h ================================================ /* * Copyright © 2018-2020, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_HEADERS_H #define DAV1D_HEADERS_H #include #include #ifdef __cplusplus extern "C" { #endif // Constants from Section 3. "Symbols and abbreviated terms" #define DAV1D_MAX_CDEF_STRENGTHS 8 #define DAV1D_MAX_OPERATING_POINTS 32 #define DAV1D_MAX_TILE_COLS 64 #define DAV1D_MAX_TILE_ROWS 64 #define DAV1D_MAX_SEGMENTS 8 #define DAV1D_NUM_REF_FRAMES 8 #define DAV1D_PRIMARY_REF_NONE 7 #define DAV1D_REFS_PER_FRAME 7 #define DAV1D_TOTAL_REFS_PER_FRAME (DAV1D_REFS_PER_FRAME + 1) enum Dav1dObuType { DAV1D_OBU_SEQ_HDR = 1, DAV1D_OBU_TD = 2, DAV1D_OBU_FRAME_HDR = 3, DAV1D_OBU_TILE_GRP = 4, DAV1D_OBU_METADATA = 5, DAV1D_OBU_FRAME = 6, DAV1D_OBU_REDUNDANT_FRAME_HDR = 7, DAV1D_OBU_PADDING = 15, }; enum Dav1dTxfmMode { DAV1D_TX_4X4_ONLY, DAV1D_TX_LARGEST, DAV1D_TX_SWITCHABLE, DAV1D_N_TX_MODES, }; enum Dav1dFilterMode { DAV1D_FILTER_8TAP_REGULAR, DAV1D_FILTER_8TAP_SMOOTH, DAV1D_FILTER_8TAP_SHARP, DAV1D_N_SWITCHABLE_FILTERS, DAV1D_FILTER_BILINEAR = DAV1D_N_SWITCHABLE_FILTERS, DAV1D_N_FILTERS, DAV1D_FILTER_SWITCHABLE = DAV1D_N_FILTERS, }; enum Dav1dAdaptiveBoolean { DAV1D_OFF = 0, DAV1D_ON = 1, DAV1D_ADAPTIVE = 2, }; enum Dav1dRestorationType { DAV1D_RESTORATION_NONE, DAV1D_RESTORATION_SWITCHABLE, DAV1D_RESTORATION_WIENER, DAV1D_RESTORATION_SGRPROJ, }; enum Dav1dWarpedMotionType { DAV1D_WM_TYPE_IDENTITY, DAV1D_WM_TYPE_TRANSLATION, DAV1D_WM_TYPE_ROT_ZOOM, DAV1D_WM_TYPE_AFFINE, }; typedef struct Dav1dWarpedMotionParams { enum Dav1dWarpedMotionType type; int32_t matrix[6]; union { struct { int16_t alpha, beta, gamma, delta; } p; int16_t abcd[4]; } u; } Dav1dWarpedMotionParams; enum Dav1dPixelLayout { DAV1D_PIXEL_LAYOUT_I400, ///< monochrome DAV1D_PIXEL_LAYOUT_I420, ///< 4:2:0 planar DAV1D_PIXEL_LAYOUT_I422, ///< 4:2:2 planar DAV1D_PIXEL_LAYOUT_I444, ///< 4:4:4 planar }; enum Dav1dFrameType { DAV1D_FRAME_TYPE_KEY = 0, ///< Key Intra frame DAV1D_FRAME_TYPE_INTER = 1, ///< Inter frame DAV1D_FRAME_TYPE_INTRA = 2, ///< Non key Intra frame DAV1D_FRAME_TYPE_SWITCH = 3, ///< Switch Inter frame }; enum Dav1dColorPrimaries { DAV1D_COLOR_PRI_BT709 = 1, DAV1D_COLOR_PRI_UNKNOWN = 2, DAV1D_COLOR_PRI_BT470M = 4, DAV1D_COLOR_PRI_BT470BG = 5, DAV1D_COLOR_PRI_BT601 = 6, DAV1D_COLOR_PRI_SMPTE240 = 7, DAV1D_COLOR_PRI_FILM = 8, DAV1D_COLOR_PRI_BT2020 = 9, DAV1D_COLOR_PRI_XYZ = 10, DAV1D_COLOR_PRI_SMPTE431 = 11, DAV1D_COLOR_PRI_SMPTE432 = 12, DAV1D_COLOR_PRI_EBU3213 = 22, DAV1D_COLOR_PRI_RESERVED = 255, }; enum Dav1dTransferCharacteristics { DAV1D_TRC_BT709 = 1, DAV1D_TRC_UNKNOWN = 2, DAV1D_TRC_BT470M = 4, DAV1D_TRC_BT470BG = 5, DAV1D_TRC_BT601 = 6, DAV1D_TRC_SMPTE240 = 7, DAV1D_TRC_LINEAR = 8, DAV1D_TRC_LOG100 = 9, ///< logarithmic (100:1 range) DAV1D_TRC_LOG100_SQRT10 = 10, ///< lograithmic (100*sqrt(10):1 range) DAV1D_TRC_IEC61966 = 11, DAV1D_TRC_BT1361 = 12, DAV1D_TRC_SRGB = 13, DAV1D_TRC_BT2020_10BIT = 14, DAV1D_TRC_BT2020_12BIT = 15, DAV1D_TRC_SMPTE2084 = 16, ///< PQ DAV1D_TRC_SMPTE428 = 17, DAV1D_TRC_HLG = 18, ///< hybrid log/gamma (BT.2100 / ARIB STD-B67) DAV1D_TRC_RESERVED = 255, }; enum Dav1dMatrixCoefficients { DAV1D_MC_IDENTITY = 0, DAV1D_MC_BT709 = 1, DAV1D_MC_UNKNOWN = 2, DAV1D_MC_FCC = 4, DAV1D_MC_BT470BG = 5, DAV1D_MC_BT601 = 6, DAV1D_MC_SMPTE240 = 7, DAV1D_MC_SMPTE_YCGCO = 8, DAV1D_MC_BT2020_NCL = 9, DAV1D_MC_BT2020_CL = 10, DAV1D_MC_SMPTE2085 = 11, DAV1D_MC_CHROMAT_NCL = 12, ///< Chromaticity-derived DAV1D_MC_CHROMAT_CL = 13, DAV1D_MC_ICTCP = 14, DAV1D_MC_RESERVED = 255, }; enum Dav1dChromaSamplePosition { DAV1D_CHR_UNKNOWN = 0, DAV1D_CHR_VERTICAL = 1, ///< Horizontally co-located with luma(0, 0) ///< sample, between two vertical samples DAV1D_CHR_COLOCATED = 2, ///< Co-located with luma(0, 0) sample }; typedef struct Dav1dContentLightLevel { uint16_t max_content_light_level; uint16_t max_frame_average_light_level; } Dav1dContentLightLevel; typedef struct Dav1dMasteringDisplay { uint16_t primaries[3][2]; ///< 0.16 fixed point uint16_t white_point[2]; ///< 0.16 fixed point uint32_t max_luminance; ///< 24.8 fixed point uint32_t min_luminance; ///< 18.14 fixed point } Dav1dMasteringDisplay; typedef struct Dav1dITUTT35 { uint8_t country_code; uint8_t country_code_extension_byte; size_t payload_size; uint8_t *payload; } Dav1dITUTT35; typedef struct Dav1dSequenceHeader { /** * Stream profile, 0 for 8-10 bits/component 4:2:0 or monochrome; * 1 for 8-10 bits/component 4:4:4; 2 for 4:2:2 at any bits/component, * or 12 bits/component at any chroma subsampling. */ uint8_t profile; /** * Maximum dimensions for this stream. In non-scalable streams, these * are often the actual dimensions of the stream, although that is not * a normative requirement. */ int max_width, max_height; enum Dav1dPixelLayout layout; ///< format of the picture enum Dav1dColorPrimaries pri; ///< color primaries (av1) enum Dav1dTransferCharacteristics trc; ///< transfer characteristics (av1) enum Dav1dMatrixCoefficients mtrx; ///< matrix coefficients (av1) enum Dav1dChromaSamplePosition chr; ///< chroma sample position (av1) /** * 0, 1 and 2 mean 8, 10 or 12 bits/component, respectively. This is not * exactly the same as 'hbd' from the spec; the spec's hbd distinguishes * between 8 (0) and 10-12 (1) bits/component, and another element * (twelve_bit) to distinguish between 10 and 12 bits/component. To get * the spec's hbd, use !!our_hbd, and to get twelve_bit, use hbd == 2. */ uint8_t hbd; /** * Pixel data uses JPEG pixel range ([0,255] for 8bits) instead of * MPEG pixel range ([16,235] for 8bits luma, [16,240] for 8bits chroma). */ uint8_t color_range; uint8_t num_operating_points; struct Dav1dSequenceHeaderOperatingPoint { uint8_t major_level, minor_level; uint8_t initial_display_delay; uint16_t idc; uint8_t tier; uint8_t decoder_model_param_present; uint8_t display_model_param_present; } operating_points[DAV1D_MAX_OPERATING_POINTS]; uint8_t still_picture; uint8_t reduced_still_picture_header; uint8_t timing_info_present; uint32_t num_units_in_tick; uint32_t time_scale; uint8_t equal_picture_interval; uint32_t num_ticks_per_picture; uint8_t decoder_model_info_present; uint8_t encoder_decoder_buffer_delay_length; uint32_t num_units_in_decoding_tick; uint8_t buffer_removal_delay_length; uint8_t frame_presentation_delay_length; uint8_t display_model_info_present; uint8_t width_n_bits, height_n_bits; uint8_t frame_id_numbers_present; uint8_t delta_frame_id_n_bits; uint8_t frame_id_n_bits; uint8_t sb128; uint8_t filter_intra; uint8_t intra_edge_filter; uint8_t inter_intra; uint8_t masked_compound; uint8_t warped_motion; uint8_t dual_filter; uint8_t order_hint; uint8_t jnt_comp; uint8_t ref_frame_mvs; enum Dav1dAdaptiveBoolean screen_content_tools; enum Dav1dAdaptiveBoolean force_integer_mv; uint8_t order_hint_n_bits; uint8_t super_res; uint8_t cdef; uint8_t restoration; uint8_t ss_hor, ss_ver, monochrome; uint8_t color_description_present; uint8_t separate_uv_delta_q; uint8_t film_grain_present; // Dav1dSequenceHeaders of the same sequence are required to be // bit-identical until this offset. See 7.5 "Ordering of OBUs": // Within a particular coded video sequence, the contents of // sequence_header_obu must be bit-identical each time the // sequence header appears except for the contents of // operating_parameters_info. struct Dav1dSequenceHeaderOperatingParameterInfo { uint32_t decoder_buffer_delay; uint32_t encoder_buffer_delay; uint8_t low_delay_mode; } operating_parameter_info[DAV1D_MAX_OPERATING_POINTS]; } Dav1dSequenceHeader; typedef struct Dav1dSegmentationData { int16_t delta_q; int8_t delta_lf_y_v, delta_lf_y_h, delta_lf_u, delta_lf_v; int8_t ref; uint8_t skip; uint8_t globalmv; } Dav1dSegmentationData; typedef struct Dav1dSegmentationDataSet { Dav1dSegmentationData d[DAV1D_MAX_SEGMENTS]; uint8_t preskip; int8_t last_active_segid; } Dav1dSegmentationDataSet; typedef struct Dav1dLoopfilterModeRefDeltas { int8_t mode_delta[2 /* is_zeromv */]; int8_t ref_delta[DAV1D_TOTAL_REFS_PER_FRAME]; } Dav1dLoopfilterModeRefDeltas; typedef struct Dav1dFilmGrainData { unsigned seed; int num_y_points; uint8_t y_points[14][2 /* value, scaling */]; int chroma_scaling_from_luma; int num_uv_points[2]; uint8_t uv_points[2][10][2 /* value, scaling */]; int scaling_shift; int ar_coeff_lag; int8_t ar_coeffs_y[24]; int8_t ar_coeffs_uv[2][25 + 3 /* padding for alignment purposes */]; uint64_t ar_coeff_shift; int grain_scale_shift; int uv_mult[2]; int uv_luma_mult[2]; int uv_offset[2]; int overlap_flag; int clip_to_restricted_range; } Dav1dFilmGrainData; typedef struct Dav1dFrameHeader { struct { Dav1dFilmGrainData data; uint8_t present, update; } film_grain; ///< film grain parameters enum Dav1dFrameType frame_type; ///< type of the picture int width[2 /* { coded_width, superresolution_upscaled_width } */], height; uint8_t frame_offset; ///< frame number uint8_t temporal_id; ///< temporal id of the frame for SVC uint8_t spatial_id; ///< spatial id of the frame for SVC uint8_t show_existing_frame; uint8_t existing_frame_idx; uint32_t frame_id; uint32_t frame_presentation_delay; uint8_t show_frame; uint8_t showable_frame; uint8_t error_resilient_mode; uint8_t disable_cdf_update; uint8_t allow_screen_content_tools; uint8_t force_integer_mv; uint8_t frame_size_override; uint8_t primary_ref_frame; uint8_t buffer_removal_time_present; struct Dav1dFrameHeaderOperatingPoint { uint32_t buffer_removal_time; } operating_points[DAV1D_MAX_OPERATING_POINTS]; uint8_t refresh_frame_flags; int render_width, render_height; struct { uint8_t width_scale_denominator; uint8_t enabled; } super_res; uint8_t have_render_size; uint8_t allow_intrabc; uint8_t frame_ref_short_signaling; int8_t refidx[DAV1D_REFS_PER_FRAME]; uint8_t hp; enum Dav1dFilterMode subpel_filter_mode; uint8_t switchable_motion_mode; uint8_t use_ref_frame_mvs; uint8_t refresh_context; struct { uint8_t uniform; uint8_t n_bytes; uint8_t min_log2_cols, max_log2_cols, log2_cols, cols; uint8_t min_log2_rows, max_log2_rows, log2_rows, rows; uint16_t col_start_sb[DAV1D_MAX_TILE_COLS + 1]; uint16_t row_start_sb[DAV1D_MAX_TILE_ROWS + 1]; uint16_t update; } tiling; struct { uint8_t yac; int8_t ydc_delta; int8_t udc_delta, uac_delta, vdc_delta, vac_delta; uint8_t qm, qm_y, qm_u, qm_v; } quant; struct { uint8_t enabled, update_map, temporal, update_data; Dav1dSegmentationDataSet seg_data; uint8_t lossless[DAV1D_MAX_SEGMENTS], qidx[DAV1D_MAX_SEGMENTS]; } segmentation; struct { struct { uint8_t present; uint8_t res_log2; } q; struct { uint8_t present; uint8_t res_log2; uint8_t multi; } lf; } delta; uint8_t all_lossless; struct { uint8_t level_y[2 /* dir */]; uint8_t level_u, level_v; uint8_t mode_ref_delta_enabled; uint8_t mode_ref_delta_update; Dav1dLoopfilterModeRefDeltas mode_ref_deltas; uint8_t sharpness; } loopfilter; struct { uint8_t damping; uint8_t n_bits; uint8_t y_strength[DAV1D_MAX_CDEF_STRENGTHS]; uint8_t uv_strength[DAV1D_MAX_CDEF_STRENGTHS]; } cdef; struct { enum Dav1dRestorationType type[3 /* plane */]; uint8_t unit_size[2 /* y, uv */]; } restoration; enum Dav1dTxfmMode txfm_mode; uint8_t switchable_comp_refs; uint8_t skip_mode_allowed, skip_mode_enabled; int8_t skip_mode_refs[2]; uint8_t warp_motion; uint8_t reduced_txtp_set; Dav1dWarpedMotionParams gmv[DAV1D_REFS_PER_FRAME]; } Dav1dFrameHeader; #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_HEADERS_H */ ================================================ FILE: thirdparty/32/include/dav1d/picture.h ================================================ /* * Copyright © 2018-2020, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_PICTURE_H #define DAV1D_PICTURE_H #include #include #include "common.h" #include "headers.h" #ifdef __cplusplus extern "C" { #endif /* Number of bytes to align AND pad picture memory buffers by, so that SIMD * implementations can over-read by a few bytes, and use aligned read/write * instructions. */ #define DAV1D_PICTURE_ALIGNMENT 64 typedef struct Dav1dPictureParameters { int w; ///< width (in pixels) int h; ///< height (in pixels) enum Dav1dPixelLayout layout; ///< format of the picture int bpc; ///< bits per pixel component (8 or 10) } Dav1dPictureParameters; typedef struct Dav1dPicture { Dav1dSequenceHeader *seq_hdr; Dav1dFrameHeader *frame_hdr; /** * Pointers to planar image data (Y is [0], U is [1], V is [2]). The data * should be bytes (for 8 bpc) or words (for 10 bpc). In case of words * containing 10 bpc image data, the pixels should be located in the LSB * bits, so that values range between [0, 1023]; the upper bits should be * zero'ed out. */ void *data[3]; /** * Number of bytes between 2 lines in data[] for luma [0] or chroma [1]. */ ptrdiff_t stride[2]; Dav1dPictureParameters p; Dav1dDataProps m; /** * High Dynamic Range Content Light Level metadata applying to this picture, * as defined in section 5.8.3 and 6.7.3 */ Dav1dContentLightLevel *content_light; /** * High Dynamic Range Mastering Display Color Volume metadata applying to * this picture, as defined in section 5.8.4 and 6.7.4 */ Dav1dMasteringDisplay *mastering_display; /** * Array of ITU-T T.35 metadata as defined in section 5.8.2 and 6.7.2 */ Dav1dITUTT35 *itut_t35; /** * Number of ITU-T T35 metadata entries in the array */ size_t n_itut_t35; uintptr_t reserved[4]; ///< reserved for future use struct Dav1dRef *frame_hdr_ref; ///< Dav1dFrameHeader allocation origin struct Dav1dRef *seq_hdr_ref; ///< Dav1dSequenceHeader allocation origin struct Dav1dRef *content_light_ref; ///< Dav1dContentLightLevel allocation origin struct Dav1dRef *mastering_display_ref; ///< Dav1dMasteringDisplay allocation origin struct Dav1dRef *itut_t35_ref; ///< Dav1dITUTT35 allocation origin uintptr_t reserved_ref[4]; ///< reserved for future use struct Dav1dRef *ref; ///< Frame data allocation origin void *allocator_data; ///< pointer managed by the allocator } Dav1dPicture; typedef struct Dav1dPicAllocator { void *cookie; ///< custom data to pass to the allocator callbacks. /** * Allocate the picture buffer based on the Dav1dPictureParameters. * * The data[0], data[1] and data[2] must be DAV1D_PICTURE_ALIGNMENT byte * aligned and with a pixel width/height multiple of 128 pixels. Any * allocated memory area should also be padded by DAV1D_PICTURE_ALIGNMENT * bytes. * data[1] and data[2] must share the same stride[1]. * * This function will be called on the main thread (the thread which calls * dav1d_get_picture()). * * @param pic The picture to allocate the buffer for. The callback needs to * fill the picture data[0], data[1], data[2], stride[0] and * stride[1]. * The allocator can fill the pic allocator_data pointer with * a custom pointer that will be passed to * release_picture_callback(). * @param cookie Custom pointer passed to all calls. * * @note No fields other than data, stride and allocator_data must be filled * by this callback. * @return 0 on success. A negative DAV1D_ERR value on error. */ int (*alloc_picture_callback)(Dav1dPicture *pic, void *cookie); /** * Release the picture buffer. * * If frame threading is used, this function may be called by the main * thread (the thread which calls dav1d_get_picture()) or any of the frame * threads and thus must be thread-safe. If frame threading is not used, * this function will only be called on the main thread. * * @param pic The picture that was filled by alloc_picture_callback(). * @param cookie Custom pointer passed to all calls. */ void (*release_picture_callback)(Dav1dPicture *pic, void *cookie); } Dav1dPicAllocator; /** * Release reference to a picture. */ DAV1D_API void dav1d_picture_unref(Dav1dPicture *p); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_PICTURE_H */ ================================================ FILE: thirdparty/32/include/dav1d/version.h ================================================ /* * Copyright © 2019-2024, VideoLAN and dav1d authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_VERSION_H #define DAV1D_VERSION_H #ifdef __cplusplus extern "C" { #endif #define DAV1D_API_VERSION_MAJOR 7 #define DAV1D_API_VERSION_MINOR 0 #define DAV1D_API_VERSION_PATCH 0 /** * Extract version components from the value returned by * dav1d_version_int() */ #define DAV1D_API_MAJOR(v) (((v) >> 16) & 0xFF) #define DAV1D_API_MINOR(v) (((v) >> 8) & 0xFF) #define DAV1D_API_PATCH(v) (((v) >> 0) & 0xFF) #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_VERSION_H */ ================================================ FILE: thirdparty/32/include/gmp.h ================================================ /* Definitions for GNU multiple precision functions. -*- mode: c -*- Copyright 1991, 1993-1997, 1999-2016, 2020, 2021 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not, see https://www.gnu.org/licenses/. */ #ifndef __GMP_H__ #if defined (__cplusplus) #include /* for std::istream, std::ostream, std::string */ #include #endif /* Instantiated by configure. */ #if ! defined (__GMP_WITHIN_CONFIGURE) #define __GMP_HAVE_HOST_CPU_FAMILY_power 0 #define __GMP_HAVE_HOST_CPU_FAMILY_powerpc 0 #define GMP_LIMB_BITS 32 #define GMP_NAIL_BITS 0 #endif #define GMP_NUMB_BITS (GMP_LIMB_BITS - GMP_NAIL_BITS) #define GMP_NUMB_MASK ((~ __GMP_CAST (mp_limb_t, 0)) >> GMP_NAIL_BITS) #define GMP_NUMB_MAX GMP_NUMB_MASK #define GMP_NAIL_MASK (~ GMP_NUMB_MASK) #ifndef __GNU_MP__ #define __GNU_MP__ 6 #include /* for size_t */ #include /* Instantiated by configure. */ #if ! defined (__GMP_WITHIN_CONFIGURE) /* #undef _LONG_LONG_LIMB */ #define __GMP_LIBGMP_DLL 0 #endif /* __GMP_DECLSPEC supports Windows DLL versions of libgmp, and is empty in all other circumstances. When compiling objects for libgmp, __GMP_DECLSPEC is an export directive, or when compiling for an application it's an import directive. The two cases are differentiated by __GMP_WITHIN_GMP defined by the GMP Makefiles (and not defined from an application). __GMP_DECLSPEC_XX is similarly used for libgmpxx. __GMP_WITHIN_GMPXX indicates when building libgmpxx, and in that case libgmpxx functions are exports, but libgmp functions which might get called are imports. Libtool DLL_EXPORT define is not used. There's no attempt to support GMP built both static and DLL. Doing so would mean applications would have to tell us which of the two is going to be used when linking, and that seems very tedious and error prone if using GMP by hand, and equally tedious from a package since autoconf and automake don't give much help. __GMP_DECLSPEC is required on all documented global functions and variables, the various internals in gmp-impl.h etc can be left unadorned. But internals used by the test programs or speed measuring programs should have __GMP_DECLSPEC, and certainly constants or variables must have it or the wrong address will be resolved. In gcc __declspec can go at either the start or end of a prototype. In Microsoft C __declspec must go at the start, or after the type like void __declspec(...) *foo()". There's no __dllexport or anything to guard against someone foolish #defining dllexport. _export used to be available, but no longer. In Borland C _export still exists, but needs to go after the type, like "void _export foo();". Would have to change the __GMP_DECLSPEC syntax to make use of that. Probably more trouble than it's worth. */ #if defined (__GNUC__) #define __GMP_DECLSPEC_EXPORT __declspec(__dllexport__) #define __GMP_DECLSPEC_IMPORT __declspec(__dllimport__) #endif #if defined (_MSC_VER) || defined (__BORLANDC__) #define __GMP_DECLSPEC_EXPORT __declspec(dllexport) #define __GMP_DECLSPEC_IMPORT __declspec(dllimport) #endif #ifdef __WATCOMC__ #define __GMP_DECLSPEC_EXPORT __export #define __GMP_DECLSPEC_IMPORT __import #endif #ifdef __IBMC__ #define __GMP_DECLSPEC_EXPORT _Export #define __GMP_DECLSPEC_IMPORT _Import #endif #if __GMP_LIBGMP_DLL #ifdef __GMP_WITHIN_GMP /* compiling to go into a DLL libgmp */ #define __GMP_DECLSPEC __GMP_DECLSPEC_EXPORT #else /* compiling to go into an application which will link to a DLL libgmp */ #define __GMP_DECLSPEC __GMP_DECLSPEC_IMPORT #endif #else /* all other cases */ #define __GMP_DECLSPEC #endif #ifdef __GMP_SHORT_LIMB typedef unsigned int mp_limb_t; typedef int mp_limb_signed_t; #else #ifdef _LONG_LONG_LIMB typedef unsigned long long int mp_limb_t; typedef long long int mp_limb_signed_t; #else typedef unsigned long int mp_limb_t; typedef long int mp_limb_signed_t; #endif #endif typedef unsigned long int mp_bitcnt_t; /* For reference, note that the name __mpz_struct gets into C++ mangled function names, which means although the "__" suggests an internal, we must leave this name for binary compatibility. */ typedef struct { int _mp_alloc; /* Number of *limbs* allocated and pointed to by the _mp_d field. */ int _mp_size; /* abs(_mp_size) is the number of limbs the last field points to. If _mp_size is negative this is a negative number. */ mp_limb_t *_mp_d; /* Pointer to the limbs. */ } __mpz_struct; #endif /* __GNU_MP__ */ typedef __mpz_struct MP_INT; /* gmp 1 source compatibility */ typedef __mpz_struct mpz_t[1]; typedef mp_limb_t * mp_ptr; typedef const mp_limb_t * mp_srcptr; #if defined (_CRAY) && ! defined (_CRAYMPP) /* plain `int' is much faster (48 bits) */ #define __GMP_MP_SIZE_T_INT 1 typedef int mp_size_t; typedef int mp_exp_t; #else #define __GMP_MP_SIZE_T_INT 0 typedef long int mp_size_t; typedef long int mp_exp_t; #endif typedef struct { __mpz_struct _mp_num; __mpz_struct _mp_den; } __mpq_struct; typedef __mpq_struct MP_RAT; /* gmp 1 source compatibility */ typedef __mpq_struct mpq_t[1]; typedef struct { int _mp_prec; /* Max precision, in number of `mp_limb_t's. Set by mpf_init and modified by mpf_set_prec. The area pointed to by the _mp_d field contains `prec' + 1 limbs. */ int _mp_size; /* abs(_mp_size) is the number of limbs the last field points to. If _mp_size is negative this is a negative number. */ mp_exp_t _mp_exp; /* Exponent, in the base of `mp_limb_t'. */ mp_limb_t *_mp_d; /* Pointer to the limbs. */ } __mpf_struct; /* typedef __mpf_struct MP_FLOAT; */ typedef __mpf_struct mpf_t[1]; /* Available random number generation algorithms. */ typedef enum { GMP_RAND_ALG_DEFAULT = 0, GMP_RAND_ALG_LC = GMP_RAND_ALG_DEFAULT /* Linear congruential. */ } gmp_randalg_t; /* Random state struct. */ typedef struct { mpz_t _mp_seed; /* _mp_d member points to state of the generator. */ gmp_randalg_t _mp_alg; /* Currently unused. */ union { void *_mp_lc; /* Pointer to function pointers structure. */ } _mp_algdata; } __gmp_randstate_struct; typedef __gmp_randstate_struct gmp_randstate_t[1]; /* Types for function declarations in gmp files. */ /* ??? Should not pollute user name space with these ??? */ typedef const __mpz_struct *mpz_srcptr; typedef __mpz_struct *mpz_ptr; typedef const __mpf_struct *mpf_srcptr; typedef __mpf_struct *mpf_ptr; typedef const __mpq_struct *mpq_srcptr; typedef __mpq_struct *mpq_ptr; typedef __gmp_randstate_struct *gmp_randstate_ptr; typedef const __gmp_randstate_struct *gmp_randstate_srcptr; #if __GMP_LIBGMP_DLL #ifdef __GMP_WITHIN_GMPXX /* compiling to go into a DLL libgmpxx */ #define __GMP_DECLSPEC_XX __GMP_DECLSPEC_EXPORT #else /* compiling to go into a application which will link to a DLL libgmpxx */ #define __GMP_DECLSPEC_XX __GMP_DECLSPEC_IMPORT #endif #else /* all other cases */ #define __GMP_DECLSPEC_XX #endif #ifndef __MPN #define __MPN(x) __gmpn_##x #endif /* For reference, "defined(EOF)" cannot be used here. In g++ 2.95.4, defines EOF but not FILE. */ #if defined (FILE) \ || defined (H_STDIO) \ || defined (_H_STDIO) /* AIX */ \ || defined (_STDIO_H) /* glibc, Sun, SCO */ \ || defined (_STDIO_H_) /* BSD, OSF */ \ || defined (__STDIO_H) /* Borland */ \ || defined (__STDIO_H__) /* IRIX */ \ || defined (_STDIO_INCLUDED) /* HPUX */ \ || defined (__dj_include_stdio_h_) /* DJGPP */ \ || defined (_FILE_DEFINED) /* Microsoft */ \ || defined (__STDIO__) /* Apple MPW MrC */ \ || defined (_MSL_STDIO_H) /* Metrowerks */ \ || defined (_STDIO_H_INCLUDED) /* QNX4 */ \ || defined (_ISO_STDIO_ISO_H) /* Sun C++ */ \ || defined (__STDIO_LOADED) /* VMS */ \ || defined (_STDIO) /* HPE NonStop */ \ || defined (__DEFINED_FILE) /* musl */ #define _GMP_H_HAVE_FILE 1 #endif /* In ISO C, if a prototype involving "struct obstack *" is given without that structure defined, then the struct is scoped down to just the prototype, causing a conflict if it's subsequently defined for real. So only give prototypes if we've got obstack.h. */ #if defined (_OBSTACK_H) /* glibc */ #define _GMP_H_HAVE_OBSTACK 1 #endif /* The prototypes for gmp_vprintf etc are provided only if va_list is defined, via an application having included . Usually va_list is a typedef so can't be tested directly, but C99 specifies that va_start is a macro. will define some sort of va_list for vprintf and vfprintf, but let's not bother trying to use that since it's not standard and since application uses for gmp_vprintf etc will almost certainly require the whole anyway. */ #ifdef va_start #define _GMP_H_HAVE_VA_LIST 1 #endif /* Test for gcc >= maj.min, as per __GNUC_PREREQ in glibc */ #if defined (__GNUC__) && defined (__GNUC_MINOR__) #define __GMP_GNUC_PREREQ(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) #else #define __GMP_GNUC_PREREQ(maj, min) 0 #endif /* "pure" is in gcc 2.96 and up, see "(gcc)Function Attributes". Basically it means a function does nothing but examine its arguments and memory (global or via arguments) to generate a return value, but changes nothing and has no side-effects. __GMP_NO_ATTRIBUTE_CONST_PURE lets tune/common.c etc turn this off when trying to write timing loops. */ #if __GMP_GNUC_PREREQ (2,96) && ! defined (__GMP_NO_ATTRIBUTE_CONST_PURE) #define __GMP_ATTRIBUTE_PURE __attribute__ ((__pure__)) #else #define __GMP_ATTRIBUTE_PURE #endif /* __GMP_CAST allows us to use static_cast in C++, so our macros are clean to "g++ -Wold-style-cast". Casts in "extern inline" code within an extern "C" block don't induce these warnings, so __GMP_CAST only needs to be used on documented macros. */ #ifdef __cplusplus #define __GMP_CAST(type, expr) (static_cast (expr)) #else #define __GMP_CAST(type, expr) ((type) (expr)) #endif /* An empty "throw ()" means the function doesn't throw any C++ exceptions, this can save some stack frame info in applications. Currently it's given only on functions which never divide-by-zero etc, don't allocate memory, and are expected to never need to allocate memory. This leaves open the possibility of a C++ throw from a future GMP exceptions scheme. mpz_set_ui etc are omitted to leave open the lazy allocation scheme described in doc/tasks.html. mpz_get_d etc are omitted to leave open exceptions for float overflows. Note that __GMP_NOTHROW must be given on any inlines the same as on their prototypes (for g++ at least, where they're used together). Note also that g++ 3.0 demands that __GMP_NOTHROW is before other attributes like __GMP_ATTRIBUTE_PURE. */ #if defined (__cplusplus) #if __cplusplus >= 201103L #define __GMP_NOTHROW noexcept #else #define __GMP_NOTHROW throw () #endif #else #define __GMP_NOTHROW #endif /* PORTME: What other compilers have a useful "extern inline"? "static inline" would be an acceptable substitute if the compiler (or linker) discards unused statics. */ /* gcc has __inline__ in all modes, including strict ansi. Give a prototype for an inline too, so as to correctly specify "dllimport" on windows, in case the function is called rather than inlined. GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99 inline semantics, unless -fgnu89-inline is used. */ #ifdef __GNUC__ #if (defined __GNUC_STDC_INLINE__) || (__GNUC__ == 4 && __GNUC_MINOR__ == 2) \ || (defined __GNUC_GNU_INLINE__ && defined __cplusplus) #define __GMP_EXTERN_INLINE extern __inline__ __attribute__ ((__gnu_inline__)) #else #define __GMP_EXTERN_INLINE extern __inline__ #endif #define __GMP_INLINE_PROTOTYPES 1 #endif /* DEC C (eg. version 5.9) supports "static __inline foo()", even in -std1 strict ANSI mode. Inlining is done even when not optimizing (ie. -O0 mode, which is the default), but an unnecessary local copy of foo is emitted unless -O is used. "extern __inline" is accepted, but the "extern" appears to be ignored, ie. it becomes a plain global function but which is inlined within its file. Don't know if all old versions of DEC C supported __inline, but as a start let's do the right thing for current versions. */ #ifdef __DECC #define __GMP_EXTERN_INLINE static __inline #endif /* SCO OpenUNIX 8 cc supports "static inline foo()" but not in -Xc strict ANSI mode (__STDC__ is 1 in that mode). Inlining only actually takes place under -O. Without -O "foo" seems to be emitted whether it's used or not, which is wasteful. "extern inline foo()" isn't useful, the "extern" is apparently ignored, so foo is inlined if possible but also emitted as a global, which causes multiple definition errors when building a shared libgmp. */ #ifdef __SCO_VERSION__ #if __SCO_VERSION__ > 400000000 && __STDC__ != 1 \ && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE static inline #endif #endif /* Microsoft's C compiler accepts __inline */ #ifdef _MSC_VER #define __GMP_EXTERN_INLINE __inline #endif /* Recent enough Sun C compilers want "inline" */ #if defined (__SUNPRO_C) && __SUNPRO_C >= 0x560 \ && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE inline #endif /* Somewhat older Sun C compilers want "static inline" */ #if defined (__SUNPRO_C) && __SUNPRO_C >= 0x540 \ && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE static inline #endif /* C++ always has "inline" and since it's a normal feature the linker should discard duplicate non-inlined copies, or if it doesn't then that's a problem for everyone, not just GMP. */ #if defined (__cplusplus) && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE inline #endif /* Don't do any inlining within a configure run, since if the compiler ends up emitting copies of the code into the object file it can end up demanding the various support routines (like mpn_popcount) for linking, making the "alloca" test and perhaps others fail. And on hppa ia64 a pre-release gcc 3.2 was seen not respecting the "extern" in "extern __inline__", triggering this problem too. */ #if defined (__GMP_WITHIN_CONFIGURE) && ! __GMP_WITHIN_CONFIGURE_INLINE #undef __GMP_EXTERN_INLINE #endif /* By default, don't give a prototype when there's going to be an inline version. Note in particular that Cray C++ objects to the combination of prototype and inline. */ #ifdef __GMP_EXTERN_INLINE #ifndef __GMP_INLINE_PROTOTYPES #define __GMP_INLINE_PROTOTYPES 0 #endif #else #define __GMP_INLINE_PROTOTYPES 1 #endif #define __GMP_ABS(x) ((x) >= 0 ? (x) : -(x)) #define __GMP_MAX(h,i) ((h) > (i) ? (h) : (i)) /* __builtin_expect is in gcc 3.0, and not in 2.95. */ #if __GMP_GNUC_PREREQ (3,0) #define __GMP_LIKELY(cond) __builtin_expect ((cond) != 0, 1) #define __GMP_UNLIKELY(cond) __builtin_expect ((cond) != 0, 0) #else #define __GMP_LIKELY(cond) (cond) #define __GMP_UNLIKELY(cond) (cond) #endif #ifdef _CRAY #define __GMP_CRAY_Pragma(str) _Pragma (str) #else #define __GMP_CRAY_Pragma(str) #endif /* Allow direct user access to numerator and denominator of an mpq_t object. */ #define mpq_numref(Q) (&((Q)->_mp_num)) #define mpq_denref(Q) (&((Q)->_mp_den)) #if defined (__cplusplus) extern "C" { using std::FILE; #endif #define mp_set_memory_functions __gmp_set_memory_functions __GMP_DECLSPEC void mp_set_memory_functions (void *(*) (size_t), void *(*) (void *, size_t, size_t), void (*) (void *, size_t)) __GMP_NOTHROW; #define mp_get_memory_functions __gmp_get_memory_functions __GMP_DECLSPEC void mp_get_memory_functions (void *(**) (size_t), void *(**) (void *, size_t, size_t), void (**) (void *, size_t)) __GMP_NOTHROW; #define mp_bits_per_limb __gmp_bits_per_limb __GMP_DECLSPEC extern const int mp_bits_per_limb; #define gmp_errno __gmp_errno __GMP_DECLSPEC extern int gmp_errno; #define gmp_version __gmp_version __GMP_DECLSPEC extern const char * const gmp_version; /**************** Random number routines. ****************/ /* obsolete */ #define gmp_randinit __gmp_randinit __GMP_DECLSPEC void gmp_randinit (gmp_randstate_ptr, gmp_randalg_t, ...); #define gmp_randinit_default __gmp_randinit_default __GMP_DECLSPEC void gmp_randinit_default (gmp_randstate_ptr); #define gmp_randinit_lc_2exp __gmp_randinit_lc_2exp __GMP_DECLSPEC void gmp_randinit_lc_2exp (gmp_randstate_ptr, mpz_srcptr, unsigned long int, mp_bitcnt_t); #define gmp_randinit_lc_2exp_size __gmp_randinit_lc_2exp_size __GMP_DECLSPEC int gmp_randinit_lc_2exp_size (gmp_randstate_ptr, mp_bitcnt_t); #define gmp_randinit_mt __gmp_randinit_mt __GMP_DECLSPEC void gmp_randinit_mt (gmp_randstate_ptr); #define gmp_randinit_set __gmp_randinit_set __GMP_DECLSPEC void gmp_randinit_set (gmp_randstate_ptr, gmp_randstate_srcptr); #define gmp_randseed __gmp_randseed __GMP_DECLSPEC void gmp_randseed (gmp_randstate_ptr, mpz_srcptr); #define gmp_randseed_ui __gmp_randseed_ui __GMP_DECLSPEC void gmp_randseed_ui (gmp_randstate_ptr, unsigned long int); #define gmp_randclear __gmp_randclear __GMP_DECLSPEC void gmp_randclear (gmp_randstate_ptr); #define gmp_urandomb_ui __gmp_urandomb_ui __GMP_DECLSPEC unsigned long gmp_urandomb_ui (gmp_randstate_ptr, unsigned long); #define gmp_urandomm_ui __gmp_urandomm_ui __GMP_DECLSPEC unsigned long gmp_urandomm_ui (gmp_randstate_ptr, unsigned long); /**************** Formatted output routines. ****************/ #define gmp_asprintf __gmp_asprintf __GMP_DECLSPEC int gmp_asprintf (char **, const char *, ...); #define gmp_fprintf __gmp_fprintf #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC int gmp_fprintf (FILE *, const char *, ...); #endif #define gmp_obstack_printf __gmp_obstack_printf #if defined (_GMP_H_HAVE_OBSTACK) __GMP_DECLSPEC int gmp_obstack_printf (struct obstack *, const char *, ...); #endif #define gmp_obstack_vprintf __gmp_obstack_vprintf #if defined (_GMP_H_HAVE_OBSTACK) && defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_obstack_vprintf (struct obstack *, const char *, va_list); #endif #define gmp_printf __gmp_printf __GMP_DECLSPEC int gmp_printf (const char *, ...); #define gmp_snprintf __gmp_snprintf __GMP_DECLSPEC int gmp_snprintf (char *, size_t, const char *, ...); #define gmp_sprintf __gmp_sprintf __GMP_DECLSPEC int gmp_sprintf (char *, const char *, ...); #define gmp_vasprintf __gmp_vasprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vasprintf (char **, const char *, va_list); #endif #define gmp_vfprintf __gmp_vfprintf #if defined (_GMP_H_HAVE_FILE) && defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vfprintf (FILE *, const char *, va_list); #endif #define gmp_vprintf __gmp_vprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vprintf (const char *, va_list); #endif #define gmp_vsnprintf __gmp_vsnprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vsnprintf (char *, size_t, const char *, va_list); #endif #define gmp_vsprintf __gmp_vsprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vsprintf (char *, const char *, va_list); #endif /**************** Formatted input routines. ****************/ #define gmp_fscanf __gmp_fscanf #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC int gmp_fscanf (FILE *, const char *, ...); #endif #define gmp_scanf __gmp_scanf __GMP_DECLSPEC int gmp_scanf (const char *, ...); #define gmp_sscanf __gmp_sscanf __GMP_DECLSPEC int gmp_sscanf (const char *, const char *, ...); #define gmp_vfscanf __gmp_vfscanf #if defined (_GMP_H_HAVE_FILE) && defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vfscanf (FILE *, const char *, va_list); #endif #define gmp_vscanf __gmp_vscanf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vscanf (const char *, va_list); #endif #define gmp_vsscanf __gmp_vsscanf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vsscanf (const char *, const char *, va_list); #endif /**************** Integer (i.e. Z) routines. ****************/ #define _mpz_realloc __gmpz_realloc #define mpz_realloc __gmpz_realloc __GMP_DECLSPEC void *_mpz_realloc (mpz_ptr, mp_size_t); #define mpz_abs __gmpz_abs #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_abs) __GMP_DECLSPEC void mpz_abs (mpz_ptr, mpz_srcptr); #endif #define mpz_add __gmpz_add __GMP_DECLSPEC void mpz_add (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_add_ui __gmpz_add_ui __GMP_DECLSPEC void mpz_add_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_addmul __gmpz_addmul __GMP_DECLSPEC void mpz_addmul (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_addmul_ui __gmpz_addmul_ui __GMP_DECLSPEC void mpz_addmul_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_and __gmpz_and __GMP_DECLSPEC void mpz_and (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_array_init __gmpz_array_init __GMP_DECLSPEC void mpz_array_init (mpz_ptr, mp_size_t, mp_size_t); #define mpz_bin_ui __gmpz_bin_ui __GMP_DECLSPEC void mpz_bin_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_bin_uiui __gmpz_bin_uiui __GMP_DECLSPEC void mpz_bin_uiui (mpz_ptr, unsigned long int, unsigned long int); #define mpz_cdiv_q __gmpz_cdiv_q __GMP_DECLSPEC void mpz_cdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_cdiv_q_2exp __gmpz_cdiv_q_2exp __GMP_DECLSPEC void mpz_cdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_cdiv_q_ui __gmpz_cdiv_q_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_cdiv_qr __gmpz_cdiv_qr __GMP_DECLSPEC void mpz_cdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_cdiv_qr_ui __gmpz_cdiv_qr_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_cdiv_r __gmpz_cdiv_r __GMP_DECLSPEC void mpz_cdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_cdiv_r_2exp __gmpz_cdiv_r_2exp __GMP_DECLSPEC void mpz_cdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_cdiv_r_ui __gmpz_cdiv_r_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_cdiv_ui __gmpz_cdiv_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpz_clear __gmpz_clear __GMP_DECLSPEC void mpz_clear (mpz_ptr); #define mpz_clears __gmpz_clears __GMP_DECLSPEC void mpz_clears (mpz_ptr, ...); #define mpz_clrbit __gmpz_clrbit __GMP_DECLSPEC void mpz_clrbit (mpz_ptr, mp_bitcnt_t); #define mpz_cmp __gmpz_cmp __GMP_DECLSPEC int mpz_cmp (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_cmp_d __gmpz_cmp_d __GMP_DECLSPEC int mpz_cmp_d (mpz_srcptr, double) __GMP_ATTRIBUTE_PURE; #define _mpz_cmp_si __gmpz_cmp_si __GMP_DECLSPEC int _mpz_cmp_si (mpz_srcptr, signed long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define _mpz_cmp_ui __gmpz_cmp_ui __GMP_DECLSPEC int _mpz_cmp_ui (mpz_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_cmpabs __gmpz_cmpabs __GMP_DECLSPEC int mpz_cmpabs (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_cmpabs_d __gmpz_cmpabs_d __GMP_DECLSPEC int mpz_cmpabs_d (mpz_srcptr, double) __GMP_ATTRIBUTE_PURE; #define mpz_cmpabs_ui __gmpz_cmpabs_ui __GMP_DECLSPEC int mpz_cmpabs_ui (mpz_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_com __gmpz_com __GMP_DECLSPEC void mpz_com (mpz_ptr, mpz_srcptr); #define mpz_combit __gmpz_combit __GMP_DECLSPEC void mpz_combit (mpz_ptr, mp_bitcnt_t); #define mpz_congruent_p __gmpz_congruent_p __GMP_DECLSPEC int mpz_congruent_p (mpz_srcptr, mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_congruent_2exp_p __gmpz_congruent_2exp_p __GMP_DECLSPEC int mpz_congruent_2exp_p (mpz_srcptr, mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_congruent_ui_p __gmpz_congruent_ui_p __GMP_DECLSPEC int mpz_congruent_ui_p (mpz_srcptr, unsigned long, unsigned long) __GMP_ATTRIBUTE_PURE; #define mpz_divexact __gmpz_divexact __GMP_DECLSPEC void mpz_divexact (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_divexact_ui __gmpz_divexact_ui __GMP_DECLSPEC void mpz_divexact_ui (mpz_ptr, mpz_srcptr, unsigned long); #define mpz_divisible_p __gmpz_divisible_p __GMP_DECLSPEC int mpz_divisible_p (mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_divisible_ui_p __gmpz_divisible_ui_p __GMP_DECLSPEC int mpz_divisible_ui_p (mpz_srcptr, unsigned long) __GMP_ATTRIBUTE_PURE; #define mpz_divisible_2exp_p __gmpz_divisible_2exp_p __GMP_DECLSPEC int mpz_divisible_2exp_p (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_dump __gmpz_dump __GMP_DECLSPEC void mpz_dump (mpz_srcptr); #define mpz_export __gmpz_export __GMP_DECLSPEC void *mpz_export (void *, size_t *, int, size_t, int, size_t, mpz_srcptr); #define mpz_fac_ui __gmpz_fac_ui __GMP_DECLSPEC void mpz_fac_ui (mpz_ptr, unsigned long int); #define mpz_2fac_ui __gmpz_2fac_ui __GMP_DECLSPEC void mpz_2fac_ui (mpz_ptr, unsigned long int); #define mpz_mfac_uiui __gmpz_mfac_uiui __GMP_DECLSPEC void mpz_mfac_uiui (mpz_ptr, unsigned long int, unsigned long int); #define mpz_primorial_ui __gmpz_primorial_ui __GMP_DECLSPEC void mpz_primorial_ui (mpz_ptr, unsigned long int); #define mpz_fdiv_q __gmpz_fdiv_q __GMP_DECLSPEC void mpz_fdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_fdiv_q_2exp __gmpz_fdiv_q_2exp __GMP_DECLSPEC void mpz_fdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_fdiv_q_ui __gmpz_fdiv_q_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_fdiv_qr __gmpz_fdiv_qr __GMP_DECLSPEC void mpz_fdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_fdiv_qr_ui __gmpz_fdiv_qr_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_fdiv_r __gmpz_fdiv_r __GMP_DECLSPEC void mpz_fdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_fdiv_r_2exp __gmpz_fdiv_r_2exp __GMP_DECLSPEC void mpz_fdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_fdiv_r_ui __gmpz_fdiv_r_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_fdiv_ui __gmpz_fdiv_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpz_fib_ui __gmpz_fib_ui __GMP_DECLSPEC void mpz_fib_ui (mpz_ptr, unsigned long int); #define mpz_fib2_ui __gmpz_fib2_ui __GMP_DECLSPEC void mpz_fib2_ui (mpz_ptr, mpz_ptr, unsigned long int); #define mpz_fits_sint_p __gmpz_fits_sint_p __GMP_DECLSPEC int mpz_fits_sint_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_fits_slong_p __gmpz_fits_slong_p __GMP_DECLSPEC int mpz_fits_slong_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_fits_sshort_p __gmpz_fits_sshort_p __GMP_DECLSPEC int mpz_fits_sshort_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_fits_uint_p __gmpz_fits_uint_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_uint_p) __GMP_DECLSPEC int mpz_fits_uint_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_fits_ulong_p __gmpz_fits_ulong_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_ulong_p) __GMP_DECLSPEC int mpz_fits_ulong_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_fits_ushort_p __gmpz_fits_ushort_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_ushort_p) __GMP_DECLSPEC int mpz_fits_ushort_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_gcd __gmpz_gcd __GMP_DECLSPEC void mpz_gcd (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_gcd_ui __gmpz_gcd_ui __GMP_DECLSPEC unsigned long int mpz_gcd_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_gcdext __gmpz_gcdext __GMP_DECLSPEC void mpz_gcdext (mpz_ptr, mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_get_d __gmpz_get_d __GMP_DECLSPEC double mpz_get_d (mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_get_d_2exp __gmpz_get_d_2exp __GMP_DECLSPEC double mpz_get_d_2exp (signed long int *, mpz_srcptr); #define mpz_get_si __gmpz_get_si __GMP_DECLSPEC /* signed */ long int mpz_get_si (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_get_str __gmpz_get_str __GMP_DECLSPEC char *mpz_get_str (char *, int, mpz_srcptr); #define mpz_get_ui __gmpz_get_ui #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_get_ui) __GMP_DECLSPEC unsigned long int mpz_get_ui (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_getlimbn __gmpz_getlimbn #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_getlimbn) __GMP_DECLSPEC mp_limb_t mpz_getlimbn (mpz_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_hamdist __gmpz_hamdist __GMP_DECLSPEC mp_bitcnt_t mpz_hamdist (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_import __gmpz_import __GMP_DECLSPEC void mpz_import (mpz_ptr, size_t, int, size_t, int, size_t, const void *); #define mpz_init __gmpz_init __GMP_DECLSPEC void mpz_init (mpz_ptr) __GMP_NOTHROW; #define mpz_init2 __gmpz_init2 __GMP_DECLSPEC void mpz_init2 (mpz_ptr, mp_bitcnt_t); #define mpz_inits __gmpz_inits __GMP_DECLSPEC void mpz_inits (mpz_ptr, ...) __GMP_NOTHROW; #define mpz_init_set __gmpz_init_set __GMP_DECLSPEC void mpz_init_set (mpz_ptr, mpz_srcptr); #define mpz_init_set_d __gmpz_init_set_d __GMP_DECLSPEC void mpz_init_set_d (mpz_ptr, double); #define mpz_init_set_si __gmpz_init_set_si __GMP_DECLSPEC void mpz_init_set_si (mpz_ptr, signed long int); #define mpz_init_set_str __gmpz_init_set_str __GMP_DECLSPEC int mpz_init_set_str (mpz_ptr, const char *, int); #define mpz_init_set_ui __gmpz_init_set_ui __GMP_DECLSPEC void mpz_init_set_ui (mpz_ptr, unsigned long int); #define mpz_inp_raw __gmpz_inp_raw #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_inp_raw (mpz_ptr, FILE *); #endif #define mpz_inp_str __gmpz_inp_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_inp_str (mpz_ptr, FILE *, int); #endif #define mpz_invert __gmpz_invert __GMP_DECLSPEC int mpz_invert (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_ior __gmpz_ior __GMP_DECLSPEC void mpz_ior (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_jacobi __gmpz_jacobi __GMP_DECLSPEC int mpz_jacobi (mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_kronecker mpz_jacobi /* alias */ #define mpz_kronecker_si __gmpz_kronecker_si __GMP_DECLSPEC int mpz_kronecker_si (mpz_srcptr, long) __GMP_ATTRIBUTE_PURE; #define mpz_kronecker_ui __gmpz_kronecker_ui __GMP_DECLSPEC int mpz_kronecker_ui (mpz_srcptr, unsigned long) __GMP_ATTRIBUTE_PURE; #define mpz_si_kronecker __gmpz_si_kronecker __GMP_DECLSPEC int mpz_si_kronecker (long, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_ui_kronecker __gmpz_ui_kronecker __GMP_DECLSPEC int mpz_ui_kronecker (unsigned long, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_lcm __gmpz_lcm __GMP_DECLSPEC void mpz_lcm (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_lcm_ui __gmpz_lcm_ui __GMP_DECLSPEC void mpz_lcm_ui (mpz_ptr, mpz_srcptr, unsigned long); #define mpz_legendre mpz_jacobi /* alias */ #define mpz_lucnum_ui __gmpz_lucnum_ui __GMP_DECLSPEC void mpz_lucnum_ui (mpz_ptr, unsigned long int); #define mpz_lucnum2_ui __gmpz_lucnum2_ui __GMP_DECLSPEC void mpz_lucnum2_ui (mpz_ptr, mpz_ptr, unsigned long int); #define mpz_millerrabin __gmpz_millerrabin __GMP_DECLSPEC int mpz_millerrabin (mpz_srcptr, int) __GMP_ATTRIBUTE_PURE; #define mpz_mod __gmpz_mod __GMP_DECLSPEC void mpz_mod (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_mod_ui mpz_fdiv_r_ui /* same as fdiv_r because divisor unsigned */ #define mpz_mul __gmpz_mul __GMP_DECLSPEC void mpz_mul (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_mul_2exp __gmpz_mul_2exp __GMP_DECLSPEC void mpz_mul_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_mul_si __gmpz_mul_si __GMP_DECLSPEC void mpz_mul_si (mpz_ptr, mpz_srcptr, long int); #define mpz_mul_ui __gmpz_mul_ui __GMP_DECLSPEC void mpz_mul_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_neg __gmpz_neg #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_neg) __GMP_DECLSPEC void mpz_neg (mpz_ptr, mpz_srcptr); #endif #define mpz_nextprime __gmpz_nextprime __GMP_DECLSPEC void mpz_nextprime (mpz_ptr, mpz_srcptr); #define mpz_prevprime __gmpz_prevprime __GMP_DECLSPEC int mpz_prevprime (mpz_ptr, mpz_srcptr); #define mpz_out_raw __gmpz_out_raw #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_out_raw (FILE *, mpz_srcptr); #endif #define mpz_out_str __gmpz_out_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_out_str (FILE *, int, mpz_srcptr); #endif #define mpz_perfect_power_p __gmpz_perfect_power_p __GMP_DECLSPEC int mpz_perfect_power_p (mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_perfect_square_p __gmpz_perfect_square_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_perfect_square_p) __GMP_DECLSPEC int mpz_perfect_square_p (mpz_srcptr) __GMP_ATTRIBUTE_PURE; #endif #define mpz_popcount __gmpz_popcount #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_popcount) __GMP_DECLSPEC mp_bitcnt_t mpz_popcount (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_pow_ui __gmpz_pow_ui __GMP_DECLSPEC void mpz_pow_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_powm __gmpz_powm __GMP_DECLSPEC void mpz_powm (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr); #define mpz_powm_sec __gmpz_powm_sec __GMP_DECLSPEC void mpz_powm_sec (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr); #define mpz_powm_ui __gmpz_powm_ui __GMP_DECLSPEC void mpz_powm_ui (mpz_ptr, mpz_srcptr, unsigned long int, mpz_srcptr); #define mpz_probab_prime_p __gmpz_probab_prime_p __GMP_DECLSPEC int mpz_probab_prime_p (mpz_srcptr, int) __GMP_ATTRIBUTE_PURE; #define mpz_random __gmpz_random __GMP_DECLSPEC void mpz_random (mpz_ptr, mp_size_t); #define mpz_random2 __gmpz_random2 __GMP_DECLSPEC void mpz_random2 (mpz_ptr, mp_size_t); #define mpz_realloc2 __gmpz_realloc2 __GMP_DECLSPEC void mpz_realloc2 (mpz_ptr, mp_bitcnt_t); #define mpz_remove __gmpz_remove __GMP_DECLSPEC mp_bitcnt_t mpz_remove (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_root __gmpz_root __GMP_DECLSPEC int mpz_root (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_rootrem __gmpz_rootrem __GMP_DECLSPEC void mpz_rootrem (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_rrandomb __gmpz_rrandomb __GMP_DECLSPEC void mpz_rrandomb (mpz_ptr, gmp_randstate_ptr, mp_bitcnt_t); #define mpz_scan0 __gmpz_scan0 __GMP_DECLSPEC mp_bitcnt_t mpz_scan0 (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_scan1 __gmpz_scan1 __GMP_DECLSPEC mp_bitcnt_t mpz_scan1 (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_set __gmpz_set __GMP_DECLSPEC void mpz_set (mpz_ptr, mpz_srcptr); #define mpz_set_d __gmpz_set_d __GMP_DECLSPEC void mpz_set_d (mpz_ptr, double); #define mpz_set_f __gmpz_set_f __GMP_DECLSPEC void mpz_set_f (mpz_ptr, mpf_srcptr); #define mpz_set_q __gmpz_set_q #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_set_q) __GMP_DECLSPEC void mpz_set_q (mpz_ptr, mpq_srcptr); #endif #define mpz_set_si __gmpz_set_si __GMP_DECLSPEC void mpz_set_si (mpz_ptr, signed long int); #define mpz_set_str __gmpz_set_str __GMP_DECLSPEC int mpz_set_str (mpz_ptr, const char *, int); #define mpz_set_ui __gmpz_set_ui __GMP_DECLSPEC void mpz_set_ui (mpz_ptr, unsigned long int); #define mpz_setbit __gmpz_setbit __GMP_DECLSPEC void mpz_setbit (mpz_ptr, mp_bitcnt_t); #define mpz_size __gmpz_size #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_size) __GMP_DECLSPEC size_t mpz_size (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_sizeinbase __gmpz_sizeinbase __GMP_DECLSPEC size_t mpz_sizeinbase (mpz_srcptr, int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_sqrt __gmpz_sqrt __GMP_DECLSPEC void mpz_sqrt (mpz_ptr, mpz_srcptr); #define mpz_sqrtrem __gmpz_sqrtrem __GMP_DECLSPEC void mpz_sqrtrem (mpz_ptr, mpz_ptr, mpz_srcptr); #define mpz_sub __gmpz_sub __GMP_DECLSPEC void mpz_sub (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_sub_ui __gmpz_sub_ui __GMP_DECLSPEC void mpz_sub_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_ui_sub __gmpz_ui_sub __GMP_DECLSPEC void mpz_ui_sub (mpz_ptr, unsigned long int, mpz_srcptr); #define mpz_submul __gmpz_submul __GMP_DECLSPEC void mpz_submul (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_submul_ui __gmpz_submul_ui __GMP_DECLSPEC void mpz_submul_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_swap __gmpz_swap __GMP_DECLSPEC void mpz_swap (mpz_ptr, mpz_ptr) __GMP_NOTHROW; #define mpz_tdiv_ui __gmpz_tdiv_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpz_tdiv_q __gmpz_tdiv_q __GMP_DECLSPEC void mpz_tdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_tdiv_q_2exp __gmpz_tdiv_q_2exp __GMP_DECLSPEC void mpz_tdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_tdiv_q_ui __gmpz_tdiv_q_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_tdiv_qr __gmpz_tdiv_qr __GMP_DECLSPEC void mpz_tdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_tdiv_qr_ui __gmpz_tdiv_qr_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_tdiv_r __gmpz_tdiv_r __GMP_DECLSPEC void mpz_tdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_tdiv_r_2exp __gmpz_tdiv_r_2exp __GMP_DECLSPEC void mpz_tdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_tdiv_r_ui __gmpz_tdiv_r_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_tstbit __gmpz_tstbit __GMP_DECLSPEC int mpz_tstbit (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_ui_pow_ui __gmpz_ui_pow_ui __GMP_DECLSPEC void mpz_ui_pow_ui (mpz_ptr, unsigned long int, unsigned long int); #define mpz_urandomb __gmpz_urandomb __GMP_DECLSPEC void mpz_urandomb (mpz_ptr, gmp_randstate_ptr, mp_bitcnt_t); #define mpz_urandomm __gmpz_urandomm __GMP_DECLSPEC void mpz_urandomm (mpz_ptr, gmp_randstate_ptr, mpz_srcptr); #define mpz_xor __gmpz_xor #define mpz_eor __gmpz_xor __GMP_DECLSPEC void mpz_xor (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_limbs_read __gmpz_limbs_read __GMP_DECLSPEC mp_srcptr mpz_limbs_read (mpz_srcptr); #define mpz_limbs_write __gmpz_limbs_write __GMP_DECLSPEC mp_ptr mpz_limbs_write (mpz_ptr, mp_size_t); #define mpz_limbs_modify __gmpz_limbs_modify __GMP_DECLSPEC mp_ptr mpz_limbs_modify (mpz_ptr, mp_size_t); #define mpz_limbs_finish __gmpz_limbs_finish __GMP_DECLSPEC void mpz_limbs_finish (mpz_ptr, mp_size_t); #define mpz_roinit_n __gmpz_roinit_n __GMP_DECLSPEC mpz_srcptr mpz_roinit_n (mpz_ptr, mp_srcptr, mp_size_t); #define MPZ_ROINIT_N(xp, xs) {{0, (xs),(xp) }} /**************** Rational (i.e. Q) routines. ****************/ #define mpq_abs __gmpq_abs #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpq_abs) __GMP_DECLSPEC void mpq_abs (mpq_ptr, mpq_srcptr); #endif #define mpq_add __gmpq_add __GMP_DECLSPEC void mpq_add (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_canonicalize __gmpq_canonicalize __GMP_DECLSPEC void mpq_canonicalize (mpq_ptr); #define mpq_clear __gmpq_clear __GMP_DECLSPEC void mpq_clear (mpq_ptr); #define mpq_clears __gmpq_clears __GMP_DECLSPEC void mpq_clears (mpq_ptr, ...); #define mpq_cmp __gmpq_cmp __GMP_DECLSPEC int mpq_cmp (mpq_srcptr, mpq_srcptr) __GMP_ATTRIBUTE_PURE; #define _mpq_cmp_si __gmpq_cmp_si __GMP_DECLSPEC int _mpq_cmp_si (mpq_srcptr, long, unsigned long) __GMP_ATTRIBUTE_PURE; #define _mpq_cmp_ui __gmpq_cmp_ui __GMP_DECLSPEC int _mpq_cmp_ui (mpq_srcptr, unsigned long int, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpq_cmp_z __gmpq_cmp_z __GMP_DECLSPEC int mpq_cmp_z (mpq_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpq_div __gmpq_div __GMP_DECLSPEC void mpq_div (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_div_2exp __gmpq_div_2exp __GMP_DECLSPEC void mpq_div_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t); #define mpq_equal __gmpq_equal __GMP_DECLSPEC int mpq_equal (mpq_srcptr, mpq_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpq_get_num __gmpq_get_num __GMP_DECLSPEC void mpq_get_num (mpz_ptr, mpq_srcptr); #define mpq_get_den __gmpq_get_den __GMP_DECLSPEC void mpq_get_den (mpz_ptr, mpq_srcptr); #define mpq_get_d __gmpq_get_d __GMP_DECLSPEC double mpq_get_d (mpq_srcptr) __GMP_ATTRIBUTE_PURE; #define mpq_get_str __gmpq_get_str __GMP_DECLSPEC char *mpq_get_str (char *, int, mpq_srcptr); #define mpq_init __gmpq_init __GMP_DECLSPEC void mpq_init (mpq_ptr); #define mpq_inits __gmpq_inits __GMP_DECLSPEC void mpq_inits (mpq_ptr, ...); #define mpq_inp_str __gmpq_inp_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpq_inp_str (mpq_ptr, FILE *, int); #endif #define mpq_inv __gmpq_inv __GMP_DECLSPEC void mpq_inv (mpq_ptr, mpq_srcptr); #define mpq_mul __gmpq_mul __GMP_DECLSPEC void mpq_mul (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_mul_2exp __gmpq_mul_2exp __GMP_DECLSPEC void mpq_mul_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t); #define mpq_neg __gmpq_neg #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpq_neg) __GMP_DECLSPEC void mpq_neg (mpq_ptr, mpq_srcptr); #endif #define mpq_out_str __gmpq_out_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpq_out_str (FILE *, int, mpq_srcptr); #endif #define mpq_set __gmpq_set __GMP_DECLSPEC void mpq_set (mpq_ptr, mpq_srcptr); #define mpq_set_d __gmpq_set_d __GMP_DECLSPEC void mpq_set_d (mpq_ptr, double); #define mpq_set_den __gmpq_set_den __GMP_DECLSPEC void mpq_set_den (mpq_ptr, mpz_srcptr); #define mpq_set_f __gmpq_set_f __GMP_DECLSPEC void mpq_set_f (mpq_ptr, mpf_srcptr); #define mpq_set_num __gmpq_set_num __GMP_DECLSPEC void mpq_set_num (mpq_ptr, mpz_srcptr); #define mpq_set_si __gmpq_set_si __GMP_DECLSPEC void mpq_set_si (mpq_ptr, signed long int, unsigned long int); #define mpq_set_str __gmpq_set_str __GMP_DECLSPEC int mpq_set_str (mpq_ptr, const char *, int); #define mpq_set_ui __gmpq_set_ui __GMP_DECLSPEC void mpq_set_ui (mpq_ptr, unsigned long int, unsigned long int); #define mpq_set_z __gmpq_set_z __GMP_DECLSPEC void mpq_set_z (mpq_ptr, mpz_srcptr); #define mpq_sub __gmpq_sub __GMP_DECLSPEC void mpq_sub (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_swap __gmpq_swap __GMP_DECLSPEC void mpq_swap (mpq_ptr, mpq_ptr) __GMP_NOTHROW; /**************** Float (i.e. F) routines. ****************/ #define mpf_abs __gmpf_abs __GMP_DECLSPEC void mpf_abs (mpf_ptr, mpf_srcptr); #define mpf_add __gmpf_add __GMP_DECLSPEC void mpf_add (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_add_ui __gmpf_add_ui __GMP_DECLSPEC void mpf_add_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_ceil __gmpf_ceil __GMP_DECLSPEC void mpf_ceil (mpf_ptr, mpf_srcptr); #define mpf_clear __gmpf_clear __GMP_DECLSPEC void mpf_clear (mpf_ptr); #define mpf_clears __gmpf_clears __GMP_DECLSPEC void mpf_clears (mpf_ptr, ...); #define mpf_cmp __gmpf_cmp __GMP_DECLSPEC int mpf_cmp (mpf_srcptr, mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_cmp_z __gmpf_cmp_z __GMP_DECLSPEC int mpf_cmp_z (mpf_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_cmp_d __gmpf_cmp_d __GMP_DECLSPEC int mpf_cmp_d (mpf_srcptr, double) __GMP_ATTRIBUTE_PURE; #define mpf_cmp_si __gmpf_cmp_si __GMP_DECLSPEC int mpf_cmp_si (mpf_srcptr, signed long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_cmp_ui __gmpf_cmp_ui __GMP_DECLSPEC int mpf_cmp_ui (mpf_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_div __gmpf_div __GMP_DECLSPEC void mpf_div (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_div_2exp __gmpf_div_2exp __GMP_DECLSPEC void mpf_div_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t); #define mpf_div_ui __gmpf_div_ui __GMP_DECLSPEC void mpf_div_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_dump __gmpf_dump __GMP_DECLSPEC void mpf_dump (mpf_srcptr); #define mpf_eq __gmpf_eq __GMP_DECLSPEC int mpf_eq (mpf_srcptr, mpf_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE; #define mpf_fits_sint_p __gmpf_fits_sint_p __GMP_DECLSPEC int mpf_fits_sint_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_slong_p __gmpf_fits_slong_p __GMP_DECLSPEC int mpf_fits_slong_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_sshort_p __gmpf_fits_sshort_p __GMP_DECLSPEC int mpf_fits_sshort_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_uint_p __gmpf_fits_uint_p __GMP_DECLSPEC int mpf_fits_uint_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_ulong_p __gmpf_fits_ulong_p __GMP_DECLSPEC int mpf_fits_ulong_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_ushort_p __gmpf_fits_ushort_p __GMP_DECLSPEC int mpf_fits_ushort_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_floor __gmpf_floor __GMP_DECLSPEC void mpf_floor (mpf_ptr, mpf_srcptr); #define mpf_get_d __gmpf_get_d __GMP_DECLSPEC double mpf_get_d (mpf_srcptr) __GMP_ATTRIBUTE_PURE; #define mpf_get_d_2exp __gmpf_get_d_2exp __GMP_DECLSPEC double mpf_get_d_2exp (signed long int *, mpf_srcptr); #define mpf_get_default_prec __gmpf_get_default_prec __GMP_DECLSPEC mp_bitcnt_t mpf_get_default_prec (void) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_get_prec __gmpf_get_prec __GMP_DECLSPEC mp_bitcnt_t mpf_get_prec (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_get_si __gmpf_get_si __GMP_DECLSPEC long mpf_get_si (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_get_str __gmpf_get_str __GMP_DECLSPEC char *mpf_get_str (char *, mp_exp_t *, int, size_t, mpf_srcptr); #define mpf_get_ui __gmpf_get_ui __GMP_DECLSPEC unsigned long mpf_get_ui (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_init __gmpf_init __GMP_DECLSPEC void mpf_init (mpf_ptr); #define mpf_init2 __gmpf_init2 __GMP_DECLSPEC void mpf_init2 (mpf_ptr, mp_bitcnt_t); #define mpf_inits __gmpf_inits __GMP_DECLSPEC void mpf_inits (mpf_ptr, ...); #define mpf_init_set __gmpf_init_set __GMP_DECLSPEC void mpf_init_set (mpf_ptr, mpf_srcptr); #define mpf_init_set_d __gmpf_init_set_d __GMP_DECLSPEC void mpf_init_set_d (mpf_ptr, double); #define mpf_init_set_si __gmpf_init_set_si __GMP_DECLSPEC void mpf_init_set_si (mpf_ptr, signed long int); #define mpf_init_set_str __gmpf_init_set_str __GMP_DECLSPEC int mpf_init_set_str (mpf_ptr, const char *, int); #define mpf_init_set_ui __gmpf_init_set_ui __GMP_DECLSPEC void mpf_init_set_ui (mpf_ptr, unsigned long int); #define mpf_inp_str __gmpf_inp_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpf_inp_str (mpf_ptr, FILE *, int); #endif #define mpf_integer_p __gmpf_integer_p __GMP_DECLSPEC int mpf_integer_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_mul __gmpf_mul __GMP_DECLSPEC void mpf_mul (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_mul_2exp __gmpf_mul_2exp __GMP_DECLSPEC void mpf_mul_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t); #define mpf_mul_ui __gmpf_mul_ui __GMP_DECLSPEC void mpf_mul_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_neg __gmpf_neg __GMP_DECLSPEC void mpf_neg (mpf_ptr, mpf_srcptr); #define mpf_out_str __gmpf_out_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpf_out_str (FILE *, int, size_t, mpf_srcptr); #endif #define mpf_pow_ui __gmpf_pow_ui __GMP_DECLSPEC void mpf_pow_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_random2 __gmpf_random2 __GMP_DECLSPEC void mpf_random2 (mpf_ptr, mp_size_t, mp_exp_t); #define mpf_reldiff __gmpf_reldiff __GMP_DECLSPEC void mpf_reldiff (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_set __gmpf_set __GMP_DECLSPEC void mpf_set (mpf_ptr, mpf_srcptr); #define mpf_set_d __gmpf_set_d __GMP_DECLSPEC void mpf_set_d (mpf_ptr, double); #define mpf_set_default_prec __gmpf_set_default_prec __GMP_DECLSPEC void mpf_set_default_prec (mp_bitcnt_t) __GMP_NOTHROW; #define mpf_set_prec __gmpf_set_prec __GMP_DECLSPEC void mpf_set_prec (mpf_ptr, mp_bitcnt_t); #define mpf_set_prec_raw __gmpf_set_prec_raw __GMP_DECLSPEC void mpf_set_prec_raw (mpf_ptr, mp_bitcnt_t) __GMP_NOTHROW; #define mpf_set_q __gmpf_set_q __GMP_DECLSPEC void mpf_set_q (mpf_ptr, mpq_srcptr); #define mpf_set_si __gmpf_set_si __GMP_DECLSPEC void mpf_set_si (mpf_ptr, signed long int); #define mpf_set_str __gmpf_set_str __GMP_DECLSPEC int mpf_set_str (mpf_ptr, const char *, int); #define mpf_set_ui __gmpf_set_ui __GMP_DECLSPEC void mpf_set_ui (mpf_ptr, unsigned long int); #define mpf_set_z __gmpf_set_z __GMP_DECLSPEC void mpf_set_z (mpf_ptr, mpz_srcptr); #define mpf_size __gmpf_size __GMP_DECLSPEC size_t mpf_size (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_sqrt __gmpf_sqrt __GMP_DECLSPEC void mpf_sqrt (mpf_ptr, mpf_srcptr); #define mpf_sqrt_ui __gmpf_sqrt_ui __GMP_DECLSPEC void mpf_sqrt_ui (mpf_ptr, unsigned long int); #define mpf_sub __gmpf_sub __GMP_DECLSPEC void mpf_sub (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_sub_ui __gmpf_sub_ui __GMP_DECLSPEC void mpf_sub_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_swap __gmpf_swap __GMP_DECLSPEC void mpf_swap (mpf_ptr, mpf_ptr) __GMP_NOTHROW; #define mpf_trunc __gmpf_trunc __GMP_DECLSPEC void mpf_trunc (mpf_ptr, mpf_srcptr); #define mpf_ui_div __gmpf_ui_div __GMP_DECLSPEC void mpf_ui_div (mpf_ptr, unsigned long int, mpf_srcptr); #define mpf_ui_sub __gmpf_ui_sub __GMP_DECLSPEC void mpf_ui_sub (mpf_ptr, unsigned long int, mpf_srcptr); #define mpf_urandomb __gmpf_urandomb __GMP_DECLSPEC void mpf_urandomb (mpf_ptr, gmp_randstate_ptr, mp_bitcnt_t); /************ Low level positive-integer (i.e. N) routines. ************/ /* This is ugly, but we need to make user calls reach the prefixed function. */ #define mpn_add __MPN(add) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_add) __GMP_DECLSPEC mp_limb_t mpn_add (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #endif #define mpn_add_1 __MPN(add_1) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_add_1) __GMP_DECLSPEC mp_limb_t mpn_add_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t) __GMP_NOTHROW; #endif #define mpn_add_n __MPN(add_n) __GMP_DECLSPEC mp_limb_t mpn_add_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_addmul_1 __MPN(addmul_1) __GMP_DECLSPEC mp_limb_t mpn_addmul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_cmp __MPN(cmp) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_cmp) __GMP_DECLSPEC int mpn_cmp (mp_srcptr, mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpn_zero_p __MPN(zero_p) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_zero_p) __GMP_DECLSPEC int mpn_zero_p (mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpn_divexact_1 __MPN(divexact_1) __GMP_DECLSPEC void mpn_divexact_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_divexact_by3(dst,src,size) \ mpn_divexact_by3c (dst, src, size, __GMP_CAST (mp_limb_t, 0)) #define mpn_divexact_by3c __MPN(divexact_by3c) __GMP_DECLSPEC mp_limb_t mpn_divexact_by3c (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_divmod_1(qp,np,nsize,dlimb) \ mpn_divrem_1 (qp, __GMP_CAST (mp_size_t, 0), np, nsize, dlimb) #define mpn_divrem __MPN(divrem) __GMP_DECLSPEC mp_limb_t mpn_divrem (mp_ptr, mp_size_t, mp_ptr, mp_size_t, mp_srcptr, mp_size_t); #define mpn_divrem_1 __MPN(divrem_1) __GMP_DECLSPEC mp_limb_t mpn_divrem_1 (mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_divrem_2 __MPN(divrem_2) __GMP_DECLSPEC mp_limb_t mpn_divrem_2 (mp_ptr, mp_size_t, mp_ptr, mp_size_t, mp_srcptr); #define mpn_div_qr_1 __MPN(div_qr_1) __GMP_DECLSPEC mp_limb_t mpn_div_qr_1 (mp_ptr, mp_limb_t *, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_div_qr_2 __MPN(div_qr_2) __GMP_DECLSPEC mp_limb_t mpn_div_qr_2 (mp_ptr, mp_ptr, mp_srcptr, mp_size_t, mp_srcptr); #define mpn_gcd __MPN(gcd) __GMP_DECLSPEC mp_size_t mpn_gcd (mp_ptr, mp_ptr, mp_size_t, mp_ptr, mp_size_t); #define mpn_gcd_11 __MPN(gcd_11) __GMP_DECLSPEC mp_limb_t mpn_gcd_11 (mp_limb_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_gcd_1 __MPN(gcd_1) __GMP_DECLSPEC mp_limb_t mpn_gcd_1 (mp_srcptr, mp_size_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_gcdext_1 __MPN(gcdext_1) __GMP_DECLSPEC mp_limb_t mpn_gcdext_1 (mp_limb_signed_t *, mp_limb_signed_t *, mp_limb_t, mp_limb_t); #define mpn_gcdext __MPN(gcdext) __GMP_DECLSPEC mp_size_t mpn_gcdext (mp_ptr, mp_ptr, mp_size_t *, mp_ptr, mp_size_t, mp_ptr, mp_size_t); #define mpn_get_str __MPN(get_str) __GMP_DECLSPEC size_t mpn_get_str (unsigned char *, int, mp_ptr, mp_size_t); #define mpn_hamdist __MPN(hamdist) __GMP_DECLSPEC mp_bitcnt_t mpn_hamdist (mp_srcptr, mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpn_lshift __MPN(lshift) __GMP_DECLSPEC mp_limb_t mpn_lshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int); #define mpn_mod_1 __MPN(mod_1) __GMP_DECLSPEC mp_limb_t mpn_mod_1 (mp_srcptr, mp_size_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_mul __MPN(mul) __GMP_DECLSPEC mp_limb_t mpn_mul (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #define mpn_mul_1 __MPN(mul_1) __GMP_DECLSPEC mp_limb_t mpn_mul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_mul_n __MPN(mul_n) __GMP_DECLSPEC void mpn_mul_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_sqr __MPN(sqr) __GMP_DECLSPEC void mpn_sqr (mp_ptr, mp_srcptr, mp_size_t); #define mpn_neg __MPN(neg) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_neg) __GMP_DECLSPEC mp_limb_t mpn_neg (mp_ptr, mp_srcptr, mp_size_t); #endif #define mpn_com __MPN(com) __GMP_DECLSPEC void mpn_com (mp_ptr, mp_srcptr, mp_size_t); #define mpn_perfect_square_p __MPN(perfect_square_p) __GMP_DECLSPEC int mpn_perfect_square_p (mp_srcptr, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_perfect_power_p __MPN(perfect_power_p) __GMP_DECLSPEC int mpn_perfect_power_p (mp_srcptr, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_popcount __MPN(popcount) __GMP_DECLSPEC mp_bitcnt_t mpn_popcount (mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpn_pow_1 __MPN(pow_1) __GMP_DECLSPEC mp_size_t mpn_pow_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr); /* undocumented now, but retained here for upward compatibility */ #define mpn_preinv_mod_1 __MPN(preinv_mod_1) __GMP_DECLSPEC mp_limb_t mpn_preinv_mod_1 (mp_srcptr, mp_size_t, mp_limb_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_random __MPN(random) __GMP_DECLSPEC void mpn_random (mp_ptr, mp_size_t); #define mpn_random2 __MPN(random2) __GMP_DECLSPEC void mpn_random2 (mp_ptr, mp_size_t); #define mpn_rshift __MPN(rshift) __GMP_DECLSPEC mp_limb_t mpn_rshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int); #define mpn_scan0 __MPN(scan0) __GMP_DECLSPEC mp_bitcnt_t mpn_scan0 (mp_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE; #define mpn_scan1 __MPN(scan1) __GMP_DECLSPEC mp_bitcnt_t mpn_scan1 (mp_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE; #define mpn_set_str __MPN(set_str) __GMP_DECLSPEC mp_size_t mpn_set_str (mp_ptr, const unsigned char *, size_t, int); #define mpn_sizeinbase __MPN(sizeinbase) __GMP_DECLSPEC size_t mpn_sizeinbase (mp_srcptr, mp_size_t, int); #define mpn_sqrtrem __MPN(sqrtrem) __GMP_DECLSPEC mp_size_t mpn_sqrtrem (mp_ptr, mp_ptr, mp_srcptr, mp_size_t); #define mpn_sub __MPN(sub) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_sub) __GMP_DECLSPEC mp_limb_t mpn_sub (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #endif #define mpn_sub_1 __MPN(sub_1) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_sub_1) __GMP_DECLSPEC mp_limb_t mpn_sub_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t) __GMP_NOTHROW; #endif #define mpn_sub_n __MPN(sub_n) __GMP_DECLSPEC mp_limb_t mpn_sub_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_submul_1 __MPN(submul_1) __GMP_DECLSPEC mp_limb_t mpn_submul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_tdiv_qr __MPN(tdiv_qr) __GMP_DECLSPEC void mpn_tdiv_qr (mp_ptr, mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #define mpn_and_n __MPN(and_n) __GMP_DECLSPEC void mpn_and_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_andn_n __MPN(andn_n) __GMP_DECLSPEC void mpn_andn_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_nand_n __MPN(nand_n) __GMP_DECLSPEC void mpn_nand_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_ior_n __MPN(ior_n) __GMP_DECLSPEC void mpn_ior_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_iorn_n __MPN(iorn_n) __GMP_DECLSPEC void mpn_iorn_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_nior_n __MPN(nior_n) __GMP_DECLSPEC void mpn_nior_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_xor_n __MPN(xor_n) __GMP_DECLSPEC void mpn_xor_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_xnor_n __MPN(xnor_n) __GMP_DECLSPEC void mpn_xnor_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_copyi __MPN(copyi) __GMP_DECLSPEC void mpn_copyi (mp_ptr, mp_srcptr, mp_size_t); #define mpn_copyd __MPN(copyd) __GMP_DECLSPEC void mpn_copyd (mp_ptr, mp_srcptr, mp_size_t); #define mpn_zero __MPN(zero) __GMP_DECLSPEC void mpn_zero (mp_ptr, mp_size_t); #define mpn_cnd_add_n __MPN(cnd_add_n) __GMP_DECLSPEC mp_limb_t mpn_cnd_add_n (mp_limb_t, mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_cnd_sub_n __MPN(cnd_sub_n) __GMP_DECLSPEC mp_limb_t mpn_cnd_sub_n (mp_limb_t, mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_sec_add_1 __MPN(sec_add_1) __GMP_DECLSPEC mp_limb_t mpn_sec_add_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr); #define mpn_sec_add_1_itch __MPN(sec_add_1_itch) __GMP_DECLSPEC mp_size_t mpn_sec_add_1_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_sub_1 __MPN(sec_sub_1) __GMP_DECLSPEC mp_limb_t mpn_sec_sub_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr); #define mpn_sec_sub_1_itch __MPN(sec_sub_1_itch) __GMP_DECLSPEC mp_size_t mpn_sec_sub_1_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_cnd_swap __MPN(cnd_swap) __GMP_DECLSPEC void mpn_cnd_swap (mp_limb_t, volatile mp_limb_t *, volatile mp_limb_t *, mp_size_t); #define mpn_sec_mul __MPN(sec_mul) __GMP_DECLSPEC void mpn_sec_mul (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_mul_itch __MPN(sec_mul_itch) __GMP_DECLSPEC mp_size_t mpn_sec_mul_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_sqr __MPN(sec_sqr) __GMP_DECLSPEC void mpn_sec_sqr (mp_ptr, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_sqr_itch __MPN(sec_sqr_itch) __GMP_DECLSPEC mp_size_t mpn_sec_sqr_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_powm __MPN(sec_powm) __GMP_DECLSPEC void mpn_sec_powm (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_bitcnt_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_powm_itch __MPN(sec_powm_itch) __GMP_DECLSPEC mp_size_t mpn_sec_powm_itch (mp_size_t, mp_bitcnt_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_tabselect __MPN(sec_tabselect) __GMP_DECLSPEC void mpn_sec_tabselect (volatile mp_limb_t *, volatile const mp_limb_t *, mp_size_t, mp_size_t, mp_size_t); #define mpn_sec_div_qr __MPN(sec_div_qr) __GMP_DECLSPEC mp_limb_t mpn_sec_div_qr (mp_ptr, mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_div_qr_itch __MPN(sec_div_qr_itch) __GMP_DECLSPEC mp_size_t mpn_sec_div_qr_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_div_r __MPN(sec_div_r) __GMP_DECLSPEC void mpn_sec_div_r (mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_div_r_itch __MPN(sec_div_r_itch) __GMP_DECLSPEC mp_size_t mpn_sec_div_r_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_invert __MPN(sec_invert) __GMP_DECLSPEC int mpn_sec_invert (mp_ptr, mp_ptr, mp_srcptr, mp_size_t, mp_bitcnt_t, mp_ptr); #define mpn_sec_invert_itch __MPN(sec_invert_itch) __GMP_DECLSPEC mp_size_t mpn_sec_invert_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; /**************** mpz inlines ****************/ /* The following are provided as inlines where possible, but always exist as library functions too, for binary compatibility. Within gmp itself this inlining generally isn't relied on, since it doesn't get done for all compilers, whereas if something is worth inlining then it's worth arranging always. There are two styles of inlining here. When the same bit of code is wanted for the inline as for the library version, then __GMP_FORCE_foo arranges for that code to be emitted and the __GMP_EXTERN_INLINE directive suppressed, eg. mpz_fits_uint_p. When a different bit of code is wanted for the inline than for the library version, then __GMP_FORCE_foo arranges the inline to be suppressed, eg. mpz_abs. */ #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpz_abs) __GMP_EXTERN_INLINE void mpz_abs (mpz_ptr __gmp_w, mpz_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpz_set (__gmp_w, __gmp_u); __gmp_w->_mp_size = __GMP_ABS (__gmp_w->_mp_size); } #endif #if GMP_NAIL_BITS == 0 #define __GMPZ_FITS_UTYPE_P(z,maxval) \ mp_size_t __gmp_n = z->_mp_size; \ mp_ptr __gmp_p = z->_mp_d; \ return (__gmp_n == 0 || (__gmp_n == 1 && __gmp_p[0] <= maxval)); #else #define __GMPZ_FITS_UTYPE_P(z,maxval) \ mp_size_t __gmp_n = z->_mp_size; \ mp_ptr __gmp_p = z->_mp_d; \ return (__gmp_n == 0 || (__gmp_n == 1 && __gmp_p[0] <= maxval) \ || (__gmp_n == 2 && __gmp_p[1] <= ((mp_limb_t) maxval >> GMP_NUMB_BITS))); #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_uint_p) #if ! defined (__GMP_FORCE_mpz_fits_uint_p) __GMP_EXTERN_INLINE #endif int mpz_fits_uint_p (mpz_srcptr __gmp_z) __GMP_NOTHROW { __GMPZ_FITS_UTYPE_P (__gmp_z, UINT_MAX); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_ulong_p) #if ! defined (__GMP_FORCE_mpz_fits_ulong_p) __GMP_EXTERN_INLINE #endif int mpz_fits_ulong_p (mpz_srcptr __gmp_z) __GMP_NOTHROW { __GMPZ_FITS_UTYPE_P (__gmp_z, ULONG_MAX); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_ushort_p) #if ! defined (__GMP_FORCE_mpz_fits_ushort_p) __GMP_EXTERN_INLINE #endif int mpz_fits_ushort_p (mpz_srcptr __gmp_z) __GMP_NOTHROW { __GMPZ_FITS_UTYPE_P (__gmp_z, USHRT_MAX); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_get_ui) #if ! defined (__GMP_FORCE_mpz_get_ui) __GMP_EXTERN_INLINE #endif unsigned long mpz_get_ui (mpz_srcptr __gmp_z) __GMP_NOTHROW { mp_ptr __gmp_p = __gmp_z->_mp_d; mp_size_t __gmp_n = __gmp_z->_mp_size; mp_limb_t __gmp_l = __gmp_p[0]; /* This is a "#if" rather than a plain "if" so as to avoid gcc warnings about "<< GMP_NUMB_BITS" exceeding the type size, and to avoid Borland C++ 6.0 warnings about condition always true for something like "ULONG_MAX < GMP_NUMB_MASK". */ #if GMP_NAIL_BITS == 0 || defined (_LONG_LONG_LIMB) /* limb==long and no nails, or limb==longlong, one limb is enough */ return (__gmp_n != 0 ? __gmp_l : 0); #else /* limb==long and nails, need two limbs when available */ __gmp_n = __GMP_ABS (__gmp_n); if (__gmp_n <= 1) return (__gmp_n != 0 ? __gmp_l : 0); else return __gmp_l + (__gmp_p[1] << GMP_NUMB_BITS); #endif } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_getlimbn) #if ! defined (__GMP_FORCE_mpz_getlimbn) __GMP_EXTERN_INLINE #endif mp_limb_t mpz_getlimbn (mpz_srcptr __gmp_z, mp_size_t __gmp_n) __GMP_NOTHROW { mp_limb_t __gmp_result = 0; if (__GMP_LIKELY (__gmp_n >= 0 && __gmp_n < __GMP_ABS (__gmp_z->_mp_size))) __gmp_result = __gmp_z->_mp_d[__gmp_n]; return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpz_neg) __GMP_EXTERN_INLINE void mpz_neg (mpz_ptr __gmp_w, mpz_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpz_set (__gmp_w, __gmp_u); __gmp_w->_mp_size = - __gmp_w->_mp_size; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_perfect_square_p) #if ! defined (__GMP_FORCE_mpz_perfect_square_p) __GMP_EXTERN_INLINE #endif int mpz_perfect_square_p (mpz_srcptr __gmp_a) { mp_size_t __gmp_asize; int __gmp_result; __gmp_asize = __gmp_a->_mp_size; __gmp_result = (__gmp_asize >= 0); /* zero is a square, negatives are not */ if (__GMP_LIKELY (__gmp_asize > 0)) __gmp_result = mpn_perfect_square_p (__gmp_a->_mp_d, __gmp_asize); return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_popcount) #if ! defined (__GMP_FORCE_mpz_popcount) __GMP_EXTERN_INLINE #endif mp_bitcnt_t mpz_popcount (mpz_srcptr __gmp_u) __GMP_NOTHROW { mp_size_t __gmp_usize; mp_bitcnt_t __gmp_result; __gmp_usize = __gmp_u->_mp_size; __gmp_result = (__gmp_usize < 0 ? ~ __GMP_CAST (mp_bitcnt_t, 0) : __GMP_CAST (mp_bitcnt_t, 0)); if (__GMP_LIKELY (__gmp_usize > 0)) __gmp_result = mpn_popcount (__gmp_u->_mp_d, __gmp_usize); return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_set_q) #if ! defined (__GMP_FORCE_mpz_set_q) __GMP_EXTERN_INLINE #endif void mpz_set_q (mpz_ptr __gmp_w, mpq_srcptr __gmp_u) { mpz_tdiv_q (__gmp_w, mpq_numref (__gmp_u), mpq_denref (__gmp_u)); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_size) #if ! defined (__GMP_FORCE_mpz_size) __GMP_EXTERN_INLINE #endif size_t mpz_size (mpz_srcptr __gmp_z) __GMP_NOTHROW { return __GMP_ABS (__gmp_z->_mp_size); } #endif /**************** mpq inlines ****************/ #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpq_abs) __GMP_EXTERN_INLINE void mpq_abs (mpq_ptr __gmp_w, mpq_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpq_set (__gmp_w, __gmp_u); __gmp_w->_mp_num._mp_size = __GMP_ABS (__gmp_w->_mp_num._mp_size); } #endif #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpq_neg) __GMP_EXTERN_INLINE void mpq_neg (mpq_ptr __gmp_w, mpq_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpq_set (__gmp_w, __gmp_u); __gmp_w->_mp_num._mp_size = - __gmp_w->_mp_num._mp_size; } #endif /**************** mpn inlines ****************/ /* The comments with __GMPN_ADD_1 below apply here too. The test for FUNCTION returning 0 should predict well. If it's assumed {yp,ysize} will usually have a random number of bits then the high limb won't be full and a carry out will occur a good deal less than 50% of the time. ysize==0 isn't a documented feature, but is used internally in a few places. Producing cout last stops it using up a register during the main part of the calculation, though gcc (as of 3.0) on an "if (mpn_add (...))" doesn't seem able to move the true and false legs of the conditional up to the two places cout is generated. */ #define __GMPN_AORS(cout, wp, xp, xsize, yp, ysize, FUNCTION, TEST) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x; \ \ /* ASSERT ((ysize) >= 0); */ \ /* ASSERT ((xsize) >= (ysize)); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE2_P (wp, xsize, xp, xsize)); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE2_P (wp, xsize, yp, ysize)); */ \ \ __gmp_i = (ysize); \ if (__gmp_i != 0) \ { \ if (FUNCTION (wp, xp, yp, __gmp_i)) \ { \ do \ { \ if (__gmp_i >= (xsize)) \ { \ (cout) = 1; \ goto __gmp_done; \ } \ __gmp_x = (xp)[__gmp_i]; \ } \ while (TEST); \ } \ } \ if ((wp) != (xp)) \ __GMPN_COPY_REST (wp, xp, xsize, __gmp_i); \ (cout) = 0; \ __gmp_done: \ ; \ } while (0) #define __GMPN_ADD(cout, wp, xp, xsize, yp, ysize) \ __GMPN_AORS (cout, wp, xp, xsize, yp, ysize, mpn_add_n, \ (((wp)[__gmp_i++] = (__gmp_x + 1) & GMP_NUMB_MASK) == 0)) #define __GMPN_SUB(cout, wp, xp, xsize, yp, ysize) \ __GMPN_AORS (cout, wp, xp, xsize, yp, ysize, mpn_sub_n, \ (((wp)[__gmp_i++] = (__gmp_x - 1) & GMP_NUMB_MASK), __gmp_x == 0)) /* The use of __gmp_i indexing is designed to ensure a compile time src==dst remains nice and clear to the compiler, so that __GMPN_COPY_REST can disappear, and the load/add/store gets a chance to become a read-modify-write on CISC CPUs. Alternatives: Using a pair of pointers instead of indexing would be possible, but gcc isn't able to recognise compile-time src==dst in that case, even when the pointers are incremented more or less together. Other compilers would very likely have similar difficulty. gcc could use "if (__builtin_constant_p(src==dst) && src==dst)" or similar to detect a compile-time src==dst. This works nicely on gcc 2.95.x, it's not good on gcc 3.0 where __builtin_constant_p(p==p) seems to be always false, for a pointer p. But the current code form seems good enough for src==dst anyway. gcc on x86 as usual doesn't give particularly good flags handling for the carry/borrow detection. It's tempting to want some multi instruction asm blocks to help it, and this was tried, but in truth there's only a few instructions to save and any gain is all too easily lost by register juggling setting up for the asm. */ #if GMP_NAIL_BITS == 0 #define __GMPN_AORS_1(cout, dst, src, n, v, OP, CB) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x, __gmp_r; \ \ /* ASSERT ((n) >= 1); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, n)); */ \ \ __gmp_x = (src)[0]; \ __gmp_r = __gmp_x OP (v); \ (dst)[0] = __gmp_r; \ if (CB (__gmp_r, __gmp_x, (v))) \ { \ (cout) = 1; \ for (__gmp_i = 1; __gmp_i < (n);) \ { \ __gmp_x = (src)[__gmp_i]; \ __gmp_r = __gmp_x OP 1; \ (dst)[__gmp_i] = __gmp_r; \ ++__gmp_i; \ if (!CB (__gmp_r, __gmp_x, 1)) \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, __gmp_i); \ (cout) = 0; \ break; \ } \ } \ } \ else \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, 1); \ (cout) = 0; \ } \ } while (0) #endif #if GMP_NAIL_BITS >= 1 #define __GMPN_AORS_1(cout, dst, src, n, v, OP, CB) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x, __gmp_r; \ \ /* ASSERT ((n) >= 1); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, n)); */ \ \ __gmp_x = (src)[0]; \ __gmp_r = __gmp_x OP (v); \ (dst)[0] = __gmp_r & GMP_NUMB_MASK; \ if (__gmp_r >> GMP_NUMB_BITS != 0) \ { \ (cout) = 1; \ for (__gmp_i = 1; __gmp_i < (n);) \ { \ __gmp_x = (src)[__gmp_i]; \ __gmp_r = __gmp_x OP 1; \ (dst)[__gmp_i] = __gmp_r & GMP_NUMB_MASK; \ ++__gmp_i; \ if (__gmp_r >> GMP_NUMB_BITS == 0) \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, __gmp_i); \ (cout) = 0; \ break; \ } \ } \ } \ else \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, 1); \ (cout) = 0; \ } \ } while (0) #endif #define __GMPN_ADDCB(r,x,y) ((r) < (y)) #define __GMPN_SUBCB(r,x,y) ((x) < (y)) #define __GMPN_ADD_1(cout, dst, src, n, v) \ __GMPN_AORS_1(cout, dst, src, n, v, +, __GMPN_ADDCB) #define __GMPN_SUB_1(cout, dst, src, n, v) \ __GMPN_AORS_1(cout, dst, src, n, v, -, __GMPN_SUBCB) /* Compare {xp,size} and {yp,size}, setting "result" to positive, zero or negative. size==0 is allowed. On random data usually only one limb will need to be examined to get a result, so it's worth having it inline. */ #define __GMPN_CMP(result, xp, yp, size) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x, __gmp_y; \ \ /* ASSERT ((size) >= 0); */ \ \ (result) = 0; \ __gmp_i = (size); \ while (--__gmp_i >= 0) \ { \ __gmp_x = (xp)[__gmp_i]; \ __gmp_y = (yp)[__gmp_i]; \ if (__gmp_x != __gmp_y) \ { \ /* Cannot use __gmp_x - __gmp_y, may overflow an "int" */ \ (result) = (__gmp_x > __gmp_y ? 1 : -1); \ break; \ } \ } \ } while (0) #if defined (__GMPN_COPY) && ! defined (__GMPN_COPY_REST) #define __GMPN_COPY_REST(dst, src, size, start) \ do { \ /* ASSERT ((start) >= 0); */ \ /* ASSERT ((start) <= (size)); */ \ __GMPN_COPY ((dst)+(start), (src)+(start), (size)-(start)); \ } while (0) #endif /* Copy {src,size} to {dst,size}, starting at "start". This is designed to keep the indexing dst[j] and src[j] nice and simple for __GMPN_ADD_1, __GMPN_ADD, etc. */ #if ! defined (__GMPN_COPY_REST) #define __GMPN_COPY_REST(dst, src, size, start) \ do { \ mp_size_t __gmp_j; \ /* ASSERT ((size) >= 0); */ \ /* ASSERT ((start) >= 0); */ \ /* ASSERT ((start) <= (size)); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, size)); */ \ __GMP_CRAY_Pragma ("_CRI ivdep"); \ for (__gmp_j = (start); __gmp_j < (size); __gmp_j++) \ (dst)[__gmp_j] = (src)[__gmp_j]; \ } while (0) #endif /* Enhancement: Use some of the smarter code from gmp-impl.h. Maybe use mpn_copyi if there's a native version, and if we don't mind demanding binary compatibility for it (on targets which use it). */ #if ! defined (__GMPN_COPY) #define __GMPN_COPY(dst, src, size) __GMPN_COPY_REST (dst, src, size, 0) #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_add) #if ! defined (__GMP_FORCE_mpn_add) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_add (mp_ptr __gmp_wp, mp_srcptr __gmp_xp, mp_size_t __gmp_xsize, mp_srcptr __gmp_yp, mp_size_t __gmp_ysize) { mp_limb_t __gmp_c; __GMPN_ADD (__gmp_c, __gmp_wp, __gmp_xp, __gmp_xsize, __gmp_yp, __gmp_ysize); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_add_1) #if ! defined (__GMP_FORCE_mpn_add_1) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_add_1 (mp_ptr __gmp_dst, mp_srcptr __gmp_src, mp_size_t __gmp_size, mp_limb_t __gmp_n) __GMP_NOTHROW { mp_limb_t __gmp_c; __GMPN_ADD_1 (__gmp_c, __gmp_dst, __gmp_src, __gmp_size, __gmp_n); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_cmp) #if ! defined (__GMP_FORCE_mpn_cmp) __GMP_EXTERN_INLINE #endif int mpn_cmp (mp_srcptr __gmp_xp, mp_srcptr __gmp_yp, mp_size_t __gmp_size) __GMP_NOTHROW { int __gmp_result; __GMPN_CMP (__gmp_result, __gmp_xp, __gmp_yp, __gmp_size); return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_zero_p) #if ! defined (__GMP_FORCE_mpn_zero_p) __GMP_EXTERN_INLINE #endif int mpn_zero_p (mp_srcptr __gmp_p, mp_size_t __gmp_n) __GMP_NOTHROW { /* if (__GMP_LIKELY (__gmp_n > 0)) */ do { if (__gmp_p[--__gmp_n] != 0) return 0; } while (__gmp_n != 0); return 1; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_sub) #if ! defined (__GMP_FORCE_mpn_sub) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_sub (mp_ptr __gmp_wp, mp_srcptr __gmp_xp, mp_size_t __gmp_xsize, mp_srcptr __gmp_yp, mp_size_t __gmp_ysize) { mp_limb_t __gmp_c; __GMPN_SUB (__gmp_c, __gmp_wp, __gmp_xp, __gmp_xsize, __gmp_yp, __gmp_ysize); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_sub_1) #if ! defined (__GMP_FORCE_mpn_sub_1) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_sub_1 (mp_ptr __gmp_dst, mp_srcptr __gmp_src, mp_size_t __gmp_size, mp_limb_t __gmp_n) __GMP_NOTHROW { mp_limb_t __gmp_c; __GMPN_SUB_1 (__gmp_c, __gmp_dst, __gmp_src, __gmp_size, __gmp_n); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_neg) #if ! defined (__GMP_FORCE_mpn_neg) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_neg (mp_ptr __gmp_rp, mp_srcptr __gmp_up, mp_size_t __gmp_n) { while (*__gmp_up == 0) /* Low zero limbs are unchanged by negation. */ { *__gmp_rp = 0; if (!--__gmp_n) /* All zero */ return 0; ++__gmp_up; ++__gmp_rp; } *__gmp_rp = (- *__gmp_up) & GMP_NUMB_MASK; if (--__gmp_n) /* Higher limbs get complemented. */ mpn_com (++__gmp_rp, ++__gmp_up, __gmp_n); return 1; } #endif #if defined (__cplusplus) } #endif /* Allow faster testing for negative, zero, and positive. */ #define mpz_sgn(Z) ((Z)->_mp_size < 0 ? -1 : (Z)->_mp_size > 0) #define mpf_sgn(F) ((F)->_mp_size < 0 ? -1 : (F)->_mp_size > 0) #define mpq_sgn(Q) ((Q)->_mp_num._mp_size < 0 ? -1 : (Q)->_mp_num._mp_size > 0) /* When using GCC, optimize certain common comparisons. */ #if defined (__GNUC__) && __GNUC__ >= 2 #define mpz_cmp_ui(Z,UI) \ (__builtin_constant_p (UI) && (UI) == 0 \ ? mpz_sgn (Z) : _mpz_cmp_ui (Z,UI)) #define mpz_cmp_si(Z,SI) \ (__builtin_constant_p ((SI) >= 0) && (SI) >= 0 \ ? mpz_cmp_ui (Z, __GMP_CAST (unsigned long, SI)) \ : _mpz_cmp_si (Z,SI)) #define mpq_cmp_ui(Q,NUI,DUI) \ (__builtin_constant_p (NUI) && (NUI) == 0 ? mpq_sgn (Q) \ : __builtin_constant_p ((NUI) == (DUI)) && (NUI) == (DUI) \ ? mpz_cmp (mpq_numref (Q), mpq_denref (Q)) \ : _mpq_cmp_ui (Q,NUI,DUI)) #define mpq_cmp_si(q,n,d) \ (__builtin_constant_p ((n) >= 0) && (n) >= 0 \ ? mpq_cmp_ui (q, __GMP_CAST (unsigned long, n), d) \ : _mpq_cmp_si (q, n, d)) #else #define mpz_cmp_ui(Z,UI) _mpz_cmp_ui (Z,UI) #define mpz_cmp_si(Z,UI) _mpz_cmp_si (Z,UI) #define mpq_cmp_ui(Q,NUI,DUI) _mpq_cmp_ui (Q,NUI,DUI) #define mpq_cmp_si(q,n,d) _mpq_cmp_si(q,n,d) #endif /* Using "&" rather than "&&" means these can come out branch-free. Every mpz_t has at least one limb allocated, so fetching the low limb is always allowed. */ #define mpz_odd_p(z) (((z)->_mp_size != 0) & __GMP_CAST (int, (z)->_mp_d[0])) #define mpz_even_p(z) (! mpz_odd_p (z)) /**************** C++ routines ****************/ #ifdef __cplusplus __GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpz_srcptr); __GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpq_srcptr); __GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpf_srcptr); __GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpz_ptr); __GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpq_ptr); __GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpf_ptr); #endif /* Source-level compatibility with GMP 2 and earlier. */ #define mpn_divmod(qp,np,nsize,dp,dsize) \ mpn_divrem (qp, __GMP_CAST (mp_size_t, 0), np, nsize, dp, dsize) /* Source-level compatibility with GMP 1. */ #define mpz_mdiv mpz_fdiv_q #define mpz_mdivmod mpz_fdiv_qr #define mpz_mmod mpz_fdiv_r #define mpz_mdiv_ui mpz_fdiv_q_ui #define mpz_mdivmod_ui(q,r,n,d) \ (((r) == 0) ? mpz_fdiv_q_ui (q,n,d) : mpz_fdiv_qr_ui (q,r,n,d)) #define mpz_mmod_ui(r,n,d) \ (((r) == 0) ? mpz_fdiv_ui (n,d) : mpz_fdiv_r_ui (r,n,d)) /* Useful synonyms, but not quite compatible with GMP 1. */ #define mpz_div mpz_fdiv_q #define mpz_divmod mpz_fdiv_qr #define mpz_div_ui mpz_fdiv_q_ui #define mpz_divmod_ui mpz_fdiv_qr_ui #define mpz_div_2exp mpz_fdiv_q_2exp #define mpz_mod_2exp mpz_fdiv_r_2exp enum { GMP_ERROR_NONE = 0, GMP_ERROR_UNSUPPORTED_ARGUMENT = 1, GMP_ERROR_DIVISION_BY_ZERO = 2, GMP_ERROR_SQRT_OF_NEGATIVE = 4, GMP_ERROR_INVALID_ARGUMENT = 8, GMP_ERROR_MPZ_OVERFLOW = 16 }; /* Define CC and CFLAGS which were used to build this version of GMP */ #define __GMP_CC "gcc" #define __GMP_CFLAGS "-m32 -O2 -pedantic -fomit-frame-pointer -mtune=pentiumpro -march=pentiumpro" /* Major version number is the value of __GNU_MP__ too, above. */ #define __GNU_MP_VERSION 6 #define __GNU_MP_VERSION_MINOR 3 #define __GNU_MP_VERSION_PATCHLEVEL 0 #define __GNU_MP_RELEASE (__GNU_MP_VERSION * 10000 + __GNU_MP_VERSION_MINOR * 100 + __GNU_MP_VERSION_PATCHLEVEL) #define __GMP_H__ #endif /* __GMP_H__ */ ================================================ FILE: thirdparty/32/include/gnutls/abstract.h ================================================ /* * Copyright (C) 2010-2012 Free Software Foundation, Inc. * Copyright (C) 2015-2017 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_ABSTRACT_H #define GNUTLS_ABSTRACT_H #include #include #include #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* Public key operations */ #define GNUTLS_PUBKEY_VERIFY_FLAG_TLS_RSA GNUTLS_PUBKEY_VERIFY_FLAG_TLS1_RSA /** * gnutls_pubkey_flags: * @GNUTLS_PUBKEY_DISABLE_CALLBACKS: The following flag disables call to PIN callbacks. Only * relevant to TPM keys. * @GNUTLS_PUBKEY_GET_OPENPGP_FINGERPRINT: request an OPENPGP fingerprint instead of the default. * * Enumeration of different certificate import flags. */ typedef enum gnutls_pubkey_flags { GNUTLS_PUBKEY_DISABLE_CALLBACKS = 1 << 2, GNUTLS_PUBKEY_GET_OPENPGP_FINGERPRINT = 1 << 3 } gnutls_pubkey_flags_t; /** * gnutls_abstract_export_flags: * @GNUTLS_EXPORT_FLAG_NO_LZ: do not prepend a leading zero to exported values * * Enumeration of different certificate import flags. */ typedef enum gnutls_abstract_export_flags { GNUTLS_EXPORT_FLAG_NO_LZ = 1 } gnutls_abstract_export_flags_t; #define GNUTLS_PUBKEY_VERIFY_FLAG_TLS1_RSA GNUTLS_VERIFY_USE_TLS1_RSA typedef int (*gnutls_privkey_sign_func) (gnutls_privkey_t key, void *userdata, const gnutls_datum_t *raw_data, gnutls_datum_t * signature); typedef int (*gnutls_privkey_decrypt_func) (gnutls_privkey_t key, void *userdata, const gnutls_datum_t *ciphertext, gnutls_datum_t * plaintext); typedef int (*gnutls_privkey_decrypt_func2) (gnutls_privkey_t key, void *userdata, const gnutls_datum_t *ciphertext, unsigned char * plaintext, size_t plaintext_size); /* to be called to sign pre-hashed data. The input will be * the output of the hash (such as SHA256) corresponding to * the signature algorithm. The algorithm GNUTLS_SIGN_RSA_RAW * will be provided when RSA PKCS#1 DigestInfo structure is provided * as data (when this is called from a TLS 1.0 or 1.1 session). */ typedef int (*gnutls_privkey_sign_hash_func) (gnutls_privkey_t key, gnutls_sign_algorithm_t algo, void *userdata, unsigned int flags, const gnutls_datum_t *hash, gnutls_datum_t * signature); /* to be called to sign data. The input data will be * the data to be signed (and hashed), with the provided * signature algorithm. This function is used for algorithms * like ed25519 which cannot take pre-hashed data as input. */ typedef int (*gnutls_privkey_sign_data_func) (gnutls_privkey_t key, gnutls_sign_algorithm_t algo, void *userdata, unsigned int flags, const gnutls_datum_t *data, gnutls_datum_t * signature); typedef void (*gnutls_privkey_deinit_func) (gnutls_privkey_t key, void *userdata); #define GNUTLS_SIGN_ALGO_TO_FLAGS(sig) (unsigned int)((sig)<<20) #define GNUTLS_FLAGS_TO_SIGN_ALGO(flags) (unsigned int)((flags)>>20) /* Should return the public key algorithm (gnutls_pk_algorithm_t) */ #define GNUTLS_PRIVKEY_INFO_PK_ALGO 1 /* Should return the preferred signature algorithm (gnutls_sign_algorithm_t) or 0. */ #define GNUTLS_PRIVKEY_INFO_SIGN_ALGO (1<<1) /* Should return true (1) or false (0) if the provided sign algorithm * (obtained with GNUTLS_FLAGS_TO_SIGN_ALGO) is supported. */ #define GNUTLS_PRIVKEY_INFO_HAVE_SIGN_ALGO (1<<2) /* Should return the number of bits of the public key algorithm (required for RSA-PSS) * It is the value that should be returned by gnutls_pubkey_get_pk_algorithm() */ #define GNUTLS_PRIVKEY_INFO_PK_ALGO_BITS (1<<3) /* returns information on the public key associated with userdata */ typedef int (*gnutls_privkey_info_func) (gnutls_privkey_t key, unsigned int flags, void *userdata); int gnutls_pubkey_init(gnutls_pubkey_t * key); void gnutls_pubkey_deinit(gnutls_pubkey_t key); int gnutls_pubkey_verify_params(gnutls_pubkey_t key); void gnutls_pubkey_set_pin_function(gnutls_pubkey_t key, gnutls_pin_callback_t fn, void *userdata); int gnutls_pubkey_get_pk_algorithm(gnutls_pubkey_t key, unsigned int *bits); int gnutls_pubkey_set_spki(gnutls_pubkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_pubkey_get_spki(gnutls_pubkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_pubkey_import_x509(gnutls_pubkey_t key, gnutls_x509_crt_t crt, unsigned int flags); int gnutls_pubkey_import_x509_crq(gnutls_pubkey_t key, gnutls_x509_crq_t crq, unsigned int flags); int gnutls_pubkey_import_pkcs11(gnutls_pubkey_t key, gnutls_pkcs11_obj_t obj, unsigned int flags); int gnutls_pubkey_import_openpgp(gnutls_pubkey_t key, gnutls_openpgp_crt_t crt, unsigned int flags); int gnutls_pubkey_import_openpgp_raw(gnutls_pubkey_t pkey, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format, const gnutls_openpgp_keyid_t keyid, unsigned int flags); int gnutls_pubkey_import_x509_raw(gnutls_pubkey_t pkey, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pubkey_import_privkey(gnutls_pubkey_t key, gnutls_privkey_t pkey, unsigned int usage, unsigned int flags); int gnutls_pubkey_import_tpm_url(gnutls_pubkey_t pkey, const char *url, const char *srk_password, unsigned int flags); int gnutls_pubkey_import_url(gnutls_pubkey_t key, const char *url, unsigned int flags); int gnutls_pubkey_import_tpm_raw(gnutls_pubkey_t pkey, const gnutls_datum_t * fdata, gnutls_tpmkey_fmt_t format, const char *srk_password, unsigned int flags); int gnutls_pubkey_get_preferred_hash_algorithm(gnutls_pubkey_t key, gnutls_digest_algorithm_t * hash, unsigned int *mand); #define gnutls_pubkey_get_pk_rsa_raw gnutls_pubkey_export_rsa_raw int gnutls_pubkey_export_rsa_raw(gnutls_pubkey_t key, gnutls_datum_t * m, gnutls_datum_t * e); int gnutls_pubkey_export_rsa_raw2(gnutls_pubkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, unsigned flags); #define gnutls_pubkey_get_pk_dsa_raw gnutls_pubkey_export_dsa_raw int gnutls_pubkey_export_dsa_raw(gnutls_pubkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y); int gnutls_pubkey_export_dsa_raw2(gnutls_pubkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, unsigned flags); int gnutls_pubkey_export_ecc_raw2(gnutls_pubkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, unsigned flags); int gnutls_pubkey_export_gost_raw2(gnutls_pubkey_t key, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t * paramset, gnutls_datum_t * x, gnutls_datum_t * y, unsigned int flags); #define gnutls_pubkey_get_pk_ecc_raw gnutls_pubkey_export_ecc_raw int gnutls_pubkey_export_ecc_raw(gnutls_pubkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y); #define gnutls_pubkey_get_pk_ecc_x962 gnutls_pubkey_export_ecc_x962 int gnutls_pubkey_export_ecc_x962(gnutls_pubkey_t key, gnutls_datum_t * parameters, gnutls_datum_t * ecpoint); int gnutls_pubkey_export(gnutls_pubkey_t key, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_pubkey_export2(gnutls_pubkey_t key, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_pubkey_get_key_id(gnutls_pubkey_t key, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_pubkey_get_openpgp_key_id(gnutls_pubkey_t key, unsigned int flags, unsigned char *output_data, size_t * output_data_size, unsigned int *subkey); int gnutls_pubkey_get_key_usage(gnutls_pubkey_t key, unsigned int *usage); int gnutls_pubkey_set_key_usage(gnutls_pubkey_t key, unsigned int usage); int gnutls_pubkey_import(gnutls_pubkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); #define gnutls_pubkey_import_pkcs11_url(key, url, flags) gnutls_pubkey_import_url(key, url, flags) int gnutls_pubkey_import_dsa_raw(gnutls_pubkey_t key, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * g, const gnutls_datum_t * y); int gnutls_pubkey_import_rsa_raw(gnutls_pubkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e); int gnutls_pubkey_import_ecc_x962(gnutls_pubkey_t key, const gnutls_datum_t * parameters, const gnutls_datum_t * ecpoint); int gnutls_pubkey_import_ecc_raw(gnutls_pubkey_t key, gnutls_ecc_curve_t curve, const gnutls_datum_t * x, const gnutls_datum_t * y); int gnutls_pubkey_import_gost_raw(gnutls_pubkey_t key, gnutls_ecc_curve_t curve, gnutls_digest_algorithm_t digest, gnutls_gost_paramset_t paramset, const gnutls_datum_t * x, const gnutls_datum_t * y); int gnutls_pubkey_encrypt_data(gnutls_pubkey_t key, unsigned int flags, const gnutls_datum_t * plaintext, gnutls_datum_t * ciphertext); int gnutls_x509_crt_set_pubkey(gnutls_x509_crt_t crt, gnutls_pubkey_t key); int gnutls_x509_crq_set_pubkey(gnutls_x509_crq_t crq, gnutls_pubkey_t key); int gnutls_pubkey_verify_hash2(gnutls_pubkey_t key, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * hash, const gnutls_datum_t * signature); int gnutls_pubkey_verify_data2(gnutls_pubkey_t pubkey, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * data, const gnutls_datum_t * signature); /* Private key operations */ int gnutls_privkey_init(gnutls_privkey_t * key); void gnutls_privkey_deinit(gnutls_privkey_t key); /* macros to allow specifying a subgroup and group size in gnutls_privkey_generate() * and gnutls_x509_privkey_generate() */ #define GNUTLS_SUBGROUP_TO_BITS(group, subgroup) (unsigned int)((subgroup<<16)|(group)) #define GNUTLS_BITS_TO_SUBGROUP(bits) ((bits >> 16) & 0xFFFF) #define GNUTLS_BITS_TO_GROUP(bits) (bits & 0xFFFF) #define GNUTLS_BITS_HAVE_SUBGROUP(bits) ((bits) & 0xFFFF0000) int gnutls_privkey_generate (gnutls_privkey_t key, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags); int gnutls_privkey_generate2(gnutls_privkey_t pkey, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags, const gnutls_keygen_data_st *data, unsigned data_size); int gnutls_privkey_set_spki(gnutls_privkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_privkey_get_spki(gnutls_privkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_privkey_verify_seed(gnutls_privkey_t key, gnutls_digest_algorithm_t, const void *seed, size_t seed_size); int gnutls_privkey_get_seed(gnutls_privkey_t key, gnutls_digest_algorithm_t*, void *seed, size_t *seed_size); int gnutls_privkey_verify_params(gnutls_privkey_t key); void gnutls_privkey_set_flags(gnutls_privkey_t key, unsigned int flags); void gnutls_privkey_set_pin_function (gnutls_privkey_t key, gnutls_pin_callback_t fn, void *userdata); int gnutls_privkey_get_pk_algorithm(gnutls_privkey_t key, unsigned int *bits); gnutls_privkey_type_t gnutls_privkey_get_type(gnutls_privkey_t key); int gnutls_privkey_status(gnutls_privkey_t key); /** * gnutls_privkey_flags: * @GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA: Make an RSA signature on the hashed data as in the TLS protocol. * @GNUTLS_PRIVKEY_SIGN_FLAG_RSA_PSS: Make an RSA signature on the hashed data with the PSS padding. * @GNUTLS_PRIVKEY_FLAG_REPRODUCIBLE: Make a signature on the hashed data with reproducible parameters. * For RSA-PSS, that means to use empty salt instead of random value. To * verify a signature created using this flag, the corresponding SPKI needs * to be set on the public key. Use gnutls_pubkey_set_spki() for that. * For ECDSA/DSA, it uses the deterministic construction of random parameter * according to RFC 6979. Note that this only supports the NIST curves and DSA * subgroup bits up to 512. * @GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE: When importing a private key, automatically * release it when the structure it was imported is released. * @GNUTLS_PRIVKEY_IMPORT_COPY: Copy required values during import. * @GNUTLS_PRIVKEY_DISABLE_CALLBACKS: The following flag disables call to PIN callbacks etc. * Only relevant to TPM keys. * @GNUTLS_PRIVKEY_FLAG_PROVABLE: When generating a key involving prime numbers, use provable primes; a seed may be required. * @GNUTLS_PRIVKEY_FLAG_CA: The generated private key is going to be used as a CA (relevant for RSA-PSS keys). * @GNUTLS_PRIVKEY_FLAG_EXPORT_COMPAT: Keys generated or imported as provable require an extended format which cannot be read by previous versions * of gnutls or other applications. By setting this flag the key will be exported in a backwards compatible way, * even if the information about the seed used will be lost. * @GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH: When making an RSA-PSS * signature, use the salt whose length is equal to the digest length, as * mandated in RFC 8446 4.2.3. * * Enumeration of different certificate import flags. */ typedef enum gnutls_privkey_flags { GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE = 1, GNUTLS_PRIVKEY_IMPORT_COPY = 1 << 1, GNUTLS_PRIVKEY_DISABLE_CALLBACKS = 1 << 2, GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA = 1 << 4, GNUTLS_PRIVKEY_FLAG_PROVABLE = 1 << 5, GNUTLS_PRIVKEY_FLAG_EXPORT_COMPAT = 1 << 6, GNUTLS_PRIVKEY_SIGN_FLAG_RSA_PSS = 1 << 7, GNUTLS_PRIVKEY_FLAG_REPRODUCIBLE = 1 << 8, GNUTLS_PRIVKEY_FLAG_CA = 1 << 9, GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH = 1 << 10 } gnutls_privkey_flags_t; int gnutls_privkey_import_pkcs11(gnutls_privkey_t pkey, gnutls_pkcs11_privkey_t key, unsigned int flags); int gnutls_privkey_import_x509(gnutls_privkey_t pkey, gnutls_x509_privkey_t key, unsigned int flags); int gnutls_privkey_import_openpgp(gnutls_privkey_t pkey, gnutls_openpgp_privkey_t key, unsigned int flags); int gnutls_privkey_export_x509(gnutls_privkey_t pkey, gnutls_x509_privkey_t * key); int gnutls_privkey_export_openpgp(gnutls_privkey_t pkey, gnutls_openpgp_privkey_t * key); int gnutls_privkey_export_pkcs11(gnutls_privkey_t pkey, gnutls_pkcs11_privkey_t *key); int gnutls_privkey_import_openpgp_raw(gnutls_privkey_t pkey, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format, const gnutls_openpgp_keyid_t keyid, const char *password); int gnutls_privkey_import_x509_raw(gnutls_privkey_t pkey, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags); int gnutls_privkey_import_tpm_raw(gnutls_privkey_t pkey, const gnutls_datum_t * fdata, gnutls_tpmkey_fmt_t format, const char *srk_password, const char *key_password, unsigned int flags); int gnutls_privkey_import_tpm_url(gnutls_privkey_t pkey, const char *url, const char *srk_password, const char *key_password, unsigned int flags); int gnutls_privkey_import_url(gnutls_privkey_t key, const char *url, unsigned int flags); #if 0 /* for documentation purposes */ int gnutls_privkey_import_pkcs11_url(gnutls_privkey_t key, const char *url); #endif #define gnutls_privkey_import_pkcs11_url(key, url) gnutls_privkey_import_url(key, url, 0) int gnutls_privkey_import_ext(gnutls_privkey_t pkey, gnutls_pk_algorithm_t pk, void *userdata, gnutls_privkey_sign_func sign_func, gnutls_privkey_decrypt_func decrypt_func, unsigned int flags); int gnutls_privkey_import_ext2(gnutls_privkey_t pkey, gnutls_pk_algorithm_t pk, void *userdata, gnutls_privkey_sign_func sign_func, gnutls_privkey_decrypt_func decrypt_func, gnutls_privkey_deinit_func deinit_func, unsigned int flags); int gnutls_privkey_import_ext3(gnutls_privkey_t pkey, void *userdata, gnutls_privkey_sign_func sign_func, gnutls_privkey_decrypt_func decrypt_func, gnutls_privkey_deinit_func deinit_func, gnutls_privkey_info_func info_func, unsigned int flags); int gnutls_privkey_import_ext4(gnutls_privkey_t pkey, void *userdata, gnutls_privkey_sign_data_func sign_data_func, gnutls_privkey_sign_hash_func sign_hash_func, gnutls_privkey_decrypt_func decrypt_func, gnutls_privkey_deinit_func deinit_func, gnutls_privkey_info_func info_func, unsigned int flags); int gnutls_privkey_import_dsa_raw(gnutls_privkey_t key, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * g, const gnutls_datum_t * y, const gnutls_datum_t * x); int gnutls_privkey_import_rsa_raw(gnutls_privkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e, const gnutls_datum_t * d, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * u, const gnutls_datum_t * e1, const gnutls_datum_t * e2); int gnutls_privkey_import_ecc_raw(gnutls_privkey_t key, gnutls_ecc_curve_t curve, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_privkey_import_gost_raw(gnutls_privkey_t key, gnutls_ecc_curve_t curve, gnutls_digest_algorithm_t digest, gnutls_gost_paramset_t paramset, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_privkey_sign_data(gnutls_privkey_t signer, gnutls_digest_algorithm_t hash, unsigned int flags, const gnutls_datum_t * data, gnutls_datum_t * signature); int gnutls_privkey_sign_data2(gnutls_privkey_t signer, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * data, gnutls_datum_t * signature); #define gnutls_privkey_sign_raw_data(key, flags, data, sig) \ gnutls_privkey_sign_hash ( key, 0, GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA, data, sig) int gnutls_privkey_sign_hash(gnutls_privkey_t signer, gnutls_digest_algorithm_t hash_algo, unsigned int flags, const gnutls_datum_t * hash_data, gnutls_datum_t * signature); int gnutls_privkey_sign_hash2(gnutls_privkey_t signer, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * hash_data, gnutls_datum_t * signature); int gnutls_privkey_decrypt_data(gnutls_privkey_t key, unsigned int flags, const gnutls_datum_t * ciphertext, gnutls_datum_t * plaintext); int gnutls_privkey_decrypt_data2(gnutls_privkey_t key, unsigned int flags, const gnutls_datum_t * ciphertext, unsigned char * plaintext, size_t plaintext_size); int gnutls_privkey_export_rsa_raw(gnutls_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u, gnutls_datum_t * e1, gnutls_datum_t * e2); int gnutls_privkey_export_rsa_raw2(gnutls_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u, gnutls_datum_t * e1, gnutls_datum_t * e2, unsigned flags); int gnutls_privkey_export_dsa_raw(gnutls_privkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x); int gnutls_privkey_export_dsa_raw2(gnutls_privkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x, unsigned flags); int gnutls_privkey_export_ecc_raw(gnutls_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k); int gnutls_privkey_export_ecc_raw2(gnutls_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k, unsigned flags); int gnutls_privkey_export_gost_raw2(gnutls_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t * paramset, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k, unsigned flags); int gnutls_x509_crt_privkey_sign(gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crl_privkey_sign(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer, gnutls_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crq_privkey_sign(gnutls_x509_crq_t crq, gnutls_privkey_t key, gnutls_digest_algorithm_t dig, unsigned int flags); /** * gnutls_pcert_st: * @pubkey: public key of parsed certificate. * @cert: certificate itself of parsed certificate * @type: type of certificate, a #gnutls_certificate_type_t type. * * A parsed certificate. */ typedef struct gnutls_pcert_st { gnutls_pubkey_t pubkey; gnutls_datum_t cert; gnutls_certificate_type_t type; } gnutls_pcert_st; /* This flag is unused/ignored */ #define GNUTLS_PCERT_NO_CERT 1 int gnutls_pcert_import_x509(gnutls_pcert_st * pcert, gnutls_x509_crt_t crt, unsigned int flags); int gnutls_pcert_import_x509_list(gnutls_pcert_st * pcert, gnutls_x509_crt_t *crt, unsigned *ncrt, unsigned int flags); int gnutls_pcert_export_x509(gnutls_pcert_st * pcert, gnutls_x509_crt_t * crt); int gnutls_pcert_list_import_x509_raw(gnutls_pcert_st * pcerts, unsigned int *pcert_max, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pcert_list_import_x509_file(gnutls_pcert_st *pcert_list, unsigned *pcert_list_size, const char *file, gnutls_x509_crt_fmt_t format, gnutls_pin_callback_t pin_fn, void *pin_fn_userdata, unsigned int flags); int gnutls_pcert_import_x509_raw(gnutls_pcert_st * pcert, const gnutls_datum_t * cert, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pcert_import_openpgp_raw(gnutls_pcert_st * pcert, const gnutls_datum_t * cert, gnutls_openpgp_crt_fmt_t format, gnutls_openpgp_keyid_t keyid, unsigned int flags); int gnutls_pcert_import_openpgp(gnutls_pcert_st * pcert, gnutls_openpgp_crt_t crt, unsigned int flags); int gnutls_pcert_export_openpgp(gnutls_pcert_st * pcert, gnutls_openpgp_crt_t * crt); void gnutls_pcert_deinit(gnutls_pcert_st * pcert); int gnutls_pcert_import_rawpk(gnutls_pcert_st* pcert, gnutls_pubkey_t key, unsigned int flags); int gnutls_pcert_import_rawpk_raw(gnutls_pcert_st* pcert, const gnutls_datum_t* rawpubkey, gnutls_x509_crt_fmt_t format, unsigned int key_usage, unsigned int flags); /* For certificate credentials */ /* This is the same as gnutls_certificate_retrieve_function() * but retrieves a gnutls_pcert_st which requires much less processing * within the library. */ typedef int gnutls_certificate_retrieve_function2(gnutls_session_t, const gnutls_datum_t *req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t *pk_algos, int pk_algos_length, gnutls_pcert_st**, unsigned int *pcert_length, gnutls_privkey_t *privkey); void gnutls_certificate_set_retrieve_function2 (gnutls_certificate_credentials_t cred, gnutls_certificate_retrieve_function2 *func); struct gnutls_cert_retr_st { unsigned version; /* set to 1 */ gnutls_certificate_credentials_t cred; const gnutls_datum_t *req_ca_rdn; unsigned nreqs; const gnutls_pk_algorithm_t *pk_algos; unsigned pk_algos_length; /* other fields may be added if version is > 1 */ unsigned char padding[64]; }; /* When the callback sets this value, gnutls will deinitialize the given * values after use */ #define GNUTLS_CERT_RETR_DEINIT_ALL 1 typedef int gnutls_certificate_retrieve_function3( gnutls_session_t, const struct gnutls_cert_retr_st *info, gnutls_pcert_st **certs, unsigned int *certs_length, gnutls_ocsp_data_st **ocsp, unsigned int *ocsp_length, gnutls_privkey_t *privkey, unsigned int *flags); void gnutls_certificate_set_retrieve_function3 (gnutls_certificate_credentials_t cred, gnutls_certificate_retrieve_function3 *func); int gnutls_certificate_set_key(gnutls_certificate_credentials_t res, const char **names, int names_size, gnutls_pcert_st * pcert_list, int pcert_list_size, gnutls_privkey_t key); int gnutls_pubkey_print(gnutls_pubkey_t pubkey, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_ABSTRACT_H */ ================================================ FILE: thirdparty/32/include/gnutls/compat.h ================================================ /* * Copyright (C) 2008-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* Typedefs for more compatibility with older GnuTLS. */ #ifndef GNUTLS_COMPAT_H #define GNUTLS_COMPAT_H /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #ifdef __GNUC__ #define _GNUTLS_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #if !defined GNUTLS_INTERNAL_BUILD #if _GNUTLS_GCC_VERSION >= 30100 #define _GNUTLS_GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__)) #endif #endif #endif /* __GNUC__ */ #ifndef _GNUTLS_GCC_ATTR_DEPRECATED #define _GNUTLS_GCC_ATTR_DEPRECATED #endif /* gnutls_connection_end_t was made redundant in 2.99.0 */ typedef unsigned int gnutls_connection_end_t _GNUTLS_GCC_ATTR_DEPRECATED; /* Stuff deprecated in 2.x */ typedef gnutls_cipher_algorithm_t gnutls_cipher_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_kx_algorithm_t gnutls_kx_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_mac_algorithm_t gnutls_mac_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_digest_algorithm_t gnutls_digest_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_compression_method_t gnutls_compression_method _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_connection_end_t gnutls_connection_end _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crt_fmt_t gnutls_x509_crt_fmt _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_pk_algorithm_t gnutls_pk_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_sign_algorithm_t gnutls_sign_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_close_request_t gnutls_close_request _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_request_t gnutls_certificate_request _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_status_t gnutls_certificate_status _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_session_t gnutls_session _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_alert_level_t gnutls_alert_level _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_alert_description_t gnutls_alert_description _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_subject_alt_name_t gnutls_x509_subject_alt_name _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_openpgp_privkey_t gnutls_openpgp_privkey _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_openpgp_keyring_t gnutls_openpgp_keyring _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crt_t gnutls_x509_crt _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_privkey_t gnutls_x509_privkey _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crl_t gnutls_x509_crl _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crq_t gnutls_x509_crq _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_credentials_t gnutls_certificate_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_anon_server_credentials_t gnutls_anon_server_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_anon_client_credentials_t gnutls_anon_client_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_srp_client_credentials_t gnutls_srp_client_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_srp_server_credentials_t gnutls_srp_server_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_dh_params_t gnutls_dh_params _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_rsa_params_t gnutls_rsa_params _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_params_type_t gnutls_params_type _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_credentials_type_t gnutls_credentials_type _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_type_t gnutls_certificate_type _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_datum_t gnutls_datum _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_transport_ptr_t gnutls_transport_ptr _GNUTLS_GCC_ATTR_DEPRECATED; /* Old verification flags */ #define GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT (0) /* Old SRP alerts removed in 2.1.x because the TLS-SRP RFC was modified to use the PSK alert. */ #define GNUTLS_A_MISSING_SRP_USERNAME GNUTLS_A_UNKNOWN_PSK_IDENTITY #define GNUTLS_A_UNKNOWN_SRP_USERNAME GNUTLS_A_UNKNOWN_PSK_IDENTITY /* OpenPGP stuff renamed in 2.1.x. */ #define GNUTLS_OPENPGP_KEY GNUTLS_OPENPGP_CERT #define GNUTLS_OPENPGP_KEY_FINGERPRINT GNUTLS_OPENPGP_CERT_FINGERPRINT #define gnutls_openpgp_send_key gnutls_openpgp_send_cert typedef gnutls_openpgp_crt_status_t gnutls_openpgp_key_status_t _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_openpgp_crt_t gnutls_openpgp_key_t _GNUTLS_GCC_ATTR_DEPRECATED; #define gnutls_openpgp_key_init gnutls_openpgp_crt_init #define gnutls_openpgp_key_deinit gnutls_openpgp_crt_deinit #define gnutls_openpgp_key_import gnutls_openpgp_crt_import #define gnutls_openpgp_key_export gnutls_openpgp_crt_export #define gnutls_openpgp_key_get_key_usage gnutls_openpgp_crt_get_key_usage #define gnutls_openpgp_key_get_fingerprint gnutls_openpgp_crt_get_fingerprint #define gnutls_openpgp_key_get_pk_algorithm gnutls_openpgp_crt_get_pk_algorithm #define gnutls_openpgp_key_get_name gnutls_openpgp_crt_get_name #define gnutls_openpgp_key_get_version gnutls_openpgp_crt_get_version #define gnutls_openpgp_key_get_creation_time gnutls_openpgp_crt_get_creation_time #define gnutls_openpgp_key_get_expiration_time gnutls_openpgp_crt_get_expiration_time #define gnutls_openpgp_key_get_id gnutls_openpgp_crt_get_id #define gnutls_openpgp_key_check_hostname gnutls_openpgp_crt_check_hostname /* OpenPGP stuff renamed in 2.3.x. */ #define gnutls_openpgp_crt_get_id gnutls_openpgp_crt_get_key_id /* New better names renamed in 2.3.x, add these for backwards compatibility with old poor names.*/ #define GNUTLS_X509_CRT_FULL GNUTLS_CRT_PRINT_FULL #define GNUTLS_X509_CRT_ONELINE GNUTLS_CRT_PRINT_ONELINE #define GNUTLS_X509_CRT_UNSIGNED_FULL GNUTLS_CRT_PRINT_UNSIGNED_FULL /* Namespace problems. */ #define LIBGNUTLS_VERSION GNUTLS_VERSION #define LIBGNUTLS_VERSION_MAJOR GNUTLS_VERSION_MAJOR #define LIBGNUTLS_VERSION_MINOR GNUTLS_VERSION_MINOR #define LIBGNUTLS_VERSION_PATCH GNUTLS_VERSION_PATCH #define LIBGNUTLS_VERSION_NUMBER GNUTLS_VERSION_NUMBER #define LIBGNUTLS_EXTRA_VERSION GNUTLS_VERSION /* This is a very dangerous and error-prone function. * Use gnutls_privkey_sign_hash() instead. */ int gnutls_x509_privkey_sign_hash(gnutls_x509_privkey_t key, const gnutls_datum_t * hash, gnutls_datum_t * signature) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_sign_hash(gnutls_openpgp_privkey_t key, const gnutls_datum_t * hash, gnutls_datum_t * signature) _GNUTLS_GCC_ATTR_DEPRECATED; /* gnutls_pubkey_get_preferred_hash_algorithm() */ int gnutls_x509_crt_get_preferred_hash_algorithm(gnutls_x509_crt_t crt, gnutls_digest_algorithm_t * hash, unsigned int *mand) _GNUTLS_GCC_ATTR_DEPRECATED; /* use gnutls_privkey_sign_hash() with the GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA flag */ #ifdef _ISOC99_SOURCE /* we provide older functions for compatibility as inline functions that * depend on gnutls_session_get_random. */ static inline const void *gnutls_session_get_server_random(gnutls_session_t session) _GNUTLS_GCC_ATTR_DEPRECATED; static inline const void *gnutls_session_get_server_random(gnutls_session_t session) { gnutls_datum_t rnd; gnutls_session_get_random(session, NULL, &rnd); /*doc-skip */ return rnd.data; } static inline const void *gnutls_session_get_client_random(gnutls_session_t session) _GNUTLS_GCC_ATTR_DEPRECATED; static inline const void *gnutls_session_get_client_random(gnutls_session_t session) { gnutls_datum_t rnd; gnutls_session_get_random(session, &rnd, NULL); /*doc-skip */ return rnd.data; } #endif void gnutls_global_set_mem_functions(gnutls_alloc_function alloc_func, gnutls_alloc_function secure_alloc_func, gnutls_is_secure_function is_secure_func, gnutls_realloc_function realloc_func, gnutls_free_function free_func) _GNUTLS_GCC_ATTR_DEPRECATED; /* defined in old headers - unused nevertheless */ #define GNUTLS_SUPPLEMENTAL_USER_MAPPING_DATA 0 /* old compression related functions */ gnutls_compression_method_t gnutls_compression_get(gnutls_session_t session) _GNUTLS_GCC_ATTR_DEPRECATED; const char * gnutls_compression_get_name(gnutls_compression_method_t algorithm) __GNUTLS_CONST__ _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_compression_method_t gnutls_compression_get_id(const char *name) __GNUTLS_CONST__ _GNUTLS_GCC_ATTR_DEPRECATED; const gnutls_compression_method_t * gnutls_compression_list(void) __GNUTLS_PURE__ _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_priority_compression_list(gnutls_priority_t pcache, const unsigned int **list) _GNUTLS_GCC_ATTR_DEPRECATED; /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_COMPAT_H */ ================================================ FILE: thirdparty/32/include/gnutls/crypto.h ================================================ /* * Copyright (C) 2008-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_CRYPTO_H #define GNUTLS_CRYPTO_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ typedef struct api_cipher_hd_st *gnutls_cipher_hd_t; int gnutls_cipher_init(gnutls_cipher_hd_t * handle, gnutls_cipher_algorithm_t cipher, const gnutls_datum_t * key, const gnutls_datum_t * iv); int gnutls_cipher_encrypt(const gnutls_cipher_hd_t handle, void *text, size_t textlen); int gnutls_cipher_decrypt(const gnutls_cipher_hd_t handle, void *ciphertext, size_t ciphertextlen); int gnutls_cipher_decrypt2(gnutls_cipher_hd_t handle, const void *ciphertext, size_t ciphertextlen, void *text, size_t textlen); int gnutls_cipher_encrypt2(gnutls_cipher_hd_t handle, const void *text, size_t textlen, void *ciphertext, size_t ciphertextlen); /** * gnutls_cipher_flags_t: * @GNUTLS_CIPHER_PADDING_PKCS7: Flag to indicate PKCS#7 padding * * Enumeration of flags to control block cipher padding, used by * gnutls_cipher_encrypt3() and gnutls_cipher_decrypt3(). * * Since: 3.7.7 */ typedef enum gnutls_cipher_flags_t { GNUTLS_CIPHER_PADDING_PKCS7 = 1 } gnutls_cipher_flags_t; int gnutls_cipher_encrypt3(gnutls_cipher_hd_t handle, const void *ptext, size_t ptext_len, void *ctext, size_t *ctext_len, unsigned flags); int gnutls_cipher_decrypt3(gnutls_cipher_hd_t handle, const void *ctext, size_t ctext_len, void *ptext, size_t *ptext_len, unsigned flags); void gnutls_cipher_set_iv(gnutls_cipher_hd_t handle, void *iv, size_t ivlen); int gnutls_cipher_tag(gnutls_cipher_hd_t handle, void *tag, size_t tag_size); int gnutls_cipher_add_auth(gnutls_cipher_hd_t handle, const void *text, size_t text_size); void gnutls_cipher_deinit(gnutls_cipher_hd_t handle); unsigned gnutls_cipher_get_block_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_cipher_get_iv_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_cipher_get_tag_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; /* AEAD API */ typedef struct api_aead_cipher_hd_st *gnutls_aead_cipher_hd_t; int gnutls_aead_cipher_init(gnutls_aead_cipher_hd_t * handle, gnutls_cipher_algorithm_t cipher, const gnutls_datum_t * key); int gnutls_aead_cipher_set_key(gnutls_aead_cipher_hd_t handle, const gnutls_datum_t *key); int gnutls_aead_cipher_decrypt(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const void *auth, size_t auth_len, size_t tag_size, const void *ctext, size_t ctext_len, void *ptext, size_t *ptext_len); int gnutls_aead_cipher_encrypt(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const void *auth, size_t auth_len, size_t tag_size, const void *ptext, size_t ptext_len, void *ctext, size_t *ctext_len); int gnutls_aead_cipher_encryptv(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const giovec_t *auth_iov, int auth_iovcnt, size_t tag_size, const giovec_t *iov, int iovcnt, void *ctext, size_t *ctext_len); int gnutls_aead_cipher_encryptv2(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const giovec_t *auth_iov, int auth_iovcnt, const giovec_t *iov, int iovcnt, void *tag, size_t *tag_size); int gnutls_aead_cipher_decryptv2(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const giovec_t *auth_iov, int auth_iovcnt, const giovec_t *iov, int iovcnt, void *tag, size_t tag_size); void gnutls_aead_cipher_deinit(gnutls_aead_cipher_hd_t handle); /* Hash - MAC API */ typedef struct hash_hd_st *gnutls_hash_hd_t; typedef struct hmac_hd_st *gnutls_hmac_hd_t; size_t gnutls_mac_get_nonce_size(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; int gnutls_hmac_init(gnutls_hmac_hd_t * dig, gnutls_mac_algorithm_t algorithm, const void *key, size_t keylen); void gnutls_hmac_set_nonce(gnutls_hmac_hd_t handle, const void *nonce, size_t nonce_len); int gnutls_hmac(gnutls_hmac_hd_t handle, const void *text, size_t textlen); void gnutls_hmac_output(gnutls_hmac_hd_t handle, void *digest); void gnutls_hmac_deinit(gnutls_hmac_hd_t handle, void *digest); unsigned gnutls_hmac_get_len(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_hmac_get_key_size(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; int gnutls_hmac_fast(gnutls_mac_algorithm_t algorithm, const void *key, size_t keylen, const void *text, size_t textlen, void *digest); gnutls_hmac_hd_t gnutls_hmac_copy(gnutls_hmac_hd_t handle); int gnutls_hash_init(gnutls_hash_hd_t * dig, gnutls_digest_algorithm_t algorithm); int gnutls_hash(gnutls_hash_hd_t handle, const void *text, size_t textlen); void gnutls_hash_output(gnutls_hash_hd_t handle, void *digest); void gnutls_hash_deinit(gnutls_hash_hd_t handle, void *digest); unsigned gnutls_hash_get_len(gnutls_digest_algorithm_t algorithm) __GNUTLS_CONST__; int gnutls_hash_fast(gnutls_digest_algorithm_t algorithm, const void *text, size_t textlen, void *digest); gnutls_hash_hd_t gnutls_hash_copy(gnutls_hash_hd_t handle); /* KDF API */ int gnutls_hkdf_extract(gnutls_mac_algorithm_t mac, const gnutls_datum_t *key, const gnutls_datum_t *salt, void *output); int gnutls_hkdf_expand(gnutls_mac_algorithm_t mac, const gnutls_datum_t *key, const gnutls_datum_t *info, void *output, size_t length); int gnutls_pbkdf2(gnutls_mac_algorithm_t mac, const gnutls_datum_t *key, const gnutls_datum_t *salt, unsigned iter_count, void *output, size_t length); /* register ciphers */ /** * gnutls_rnd_level_t: * @GNUTLS_RND_NONCE: Non-predictable random number. Fatal in parts * of session if broken, i.e., vulnerable to statistical analysis. * @GNUTLS_RND_RANDOM: Pseudo-random cryptographic random number. * Fatal in session if broken. Example use: temporal keys. * @GNUTLS_RND_KEY: Fatal in many sessions if broken. Example use: * Long-term keys. * * Enumeration of random quality levels. */ typedef enum gnutls_rnd_level { GNUTLS_RND_NONCE = 0, GNUTLS_RND_RANDOM = 1, GNUTLS_RND_KEY = 2 } gnutls_rnd_level_t; int gnutls_rnd(gnutls_rnd_level_t level, void *data, size_t len); void gnutls_rnd_refresh(void); /* API to override ciphers and MAC algorithms */ typedef int (*gnutls_cipher_init_func) (gnutls_cipher_algorithm_t, void **ctx, int enc); typedef int (*gnutls_cipher_setkey_func) (void *ctx, const void *key, size_t keysize); /* old style ciphers */ typedef int (*gnutls_cipher_setiv_func) (void *ctx, const void *iv, size_t ivsize); typedef int (*gnutls_cipher_getiv_func) (void *ctx, void *iv, size_t ivsize); typedef int (*gnutls_cipher_encrypt_func) (void *ctx, const void *plain, size_t plainsize, void *encr, size_t encrsize); typedef int (*gnutls_cipher_decrypt_func) (void *ctx, const void *encr, size_t encrsize, void *plain, size_t plainsize); /* aead ciphers */ typedef int (*gnutls_cipher_auth_func) (void *ctx, const void *data, size_t datasize); typedef void (*gnutls_cipher_tag_func) (void *ctx, void *tag, size_t tagsize); typedef int (*gnutls_cipher_aead_encrypt_func) (void *ctx, const void *nonce, size_t noncesize, const void *auth, size_t authsize, size_t tag_size, const void *plain, size_t plainsize, void *encr, size_t encrsize); typedef int (*gnutls_cipher_aead_decrypt_func) (void *ctx, const void *nonce, size_t noncesize, const void *auth, size_t authsize, size_t tag_size, const void *encr, size_t encrsize, void *plain, size_t plainsize); typedef void (*gnutls_cipher_deinit_func) (void *ctx); int gnutls_crypto_register_cipher(gnutls_cipher_algorithm_t algorithm, int priority, gnutls_cipher_init_func init, gnutls_cipher_setkey_func setkey, gnutls_cipher_setiv_func setiv, gnutls_cipher_encrypt_func encrypt, gnutls_cipher_decrypt_func decrypt, gnutls_cipher_deinit_func deinit) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_crypto_register_aead_cipher(gnutls_cipher_algorithm_t algorithm, int priority, gnutls_cipher_init_func init, gnutls_cipher_setkey_func setkey, gnutls_cipher_aead_encrypt_func aead_encrypt, gnutls_cipher_aead_decrypt_func aead_decrypt, gnutls_cipher_deinit_func deinit) _GNUTLS_GCC_ATTR_DEPRECATED; typedef int (*gnutls_mac_init_func) (gnutls_mac_algorithm_t, void **ctx); typedef int (*gnutls_mac_setkey_func) (void *ctx, const void *key, size_t keysize); typedef int (*gnutls_mac_setnonce_func) (void *ctx, const void *nonce, size_t noncesize); typedef int (*gnutls_mac_hash_func) (void *ctx, const void *text, size_t textsize); typedef int (*gnutls_mac_output_func) (void *src_ctx, void *digest, size_t digestsize); typedef void (*gnutls_mac_deinit_func) (void *ctx); typedef int (*gnutls_mac_fast_func) (gnutls_mac_algorithm_t, const void *nonce, size_t nonce_size, const void *key, size_t keysize, const void *text, size_t textsize, void *digest); typedef void *(*gnutls_mac_copy_func) (const void *ctx); int gnutls_crypto_register_mac(gnutls_mac_algorithm_t mac, int priority, gnutls_mac_init_func init, gnutls_mac_setkey_func setkey, gnutls_mac_setnonce_func setnonce, gnutls_mac_hash_func hash, gnutls_mac_output_func output, gnutls_mac_deinit_func deinit, gnutls_mac_fast_func hash_fast) _GNUTLS_GCC_ATTR_DEPRECATED; typedef int (*gnutls_digest_init_func) (gnutls_digest_algorithm_t, void **ctx); typedef int (*gnutls_digest_hash_func) (void *ctx, const void *text, size_t textsize); typedef int (*gnutls_digest_output_func) (void *src_ctx, void *digest, size_t digestsize); typedef void (*gnutls_digest_deinit_func) (void *ctx); typedef int (*gnutls_digest_fast_func) (gnutls_digest_algorithm_t, const void *text, size_t textsize, void *digest); typedef void *(*gnutls_digest_copy_func) (const void *ctx); int gnutls_crypto_register_digest(gnutls_digest_algorithm_t digest, int priority, gnutls_digest_init_func init, gnutls_digest_hash_func hash, gnutls_digest_output_func output, gnutls_digest_deinit_func deinit, gnutls_digest_fast_func hash_fast) _GNUTLS_GCC_ATTR_DEPRECATED; /* RSA-PKCS#1 1.5 helper functions */ int gnutls_encode_ber_digest_info(gnutls_digest_algorithm_t hash, const gnutls_datum_t * digest, gnutls_datum_t * output); int gnutls_decode_ber_digest_info(const gnutls_datum_t * info, gnutls_digest_algorithm_t *hash, unsigned char *digest, unsigned int *digest_size); int gnutls_decode_rs_value(const gnutls_datum_t * sig_value, gnutls_datum_t *r, gnutls_datum_t *s); int gnutls_encode_rs_value(gnutls_datum_t * sig_value, const gnutls_datum_t * r, const gnutls_datum_t * s); int gnutls_encode_gost_rs_value(gnutls_datum_t * sig_value, const gnutls_datum_t * r, const gnutls_datum_t *s); int gnutls_decode_gost_rs_value(const gnutls_datum_t * sig_value, gnutls_datum_t * r, gnutls_datum_t * s); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_CRYPTO_H */ ================================================ FILE: thirdparty/32/include/gnutls/dtls.h ================================================ /* * Copyright (C) 2011-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the X.509 * certificate and CRL handling functions. */ #ifndef GNUTLS_DTLS_H #define GNUTLS_DTLS_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_COOKIE_KEY_SIZE 16 void gnutls_dtls_set_timeouts(gnutls_session_t session, unsigned int retrans_timeout, unsigned int total_timeout); unsigned int gnutls_dtls_get_mtu(gnutls_session_t session); unsigned int gnutls_dtls_get_data_mtu(gnutls_session_t session); void gnutls_dtls_set_mtu(gnutls_session_t session, unsigned int mtu); int gnutls_dtls_set_data_mtu(gnutls_session_t session, unsigned int mtu); unsigned int gnutls_dtls_get_timeout(gnutls_session_t session); /** * gnutls_dtls_prestate_st: * @record_seq: record sequence number * @hsk_read_seq: handshake read sequence number * @hsk_write_seq: handshake write sequence number * * DTLS cookie prestate struct. This is usually never modified by * the application, it is used to carry the cookie data between * gnutls_dtls_cookie_send(), gnutls_dtls_cookie_verify() and * gnutls_dtls_prestate_set(). */ typedef struct { unsigned int record_seq; unsigned int hsk_read_seq; unsigned int hsk_write_seq; } gnutls_dtls_prestate_st; int gnutls_dtls_cookie_send(gnutls_datum_t * key, void *client_data, size_t client_data_size, gnutls_dtls_prestate_st * prestate, gnutls_transport_ptr_t ptr, gnutls_push_func push_func); int gnutls_dtls_cookie_verify(gnutls_datum_t * key, void *client_data, size_t client_data_size, void *_msg, size_t msg_size, gnutls_dtls_prestate_st * prestate); void gnutls_dtls_prestate_set(gnutls_session_t session, gnutls_dtls_prestate_st * prestate); unsigned int gnutls_record_get_discarded(gnutls_session_t session); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_DTLS_H */ ================================================ FILE: thirdparty/32/include/gnutls/gnutls.h ================================================ /* -*- c -*- * Copyright (C) 2000-2016 Free Software Foundation, Inc. * Copyright (C) 2015-2017 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for all the * high level functionality of the gnutls main library. * * If the optional C++ binding was built, it is available in * gnutls/gnutlsxx.h. * * The openssl compatibility layer (which is under the GNU GPL * license) is in gnutls/openssl.h. * * The low level cipher functionality is in gnutls/crypto.h. */ #ifndef GNUTLS_GNUTLS_H #define GNUTLS_GNUTLS_H /* Get ssize_t. */ #include /* Get size_t. */ #include /* Get time_t. */ #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_VERSION "3.7.10" #define GNUTLS_VERSION_MAJOR 3 #define GNUTLS_VERSION_MINOR 7 #define GNUTLS_VERSION_PATCH 10 #define GNUTLS_VERSION_NUMBER 0x03070a #define GNUTLS_CIPHER_RIJNDAEL_128_CBC GNUTLS_CIPHER_AES_128_CBC #define GNUTLS_CIPHER_RIJNDAEL_256_CBC GNUTLS_CIPHER_AES_256_CBC #define GNUTLS_CIPHER_RIJNDAEL_CBC GNUTLS_CIPHER_AES_128_CBC #define GNUTLS_CIPHER_ARCFOUR GNUTLS_CIPHER_ARCFOUR_128 #if !defined(GNUTLS_INTERNAL_BUILD) && defined(_WIN32) # define _SYM_EXPORT __declspec(dllimport) #else # define _SYM_EXPORT #endif #ifdef __GNUC__ # define __GNUTLS_CONST__ __attribute__((const)) # define __GNUTLS_PURE__ __attribute__((pure)) #else # define __GNUTLS_CONST__ # define __GNUTLS_PURE__ #endif /* Use the following definition globally in your program to disable * implicit initialization of gnutls. */ #define GNUTLS_SKIP_GLOBAL_INIT int _gnutls_global_init_skip(void); \ int _gnutls_global_init_skip(void) {return 1;} /** * gnutls_cipher_algorithm_t: * @GNUTLS_CIPHER_UNKNOWN: Value to identify an unknown/unsupported algorithm. * @GNUTLS_CIPHER_NULL: The NULL (identity) encryption algorithm. * @GNUTLS_CIPHER_ARCFOUR_128: ARCFOUR stream cipher with 128-bit keys. * @GNUTLS_CIPHER_3DES_CBC: 3DES in CBC mode. * @GNUTLS_CIPHER_AES_128_CBC: AES in CBC mode with 128-bit keys. * @GNUTLS_CIPHER_AES_192_CBC: AES in CBC mode with 192-bit keys. * @GNUTLS_CIPHER_AES_256_CBC: AES in CBC mode with 256-bit keys. * @GNUTLS_CIPHER_AES_128_CFB8: AES in CFB8 mode with 128-bit keys. * @GNUTLS_CIPHER_AES_192_CFB8: AES in CFB8 mode with 192-bit keys. * @GNUTLS_CIPHER_AES_256_CFB8: AES in CFB8 mode with 256-bit keys. * @GNUTLS_CIPHER_ARCFOUR_40: ARCFOUR stream cipher with 40-bit keys. * @GNUTLS_CIPHER_CAMELLIA_128_CBC: Camellia in CBC mode with 128-bit keys. * @GNUTLS_CIPHER_CAMELLIA_192_CBC: Camellia in CBC mode with 192-bit keys. * @GNUTLS_CIPHER_CAMELLIA_256_CBC: Camellia in CBC mode with 256-bit keys. * @GNUTLS_CIPHER_RC2_40_CBC: RC2 in CBC mode with 40-bit keys. * @GNUTLS_CIPHER_DES_CBC: DES in CBC mode (56-bit keys). * @GNUTLS_CIPHER_AES_128_GCM: AES in GCM mode with 128-bit keys (AEAD). * @GNUTLS_CIPHER_AES_256_GCM: AES in GCM mode with 256-bit keys (AEAD). * @GNUTLS_CIPHER_AES_128_CCM: AES in CCM mode with 128-bit keys (AEAD). * @GNUTLS_CIPHER_AES_256_CCM: AES in CCM mode with 256-bit keys (AEAD). * @GNUTLS_CIPHER_AES_128_CCM_8: AES in CCM mode with 64-bit tag and 128-bit keys (AEAD). * @GNUTLS_CIPHER_AES_256_CCM_8: AES in CCM mode with 64-bit tag and 256-bit keys (AEAD). * @GNUTLS_CIPHER_CAMELLIA_128_GCM: CAMELLIA in GCM mode with 128-bit keys (AEAD). * @GNUTLS_CIPHER_CAMELLIA_256_GCM: CAMELLIA in GCM mode with 256-bit keys (AEAD). * @GNUTLS_CIPHER_SALSA20_256: Salsa20 with 256-bit keys. * @GNUTLS_CIPHER_ESTREAM_SALSA20_256: Estream's Salsa20 variant with 256-bit keys. * @GNUTLS_CIPHER_CHACHA20_32: Chacha20 cipher with 96-bit nonces and 32-bit block counters. * @GNUTLS_CIPHER_CHACHA20_64: Chacha20 cipher with 64-bit nonces and 64-bit block counters. * @GNUTLS_CIPHER_CHACHA20_POLY1305: The Chacha20 cipher with the Poly1305 authenticator (AEAD). * @GNUTLS_CIPHER_GOST28147_TC26Z_CFB: GOST 28147-89 (Magma) cipher in CFB mode with TC26 Z S-box. * @GNUTLS_CIPHER_GOST28147_CPA_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro A S-box. * @GNUTLS_CIPHER_GOST28147_CPB_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro B S-box. * @GNUTLS_CIPHER_GOST28147_CPC_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro C S-box. * @GNUTLS_CIPHER_GOST28147_CPD_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro D S-box. * @GNUTLS_CIPHER_AES_128_XTS: AES in XTS mode with 128-bit key + 128bit tweak key. * @GNUTLS_CIPHER_AES_256_XTS: AES in XTS mode with 256-bit key + 256bit tweak key. * Note that the XTS ciphers are message oriented. * The whole message needs to be provided with a single call, because * cipher-stealing requires to know where the message actually terminates * in order to be able to compute where the stealing occurs. * @GNUTLS_CIPHER_GOST28147_TC26Z_CNT: GOST 28147-89 (Magma) cipher in CNT mode with TC26 Z S-box. * @GNUTLS_CIPHER_MAGMA_CTR_ACPKM: GOST R 34.12-2015 (Magma) cipher in CTR-ACPKM mode. * @GNUTLS_CIPHER_KUZNYECHIK_CTR_ACPKM: GOST R 34.12-2015 (Kuznyechik) cipher in CTR-ACPKM mode. * @GNUTLS_CIPHER_IDEA_PGP_CFB: IDEA in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_3DES_PGP_CFB: 3DES in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_CAST5_PGP_CFB: CAST5 in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_BLOWFISH_PGP_CFB: Blowfish in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_SAFER_SK128_PGP_CFB: Safer-SK in CFB mode with 128-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_AES128_PGP_CFB: AES in CFB mode with 128-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_AES192_PGP_CFB: AES in CFB mode with 192-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_AES256_PGP_CFB: AES in CFB mode with 256-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_TWOFISH_PGP_CFB: Twofish in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_AES_128_SIV: AES in SIV mode with 128-bit key. * @GNUTLS_CIPHER_AES_256_SIV: AES in SIV mode with 256-bit key. * Note that the SIV ciphers can only be used with * the AEAD interface, and the IV plays a role as * the authentication tag while it is prepended to * the cipher text. * @GNUTLS_CIPHER_AES_192_GCM: AES in GCM mode with 192-bit keys (AEAD). * * Enumeration of different symmetric encryption algorithms. */ typedef enum gnutls_cipher_algorithm { GNUTLS_CIPHER_UNKNOWN = 0, GNUTLS_CIPHER_NULL = 1, GNUTLS_CIPHER_ARCFOUR_128 = 2, GNUTLS_CIPHER_3DES_CBC = 3, GNUTLS_CIPHER_AES_128_CBC = 4, GNUTLS_CIPHER_AES_256_CBC = 5, GNUTLS_CIPHER_ARCFOUR_40 = 6, GNUTLS_CIPHER_CAMELLIA_128_CBC = 7, GNUTLS_CIPHER_CAMELLIA_256_CBC = 8, GNUTLS_CIPHER_AES_192_CBC = 9, GNUTLS_CIPHER_AES_128_GCM = 10, GNUTLS_CIPHER_AES_256_GCM = 11, GNUTLS_CIPHER_CAMELLIA_192_CBC = 12, GNUTLS_CIPHER_SALSA20_256 = 13, GNUTLS_CIPHER_ESTREAM_SALSA20_256 = 14, GNUTLS_CIPHER_CAMELLIA_128_GCM = 15, GNUTLS_CIPHER_CAMELLIA_256_GCM = 16, GNUTLS_CIPHER_RC2_40_CBC = 17, GNUTLS_CIPHER_DES_CBC = 18, GNUTLS_CIPHER_AES_128_CCM = 19, GNUTLS_CIPHER_AES_256_CCM = 20, GNUTLS_CIPHER_AES_128_CCM_8 = 21, GNUTLS_CIPHER_AES_256_CCM_8 = 22, GNUTLS_CIPHER_CHACHA20_POLY1305 = 23, GNUTLS_CIPHER_GOST28147_TC26Z_CFB = 24, GNUTLS_CIPHER_GOST28147_CPA_CFB = 25, GNUTLS_CIPHER_GOST28147_CPB_CFB = 26, GNUTLS_CIPHER_GOST28147_CPC_CFB = 27, GNUTLS_CIPHER_GOST28147_CPD_CFB = 28, GNUTLS_CIPHER_AES_128_CFB8 = 29, GNUTLS_CIPHER_AES_192_CFB8 = 30, GNUTLS_CIPHER_AES_256_CFB8 = 31, GNUTLS_CIPHER_AES_128_XTS = 32, GNUTLS_CIPHER_AES_256_XTS = 33, GNUTLS_CIPHER_GOST28147_TC26Z_CNT = 34, GNUTLS_CIPHER_CHACHA20_64 = 35, GNUTLS_CIPHER_CHACHA20_32 = 36, GNUTLS_CIPHER_AES_128_SIV = 37, GNUTLS_CIPHER_AES_256_SIV = 38, GNUTLS_CIPHER_AES_192_GCM = 39, GNUTLS_CIPHER_MAGMA_CTR_ACPKM = 40, GNUTLS_CIPHER_KUZNYECHIK_CTR_ACPKM = 41, /* used only for PGP internals. Ignored in TLS/SSL */ GNUTLS_CIPHER_IDEA_PGP_CFB = 200, GNUTLS_CIPHER_3DES_PGP_CFB = 201, GNUTLS_CIPHER_CAST5_PGP_CFB = 202, GNUTLS_CIPHER_BLOWFISH_PGP_CFB = 203, GNUTLS_CIPHER_SAFER_SK128_PGP_CFB = 204, GNUTLS_CIPHER_AES128_PGP_CFB = 205, GNUTLS_CIPHER_AES192_PGP_CFB = 206, GNUTLS_CIPHER_AES256_PGP_CFB = 207, GNUTLS_CIPHER_TWOFISH_PGP_CFB = 208 } gnutls_cipher_algorithm_t; /** * gnutls_kx_algorithm_t: * @GNUTLS_KX_UNKNOWN: Unknown key-exchange algorithm. * @GNUTLS_KX_RSA: RSA key-exchange algorithm. * @GNUTLS_KX_DHE_DSS: DHE-DSS key-exchange algorithm. * @GNUTLS_KX_DHE_RSA: DHE-RSA key-exchange algorithm. * @GNUTLS_KX_ECDHE_RSA: ECDHE-RSA key-exchange algorithm. * @GNUTLS_KX_ECDHE_ECDSA: ECDHE-ECDSA key-exchange algorithm. * @GNUTLS_KX_ANON_DH: Anon-DH key-exchange algorithm. * @GNUTLS_KX_ANON_ECDH: Anon-ECDH key-exchange algorithm. * @GNUTLS_KX_SRP: SRP key-exchange algorithm. * @GNUTLS_KX_RSA_EXPORT: RSA-EXPORT key-exchange algorithm (defunc). * @GNUTLS_KX_SRP_RSA: SRP-RSA key-exchange algorithm. * @GNUTLS_KX_SRP_DSS: SRP-DSS key-exchange algorithm. * @GNUTLS_KX_PSK: PSK key-exchange algorithm. * @GNUTLS_KX_DHE_PSK: DHE-PSK key-exchange algorithm. * @GNUTLS_KX_ECDHE_PSK: ECDHE-PSK key-exchange algorithm. * @GNUTLS_KX_RSA_PSK: RSA-PSK key-exchange algorithm. * @GNUTLS_KX_VKO_GOST_12: VKO GOST R 34.10-2012 key-exchange algorithm. * * Enumeration of different key exchange algorithms. */ typedef enum { GNUTLS_KX_UNKNOWN = 0, GNUTLS_KX_RSA = 1, GNUTLS_KX_DHE_DSS = 2, GNUTLS_KX_DHE_RSA = 3, GNUTLS_KX_ANON_DH = 4, GNUTLS_KX_SRP = 5, GNUTLS_KX_RSA_EXPORT = 6, GNUTLS_KX_SRP_RSA = 7, GNUTLS_KX_SRP_DSS = 8, GNUTLS_KX_PSK = 9, GNUTLS_KX_DHE_PSK = 10, GNUTLS_KX_ANON_ECDH = 11, GNUTLS_KX_ECDHE_RSA = 12, GNUTLS_KX_ECDHE_ECDSA = 13, GNUTLS_KX_ECDHE_PSK = 14, GNUTLS_KX_RSA_PSK = 15, GNUTLS_KX_VKO_GOST_12 = 16 } gnutls_kx_algorithm_t; /** * gnutls_params_type_t: * @GNUTLS_PARAMS_RSA_EXPORT: Session RSA-EXPORT parameters (defunc). * @GNUTLS_PARAMS_DH: Session Diffie-Hellman parameters. * @GNUTLS_PARAMS_ECDH: Session Elliptic-Curve Diffie-Hellman parameters. * * Enumeration of different TLS session parameter types. */ typedef enum { GNUTLS_PARAMS_RSA_EXPORT = 1, GNUTLS_PARAMS_DH = 2, GNUTLS_PARAMS_ECDH = 3 } gnutls_params_type_t; /** * gnutls_credentials_type_t: * @GNUTLS_CRD_CERTIFICATE: Certificate credential. * @GNUTLS_CRD_ANON: Anonymous credential. * @GNUTLS_CRD_SRP: SRP credential. * @GNUTLS_CRD_PSK: PSK credential. * @GNUTLS_CRD_IA: IA credential. * * Enumeration of different credential types. */ typedef enum { GNUTLS_CRD_CERTIFICATE = 1, GNUTLS_CRD_ANON, GNUTLS_CRD_SRP, GNUTLS_CRD_PSK, GNUTLS_CRD_IA } gnutls_credentials_type_t; #define GNUTLS_MAC_SHA GNUTLS_MAC_SHA1 #define GNUTLS_DIG_SHA GNUTLS_DIG_SHA1 /** * gnutls_mac_algorithm_t: * @GNUTLS_MAC_UNKNOWN: Unknown MAC algorithm. * @GNUTLS_MAC_NULL: NULL MAC algorithm (empty output). * @GNUTLS_MAC_MD5: HMAC-MD5 algorithm. * @GNUTLS_MAC_SHA1: HMAC-SHA-1 algorithm. * @GNUTLS_MAC_RMD160: HMAC-RMD160 algorithm. * @GNUTLS_MAC_MD2: HMAC-MD2 algorithm. * @GNUTLS_MAC_SHA256: HMAC-SHA-256 algorithm. * @GNUTLS_MAC_SHA384: HMAC-SHA-384 algorithm. * @GNUTLS_MAC_SHA512: HMAC-SHA-512 algorithm. * @GNUTLS_MAC_SHA224: HMAC-SHA-224 algorithm. * @GNUTLS_MAC_MD5_SHA1: Combined MD5+SHA1 MAC placeholder. * @GNUTLS_MAC_GOSTR_94: HMAC GOST R 34.11-94 algorithm. * @GNUTLS_MAC_STREEBOG_256: HMAC GOST R 34.11-2001 (Streebog) algorithm, 256 bit. * @GNUTLS_MAC_STREEBOG_512: HMAC GOST R 34.11-2001 (Streebog) algorithm, 512 bit. * @GNUTLS_MAC_AEAD: MAC implicit through AEAD cipher. * @GNUTLS_MAC_UMAC_96: The UMAC-96 MAC algorithm (requires nonce). * @GNUTLS_MAC_UMAC_128: The UMAC-128 MAC algorithm (requires nonce). * @GNUTLS_MAC_AES_CMAC_128: The AES-CMAC-128 MAC algorithm. * @GNUTLS_MAC_AES_CMAC_256: The AES-CMAC-256 MAC algorithm. * @GNUTLS_MAC_AES_GMAC_128: The AES-GMAC-128 MAC algorithm (requires nonce). * @GNUTLS_MAC_AES_GMAC_192: The AES-GMAC-192 MAC algorithm (requires nonce). * @GNUTLS_MAC_AES_GMAC_256: The AES-GMAC-256 MAC algorithm (requires nonce). * @GNUTLS_MAC_SHA3_224: Reserved; unimplemented. * @GNUTLS_MAC_SHA3_256: Reserved; unimplemented. * @GNUTLS_MAC_SHA3_384: Reserved; unimplemented. * @GNUTLS_MAC_SHA3_512: Reserved; unimplemented. * @GNUTLS_MAC_GOST28147_TC26Z_IMIT: The GOST 28147-89 working in IMIT mode with TC26 Z S-box. * @GNUTLS_MAC_SHAKE_128: Reserved; unimplemented. * @GNUTLS_MAC_SHAKE_256: Reserved; unimplemented. * @GNUTLS_MAC_MAGMA_OMAC: GOST R 34.12-2015 (Magma) in OMAC (CMAC) mode. * @GNUTLS_MAC_KUZNYECHIK_OMAC: GOST R 34.12-2015 (Kuznyechik) in OMAC (CMAC) mode. * * Enumeration of different Message Authentication Code (MAC) * algorithms. */ typedef enum { GNUTLS_MAC_UNKNOWN = 0, GNUTLS_MAC_NULL = 1, GNUTLS_MAC_MD5 = 2, GNUTLS_MAC_SHA1 = 3, GNUTLS_MAC_RMD160 = 4, GNUTLS_MAC_MD2 = 5, GNUTLS_MAC_SHA256 = 6, GNUTLS_MAC_SHA384 = 7, GNUTLS_MAC_SHA512 = 8, GNUTLS_MAC_SHA224 = 9, GNUTLS_MAC_SHA3_224 = 10, /* reserved: no implementation */ GNUTLS_MAC_SHA3_256 = 11, /* reserved: no implementation */ GNUTLS_MAC_SHA3_384 = 12, /* reserved: no implementation */ GNUTLS_MAC_SHA3_512 = 13, /* reserved: no implementation */ GNUTLS_MAC_MD5_SHA1 = 14, /* reserved: no implementation */ GNUTLS_MAC_GOSTR_94 = 15, GNUTLS_MAC_STREEBOG_256 = 16, GNUTLS_MAC_STREEBOG_512 = 17, /* If you add anything here, make sure you align with gnutls_digest_algorithm_t. */ GNUTLS_MAC_AEAD = 200, /* indicates that MAC is on the cipher */ GNUTLS_MAC_UMAC_96 = 201, GNUTLS_MAC_UMAC_128 = 202, GNUTLS_MAC_AES_CMAC_128 = 203, GNUTLS_MAC_AES_CMAC_256 = 204, GNUTLS_MAC_AES_GMAC_128 = 205, GNUTLS_MAC_AES_GMAC_192 = 206, GNUTLS_MAC_AES_GMAC_256 = 207, GNUTLS_MAC_GOST28147_TC26Z_IMIT = 208, GNUTLS_MAC_SHAKE_128 = 209, GNUTLS_MAC_SHAKE_256 = 210, GNUTLS_MAC_MAGMA_OMAC = 211, GNUTLS_MAC_KUZNYECHIK_OMAC = 212 } gnutls_mac_algorithm_t; /** * gnutls_digest_algorithm_t: * @GNUTLS_DIG_UNKNOWN: Unknown hash algorithm. * @GNUTLS_DIG_NULL: NULL hash algorithm (empty output). * @GNUTLS_DIG_MD5: MD5 algorithm. * @GNUTLS_DIG_SHA1: SHA-1 algorithm. * @GNUTLS_DIG_RMD160: RMD160 algorithm. * @GNUTLS_DIG_MD2: MD2 algorithm. * @GNUTLS_DIG_SHA256: SHA-256 algorithm. * @GNUTLS_DIG_SHA384: SHA-384 algorithm. * @GNUTLS_DIG_SHA512: SHA-512 algorithm. * @GNUTLS_DIG_SHA224: SHA-224 algorithm. * @GNUTLS_DIG_SHA3_224: SHA3-224 algorithm. * @GNUTLS_DIG_SHA3_256: SHA3-256 algorithm. * @GNUTLS_DIG_SHA3_384: SHA3-384 algorithm. * @GNUTLS_DIG_SHA3_512: SHA3-512 algorithm. * @GNUTLS_DIG_MD5_SHA1: Combined MD5+SHA1 algorithm. * @GNUTLS_DIG_GOSTR_94: GOST R 34.11-94 algorithm. * @GNUTLS_DIG_STREEBOG_256: GOST R 34.11-2001 (Streebog) algorithm, 256 bit. * @GNUTLS_DIG_STREEBOG_512: GOST R 34.11-2001 (Streebog) algorithm, 512 bit. * @GNUTLS_DIG_SHAKE_128: Reserved; unimplemented. * @GNUTLS_DIG_SHAKE_256: Reserved; unimplemented. * * Enumeration of different digest (hash) algorithms. */ typedef enum { GNUTLS_DIG_UNKNOWN = GNUTLS_MAC_UNKNOWN, GNUTLS_DIG_NULL = GNUTLS_MAC_NULL, GNUTLS_DIG_MD5 = GNUTLS_MAC_MD5, GNUTLS_DIG_SHA1 = GNUTLS_MAC_SHA1, GNUTLS_DIG_RMD160 = GNUTLS_MAC_RMD160, GNUTLS_DIG_MD2 = GNUTLS_MAC_MD2, GNUTLS_DIG_SHA256 = GNUTLS_MAC_SHA256, GNUTLS_DIG_SHA384 = GNUTLS_MAC_SHA384, GNUTLS_DIG_SHA512 = GNUTLS_MAC_SHA512, GNUTLS_DIG_SHA224 = GNUTLS_MAC_SHA224, GNUTLS_DIG_SHA3_224 = GNUTLS_MAC_SHA3_224, GNUTLS_DIG_SHA3_256 = GNUTLS_MAC_SHA3_256, GNUTLS_DIG_SHA3_384 = GNUTLS_MAC_SHA3_384, GNUTLS_DIG_SHA3_512 = GNUTLS_MAC_SHA3_512, GNUTLS_DIG_MD5_SHA1 = GNUTLS_MAC_MD5_SHA1, GNUTLS_DIG_GOSTR_94 = GNUTLS_MAC_GOSTR_94, GNUTLS_DIG_STREEBOG_256 = GNUTLS_MAC_STREEBOG_256, GNUTLS_DIG_STREEBOG_512 = GNUTLS_MAC_STREEBOG_512, GNUTLS_DIG_SHAKE_128 = GNUTLS_MAC_SHAKE_128, GNUTLS_DIG_SHAKE_256 = GNUTLS_MAC_SHAKE_256 /* If you add anything here, make sure you align with gnutls_mac_algorithm_t. */ } gnutls_digest_algorithm_t; /* exported for other gnutls headers. This is the maximum number of * algorithms (ciphers, kx or macs). */ #define GNUTLS_MAX_ALGORITHM_NUM 128 #define GNUTLS_MAX_SESSION_ID_SIZE 32 /** * gnutls_compression_method_t: * @GNUTLS_COMP_UNKNOWN: Unknown compression method. * @GNUTLS_COMP_NULL: The NULL compression method (no compression). * @GNUTLS_COMP_DEFLATE: The DEFLATE compression method from zlib. * @GNUTLS_COMP_ZLIB: Same as %GNUTLS_COMP_DEFLATE. * @GNUTLS_COMP_BROTLI: Brotli compression method. * @GNUTLS_COMP_ZSTD: Zstandard compression method. * * Enumeration of different TLS compression methods. */ typedef enum { GNUTLS_COMP_UNKNOWN = 0, GNUTLS_COMP_NULL = 1, GNUTLS_COMP_DEFLATE = 2, GNUTLS_COMP_ZLIB = GNUTLS_COMP_DEFLATE, GNUTLS_COMP_BROTLI = 3, GNUTLS_COMP_ZSTD = 4 } gnutls_compression_method_t; /** * gnutls_init_flags_t: * * @GNUTLS_SERVER: Connection end is a server. * @GNUTLS_CLIENT: Connection end is a client. * @GNUTLS_DATAGRAM: Connection is datagram oriented (DTLS). Since 3.0.0. * @GNUTLS_NONBLOCK: Connection should not block. Since 3.0.0. * @GNUTLS_NO_SIGNAL: In systems where SIGPIPE is delivered on send, it will be disabled. That flag has effect in systems which support the MSG_NOSIGNAL sockets flag (since 3.4.2). * @GNUTLS_NO_EXTENSIONS: Do not enable any TLS extensions by default (since 3.1.2). As TLS 1.2 and later require extensions this option is considered obsolete and should not be used. * @GNUTLS_NO_REPLAY_PROTECTION: Disable any replay protection in DTLS. This must only be used if replay protection is achieved using other means. Since 3.2.2. * @GNUTLS_ALLOW_ID_CHANGE: Allow the peer to replace its certificate, or change its ID during a rehandshake. This change is often used in attacks and thus prohibited by default. Since 3.5.0. * @GNUTLS_ENABLE_FALSE_START: Enable the TLS false start on client side if the negotiated ciphersuites allow it. This will enable sending data prior to the handshake being complete, and may introduce a risk of crypto failure when combined with certain key exchanged; for that GnuTLS may not enable that option in ciphersuites that are known to be not safe for false start. Since 3.5.0. * @GNUTLS_ENABLE_EARLY_START: Under TLS1.3 allow the server to return earlier than the full handshake * finish; similarly to false start the handshake will be completed once data are received by the * client, while the server is able to transmit sooner. This is not enabled by default as it could * break certain existing server assumptions and use-cases. Since 3.6.4. * @GNUTLS_ENABLE_EARLY_DATA: Under TLS1.3 allow the server to receive early data sent as part of the initial ClientHello (0-RTT). * This can also be used to explicitly indicate that the client will send early data. * This is not enabled by default as early data has weaker security properties than other data. Since 3.6.5. * @GNUTLS_FORCE_CLIENT_CERT: When in client side and only a single cert is specified, send that certificate irrespective of the issuers expected by the server. Since 3.5.0. * @GNUTLS_NO_TICKETS: Flag to indicate that the session should not use resumption with session tickets. * @GNUTLS_NO_TICKETS_TLS12: Flag to indicate that the session should not use resumption with session tickets. This flag only has effect if TLS 1.2 is used. * @GNUTLS_KEY_SHARE_TOP3: Generate key shares for the top-3 different groups which are enabled. * That is, as each group is associated with a key type (EC, finite field, x25519), generate * three keys using %GNUTLS_PK_DH, %GNUTLS_PK_EC, %GNUTLS_PK_ECDH_X25519 if all of them are enabled. * @GNUTLS_KEY_SHARE_TOP2: Generate key shares for the top-2 different groups which are enabled. * For example (ECDH + x25519). This is the default. * @GNUTLS_KEY_SHARE_TOP: Generate key share for the first group which is enabled. * For example x25519. This option is the most performant for client (less CPU spent * generating keys), but if the server doesn't support the advertized option it may * result to more roundtrips needed to discover the server's choice. * @GNUTLS_NO_AUTO_REKEY: Disable auto-rekeying under TLS1.3. If this option is not specified * gnutls will force a rekey after 2^24 records have been sent. * @GNUTLS_POST_HANDSHAKE_AUTH: Enable post handshake authentication for server and client. When set and * a server requests authentication after handshake %GNUTLS_E_REAUTH_REQUEST will be returned * by gnutls_record_recv(). A client should then call gnutls_reauth() to re-authenticate. * @GNUTLS_SAFE_PADDING_CHECK: Flag to indicate that the TLS 1.3 padding check will be done in a * safe way which doesn't leak the pad size based on GnuTLS processing time. This is of use to * applications which hide the length of transferred data via the TLS1.3 padding mechanism and * are already taking steps to hide the data processing time. This comes at a performance * penalty. * @GNUTLS_AUTO_REAUTH: Enable transparent re-authentication in client side when the server * requests to. That is, reauthentication is handled within gnutls_record_recv(), and * the %GNUTLS_E_REHANDSHAKE or %GNUTLS_E_REAUTH_REQUEST are not returned. This must be * enabled with %GNUTLS_POST_HANDSHAKE_AUTH for TLS1.3. Enabling this flag requires to restore * interrupted calls to gnutls_record_recv() based on the output of gnutls_record_get_direction(), * since gnutls_record_recv() could be interrupted when sending when this flag is enabled. * Note this flag may not be used if you are using the same session for sending and receiving * in different threads. * @GNUTLS_ENABLE_RAWPK: Allows raw public-keys to be negotiated during the handshake. Since 3.6.6. * @GNUTLS_NO_AUTO_SEND_TICKET: Under TLS1.3 disable auto-sending of * session tickets during the handshake. * @GNUTLS_NO_END_OF_EARLY_DATA: Under TLS1.3 suppress sending EndOfEarlyData message. Since 3.7.2. * * Enumeration of different flags for gnutls_init() function. All the flags * can be combined except @GNUTLS_SERVER and @GNUTLS_CLIENT which are mutually * exclusive. * * The key share options relate to the TLS 1.3 key share extension * which is a speculative key generation expecting that the server * would support the generated key. */ typedef enum { GNUTLS_SERVER = 1, GNUTLS_CLIENT = (1<<1), GNUTLS_DATAGRAM = (1<<2), GNUTLS_NONBLOCK = (1<<3), GNUTLS_NO_EXTENSIONS = (1<<4), GNUTLS_NO_REPLAY_PROTECTION = (1<<5), GNUTLS_NO_SIGNAL = (1<<6), GNUTLS_ALLOW_ID_CHANGE = (1<<7), GNUTLS_ENABLE_FALSE_START = (1<<8), GNUTLS_FORCE_CLIENT_CERT = (1<<9), GNUTLS_NO_TICKETS = (1<<10), GNUTLS_KEY_SHARE_TOP = (1<<11), GNUTLS_KEY_SHARE_TOP2 = (1<<12), GNUTLS_KEY_SHARE_TOP3 = (1<<13), GNUTLS_POST_HANDSHAKE_AUTH = (1<<14), GNUTLS_NO_AUTO_REKEY = (1<<15), GNUTLS_SAFE_PADDING_CHECK = (1<<16), GNUTLS_ENABLE_EARLY_START = (1<<17), GNUTLS_ENABLE_RAWPK = (1<<18), GNUTLS_AUTO_REAUTH = (1<<19), GNUTLS_ENABLE_EARLY_DATA = (1<<20), GNUTLS_NO_AUTO_SEND_TICKET = (1<<21), GNUTLS_NO_END_OF_EARLY_DATA = (1<<22), GNUTLS_NO_TICKETS_TLS12 = (1<<23) } gnutls_init_flags_t; /* compatibility defines (previous versions of gnutls * used defines instead of enumerated values). */ #define GNUTLS_SERVER (1) #define GNUTLS_CLIENT (1<<1) #define GNUTLS_DATAGRAM (1<<2) #define GNUTLS_NONBLOCK (1<<3) #define GNUTLS_NO_EXTENSIONS (1<<4) #define GNUTLS_NO_REPLAY_PROTECTION (1<<5) #define GNUTLS_NO_SIGNAL (1<<6) #define GNUTLS_ALLOW_ID_CHANGE (1<<7) #define GNUTLS_ENABLE_FALSE_START (1<<8) #define GNUTLS_FORCE_CLIENT_CERT (1<<9) #define GNUTLS_NO_TICKETS (1<<10) #define GNUTLS_ENABLE_CERT_TYPE_NEG 0 // Here for compatibility reasons /** * gnutls_alert_level_t: * @GNUTLS_AL_WARNING: Alert of warning severity. * @GNUTLS_AL_FATAL: Alert of fatal severity. * * Enumeration of different TLS alert severities. */ typedef enum { GNUTLS_AL_WARNING = 1, GNUTLS_AL_FATAL } gnutls_alert_level_t; /** * gnutls_alert_description_t: * @GNUTLS_A_CLOSE_NOTIFY: Close notify. * @GNUTLS_A_UNEXPECTED_MESSAGE: Unexpected message. * @GNUTLS_A_BAD_RECORD_MAC: Bad record MAC. * @GNUTLS_A_DECRYPTION_FAILED: Decryption failed. * @GNUTLS_A_RECORD_OVERFLOW: Record overflow. * @GNUTLS_A_DECOMPRESSION_FAILURE: Decompression failed. * @GNUTLS_A_HANDSHAKE_FAILURE: Handshake failed. * @GNUTLS_A_SSL3_NO_CERTIFICATE: No certificate. * @GNUTLS_A_BAD_CERTIFICATE: Certificate is bad. * @GNUTLS_A_UNSUPPORTED_CERTIFICATE: Certificate is not supported. * @GNUTLS_A_CERTIFICATE_REVOKED: Certificate was revoked. * @GNUTLS_A_CERTIFICATE_EXPIRED: Certificate is expired. * @GNUTLS_A_CERTIFICATE_UNKNOWN: Unknown certificate. * @GNUTLS_A_ILLEGAL_PARAMETER: Illegal parameter. * @GNUTLS_A_UNKNOWN_CA: CA is unknown. * @GNUTLS_A_ACCESS_DENIED: Access was denied. * @GNUTLS_A_DECODE_ERROR: Decode error. * @GNUTLS_A_DECRYPT_ERROR: Decrypt error. * @GNUTLS_A_EXPORT_RESTRICTION: Export restriction. * @GNUTLS_A_PROTOCOL_VERSION: Error in protocol version. * @GNUTLS_A_INSUFFICIENT_SECURITY: Insufficient security. * @GNUTLS_A_INTERNAL_ERROR: Internal error. * @GNUTLS_A_INAPPROPRIATE_FALLBACK: Inappropriate fallback, * @GNUTLS_A_USER_CANCELED: User canceled. * @GNUTLS_A_NO_RENEGOTIATION: No renegotiation is allowed. * @GNUTLS_A_MISSING_EXTENSION: An extension was expected but was not seen * @GNUTLS_A_UNSUPPORTED_EXTENSION: An unsupported extension was * sent. * @GNUTLS_A_CERTIFICATE_UNOBTAINABLE: Could not retrieve the * specified certificate. * @GNUTLS_A_UNRECOGNIZED_NAME: The server name sent was not * recognized. * @GNUTLS_A_UNKNOWN_PSK_IDENTITY: The SRP/PSK username is missing * or not known. * @GNUTLS_A_CERTIFICATE_REQUIRED: Certificate is required. * @GNUTLS_A_NO_APPLICATION_PROTOCOL: The ALPN protocol requested is * not supported by the peer. * * Enumeration of different TLS alerts. */ typedef enum { GNUTLS_A_CLOSE_NOTIFY, GNUTLS_A_UNEXPECTED_MESSAGE = 10, GNUTLS_A_BAD_RECORD_MAC = 20, GNUTLS_A_DECRYPTION_FAILED, GNUTLS_A_RECORD_OVERFLOW, GNUTLS_A_DECOMPRESSION_FAILURE = 30, GNUTLS_A_HANDSHAKE_FAILURE = 40, GNUTLS_A_SSL3_NO_CERTIFICATE = 41, GNUTLS_A_BAD_CERTIFICATE = 42, GNUTLS_A_UNSUPPORTED_CERTIFICATE, GNUTLS_A_CERTIFICATE_REVOKED, GNUTLS_A_CERTIFICATE_EXPIRED, GNUTLS_A_CERTIFICATE_UNKNOWN, GNUTLS_A_ILLEGAL_PARAMETER, GNUTLS_A_UNKNOWN_CA, GNUTLS_A_ACCESS_DENIED, GNUTLS_A_DECODE_ERROR = 50, GNUTLS_A_DECRYPT_ERROR, GNUTLS_A_EXPORT_RESTRICTION = 60, GNUTLS_A_PROTOCOL_VERSION = 70, GNUTLS_A_INSUFFICIENT_SECURITY, GNUTLS_A_INTERNAL_ERROR = 80, GNUTLS_A_INAPPROPRIATE_FALLBACK = 86, GNUTLS_A_USER_CANCELED = 90, GNUTLS_A_NO_RENEGOTIATION = 100, GNUTLS_A_MISSING_EXTENSION = 109, GNUTLS_A_UNSUPPORTED_EXTENSION = 110, GNUTLS_A_CERTIFICATE_UNOBTAINABLE = 111, GNUTLS_A_UNRECOGNIZED_NAME = 112, GNUTLS_A_UNKNOWN_PSK_IDENTITY = 115, GNUTLS_A_CERTIFICATE_REQUIRED = 116, GNUTLS_A_NO_APPLICATION_PROTOCOL = 120, GNUTLS_A_MAX = GNUTLS_A_NO_APPLICATION_PROTOCOL } gnutls_alert_description_t; /** * gnutls_handshake_description_t: * @GNUTLS_HANDSHAKE_HELLO_REQUEST: Hello request. * @GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST: DTLS Hello verify request. * @GNUTLS_HANDSHAKE_CLIENT_HELLO: Client hello. * @GNUTLS_HANDSHAKE_SERVER_HELLO: Server hello. * @GNUTLS_HANDSHAKE_END_OF_EARLY_DATA: End of early data. * @GNUTLS_HANDSHAKE_HELLO_RETRY_REQUEST: Hello retry request. * @GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: New session ticket. * @GNUTLS_HANDSHAKE_CERTIFICATE_PKT: Certificate packet. * @GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE: Server key exchange. * @GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST: Certificate request. * @GNUTLS_HANDSHAKE_SERVER_HELLO_DONE: Server hello done. * @GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY: Certificate verify. * @GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE: Client key exchange. * @GNUTLS_HANDSHAKE_FINISHED: Finished. * @GNUTLS_HANDSHAKE_CERTIFICATE_STATUS: Certificate status (OCSP). * @GNUTLS_HANDSHAKE_KEY_UPDATE: TLS1.3 key update message. * @GNUTLS_HANDSHAKE_COMPRESSED_CERTIFICATE_PKT: Compressed certificate packet. * @GNUTLS_HANDSHAKE_SUPPLEMENTAL: Supplemental. * @GNUTLS_HANDSHAKE_CHANGE_CIPHER_SPEC: Change Cipher Spec. * @GNUTLS_HANDSHAKE_CLIENT_HELLO_V2: SSLv2 Client Hello. * @GNUTLS_HANDSHAKE_ENCRYPTED_EXTENSIONS: Encrypted extensions message. * * Enumeration of different TLS handshake packets. */ typedef enum { GNUTLS_HANDSHAKE_HELLO_REQUEST = 0, GNUTLS_HANDSHAKE_CLIENT_HELLO = 1, GNUTLS_HANDSHAKE_SERVER_HELLO = 2, GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST = 3, GNUTLS_HANDSHAKE_NEW_SESSION_TICKET = 4, GNUTLS_HANDSHAKE_END_OF_EARLY_DATA = 5, GNUTLS_HANDSHAKE_ENCRYPTED_EXTENSIONS = 8, GNUTLS_HANDSHAKE_CERTIFICATE_PKT = 11, GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE = 12, GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST = 13, GNUTLS_HANDSHAKE_SERVER_HELLO_DONE = 14, GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY = 15, GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE = 16, GNUTLS_HANDSHAKE_FINISHED = 20, GNUTLS_HANDSHAKE_CERTIFICATE_STATUS = 22, GNUTLS_HANDSHAKE_SUPPLEMENTAL = 23, GNUTLS_HANDSHAKE_KEY_UPDATE = 24, GNUTLS_HANDSHAKE_COMPRESSED_CERTIFICATE_PKT = 25, GNUTLS_HANDSHAKE_CHANGE_CIPHER_SPEC = 254, GNUTLS_HANDSHAKE_CLIENT_HELLO_V2 = 1024, GNUTLS_HANDSHAKE_HELLO_RETRY_REQUEST = 1025, } gnutls_handshake_description_t; #define GNUTLS_HANDSHAKE_ANY ((unsigned int)-1) const char *gnutls_handshake_description_get_name(gnutls_handshake_description_t type); /** * gnutls_certificate_status_t: * @GNUTLS_CERT_INVALID: The certificate is not signed by one of the * known authorities or the signature is invalid (deprecated by the flags * %GNUTLS_CERT_SIGNATURE_FAILURE and %GNUTLS_CERT_SIGNER_NOT_FOUND). * @GNUTLS_CERT_SIGNATURE_FAILURE: The signature verification failed. * @GNUTLS_CERT_REVOKED: Certificate is revoked by its authority. In X.509 this will be * set only if CRLs are checked. * @GNUTLS_CERT_SIGNER_NOT_FOUND: The certificate's issuer is not known. * This is the case if the issuer is not included in the trusted certificate list. * @GNUTLS_CERT_SIGNER_NOT_CA: The certificate's signer was not a CA. This * may happen if this was a version 1 certificate, which is common with * some CAs, or a version 3 certificate without the basic constrains extension. * @GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE: The certificate's signer constraints were * violated. * @GNUTLS_CERT_INSECURE_ALGORITHM: The certificate was signed using an insecure * algorithm such as MD2 or MD5. These algorithms have been broken and * should not be trusted. * @GNUTLS_CERT_NOT_ACTIVATED: The certificate is not yet activated. * @GNUTLS_CERT_EXPIRED: The certificate has expired. * @GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED: The revocation data are old and have been superseded. * @GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE: The revocation data have a future issue date. * @GNUTLS_CERT_UNEXPECTED_OWNER: The owner is not the expected one. * @GNUTLS_CERT_MISMATCH: The certificate presented isn't the expected one (TOFU) * @GNUTLS_CERT_PURPOSE_MISMATCH: The certificate or an intermediate does not match the intended purpose (extended key usage). * @GNUTLS_CERT_MISSING_OCSP_STATUS: The certificate requires the server to send the certificate status, but no status was received. * @GNUTLS_CERT_INVALID_OCSP_STATUS: The received OCSP status response is invalid. * @GNUTLS_CERT_UNKNOWN_CRIT_EXTENSIONS: The certificate has extensions marked as critical which are not supported. * * Enumeration of certificate status codes. Note that the status * bits may have different meanings in OpenPGP keys and X.509 * certificate verification. */ typedef enum { GNUTLS_CERT_INVALID = 1 << 1, GNUTLS_CERT_REVOKED = 1 << 5, GNUTLS_CERT_SIGNER_NOT_FOUND = 1 << 6, GNUTLS_CERT_SIGNER_NOT_CA = 1 << 7, GNUTLS_CERT_INSECURE_ALGORITHM = 1 << 8, GNUTLS_CERT_NOT_ACTIVATED = 1 << 9, GNUTLS_CERT_EXPIRED = 1 << 10, GNUTLS_CERT_SIGNATURE_FAILURE = 1 << 11, GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED = 1 << 12, GNUTLS_CERT_UNEXPECTED_OWNER = 1 << 14, GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE = 1 << 15, GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE = 1 << 16, GNUTLS_CERT_MISMATCH = 1 << 17, GNUTLS_CERT_PURPOSE_MISMATCH = 1 << 18, GNUTLS_CERT_MISSING_OCSP_STATUS = 1 << 19, GNUTLS_CERT_INVALID_OCSP_STATUS = 1 << 20, GNUTLS_CERT_UNKNOWN_CRIT_EXTENSIONS = 1 << 21 } gnutls_certificate_status_t; /** * gnutls_certificate_request_t: * @GNUTLS_CERT_IGNORE: Ignore certificate. * @GNUTLS_CERT_REQUEST: Request certificate. * @GNUTLS_CERT_REQUIRE: Require certificate. * * Enumeration of certificate request types. */ typedef enum { GNUTLS_CERT_IGNORE = 0, GNUTLS_CERT_REQUEST = 1, GNUTLS_CERT_REQUIRE = 2 } gnutls_certificate_request_t; /** * gnutls_openpgp_crt_status_t: * @GNUTLS_OPENPGP_CERT: Send entire certificate. * @GNUTLS_OPENPGP_CERT_FINGERPRINT: Send only certificate fingerprint. * * Enumeration of ways to send OpenPGP certificate. */ typedef enum { GNUTLS_OPENPGP_CERT = 0, GNUTLS_OPENPGP_CERT_FINGERPRINT = 1 } gnutls_openpgp_crt_status_t; /** * gnutls_close_request_t: * @GNUTLS_SHUT_RDWR: Disallow further receives/sends. * @GNUTLS_SHUT_WR: Disallow further sends. * * Enumeration of how TLS session should be terminated. See gnutls_bye(). */ typedef enum { GNUTLS_SHUT_RDWR = 0, GNUTLS_SHUT_WR = 1 } gnutls_close_request_t; /** * gnutls_protocol_t: * @GNUTLS_SSL3: SSL version 3.0. * @GNUTLS_TLS1_0: TLS version 1.0. * @GNUTLS_TLS1: Same as %GNUTLS_TLS1_0. * @GNUTLS_TLS1_1: TLS version 1.1. * @GNUTLS_TLS1_2: TLS version 1.2. * @GNUTLS_TLS1_3: TLS version 1.3. * @GNUTLS_DTLS1_0: DTLS version 1.0. * @GNUTLS_DTLS1_2: DTLS version 1.2. * @GNUTLS_DTLS0_9: DTLS version 0.9 (Cisco AnyConnect / OpenSSL 0.9.8e). * @GNUTLS_TLS_VERSION_MAX: Maps to the highest supported TLS version. * @GNUTLS_DTLS_VERSION_MAX: Maps to the highest supported DTLS version. * @GNUTLS_VERSION_UNKNOWN: Unknown SSL/TLS version. * * Enumeration of different SSL/TLS protocol versions. */ typedef enum { GNUTLS_SSL3 = 1, GNUTLS_TLS1_0 = 2, GNUTLS_TLS1 = GNUTLS_TLS1_0, GNUTLS_TLS1_1 = 3, GNUTLS_TLS1_2 = 4, GNUTLS_TLS1_3 = 5, GNUTLS_DTLS0_9 = 200, GNUTLS_DTLS1_0 = 201, /* 201 */ GNUTLS_DTLS1_2 = 202, GNUTLS_DTLS_VERSION_MIN = GNUTLS_DTLS0_9, GNUTLS_DTLS_VERSION_MAX = GNUTLS_DTLS1_2, GNUTLS_TLS_VERSION_MAX = GNUTLS_TLS1_3, GNUTLS_VERSION_UNKNOWN = 0xff /* change it to 0xffff */ } gnutls_protocol_t; #define GNUTLS_CRT_RAW GNUTLS_CRT_RAWPK /** * gnutls_certificate_type_t: * @GNUTLS_CRT_UNKNOWN: Unknown certificate type. * @GNUTLS_CRT_X509: X.509 Certificate. * @GNUTLS_CRT_OPENPGP: OpenPGP certificate. * @GNUTLS_CRT_RAWPK: Raw public-key (SubjectPublicKeyInfo) * * Enumeration of different certificate types. */ typedef enum { GNUTLS_CRT_UNKNOWN = 0, GNUTLS_CRT_X509 = 1, GNUTLS_CRT_OPENPGP = 2, GNUTLS_CRT_RAWPK = 3, GNUTLS_CRT_MAX = GNUTLS_CRT_RAWPK } gnutls_certificate_type_t; /** * gnutls_x509_crt_fmt_t: * @GNUTLS_X509_FMT_DER: X.509 certificate in DER format (binary). * @GNUTLS_X509_FMT_PEM: X.509 certificate in PEM format (text). * * Enumeration of different certificate encoding formats. */ typedef enum { GNUTLS_X509_FMT_DER = 0, GNUTLS_X509_FMT_PEM = 1 } gnutls_x509_crt_fmt_t; /** * gnutls_certificate_print_formats_t: * @GNUTLS_CRT_PRINT_FULL: Full information about certificate. * @GNUTLS_CRT_PRINT_FULL_NUMBERS: Full information about certificate and include easy to parse public key parameters. * @GNUTLS_CRT_PRINT_COMPACT: Information about certificate name in one line, plus identification of the public key. * @GNUTLS_CRT_PRINT_ONELINE: Information about certificate in one line. * @GNUTLS_CRT_PRINT_UNSIGNED_FULL: All info for an unsigned certificate. * * Enumeration of different certificate printing variants. */ typedef enum gnutls_certificate_print_formats { GNUTLS_CRT_PRINT_FULL = 0, GNUTLS_CRT_PRINT_ONELINE = 1, GNUTLS_CRT_PRINT_UNSIGNED_FULL = 2, GNUTLS_CRT_PRINT_COMPACT = 3, GNUTLS_CRT_PRINT_FULL_NUMBERS = 4 } gnutls_certificate_print_formats_t; #define GNUTLS_PK_ECC GNUTLS_PK_ECDSA #define GNUTLS_PK_EC GNUTLS_PK_ECDSA #define GNUTLS_PK_ECDHX GNUTLS_PK_ECDH_X25519 /** * gnutls_pk_algorithm_t: * @GNUTLS_PK_UNKNOWN: Unknown public-key algorithm. * @GNUTLS_PK_RSA: RSA public-key algorithm. * @GNUTLS_PK_RSA_PSS: RSA public-key algorithm, with PSS padding. * @GNUTLS_PK_DSA: DSA public-key algorithm. * @GNUTLS_PK_DH: Diffie-Hellman algorithm. Used to generate parameters. * @GNUTLS_PK_ECDSA: Elliptic curve algorithm. These parameters are compatible with the ECDSA and ECDH algorithm. * @GNUTLS_PK_ECDH_X25519: Elliptic curve algorithm, restricted to ECDH as per rfc7748. * @GNUTLS_PK_EDDSA_ED25519: Edwards curve Digital signature algorithm. Used with SHA512 on signatures. * @GNUTLS_PK_GOST_01: GOST R 34.10-2001 algorithm per rfc5832. * @GNUTLS_PK_GOST_12_256: GOST R 34.10-2012 algorithm, 256-bit key per rfc7091. * @GNUTLS_PK_GOST_12_512: GOST R 34.10-2012 algorithm, 512-bit key per rfc7091. * @GNUTLS_PK_ECDH_X448: Elliptic curve algorithm, restricted to ECDH as per rfc7748. * @GNUTLS_PK_EDDSA_ED448: Edwards curve Digital signature algorithm. Used with SHAKE256 on signatures. * * Enumeration of different public-key algorithms. */ typedef enum { GNUTLS_PK_UNKNOWN = 0, GNUTLS_PK_RSA = 1, GNUTLS_PK_DSA = 2, GNUTLS_PK_DH = 3, GNUTLS_PK_ECDSA = 4, GNUTLS_PK_ECDH_X25519 = 5, GNUTLS_PK_RSA_PSS = 6, GNUTLS_PK_EDDSA_ED25519 = 7, GNUTLS_PK_GOST_01 = 8, GNUTLS_PK_GOST_12_256 = 9, GNUTLS_PK_GOST_12_512 = 10, GNUTLS_PK_ECDH_X448 = 11, GNUTLS_PK_EDDSA_ED448 = 12, GNUTLS_PK_MAX = GNUTLS_PK_EDDSA_ED448 } gnutls_pk_algorithm_t; const char *gnutls_pk_algorithm_get_name(gnutls_pk_algorithm_t algorithm); /** * gnutls_sign_algorithm_t: * @GNUTLS_SIGN_UNKNOWN: Unknown signature algorithm. * @GNUTLS_SIGN_RSA_RAW: Digital signature algorithm RSA with DigestInfo formatted data * @GNUTLS_SIGN_RSA_SHA1: Digital signature algorithm RSA with SHA-1 * @GNUTLS_SIGN_RSA_SHA: Same as %GNUTLS_SIGN_RSA_SHA1. * @GNUTLS_SIGN_DSA_SHA1: Digital signature algorithm DSA with SHA-1 * @GNUTLS_SIGN_DSA_SHA224: Digital signature algorithm DSA with SHA-224 * @GNUTLS_SIGN_DSA_SHA256: Digital signature algorithm DSA with SHA-256 * @GNUTLS_SIGN_DSA_SHA384: Digital signature algorithm DSA with SHA-384 * @GNUTLS_SIGN_DSA_SHA512: Digital signature algorithm DSA with SHA-512 * @GNUTLS_SIGN_DSA_SHA: Same as %GNUTLS_SIGN_DSA_SHA1. * @GNUTLS_SIGN_RSA_MD5: Digital signature algorithm RSA with MD5. * @GNUTLS_SIGN_RSA_MD2: Digital signature algorithm RSA with MD2. * @GNUTLS_SIGN_RSA_RMD160: Digital signature algorithm RSA with RMD-160. * @GNUTLS_SIGN_RSA_SHA256: Digital signature algorithm RSA with SHA-256. * @GNUTLS_SIGN_RSA_SHA384: Digital signature algorithm RSA with SHA-384. * @GNUTLS_SIGN_RSA_SHA512: Digital signature algorithm RSA with SHA-512. * @GNUTLS_SIGN_RSA_SHA224: Digital signature algorithm RSA with SHA-224. * @GNUTLS_SIGN_ECDSA_SHA1: ECDSA with SHA1. * @GNUTLS_SIGN_ECDSA_SHA224: Digital signature algorithm ECDSA with SHA-224. * @GNUTLS_SIGN_ECDSA_SHA256: Digital signature algorithm ECDSA with SHA-256. * @GNUTLS_SIGN_ECDSA_SHA384: Digital signature algorithm ECDSA with SHA-384. * @GNUTLS_SIGN_ECDSA_SHA512: Digital signature algorithm ECDSA with SHA-512. * @GNUTLS_SIGN_ECDSA_SECP256R1_SHA256: Digital signature algorithm ECDSA-SECP256R1 with SHA-256 (used in TLS 1.3 but not PKIX). * @GNUTLS_SIGN_ECDSA_SECP384R1_SHA384: Digital signature algorithm ECDSA-SECP384R1 with SHA-384 (used in TLS 1.3 but not PKIX). * @GNUTLS_SIGN_ECDSA_SECP521R1_SHA512: Digital signature algorithm ECDSA-SECP521R1 with SHA-512 (used in TLS 1.3 but not PKIX). * @GNUTLS_SIGN_ECDSA_SHA3_224: Digital signature algorithm ECDSA with SHA3-224. * @GNUTLS_SIGN_ECDSA_SHA3_256: Digital signature algorithm ECDSA with SHA3-256. * @GNUTLS_SIGN_ECDSA_SHA3_384: Digital signature algorithm ECDSA with SHA3-384. * @GNUTLS_SIGN_ECDSA_SHA3_512: Digital signature algorithm ECDSA with SHA3-512. * @GNUTLS_SIGN_DSA_SHA3_224: Digital signature algorithm DSA with SHA3-224. * @GNUTLS_SIGN_DSA_SHA3_256: Digital signature algorithm DSA with SHA3-256. * @GNUTLS_SIGN_DSA_SHA3_384: Digital signature algorithm DSA with SHA3-384. * @GNUTLS_SIGN_DSA_SHA3_512: Digital signature algorithm DSA with SHA3-512. * @GNUTLS_SIGN_RSA_SHA3_224: Digital signature algorithm RSA with SHA3-224. * @GNUTLS_SIGN_RSA_SHA3_256: Digital signature algorithm RSA with SHA3-256. * @GNUTLS_SIGN_RSA_SHA3_384: Digital signature algorithm RSA with SHA3-384. * @GNUTLS_SIGN_RSA_SHA3_512: Digital signature algorithm RSA with SHA3-512. * @GNUTLS_SIGN_RSA_PSS_RSAE_SHA256: Digital signature algorithm RSA with SHA-256, * with PSS padding (RSA PKCS#1 1.5 certificate). This signature is identical * to #GNUTLS_SIGN_RSA_PSS_SHA256, but they are distinct as the TLS1.3 protocol * treats them differently. * @GNUTLS_SIGN_RSA_PSS_RSAE_SHA384: Digital signature algorithm RSA with SHA-384, * with PSS padding (RSA PKCS#1 1.5 certificate). This signature is identical * to #GNUTLS_SIGN_RSA_PSS_SHA384, but they are distinct as the TLS1.3 protocol * treats them differently. * @GNUTLS_SIGN_RSA_PSS_RSAE_SHA512: Digital signature algorithm RSA with SHA-512, * with PSS padding (RSA PKCS#1 1.5 certificate). This signature is identical * to #GNUTLS_SIGN_RSA_PSS_SHA512, but they are distinct as the TLS1.3 protocol * treats them differently. * @GNUTLS_SIGN_RSA_PSS_SHA256: Digital signature algorithm RSA with SHA-256, with PSS padding (RSA-PSS certificate). * @GNUTLS_SIGN_RSA_PSS_SHA384: Digital signature algorithm RSA with SHA-384, with PSS padding (RSA-PSS certificate). * @GNUTLS_SIGN_RSA_PSS_SHA512: Digital signature algorithm RSA with SHA-512, with PSS padding (RSA-PSS certificate). * @GNUTLS_SIGN_EDDSA_ED25519: Digital signature algorithm EdDSA with Ed25519 curve. * @GNUTLS_SIGN_GOST_94: Digital signature algorithm GOST R 34.10-2001 with GOST R 34.11-94 * @GNUTLS_SIGN_GOST_256: Digital signature algorithm GOST R 34.10-2012 with GOST R 34.11-2012 256 bit * @GNUTLS_SIGN_GOST_512: Digital signature algorithm GOST R 34.10-2012 with GOST R 34.11-2012 512 bit * @GNUTLS_SIGN_EDDSA_ED448: Digital signature algorithm EdDSA with Ed448 curve. * * Enumeration of different digital signature algorithms. */ typedef enum { GNUTLS_SIGN_UNKNOWN = 0, GNUTLS_SIGN_RSA_SHA1 = 1, GNUTLS_SIGN_RSA_SHA = GNUTLS_SIGN_RSA_SHA1, GNUTLS_SIGN_DSA_SHA1 = 2, GNUTLS_SIGN_DSA_SHA = GNUTLS_SIGN_DSA_SHA1, GNUTLS_SIGN_RSA_MD5 = 3, GNUTLS_SIGN_RSA_MD2 = 4, GNUTLS_SIGN_RSA_RMD160 = 5, GNUTLS_SIGN_RSA_SHA256 = 6, GNUTLS_SIGN_RSA_SHA384 = 7, GNUTLS_SIGN_RSA_SHA512 = 8, GNUTLS_SIGN_RSA_SHA224 = 9, GNUTLS_SIGN_DSA_SHA224 = 10, GNUTLS_SIGN_DSA_SHA256 = 11, GNUTLS_SIGN_ECDSA_SHA1 = 12, GNUTLS_SIGN_ECDSA_SHA224 = 13, GNUTLS_SIGN_ECDSA_SHA256 = 14, GNUTLS_SIGN_ECDSA_SHA384 = 15, GNUTLS_SIGN_ECDSA_SHA512 = 16, GNUTLS_SIGN_DSA_SHA384 = 17, GNUTLS_SIGN_DSA_SHA512 = 18, GNUTLS_SIGN_ECDSA_SHA3_224 = 20, GNUTLS_SIGN_ECDSA_SHA3_256 = 21, GNUTLS_SIGN_ECDSA_SHA3_384 = 22, GNUTLS_SIGN_ECDSA_SHA3_512 = 23, GNUTLS_SIGN_DSA_SHA3_224 = 24, GNUTLS_SIGN_DSA_SHA3_256 = 25, GNUTLS_SIGN_DSA_SHA3_384 = 26, GNUTLS_SIGN_DSA_SHA3_512 = 27, GNUTLS_SIGN_RSA_SHA3_224 = 28, GNUTLS_SIGN_RSA_SHA3_256 = 29, GNUTLS_SIGN_RSA_SHA3_384 = 30, GNUTLS_SIGN_RSA_SHA3_512 = 31, GNUTLS_SIGN_RSA_PSS_SHA256 = 32, GNUTLS_SIGN_RSA_PSS_SHA384 = 33, GNUTLS_SIGN_RSA_PSS_SHA512 = 34, GNUTLS_SIGN_EDDSA_ED25519 = 35, GNUTLS_SIGN_RSA_RAW = 36, GNUTLS_SIGN_ECDSA_SECP256R1_SHA256 = 37, GNUTLS_SIGN_ECDSA_SECP384R1_SHA384 = 38, GNUTLS_SIGN_ECDSA_SECP521R1_SHA512 = 39, GNUTLS_SIGN_RSA_PSS_RSAE_SHA256 = 40, GNUTLS_SIGN_RSA_PSS_RSAE_SHA384 = 41, GNUTLS_SIGN_RSA_PSS_RSAE_SHA512 = 42, GNUTLS_SIGN_GOST_94 = 43, GNUTLS_SIGN_GOST_256 = 44, GNUTLS_SIGN_GOST_512 = 45, GNUTLS_SIGN_EDDSA_ED448 = 46, GNUTLS_SIGN_MAX = GNUTLS_SIGN_EDDSA_ED448 } gnutls_sign_algorithm_t; /** * gnutls_ecc_curve_t: * @GNUTLS_ECC_CURVE_INVALID: Cannot be known * @GNUTLS_ECC_CURVE_SECP192R1: the SECP192R1 curve * @GNUTLS_ECC_CURVE_SECP224R1: the SECP224R1 curve * @GNUTLS_ECC_CURVE_SECP256R1: the SECP256R1 curve * @GNUTLS_ECC_CURVE_SECP384R1: the SECP384R1 curve * @GNUTLS_ECC_CURVE_SECP521R1: the SECP521R1 curve * @GNUTLS_ECC_CURVE_X25519: the X25519 curve (ECDH only) * @GNUTLS_ECC_CURVE_ED25519: the Ed25519 curve * @GNUTLS_ECC_CURVE_GOST256CPA: GOST R 34.10 CryptoPro 256 A curve * @GNUTLS_ECC_CURVE_GOST256CPB: GOST R 34.10 CryptoPro 256 B curve * @GNUTLS_ECC_CURVE_GOST256CPC: GOST R 34.10 CryptoPro 256 C curve * @GNUTLS_ECC_CURVE_GOST256CPXA: GOST R 34.10 CryptoPro 256 XchA curve * @GNUTLS_ECC_CURVE_GOST256CPXB: GOST R 34.10 CryptoPro 256 XchB curve * @GNUTLS_ECC_CURVE_GOST512A: GOST R 34.10 TC26 512 A curve * @GNUTLS_ECC_CURVE_GOST512B: GOST R 34.10 TC26 512 B curve * @GNUTLS_ECC_CURVE_GOST512C: GOST R 34.10 TC26 512 C curve * @GNUTLS_ECC_CURVE_GOST256A: GOST R 34.10 TC26 256 A curve * @GNUTLS_ECC_CURVE_GOST256B: GOST R 34.10 TC26 256 B curve * @GNUTLS_ECC_CURVE_GOST256C: GOST R 34.10 TC26 256 C curve * @GNUTLS_ECC_CURVE_GOST256D: GOST R 34.10 TC26 256 D curve * @GNUTLS_ECC_CURVE_X448: the X448 curve (ECDH only) * @GNUTLS_ECC_CURVE_ED448: the Ed448 curve * * Enumeration of ECC curves. */ typedef enum { GNUTLS_ECC_CURVE_INVALID = 0, GNUTLS_ECC_CURVE_SECP224R1, GNUTLS_ECC_CURVE_SECP256R1, GNUTLS_ECC_CURVE_SECP384R1, GNUTLS_ECC_CURVE_SECP521R1, GNUTLS_ECC_CURVE_SECP192R1, GNUTLS_ECC_CURVE_X25519, GNUTLS_ECC_CURVE_ED25519, GNUTLS_ECC_CURVE_GOST256CPA, GNUTLS_ECC_CURVE_GOST256CPB, GNUTLS_ECC_CURVE_GOST256CPC, GNUTLS_ECC_CURVE_GOST256CPXA, GNUTLS_ECC_CURVE_GOST256CPXB, GNUTLS_ECC_CURVE_GOST512A, GNUTLS_ECC_CURVE_GOST512B, GNUTLS_ECC_CURVE_GOST512C, GNUTLS_ECC_CURVE_GOST256A, GNUTLS_ECC_CURVE_GOST256B, GNUTLS_ECC_CURVE_GOST256C, GNUTLS_ECC_CURVE_GOST256D, GNUTLS_ECC_CURVE_X448, GNUTLS_ECC_CURVE_ED448, GNUTLS_ECC_CURVE_MAX = GNUTLS_ECC_CURVE_ED448 } gnutls_ecc_curve_t; /** * gnutls_group_t: * @GNUTLS_GROUP_INVALID: Indicates unknown/invalid group * @GNUTLS_GROUP_SECP192R1: the SECP192R1 curve group (legacy, only for TLS 1.2 compatibility) * @GNUTLS_GROUP_SECP224R1: the SECP224R1 curve group (legacy, only for TLS 1.2 compatibility) * @GNUTLS_GROUP_SECP256R1: the SECP256R1 curve group * @GNUTLS_GROUP_SECP384R1: the SECP384R1 curve group * @GNUTLS_GROUP_SECP521R1: the SECP521R1 curve group * @GNUTLS_GROUP_X25519: the X25519 curve group * @GNUTLS_GROUP_GC256A: the GOST R 34.10 TC26 256 A curve group * @GNUTLS_GROUP_GC256B: the GOST R 34.10 TC26 256 B curve group * @GNUTLS_GROUP_GC256C: the GOST R 34.10 TC26 256 C curve group * @GNUTLS_GROUP_GC256D: the GOST R 34.10 TC26 256 D curve group * @GNUTLS_GROUP_GC512A: the GOST R 34.10 TC26 512 A curve group * @GNUTLS_GROUP_GC512B: the GOST R 34.10 TC26 512 B curve group * @GNUTLS_GROUP_GC512C: the GOST R 34.10 TC26 512 C curve group * @GNUTLS_GROUP_FFDHE2048: the FFDHE2048 group * @GNUTLS_GROUP_FFDHE3072: the FFDHE3072 group * @GNUTLS_GROUP_FFDHE4096: the FFDHE4096 group * @GNUTLS_GROUP_FFDHE6144: the FFDHE6144 group * @GNUTLS_GROUP_FFDHE8192: the FFDHE8192 group * @GNUTLS_GROUP_X448: the X448 curve group * * Enumeration of supported groups. It is intended to be backwards * compatible with the enumerations in %gnutls_ecc_curve_t for the groups * which are valid elliptic curves. */ typedef enum { GNUTLS_GROUP_INVALID = 0, GNUTLS_GROUP_SECP192R1 = GNUTLS_ECC_CURVE_SECP192R1, GNUTLS_GROUP_SECP224R1 = GNUTLS_ECC_CURVE_SECP224R1, GNUTLS_GROUP_SECP256R1 = GNUTLS_ECC_CURVE_SECP256R1, GNUTLS_GROUP_SECP384R1 = GNUTLS_ECC_CURVE_SECP384R1, GNUTLS_GROUP_SECP521R1 = GNUTLS_ECC_CURVE_SECP521R1, GNUTLS_GROUP_X25519 = GNUTLS_ECC_CURVE_X25519, GNUTLS_GROUP_X448 = GNUTLS_ECC_CURVE_X448, GNUTLS_GROUP_GC256A = GNUTLS_ECC_CURVE_GOST256A, GNUTLS_GROUP_GC256B = GNUTLS_ECC_CURVE_GOST256B, GNUTLS_GROUP_GC256C = GNUTLS_ECC_CURVE_GOST256C, GNUTLS_GROUP_GC256D = GNUTLS_ECC_CURVE_GOST256D, GNUTLS_GROUP_GC512A = GNUTLS_ECC_CURVE_GOST512A, GNUTLS_GROUP_GC512B = GNUTLS_ECC_CURVE_GOST512B, GNUTLS_GROUP_GC512C = GNUTLS_ECC_CURVE_GOST512C, GNUTLS_GROUP_FFDHE2048 = 256, GNUTLS_GROUP_FFDHE3072, GNUTLS_GROUP_FFDHE4096, GNUTLS_GROUP_FFDHE8192, GNUTLS_GROUP_FFDHE6144, GNUTLS_GROUP_MAX = GNUTLS_GROUP_FFDHE6144, } gnutls_group_t; /* macros to allow specifying a specific curve in gnutls_privkey_generate() * and gnutls_x509_privkey_generate() */ #define GNUTLS_CURVE_TO_BITS(curve) (unsigned int)(((unsigned int)1<<31)|((unsigned int)(curve))) #define GNUTLS_BITS_TO_CURVE(bits) (((unsigned int)(bits)) & 0x7FFFFFFF) #define GNUTLS_BITS_ARE_CURVE(bits) (((unsigned int)(bits)) & 0x80000000) /** * gnutls_sec_param_t: * @GNUTLS_SEC_PARAM_UNKNOWN: Cannot be known * @GNUTLS_SEC_PARAM_INSECURE: Less than 42 bits of security * @GNUTLS_SEC_PARAM_EXPORT: 42 bits of security * @GNUTLS_SEC_PARAM_VERY_WEAK: 64 bits of security * @GNUTLS_SEC_PARAM_WEAK: 72 bits of security * @GNUTLS_SEC_PARAM_LOW: 80 bits of security * @GNUTLS_SEC_PARAM_LEGACY: 96 bits of security * @GNUTLS_SEC_PARAM_MEDIUM: 112 bits of security (used to be %GNUTLS_SEC_PARAM_NORMAL) * @GNUTLS_SEC_PARAM_HIGH: 128 bits of security * @GNUTLS_SEC_PARAM_ULTRA: 192 bits of security * @GNUTLS_SEC_PARAM_FUTURE: 256 bits of security * * Enumeration of security parameters for passive attacks. */ typedef enum { GNUTLS_SEC_PARAM_UNKNOWN = 0, GNUTLS_SEC_PARAM_INSECURE = 5, GNUTLS_SEC_PARAM_EXPORT = 10, GNUTLS_SEC_PARAM_VERY_WEAK = 15, GNUTLS_SEC_PARAM_WEAK = 20, GNUTLS_SEC_PARAM_LOW = 25, GNUTLS_SEC_PARAM_LEGACY = 30, GNUTLS_SEC_PARAM_MEDIUM = 35, GNUTLS_SEC_PARAM_HIGH = 40, GNUTLS_SEC_PARAM_ULTRA = 45, GNUTLS_SEC_PARAM_FUTURE = 50, GNUTLS_SEC_PARAM_MAX = GNUTLS_SEC_PARAM_FUTURE } gnutls_sec_param_t; /* old name */ #define GNUTLS_SEC_PARAM_NORMAL GNUTLS_SEC_PARAM_MEDIUM /** * gnutls_channel_binding_t: * @GNUTLS_CB_TLS_UNIQUE: "tls-unique" (RFC 5929) channel binding * @GNUTLS_CB_TLS_SERVER_END_POINT: "tls-server-end-point" (RFC 5929) channel binding * @GNUTLS_CB_TLS_EXPORTER: "tls-exporter" (RFC 9266) channel binding * * Enumeration of supported channel binding types. */ typedef enum { GNUTLS_CB_TLS_UNIQUE, GNUTLS_CB_TLS_SERVER_END_POINT, GNUTLS_CB_TLS_EXPORTER } gnutls_channel_binding_t; /** * gnutls_gost_paramset_t: * @GNUTLS_GOST_PARAMSET_UNKNOWN: Unknown/default parameter set * @GNUTLS_GOST_PARAMSET_TC26_Z: Specified by TC26, see rfc7836 * @GNUTLS_GOST_PARAMSET_CP_A: CryptoPro-A, see rfc4357 * @GNUTLS_GOST_PARAMSET_CP_B: CryptoPro-B, see rfc4357 * @GNUTLS_GOST_PARAMSET_CP_C: CryptoPro-C, see rfc4357 * @GNUTLS_GOST_PARAMSET_CP_D: CryptoPro-D, see rfc4357 * * Enumeration of different GOST 28147 parameter sets. */ typedef enum { GNUTLS_GOST_PARAMSET_UNKNOWN = 0, GNUTLS_GOST_PARAMSET_TC26_Z, GNUTLS_GOST_PARAMSET_CP_A, GNUTLS_GOST_PARAMSET_CP_B, GNUTLS_GOST_PARAMSET_CP_C, GNUTLS_GOST_PARAMSET_CP_D } gnutls_gost_paramset_t; /** * gnutls_ctype_target_t: * @GNUTLS_CTYPE_CLIENT: for requesting client certificate type values. * @GNUTLS_CTYPE_SERVER: for requesting server certificate type values. * @GNUTLS_CTYPE_OURS: for requesting our certificate type values. * @GNUTLS_CTYPE_PEERS: for requesting the peers' certificate type values. * * Enumeration of certificate type targets with respect to asymmetric * certificate types as specified in RFC7250 and P2P connection set up * as specified in draft-vanrein-tls-symmetry-02. */ typedef enum { GNUTLS_CTYPE_CLIENT, GNUTLS_CTYPE_SERVER, GNUTLS_CTYPE_OURS, GNUTLS_CTYPE_PEERS } gnutls_ctype_target_t; /* If you want to change this, then also change the define in * gnutls_int.h, and recompile. */ typedef void *gnutls_transport_ptr_t; struct gnutls_session_int; typedef struct gnutls_session_int *gnutls_session_t; struct gnutls_dh_params_int; typedef struct gnutls_dh_params_int *gnutls_dh_params_t; /* XXX ugly. */ struct gnutls_x509_privkey_int; typedef struct gnutls_x509_privkey_int *gnutls_rsa_params_t; struct gnutls_priority_st; typedef struct gnutls_priority_st *gnutls_priority_t; typedef struct { unsigned char *data; unsigned int size; } gnutls_datum_t; typedef struct gnutls_library_config_st { const char *name; const char *value; } gnutls_library_config_st; typedef struct gnutls_params_st { gnutls_params_type_t type; union params { gnutls_dh_params_t dh; gnutls_rsa_params_t rsa_export; } params; int deinit; } gnutls_params_st; typedef int gnutls_params_function(gnutls_session_t, gnutls_params_type_t, gnutls_params_st *); /* internal functions */ int gnutls_init(gnutls_session_t * session, unsigned int flags); void gnutls_deinit(gnutls_session_t session); #define _gnutls_deinit(x) gnutls_deinit(x) int gnutls_bye(gnutls_session_t session, gnutls_close_request_t how); int gnutls_handshake(gnutls_session_t session); int gnutls_reauth(gnutls_session_t session, unsigned int flags); #define GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT ((unsigned int)-1) #define GNUTLS_INDEFINITE_TIMEOUT ((unsigned int)-2) void gnutls_handshake_set_timeout(gnutls_session_t session, unsigned int ms); int gnutls_rehandshake(gnutls_session_t session); #define GNUTLS_KU_PEER 1 int gnutls_session_key_update(gnutls_session_t session, unsigned flags); gnutls_alert_description_t gnutls_alert_get(gnutls_session_t session); int gnutls_alert_send(gnutls_session_t session, gnutls_alert_level_t level, gnutls_alert_description_t desc); int gnutls_alert_send_appropriate(gnutls_session_t session, int err); const char *gnutls_alert_get_name(gnutls_alert_description_t alert); const char *gnutls_alert_get_strname(gnutls_alert_description_t alert); gnutls_sec_param_t gnutls_pk_bits_to_sec_param(gnutls_pk_algorithm_t algo, unsigned int bits); const char *gnutls_sec_param_get_name(gnutls_sec_param_t param); unsigned int gnutls_sec_param_to_pk_bits(gnutls_pk_algorithm_t algo, gnutls_sec_param_t param); unsigned int gnutls_sec_param_to_symmetric_bits(gnutls_sec_param_t param) __GNUTLS_CONST__; /* Elliptic curves */ const char * gnutls_ecc_curve_get_name(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; const char * gnutls_ecc_curve_get_oid(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; const char * gnutls_group_get_name(gnutls_group_t group) __GNUTLS_CONST__; int gnutls_ecc_curve_get_size(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; gnutls_ecc_curve_t gnutls_ecc_curve_get(gnutls_session_t session); gnutls_group_t gnutls_group_get(gnutls_session_t session); /* get information on the current session */ gnutls_cipher_algorithm_t gnutls_cipher_get(gnutls_session_t session); gnutls_cipher_algorithm_t gnutls_early_cipher_get(gnutls_session_t session); gnutls_kx_algorithm_t gnutls_kx_get(gnutls_session_t session); gnutls_mac_algorithm_t gnutls_mac_get(gnutls_session_t session); gnutls_digest_algorithm_t gnutls_prf_hash_get(const gnutls_session_t session); gnutls_digest_algorithm_t gnutls_early_prf_hash_get(const gnutls_session_t session); gnutls_certificate_type_t gnutls_certificate_type_get(gnutls_session_t session); gnutls_certificate_type_t gnutls_certificate_type_get2(gnutls_session_t session, gnutls_ctype_target_t target); int gnutls_sign_algorithm_get(gnutls_session_t session); int gnutls_sign_algorithm_get_client(gnutls_session_t session); int gnutls_sign_algorithm_get_requested(gnutls_session_t session, size_t indx, gnutls_sign_algorithm_t * algo); /* the name of the specified algorithms */ const char * gnutls_cipher_get_name(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_mac_get_name(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_digest_get_name(gnutls_digest_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_digest_get_oid(gnutls_digest_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_kx_get_name(gnutls_kx_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_certificate_type_get_name(gnutls_certificate_type_t type) __GNUTLS_CONST__; const char * gnutls_pk_get_name(gnutls_pk_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_pk_get_oid(gnutls_pk_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_sign_get_name(gnutls_sign_algorithm_t algorithm) __GNUTLS_CONST__; const char *gnutls_sign_get_oid(gnutls_sign_algorithm_t sign) __GNUTLS_CONST__; const char * gnutls_gost_paramset_get_name(gnutls_gost_paramset_t param) __GNUTLS_CONST__; const char * gnutls_gost_paramset_get_oid(gnutls_gost_paramset_t param) __GNUTLS_CONST__; size_t gnutls_cipher_get_key_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; size_t gnutls_mac_get_key_size(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_sign_is_secure(gnutls_sign_algorithm_t algorithm) __GNUTLS_CONST__; /* It is possible that a signature algorithm is ok to use for short-lived * data (e.g., to sign a TLS session), but not for data that are long-lived * like certificates. This flag is about checking the security of the algorithm * for long-lived data. */ #define GNUTLS_SIGN_FLAG_SECURE_FOR_CERTS 1 unsigned gnutls_sign_is_secure2(gnutls_sign_algorithm_t algorithm, unsigned int flags) __GNUTLS_CONST__; gnutls_digest_algorithm_t gnutls_sign_get_hash_algorithm(gnutls_sign_algorithm_t sign) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_sign_get_pk_algorithm(gnutls_sign_algorithm_t sign) __GNUTLS_CONST__; gnutls_sign_algorithm_t gnutls_pk_to_sign(gnutls_pk_algorithm_t pk, gnutls_digest_algorithm_t hash) __GNUTLS_CONST__; unsigned gnutls_sign_supports_pk_algorithm(gnutls_sign_algorithm_t sign, gnutls_pk_algorithm_t pk) __GNUTLS_CONST__; #define gnutls_sign_algorithm_get_name gnutls_sign_get_name gnutls_mac_algorithm_t gnutls_mac_get_id(const char *name) __GNUTLS_CONST__; gnutls_digest_algorithm_t gnutls_digest_get_id(const char *name) __GNUTLS_CONST__; gnutls_cipher_algorithm_t gnutls_cipher_get_id(const char *name) __GNUTLS_CONST__; gnutls_kx_algorithm_t gnutls_kx_get_id(const char *name) __GNUTLS_CONST__; gnutls_protocol_t gnutls_protocol_get_id(const char *name) __GNUTLS_CONST__; gnutls_certificate_type_t gnutls_certificate_type_get_id(const char *name) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_pk_get_id(const char *name) __GNUTLS_CONST__; gnutls_sign_algorithm_t gnutls_sign_get_id(const char *name) __GNUTLS_CONST__; gnutls_ecc_curve_t gnutls_ecc_curve_get_id(const char *name) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_ecc_curve_get_pk(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; gnutls_group_t gnutls_group_get_id(const char *name); gnutls_digest_algorithm_t gnutls_oid_to_digest(const char *oid) __GNUTLS_CONST__; gnutls_mac_algorithm_t gnutls_oid_to_mac(const char *oid) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_oid_to_pk(const char *oid) __GNUTLS_CONST__; gnutls_sign_algorithm_t gnutls_oid_to_sign(const char *oid) __GNUTLS_CONST__; gnutls_ecc_curve_t gnutls_oid_to_ecc_curve(const char *oid) __GNUTLS_CONST__; gnutls_gost_paramset_t gnutls_oid_to_gost_paramset(const char *oid) __GNUTLS_CONST__; /* list supported algorithms */ const gnutls_ecc_curve_t * gnutls_ecc_curve_list(void) __GNUTLS_PURE__; const gnutls_group_t * gnutls_group_list(void) __GNUTLS_PURE__; const gnutls_cipher_algorithm_t * gnutls_cipher_list(void) __GNUTLS_PURE__; const gnutls_mac_algorithm_t * gnutls_mac_list(void) __GNUTLS_PURE__; const gnutls_digest_algorithm_t * gnutls_digest_list(void) __GNUTLS_PURE__; const gnutls_protocol_t * gnutls_protocol_list(void) __GNUTLS_PURE__; const gnutls_certificate_type_t * gnutls_certificate_type_list(void) __GNUTLS_PURE__; const gnutls_kx_algorithm_t * gnutls_kx_list(void) __GNUTLS_PURE__; const gnutls_pk_algorithm_t * gnutls_pk_list(void) __GNUTLS_PURE__; const gnutls_sign_algorithm_t * gnutls_sign_list(void) __GNUTLS_PURE__; const char * gnutls_cipher_suite_info(size_t idx, unsigned char *cs_id, gnutls_kx_algorithm_t * kx, gnutls_cipher_algorithm_t * cipher, gnutls_mac_algorithm_t * mac, gnutls_protocol_t * min_version); /* functions for run-time enablement of algorithms */ int gnutls_ecc_curve_set_enabled(gnutls_ecc_curve_t curve, unsigned int enabled); int gnutls_sign_set_secure(gnutls_sign_algorithm_t sign, unsigned int secure); int gnutls_sign_set_secure_for_certs(gnutls_sign_algorithm_t sign, unsigned int secure); int gnutls_digest_set_secure(gnutls_digest_algorithm_t dig, unsigned int secure); int gnutls_protocol_set_enabled(gnutls_protocol_t version, unsigned int enabled); /* error functions */ int gnutls_error_is_fatal(int error) __GNUTLS_CONST__; int gnutls_error_to_alert(int err, int *level); void gnutls_perror(int error); const char * gnutls_strerror(int error) __GNUTLS_CONST__; const char * gnutls_strerror_name(int error) __GNUTLS_CONST__; /* Semi-internal functions. */ void gnutls_handshake_set_private_extensions(gnutls_session_t session, int allow); int gnutls_handshake_set_random(gnutls_session_t session, const gnutls_datum_t * random); gnutls_handshake_description_t gnutls_handshake_get_last_out(gnutls_session_t session); gnutls_handshake_description_t gnutls_handshake_get_last_in(gnutls_session_t session); /* Record layer functions. */ #define GNUTLS_HEARTBEAT_WAIT 1 int gnutls_heartbeat_ping(gnutls_session_t session, size_t data_size, unsigned int max_tries, unsigned int flags); int gnutls_heartbeat_pong(gnutls_session_t session, unsigned int flags); void gnutls_record_set_timeout(gnutls_session_t session, unsigned int ms); void gnutls_record_disable_padding(gnutls_session_t session); void gnutls_record_cork(gnutls_session_t session); #define GNUTLS_RECORD_WAIT 1 int gnutls_record_uncork(gnutls_session_t session, unsigned int flags); size_t gnutls_record_discard_queued(gnutls_session_t session); int gnutls_record_get_state(gnutls_session_t session, unsigned read, gnutls_datum_t *mac_key, gnutls_datum_t *IV, gnutls_datum_t *cipher_key, unsigned char seq_number[8]); int gnutls_record_set_state(gnutls_session_t session, unsigned read, const unsigned char seq_number[8]); typedef struct { size_t low; size_t high; } gnutls_range_st; int gnutls_range_split(gnutls_session_t session, const gnutls_range_st * orig, gnutls_range_st * small_range, gnutls_range_st * rem_range); ssize_t gnutls_record_send(gnutls_session_t session, const void *data, size_t data_size); ssize_t gnutls_record_send2(gnutls_session_t session, const void *data, size_t data_size, size_t pad, unsigned flags); ssize_t gnutls_record_send_range(gnutls_session_t session, const void *data, size_t data_size, const gnutls_range_st * range); ssize_t gnutls_record_send_file(gnutls_session_t session, int fd, off_t *offset, size_t count); ssize_t gnutls_record_recv(gnutls_session_t session, void *data, size_t data_size); typedef struct mbuffer_st *gnutls_packet_t; ssize_t gnutls_record_recv_packet(gnutls_session_t session, gnutls_packet_t *packet); void gnutls_packet_get(gnutls_packet_t packet, gnutls_datum_t *data, unsigned char *sequence); void gnutls_packet_deinit(gnutls_packet_t packet); #define gnutls_read gnutls_record_recv #define gnutls_write gnutls_record_send ssize_t gnutls_record_recv_seq(gnutls_session_t session, void *data, size_t data_size, unsigned char *seq); size_t gnutls_record_overhead_size(gnutls_session_t session); size_t gnutls_est_record_overhead_size(gnutls_protocol_t version, gnutls_cipher_algorithm_t cipher, gnutls_mac_algorithm_t mac, gnutls_compression_method_t comp, unsigned int flags) __GNUTLS_CONST__; void gnutls_session_enable_compatibility_mode(gnutls_session_t session); #define gnutls_record_set_max_empty_records(session, x) unsigned gnutls_record_can_use_length_hiding(gnutls_session_t session); int gnutls_record_get_direction(gnutls_session_t session); size_t gnutls_record_get_max_size(gnutls_session_t session); ssize_t gnutls_record_set_max_size(gnutls_session_t session, size_t size); ssize_t gnutls_record_set_max_recv_size(gnutls_session_t session, size_t size); size_t gnutls_record_check_pending(gnutls_session_t session); size_t gnutls_record_check_corked(gnutls_session_t session); size_t gnutls_record_get_max_early_data_size(gnutls_session_t session); int gnutls_record_set_max_early_data_size(gnutls_session_t session, size_t size); ssize_t gnutls_record_send_early_data(gnutls_session_t session, const void *data, size_t length); ssize_t gnutls_record_recv_early_data(gnutls_session_t session, void *data, size_t data_size); void gnutls_session_force_valid(gnutls_session_t session); int gnutls_prf(gnutls_session_t session, size_t label_size, const char *label, int server_random_first, size_t extra_size, const char *extra, size_t outsize, char *out); int gnutls_prf_rfc5705(gnutls_session_t session, size_t label_size, const char *label, size_t context_size, const char *context, size_t outsize, char *out); int gnutls_prf_early(gnutls_session_t session, size_t label_size, const char *label, size_t context_size, const char *context, size_t outsize, char *out); int gnutls_prf_raw(gnutls_session_t session, size_t label_size, const char *label, size_t seed_size, const char *seed, size_t outsize, char *out); /** * gnutls_server_name_type_t: * @GNUTLS_NAME_DNS: Domain Name System name type. * * Enumeration of different server name types. */ typedef enum { GNUTLS_NAME_DNS = 1 } gnutls_server_name_type_t; int gnutls_server_name_set(gnutls_session_t session, gnutls_server_name_type_t type, const void *name, size_t name_length); int gnutls_server_name_get(gnutls_session_t session, void *data, size_t * data_length, unsigned int *type, unsigned int indx); unsigned int gnutls_heartbeat_get_timeout(gnutls_session_t session); void gnutls_heartbeat_set_timeouts(gnutls_session_t session, unsigned int retrans_timeout, unsigned int total_timeout); #define GNUTLS_HB_PEER_ALLOWED_TO_SEND (1) #define GNUTLS_HB_PEER_NOT_ALLOWED_TO_SEND (1<<1) /* Heartbeat */ void gnutls_heartbeat_enable(gnutls_session_t session, unsigned int type); #define GNUTLS_HB_LOCAL_ALLOWED_TO_SEND (1<<2) unsigned gnutls_heartbeat_allowed(gnutls_session_t session, unsigned int type); /* Safe renegotiation */ unsigned gnutls_safe_renegotiation_status(gnutls_session_t session); unsigned gnutls_session_ext_master_secret_status(gnutls_session_t session); unsigned gnutls_session_etm_status(gnutls_session_t session); /** * gnutls_session_flags_t: * @GNUTLS_SFLAGS_SAFE_RENEGOTIATION: Safe renegotiation (RFC5746) was used * @GNUTLS_SFLAGS_EXT_MASTER_SECRET: The extended master secret (RFC7627) extension was used * @GNUTLS_SFLAGS_ETM: The encrypt then MAC (RFC7366) extension was used * @GNUTLS_SFLAGS_RFC7919: The RFC7919 Diffie-Hellman parameters were negotiated * @GNUTLS_SFLAGS_HB_LOCAL_SEND: The heartbeat negotiation allows the local side to send heartbeat messages * @GNUTLS_SFLAGS_HB_PEER_SEND: The heartbeat negotiation allows the peer to send heartbeat messages * @GNUTLS_SFLAGS_FALSE_START: False start was used in this client session. * @GNUTLS_SFLAGS_SESSION_TICKET: A session ticket has been received by the server. * @GNUTLS_SFLAGS_POST_HANDSHAKE_AUTH: Indicates client capability for post-handshake auth; set only on server side. * @GNUTLS_SFLAGS_EARLY_START: The TLS1.3 server session returned early. * @GNUTLS_SFLAGS_EARLY_DATA: The TLS1.3 early data has been received by the server. * @GNUTLS_SFLAGS_CLI_REQUESTED_OCSP: Set when the client has requested OCSP staple during handshake. * @GNUTLS_SFLAGS_SERV_REQUESTED_OCSP: Set when the server has requested OCSP staple during handshake. * * Enumeration of different session parameters. */ typedef enum { GNUTLS_SFLAGS_SAFE_RENEGOTIATION = 1, GNUTLS_SFLAGS_EXT_MASTER_SECRET = 1<<1, GNUTLS_SFLAGS_ETM = 1<<2, GNUTLS_SFLAGS_HB_LOCAL_SEND = 1<<3, GNUTLS_SFLAGS_HB_PEER_SEND = 1<<4, GNUTLS_SFLAGS_FALSE_START = 1<<5, GNUTLS_SFLAGS_RFC7919 = 1<<6, GNUTLS_SFLAGS_SESSION_TICKET = 1<<7, GNUTLS_SFLAGS_POST_HANDSHAKE_AUTH = 1<<8, GNUTLS_SFLAGS_EARLY_START = 1<<9, GNUTLS_SFLAGS_EARLY_DATA = 1<<10, GNUTLS_SFLAGS_CLI_REQUESTED_OCSP = 1<<11, GNUTLS_SFLAGS_SERV_REQUESTED_OCSP = 1<<12 } gnutls_session_flags_t; unsigned gnutls_session_get_flags(gnutls_session_t session); /** * gnutls_supplemental_data_format_type_t: * @GNUTLS_SUPPLEMENTAL_UNKNOWN: Unknown data format * * Enumeration of different supplemental data types (RFC 4680). */ typedef enum { GNUTLS_SUPPLEMENTAL_UNKNOWN = 0, } gnutls_supplemental_data_format_type_t; const char *gnutls_supplemental_get_name(gnutls_supplemental_data_format_type_t type); /* SessionTicket, RFC 5077. */ int gnutls_session_ticket_key_generate(gnutls_datum_t * key); int gnutls_session_ticket_enable_client(gnutls_session_t session); int gnutls_session_ticket_enable_server(gnutls_session_t session, const gnutls_datum_t * key); int gnutls_session_ticket_send(gnutls_session_t session, unsigned nr, unsigned flags); /* SRTP, RFC 5764 */ /** * gnutls_srtp_profile_t: * @GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80: 128 bit AES with a 80 bit HMAC-SHA1 * @GNUTLS_SRTP_AES128_CM_HMAC_SHA1_32: 128 bit AES with a 32 bit HMAC-SHA1 * @GNUTLS_SRTP_NULL_HMAC_SHA1_80: NULL cipher with a 80 bit HMAC-SHA1 * @GNUTLS_SRTP_NULL_HMAC_SHA1_32: NULL cipher with a 32 bit HMAC-SHA1 * * Enumeration of different SRTP protection profiles. */ typedef enum { GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80 = 0x0001, GNUTLS_SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002, GNUTLS_SRTP_NULL_HMAC_SHA1_80 = 0x0005, GNUTLS_SRTP_NULL_HMAC_SHA1_32 = 0x0006 } gnutls_srtp_profile_t; int gnutls_srtp_set_profile(gnutls_session_t session, gnutls_srtp_profile_t profile); int gnutls_srtp_set_profile_direct(gnutls_session_t session, const char *profiles, const char **err_pos); int gnutls_srtp_get_selected_profile(gnutls_session_t session, gnutls_srtp_profile_t * profile); const char *gnutls_srtp_get_profile_name(gnutls_srtp_profile_t profile); int gnutls_srtp_get_profile_id(const char *name, gnutls_srtp_profile_t * profile); int gnutls_srtp_get_keys(gnutls_session_t session, void *key_material, unsigned int key_material_size, gnutls_datum_t * client_key, gnutls_datum_t * client_salt, gnutls_datum_t * server_key, gnutls_datum_t * server_salt); int gnutls_srtp_set_mki(gnutls_session_t session, const gnutls_datum_t * mki); int gnutls_srtp_get_mki(gnutls_session_t session, gnutls_datum_t * mki); /* COMPRESS_CERTIFICATE extension, RFC8879 */ gnutls_compression_method_t gnutls_compress_certificate_get_selected_method(gnutls_session_t session); int gnutls_compress_certificate_set_methods(gnutls_session_t session, const gnutls_compression_method_t * methods, size_t methods_len); /* ALPN TLS extension */ /** * gnutls_alpn_flags_t: * @GNUTLS_ALPN_MANDATORY: Require ALPN negotiation. The connection will be * aborted if no matching ALPN protocol is found. * @GNUTLS_ALPN_SERVER_PRECEDENCE: The choices set by the server * will take precedence over the client's. * * Enumeration of different ALPN flags. These are used by gnutls_alpn_set_protocols(). */ typedef enum { GNUTLS_ALPN_MANDATORY = 1, GNUTLS_ALPN_SERVER_PRECEDENCE = (1<<1) } gnutls_alpn_flags_t; #define GNUTLS_ALPN_MAND GNUTLS_ALPN_MANDATORY int gnutls_alpn_get_selected_protocol(gnutls_session_t session, gnutls_datum_t * protocol); int gnutls_alpn_set_protocols(gnutls_session_t session, const gnutls_datum_t * protocols, unsigned protocols_size, unsigned flags); int gnutls_key_generate(gnutls_datum_t * key, unsigned int key_size); #define GNUTLS_PRIORITY_INIT_DEF_APPEND 1 int gnutls_priority_init(gnutls_priority_t * priority_cache, const char *priorities, const char **err_pos); int gnutls_priority_init2(gnutls_priority_t * priority_cache, const char *priorities, const char **err_pos, unsigned flags); void gnutls_priority_deinit(gnutls_priority_t priority_cache); int gnutls_priority_get_cipher_suite_index(gnutls_priority_t pcache, unsigned int idx, unsigned int *sidx); #define GNUTLS_PRIORITY_LIST_INIT_KEYWORDS 1 #define GNUTLS_PRIORITY_LIST_SPECIAL 2 const char * gnutls_priority_string_list(unsigned iter, unsigned int flags); int gnutls_priority_set(gnutls_session_t session, gnutls_priority_t priority); int gnutls_priority_set_direct(gnutls_session_t session, const char *priorities, const char **err_pos); int gnutls_priority_certificate_type_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_certificate_type_list2(gnutls_priority_t pcache, const unsigned int **list, gnutls_ctype_target_t target); int gnutls_priority_sign_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_protocol_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_ecc_curve_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_group_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_kx_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_cipher_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_mac_list(gnutls_priority_t pcache, const unsigned int **list); const char *gnutls_get_system_config_file(void); int gnutls_set_default_priority(gnutls_session_t session); int gnutls_set_default_priority_append(gnutls_session_t session, const char *add_prio, const char **err_pos, unsigned flags); /* Returns the name of a cipher suite */ const char * gnutls_cipher_suite_get_name(gnutls_kx_algorithm_t kx_algorithm, gnutls_cipher_algorithm_t cipher_algorithm, gnutls_mac_algorithm_t mac_algorithm) __GNUTLS_CONST__; const char * gnutls_ciphersuite_get(gnutls_session_t session) __GNUTLS_CONST__; /* get the currently used protocol version */ gnutls_protocol_t gnutls_protocol_get_version(gnutls_session_t session); const char * gnutls_protocol_get_name(gnutls_protocol_t version) __GNUTLS_CONST__; /* get/set session */ int gnutls_session_set_data(gnutls_session_t session, const void *session_data, size_t session_data_size); int gnutls_session_get_data(gnutls_session_t session, void *session_data, size_t * session_data_size); int gnutls_session_get_data2(gnutls_session_t session, gnutls_datum_t * data); void gnutls_session_get_random(gnutls_session_t session, gnutls_datum_t * client, gnutls_datum_t * server); void gnutls_session_get_master_secret(gnutls_session_t session, gnutls_datum_t * secret); char *gnutls_session_get_desc(gnutls_session_t session); typedef int gnutls_certificate_verify_function(gnutls_session_t); void gnutls_session_set_verify_function(gnutls_session_t session, gnutls_certificate_verify_function * func); /** * gnutls_vdata_types_t: * @GNUTLS_DT_UNKNOWN: Unknown data type. * @GNUTLS_DT_DNS_HOSTNAME: The data contain a null-terminated DNS hostname; the hostname will be * matched using the RFC6125 rules. If the data contain a textual IP (v4 or v6) address it will * be marched against the IPAddress Alternative name, unless the verification flag %GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES * is specified. * @GNUTLS_DT_IP_ADDRESS: The data contain a raw IP address (4 or 16 bytes). If will be matched * against the IPAddress Alternative name; option available since 3.6.0. * @GNUTLS_DT_RFC822NAME: The data contain a null-terminated email address; the email will be * matched against the RFC822Name Alternative name of the certificate, or the EMAIL DN component if the * former isn't available. Prior to matching the email address will be converted to ACE * (ASCII-compatible-encoding). * @GNUTLS_DT_KEY_PURPOSE_OID: The data contain a null-terminated key purpose OID. It will be matched * against the certificate's Extended Key Usage extension. * * Enumeration of different typed-data options. They are used as input to certificate * verification functions to provide information about the name and purpose of the * certificate. Only a single option of a type can be provided to the relevant functions * (i.e., options %GNUTLS_DT_DNS_HOSTNAME, %GNUTLS_DT_IP_ADDRESS and * %GNUTLS_DT_RFC822NAME cannot be combined). */ typedef enum { GNUTLS_DT_UNKNOWN = 0, GNUTLS_DT_DNS_HOSTNAME = 1, GNUTLS_DT_KEY_PURPOSE_OID = 2, GNUTLS_DT_RFC822NAME = 3, GNUTLS_DT_IP_ADDRESS = 4 } gnutls_vdata_types_t; typedef struct { gnutls_vdata_types_t type; unsigned char *data; unsigned int size; } gnutls_typed_vdata_st; void gnutls_session_set_verify_cert(gnutls_session_t session, const char *hostname, unsigned flags); void gnutls_session_set_verify_cert2(gnutls_session_t session, gnutls_typed_vdata_st * data, unsigned elements, unsigned flags); unsigned int gnutls_session_get_verify_cert_status(gnutls_session_t); int gnutls_session_set_premaster(gnutls_session_t session, unsigned int entity, gnutls_protocol_t version, gnutls_kx_algorithm_t kx, gnutls_cipher_algorithm_t cipher, gnutls_mac_algorithm_t mac, gnutls_compression_method_t comp, const gnutls_datum_t * master, const gnutls_datum_t * session_id); /* returns the session ID */ #define GNUTLS_MAX_SESSION_ID 32 int gnutls_session_get_id(gnutls_session_t session, void *session_id, size_t * session_id_size); int gnutls_session_get_id2(gnutls_session_t session, gnutls_datum_t * session_id); int gnutls_session_set_id(gnutls_session_t session, const gnutls_datum_t * sid); int gnutls_session_channel_binding(gnutls_session_t session, gnutls_channel_binding_t cbtype, gnutls_datum_t * cb); /* checks if this session is a resumed one */ int gnutls_session_is_resumed(gnutls_session_t session); int gnutls_session_resumption_requested(gnutls_session_t session); typedef int (*gnutls_db_store_func) (void *, gnutls_datum_t key, gnutls_datum_t data); typedef int (*gnutls_db_remove_func) (void *, gnutls_datum_t key); typedef gnutls_datum_t(*gnutls_db_retr_func) (void *, gnutls_datum_t key); void gnutls_db_set_cache_expiration(gnutls_session_t session, int seconds); unsigned gnutls_db_get_default_cache_expiration(void); void gnutls_db_remove_session(gnutls_session_t session); void gnutls_db_set_retrieve_function(gnutls_session_t session, gnutls_db_retr_func retr_func); void gnutls_db_set_remove_function(gnutls_session_t session, gnutls_db_remove_func rem_func); void gnutls_db_set_store_function(gnutls_session_t session, gnutls_db_store_func store_func); void gnutls_db_set_ptr(gnutls_session_t session, void *ptr); void *gnutls_db_get_ptr(gnutls_session_t session); int gnutls_db_check_entry(gnutls_session_t session, gnutls_datum_t session_entry); time_t gnutls_db_check_entry_time(gnutls_datum_t * entry); time_t gnutls_db_check_entry_expire_time(gnutls_datum_t * entry); /** * gnutls_handshake_hook_func: * @session: the current session * @htype: the type of the handshake message (%gnutls_handshake_description_t) * @when: non zero if this is a post-process/generation call and zero otherwise * @incoming: non zero if this is an incoming message and zero if this is an outgoing message * @msg: the (const) data of the handshake message without the handshake headers. * * Function prototype for handshake hooks. It is set using * gnutls_handshake_set_hook_function(). * * Returns: Non zero on error. */ #define GNUTLS_HOOK_POST (1) #define GNUTLS_HOOK_PRE (0) #define GNUTLS_HOOK_BOTH (-1) typedef int (*gnutls_handshake_hook_func) (gnutls_session_t, unsigned int htype, unsigned when, unsigned int incoming, const gnutls_datum_t *msg); void gnutls_handshake_set_hook_function(gnutls_session_t session, unsigned int htype, int when, gnutls_handshake_hook_func func); #define gnutls_handshake_post_client_hello_func gnutls_handshake_simple_hook_func typedef int (*gnutls_handshake_simple_hook_func) (gnutls_session_t); void gnutls_handshake_set_post_client_hello_function(gnutls_session_t session, gnutls_handshake_simple_hook_func func); void gnutls_handshake_set_max_packet_length(gnutls_session_t session, size_t max); /* returns libgnutls version (call it with a NULL argument) */ const char * gnutls_check_version(const char *req_version) __GNUTLS_CONST__; /* A macro which will allow optimizing out calls to gnutls_check_version() * when the version being compiled with is sufficient. * Used as: * if (gnutls_check_version_numerc(3,3,16)) { */ #define gnutls_check_version_numeric(a,b,c) \ ((GNUTLS_VERSION_MAJOR >= (a)) && \ ((GNUTLS_VERSION_NUMBER >= ( ((a) << 16) + ((b) << 8) + (c) )) || \ gnutls_check_version(#a "." #b "." #c))) /* Functions for setting/clearing credentials */ void gnutls_credentials_clear(gnutls_session_t session); /* cred is a structure defined by the kx algorithm */ int gnutls_credentials_set(gnutls_session_t session, gnutls_credentials_type_t type, void *cred); int gnutls_credentials_get(gnutls_session_t session, gnutls_credentials_type_t type, void **cred); #define gnutls_cred_set gnutls_credentials_set /* x.509 types */ struct gnutls_pubkey_st; typedef struct gnutls_pubkey_st *gnutls_pubkey_t; struct gnutls_privkey_st; typedef struct gnutls_privkey_st *gnutls_privkey_t; struct gnutls_x509_privkey_int; typedef struct gnutls_x509_privkey_int *gnutls_x509_privkey_t; struct gnutls_x509_crl_int; typedef struct gnutls_x509_crl_int *gnutls_x509_crl_t; struct gnutls_x509_crt_int; typedef struct gnutls_x509_crt_int *gnutls_x509_crt_t; struct gnutls_x509_crq_int; typedef struct gnutls_x509_crq_int *gnutls_x509_crq_t; struct gnutls_openpgp_keyring_int; typedef struct gnutls_openpgp_keyring_int *gnutls_openpgp_keyring_t; /* Credential structures - used in gnutls_credentials_set(); */ struct gnutls_certificate_credentials_st; typedef struct gnutls_certificate_credentials_st *gnutls_certificate_credentials_t; typedef gnutls_certificate_credentials_t gnutls_certificate_server_credentials; typedef gnutls_certificate_credentials_t gnutls_certificate_client_credentials; typedef struct gnutls_anon_server_credentials_st *gnutls_anon_server_credentials_t; typedef struct gnutls_anon_client_credentials_st *gnutls_anon_client_credentials_t; void gnutls_anon_free_server_credentials(gnutls_anon_server_credentials_t sc); int gnutls_anon_allocate_server_credentials(gnutls_anon_server_credentials_t * sc); void gnutls_anon_set_server_dh_params(gnutls_anon_server_credentials_t res, gnutls_dh_params_t dh_params); int gnutls_anon_set_server_known_dh_params(gnutls_anon_server_credentials_t res, gnutls_sec_param_t sec_param); void gnutls_anon_set_server_params_function(gnutls_anon_server_credentials_t res, gnutls_params_function * func); void gnutls_anon_free_client_credentials(gnutls_anon_client_credentials_t sc); int gnutls_anon_allocate_client_credentials(gnutls_anon_client_credentials_t * sc); /* CERTFILE is an x509 certificate in PEM form. * KEYFILE is a pkcs-1 private key in PEM form (for RSA keys). */ void gnutls_certificate_free_credentials(gnutls_certificate_credentials_t sc); int gnutls_certificate_allocate_credentials(gnutls_certificate_credentials_t * res); int gnutls_certificate_get_issuer(gnutls_certificate_credentials_t sc, gnutls_x509_crt_t cert, gnutls_x509_crt_t * issuer, unsigned int flags); int gnutls_certificate_get_crt_raw(gnutls_certificate_credentials_t sc, unsigned idx1, unsigned idx2, gnutls_datum_t * cert); void gnutls_certificate_free_keys(gnutls_certificate_credentials_t sc); void gnutls_certificate_free_cas(gnutls_certificate_credentials_t sc); void gnutls_certificate_free_ca_names(gnutls_certificate_credentials_t sc); void gnutls_certificate_free_crls(gnutls_certificate_credentials_t sc); void gnutls_certificate_set_dh_params(gnutls_certificate_credentials_t res, gnutls_dh_params_t dh_params); int gnutls_certificate_set_known_dh_params(gnutls_certificate_credentials_t res, gnutls_sec_param_t sec_param); void gnutls_certificate_set_verify_flags(gnutls_certificate_credentials_t res, unsigned int flags); unsigned int gnutls_certificate_get_verify_flags(gnutls_certificate_credentials_t res); /** * gnutls_certificate_flags: * @GNUTLS_CERTIFICATE_SKIP_KEY_CERT_MATCH: Skip the key and certificate matching check. * @GNUTLS_CERTIFICATE_API_V2: If set the gnutls_certificate_set_*key* functions will return an index of the added key pair instead of zero. * @GNUTLS_CERTIFICATE_SKIP_OCSP_RESPONSE_CHECK: If set, the gnutls_certificate_set_ocsp_status_request_file * function, will not check whether the response set matches any of the certificates. * @GNUTLS_CERTIFICATE_VERIFY_CRLS: This will enable CRL verification when added in the certificate structure. * When used, it requires CAs to be added before CRLs. * * Enumeration of different certificate credentials flags. */ typedef enum gnutls_certificate_flags { GNUTLS_CERTIFICATE_SKIP_KEY_CERT_MATCH = 1, GNUTLS_CERTIFICATE_API_V2 = (1<<1), GNUTLS_CERTIFICATE_SKIP_OCSP_RESPONSE_CHECK = (1<<2), GNUTLS_CERTIFICATE_VERIFY_CRLS = (1<<3) } gnutls_certificate_flags; void gnutls_certificate_set_flags(gnutls_certificate_credentials_t, unsigned flags); void gnutls_certificate_set_verify_limits(gnutls_certificate_credentials_t res, unsigned int max_bits, unsigned int max_depth); int gnutls_certificate_set_x509_system_trust(gnutls_certificate_credentials_t cred); int gnutls_certificate_set_x509_trust_file(gnutls_certificate_credentials_t cred, const char *cafile, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_trust_dir(gnutls_certificate_credentials_t cred, const char *ca_dir, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_trust_mem(gnutls_certificate_credentials_t res, const gnutls_datum_t * ca, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_crl_file(gnutls_certificate_credentials_t res, const char *crlfile, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_crl_mem(gnutls_certificate_credentials_t res, const gnutls_datum_t * CRL, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_key_file(gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_key_file2(gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, gnutls_x509_crt_fmt_t type, const char *pass, unsigned int flags); int gnutls_certificate_set_x509_key_mem(gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_key_mem2(gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, gnutls_x509_crt_fmt_t type, const char *pass, unsigned int flags); void gnutls_certificate_send_x509_rdn_sequence(gnutls_session_t session, int status); int gnutls_certificate_set_x509_simple_pkcs12_file (gnutls_certificate_credentials_t res, const char *pkcs12file, gnutls_x509_crt_fmt_t type, const char *password); int gnutls_certificate_set_x509_simple_pkcs12_mem (gnutls_certificate_credentials_t res, const gnutls_datum_t * p12blob, gnutls_x509_crt_fmt_t type, const char *password); /* New functions to allow setting already parsed X.509 stuff. */ int gnutls_certificate_set_x509_key(gnutls_certificate_credentials_t res, gnutls_x509_crt_t * cert_list, int cert_list_size, gnutls_x509_privkey_t key); int gnutls_certificate_set_x509_trust(gnutls_certificate_credentials_t res, gnutls_x509_crt_t * ca_list, int ca_list_size); int gnutls_certificate_set_x509_crl(gnutls_certificate_credentials_t res, gnutls_x509_crl_t * crl_list, int crl_list_size); int gnutls_certificate_get_x509_key(gnutls_certificate_credentials_t res, unsigned index, gnutls_x509_privkey_t *key); int gnutls_certificate_get_x509_crt(gnutls_certificate_credentials_t res, unsigned index, gnutls_x509_crt_t **crt_list, unsigned *crt_list_size); /* OCSP status request extension, RFC 6066 */ typedef int (*gnutls_status_request_ocsp_func) (gnutls_session_t session, void *ptr, gnutls_datum_t *ocsp_response); void gnutls_certificate_set_ocsp_status_request_function (gnutls_certificate_credentials_t res, gnutls_status_request_ocsp_func ocsp_func, void *ptr); int gnutls_certificate_set_ocsp_status_request_function2 (gnutls_certificate_credentials_t res, unsigned idx, gnutls_status_request_ocsp_func ocsp_func, void *ptr); int gnutls_certificate_set_ocsp_status_request_file (gnutls_certificate_credentials_t res, const char *response_file, unsigned idx); int gnutls_certificate_set_ocsp_status_request_file2 (gnutls_certificate_credentials_t res, const char *response_file, unsigned idx, gnutls_x509_crt_fmt_t fmt); int gnutls_certificate_set_ocsp_status_request_mem (gnutls_certificate_credentials_t res, const gnutls_datum_t *resp, unsigned idx, gnutls_x509_crt_fmt_t fmt); typedef struct gnutls_ocsp_data_st { unsigned int version; /* must be zero */ gnutls_datum_t response; time_t exptime; unsigned char padding[32]; } gnutls_ocsp_data_st; time_t gnutls_certificate_get_ocsp_expiration(gnutls_certificate_credentials_t sc, unsigned idx, int oidx, unsigned flags); int gnutls_ocsp_status_request_enable_client(gnutls_session_t session, gnutls_datum_t * responder_id, size_t responder_id_size, gnutls_datum_t * request_extensions); int gnutls_ocsp_status_request_get(gnutls_session_t session, gnutls_datum_t * response); #define GNUTLS_OCSP_SR_IS_AVAIL 1 unsigned gnutls_ocsp_status_request_is_checked(gnutls_session_t session, unsigned int flags); int gnutls_ocsp_status_request_get2(gnutls_session_t session, unsigned idx, gnutls_datum_t * response); /* RAW public key functions (RFC7250) */ int gnutls_certificate_set_rawpk_key_mem(gnutls_certificate_credentials_t cred, const gnutls_datum_t* spki, const gnutls_datum_t* pkey, gnutls_x509_crt_fmt_t format, const char* pass, unsigned int key_usage, const char **names, unsigned int names_length, unsigned int flags); int gnutls_certificate_set_rawpk_key_file(gnutls_certificate_credentials_t cred, const char* rawpkfile, const char* privkeyfile, gnutls_x509_crt_fmt_t format, const char *pass, unsigned int key_usage, const char **names, unsigned int names_length, unsigned int privkey_flags, unsigned int pkcs11_flags); /* global state functions */ int gnutls_global_init(void); void gnutls_global_deinit(void); const gnutls_library_config_st *gnutls_get_library_config(void); /** * gnutls_time_func: * @t: where to store time. * * Function prototype for time()-like function. Set with * gnutls_global_set_time_function(). * * Returns: Number of seconds since the epoch, or (time_t)-1 on errors. */ typedef time_t(*gnutls_time_func) (time_t * t); typedef int (*mutex_init_func) (void **mutex); typedef int (*mutex_lock_func) (void **mutex); typedef int (*mutex_unlock_func) (void **mutex); typedef int (*mutex_deinit_func) (void **mutex); void gnutls_global_set_mutex(mutex_init_func init, mutex_deinit_func deinit, mutex_lock_func lock, mutex_unlock_func unlock); typedef void *(*gnutls_alloc_function) (size_t); typedef void *(*gnutls_calloc_function) (size_t, size_t); typedef int (*gnutls_is_secure_function) (const void *); typedef void (*gnutls_free_function) (void *); typedef void *(*gnutls_realloc_function) (void *, size_t); void gnutls_global_set_time_function(gnutls_time_func time_func); /* For use in callbacks */ extern _SYM_EXPORT gnutls_alloc_function gnutls_malloc; extern _SYM_EXPORT gnutls_realloc_function gnutls_realloc; extern _SYM_EXPORT gnutls_calloc_function gnutls_calloc; extern _SYM_EXPORT gnutls_free_function gnutls_free; #ifdef GNUTLS_INTERNAL_BUILD #define gnutls_free(a) gnutls_free((void *) (a)), a=NULL #endif extern _SYM_EXPORT char *(*gnutls_strdup) (const char *); /* a variant of memset that doesn't get optimized out */ void gnutls_memset(void *data, int c, size_t size); /* constant time memcmp */ int gnutls_memcmp(const void *s1, const void *s2, size_t n); typedef void (*gnutls_log_func) (int, const char *); typedef void (*gnutls_audit_log_func) (gnutls_session_t, const char *); void gnutls_global_set_log_function(gnutls_log_func log_func); void gnutls_global_set_audit_log_function(gnutls_audit_log_func log_func); void gnutls_global_set_log_level(int level); /** * gnutls_keylog_func: * @session: the current session * @label: the keylog label * @secret: the (const) data of the derived secret. * * Function prototype for keylog hooks. It is set using * gnutls_session_set_keylog_function(). * * Returns: Non zero on error. * Since: 3.6.13 */ typedef int (*gnutls_keylog_func) (gnutls_session_t session, const char *label, const gnutls_datum_t *secret); gnutls_keylog_func gnutls_session_get_keylog_function(const gnutls_session_t session); void gnutls_session_set_keylog_function(gnutls_session_t session, gnutls_keylog_func func); /* Diffie-Hellman parameter handling. */ int gnutls_dh_params_init(gnutls_dh_params_t * dh_params); void gnutls_dh_params_deinit(gnutls_dh_params_t dh_params); int gnutls_dh_params_import_raw(gnutls_dh_params_t dh_params, const gnutls_datum_t * prime, const gnutls_datum_t * generator); int gnutls_dh_params_import_dsa(gnutls_dh_params_t dh_params, gnutls_x509_privkey_t key); int gnutls_dh_params_import_raw2(gnutls_dh_params_t dh_params, const gnutls_datum_t * prime, const gnutls_datum_t * generator, unsigned key_bits); int gnutls_dh_params_import_raw3(gnutls_dh_params_t dh_params, const gnutls_datum_t * prime, const gnutls_datum_t * q, const gnutls_datum_t * generator); int gnutls_dh_params_import_pkcs3(gnutls_dh_params_t params, const gnutls_datum_t * pkcs3_params, gnutls_x509_crt_fmt_t format); int gnutls_dh_params_generate2(gnutls_dh_params_t params, unsigned int bits); int gnutls_dh_params_export_pkcs3(gnutls_dh_params_t params, gnutls_x509_crt_fmt_t format, unsigned char *params_data, size_t * params_data_size); int gnutls_dh_params_export2_pkcs3(gnutls_dh_params_t params, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_dh_params_export_raw(gnutls_dh_params_t params, gnutls_datum_t * prime, gnutls_datum_t * generator, unsigned int *bits); int gnutls_dh_params_cpy(gnutls_dh_params_t dst, gnutls_dh_params_t src); /* Session stuff */ typedef struct { void *iov_base; size_t iov_len; } giovec_t; typedef ssize_t(*gnutls_pull_func) (gnutls_transport_ptr_t, void *, size_t); typedef ssize_t(*gnutls_push_func) (gnutls_transport_ptr_t, const void *, size_t); int gnutls_system_recv_timeout(gnutls_transport_ptr_t ptr, unsigned int ms); typedef int (*gnutls_pull_timeout_func) (gnutls_transport_ptr_t, unsigned int ms); typedef ssize_t(*gnutls_vec_push_func) (gnutls_transport_ptr_t, const giovec_t * iov, int iovcnt); typedef int (*gnutls_errno_func) (gnutls_transport_ptr_t); #if 0 /* This will be defined as macro. */ void gnutls_transport_set_int (gnutls_session_t session, int r); #endif void gnutls_transport_set_int2(gnutls_session_t session, int r, int s); #define gnutls_transport_set_int(s, i) gnutls_transport_set_int2(s, i, i) void gnutls_transport_get_int2(gnutls_session_t session, int *r, int *s); int gnutls_transport_get_int(gnutls_session_t session); void gnutls_transport_set_ptr(gnutls_session_t session, gnutls_transport_ptr_t ptr); void gnutls_transport_set_ptr2(gnutls_session_t session, gnutls_transport_ptr_t recv_ptr, gnutls_transport_ptr_t send_ptr); gnutls_transport_ptr_t gnutls_transport_get_ptr(gnutls_session_t session); void gnutls_transport_get_ptr2(gnutls_session_t session, gnutls_transport_ptr_t * recv_ptr, gnutls_transport_ptr_t * send_ptr); void gnutls_transport_set_vec_push_function(gnutls_session_t session, gnutls_vec_push_func vec_func); void gnutls_transport_set_push_function(gnutls_session_t session, gnutls_push_func push_func); void gnutls_transport_set_pull_function(gnutls_session_t session, gnutls_pull_func pull_func); void gnutls_transport_set_pull_timeout_function(gnutls_session_t session, gnutls_pull_timeout_func func); void gnutls_transport_set_errno_function(gnutls_session_t session, gnutls_errno_func errno_func); void gnutls_transport_set_errno(gnutls_session_t session, int err); /* session specific */ void gnutls_session_set_ptr(gnutls_session_t session, void *ptr); void *gnutls_session_get_ptr(gnutls_session_t session); void gnutls_openpgp_send_cert(gnutls_session_t session, gnutls_openpgp_crt_status_t status); /* This function returns the hash of the given data. */ int gnutls_fingerprint(gnutls_digest_algorithm_t algo, const gnutls_datum_t * data, void *result, size_t * result_size); /** * gnutls_random_art_t: * @GNUTLS_RANDOM_ART_OPENSSH: OpenSSH-style random art. * * Enumeration of different random art types. */ typedef enum gnutls_random_art { GNUTLS_RANDOM_ART_OPENSSH = 1 } gnutls_random_art_t; int gnutls_random_art(gnutls_random_art_t type, const char *key_type, unsigned int key_size, void *fpr, size_t fpr_size, gnutls_datum_t * art); /* IDNA */ #define GNUTLS_IDNA_FORCE_2008 (1<<1) int gnutls_idna_map(const char * input, unsigned ilen, gnutls_datum_t *out, unsigned flags); int gnutls_idna_reverse_map(const char *input, unsigned ilen, gnutls_datum_t *out, unsigned flags); /* SRP */ typedef struct gnutls_srp_server_credentials_st *gnutls_srp_server_credentials_t; typedef struct gnutls_srp_client_credentials_st *gnutls_srp_client_credentials_t; void gnutls_srp_free_client_credentials(gnutls_srp_client_credentials_t sc); int gnutls_srp_allocate_client_credentials(gnutls_srp_client_credentials_t * sc); int gnutls_srp_set_client_credentials(gnutls_srp_client_credentials_t res, const char *username, const char *password); void gnutls_srp_free_server_credentials(gnutls_srp_server_credentials_t sc); int gnutls_srp_allocate_server_credentials(gnutls_srp_server_credentials_t * sc); int gnutls_srp_set_server_credentials_file(gnutls_srp_server_credentials_t res, const char *password_file, const char *password_conf_file); const char *gnutls_srp_server_get_username(gnutls_session_t session); void gnutls_srp_set_prime_bits(gnutls_session_t session, unsigned int bits); int gnutls_srp_verifier(const char *username, const char *password, const gnutls_datum_t * salt, const gnutls_datum_t * generator, const gnutls_datum_t * prime, gnutls_datum_t * res); /* The static parameters defined in draft-ietf-tls-srp-05 * Those should be used as input to gnutls_srp_verifier(). */ extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_8192_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_8192_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_4096_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_4096_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_3072_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_3072_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_2048_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_2048_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1536_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1536_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1024_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1024_group_generator; /* The static parameters defined in rfc7919 */ extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_8192_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_8192_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_8192_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_8192_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_6144_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_6144_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_6144_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_6144_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_4096_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_4096_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_4096_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_4096_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_3072_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_3072_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_3072_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_3072_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_2048_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_2048_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_2048_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_2048_key_bits; typedef int gnutls_srp_server_credentials_function(gnutls_session_t, const char *username, gnutls_datum_t * salt, gnutls_datum_t * verifier, gnutls_datum_t * generator, gnutls_datum_t * prime); void gnutls_srp_set_server_credentials_function(gnutls_srp_server_credentials_t cred, gnutls_srp_server_credentials_function * func); typedef int gnutls_srp_client_credentials_function(gnutls_session_t, char **, char **); void gnutls_srp_set_client_credentials_function(gnutls_srp_client_credentials_t cred, gnutls_srp_client_credentials_function * func); int gnutls_srp_base64_encode(const gnutls_datum_t * data, char *result, size_t * result_size); int gnutls_srp_base64_encode2(const gnutls_datum_t * data, gnutls_datum_t * result); int gnutls_srp_base64_decode(const gnutls_datum_t * b64_data, char *result, size_t * result_size); int gnutls_srp_base64_decode2(const gnutls_datum_t * b64_data, gnutls_datum_t * result); #define gnutls_srp_base64_encode_alloc gnutls_srp_base64_encode2 #define gnutls_srp_base64_decode_alloc gnutls_srp_base64_decode2 void gnutls_srp_set_server_fake_salt_seed(gnutls_srp_server_credentials_t sc, const gnutls_datum_t * seed, unsigned int salt_length); /* PSK stuff */ typedef struct gnutls_psk_server_credentials_st *gnutls_psk_server_credentials_t; typedef struct gnutls_psk_client_credentials_st *gnutls_psk_client_credentials_t; /** * gnutls_psk_key_flags: * @GNUTLS_PSK_KEY_RAW: PSK-key in raw format. * @GNUTLS_PSK_KEY_HEX: PSK-key in hex format. * * Enumeration of different PSK key flags. */ typedef enum gnutls_psk_key_flags { GNUTLS_PSK_KEY_RAW = 0, GNUTLS_PSK_KEY_HEX } gnutls_psk_key_flags; void gnutls_psk_free_client_credentials(gnutls_psk_client_credentials_t sc); int gnutls_psk_allocate_client_credentials(gnutls_psk_client_credentials_t * sc); int gnutls_psk_set_client_credentials(gnutls_psk_client_credentials_t res, const char *username, const gnutls_datum_t * key, gnutls_psk_key_flags flags); int gnutls_psk_set_client_credentials2(gnutls_psk_client_credentials_t res, const gnutls_datum_t *username, const gnutls_datum_t *key, gnutls_psk_key_flags flags); void gnutls_psk_free_server_credentials(gnutls_psk_server_credentials_t sc); int gnutls_psk_allocate_server_credentials(gnutls_psk_server_credentials_t * sc); int gnutls_psk_set_server_credentials_file(gnutls_psk_server_credentials_t res, const char *password_file); int gnutls_psk_set_server_credentials_hint(gnutls_psk_server_credentials_t res, const char *hint); const char *gnutls_psk_server_get_username(gnutls_session_t session); int gnutls_psk_server_get_username2(gnutls_session_t session, gnutls_datum_t *out); const char *gnutls_psk_client_get_hint(gnutls_session_t session); typedef int gnutls_psk_server_credentials_function(gnutls_session_t, const char *username, gnutls_datum_t * key); typedef int gnutls_psk_server_credentials_function2(gnutls_session_t, const gnutls_datum_t *username, gnutls_datum_t *key); void gnutls_psk_set_server_credentials_function(gnutls_psk_server_credentials_t cred, gnutls_psk_server_credentials_function * func); void gnutls_psk_set_server_credentials_function2(gnutls_psk_server_credentials_t cred, gnutls_psk_server_credentials_function2 *func); typedef int gnutls_psk_client_credentials_function(gnutls_session_t, char **username, gnutls_datum_t * key); typedef int gnutls_psk_client_credentials_function2(gnutls_session_t, gnutls_datum_t *username, gnutls_datum_t *key); void gnutls_psk_set_client_credentials_function(gnutls_psk_client_credentials_t cred, gnutls_psk_client_credentials_function * func); void gnutls_psk_set_client_credentials_function2(gnutls_psk_client_credentials_t cred, gnutls_psk_client_credentials_function2 *func); int gnutls_hex_encode(const gnutls_datum_t * data, char *result, size_t * result_size); int gnutls_hex_decode(const gnutls_datum_t * hex_data, void *result, size_t * result_size); int gnutls_hex_encode2(const gnutls_datum_t * data, gnutls_datum_t *result); int gnutls_hex_decode2(const gnutls_datum_t * data, gnutls_datum_t *result); void gnutls_psk_set_server_dh_params(gnutls_psk_server_credentials_t res, gnutls_dh_params_t dh_params); int gnutls_psk_set_server_known_dh_params(gnutls_psk_server_credentials_t res, gnutls_sec_param_t sec_param); void gnutls_psk_set_server_params_function(gnutls_psk_server_credentials_t res, gnutls_params_function * func); /** * gnutls_x509_subject_alt_name_t: * @GNUTLS_SAN_DNSNAME: DNS-name SAN. * @GNUTLS_SAN_RFC822NAME: E-mail address SAN. * @GNUTLS_SAN_URI: URI SAN. * @GNUTLS_SAN_IPADDRESS: IP address SAN. * @GNUTLS_SAN_OTHERNAME: OtherName SAN. * @GNUTLS_SAN_DN: DN SAN. * @GNUTLS_SAN_REGISTERED_ID: RegisteredID. * @GNUTLS_SAN_OTHERNAME_XMPP: Virtual SAN, used by certain functions for convenience. * @GNUTLS_SAN_OTHERNAME_KRB5PRINCIPAL: Virtual SAN, used by certain functions for convenience. * @GNUTLS_SAN_OTHERNAME_MSUSERPRINCIPAL: Virtual SAN, used by certain functions for convenience. * * Enumeration of different subject alternative names types. */ typedef enum gnutls_x509_subject_alt_name_t { GNUTLS_SAN_DNSNAME = 1, GNUTLS_SAN_RFC822NAME = 2, GNUTLS_SAN_URI = 3, GNUTLS_SAN_IPADDRESS = 4, GNUTLS_SAN_OTHERNAME = 5, GNUTLS_SAN_DN = 6, GNUTLS_SAN_REGISTERED_ID = 7, GNUTLS_SAN_MAX = GNUTLS_SAN_REGISTERED_ID, /* The following are "virtual" subject alternative name types, in that they are represented by an otherName value and an OID. Used by gnutls_x509_crt_get_subject_alt_othername_oid. */ GNUTLS_SAN_OTHERNAME_XMPP = 1000, GNUTLS_SAN_OTHERNAME_KRB5PRINCIPAL, GNUTLS_SAN_OTHERNAME_MSUSERPRINCIPAL } gnutls_x509_subject_alt_name_t; struct gnutls_openpgp_crt_int; typedef struct gnutls_openpgp_crt_int *gnutls_openpgp_crt_t; struct gnutls_openpgp_privkey_int; typedef struct gnutls_openpgp_privkey_int *gnutls_openpgp_privkey_t; struct gnutls_pkcs11_privkey_st; typedef struct gnutls_pkcs11_privkey_st *gnutls_pkcs11_privkey_t; /** * gnutls_privkey_type_t: * @GNUTLS_PRIVKEY_X509: X.509 private key, #gnutls_x509_privkey_t. * @GNUTLS_PRIVKEY_OPENPGP: OpenPGP private key, #gnutls_openpgp_privkey_t. * @GNUTLS_PRIVKEY_PKCS11: PKCS11 private key, #gnutls_pkcs11_privkey_t. * @GNUTLS_PRIVKEY_EXT: External private key, operating using callbacks. * * Enumeration of different private key types. */ typedef enum { GNUTLS_PRIVKEY_X509, GNUTLS_PRIVKEY_OPENPGP, GNUTLS_PRIVKEY_PKCS11, GNUTLS_PRIVKEY_EXT } gnutls_privkey_type_t; typedef struct gnutls_retr2_st { gnutls_certificate_type_t cert_type; gnutls_privkey_type_t key_type; union { gnutls_x509_crt_t *x509; gnutls_openpgp_crt_t pgp; } cert; unsigned int ncerts; /* one for pgp keys */ union { gnutls_x509_privkey_t x509; gnutls_openpgp_privkey_t pgp; gnutls_pkcs11_privkey_t pkcs11; } key; unsigned int deinit_all; /* if non zero all keys will be deinited */ } gnutls_retr2_st; /* Functions that allow auth_info_t structures handling */ gnutls_credentials_type_t gnutls_auth_get_type(gnutls_session_t session); gnutls_credentials_type_t gnutls_auth_server_get_type(gnutls_session_t session); gnutls_credentials_type_t gnutls_auth_client_get_type(gnutls_session_t session); /* DH */ void gnutls_dh_set_prime_bits(gnutls_session_t session, unsigned int bits); int gnutls_dh_get_secret_bits(gnutls_session_t session); int gnutls_dh_get_peers_public_bits(gnutls_session_t session); int gnutls_dh_get_prime_bits(gnutls_session_t session); int gnutls_dh_get_group(gnutls_session_t session, gnutls_datum_t * raw_gen, gnutls_datum_t * raw_prime); int gnutls_dh_get_pubkey(gnutls_session_t session, gnutls_datum_t * raw_key); /* X509PKI */ /* These are set on the credentials structure. */ /* use gnutls_certificate_set_retrieve_function2() in abstract.h * instead. It's much more efficient. */ typedef int gnutls_certificate_retrieve_function(gnutls_session_t, const gnutls_datum_t * req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t * pk_algos, int pk_algos_length, gnutls_retr2_st *); void gnutls_certificate_set_retrieve_function(gnutls_certificate_credentials_t cred, gnutls_certificate_retrieve_function * func); void gnutls_certificate_set_verify_function(gnutls_certificate_credentials_t cred, gnutls_certificate_verify_function * func); void gnutls_certificate_server_set_request(gnutls_session_t session, gnutls_certificate_request_t req); /* get data from the session */ const gnutls_datum_t *gnutls_certificate_get_peers(gnutls_session_t session, unsigned int *list_size); const gnutls_datum_t *gnutls_certificate_get_ours(gnutls_session_t session); int gnutls_certificate_get_peers_subkey_id(gnutls_session_t session, gnutls_datum_t * id); time_t gnutls_certificate_activation_time_peers(gnutls_session_t session); time_t gnutls_certificate_expiration_time_peers(gnutls_session_t session); unsigned gnutls_certificate_client_get_request_status(gnutls_session_t session); int gnutls_certificate_verify_peers2(gnutls_session_t session, unsigned int *status); int gnutls_certificate_verify_peers3(gnutls_session_t session, const char *hostname, unsigned int *status); int gnutls_certificate_verify_peers(gnutls_session_t session, gnutls_typed_vdata_st * data, unsigned int elements, unsigned int *status); int gnutls_certificate_verification_status_print(unsigned int status, gnutls_certificate_type_t type, gnutls_datum_t * out, unsigned int flags); int gnutls_pem_base64_encode(const char *msg, const gnutls_datum_t * data, char *result, size_t * result_size); int gnutls_pem_base64_decode(const char *header, const gnutls_datum_t * b64_data, unsigned char *result, size_t * result_size); int gnutls_pem_base64_encode2(const char *msg, const gnutls_datum_t * data, gnutls_datum_t * result); int gnutls_pem_base64_decode2(const char *header, const gnutls_datum_t * b64_data, gnutls_datum_t * result); int gnutls_base64_encode2(const gnutls_datum_t * data, gnutls_datum_t * result); int gnutls_base64_decode2(const gnutls_datum_t * b64_data, gnutls_datum_t * result); #define gnutls_pem_base64_encode_alloc gnutls_pem_base64_encode2 #define gnutls_pem_base64_decode_alloc gnutls_pem_base64_decode2 /* key_usage will be an OR of the following values: */ /* when the key is to be used for signing: */ #define GNUTLS_KEY_DIGITAL_SIGNATURE 128 #define GNUTLS_KEY_NON_REPUDIATION 64 /* when the key is to be used for encryption: */ #define GNUTLS_KEY_KEY_ENCIPHERMENT 32 #define GNUTLS_KEY_DATA_ENCIPHERMENT 16 #define GNUTLS_KEY_KEY_AGREEMENT 8 #define GNUTLS_KEY_KEY_CERT_SIGN 4 #define GNUTLS_KEY_CRL_SIGN 2 #define GNUTLS_KEY_ENCIPHER_ONLY 1 #define GNUTLS_KEY_DECIPHER_ONLY 32768 void gnutls_certificate_set_params_function(gnutls_certificate_credentials_t res, gnutls_params_function * func); void gnutls_anon_set_params_function(gnutls_anon_server_credentials_t res, gnutls_params_function * func); void gnutls_psk_set_params_function(gnutls_psk_server_credentials_t res, gnutls_params_function * func); int gnutls_hex2bin(const char *hex_data, size_t hex_size, void *bin_data, size_t * bin_size); /* Trust on first use (or ssh like) functions */ /* stores the provided information to a database */ typedef int (*gnutls_tdb_store_func) (const char *db_name, const char *host, const char *service, time_t expiration, const gnutls_datum_t * pubkey); typedef int (*gnutls_tdb_store_commitment_func) (const char *db_name, const char *host, const char *service, time_t expiration, gnutls_digest_algorithm_t hash_algo, const gnutls_datum_t * hash); /* searches for the provided host/service pair that match the * provided public key in the database. */ typedef int (*gnutls_tdb_verify_func) (const char *db_name, const char *host, const char *service, const gnutls_datum_t * pubkey); struct gnutls_tdb_int; typedef struct gnutls_tdb_int *gnutls_tdb_t; int gnutls_tdb_init(gnutls_tdb_t * tdb); void gnutls_tdb_set_store_func(gnutls_tdb_t tdb, gnutls_tdb_store_func store); void gnutls_tdb_set_store_commitment_func(gnutls_tdb_t tdb, gnutls_tdb_store_commitment_func cstore); void gnutls_tdb_set_verify_func(gnutls_tdb_t tdb, gnutls_tdb_verify_func verify); void gnutls_tdb_deinit(gnutls_tdb_t tdb); int gnutls_verify_stored_pubkey(const char *db_name, gnutls_tdb_t tdb, const char *host, const char *service, gnutls_certificate_type_t cert_type, const gnutls_datum_t * cert, unsigned int flags); #define GNUTLS_SCOMMIT_FLAG_ALLOW_BROKEN 1 int gnutls_store_commitment(const char *db_name, gnutls_tdb_t tdb, const char *host, const char *service, gnutls_digest_algorithm_t hash_algo, const gnutls_datum_t * hash, time_t expiration, unsigned int flags); int gnutls_store_pubkey(const char *db_name, gnutls_tdb_t tdb, const char *host, const char *service, gnutls_certificate_type_t cert_type, const gnutls_datum_t * cert, time_t expiration, unsigned int flags); /* Other helper functions */ int gnutls_load_file(const char *filename, gnutls_datum_t * data); unsigned gnutls_url_is_supported(const char *url); /* PIN callback */ /** * gnutls_pin_flag_t: * @GNUTLS_PIN_USER: The PIN for the user. * @GNUTLS_PIN_SO: The PIN for the security officer (admin). * @GNUTLS_PIN_CONTEXT_SPECIFIC: The PIN is for a specific action and key like signing. * @GNUTLS_PIN_FINAL_TRY: This is the final try before blocking. * @GNUTLS_PIN_COUNT_LOW: Few tries remain before token blocks. * @GNUTLS_PIN_WRONG: Last given PIN was not correct. * * Enumeration of different flags that are input to the PIN function. */ typedef enum { GNUTLS_PIN_USER = (1 << 0), GNUTLS_PIN_SO = (1 << 1), GNUTLS_PIN_FINAL_TRY = (1 << 2), GNUTLS_PIN_COUNT_LOW = (1 << 3), GNUTLS_PIN_CONTEXT_SPECIFIC = (1 << 4), GNUTLS_PIN_WRONG = (1 << 5) } gnutls_pin_flag_t; #define GNUTLS_PKCS11_PIN_USER GNUTLS_PIN_USER #define GNUTLS_PKCS11_PIN_SO GNUTLS_PIN_SO #define GNUTLS_PKCS11_PIN_FINAL_TRY GNUTLS_PIN_FINAL_TRY #define GNUTLS_PKCS11_PIN_COUNT_LOW GNUTLS_PIN_COUNT_LOW #define GNUTLS_PKCS11_PIN_CONTEXT_SPECIFIC GNUTLS_PIN_CONTEXT_SPECIFIC #define GNUTLS_PKCS11_PIN_WRONG GNUTLS_PIN_WRONG /** * gnutls_pin_callback_t: * @userdata: user-controlled data from gnutls_pkcs11_set_pin_function(). * @attempt: pin-attempt counter, initially 0. * @token_url: URL of token. * @token_label: label of token. * @flags: a #gnutls_pin_flag_t flag. * @pin: buffer to hold PIN, of size @pin_max. * @pin_max: size of @pin buffer. * * Callback function type for PKCS#11 or TPM PIN entry. It is set by * functions like gnutls_pkcs11_set_pin_function(). * * The callback should provides the PIN code to unlock the token with * label @token_label, specified by the URL @token_url. * * The PIN code, as a NUL-terminated ASCII string, should be copied * into the @pin buffer (of maximum size @pin_max), and return 0 to * indicate success. Alternatively, the callback may return a * negative gnutls error code to indicate failure and cancel PIN entry * (in which case, the contents of the @pin parameter are ignored). * * When a PIN is required, the callback will be invoked repeatedly * (and indefinitely) until either the returned PIN code is correct, * the callback returns failure, or the token refuses login (e.g. when * the token is locked due to too many incorrect PINs!). For the * first such invocation, the @attempt counter will have value zero; * it will increase by one for each subsequent attempt. * * Returns: %GNUTLS_E_SUCCESS (0) on success or a negative error code on error. * * Since: 2.12.0 **/ typedef int (*gnutls_pin_callback_t) (void *userdata, int attempt, const char *token_url, const char *token_label, unsigned int flags, char *pin, size_t pin_max); void gnutls_certificate_set_pin_function(gnutls_certificate_credentials_t, gnutls_pin_callback_t fn, void *userdata); /* Public string related functions */ typedef struct gnutls_buffer_st *gnutls_buffer_t; int gnutls_buffer_append_data(gnutls_buffer_t, const void *data, size_t data_size); #define GNUTLS_UTF8_IGNORE_ERRS 1 int gnutls_utf8_password_normalize(const unsigned char *password, unsigned password_len, gnutls_datum_t *out, unsigned flags); /* Public extensions related functions */ typedef void *gnutls_ext_priv_data_t; void gnutls_ext_set_data(gnutls_session_t session, unsigned type, gnutls_ext_priv_data_t); int gnutls_ext_get_data(gnutls_session_t session, unsigned type, gnutls_ext_priv_data_t *); unsigned gnutls_ext_get_current_msg(gnutls_session_t session); typedef int (*gnutls_ext_recv_func) (gnutls_session_t session, const unsigned char *data, size_t len); typedef int (*gnutls_ext_send_func) (gnutls_session_t session, gnutls_buffer_t extdata); typedef void (*gnutls_ext_deinit_data_func) (gnutls_ext_priv_data_t data); typedef int (*gnutls_ext_pack_func) (gnutls_ext_priv_data_t data, gnutls_buffer_t packed_data); typedef int (*gnutls_ext_unpack_func) (gnutls_buffer_t packed_data, gnutls_ext_priv_data_t *data); #define GNUTLS_EXT_RAW_FLAG_TLS_CLIENT_HELLO 1 #define GNUTLS_EXT_RAW_FLAG_DTLS_CLIENT_HELLO (1<<1) typedef int (*gnutls_ext_raw_process_func)(void *ctx, unsigned tls_id, const unsigned char *data, unsigned data_size); int gnutls_ext_raw_parse(void *ctx, gnutls_ext_raw_process_func cb, const gnutls_datum_t *data, unsigned int flags); /** * gnutls_ext_parse_type_t: * @GNUTLS_EXT_NONE: Never to be parsed * @GNUTLS_EXT_ANY: Any extension type (should not be used as it is used only internally). * @GNUTLS_EXT_VERSION_NEG: Extensions to be parsed first for TLS version negotiation. * @GNUTLS_EXT_MANDATORY: Parsed after @GNUTLS_EXT_VERSION_NEG and even when resuming. * @GNUTLS_EXT_APPLICATION: Parsed after @GNUTLS_EXT_MANDATORY * @GNUTLS_EXT_TLS: TLS-internal extensions, parsed after @GNUTLS_EXT_APPLICATION. * * Enumeration of different TLS extension parsing phases. The @gnutls_ext_parse_type_t * indicates the time/phase an extension is parsed during Client or Server hello parsing. * */ typedef enum { GNUTLS_EXT_ANY = 0, GNUTLS_EXT_APPLICATION = 1, GNUTLS_EXT_TLS = 2, GNUTLS_EXT_MANDATORY = 3, GNUTLS_EXT_NONE = 4, GNUTLS_EXT_VERSION_NEG = 5 } gnutls_ext_parse_type_t; /** * gnutls_ext_flags_t: * @GNUTLS_EXT_FLAG_OVERRIDE_INTERNAL: If specified the extension registered will override the internal; this does not work with extensions existing prior to 3.6.0. * @GNUTLS_EXT_FLAG_CLIENT_HELLO: This extension can be present in a client hello * @GNUTLS_EXT_FLAG_TLS12_SERVER_HELLO: This extension can be present in a TLS1.2 or earlier server hello * @GNUTLS_EXT_FLAG_TLS13_SERVER_HELLO: This extension can be present in a TLS1.3 server hello * @GNUTLS_EXT_FLAG_EE: This extension can be present in encrypted extensions message * @GNUTLS_EXT_FLAG_HRR: This extension can be present in hello retry request message * @GNUTLS_EXT_FLAG_IGNORE_CLIENT_REQUEST: When flag is present, this extension will be send even if the client didn't advertise it. An extension of this type is the Cookie TLS1.3 extension. * @GNUTLS_EXT_FLAG_DTLS: This extension can be present under DTLS; otherwise ignored. * @GNUTLS_EXT_FLAG_TLS: This extension can be present under TLS; otherwise ignored. * * Enumeration of different TLS extension registration flags. */ typedef enum { GNUTLS_EXT_FLAG_OVERRIDE_INTERNAL = 1, GNUTLS_EXT_FLAG_CLIENT_HELLO = (1<<1), GNUTLS_EXT_FLAG_TLS12_SERVER_HELLO = (1<<2), GNUTLS_EXT_FLAG_TLS13_SERVER_HELLO = (1<<3), GNUTLS_EXT_FLAG_EE = (1<<4), /* ENCRYPTED */ GNUTLS_EXT_FLAG_HRR = (1<<5), GNUTLS_EXT_FLAG_IGNORE_CLIENT_REQUEST = (1<<6), GNUTLS_EXT_FLAG_TLS = (1<<7), GNUTLS_EXT_FLAG_DTLS = (1<<8) } gnutls_ext_flags_t; /* Register a custom tls extension */ int gnutls_ext_register(const char *name, int type, gnutls_ext_parse_type_t parse_point, gnutls_ext_recv_func recv_func, gnutls_ext_send_func send_func, gnutls_ext_deinit_data_func deinit_func, gnutls_ext_pack_func pack_func, gnutls_ext_unpack_func unpack_func); int gnutls_session_ext_register(gnutls_session_t, const char *name, int type, gnutls_ext_parse_type_t parse_point, gnutls_ext_recv_func recv_func, gnutls_ext_send_func send_func, gnutls_ext_deinit_data_func deinit_func, gnutls_ext_pack_func pack_func, gnutls_ext_unpack_func unpack_func, unsigned flags); const char *gnutls_ext_get_name(unsigned int ext); const char *gnutls_ext_get_name2(gnutls_session_t session, unsigned int tls_id, gnutls_ext_parse_type_t parse_point); /* Public supplemental data related functions */ typedef int (*gnutls_supp_recv_func) (gnutls_session_t session, const unsigned char * data, size_t data_size); typedef int (*gnutls_supp_send_func) (gnutls_session_t session, gnutls_buffer_t buf); int gnutls_supplemental_register(const char *name, gnutls_supplemental_data_format_type_t type, gnutls_supp_recv_func supp_recv_func, gnutls_supp_send_func supp_send_func); int gnutls_session_supplemental_register(gnutls_session_t session, const char *name, gnutls_supplemental_data_format_type_t type, gnutls_supp_recv_func supp_recv_func, gnutls_supp_send_func supp_send_func, unsigned int flags); void gnutls_supplemental_recv(gnutls_session_t session, unsigned do_recv_supplemental); void gnutls_supplemental_send(gnutls_session_t session, unsigned do_send_supplemental); /* Anti-replay related functions */ typedef struct gnutls_anti_replay_st *gnutls_anti_replay_t; int gnutls_anti_replay_init(gnutls_anti_replay_t *anti_replay); void gnutls_anti_replay_deinit(gnutls_anti_replay_t anti_replay); void gnutls_anti_replay_set_window(gnutls_anti_replay_t anti_replay, unsigned int window); void gnutls_anti_replay_enable(gnutls_session_t session, gnutls_anti_replay_t anti_replay); typedef int (*gnutls_db_add_func) (void *, time_t exp_time, const gnutls_datum_t *key, const gnutls_datum_t *data); void gnutls_anti_replay_set_add_function(gnutls_anti_replay_t, gnutls_db_add_func add_func); void gnutls_anti_replay_set_ptr(gnutls_anti_replay_t, void *ptr); /** * gnutls_record_encryption_level_t: * @GNUTLS_ENCRYPTION_LEVEL_INITIAL: initial level that doesn't involve any * encryption * @GNUTLS_ENCRYPTION_LEVEL_EARLY: early traffic secret is installed * @GNUTLS_ENCRYPTION_LEVEL_HANDSHAKE: handshake traffic secret is installed * @GNUTLS_ENCRYPTION_LEVEL_APPLICATION: application traffic secret is installed * * Enumeration of different levels of record encryption currently in place. * This is used by gnutls_handshake_set_read_function() and * gnutls_handshake_write(). * * Since: 3.7.0 */ typedef enum { GNUTLS_ENCRYPTION_LEVEL_INITIAL, GNUTLS_ENCRYPTION_LEVEL_EARLY, GNUTLS_ENCRYPTION_LEVEL_HANDSHAKE, GNUTLS_ENCRYPTION_LEVEL_APPLICATION } gnutls_record_encryption_level_t; /** * gnutls_handshake_read_func: * @session: the current session * @htype: the type of the handshake message (#gnutls_handshake_description_t) * @level: #gnutls_record_encryption_level_t * @data: the (const) data that was being sent * @data_size: the size of data * * Function prototype for handshake intercepting hooks. It is set using * gnutls_handshake_set_read_function(). * * Returns: Non zero on error. * Since: 3.7.0 */ typedef int (*gnutls_handshake_read_func) (gnutls_session_t session, gnutls_record_encryption_level_t level, gnutls_handshake_description_t htype, const void *data, size_t data_size); void gnutls_handshake_set_read_function(gnutls_session_t session, gnutls_handshake_read_func func); int gnutls_handshake_write(gnutls_session_t session, gnutls_record_encryption_level_t level, const void *data, size_t data_size); /** * gnutls_handshake_secret_func: * @session: the current session * @level: the encryption level * @secret_read: the secret used for reading, can be %NULL if not set * @secret_write: the secret used for writing, can be %NULL if not set * @secret_size: the size of the secrets * * Function prototype for secret hooks. It is set using * gnutls_handshake_set_secret_function(). * * Returns: Non zero on error. * Since: 3.7.0 */ typedef int (*gnutls_handshake_secret_func) (gnutls_session_t session, gnutls_record_encryption_level_t level, const void *secret_read, const void *secret_write, size_t secret_size); void gnutls_handshake_set_secret_function(gnutls_session_t session, gnutls_handshake_secret_func func); /** * gnutls_alert_read_func: * @session: the current session * @level: #gnutls_record_encryption_level_t * @alert_level: the level of the alert * @alert_desc: the alert description * * Function prototype for alert intercepting hooks. It is set using * gnutls_alert_set_read_function(). * * Returns: Non zero on error. * Since: 3.7.0 */ typedef int (*gnutls_alert_read_func) (gnutls_session_t session, gnutls_record_encryption_level_t level, gnutls_alert_level_t alert_level, gnutls_alert_description_t alert_desc); void gnutls_alert_set_read_function(gnutls_session_t session, gnutls_alert_read_func func); /* FIPS140-2 related functions */ unsigned gnutls_fips140_mode_enabled(void); /** * gnutls_fips_mode_t: * @GNUTLS_FIPS140_DISABLED: The FIPS140-2 mode is disabled. * @GNUTLS_FIPS140_STRICT: The default mode; all forbidden operations will cause an * operation failure via error code. * @GNUTLS_FIPS140_LAX: The library still uses the FIPS140-2 relevant algorithms but all * forbidden by FIPS140-2 operations are allowed; this is useful when the * application is aware of the followed security policy, and needs * to utilize disallowed operations for other reasons (e.g., compatibility). * @GNUTLS_FIPS140_LOG: Similarly to %GNUTLS_FIPS140_LAX, it allows forbidden operations; any use of them results * to a message to the audit callback functions. * @GNUTLS_FIPS140_SELFTESTS: A transient state during library initialization. That state * cannot be set or seen by applications. * * Enumeration of different operational modes under FIPS140-2. */ typedef enum gnutls_fips_mode_t { GNUTLS_FIPS140_DISABLED = 0, GNUTLS_FIPS140_STRICT = 1, GNUTLS_FIPS140_SELFTESTS = 2, GNUTLS_FIPS140_LAX = 3, GNUTLS_FIPS140_LOG = 4 } gnutls_fips_mode_t; #define GNUTLS_FIPS140_SET_MODE_THREAD 1 void gnutls_fips140_set_mode(gnutls_fips_mode_t mode, unsigned flags); #define GNUTLS_FIPS140_SET_LAX_MODE() do { \ if (gnutls_fips140_mode_enabled()) \ gnutls_fips140_set_mode(GNUTLS_FIPS140_LAX, GNUTLS_FIPS140_SET_MODE_THREAD); \ } while(0) #define GNUTLS_FIPS140_SET_STRICT_MODE() do { \ if (gnutls_fips140_mode_enabled()) \ gnutls_fips140_set_mode(GNUTLS_FIPS140_STRICT, GNUTLS_FIPS140_SET_MODE_THREAD); \ } while(0) typedef struct gnutls_fips140_context_st *gnutls_fips140_context_t; int gnutls_fips140_context_init(gnutls_fips140_context_t *context); void gnutls_fips140_context_deinit(gnutls_fips140_context_t context); /** * gnutls_fips140_operation_state_t: * @GNUTLS_FIPS140_OP_INITIAL: no previous operation has done * @GNUTLS_FIPS140_OP_APPROVED: the previous operation was FIPS approved * @GNUTLS_FIPS140_OP_NOT_APPROVED: the previous operation was not FIPS approved * @GNUTLS_FIPS140_OP_ERROR: the previous operation caused an error regardless of FIPS * * The FIPS operation state set by the preceding operation. * * There are state transition rules among the enum values: * - When the context is attached to a thread, it will be set to reset * to the %GNUTLS_FIPS140_OP_INITIAL state * - From the %GNUTLS_FIPS140_OP_INITIAL state, the context can * transition to either %GNUTLS_FIPS140_OP_APPROVED, * %GNUTLS_FIPS140_OP_NOT_APPROVED, or %GNUTLS_FIPS140_OP_ERROR * - From the %GNUTLS_FIPS140_OP_APPROVED state, the context can * transition to %GNUTLS_FIPS140_OP_NOT_APPROVED * - All other transitions are prohibited. * * Since: 3.7.3 */ typedef enum { GNUTLS_FIPS140_OP_INITIAL, GNUTLS_FIPS140_OP_APPROVED, GNUTLS_FIPS140_OP_NOT_APPROVED, GNUTLS_FIPS140_OP_ERROR } gnutls_fips140_operation_state_t; gnutls_fips140_operation_state_t gnutls_fips140_get_operation_state(gnutls_fips140_context_t context); int gnutls_fips140_push_context(gnutls_fips140_context_t context); int gnutls_fips140_pop_context(void); int gnutls_fips140_run_self_tests(void); /* Gnutls error codes. The mapping to a TLS alert is also shown in * comments. */ #define GNUTLS_E_SUCCESS 0 #define GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM -3 #define GNUTLS_E_UNKNOWN_CIPHER_TYPE -6 #define GNUTLS_E_LARGE_PACKET -7 #define GNUTLS_E_UNSUPPORTED_VERSION_PACKET -8 /* GNUTLS_A_PROTOCOL_VERSION */ #define GNUTLS_E_TLS_PACKET_DECODING_ERROR GNUTLS_E_UNEXPECTED_PACKET_LENGTH #define GNUTLS_E_UNEXPECTED_PACKET_LENGTH -9 /* GNUTLS_A_DECODE_ERROR */ #define GNUTLS_E_INVALID_SESSION -10 #define GNUTLS_E_FATAL_ALERT_RECEIVED -12 #define GNUTLS_E_UNEXPECTED_PACKET -15 /* GNUTLS_A_UNEXPECTED_MESSAGE */ #define GNUTLS_E_WARNING_ALERT_RECEIVED -16 #define GNUTLS_E_ERROR_IN_FINISHED_PACKET -18 #define GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET -19 #define GNUTLS_E_UNKNOWN_CIPHER_SUITE -21 /* GNUTLS_A_HANDSHAKE_FAILURE */ #define GNUTLS_E_UNWANTED_ALGORITHM -22 #define GNUTLS_E_MPI_SCAN_FAILED -23 #define GNUTLS_E_DECRYPTION_FAILED -24 /* GNUTLS_A_DECRYPTION_FAILED, GNUTLS_A_BAD_RECORD_MAC */ #define GNUTLS_E_MEMORY_ERROR -25 #define GNUTLS_E_DECOMPRESSION_FAILED -26 /* GNUTLS_A_DECOMPRESSION_FAILURE */ #define GNUTLS_E_COMPRESSION_FAILED -27 #define GNUTLS_E_AGAIN -28 #define GNUTLS_E_EXPIRED -29 #define GNUTLS_E_DB_ERROR -30 #define GNUTLS_E_SRP_PWD_ERROR GNUTLS_E_KEYFILE_ERROR #define GNUTLS_E_KEYFILE_ERROR -31 #define GNUTLS_E_INSUFFICIENT_CREDENTIALS -32 #define GNUTLS_E_INSUFICIENT_CREDENTIALS GNUTLS_E_INSUFFICIENT_CREDENTIALS /* for backwards compatibility only */ #define GNUTLS_E_INSUFFICIENT_CRED GNUTLS_E_INSUFFICIENT_CREDENTIALS #define GNUTLS_E_INSUFICIENT_CRED GNUTLS_E_INSUFFICIENT_CREDENTIALS /* for backwards compatibility only */ #define GNUTLS_E_HASH_FAILED -33 #define GNUTLS_E_BASE64_DECODING_ERROR -34 #define GNUTLS_E_MPI_PRINT_FAILED -35 #define GNUTLS_E_REHANDSHAKE -37 /* GNUTLS_A_NO_RENEGOTIATION */ #define GNUTLS_E_GOT_APPLICATION_DATA -38 #define GNUTLS_E_RECORD_LIMIT_REACHED -39 #define GNUTLS_E_ENCRYPTION_FAILED -40 #define GNUTLS_E_PK_ENCRYPTION_FAILED -44 #define GNUTLS_E_PK_DECRYPTION_FAILED -45 #define GNUTLS_E_PK_SIGN_FAILED -46 #define GNUTLS_E_X509_UNSUPPORTED_CRITICAL_EXTENSION -47 #define GNUTLS_E_KEY_USAGE_VIOLATION -48 #define GNUTLS_E_NO_CERTIFICATE_FOUND -49 /* GNUTLS_A_BAD_CERTIFICATE */ #define GNUTLS_E_INVALID_REQUEST -50 #define GNUTLS_E_SHORT_MEMORY_BUFFER -51 #define GNUTLS_E_INTERRUPTED -52 #define GNUTLS_E_PUSH_ERROR -53 #define GNUTLS_E_PULL_ERROR -54 #define GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER -55 /* GNUTLS_A_ILLEGAL_PARAMETER */ #define GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE -56 #define GNUTLS_E_PKCS1_WRONG_PAD -57 #define GNUTLS_E_RECEIVED_ILLEGAL_EXTENSION -58 #define GNUTLS_E_INTERNAL_ERROR -59 #define GNUTLS_E_DH_PRIME_UNACCEPTABLE -63 #define GNUTLS_E_FILE_ERROR -64 #define GNUTLS_E_TOO_MANY_EMPTY_PACKETS -78 #define GNUTLS_E_UNKNOWN_PK_ALGORITHM -80 #define GNUTLS_E_TOO_MANY_HANDSHAKE_PACKETS -81 #define GNUTLS_E_RECEIVED_DISALLOWED_NAME -82 /* GNUTLS_A_ILLEGAL_PARAMETER */ #define GNUTLS_E_CERTIFICATE_REQUIRED -112 /* GNUTLS_A_CERTIFICATE_REQUIRED */ /* returned if you need to generate temporary RSA * parameters. These are needed for export cipher suites. */ #define GNUTLS_E_NO_TEMPORARY_RSA_PARAMS -84 #define GNUTLS_E_NO_COMPRESSION_ALGORITHMS -86 #define GNUTLS_E_NO_CIPHER_SUITES -87 #define GNUTLS_E_OPENPGP_GETKEY_FAILED -88 #define GNUTLS_E_PK_SIG_VERIFY_FAILED -89 #define GNUTLS_E_ILLEGAL_SRP_USERNAME -90 #define GNUTLS_E_SRP_PWD_PARSING_ERROR GNUTLS_E_KEYFILE_PARSING_ERROR #define GNUTLS_E_KEYFILE_PARSING_ERROR -91 #define GNUTLS_E_NO_TEMPORARY_DH_PARAMS -93 /* For certificate and key stuff */ #define GNUTLS_E_ASN1_ELEMENT_NOT_FOUND -67 #define GNUTLS_E_ASN1_IDENTIFIER_NOT_FOUND -68 #define GNUTLS_E_ASN1_DER_ERROR -69 #define GNUTLS_E_ASN1_VALUE_NOT_FOUND -70 #define GNUTLS_E_ASN1_GENERIC_ERROR -71 #define GNUTLS_E_ASN1_VALUE_NOT_VALID -72 #define GNUTLS_E_ASN1_TAG_ERROR -73 #define GNUTLS_E_ASN1_TAG_IMPLICIT -74 #define GNUTLS_E_ASN1_TYPE_ANY_ERROR -75 #define GNUTLS_E_ASN1_SYNTAX_ERROR -76 #define GNUTLS_E_ASN1_DER_OVERFLOW -77 #define GNUTLS_E_OPENPGP_UID_REVOKED -79 #define GNUTLS_E_CERTIFICATE_ERROR -43 #define GNUTLS_E_X509_CERTIFICATE_ERROR GNUTLS_E_CERTIFICATE_ERROR #define GNUTLS_E_CERTIFICATE_KEY_MISMATCH -60 #define GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE -61 /* GNUTLS_A_UNSUPPORTED_CERTIFICATE */ #define GNUTLS_E_X509_UNKNOWN_SAN -62 #define GNUTLS_E_OPENPGP_FINGERPRINT_UNSUPPORTED -94 #define GNUTLS_E_X509_UNSUPPORTED_ATTRIBUTE -95 #define GNUTLS_E_UNKNOWN_HASH_ALGORITHM -96 #define GNUTLS_E_UNKNOWN_PKCS_CONTENT_TYPE -97 #define GNUTLS_E_UNKNOWN_PKCS_BAG_TYPE -98 #define GNUTLS_E_INVALID_PASSWORD -99 #define GNUTLS_E_MAC_VERIFY_FAILED -100 /* for PKCS #12 MAC */ #define GNUTLS_E_CONSTRAINT_ERROR -101 #define GNUTLS_E_WARNING_IA_IPHF_RECEIVED -102 #define GNUTLS_E_WARNING_IA_FPHF_RECEIVED -103 #define GNUTLS_E_IA_VERIFY_FAILED -104 #define GNUTLS_E_UNKNOWN_ALGORITHM -105 #define GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM -106 #define GNUTLS_E_SAFE_RENEGOTIATION_FAILED -107 #define GNUTLS_E_UNSAFE_RENEGOTIATION_DENIED -108 #define GNUTLS_E_UNKNOWN_SRP_USERNAME -109 #define GNUTLS_E_PREMATURE_TERMINATION -110 #define GNUTLS_E_MALFORMED_CIDR -111 #define GNUTLS_E_BASE64_ENCODING_ERROR -201 #define GNUTLS_E_INCOMPATIBLE_GCRYPT_LIBRARY -202 /* obsolete */ #define GNUTLS_E_INCOMPATIBLE_CRYPTO_LIBRARY -202 #define GNUTLS_E_INCOMPATIBLE_LIBTASN1_LIBRARY -203 #define GNUTLS_E_OPENPGP_KEYRING_ERROR -204 #define GNUTLS_E_X509_UNSUPPORTED_OID -205 #define GNUTLS_E_RANDOM_FAILED -206 #define GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR -207 #define GNUTLS_E_OPENPGP_SUBKEY_ERROR -208 #define GNUTLS_E_CRYPTO_ALREADY_REGISTERED GNUTLS_E_ALREADY_REGISTERED #define GNUTLS_E_ALREADY_REGISTERED -209 #define GNUTLS_E_HANDSHAKE_TOO_LARGE -210 #define GNUTLS_E_CRYPTODEV_IOCTL_ERROR -211 #define GNUTLS_E_CRYPTODEV_DEVICE_ERROR -212 #define GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE -213 #define GNUTLS_E_BAD_COOKIE -214 #define GNUTLS_E_OPENPGP_PREFERRED_KEY_ERROR -215 #define GNUTLS_E_INCOMPAT_DSA_KEY_WITH_TLS_PROTOCOL -216 #define GNUTLS_E_INSUFFICIENT_SECURITY -217 #define GNUTLS_E_HEARTBEAT_PONG_RECEIVED -292 #define GNUTLS_E_HEARTBEAT_PING_RECEIVED -293 #define GNUTLS_E_UNRECOGNIZED_NAME -294 /* PKCS11 related */ #define GNUTLS_E_PKCS11_ERROR -300 #define GNUTLS_E_PKCS11_LOAD_ERROR -301 #define GNUTLS_E_PARSING_ERROR -302 #define GNUTLS_E_PKCS11_PIN_ERROR -303 #define GNUTLS_E_PKCS11_SLOT_ERROR -305 #define GNUTLS_E_LOCKING_ERROR -306 #define GNUTLS_E_PKCS11_ATTRIBUTE_ERROR -307 #define GNUTLS_E_PKCS11_DEVICE_ERROR -308 #define GNUTLS_E_PKCS11_DATA_ERROR -309 #define GNUTLS_E_PKCS11_UNSUPPORTED_FEATURE_ERROR -310 #define GNUTLS_E_PKCS11_KEY_ERROR -311 #define GNUTLS_E_PKCS11_PIN_EXPIRED -312 #define GNUTLS_E_PKCS11_PIN_LOCKED -313 #define GNUTLS_E_PKCS11_SESSION_ERROR -314 #define GNUTLS_E_PKCS11_SIGNATURE_ERROR -315 #define GNUTLS_E_PKCS11_TOKEN_ERROR -316 #define GNUTLS_E_PKCS11_USER_ERROR -317 #define GNUTLS_E_CRYPTO_INIT_FAILED -318 #define GNUTLS_E_TIMEDOUT -319 #define GNUTLS_E_USER_ERROR -320 #define GNUTLS_E_ECC_NO_SUPPORTED_CURVES -321 #define GNUTLS_E_ECC_UNSUPPORTED_CURVE -322 #define GNUTLS_E_PKCS11_REQUESTED_OBJECT_NOT_AVAILBLE -323 #define GNUTLS_E_CERTIFICATE_LIST_UNSORTED -324 #define GNUTLS_E_ILLEGAL_PARAMETER -325 /* GNUTLS_A_ILLEGAL_PARAMETER */ #define GNUTLS_E_NO_PRIORITIES_WERE_SET -326 #define GNUTLS_E_X509_UNSUPPORTED_EXTENSION -327 #define GNUTLS_E_SESSION_EOF -328 #define GNUTLS_E_TPM_ERROR -329 #define GNUTLS_E_TPM_KEY_PASSWORD_ERROR -330 #define GNUTLS_E_TPM_SRK_PASSWORD_ERROR -331 #define GNUTLS_E_TPM_SESSION_ERROR -332 #define GNUTLS_E_TPM_KEY_NOT_FOUND -333 #define GNUTLS_E_TPM_UNINITIALIZED -334 #define GNUTLS_E_TPM_NO_LIB -335 #define GNUTLS_E_NO_CERTIFICATE_STATUS -340 #define GNUTLS_E_OCSP_RESPONSE_ERROR -341 #define GNUTLS_E_RANDOM_DEVICE_ERROR -342 #define GNUTLS_E_AUTH_ERROR -343 #define GNUTLS_E_NO_APPLICATION_PROTOCOL -344 #define GNUTLS_E_SOCKETS_INIT_ERROR -345 #define GNUTLS_E_KEY_IMPORT_FAILED -346 #define GNUTLS_E_INAPPROPRIATE_FALLBACK -347 /*GNUTLS_A_INAPPROPRIATE_FALLBACK*/ #define GNUTLS_E_CERTIFICATE_VERIFICATION_ERROR -348 #define GNUTLS_E_PRIVKEY_VERIFICATION_ERROR -349 #define GNUTLS_E_UNEXPECTED_EXTENSIONS_LENGTH -350 /*GNUTLS_A_DECODE_ERROR*/ #define GNUTLS_E_ASN1_EMBEDDED_NULL_IN_STRING -351 #define GNUTLS_E_SELF_TEST_ERROR -400 #define GNUTLS_E_NO_SELF_TEST -401 #define GNUTLS_E_LIB_IN_ERROR_STATE -402 #define GNUTLS_E_PK_GENERATION_ERROR -403 #define GNUTLS_E_IDNA_ERROR -404 #define GNUTLS_E_NEED_FALLBACK -405 #define GNUTLS_E_SESSION_USER_ID_CHANGED -406 #define GNUTLS_E_HANDSHAKE_DURING_FALSE_START -407 #define GNUTLS_E_UNAVAILABLE_DURING_HANDSHAKE -408 #define GNUTLS_E_PK_INVALID_PUBKEY -409 #define GNUTLS_E_PK_INVALID_PRIVKEY -410 #define GNUTLS_E_NOT_YET_ACTIVATED -411 #define GNUTLS_E_INVALID_UTF8_STRING -412 #define GNUTLS_E_NO_EMBEDDED_DATA -413 #define GNUTLS_E_INVALID_UTF8_EMAIL -414 #define GNUTLS_E_INVALID_PASSWORD_STRING -415 #define GNUTLS_E_CERTIFICATE_TIME_ERROR -416 #define GNUTLS_E_RECORD_OVERFLOW -417 /* GNUTLS_A_RECORD_OVERFLOW */ #define GNUTLS_E_ASN1_TIME_ERROR -418 #define GNUTLS_E_INCOMPATIBLE_SIG_WITH_KEY -419 #define GNUTLS_E_PK_INVALID_PUBKEY_PARAMS -420 #define GNUTLS_E_PK_NO_VALIDATION_PARAMS -421 #define GNUTLS_E_OCSP_MISMATCH_WITH_CERTS -422 #define GNUTLS_E_NO_COMMON_KEY_SHARE -423 #define GNUTLS_E_REAUTH_REQUEST -424 #define GNUTLS_E_TOO_MANY_MATCHES -425 #define GNUTLS_E_CRL_VERIFICATION_ERROR -426 #define GNUTLS_E_MISSING_EXTENSION -427 #define GNUTLS_E_DB_ENTRY_EXISTS -428 #define GNUTLS_E_EARLY_DATA_REJECTED -429 #define GNUTLS_E_X509_DUPLICATE_EXTENSION -430 #define GNUTLS_E_UNIMPLEMENTED_FEATURE -1250 /* Internal errors of the library; will never be returned * to a calling application */ #define GNUTLS_E_INT_RET_0 -1251 #define GNUTLS_E_INT_CHECK_AGAIN -1252 #define GNUTLS_E_APPLICATION_ERROR_MAX -65000 #define GNUTLS_E_APPLICATION_ERROR_MIN -65500 /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #include #endif /* GNUTLS_GNUTLS_H */ ================================================ FILE: thirdparty/32/include/gnutls/ocsp.h ================================================ /* * Copyright (C) 2011-2012 Free Software Foundation, Inc. * * Author: Simon Josefsson * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* Online Certificate Status Protocol - RFC 2560 */ #ifndef GNUTLS_OCSP_H #define GNUTLS_OCSP_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_OCSP_NONCE "1.3.6.1.5.5.7.48.1.2" /** * gnutls_ocsp_print_formats_t: * @GNUTLS_OCSP_PRINT_FULL: Full information about OCSP request/response. * @GNUTLS_OCSP_PRINT_COMPACT: More compact information about OCSP request/response. * * Enumeration of different OCSP printing variants. */ typedef enum gnutls_ocsp_print_formats_t { GNUTLS_OCSP_PRINT_FULL = 0, GNUTLS_OCSP_PRINT_COMPACT = 1 } gnutls_ocsp_print_formats_t; /** * gnutls_ocsp_resp_status_t: * @GNUTLS_OCSP_RESP_SUCCESSFUL: Response has valid confirmations. * @GNUTLS_OCSP_RESP_MALFORMEDREQUEST: Illegal confirmation request * @GNUTLS_OCSP_RESP_INTERNALERROR: Internal error in issuer * @GNUTLS_OCSP_RESP_TRYLATER: Try again later * @GNUTLS_OCSP_RESP_SIGREQUIRED: Must sign the request * @GNUTLS_OCSP_RESP_UNAUTHORIZED: Request unauthorized * * Enumeration of different OCSP response status codes. */ typedef enum gnutls_ocsp_resp_status_t { GNUTLS_OCSP_RESP_SUCCESSFUL = 0, GNUTLS_OCSP_RESP_MALFORMEDREQUEST = 1, GNUTLS_OCSP_RESP_INTERNALERROR = 2, GNUTLS_OCSP_RESP_TRYLATER = 3, GNUTLS_OCSP_RESP_SIGREQUIRED = 5, GNUTLS_OCSP_RESP_UNAUTHORIZED = 6 } gnutls_ocsp_resp_status_t; /** * gnutls_ocsp_cert_status_t: * @GNUTLS_OCSP_CERT_GOOD: Positive response to status inquiry. * @GNUTLS_OCSP_CERT_REVOKED: Certificate has been revoked. * @GNUTLS_OCSP_CERT_UNKNOWN: The responder doesn't know about the * certificate. * * Enumeration of different OCSP response certificate status codes. */ typedef enum gnutls_ocsp_cert_status_t { GNUTLS_OCSP_CERT_GOOD = 0, GNUTLS_OCSP_CERT_REVOKED = 1, GNUTLS_OCSP_CERT_UNKNOWN = 2 } gnutls_ocsp_cert_status_t; /** * gnutls_x509_crl_reason_t: * @GNUTLS_X509_CRLREASON_UNSPECIFIED: Unspecified reason. * @GNUTLS_X509_CRLREASON_KEYCOMPROMISE: Private key compromised. * @GNUTLS_X509_CRLREASON_CACOMPROMISE: CA compromised. * @GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED: Affiliation has changed. * @GNUTLS_X509_CRLREASON_SUPERSEDED: Certificate superseded. * @GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION: Operation has ceased. * @GNUTLS_X509_CRLREASON_CERTIFICATEHOLD: Certificate is on hold. * @GNUTLS_X509_CRLREASON_REMOVEFROMCRL: Will be removed from delta CRL. * @GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN: Privilege withdrawn. * @GNUTLS_X509_CRLREASON_AACOMPROMISE: AA compromised. * * Enumeration of different reason codes. Note that this * corresponds to the CRLReason ASN.1 enumeration type, and not the * ReasonFlags ASN.1 bit string. */ typedef enum gnutls_x509_crl_reason_t { GNUTLS_X509_CRLREASON_UNSPECIFIED = 0, GNUTLS_X509_CRLREASON_KEYCOMPROMISE = 1, GNUTLS_X509_CRLREASON_CACOMPROMISE = 2, GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED = 3, GNUTLS_X509_CRLREASON_SUPERSEDED = 4, GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION = 5, GNUTLS_X509_CRLREASON_CERTIFICATEHOLD = 6, GNUTLS_X509_CRLREASON_REMOVEFROMCRL = 8, GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN = 9, GNUTLS_X509_CRLREASON_AACOMPROMISE = 10 } gnutls_x509_crl_reason_t; /* When adding a verify failure reason update: * _gnutls_ocsp_verify_status_to_str() */ /** * gnutls_ocsp_verify_reason_t: * @GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND: Signer cert not found. * @GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR: Signer keyusage bits incorrect. * @GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER: Signer is not trusted. * @GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM: Signature using insecure algorithm. * @GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE: Signature mismatch. * @GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED: Signer cert is not yet activated. * @GNUTLS_OCSP_VERIFY_CERT_EXPIRED: Signer cert has expired. * * Enumeration of OCSP verify status codes, used by * gnutls_ocsp_resp_verify() and gnutls_ocsp_resp_verify_direct(). */ typedef enum gnutls_ocsp_verify_reason_t { GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND = 1, GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR = 2, GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER = 4, GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM = 8, GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE = 16, GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED = 32, GNUTLS_OCSP_VERIFY_CERT_EXPIRED = 64 } gnutls_ocsp_verify_reason_t; struct gnutls_ocsp_req_int; typedef struct gnutls_ocsp_req_int *gnutls_ocsp_req_t; typedef const struct gnutls_ocsp_req_int *gnutls_ocsp_req_const_t; int gnutls_ocsp_req_init(gnutls_ocsp_req_t * req); void gnutls_ocsp_req_deinit(gnutls_ocsp_req_t req); int gnutls_ocsp_req_import(gnutls_ocsp_req_t req, const gnutls_datum_t * data); int gnutls_ocsp_req_export(gnutls_ocsp_req_const_t req, gnutls_datum_t * data); int gnutls_ocsp_req_print(gnutls_ocsp_req_const_t req, gnutls_ocsp_print_formats_t format, gnutls_datum_t * out); int gnutls_ocsp_req_get_version(gnutls_ocsp_req_const_t req); int gnutls_ocsp_req_get_cert_id(gnutls_ocsp_req_const_t req, unsigned indx, gnutls_digest_algorithm_t * digest, gnutls_datum_t * issuer_name_hash, gnutls_datum_t * issuer_key_hash, gnutls_datum_t * serial_number); int gnutls_ocsp_req_add_cert_id(gnutls_ocsp_req_t req, gnutls_digest_algorithm_t digest, const gnutls_datum_t * issuer_name_hash, const gnutls_datum_t * issuer_key_hash, const gnutls_datum_t * serial_number); int gnutls_ocsp_req_add_cert(gnutls_ocsp_req_t req, gnutls_digest_algorithm_t digest, gnutls_x509_crt_t issuer, gnutls_x509_crt_t cert); int gnutls_ocsp_req_get_extension(gnutls_ocsp_req_const_t req, unsigned indx, gnutls_datum_t * oid, unsigned int *critical, gnutls_datum_t * data); int gnutls_ocsp_req_set_extension(gnutls_ocsp_req_t req, const char *oid, unsigned int critical, const gnutls_datum_t * data); int gnutls_ocsp_req_get_nonce(gnutls_ocsp_req_const_t req, unsigned int *critical, gnutls_datum_t * nonce); int gnutls_ocsp_req_set_nonce(gnutls_ocsp_req_t req, unsigned int critical, const gnutls_datum_t * nonce); int gnutls_ocsp_req_randomize_nonce(gnutls_ocsp_req_t req); struct gnutls_ocsp_resp_int; typedef struct gnutls_ocsp_resp_int *gnutls_ocsp_resp_t; typedef const struct gnutls_ocsp_resp_int *gnutls_ocsp_resp_const_t; int gnutls_ocsp_resp_init(gnutls_ocsp_resp_t * resp); void gnutls_ocsp_resp_deinit(gnutls_ocsp_resp_t resp); int gnutls_ocsp_resp_import(gnutls_ocsp_resp_t resp, const gnutls_datum_t * data); int gnutls_ocsp_resp_import2(gnutls_ocsp_resp_t resp, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t fmt); int gnutls_ocsp_resp_export(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * data); int gnutls_ocsp_resp_export2(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * data, gnutls_x509_crt_fmt_t fmt); int gnutls_ocsp_resp_print(gnutls_ocsp_resp_const_t resp, gnutls_ocsp_print_formats_t format, gnutls_datum_t * out); int gnutls_ocsp_resp_get_status(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_response(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * response_type_oid, gnutls_datum_t * response); int gnutls_ocsp_resp_get_version(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_responder(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * dn); int gnutls_ocsp_resp_get_responder2(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * dn, unsigned flags); /* the raw key ID of the responder */ #define GNUTLS_OCSP_RESP_ID_KEY 1 /* the raw DN of the responder */ #define GNUTLS_OCSP_RESP_ID_DN 2 int gnutls_ocsp_resp_get_responder_raw_id(gnutls_ocsp_resp_const_t resp, unsigned type, gnutls_datum_t * raw); time_t gnutls_ocsp_resp_get_produced(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_single(gnutls_ocsp_resp_const_t resp, unsigned indx, gnutls_digest_algorithm_t * digest, gnutls_datum_t * issuer_name_hash, gnutls_datum_t * issuer_key_hash, gnutls_datum_t * serial_number, unsigned int *cert_status, time_t * this_update, time_t * next_update, time_t * revocation_time, unsigned int *revocation_reason); int gnutls_ocsp_resp_get_extension(gnutls_ocsp_resp_const_t resp, unsigned indx, gnutls_datum_t * oid, unsigned int *critical, gnutls_datum_t * data); int gnutls_ocsp_resp_get_nonce(gnutls_ocsp_resp_const_t resp, unsigned int *critical, gnutls_datum_t * nonce); int gnutls_ocsp_resp_get_signature_algorithm(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_signature(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * sig); int gnutls_ocsp_resp_get_certs(gnutls_ocsp_resp_const_t resp, gnutls_x509_crt_t ** certs, size_t * ncerts); int gnutls_ocsp_resp_verify_direct(gnutls_ocsp_resp_const_t resp, gnutls_x509_crt_t issuer, unsigned int *verify, unsigned int flags); int gnutls_ocsp_resp_verify(gnutls_ocsp_resp_const_t resp, gnutls_x509_trust_list_t trustlist, unsigned int *verify, unsigned int flags); int gnutls_ocsp_resp_check_crt(gnutls_ocsp_resp_const_t resp, unsigned int indx, gnutls_x509_crt_t crt); int gnutls_ocsp_resp_list_import2(gnutls_ocsp_resp_t **ocsps, unsigned int *size, const gnutls_datum_t *resp_data, gnutls_x509_crt_fmt_t format, unsigned int flags); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_OCSP_H */ ================================================ FILE: thirdparty/32/include/gnutls/openpgp.h ================================================ /* * Copyright (C) 2003-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the OpenPGP * key and private key parsing functions. */ #ifndef GNUTLS_OPENPGP_H #define GNUTLS_OPENPGP_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* Openpgp certificate stuff */ /** * gnutls_openpgp_crt_fmt_t: * @GNUTLS_OPENPGP_FMT_RAW: OpenPGP certificate in raw format. * @GNUTLS_OPENPGP_FMT_BASE64: OpenPGP certificate in base64 format. * * Enumeration of different OpenPGP key formats. */ typedef enum gnutls_openpgp_crt_fmt { GNUTLS_OPENPGP_FMT_RAW, GNUTLS_OPENPGP_FMT_BASE64 } gnutls_openpgp_crt_fmt_t; #define GNUTLS_OPENPGP_KEYID_SIZE 8 #define GNUTLS_OPENPGP_V4_FINGERPRINT_SIZE 20 typedef unsigned char gnutls_openpgp_keyid_t[GNUTLS_OPENPGP_KEYID_SIZE]; /* gnutls_openpgp_cert_t should be defined in gnutls.h */ /* initializes the memory for gnutls_openpgp_crt_t struct */ int gnutls_openpgp_crt_init(gnutls_openpgp_crt_t * key) _GNUTLS_GCC_ATTR_DEPRECATED; /* frees all memory */ void gnutls_openpgp_crt_deinit(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_import(gnutls_openpgp_crt_t key, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_export(gnutls_openpgp_crt_t key, gnutls_openpgp_crt_fmt_t format, void *output_data, size_t * output_data_size) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_export2(gnutls_openpgp_crt_t key, gnutls_openpgp_crt_fmt_t format, gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_print(gnutls_openpgp_crt_t cert, gnutls_certificate_print_formats_t format, gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED; /* The key_usage flags are defined in gnutls.h. They are * the GNUTLS_KEY_* definitions. */ #define GNUTLS_OPENPGP_MASTER_KEYID_IDX INT_MAX int gnutls_openpgp_crt_get_key_usage(gnutls_openpgp_crt_t key, unsigned int *key_usage) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_fingerprint(gnutls_openpgp_crt_t key, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_fingerprint(gnutls_openpgp_crt_t key, unsigned int idx, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_name(gnutls_openpgp_crt_t key, int idx, char *buf, size_t * sizeof_buf) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_crt_get_pk_algorithm(gnutls_openpgp_crt_t key, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_version(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_creation_time(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_expiration_time(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_key_id(gnutls_openpgp_crt_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_check_hostname(gnutls_openpgp_crt_t key, const char *hostname) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_check_hostname2(gnutls_openpgp_crt_t key, const char *hostname, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_check_email(gnutls_openpgp_crt_t key, const char *email, unsigned flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_revoked_status(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_count(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_idx(gnutls_openpgp_crt_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_revoked_status (gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_crt_get_subkey_pk_algorithm(gnutls_openpgp_crt_t key, unsigned int idx, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_subkey_creation_time (gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_subkey_expiration_time (gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_id(gnutls_openpgp_crt_t key, unsigned int idx, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_usage(gnutls_openpgp_crt_t key, unsigned int idx, unsigned int *key_usage) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_pk_dsa_raw(gnutls_openpgp_crt_t crt, unsigned int idx, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_pk_rsa_raw(gnutls_openpgp_crt_t crt, unsigned int idx, gnutls_datum_t * m, gnutls_datum_t * e) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_pk_dsa_raw(gnutls_openpgp_crt_t crt, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_pk_rsa_raw(gnutls_openpgp_crt_t crt, gnutls_datum_t * m, gnutls_datum_t * e) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_preferred_key_id(gnutls_openpgp_crt_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_set_preferred_key_id(gnutls_openpgp_crt_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; /* privkey stuff. */ int gnutls_openpgp_privkey_init(gnutls_openpgp_privkey_t * key) _GNUTLS_GCC_ATTR_DEPRECATED; void gnutls_openpgp_privkey_deinit(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_privkey_get_pk_algorithm (gnutls_openpgp_privkey_t key, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_sec_param_t gnutls_openpgp_privkey_sec_param(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_import(gnutls_openpgp_privkey_t key, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format, const char *password, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_fingerprint(gnutls_openpgp_privkey_t key, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_fingerprint (gnutls_openpgp_privkey_t key, unsigned int idx, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_key_id(gnutls_openpgp_privkey_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_count(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_idx(gnutls_openpgp_privkey_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_revoked_status (gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_revoked_status (gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_privkey_get_subkey_pk_algorithm (gnutls_openpgp_privkey_t key, unsigned int idx, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_privkey_get_subkey_expiration_time (gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_id(gnutls_openpgp_privkey_t key, unsigned int idx, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_privkey_get_subkey_creation_time (gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_subkey_dsa_raw (gnutls_openpgp_privkey_t pkey, unsigned int idx, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_subkey_rsa_raw (gnutls_openpgp_privkey_t pkey, unsigned int idx, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_dsa_raw(gnutls_openpgp_privkey_t pkey, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_rsa_raw(gnutls_openpgp_privkey_t pkey, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export(gnutls_openpgp_privkey_t key, gnutls_openpgp_crt_fmt_t format, const char *password, unsigned int flags, void *output_data, size_t * output_data_size) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export2(gnutls_openpgp_privkey_t key, gnutls_openpgp_crt_fmt_t format, const char *password, unsigned int flags, gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_set_preferred_key_id (gnutls_openpgp_privkey_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_preferred_key_id (gnutls_openpgp_privkey_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_auth_subkey(gnutls_openpgp_crt_t crt, gnutls_openpgp_keyid_t keyid, unsigned int flag) _GNUTLS_GCC_ATTR_DEPRECATED; /* Keyring stuff. */ int gnutls_openpgp_keyring_init(gnutls_openpgp_keyring_t * keyring) _GNUTLS_GCC_ATTR_DEPRECATED; void gnutls_openpgp_keyring_deinit(gnutls_openpgp_keyring_t keyring) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_import(gnutls_openpgp_keyring_t keyring, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_check_id(gnutls_openpgp_keyring_t ring, const gnutls_openpgp_keyid_t keyid, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_verify_ring(gnutls_openpgp_crt_t key, gnutls_openpgp_keyring_t keyring, unsigned int flags, unsigned int *verify /* the output of the verification */ ) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_verify_self(gnutls_openpgp_crt_t key, unsigned int flags, unsigned int *verify) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_get_crt(gnutls_openpgp_keyring_t ring, unsigned int idx, gnutls_openpgp_crt_t * cert) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_get_crt_count(gnutls_openpgp_keyring_t ring) _GNUTLS_GCC_ATTR_DEPRECATED; /** * gnutls_openpgp_recv_key_func: * @session: a TLS session * @keyfpr: key fingerprint * @keyfpr_length: length of key fingerprint * @key: output key. * * A callback of this type is used to retrieve OpenPGP keys. Only * useful on the server, and will only be used if the peer send a key * fingerprint instead of a full key. See also * gnutls_openpgp_set_recv_key_function(). * * The variable @key must be allocated using gnutls_malloc(). * * Returns: On success, %GNUTLS_E_SUCCESS (zero) is returned, * otherwise an error code is returned. */ typedef int (*gnutls_openpgp_recv_key_func) (gnutls_session_t session, const unsigned char *keyfpr, unsigned int keyfpr_length, gnutls_datum_t * key); void gnutls_openpgp_set_recv_key_function(gnutls_session_t session, gnutls_openpgp_recv_key_func func) _GNUTLS_GCC_ATTR_DEPRECATED; /* certificate authentication stuff. */ int gnutls_certificate_set_openpgp_key (gnutls_certificate_credentials_t res, gnutls_openpgp_crt_t crt, gnutls_openpgp_privkey_t pkey) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_get_openpgp_key(gnutls_certificate_credentials_t res, unsigned index, gnutls_openpgp_privkey_t *key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_get_openpgp_crt(gnutls_certificate_credentials_t res, unsigned index, gnutls_openpgp_crt_t **crt_list, unsigned *crt_list_size) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_file (gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_mem (gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_file2 (gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, const char *subkey_id, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_mem2 (gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, const char *subkey_id, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_keyring_mem (gnutls_certificate_credentials_t c, const unsigned char *data, size_t dlen, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_keyring_file (gnutls_certificate_credentials_t c, const char *file, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_OPENPGP_H */ ================================================ FILE: thirdparty/32/include/gnutls/pkcs11.h ================================================ /* * Copyright (C) 2010-2012 Free Software Foundation, Inc. * Copyright (C) 2016-2018 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_PKCS11_H #define GNUTLS_PKCS11_H #include #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_PKCS11_MAX_PIN_LEN 256 /** * gnutls_pkcs11_token_callback_t: * @userdata: user-controlled data from gnutls_pkcs11_set_token_function(). * @label: token label. * @retry: retry counter, initially 0. * * Token callback function. The callback will be used to ask the user * to re-insert the token with given (null terminated) label. The * callback should return zero if token has been inserted by user and * a negative error code otherwise. It might be called multiple times * if the token is not detected and the retry counter will be * increased. * * Returns: %GNUTLS_E_SUCCESS (0) on success or a negative error code * on error. * * Since: 2.12.0 **/ typedef int (*gnutls_pkcs11_token_callback_t) (void *const userdata, const char *const label, unsigned retry); struct gnutls_pkcs11_obj_st; typedef struct gnutls_pkcs11_obj_st *gnutls_pkcs11_obj_t; #define GNUTLS_PKCS11_FLAG_MANUAL 0 /* Manual loading of libraries */ #define GNUTLS_PKCS11_FLAG_AUTO 1 /* Automatically load libraries by reading /etc/gnutls/pkcs11.conf */ #define GNUTLS_PKCS11_FLAG_AUTO_TRUSTED (1<<1) /* Automatically load trusted libraries by reading /etc/gnutls/pkcs11.conf */ /* pkcs11.conf format: * load = /lib/xxx-pkcs11.so * load = /lib/yyy-pkcs11.so */ int gnutls_pkcs11_init(unsigned int flags, const char *deprecated_config_file); int gnutls_pkcs11_reinit(void); void gnutls_pkcs11_deinit(void); void gnutls_pkcs11_set_token_function (gnutls_pkcs11_token_callback_t fn, void *userdata); void gnutls_pkcs11_set_pin_function(gnutls_pin_callback_t fn, void *userdata); gnutls_pin_callback_t gnutls_pkcs11_get_pin_function(void **userdata); int gnutls_pkcs11_add_provider(const char *name, const char *params); int gnutls_pkcs11_obj_init(gnutls_pkcs11_obj_t * obj); void gnutls_pkcs11_obj_set_pin_function(gnutls_pkcs11_obj_t obj, gnutls_pin_callback_t fn, void *userdata); /** * gnutls_pkcs11_obj_flags: * @GNUTLS_PKCS11_OBJ_FLAG_LOGIN: Force login in the token for the operation (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED: object marked as trusted (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE: object is explicitly marked as sensitive -unexportable (store). * @GNUTLS_PKCS11_OBJ_FLAG_LOGIN_SO: force login as a security officer in the token for the operation (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE: marked as private -requires PIN to access (store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_PRIVATE: marked as not private (store). * @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_ANY: When retrieving an object, do not set any requirements (store). * @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_TRUSTED: When retrieving an object, only retrieve the marked as trusted (alias to %GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED). * In gnutls_pkcs11_crt_is_known() it implies %GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_COMPARE if %GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY is not given. * @GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED: When writing an object, mark it as distrusted (store). * @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_DISTRUSTED: When retrieving an object, only retrieve the marked as distrusted (seek). * @GNUTLS_PKCS11_OBJ_FLAG_COMPARE: When checking an object's presence, fully compare it before returning any result (seek). * @GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY: When checking an object's presence, compare the key before returning any result (seek). * @GNUTLS_PKCS11_OBJ_FLAG_PRESENT_IN_TRUSTED_MODULE: The object must be present in a marked as trusted module (seek). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_CA: Mark the object as a CA (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_KEY_WRAP: Mark the generated key pair as wrapping and unwrapping keys (store). * @GNUTLS_PKCS11_OBJ_FLAG_OVERWRITE_TRUSTMOD_EXT: When an issuer is requested, override its extensions with the ones present in the trust module (seek). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH: Mark the key pair as requiring authentication (pin entry) before every operation (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_EXTRACTABLE: Mark the key pair as being extractable (store). * @GNUTLS_PKCS11_OBJ_FLAG_NEVER_EXTRACTABLE: If set, the object was never marked as extractable (store). * @GNUTLS_PKCS11_OBJ_FLAG_CRT: When searching, restrict to certificates only (seek). * @GNUTLS_PKCS11_OBJ_FLAG_PUBKEY: When searching, restrict to public key objects only (seek). * @GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY: When searching, restrict to private key objects only (seek). * @GNUTLS_PKCS11_OBJ_FLAG_NO_STORE_PUBKEY: When generating a keypair don't store the public key (store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE: object marked as not sensitive -exportable (store). * * Enumeration of different PKCS #11 object flags. Some flags are used * to mark objects when storing, while others are also used while seeking * or retrieving objects. */ typedef enum gnutls_pkcs11_obj_flags { GNUTLS_PKCS11_OBJ_FLAG_LOGIN = (1<<0), GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED = (1<<1), GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE = (1<<2), GNUTLS_PKCS11_OBJ_FLAG_LOGIN_SO = (1<<3), GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE = (1<<4), GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_PRIVATE = (1<<5), GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_ANY = (1<<6), GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_TRUSTED = GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED, GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED = (1<<8), GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_DISTRUSTED = GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED, GNUTLS_PKCS11_OBJ_FLAG_COMPARE = (1<<9), GNUTLS_PKCS11_OBJ_FLAG_PRESENT_IN_TRUSTED_MODULE = (1<<10), GNUTLS_PKCS11_OBJ_FLAG_MARK_CA = (1<<11), GNUTLS_PKCS11_OBJ_FLAG_MARK_KEY_WRAP = (1<<12), GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY = (1<<13), GNUTLS_PKCS11_OBJ_FLAG_OVERWRITE_TRUSTMOD_EXT = (1<<14), GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH = (1<<15), GNUTLS_PKCS11_OBJ_FLAG_MARK_EXTRACTABLE = (1<<16), GNUTLS_PKCS11_OBJ_FLAG_NEVER_EXTRACTABLE = (1<<17), GNUTLS_PKCS11_OBJ_FLAG_CRT = (1<<18), GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY = (1<<19), GNUTLS_PKCS11_OBJ_FLAG_PUBKEY = (1<<20), GNUTLS_PKCS11_OBJ_FLAG_NO_STORE_PUBKEY = GNUTLS_PKCS11_OBJ_FLAG_PUBKEY, GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY = (1<<21), GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE = (1<<22), /* flags 1<<29 and later are reserved - see pkcs11_int.h */ } gnutls_pkcs11_obj_flags; #define gnutls_pkcs11_obj_attr_t gnutls_pkcs11_obj_flags /** * gnutls_pkcs11_url_type_t: * @GNUTLS_PKCS11_URL_GENERIC: A generic-purpose URL. * @GNUTLS_PKCS11_URL_LIB: A URL that specifies the library used as well. * @GNUTLS_PKCS11_URL_LIB_VERSION: A URL that specifies the library and its version. * * Enumeration of different URL extraction flags. */ typedef enum { GNUTLS_PKCS11_URL_GENERIC, /* URL specifies the object on token level */ GNUTLS_PKCS11_URL_LIB, /* URL specifies the object on module level */ GNUTLS_PKCS11_URL_LIB_VERSION /* URL specifies the object on module and version level */ } gnutls_pkcs11_url_type_t; int gnutls_pkcs11_obj_import_url(gnutls_pkcs11_obj_t obj, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_obj_export_url(gnutls_pkcs11_obj_t obj, gnutls_pkcs11_url_type_t detailed, char **url); void gnutls_pkcs11_obj_deinit(gnutls_pkcs11_obj_t obj); int gnutls_pkcs11_obj_export(gnutls_pkcs11_obj_t obj, void *output_data, size_t * output_data_size); int gnutls_pkcs11_obj_export2(gnutls_pkcs11_obj_t obj, gnutls_datum_t * out); int gnutls_pkcs11_obj_export3(gnutls_pkcs11_obj_t obj, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * out); int gnutls_pkcs11_get_raw_issuer(const char *url, gnutls_x509_crt_t cert, gnutls_datum_t * issuer, gnutls_x509_crt_fmt_t fmt, unsigned int flags); int gnutls_pkcs11_get_raw_issuer_by_dn (const char *url, const gnutls_datum_t *dn, gnutls_datum_t *issuer, gnutls_x509_crt_fmt_t fmt, unsigned int flags); int gnutls_pkcs11_get_raw_issuer_by_subject_key_id (const char *url, const gnutls_datum_t *dn, const gnutls_datum_t *spki, gnutls_datum_t *issuer, gnutls_x509_crt_fmt_t fmt, unsigned int flags); unsigned gnutls_pkcs11_crt_is_known(const char *url, gnutls_x509_crt_t cert, unsigned int flags); #if 0 /* for documentation */ int gnutls_pkcs11_copy_x509_crt(const char *token_url, gnutls_x509_crt_t crt, const char *label, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_copy_x509_privkey(const char *token_url, gnutls_x509_privkey_t key, const char *label, unsigned int key_usage, unsigned int flags); int gnutls_pkcs11_privkey_generate2(const char *url, gnutls_pk_algorithm_t pk, unsigned int bits, const char *label, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * pubkey, unsigned int flags); int gnutls_pkcs11_privkey_generate(const char *url, gnutls_pk_algorithm_t pk, unsigned int bits, const char *label, unsigned int flags); #endif int gnutls_pkcs11_copy_pubkey(const char *token_url, gnutls_pubkey_t crt, const char *label, const gnutls_datum_t *cid, unsigned int key_usage, unsigned int flags); #define gnutls_pkcs11_copy_x509_crt(url, crt, label, flags) \ gnutls_pkcs11_copy_x509_crt2(url, crt, label, NULL, flags) int gnutls_pkcs11_copy_x509_crt2(const char *token_url, gnutls_x509_crt_t crt, const char *label, const gnutls_datum_t *id, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */); #define gnutls_pkcs11_copy_x509_privkey(url, key, label, usage, flags) \ gnutls_pkcs11_copy_x509_privkey2(url, key, label, NULL, usage, flags) int gnutls_pkcs11_copy_x509_privkey2(const char *token_url, gnutls_x509_privkey_t key, const char *label, const gnutls_datum_t *cid, unsigned int key_usage /*GNUTLS_KEY_* */ , unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_delete_url(const char *object_url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_copy_secret_key(const char *token_url, gnutls_datum_t * key, const char *label, unsigned int key_usage /* GNUTLS_KEY_* */ , unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); /** * gnutls_pkcs11_obj_info_t: * @GNUTLS_PKCS11_OBJ_ID_HEX: The object ID in hex. Null-terminated text. * @GNUTLS_PKCS11_OBJ_LABEL: The object label. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_LABEL: The token's label. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_SERIAL: The token's serial number. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_MANUFACTURER: The token's manufacturer. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_MODEL: The token's model. Null-terminated text. * @GNUTLS_PKCS11_OBJ_ID: The object ID. Raw bytes. * @GNUTLS_PKCS11_OBJ_LIBRARY_VERSION: The library's version. Null-terminated text. * @GNUTLS_PKCS11_OBJ_LIBRARY_DESCRIPTION: The library's description. Null-terminated text. * @GNUTLS_PKCS11_OBJ_LIBRARY_MANUFACTURER: The library's manufacturer name. Null-terminated text. * * Enumeration of several object information types. */ typedef enum { GNUTLS_PKCS11_OBJ_ID_HEX = 1, GNUTLS_PKCS11_OBJ_LABEL, GNUTLS_PKCS11_OBJ_TOKEN_LABEL, GNUTLS_PKCS11_OBJ_TOKEN_SERIAL, GNUTLS_PKCS11_OBJ_TOKEN_MANUFACTURER, GNUTLS_PKCS11_OBJ_TOKEN_MODEL, GNUTLS_PKCS11_OBJ_ID, /* the pkcs11 provider library info */ GNUTLS_PKCS11_OBJ_LIBRARY_VERSION, GNUTLS_PKCS11_OBJ_LIBRARY_DESCRIPTION, GNUTLS_PKCS11_OBJ_LIBRARY_MANUFACTURER } gnutls_pkcs11_obj_info_t; int gnutls_pkcs11_obj_get_ptr(gnutls_pkcs11_obj_t obj, void **ptr, void **session, void **ohandle, unsigned long *slot_id, unsigned int flags); int gnutls_pkcs11_obj_get_info(gnutls_pkcs11_obj_t obj, gnutls_pkcs11_obj_info_t itype, void *output, size_t * output_size); int gnutls_pkcs11_obj_set_info(gnutls_pkcs11_obj_t obj, gnutls_pkcs11_obj_info_t itype, const void *data, size_t data_size, unsigned flags); #define GNUTLS_PKCS11_OBJ_ATTR_CRT_ALL GNUTLS_PKCS11_OBJ_FLAG_CRT #define GNUTLS_PKCS11_OBJ_ATTR_MATCH 0 /* always match the given URL */ #define GNUTLS_PKCS11_OBJ_ATTR_ALL 0 /* match everything! */ #define GNUTLS_PKCS11_OBJ_ATTR_CRT_TRUSTED (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED) #define GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY) #define GNUTLS_PKCS11_OBJ_ATTR_CRT_TRUSTED_CA (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_MARK_CA|GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED) #define GNUTLS_PKCS11_OBJ_ATTR_PUBKEY GNUTLS_PKCS11_OBJ_FLAG_PUBKEY #define GNUTLS_PKCS11_OBJ_ATTR_PRIVKEY GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY /** * gnutls_pkcs11_token_info_t: * @GNUTLS_PKCS11_TOKEN_LABEL: The token's label (string) * @GNUTLS_PKCS11_TOKEN_SERIAL: The token's serial number (string) * @GNUTLS_PKCS11_TOKEN_MANUFACTURER: The token's manufacturer (string) * @GNUTLS_PKCS11_TOKEN_MODEL: The token's model (string) * @GNUTLS_PKCS11_TOKEN_MODNAME: The token's module name (string - since 3.4.3). This value is * unavailable for providers which were manually loaded. * * Enumeration of types for retrieving token information. */ typedef enum { GNUTLS_PKCS11_TOKEN_LABEL, GNUTLS_PKCS11_TOKEN_SERIAL, GNUTLS_PKCS11_TOKEN_MANUFACTURER, GNUTLS_PKCS11_TOKEN_MODEL, GNUTLS_PKCS11_TOKEN_MODNAME } gnutls_pkcs11_token_info_t; /** * gnutls_pkcs11_obj_type_t: * @GNUTLS_PKCS11_OBJ_UNKNOWN: Unknown PKCS11 object. * @GNUTLS_PKCS11_OBJ_X509_CRT: X.509 certificate. * @GNUTLS_PKCS11_OBJ_PUBKEY: Public key. * @GNUTLS_PKCS11_OBJ_PRIVKEY: Private key. * @GNUTLS_PKCS11_OBJ_SECRET_KEY: Secret key. * @GNUTLS_PKCS11_OBJ_DATA: Data object. * @GNUTLS_PKCS11_OBJ_X509_CRT_EXTENSION: X.509 certificate extension (supported by p11-kit trust module only). * * Enumeration of object types. */ typedef enum { GNUTLS_PKCS11_OBJ_UNKNOWN, GNUTLS_PKCS11_OBJ_X509_CRT, GNUTLS_PKCS11_OBJ_PUBKEY, GNUTLS_PKCS11_OBJ_PRIVKEY, GNUTLS_PKCS11_OBJ_SECRET_KEY, GNUTLS_PKCS11_OBJ_DATA, GNUTLS_PKCS11_OBJ_X509_CRT_EXTENSION } gnutls_pkcs11_obj_type_t; int gnutls_pkcs11_token_init(const char *token_url, const char *so_pin, const char *label); int gnutls_pkcs11_token_get_ptr(const char *url, void **ptr, unsigned long *slot_id, unsigned int flags); int gnutls_pkcs11_token_get_mechanism(const char *url, unsigned int idx, unsigned long *mechanism); unsigned gnutls_pkcs11_token_check_mechanism(const char *url, unsigned long mechanism, void *ptr, unsigned psize, unsigned flags); int gnutls_pkcs11_token_set_pin(const char *token_url, const char *oldpin, const char *newpin, unsigned int flags /*gnutls_pin_flag_t */); int gnutls_pkcs11_token_get_url(unsigned int seq, gnutls_pkcs11_url_type_t detailed, char **url); int gnutls_pkcs11_token_get_info(const char *url, gnutls_pkcs11_token_info_t ttype, void *output, size_t * output_size); #define GNUTLS_PKCS11_TOKEN_HW 1 #define GNUTLS_PKCS11_TOKEN_TRUSTED (1<<1) /* p11-kit trusted */ #define GNUTLS_PKCS11_TOKEN_RNG (1<<2) /* CKF_RNG */ #define GNUTLS_PKCS11_TOKEN_LOGIN_REQUIRED (1<<3) /* CKF_LOGIN_REQUIRED */ #define GNUTLS_PKCS11_TOKEN_PROTECTED_AUTHENTICATION_PATH (1<<4) /* CKF_PROTECTED_AUTHENTICATION_PATH */ #define GNUTLS_PKCS11_TOKEN_INITIALIZED (1<<5) /* CKF_TOKEN_INITIALIZED */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_COUNT_LOW (1<<6) /* CKF_USER_PIN_COUNT_LOW */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_FINAL_TRY (1<<7) /* CKF_USER_PIN_FINAL_TRY */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_LOCKED (1<<8) /* CKF_USER_PIN_LOCKED */ #define GNUTLS_PKCS11_TOKEN_SO_PIN_COUNT_LOW (1<<9) /* CKF_SO_PIN_COUNT_LOW */ #define GNUTLS_PKCS11_TOKEN_SO_PIN_FINAL_TRY (1<<10) /* CKF_SO_PIN_FINAL_TRY */ #define GNUTLS_PKCS11_TOKEN_SO_PIN_LOCKED (1<<11) /* CKF_SO_PIN_LOCKED */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_INITIALIZED (1<<12) /* CKF_USER_PIN_INITIALIZED */ #define GNUTLS_PKCS11_TOKEN_ERROR_STATE (1<<13) /* CKF_ERROR_STATE */ int gnutls_pkcs11_token_get_flags(const char *url, unsigned int *flags); #define gnutls_pkcs11_obj_list_import_url(p_list, n_list, url, attrs, flags) gnutls_pkcs11_obj_list_import_url3(p_list, n_list, url, attrs|flags) #define gnutls_pkcs11_obj_list_import_url2(p_list, n_list, url, attrs, flags) gnutls_pkcs11_obj_list_import_url4(p_list, n_list, url, attrs|flags) int gnutls_pkcs11_obj_list_import_url3(gnutls_pkcs11_obj_t * p_list, unsigned int *const n_list, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_obj_list_import_url4(gnutls_pkcs11_obj_t ** p_list, unsigned int *n_list, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_x509_crt_import_pkcs11(gnutls_x509_crt_t crt, gnutls_pkcs11_obj_t pkcs11_crt); gnutls_pkcs11_obj_type_t gnutls_pkcs11_obj_get_type(gnutls_pkcs11_obj_t obj); const char *gnutls_pkcs11_type_get_name(gnutls_pkcs11_obj_type_t type); int gnutls_pkcs11_obj_get_exts(gnutls_pkcs11_obj_t obj, struct gnutls_x509_ext_st **exts, unsigned int *exts_size, unsigned int flags); int gnutls_pkcs11_obj_get_flags(gnutls_pkcs11_obj_t obj, unsigned int *oflags); char *gnutls_pkcs11_obj_flags_get_str(unsigned int flags); int gnutls_x509_crt_list_import_pkcs11(gnutls_x509_crt_t * certs, unsigned int cert_max, gnutls_pkcs11_obj_t * const objs, unsigned int flags /* must be zero */ ); /* private key functions...*/ int gnutls_pkcs11_privkey_init(gnutls_pkcs11_privkey_t * key); int gnutls_pkcs11_privkey_cpy(gnutls_pkcs11_privkey_t dst, gnutls_pkcs11_privkey_t src); void gnutls_pkcs11_privkey_set_pin_function(gnutls_pkcs11_privkey_t key, gnutls_pin_callback_t fn, void *userdata); void gnutls_pkcs11_privkey_deinit(gnutls_pkcs11_privkey_t key); int gnutls_pkcs11_privkey_get_pk_algorithm(gnutls_pkcs11_privkey_t key, unsigned int *bits); int gnutls_pkcs11_privkey_get_info(gnutls_pkcs11_privkey_t pkey, gnutls_pkcs11_obj_info_t itype, void *output, size_t * output_size); int gnutls_pkcs11_privkey_import_url(gnutls_pkcs11_privkey_t pkey, const char *url, unsigned int flags); int gnutls_pkcs11_privkey_export_url(gnutls_pkcs11_privkey_t key, gnutls_pkcs11_url_type_t detailed, char **url); unsigned gnutls_pkcs11_privkey_status(gnutls_pkcs11_privkey_t key); #define gnutls_pkcs11_privkey_generate(url, pk, bits, label, flags) \ gnutls_pkcs11_privkey_generate3(url, pk, bits, label, NULL, 0, NULL, 0, flags) #define gnutls_pkcs11_privkey_generate2(url, pk, bits, label, fmt, pubkey, flags) \ gnutls_pkcs11_privkey_generate3(url, pk, bits, label, NULL, fmt, pubkey, 0, flags) int gnutls_pkcs11_privkey_generate3(const char *url, gnutls_pk_algorithm_t pk, unsigned int bits, const char *label, const gnutls_datum_t *cid, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * pubkey, unsigned int key_usage, unsigned int flags); int gnutls_pkcs11_privkey_export_pubkey(gnutls_pkcs11_privkey_t pkey, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * pubkey, unsigned int flags); int gnutls_pkcs11_token_get_random(const char *token_url, void *data, size_t len); int gnutls_pkcs11_copy_attached_extension(const char *token_url, gnutls_x509_crt_t crt, gnutls_datum_t *data, const char *label, unsigned int flags); #define gnutls_x509_crt_import_pkcs11_url gnutls_x509_crt_import_url /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_PKCS11_H */ ================================================ FILE: thirdparty/32/include/gnutls/pkcs12.h ================================================ /* * Copyright (C) 2003-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_PKCS12_H #define GNUTLS_PKCS12_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* PKCS12 structures handling */ struct gnutls_pkcs12_int; typedef struct gnutls_pkcs12_int *gnutls_pkcs12_t; struct gnutls_pkcs12_bag_int; typedef struct gnutls_pkcs12_bag_int *gnutls_pkcs12_bag_t; int gnutls_pkcs12_init(gnutls_pkcs12_t * pkcs12); void gnutls_pkcs12_deinit(gnutls_pkcs12_t pkcs12); int gnutls_pkcs12_import(gnutls_pkcs12_t pkcs12, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pkcs12_export(gnutls_pkcs12_t pkcs12, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_pkcs12_export2(gnutls_pkcs12_t pkcs12, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_pkcs12_get_bag(gnutls_pkcs12_t pkcs12, int indx, gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_set_bag(gnutls_pkcs12_t pkcs12, gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_generate_mac(gnutls_pkcs12_t pkcs12, const char *pass); int gnutls_pkcs12_generate_mac2(gnutls_pkcs12_t pkcs12, gnutls_mac_algorithm_t mac, const char *pass); int gnutls_pkcs12_verify_mac(gnutls_pkcs12_t pkcs12, const char *pass); int gnutls_pkcs12_bag_decrypt(gnutls_pkcs12_bag_t bag, const char *pass); int gnutls_pkcs12_bag_encrypt(gnutls_pkcs12_bag_t bag, const char *pass, unsigned int flags); int gnutls_pkcs12_bag_enc_info(gnutls_pkcs12_bag_t bag, unsigned int *schema, unsigned int *cipher, void *salt, unsigned int *salt_size, unsigned int *iter_count, char **oid); int gnutls_pkcs12_mac_info(gnutls_pkcs12_t pkcs12, unsigned int *mac, void *salt, unsigned int *salt_size, unsigned int *iter_count, char **oid); #define GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED 1 int gnutls_pkcs12_simple_parse(gnutls_pkcs12_t p12, const char *password, gnutls_x509_privkey_t * key, gnutls_x509_crt_t ** chain, unsigned int *chain_len, gnutls_x509_crt_t ** extra_certs, unsigned int *extra_certs_len, gnutls_x509_crl_t * crl, unsigned int flags); /** * gnutls_pkcs12_bag_type_t: * @GNUTLS_BAG_EMPTY: Empty PKCS-12 bag. * @GNUTLS_BAG_PKCS8_ENCRYPTED_KEY: PKCS-12 bag with PKCS-8 encrypted key. * @GNUTLS_BAG_PKCS8_KEY: PKCS-12 bag with PKCS-8 key. * @GNUTLS_BAG_CERTIFICATE: PKCS-12 bag with certificate. * @GNUTLS_BAG_CRL: PKCS-12 bag with CRL. * @GNUTLS_BAG_SECRET: PKCS-12 bag with secret PKCS-9 keys. * @GNUTLS_BAG_ENCRYPTED: Encrypted PKCS-12 bag. * @GNUTLS_BAG_UNKNOWN: Unknown PKCS-12 bag. * * Enumeration of different PKCS 12 bag types. */ typedef enum gnutls_pkcs12_bag_type_t { GNUTLS_BAG_EMPTY = 0, GNUTLS_BAG_PKCS8_ENCRYPTED_KEY = 1, GNUTLS_BAG_PKCS8_KEY = 2, GNUTLS_BAG_CERTIFICATE = 3, GNUTLS_BAG_CRL = 4, GNUTLS_BAG_SECRET = 5, /* Secret data. Underspecified in pkcs-12, * gnutls extension. We use the PKCS-9 * random nonce ID 1.2.840.113549.1.9.25.3 * to store randomly generated keys. */ GNUTLS_BAG_ENCRYPTED = 10, GNUTLS_BAG_UNKNOWN = 20 } gnutls_pkcs12_bag_type_t; int gnutls_pkcs12_bag_get_type(gnutls_pkcs12_bag_t bag, unsigned indx); int gnutls_pkcs12_bag_get_data(gnutls_pkcs12_bag_t bag, unsigned indx, gnutls_datum_t * data); int gnutls_pkcs12_bag_set_data(gnutls_pkcs12_bag_t bag, gnutls_pkcs12_bag_type_t type, const gnutls_datum_t * data); int gnutls_pkcs12_bag_set_crl(gnutls_pkcs12_bag_t bag, gnutls_x509_crl_t crl); int gnutls_pkcs12_bag_set_crt(gnutls_pkcs12_bag_t bag, gnutls_x509_crt_t crt); int gnutls_pkcs12_bag_set_privkey(gnutls_pkcs12_bag_t bag, gnutls_x509_privkey_t privkey, const char *password, unsigned flags); int gnutls_pkcs12_bag_init(gnutls_pkcs12_bag_t * bag); void gnutls_pkcs12_bag_deinit(gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_bag_get_count(gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_bag_get_key_id(gnutls_pkcs12_bag_t bag, unsigned indx, gnutls_datum_t * id); int gnutls_pkcs12_bag_set_key_id(gnutls_pkcs12_bag_t bag, unsigned indx, const gnutls_datum_t * id); int gnutls_pkcs12_bag_get_friendly_name(gnutls_pkcs12_bag_t bag, unsigned indx, char **name); int gnutls_pkcs12_bag_set_friendly_name(gnutls_pkcs12_bag_t bag, unsigned indx, const char *name); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_PKCS12_H */ ================================================ FILE: thirdparty/32/include/gnutls/pkcs7.h ================================================ /* * Copyright (C) 2003-2012 Free Software Foundation, Inc. * Copyright (C) 2015 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the X.509 * certificate and CRL handling functions. */ #ifndef GNUTLS_PKCS7_H #define GNUTLS_PKCS7_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* PKCS7 structures handling */ struct gnutls_pkcs7_int; typedef struct gnutls_pkcs7_int *gnutls_pkcs7_t; int gnutls_pkcs7_init(gnutls_pkcs7_t * pkcs7); void gnutls_pkcs7_deinit(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_import(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_pkcs7_export(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_pkcs7_export2(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_pkcs7_get_signature_count(gnutls_pkcs7_t pkcs7); #define GNUTLS_PKCS7_EDATA_GET_RAW (1<<24) int gnutls_pkcs7_get_embedded_data(gnutls_pkcs7_t pkcs7, unsigned flags, gnutls_datum_t *data); const char * gnutls_pkcs7_get_embedded_data_oid(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_get_crt_count(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_get_crt_raw(gnutls_pkcs7_t pkcs7, unsigned indx, void *certificate, size_t * certificate_size); int gnutls_pkcs7_set_crt_raw(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * crt); int gnutls_pkcs7_set_crt(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_t crt); int gnutls_pkcs7_delete_crt(gnutls_pkcs7_t pkcs7, int indx); int gnutls_pkcs7_get_crl_raw(gnutls_pkcs7_t pkcs7, unsigned indx, void *crl, size_t * crl_size); int gnutls_pkcs7_get_crl_count(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_set_crl_raw(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * crl); int gnutls_pkcs7_set_crl(gnutls_pkcs7_t pkcs7, gnutls_x509_crl_t crl); int gnutls_pkcs7_delete_crl(gnutls_pkcs7_t pkcs7, int indx); typedef struct gnutls_pkcs7_attrs_st *gnutls_pkcs7_attrs_t; typedef struct gnutls_pkcs7_signature_info_st { gnutls_sign_algorithm_t algo; gnutls_datum_t sig; gnutls_datum_t issuer_dn; gnutls_datum_t signer_serial; gnutls_datum_t issuer_keyid; time_t signing_time; gnutls_pkcs7_attrs_t signed_attrs; gnutls_pkcs7_attrs_t unsigned_attrs; char pad[64]; } gnutls_pkcs7_signature_info_st; void gnutls_pkcs7_signature_info_deinit(gnutls_pkcs7_signature_info_st *info); int gnutls_pkcs7_get_signature_info(gnutls_pkcs7_t pkcs7, unsigned idx, gnutls_pkcs7_signature_info_st *info); int gnutls_pkcs7_verify_direct(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_t signer, unsigned idx, const gnutls_datum_t *data, unsigned flags); int gnutls_pkcs7_verify(gnutls_pkcs7_t pkcs7, gnutls_x509_trust_list_t tl, gnutls_typed_vdata_st * vdata, unsigned int vdata_size, unsigned idx, const gnutls_datum_t *data, unsigned flags); #define GNUTLS_PKCS7_ATTR_ENCODE_OCTET_STRING 1 int gnutls_pkcs7_add_attr(gnutls_pkcs7_attrs_t *list, const char *oid, gnutls_datum_t *data, unsigned flags); void gnutls_pkcs7_attrs_deinit(gnutls_pkcs7_attrs_t list); int gnutls_pkcs7_get_attr(gnutls_pkcs7_attrs_t list, unsigned idx, char **oid, gnutls_datum_t *data, unsigned flags); /** * gnutls_pkcs7_sign_flags: * @GNUTLS_PKCS7_EMBED_DATA: The signed data will be embedded in the structure. * @GNUTLS_PKCS7_INCLUDE_TIME: The signing time will be included in the structure. * @GNUTLS_PKCS7_INCLUDE_CERT: The signer's certificate will be included in the cert list. * @GNUTLS_PKCS7_WRITE_SPKI: Use the signer's key identifier instead of name. * * Enumeration of the different PKCS #7 signature flags. */ typedef enum gnutls_pkcs7_sign_flags { GNUTLS_PKCS7_EMBED_DATA = 1, GNUTLS_PKCS7_INCLUDE_TIME = (1<<1), GNUTLS_PKCS7_INCLUDE_CERT = (1<<2), GNUTLS_PKCS7_WRITE_SPKI = (1<<3) } gnutls_pkcs7_sign_flags; int gnutls_pkcs7_sign(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_t signer, gnutls_privkey_t signer_key, const gnutls_datum_t *data, gnutls_pkcs7_attrs_t signed_attrs, gnutls_pkcs7_attrs_t unsigned_attrs, gnutls_digest_algorithm_t dig, unsigned flags); int gnutls_pkcs7_get_crt_raw2(gnutls_pkcs7_t pkcs7, unsigned indx, gnutls_datum_t *cert); int gnutls_pkcs7_get_crl_raw2(gnutls_pkcs7_t pkcs7, unsigned indx, gnutls_datum_t *crl); int gnutls_pkcs7_print(gnutls_pkcs7_t pkcs7, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); int gnutls_pkcs7_print_signature_info(gnutls_pkcs7_signature_info_st * info, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_PKCS7_H */ ================================================ FILE: thirdparty/32/include/gnutls/self-test.h ================================================ /* * Copyright (C) 2014 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_SELF_TEST_H #define GNUTLS_SELF_TEST_H #include /* Self checking functions */ #define GNUTLS_SELF_TEST_FLAG_ALL 1 #define GNUTLS_SELF_TEST_FLAG_NO_COMPAT (1<<1) int gnutls_cipher_self_test(unsigned flags, gnutls_cipher_algorithm_t cipher); int gnutls_mac_self_test(unsigned flags, gnutls_mac_algorithm_t mac); int gnutls_digest_self_test(unsigned flags, gnutls_digest_algorithm_t digest); int gnutls_pk_self_test(unsigned flags, gnutls_pk_algorithm_t pk); int gnutls_hkdf_self_test(unsigned flags, gnutls_mac_algorithm_t mac); int gnutls_pbkdf2_self_test(unsigned flags, gnutls_mac_algorithm_t mac); int gnutls_tlsprf_self_test(unsigned flags, gnutls_mac_algorithm_t mac); #endif /* GNUTLS_SELF_TEST_H */ ================================================ FILE: thirdparty/32/include/gnutls/socket.h ================================================ /* * Copyright (C) 2016 Free Software Foundation, Inc. * * Author: Tim Ruehsen * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains socket related types, prototypes and includes. */ #ifndef GNUTLS_SOCKET_H #define GNUTLS_SOCKET_H #include /* Get socklen_t */ #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /** * gnutls_transport_ktls_enable_flags_t: * @GNUTLS_KTLS_RECV: ktls enabled for recv function. * @GNUTLS_KTLS_SEND: ktls enabled for send function. * @GNUTLS_KTLS_DUPLEX: ktls enabled for both recv and send functions. * * Flag enumeration of ktls enable status for recv and send functions. * This is used by gnutls_transport_is_ktls_enabled(). * * Since: 3.7.3 */ typedef enum { GNUTLS_KTLS_RECV = 1 << 0, GNUTLS_KTLS_SEND = 1 << 1, GNUTLS_KTLS_DUPLEX = GNUTLS_KTLS_RECV | GNUTLS_KTLS_SEND, } gnutls_transport_ktls_enable_flags_t; gnutls_transport_ktls_enable_flags_t gnutls_transport_is_ktls_enabled(gnutls_session_t session); void gnutls_transport_set_fastopen(gnutls_session_t session, int fd, struct sockaddr *connect_addr, socklen_t connect_addrlen, unsigned int flags); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_SOCKET_H */ ================================================ FILE: thirdparty/32/include/gnutls/system-keys.h ================================================ /* * Copyright (C) 2014 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_SYSTEM_KEYS_H #define GNUTLS_SYSTEM_KEYS_H #include #include /* This API allows to access user key and certificate pairs that are * available in the current system. If any passwords are required, * they will be requested through the pin callbacks. */ /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ struct system_key_iter_st; typedef struct system_key_iter_st *gnutls_system_key_iter_t; void gnutls_system_key_iter_deinit(gnutls_system_key_iter_t iter); int gnutls_system_key_iter_get_info(gnutls_system_key_iter_t *iter, unsigned cert_type /* gnutls_certificate_type_t */, char **cert_url, char **key_url, char **label, gnutls_datum_t *der, unsigned int flags); int gnutls_system_key_delete(const char *cert_url, const char *key_url); int gnutls_system_key_add_x509(gnutls_x509_crt_t crt, gnutls_x509_privkey_t privkey, const char *label, char **cert_url, char **key_url); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_SYSTEM_KEYS_H */ ================================================ FILE: thirdparty/32/include/gnutls/tpm.h ================================================ /* * Copyright (C) 2010-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_TPM_H #define GNUTLS_TPM_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ struct tpm_key_list_st; typedef struct tpm_key_list_st *gnutls_tpm_key_list_t; #define GNUTLS_TPM_KEY_SIGNING (1<<1) #define GNUTLS_TPM_REGISTER_KEY (1<<2) #define GNUTLS_TPM_KEY_USER (1<<3) /** * gnutls_tpmkey_fmt_t: * @GNUTLS_TPMKEY_FMT_RAW: The portable data format. * @GNUTLS_TPMKEY_FMT_DER: An alias for the raw format. * @GNUTLS_TPMKEY_FMT_CTK_PEM: A custom data format used by some TPM tools. * * Enumeration of different certificate encoding formats. */ typedef enum { GNUTLS_TPMKEY_FMT_RAW = 0, GNUTLS_TPMKEY_FMT_DER = GNUTLS_TPMKEY_FMT_RAW, GNUTLS_TPMKEY_FMT_CTK_PEM = 1 } gnutls_tpmkey_fmt_t; int gnutls_tpm_privkey_generate(gnutls_pk_algorithm_t pk, unsigned int bits, const char *srk_password, const char *key_password, gnutls_tpmkey_fmt_t format, gnutls_x509_crt_fmt_t pub_format, gnutls_datum_t * privkey, gnutls_datum_t * pubkey, unsigned int flags); void gnutls_tpm_key_list_deinit(gnutls_tpm_key_list_t list); int gnutls_tpm_key_list_get_url(gnutls_tpm_key_list_t list, unsigned int idx, char **url, unsigned int flags); int gnutls_tpm_get_registered(gnutls_tpm_key_list_t * list); int gnutls_tpm_privkey_delete(const char *url, const char *srk_password); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_TPM_H */ ================================================ FILE: thirdparty/32/include/gnutls/urls.h ================================================ /* * Copyright (C) 2014 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_URLS_H #define GNUTLS_URLS_H #include #include #include /* This API allows to register application specific URLs for * keys and certificates. */ /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ typedef int (*gnutls_privkey_import_url_func)(gnutls_privkey_t pkey, const char *url, unsigned flags); typedef int (*gnutls_x509_crt_import_url_func)(gnutls_x509_crt_t pkey, const char *url, unsigned flags); /* The following callbacks are optional */ /* This is to enable gnutls_pubkey_import_url() */ typedef int (*gnutls_pubkey_import_url_func)(gnutls_pubkey_t pkey, const char *url, unsigned flags); /* This is to allow constructing a certificate chain. It will be provided * the initial certificate URL and the certificate to find its issuer, and must * return zero and the DER encoding of the issuer's certificate. If not available, * it should return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE. */ typedef int (*gnutls_get_raw_issuer_func)(const char *url, gnutls_x509_crt_t crt, gnutls_datum_t *issuer_der, unsigned flags); typedef struct gnutls_custom_url_st { const char *name; unsigned name_size; gnutls_privkey_import_url_func import_key; gnutls_x509_crt_import_url_func import_crt; gnutls_pubkey_import_url_func import_pubkey; gnutls_get_raw_issuer_func get_issuer; void *future1; /* replace in a future extension */ void *future2; /* replace in a future extension */ } gnutls_custom_url_st; int gnutls_register_custom_url(const gnutls_custom_url_st *st); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_URLS_H */ ================================================ FILE: thirdparty/32/include/gnutls/x509-ext.h ================================================ /* * Copyright (C) 2014 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* Prototypes for direct handling of extension data */ #ifndef GNUTLS_X509_EXT_H #define GNUTLS_X509_EXT_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ typedef struct gnutls_subject_alt_names_st *gnutls_subject_alt_names_t; int gnutls_subject_alt_names_init(gnutls_subject_alt_names_t *); void gnutls_subject_alt_names_deinit(gnutls_subject_alt_names_t sans); int gnutls_subject_alt_names_get(gnutls_subject_alt_names_t sans, unsigned int seq, unsigned int *san_type, gnutls_datum_t * san, gnutls_datum_t * othername_oid); int gnutls_subject_alt_names_set(gnutls_subject_alt_names_t sans, unsigned int san_type, const gnutls_datum_t * san, const char* othername_oid); int gnutls_x509_ext_import_subject_alt_names(const gnutls_datum_t * ext, gnutls_subject_alt_names_t, unsigned int flags); int gnutls_x509_ext_export_subject_alt_names(gnutls_subject_alt_names_t, gnutls_datum_t * ext); /* They are exactly the same */ #define gnutls_x509_ext_import_issuer_alt_name gnutls_x509_ext_import_subject_alt_name #define gnutls_x509_ext_export_issuer_alt_name gnutls_x509_ext_export_subject_alt_name typedef struct gnutls_x509_crl_dist_points_st *gnutls_x509_crl_dist_points_t; int gnutls_x509_crl_dist_points_init(gnutls_x509_crl_dist_points_t *); void gnutls_x509_crl_dist_points_deinit(gnutls_x509_crl_dist_points_t); int gnutls_x509_crl_dist_points_get(gnutls_x509_crl_dist_points_t, unsigned int seq, unsigned int *type, gnutls_datum_t *dist, unsigned int *reason_flags); int gnutls_x509_crl_dist_points_set(gnutls_x509_crl_dist_points_t, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t *dist, unsigned int reason_flags); int gnutls_x509_ext_import_crl_dist_points(const gnutls_datum_t * ext, gnutls_x509_crl_dist_points_t dp, unsigned int flags); int gnutls_x509_ext_export_crl_dist_points(gnutls_x509_crl_dist_points_t dp, gnutls_datum_t * ext); int gnutls_x509_ext_import_name_constraints(const gnutls_datum_t * ext, gnutls_x509_name_constraints_t nc, unsigned int flags); int gnutls_x509_ext_export_name_constraints(gnutls_x509_name_constraints_t nc, gnutls_datum_t * ext); typedef struct gnutls_x509_aia_st *gnutls_x509_aia_t; int gnutls_x509_aia_init(gnutls_x509_aia_t *); void gnutls_x509_aia_deinit(gnutls_x509_aia_t); int gnutls_x509_aia_get(gnutls_x509_aia_t aia, unsigned int seq, gnutls_datum_t *oid, unsigned *san_type, gnutls_datum_t *san); int gnutls_x509_aia_set(gnutls_x509_aia_t aia, const char *oid, unsigned san_type, const gnutls_datum_t * san); int gnutls_x509_ext_import_aia(const gnutls_datum_t * ext, gnutls_x509_aia_t, unsigned int flags); int gnutls_x509_ext_export_aia(gnutls_x509_aia_t aia, gnutls_datum_t * ext); int gnutls_x509_ext_import_subject_key_id(const gnutls_datum_t * ext, gnutls_datum_t * id); int gnutls_x509_ext_export_subject_key_id(const gnutls_datum_t * id, gnutls_datum_t * ext); typedef struct gnutls_x509_aki_st *gnutls_x509_aki_t; int gnutls_x509_ext_export_authority_key_id(gnutls_x509_aki_t, gnutls_datum_t * ext); int gnutls_x509_ext_import_authority_key_id(const gnutls_datum_t * ext, gnutls_x509_aki_t, unsigned int flags); int gnutls_x509_othername_to_virtual(const char *oid, const gnutls_datum_t *othername, unsigned int *virt_type, gnutls_datum_t *virt); int gnutls_x509_aki_init(gnutls_x509_aki_t *); int gnutls_x509_aki_get_id(gnutls_x509_aki_t, gnutls_datum_t *id); int gnutls_x509_aki_get_cert_issuer(gnutls_x509_aki_t aki, unsigned int seq, unsigned int *san_type, gnutls_datum_t * san, gnutls_datum_t *othername_oid, gnutls_datum_t *serial); int gnutls_x509_aki_set_id(gnutls_x509_aki_t aki, const gnutls_datum_t *id); int gnutls_x509_aki_set_cert_issuer(gnutls_x509_aki_t aki, unsigned int san_type, const gnutls_datum_t * san, const char *othername_oid, const gnutls_datum_t * serial); void gnutls_x509_aki_deinit(gnutls_x509_aki_t); int gnutls_x509_ext_import_private_key_usage_period(const gnutls_datum_t * ext, time_t * activation, time_t * expiration); int gnutls_x509_ext_export_private_key_usage_period(time_t activation, time_t expiration, gnutls_datum_t * ext); int gnutls_x509_ext_import_basic_constraints(const gnutls_datum_t * ext, unsigned int *ca, int *pathlen); int gnutls_x509_ext_export_basic_constraints(unsigned int ca, int pathlen, gnutls_datum_t * ext); typedef struct gnutls_x509_key_purposes_st *gnutls_x509_key_purposes_t; int gnutls_x509_key_purpose_init(gnutls_x509_key_purposes_t *p); void gnutls_x509_key_purpose_deinit(gnutls_x509_key_purposes_t p); int gnutls_x509_key_purpose_set(gnutls_x509_key_purposes_t p, const char *oid); int gnutls_x509_key_purpose_get(gnutls_x509_key_purposes_t p, unsigned idx, gnutls_datum_t *oid); int gnutls_x509_ext_import_key_purposes(const gnutls_datum_t * ext, gnutls_x509_key_purposes_t, unsigned int flags); int gnutls_x509_ext_export_key_purposes(gnutls_x509_key_purposes_t, gnutls_datum_t * ext); int gnutls_x509_ext_import_key_usage(const gnutls_datum_t * ext, unsigned int *key_usage); int gnutls_x509_ext_export_key_usage(unsigned int key_usage, gnutls_datum_t * ext); int gnutls_x509_ext_import_inhibit_anypolicy(const gnutls_datum_t * ext, unsigned int *skipcerts); int gnutls_x509_ext_export_inhibit_anypolicy(unsigned int skipcerts, gnutls_datum_t * ext); int gnutls_x509_ext_import_proxy(const gnutls_datum_t * ext, int *pathlen, char **policyLanguage, char **policy, size_t * sizeof_policy); int gnutls_x509_ext_export_proxy(int pathLenConstraint, const char *policyLanguage, const char *policy, size_t sizeof_policy, gnutls_datum_t * ext); typedef struct gnutls_x509_policies_st *gnutls_x509_policies_t; int gnutls_x509_policies_init(gnutls_x509_policies_t *); void gnutls_x509_policies_deinit(gnutls_x509_policies_t); int gnutls_x509_policies_get(gnutls_x509_policies_t policies, unsigned int seq, struct gnutls_x509_policy_st *policy); int gnutls_x509_policies_set(gnutls_x509_policies_t policies, const struct gnutls_x509_policy_st *policy); int gnutls_x509_ext_import_policies(const gnutls_datum_t * ext, gnutls_x509_policies_t policies, unsigned int flags); int gnutls_x509_ext_export_policies(gnutls_x509_policies_t policies, gnutls_datum_t * ext); int gnutls_x509_ext_import_tlsfeatures(const gnutls_datum_t * ext, gnutls_x509_tlsfeatures_t, unsigned int flags); int gnutls_x509_ext_export_tlsfeatures(gnutls_x509_tlsfeatures_t f, gnutls_datum_t * ext); int gnutls_x509_tlsfeatures_add(gnutls_x509_tlsfeatures_t f, unsigned int feature); typedef struct gnutls_x509_ct_scts_st *gnutls_x509_ct_scts_t; int gnutls_x509_ext_ct_scts_init(gnutls_x509_ct_scts_t * scts); void gnutls_x509_ext_ct_scts_deinit(gnutls_x509_ct_scts_t scts); int gnutls_x509_ext_ct_import_scts(const gnutls_datum_t * ext, gnutls_x509_ct_scts_t scts, unsigned int flags); int gnutls_x509_ext_ct_export_scts(const gnutls_x509_ct_scts_t scts, gnutls_datum_t * ext); int gnutls_x509_ct_sct_get_version(const gnutls_x509_ct_scts_t scts, unsigned idx, unsigned int *version_out); int gnutls_x509_ct_sct_get(const gnutls_x509_ct_scts_t scts, unsigned idx, time_t *timestamp, gnutls_datum_t *logid, gnutls_sign_algorithm_t *sigalg, gnutls_datum_t *signature); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_X509_EXT_H */ ================================================ FILE: thirdparty/32/include/gnutls/x509.h ================================================ /* * Copyright (C) 2003-2016 Free Software Foundation, Inc. * Copyright (C) 2015-2016 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the X.509 * certificate and CRL handling functions. */ #ifndef GNUTLS_X509_H #define GNUTLS_X509_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* Some OIDs usually found in Distinguished names, or * in Subject Directory Attribute extensions. */ #define GNUTLS_OID_X520_COUNTRY_NAME "2.5.4.6" #define GNUTLS_OID_X520_ORGANIZATION_NAME "2.5.4.10" #define GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME "2.5.4.11" #define GNUTLS_OID_X520_COMMON_NAME "2.5.4.3" #define GNUTLS_OID_X520_LOCALITY_NAME "2.5.4.7" #define GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME "2.5.4.8" #define GNUTLS_OID_X520_INITIALS "2.5.4.43" #define GNUTLS_OID_X520_GENERATION_QUALIFIER "2.5.4.44" #define GNUTLS_OID_X520_SURNAME "2.5.4.4" #define GNUTLS_OID_X520_GIVEN_NAME "2.5.4.42" #define GNUTLS_OID_X520_TITLE "2.5.4.12" #define GNUTLS_OID_X520_DN_QUALIFIER "2.5.4.46" #define GNUTLS_OID_X520_PSEUDONYM "2.5.4.65" #define GNUTLS_OID_X520_POSTALCODE "2.5.4.17" #define GNUTLS_OID_X520_NAME "2.5.4.41" #define GNUTLS_OID_LDAP_DC "0.9.2342.19200300.100.1.25" #define GNUTLS_OID_LDAP_UID "0.9.2342.19200300.100.1.1" /* The following should not be included in DN. */ #define GNUTLS_OID_PKCS9_EMAIL "1.2.840.113549.1.9.1" #define GNUTLS_OID_PKIX_DATE_OF_BIRTH "1.3.6.1.5.5.7.9.1" #define GNUTLS_OID_PKIX_PLACE_OF_BIRTH "1.3.6.1.5.5.7.9.2" #define GNUTLS_OID_PKIX_GENDER "1.3.6.1.5.5.7.9.3" #define GNUTLS_OID_PKIX_COUNTRY_OF_CITIZENSHIP "1.3.6.1.5.5.7.9.4" #define GNUTLS_OID_PKIX_COUNTRY_OF_RESIDENCE "1.3.6.1.5.5.7.9.5" /* Key purpose Object Identifiers. */ #define GNUTLS_KP_TLS_WWW_SERVER "1.3.6.1.5.5.7.3.1" #define GNUTLS_KP_TLS_WWW_CLIENT "1.3.6.1.5.5.7.3.2" #define GNUTLS_KP_CODE_SIGNING "1.3.6.1.5.5.7.3.3" #define GNUTLS_KP_MS_SMART_CARD_LOGON "1.3.6.1.4.1.311.20.2.2" #define GNUTLS_KP_EMAIL_PROTECTION "1.3.6.1.5.5.7.3.4" #define GNUTLS_KP_TIME_STAMPING "1.3.6.1.5.5.7.3.8" #define GNUTLS_KP_OCSP_SIGNING "1.3.6.1.5.5.7.3.9" #define GNUTLS_KP_IPSEC_IKE "1.3.6.1.5.5.7.3.17" #define GNUTLS_KP_ANY "2.5.29.37.0" #define GNUTLS_KP_FLAG_DISALLOW_ANY 1 #define GNUTLS_OID_AIA "1.3.6.1.5.5.7.1.1" #define GNUTLS_OID_AD_OCSP "1.3.6.1.5.5.7.48.1" #define GNUTLS_OID_AD_CAISSUERS "1.3.6.1.5.5.7.48.2" #define GNUTLS_FSAN_SET 0 #define GNUTLS_FSAN_APPEND 1 #define GNUTLS_FSAN_ENCODE_OCTET_STRING (1<<1) #define GNUTLS_FSAN_ENCODE_UTF8_STRING (1<<2) #define GNUTLS_X509EXT_OID_SUBJECT_KEY_ID "2.5.29.14" #define GNUTLS_X509EXT_OID_KEY_USAGE "2.5.29.15" #define GNUTLS_X509EXT_OID_PRIVATE_KEY_USAGE_PERIOD "2.5.29.16" #define GNUTLS_X509EXT_OID_SAN "2.5.29.17" #define GNUTLS_X509EXT_OID_IAN "2.5.29.18" #define GNUTLS_X509EXT_OID_BASIC_CONSTRAINTS "2.5.29.19" #define GNUTLS_X509EXT_OID_NAME_CONSTRAINTS "2.5.29.30" #define GNUTLS_X509EXT_OID_CRL_DIST_POINTS "2.5.29.31" #define GNUTLS_X509EXT_OID_CRT_POLICY "2.5.29.32" #define GNUTLS_X509EXT_OID_AUTHORITY_KEY_ID "2.5.29.35" #define GNUTLS_X509EXT_OID_EXTENDED_KEY_USAGE "2.5.29.37" #define GNUTLS_X509EXT_OID_INHIBIT_ANYPOLICY "2.5.29.52" #define GNUTLS_X509EXT_OID_AUTHORITY_INFO_ACCESS "1.3.6.1.5.5.7.1.1" #define GNUTLS_X509EXT_OID_PROXY_CRT_INFO "1.3.6.1.5.5.7.1.14" #define GNUTLS_X509EXT_OID_TLSFEATURES "1.3.6.1.5.5.7.1.24" #define GNUTLS_X509EXT_OID_CT_SCT_V1 "1.3.6.1.4.1.11129.2.4.2" #define GNUTLS_X509_OID_POLICY_ANY "2.5.29.54" /* Certificate handling functions. */ /** * gnutls_certificate_import_flags: * @GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED: Fail if the * certificates in the buffer are more than the space allocated for * certificates. The error code will be %GNUTLS_E_SHORT_MEMORY_BUFFER. * @GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED: Fail if the certificates * in the buffer are not ordered starting from subject to issuer. * The error code will be %GNUTLS_E_CERTIFICATE_LIST_UNSORTED. * @GNUTLS_X509_CRT_LIST_SORT: Sort the certificate chain if unsorted. * * Enumeration of different certificate import flags. */ typedef enum gnutls_certificate_import_flags { GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED = 1, GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED = 1<<1, GNUTLS_X509_CRT_LIST_SORT = 1<<2 } gnutls_certificate_import_flags; int gnutls_x509_crt_init(gnutls_x509_crt_t * cert); void gnutls_x509_crt_deinit(gnutls_x509_crt_t cert); /** * gnutls_certificate_import_flags: * @GNUTLS_X509_CRT_FLAG_IGNORE_SANITY: Ignore any sanity checks at the * import of the certificate; i.e., ignore checks such as version/field * matching and strict time field checks. Intended to be used for debugging. * * Enumeration of different certificate flags. */ typedef enum gnutls_x509_crt_flags { GNUTLS_X509_CRT_FLAG_IGNORE_SANITY = 1 } gnutls_x509_crt_flags; void gnutls_x509_crt_set_flags(gnutls_x509_crt_t cert, unsigned flags); unsigned gnutls_x509_crt_equals(gnutls_x509_crt_t cert1, gnutls_x509_crt_t cert2); unsigned gnutls_x509_crt_equals2(gnutls_x509_crt_t cert1, const gnutls_datum_t * der); int gnutls_x509_crt_import(gnutls_x509_crt_t cert, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_crt_list_import2(gnutls_x509_crt_t ** certs, unsigned int *size, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_x509_crt_list_import(gnutls_x509_crt_t * certs, unsigned int *cert_max, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_x509_crt_import_url(gnutls_x509_crt_t crt, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_x509_crt_list_import_url(gnutls_x509_crt_t **certs, unsigned int *size, const char *url, gnutls_pin_callback_t pin_fn, void *pin_fn_userdata, unsigned int flags); int gnutls_x509_crt_export(gnutls_x509_crt_t cert, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_crt_export2(gnutls_x509_crt_t cert, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_crt_get_private_key_usage_period(gnutls_x509_crt_t cert, time_t * activation, time_t * expiration, unsigned int *critical); int gnutls_x509_crt_get_issuer_dn(gnutls_x509_crt_t cert, char *buf, size_t * buf_size); int gnutls_x509_crt_get_issuer_dn2(gnutls_x509_crt_t cert, gnutls_datum_t * dn); int gnutls_x509_crt_get_issuer_dn3(gnutls_x509_crt_t cert, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crt_get_issuer_dn_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size); int gnutls_x509_crt_get_issuer_dn_by_oid(gnutls_x509_crt_t cert, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * buf_size); int gnutls_x509_crt_get_dn(gnutls_x509_crt_t cert, char *buf, size_t * buf_size); int gnutls_x509_crt_get_dn2(gnutls_x509_crt_t cert, gnutls_datum_t * dn); int gnutls_x509_crt_get_dn3(gnutls_x509_crt_t cert, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crt_get_dn_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size); int gnutls_x509_crt_get_dn_by_oid(gnutls_x509_crt_t cert, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * buf_size); unsigned gnutls_x509_crt_check_hostname(gnutls_x509_crt_t cert, const char *hostname); unsigned gnutls_x509_crt_check_hostname2(gnutls_x509_crt_t cert, const char *hostname, unsigned int flags); unsigned gnutls_x509_crt_check_email(gnutls_x509_crt_t cert, const char *email, unsigned int flags); unsigned gnutls_x509_crt_check_ip(gnutls_x509_crt_t cert, const unsigned char *ip, unsigned int ip_size, unsigned int flags); int gnutls_x509_crt_get_signature_algorithm(gnutls_x509_crt_t cert); int gnutls_x509_crt_get_signature(gnutls_x509_crt_t cert, char *sig, size_t * sizeof_sig); int gnutls_x509_crt_get_version(gnutls_x509_crt_t cert); int gnutls_x509_crt_get_pk_oid(gnutls_x509_crt_t cert, char *oid, size_t *oid_size); int gnutls_x509_crt_get_signature_oid(gnutls_x509_crt_t cert, char *oid, size_t *oid_size); /** * gnutls_keyid_flags_t: * @GNUTLS_KEYID_USE_SHA1: Use SHA1 as the key ID algorithm (default). * @GNUTLS_KEYID_USE_SHA256: Use SHA256 as the key ID algorithm. * @GNUTLS_KEYID_USE_SHA512: Use SHA512 as the key ID algorithm. * @GNUTLS_KEYID_USE_BEST_KNOWN: Use the best known algorithm to calculate key ID. Using that option will make your program behavior depend on the version of gnutls linked with. That option has a cap of 64-bytes key IDs. * * Enumeration of different flags for the key ID functions. */ typedef enum { GNUTLS_KEYID_USE_SHA1 = 0, GNUTLS_KEYID_USE_SHA256 = (1<<0), GNUTLS_KEYID_USE_SHA512 = (1<<1), GNUTLS_KEYID_USE_BEST_KNOWN = (1<<30) } gnutls_keyid_flags_t; int gnutls_x509_crt_get_key_id(gnutls_x509_crt_t crt, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_x509_crt_set_private_key_usage_period(gnutls_x509_crt_t crt, time_t activation, time_t expiration); int gnutls_x509_crt_set_authority_key_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_get_authority_key_id(gnutls_x509_crt_t cert, void *id, size_t * id_size, unsigned int *critical); int gnutls_x509_crt_get_authority_key_gn_serial(gnutls_x509_crt_t cert, unsigned int seq, void *alt, size_t * alt_size, unsigned int *alt_type, void *serial, size_t * serial_size, unsigned int *critical); int gnutls_x509_crt_get_subject_key_id(gnutls_x509_crt_t cert, void *ret, size_t * ret_size, unsigned int *critical); int gnutls_x509_crt_get_subject_unique_id(gnutls_x509_crt_t crt, char *buf, size_t * buf_size); int gnutls_x509_crt_get_issuer_unique_id(gnutls_x509_crt_t crt, char *buf, size_t * buf_size); void gnutls_x509_crt_set_pin_function(gnutls_x509_crt_t crt, gnutls_pin_callback_t fn, void *userdata); /** * gnutls_info_access_what_t: * @GNUTLS_IA_ACCESSMETHOD_OID: Get accessMethod OID. * @GNUTLS_IA_ACCESSLOCATION_GENERALNAME_TYPE: Get accessLocation name type. * @GNUTLS_IA_URI: Get accessLocation URI value. * @GNUTLS_IA_OCSP_URI: get accessLocation URI value for OCSP. * @GNUTLS_IA_CAISSUERS_URI: get accessLocation URI value for caIssuers. * * Enumeration of types for the @what parameter of * gnutls_x509_crt_get_authority_info_access(). */ typedef enum gnutls_info_access_what_t { GNUTLS_IA_ACCESSMETHOD_OID = 1, GNUTLS_IA_ACCESSLOCATION_GENERALNAME_TYPE = 2, /* use 100-108 for the generalName types, populate as needed */ GNUTLS_IA_URI = 106, /* quick-access variants that match both OID and name type. */ GNUTLS_IA_UNKNOWN = 10000, GNUTLS_IA_OCSP_URI = 10006, GNUTLS_IA_CAISSUERS_URI = 10106 } gnutls_info_access_what_t; int gnutls_x509_crt_get_authority_info_access(gnutls_x509_crt_t crt, unsigned int seq, int what, gnutls_datum_t * data, unsigned int *critical); typedef struct gnutls_name_constraints_st *gnutls_x509_name_constraints_t; unsigned gnutls_x509_name_constraints_check(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t * name); unsigned gnutls_x509_name_constraints_check_crt(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, gnutls_x509_crt_t crt); int gnutls_x509_name_constraints_init(gnutls_x509_name_constraints_t *nc); void gnutls_x509_name_constraints_deinit(gnutls_x509_name_constraints_t nc); #define GNUTLS_EXT_FLAG_APPEND 1 #define GNUTLS_NAME_CONSTRAINTS_FLAG_APPEND GNUTLS_EXT_FLAG_APPEND int gnutls_x509_crt_get_name_constraints(gnutls_x509_crt_t crt, gnutls_x509_name_constraints_t nc, unsigned int flags, unsigned int *critical); int gnutls_x509_name_constraints_add_permitted(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t * name); int gnutls_x509_name_constraints_add_excluded(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t * name); int gnutls_x509_crt_set_name_constraints(gnutls_x509_crt_t crt, gnutls_x509_name_constraints_t nc, unsigned int critical); int gnutls_x509_name_constraints_get_permitted(gnutls_x509_name_constraints_t nc, unsigned idx, unsigned *type, gnutls_datum_t * name); int gnutls_x509_name_constraints_get_excluded(gnutls_x509_name_constraints_t nc, unsigned idx, unsigned *type, gnutls_datum_t * name); int gnutls_x509_cidr_to_rfc5280(const char *cidr, gnutls_datum_t *cidr_rfc5280); #define GNUTLS_CRL_REASON_SUPERSEEDED GNUTLS_CRL_REASON_SUPERSEDED, /** * gnutls_x509_crl_reason_flags_t: * @GNUTLS_CRL_REASON_PRIVILEGE_WITHDRAWN: The privileges were withdrawn from the owner. * @GNUTLS_CRL_REASON_CERTIFICATE_HOLD: The certificate is on hold. * @GNUTLS_CRL_REASON_CESSATION_OF_OPERATION: The end-entity is no longer operating. * @GNUTLS_CRL_REASON_SUPERSEDED: There is a newer certificate of the owner. * @GNUTLS_CRL_REASON_AFFILIATION_CHANGED: The end-entity affiliation has changed. * @GNUTLS_CRL_REASON_CA_COMPROMISE: The CA was compromised. * @GNUTLS_CRL_REASON_KEY_COMPROMISE: The certificate's key was compromised. * @GNUTLS_CRL_REASON_UNUSED: The key was never used. * @GNUTLS_CRL_REASON_AA_COMPROMISE: AA compromised. * * Enumeration of types for the CRL revocation reasons. */ typedef enum gnutls_x509_crl_reason_flags_t { GNUTLS_CRL_REASON_UNSPECIFIED = 0, GNUTLS_CRL_REASON_PRIVILEGE_WITHDRAWN = 1, GNUTLS_CRL_REASON_CERTIFICATE_HOLD = 2, GNUTLS_CRL_REASON_CESSATION_OF_OPERATION = 4, GNUTLS_CRL_REASON_SUPERSEDED = 8, GNUTLS_CRL_REASON_AFFILIATION_CHANGED = 16, GNUTLS_CRL_REASON_CA_COMPROMISE = 32, GNUTLS_CRL_REASON_KEY_COMPROMISE = 64, GNUTLS_CRL_REASON_UNUSED = 128, GNUTLS_CRL_REASON_AA_COMPROMISE = 32768 } gnutls_x509_crl_reason_flags_t; int gnutls_x509_crt_get_crl_dist_points(gnutls_x509_crt_t cert, unsigned int seq, void *ret, size_t * ret_size, unsigned int *reason_flags, unsigned int *critical); int gnutls_x509_crt_set_crl_dist_points2(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data, unsigned int data_size, unsigned int reason_flags); int gnutls_x509_crt_set_crl_dist_points(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data_string, unsigned int reason_flags); int gnutls_x509_crt_cpy_crl_dist_points(gnutls_x509_crt_t dst, gnutls_x509_crt_t src); int gnutls_x509_crl_sign(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key); int gnutls_x509_crl_sign2(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); time_t gnutls_x509_crt_get_activation_time(gnutls_x509_crt_t cert); /* This macro is deprecated and defunc; do not use */ #define GNUTLS_X509_NO_WELL_DEFINED_EXPIRATION ((time_t)4294197631) time_t gnutls_x509_crt_get_expiration_time(gnutls_x509_crt_t cert); int gnutls_x509_crt_get_serial(gnutls_x509_crt_t cert, void *result, size_t * result_size); typedef struct gnutls_x509_spki_st *gnutls_x509_spki_t; int gnutls_x509_spki_init(gnutls_x509_spki_t *spki); void gnutls_x509_spki_deinit(gnutls_x509_spki_t spki); int gnutls_x509_spki_get_rsa_pss_params(gnutls_x509_spki_t spki, gnutls_digest_algorithm_t *dig, unsigned int *salt_size); void gnutls_x509_spki_set_rsa_pss_params(gnutls_x509_spki_t spki, gnutls_digest_algorithm_t dig, unsigned int salt_size); int gnutls_x509_crt_get_pk_algorithm(gnutls_x509_crt_t cert, unsigned int *bits); int gnutls_x509_crt_set_spki(gnutls_x509_crt_t crt, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crt_get_spki(gnutls_x509_crt_t cert, gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crt_get_pk_rsa_raw(gnutls_x509_crt_t crt, gnutls_datum_t * m, gnutls_datum_t * e); int gnutls_x509_crt_get_pk_dsa_raw(gnutls_x509_crt_t crt, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y); int gnutls_x509_crt_get_pk_ecc_raw(gnutls_x509_crt_t crt, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y); int gnutls_x509_crt_get_pk_gost_raw(gnutls_x509_crt_t crt, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t *paramset, gnutls_datum_t * x, gnutls_datum_t * y); int gnutls_x509_crt_get_subject_alt_name(gnutls_x509_crt_t cert, unsigned int seq, void *san, size_t * san_size, unsigned int *critical); int gnutls_x509_crt_get_subject_alt_name2(gnutls_x509_crt_t cert, unsigned int seq, void *san, size_t * san_size, unsigned int *san_type, unsigned int *critical); int gnutls_x509_crt_get_subject_alt_othername_oid(gnutls_x509_crt_t cert, unsigned int seq, void *oid, size_t * oid_size); int gnutls_x509_crt_get_issuer_alt_name(gnutls_x509_crt_t cert, unsigned int seq, void *ian, size_t * ian_size, unsigned int *critical); int gnutls_x509_crt_get_issuer_alt_name2(gnutls_x509_crt_t cert, unsigned int seq, void *ian, size_t * ian_size, unsigned int *ian_type, unsigned int *critical); int gnutls_x509_crt_get_issuer_alt_othername_oid(gnutls_x509_crt_t cert, unsigned int seq, void *ret, size_t * ret_size); int gnutls_x509_crt_get_ca_status(gnutls_x509_crt_t cert, unsigned int *critical); int gnutls_x509_crt_get_basic_constraints(gnutls_x509_crt_t cert, unsigned int *critical, unsigned int *ca, int *pathlen); /* The key_usage flags are defined in gnutls.h. They are the * GNUTLS_KEY_* definitions. */ int gnutls_x509_crt_get_key_usage(gnutls_x509_crt_t cert, unsigned int *key_usage, unsigned int *critical); int gnutls_x509_crt_set_key_usage(gnutls_x509_crt_t crt, unsigned int usage); int gnutls_x509_crt_set_authority_info_access(gnutls_x509_crt_t crt, int what, gnutls_datum_t * data); int gnutls_x509_crt_get_inhibit_anypolicy(gnutls_x509_crt_t cert, unsigned int *skipcerts, unsigned int *critical); int gnutls_x509_crt_set_inhibit_anypolicy(gnutls_x509_crt_t crt, unsigned int skipcerts); int gnutls_x509_crt_get_proxy(gnutls_x509_crt_t cert, unsigned int *critical, int *pathlen, char **policyLanguage, char **policy, size_t * sizeof_policy); typedef struct gnutls_x509_tlsfeatures_st *gnutls_x509_tlsfeatures_t; int gnutls_x509_tlsfeatures_init(gnutls_x509_tlsfeatures_t *features); void gnutls_x509_tlsfeatures_deinit(gnutls_x509_tlsfeatures_t); int gnutls_x509_tlsfeatures_get(gnutls_x509_tlsfeatures_t f, unsigned idx, unsigned int *feature); int gnutls_x509_crt_set_tlsfeatures(gnutls_x509_crt_t crt, gnutls_x509_tlsfeatures_t features); int gnutls_x509_crt_get_tlsfeatures(gnutls_x509_crt_t cert, gnutls_x509_tlsfeatures_t features, unsigned int flags, unsigned int *critical); unsigned gnutls_x509_tlsfeatures_check_crt(gnutls_x509_tlsfeatures_t feat, gnutls_x509_crt_t crt); #define GNUTLS_MAX_QUALIFIERS 8 /** * gnutls_x509_qualifier_t: * @GNUTLS_X509_QUALIFIER_UNKNOWN: Unknown qualifier. * @GNUTLS_X509_QUALIFIER_URI: A URL * @GNUTLS_X509_QUALIFIER_NOICE: A text notice. * * Enumeration of types for the X.509 qualifiers, of the certificate policy extension. */ typedef enum gnutls_x509_qualifier_t { GNUTLS_X509_QUALIFIER_UNKNOWN = 0, GNUTLS_X509_QUALIFIER_URI, GNUTLS_X509_QUALIFIER_NOTICE } gnutls_x509_qualifier_t; typedef struct gnutls_x509_policy_st { char *oid; unsigned int qualifiers; struct { gnutls_x509_qualifier_t type; char *data; unsigned int size; } qualifier[GNUTLS_MAX_QUALIFIERS]; } gnutls_x509_policy_st; void gnutls_x509_policy_release(struct gnutls_x509_policy_st *policy); int gnutls_x509_crt_get_policy(gnutls_x509_crt_t crt, unsigned indx, struct gnutls_x509_policy_st *policy, unsigned int *critical); int gnutls_x509_crt_set_policy(gnutls_x509_crt_t crt, const struct gnutls_x509_policy_st *policy, unsigned int critical); int gnutls_x509_dn_oid_known(const char *oid); #define GNUTLS_X509_DN_OID_RETURN_OID 1 const char *gnutls_x509_dn_oid_name(const char *oid, unsigned int flags); /* Read extensions by OID. */ int gnutls_x509_crt_get_extension_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size); int gnutls_x509_crt_get_extension_by_oid(gnutls_x509_crt_t cert, const char *oid, unsigned indx, void *buf, size_t * buf_size, unsigned int *critical); int gnutls_x509_crq_get_signature_algorithm(gnutls_x509_crq_t crq); int gnutls_x509_crq_get_extension_by_oid2(gnutls_x509_crq_t crq, const char *oid, unsigned indx, gnutls_datum_t *output, unsigned int *critical); /* Read extensions by sequence number. */ int gnutls_x509_crt_get_extension_info(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size, unsigned int *critical); int gnutls_x509_crt_get_extension_data(gnutls_x509_crt_t cert, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crt_get_extension_data2(gnutls_x509_crt_t cert, unsigned indx, gnutls_datum_t * data); int gnutls_x509_crt_set_extension_by_oid(gnutls_x509_crt_t crt, const char *oid, const void *buf, size_t sizeof_buf, unsigned int critical); /* X.509 Certificate writing. */ int gnutls_x509_crt_set_dn(gnutls_x509_crt_t crt, const char *dn, const char **err); int gnutls_x509_crt_set_dn_by_oid(gnutls_x509_crt_t crt, const char *oid, unsigned int raw_flag, const void *name, unsigned int sizeof_name); int gnutls_x509_crt_set_issuer_dn_by_oid(gnutls_x509_crt_t crt, const char *oid, unsigned int raw_flag, const void *name, unsigned int sizeof_name); int gnutls_x509_crt_set_issuer_dn(gnutls_x509_crt_t crt, const char *dn, const char **err); int gnutls_x509_crt_set_version(gnutls_x509_crt_t crt, unsigned int version); int gnutls_x509_crt_set_key(gnutls_x509_crt_t crt, gnutls_x509_privkey_t key); int gnutls_x509_crt_set_ca_status(gnutls_x509_crt_t crt, unsigned int ca); int gnutls_x509_crt_set_basic_constraints(gnutls_x509_crt_t crt, unsigned int ca, int pathLenConstraint); int gnutls_x509_crt_set_subject_unique_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_set_issuer_unique_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_set_subject_alternative_name(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const char *data_string); int gnutls_x509_crt_set_subject_alt_name(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_set_subject_alt_othername(gnutls_x509_crt_t crt, const char *oid, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_set_issuer_alt_name(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_set_issuer_alt_othername(gnutls_x509_crt_t crt, const char *oid, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_sign(gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key); int gnutls_x509_crt_sign2(gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crt_set_activation_time(gnutls_x509_crt_t cert, time_t act_time); int gnutls_x509_crt_set_expiration_time(gnutls_x509_crt_t cert, time_t exp_time); int gnutls_x509_crt_set_serial(gnutls_x509_crt_t cert, const void *serial, size_t serial_size); int gnutls_x509_crt_set_subject_key_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_set_proxy_dn(gnutls_x509_crt_t crt, gnutls_x509_crt_t eecrt, unsigned int raw_flag, const void *name, unsigned int sizeof_name); int gnutls_x509_crt_set_proxy(gnutls_x509_crt_t crt, int pathLenConstraint, const char *policyLanguage, const char *policy, size_t sizeof_policy); int gnutls_x509_crt_print(gnutls_x509_crt_t cert, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); int gnutls_x509_crl_print(gnutls_x509_crl_t crl, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); /* Access to internal Certificate fields. */ int gnutls_x509_crt_get_raw_issuer_dn(gnutls_x509_crt_t cert, gnutls_datum_t * start); int gnutls_x509_crt_get_raw_dn(gnutls_x509_crt_t cert, gnutls_datum_t * start); /* RDN handling. */ int gnutls_x509_rdn_get(const gnutls_datum_t * idn, char *buf, size_t * sizeof_buf); int gnutls_x509_rdn_get2(const gnutls_datum_t * idn, gnutls_datum_t *str, unsigned flags); int gnutls_x509_rdn_get_oid(const gnutls_datum_t * idn, unsigned indx, void *buf, size_t * sizeof_buf); int gnutls_x509_rdn_get_by_oid(const gnutls_datum_t * idn, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * sizeof_buf); typedef struct gnutls_x509_dn_st *gnutls_x509_dn_t; typedef struct gnutls_x509_ava_st { gnutls_datum_t oid; gnutls_datum_t value; unsigned long value_tag; } gnutls_x509_ava_st; int gnutls_x509_crt_get_subject(gnutls_x509_crt_t cert, gnutls_x509_dn_t * dn); int gnutls_x509_crt_get_issuer(gnutls_x509_crt_t cert, gnutls_x509_dn_t * dn); int gnutls_x509_dn_get_rdn_ava(gnutls_x509_dn_t dn, int irdn, int iava, gnutls_x509_ava_st * ava); int gnutls_x509_dn_get_str(gnutls_x509_dn_t dn, gnutls_datum_t *str); #define GNUTLS_X509_DN_FLAG_COMPAT 1 int gnutls_x509_dn_get_str2(gnutls_x509_dn_t dn, gnutls_datum_t *str, unsigned flags); int gnutls_x509_dn_set_str(gnutls_x509_dn_t dn, const char *str, const char **err); int gnutls_x509_dn_init(gnutls_x509_dn_t * dn); int gnutls_x509_dn_import(gnutls_x509_dn_t dn, const gnutls_datum_t * data); int gnutls_x509_dn_export(gnutls_x509_dn_t dn, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_dn_export2(gnutls_x509_dn_t dn, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); void gnutls_x509_dn_deinit(gnutls_x509_dn_t dn); /* CRL handling functions. */ int gnutls_x509_crl_init(gnutls_x509_crl_t * crl); void gnutls_x509_crl_deinit(gnutls_x509_crl_t crl); int gnutls_x509_crl_import(gnutls_x509_crl_t crl, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_crl_export(gnutls_x509_crl_t crl, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_crl_export2(gnutls_x509_crl_t crl, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_crl_get_raw_issuer_dn(gnutls_x509_crl_t crl, gnutls_datum_t * dn); int gnutls_x509_crl_get_issuer_dn(gnutls_x509_crl_t crl, char *buf, size_t * sizeof_buf); int gnutls_x509_crl_get_issuer_dn2(gnutls_x509_crl_t crl, gnutls_datum_t * dn); int gnutls_x509_crl_get_issuer_dn3(gnutls_x509_crl_t crl, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crl_get_issuer_dn_by_oid(gnutls_x509_crl_t crl, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * sizeof_buf); int gnutls_x509_crl_get_dn_oid(gnutls_x509_crl_t crl, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crl_get_signature_algorithm(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_signature(gnutls_x509_crl_t crl, char *sig, size_t * sizeof_sig); int gnutls_x509_crl_get_version(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_signature_oid(gnutls_x509_crl_t crl, char *oid, size_t *oid_size); time_t gnutls_x509_crl_get_this_update(gnutls_x509_crl_t crl); time_t gnutls_x509_crl_get_next_update(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_crt_count(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_crt_serial(gnutls_x509_crl_t crl, unsigned indx, unsigned char *serial, size_t * serial_size, time_t * t); typedef struct gnutls_x509_crl_iter * gnutls_x509_crl_iter_t; int gnutls_x509_crl_iter_crt_serial(gnutls_x509_crl_t crl, gnutls_x509_crl_iter_t *, unsigned char *serial, size_t * serial_size, time_t * t); void gnutls_x509_crl_iter_deinit(gnutls_x509_crl_iter_t); #define gnutls_x509_crl_get_certificate_count gnutls_x509_crl_get_crt_count #define gnutls_x509_crl_get_certificate gnutls_x509_crl_get_crt_serial unsigned gnutls_x509_crl_check_issuer(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer); int gnutls_x509_crl_list_import2(gnutls_x509_crl_t ** crls, unsigned int *size, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_x509_crl_list_import(gnutls_x509_crl_t * crls, unsigned int *crl_max, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); /* CRL writing. */ int gnutls_x509_crl_set_version(gnutls_x509_crl_t crl, unsigned int version); int gnutls_x509_crl_set_this_update(gnutls_x509_crl_t crl, time_t act_time); int gnutls_x509_crl_set_next_update(gnutls_x509_crl_t crl, time_t exp_time); int gnutls_x509_crl_set_crt_serial(gnutls_x509_crl_t crl, const void *serial, size_t serial_size, time_t revocation_time); int gnutls_x509_crl_set_crt(gnutls_x509_crl_t crl, gnutls_x509_crt_t crt, time_t revocation_time); int gnutls_x509_crl_get_authority_key_id(gnutls_x509_crl_t crl, void *id, size_t * id_size, unsigned int *critical); int gnutls_x509_crl_get_authority_key_gn_serial(gnutls_x509_crl_t crl, unsigned int seq, void *alt, size_t * alt_size, unsigned int *alt_type, void *serial, size_t * serial_size, unsigned int *critical); int gnutls_x509_crl_get_number(gnutls_x509_crl_t crl, void *ret, size_t * ret_size, unsigned int *critical); int gnutls_x509_crl_get_extension_oid(gnutls_x509_crl_t crl, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crl_get_extension_info(gnutls_x509_crl_t crl, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical); int gnutls_x509_crl_get_extension_data(gnutls_x509_crl_t crl, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crl_get_extension_data2(gnutls_x509_crl_t crl, unsigned indx, gnutls_datum_t * data); int gnutls_x509_crl_set_authority_key_id(gnutls_x509_crl_t crl, const void *id, size_t id_size); int gnutls_x509_crl_set_number(gnutls_x509_crl_t crl, const void *nr, size_t nr_size); /* X.509 Certificate verification functions. */ /** * gnutls_certificate_verify_flags: * @GNUTLS_VERIFY_DISABLE_CA_SIGN: If set a signer does not have to be * a certificate authority. This flag should normally be disabled, * unless you know what this means. * @GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS: If set a signer in the trusted * list is never checked for expiration or activation. * @GNUTLS_VERIFY_DO_NOT_ALLOW_X509_V1_CA_CRT: Do not allow trusted CA * certificates that have version 1. This option is to be used * to deprecate all certificates of version 1. * @GNUTLS_VERIFY_DO_NOT_ALLOW_SAME: If a certificate is not signed by * anyone trusted but exists in the trusted CA list do not treat it * as trusted. * @GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN: A certificate chain is tolerated * if unsorted (the case with many TLS servers out there). This is the * default since GnuTLS 3.1.4. * @GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN: Do not tolerate an unsorted * certificate chain. * @GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT: Allow CA certificates that * have version 1 (both root and intermediate). This might be * dangerous since those haven't the basicConstraints * extension. * @GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2: Allow certificates to be signed * using the broken MD2 algorithm. * @GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5: Allow certificates to be signed * using the broken MD5 algorithm. * @GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1: Allow certificates to be signed * using the broken SHA1 hash algorithm. * @GNUTLS_VERIFY_ALLOW_BROKEN: Allow certificates to be signed * using any broken algorithm. * @GNUTLS_VERIFY_DISABLE_TIME_CHECKS: Disable checking of activation * and expiration validity periods of certificate chains. Don't set * this unless you understand the security implications. * @GNUTLS_VERIFY_DISABLE_CRL_CHECKS: Disable checking for validity * using certificate revocation lists or the available OCSP data. * @GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS: When including a hostname * check in the verification, do not consider any wildcards. * @GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES: When verifying a hostname * prevent textual IP addresses from matching IP addresses in the * certificate. Treat the input only as a DNS name. * @GNUTLS_VERIFY_USE_TLS1_RSA: This indicates that a (raw) RSA signature is provided * as in the TLS 1.0 protocol. Not all functions accept this flag. * @GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS: This signals the verification * process, not to fail on unknown critical extensions. * @GNUTLS_VERIFY_RSA_PSS_FIXED_SALT_LENGTH: Disallow RSA-PSS signatures made * with mismatching salt length with digest length, as mandated in RFC 8446 * 4.2.3. * * Enumeration of different certificate verify flags. Additional * verification profiles can be set using GNUTLS_PROFILE_TO_VFLAGS() * and %gnutls_certificate_verification_profiles_t. */ typedef enum gnutls_certificate_verify_flags { GNUTLS_VERIFY_DISABLE_CA_SIGN = 1 << 0, GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES = 1<<1, GNUTLS_VERIFY_DO_NOT_ALLOW_SAME = 1 << 2, GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT = 1 << 3, GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2 = 1 << 4, GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5 = 1 << 5, GNUTLS_VERIFY_DISABLE_TIME_CHECKS = 1 << 6, GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS = 1 << 7, GNUTLS_VERIFY_DO_NOT_ALLOW_X509_V1_CA_CRT = 1 << 8, GNUTLS_VERIFY_DISABLE_CRL_CHECKS = 1 << 9, GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN = 1 << 10, GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN = 1 << 11, GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS = 1 << 12, GNUTLS_VERIFY_USE_TLS1_RSA = 1 << 13, GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS = 1 << 14, GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1 = 1 << 15, GNUTLS_VERIFY_RSA_PSS_FIXED_SALT_LENGTH = 1 << 16 /* cannot exceed 2^24 due to GNUTLS_PROFILE_TO_VFLAGS() */ } gnutls_certificate_verify_flags; #define GNUTLS_VERIFY_ALLOW_BROKEN (GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2|GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5) /** * gnutls_certificate_verification_profiles_t: * @GNUTLS_PROFILE_UNKNOWN: An invalid/unknown profile. * @GNUTLS_PROFILE_VERY_WEAK: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_VERY_WEAK (64 bits) * @GNUTLS_PROFILE_LOW: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_LOW (80 bits) * @GNUTLS_PROFILE_LEGACY: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_LEGACY (96 bits) * @GNUTLS_PROFILE_MEDIUM: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_MEDIUM (112 bits) * @GNUTLS_PROFILE_HIGH: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_HIGH (128 bits) * @GNUTLS_PROFILE_ULTRA: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_ULTRA (192 bits) * @GNUTLS_PROFILE_FUTURE: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_FUTURE (256 bits) * @GNUTLS_PROFILE_SUITEB128: A verification profile that * applies the SUITEB128 rules * @GNUTLS_PROFILE_SUITEB192: A verification profile that * applies the SUITEB192 rules * * Enumeration of different certificate verification profiles. */ typedef enum gnutls_certificate_verification_profiles_t { GNUTLS_PROFILE_UNKNOWN = 0, GNUTLS_PROFILE_VERY_WEAK = 1, GNUTLS_PROFILE_LOW = 2, GNUTLS_PROFILE_LEGACY = 4, GNUTLS_PROFILE_MEDIUM = 5, GNUTLS_PROFILE_HIGH = 6, GNUTLS_PROFILE_ULTRA = 7, GNUTLS_PROFILE_FUTURE = 8, GNUTLS_PROFILE_SUITEB128=32, GNUTLS_PROFILE_SUITEB192=33 /*GNUTLS_PROFILE_MAX=255*/ } gnutls_certificate_verification_profiles_t; #define GNUTLS_PROFILE_TO_VFLAGS(x) \ (((unsigned)x)<<24) #define GNUTLS_VFLAGS_PROFILE_MASK (0xff000000) #define GNUTLS_VFLAGS_TO_PROFILE(x) \ ((((unsigned)x)>>24)&0xff) const char * gnutls_certificate_verification_profile_get_name(gnutls_certificate_verification_profiles_t id) __GNUTLS_CONST__; gnutls_certificate_verification_profiles_t gnutls_certificate_verification_profile_get_id(const char *name) __GNUTLS_CONST__; unsigned gnutls_x509_crt_check_issuer(gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer); int gnutls_x509_crt_list_verify(const gnutls_x509_crt_t * cert_list, unsigned cert_list_length, const gnutls_x509_crt_t * CA_list, unsigned CA_list_length, const gnutls_x509_crl_t * CRL_list, unsigned CRL_list_length, unsigned int flags, unsigned int *verify); int gnutls_x509_crt_verify(gnutls_x509_crt_t cert, const gnutls_x509_crt_t * CA_list, unsigned CA_list_length, unsigned int flags, unsigned int *verify); int gnutls_x509_crl_verify(gnutls_x509_crl_t crl, const gnutls_x509_crt_t * CA_list, unsigned CA_list_length, unsigned int flags, unsigned int *verify); int gnutls_x509_crt_verify_data2(gnutls_x509_crt_t crt, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * data, const gnutls_datum_t * signature); int gnutls_x509_crt_check_revocation(gnutls_x509_crt_t cert, const gnutls_x509_crl_t * crl_list, unsigned crl_list_length); int gnutls_x509_crt_get_fingerprint(gnutls_x509_crt_t cert, gnutls_digest_algorithm_t algo, void *buf, size_t * buf_size); int gnutls_x509_crt_get_key_purpose_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size, unsigned int *critical); int gnutls_x509_crt_set_key_purpose_oid(gnutls_x509_crt_t cert, const void *oid, unsigned int critical); unsigned gnutls_x509_crt_check_key_purpose(gnutls_x509_crt_t cert, const char *purpose, unsigned flags); /* Private key handling. */ /* Flags for the gnutls_x509_privkey_export_pkcs8() function. */ #define GNUTLS_PKCS8_PLAIN GNUTLS_PKCS_PLAIN #define GNUTLS_PKCS8_USE_PKCS12_3DES GNUTLS_PKCS_PKCS12_3DES #define GNUTLS_PKCS8_USE_PKCS12_ARCFOUR GNUTLS_PKCS_PKCS12_ARCFOUR #define GNUTLS_PKCS8_USE_PKCS12_RC2_40 GNUTLS_PKCS_PKCS12_RC2_40 /** * gnutls_pkcs_encrypt_flags_t: * @GNUTLS_PKCS_PLAIN: Unencrypted private key. * @GNUTLS_PKCS_NULL_PASSWORD: Some schemas distinguish between an empty and a NULL password. * @GNUTLS_PKCS_PKCS12_3DES: PKCS-12 3DES. * @GNUTLS_PKCS_PKCS12_ARCFOUR: PKCS-12 ARCFOUR. * @GNUTLS_PKCS_PKCS12_RC2_40: PKCS-12 RC2-40. * @GNUTLS_PKCS_PBES2_3DES: PBES2 3DES. * @GNUTLS_PKCS_PBES2_AES_128: PBES2 AES-128. * @GNUTLS_PKCS_PBES2_AES_192: PBES2 AES-192. * @GNUTLS_PKCS_PBES2_AES_256: PBES2 AES-256. * @GNUTLS_PKCS_PBES2_DES: PBES2 single DES. * @GNUTLS_PKCS_PBES1_DES_MD5: PBES1 with single DES; for compatibility with openssl only. * @GNUTLS_PKCS_PBES2_GOST_TC26Z: PBES2 GOST 28147-89 CFB with TC26-Z S-box. * @GNUTLS_PKCS_PBES2_GOST_CPA: PBES2 GOST 28147-89 CFB with CryptoPro-A S-box. * @GNUTLS_PKCS_PBES2_GOST_CPB: PBES2 GOST 28147-89 CFB with CryptoPro-B S-box. * @GNUTLS_PKCS_PBES2_GOST_CPC: PBES2 GOST 28147-89 CFB with CryptoPro-C S-box. * @GNUTLS_PKCS_PBES2_GOST_CPD: PBES2 GOST 28147-89 CFB with CryptoPro-D S-box. * * Enumeration of different PKCS encryption flags. */ typedef enum gnutls_pkcs_encrypt_flags_t { GNUTLS_PKCS_PLAIN = 1, GNUTLS_PKCS_PKCS12_3DES = 1<<1, GNUTLS_PKCS_PKCS12_ARCFOUR = 1<<2, GNUTLS_PKCS_PKCS12_RC2_40 = 1<<3, GNUTLS_PKCS_PBES2_3DES = 1<<4, GNUTLS_PKCS_PBES2_AES_128 = 1<<5, GNUTLS_PKCS_PBES2_AES_192 = 1<<6, GNUTLS_PKCS_PBES2_AES_256 = 1<<7, GNUTLS_PKCS_NULL_PASSWORD = 1<<8, GNUTLS_PKCS_PBES2_DES = 1<<9, GNUTLS_PKCS_PBES1_DES_MD5 = 1<<10, GNUTLS_PKCS_PBES2_GOST_TC26Z = 1<<11, GNUTLS_PKCS_PBES2_GOST_CPA = 1<<12, GNUTLS_PKCS_PBES2_GOST_CPB = 1<<13, GNUTLS_PKCS_PBES2_GOST_CPC = 1<<14, GNUTLS_PKCS_PBES2_GOST_CPD = 1<<15 } gnutls_pkcs_encrypt_flags_t; #define GNUTLS_PKCS_CIPHER_MASK(x) ((x)&(~(GNUTLS_PKCS_NULL_PASSWORD))) #define GNUTLS_PKCS_USE_PKCS12_3DES GNUTLS_PKCS_PKCS12_3DES #define GNUTLS_PKCS_USE_PKCS12_ARCFOUR GNUTLS_PKCS_PKCS12_ARCFOUR #define GNUTLS_PKCS_USE_PKCS12_RC2_40 GNUTLS_PKCS_PKCS12_RC2_40 #define GNUTLS_PKCS_USE_PBES2_3DES GNUTLS_PKCS_PBES2_3DES #define GNUTLS_PKCS_USE_PBES2_AES_128 GNUTLS_PKCS_PBES2_AES_128 #define GNUTLS_PKCS_USE_PBES2_AES_192 GNUTLS_PKCS_PBES2_AES_192 #define GNUTLS_PKCS_USE_PBES2_AES_256 GNUTLS_PKCS_PBES2_AES_256 #define GNUTLS_PKCS_USE_PBES2_GOST_TC26Z GNUTLS_PKCS_PBES2_GOST_TC26Z #define GNUTLS_PKCS_USE_PBES2_GOST_CPA GNUTLS_PKCS_PBES2_GOST_CPA #define GNUTLS_PKCS_USE_PBES2_GOST_CPB GNUTLS_PKCS_PBES2_GOST_CPB #define GNUTLS_PKCS_USE_PBES2_GOST_CPC GNUTLS_PKCS_PBES2_GOST_CPC #define GNUTLS_PKCS_USE_PBES2_GOST_CPD GNUTLS_PKCS_PBES2_GOST_CPD const char *gnutls_pkcs_schema_get_name(unsigned int schema); const char *gnutls_pkcs_schema_get_oid(unsigned int schema); int gnutls_x509_privkey_init(gnutls_x509_privkey_t * key); void gnutls_x509_privkey_deinit(gnutls_x509_privkey_t key); gnutls_sec_param_t gnutls_x509_privkey_sec_param(gnutls_x509_privkey_t key); void gnutls_x509_privkey_set_pin_function(gnutls_x509_privkey_t key, gnutls_pin_callback_t fn, void *userdata); int gnutls_x509_privkey_cpy(gnutls_x509_privkey_t dst, gnutls_x509_privkey_t src); int gnutls_x509_privkey_import(gnutls_x509_privkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_privkey_import_pkcs8(gnutls_x509_privkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags); int gnutls_x509_privkey_import_openssl(gnutls_x509_privkey_t key, const gnutls_datum_t * data, const char *password); int gnutls_pkcs8_info(const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int *schema, unsigned int *cipher, void *salt, unsigned int *salt_size, unsigned int *iter_count, char **oid); int gnutls_x509_privkey_import2(gnutls_x509_privkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags); int gnutls_x509_privkey_import_rsa_raw(gnutls_x509_privkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e, const gnutls_datum_t * d, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * u); int gnutls_x509_privkey_import_rsa_raw2(gnutls_x509_privkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e, const gnutls_datum_t * d, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * u, const gnutls_datum_t * e1, const gnutls_datum_t * e2); int gnutls_x509_privkey_import_ecc_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t curve, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_x509_privkey_import_gost_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t curve, gnutls_digest_algorithm_t digest, gnutls_gost_paramset_t paramset, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_x509_privkey_fix(gnutls_x509_privkey_t key); int gnutls_x509_privkey_export_dsa_raw(gnutls_x509_privkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x); int gnutls_x509_privkey_import_dsa_raw(gnutls_x509_privkey_t key, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * g, const gnutls_datum_t * y, const gnutls_datum_t * x); int gnutls_x509_privkey_get_pk_algorithm(gnutls_x509_privkey_t key); int gnutls_x509_privkey_get_pk_algorithm2(gnutls_x509_privkey_t key, unsigned int *bits); int gnutls_x509_privkey_get_spki(gnutls_x509_privkey_t key, gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_privkey_set_spki(gnutls_x509_privkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_privkey_get_key_id(gnutls_x509_privkey_t key, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_x509_privkey_generate(gnutls_x509_privkey_t key, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags); void gnutls_x509_privkey_set_flags(gnutls_x509_privkey_t key, unsigned int flags); /** * gnutls_keygen_types_t: * @GNUTLS_KEYGEN_SEED: Specifies the seed to be used in key generation. * @GNUTLS_KEYGEN_DIGEST: The size field specifies the hash algorithm to be used in key generation. * @GNUTLS_KEYGEN_SPKI: data points to a %gnutls_x509_spki_t structure; it is not used after the key generation call. * * Enumeration of different key generation data options. */ typedef enum { GNUTLS_KEYGEN_SEED = 1, GNUTLS_KEYGEN_DIGEST = 2, GNUTLS_KEYGEN_SPKI = 3 } gnutls_keygen_types_t; typedef struct { gnutls_keygen_types_t type; unsigned char *data; unsigned int size; } gnutls_keygen_data_st; int gnutls_x509_privkey_generate2(gnutls_x509_privkey_t key, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags, const gnutls_keygen_data_st *data, unsigned data_size); int gnutls_x509_privkey_verify_seed(gnutls_x509_privkey_t key, gnutls_digest_algorithm_t, const void *seed, size_t seed_size); int gnutls_x509_privkey_get_seed(gnutls_x509_privkey_t key, gnutls_digest_algorithm_t*, void *seed, size_t *seed_size); int gnutls_x509_privkey_verify_params(gnutls_x509_privkey_t key); int gnutls_x509_privkey_export(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_privkey_export2(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_privkey_export_pkcs8(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags, void *output_data, size_t * output_data_size); int gnutls_x509_privkey_export2_pkcs8(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags, gnutls_datum_t * out); int gnutls_x509_privkey_export_rsa_raw2(gnutls_x509_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u, gnutls_datum_t * e1, gnutls_datum_t * e2); int gnutls_x509_privkey_export_rsa_raw(gnutls_x509_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u); int gnutls_x509_privkey_export_ecc_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k); int gnutls_x509_privkey_export_gost_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t * paramset, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k); int gnutls_x509_privkey_sign_data(gnutls_x509_privkey_t key, gnutls_digest_algorithm_t digest, unsigned int flags, const gnutls_datum_t * data, void *signature, size_t * signature_size); /* Certificate request stuff. */ int gnutls_x509_crq_sign(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key); int gnutls_x509_crq_sign2(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crq_print(gnutls_x509_crq_t crq, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); int gnutls_x509_crq_verify(gnutls_x509_crq_t crq, unsigned int flags); int gnutls_x509_crq_init(gnutls_x509_crq_t * crq); void gnutls_x509_crq_deinit(gnutls_x509_crq_t crq); int gnutls_x509_crq_import(gnutls_x509_crq_t crq, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_crq_get_private_key_usage_period(gnutls_x509_crq_t cert, time_t * activation, time_t * expiration, unsigned int *critical); int gnutls_x509_crq_get_dn(gnutls_x509_crq_t crq, char *buf, size_t * sizeof_buf); int gnutls_x509_crq_get_dn2(gnutls_x509_crq_t crq, gnutls_datum_t * dn); int gnutls_x509_crq_get_dn3(gnutls_x509_crq_t crq, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crq_get_dn_oid(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crq_get_dn_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * sizeof_buf); int gnutls_x509_crq_set_dn(gnutls_x509_crq_t crq, const char *dn, const char **err); int gnutls_x509_crq_set_dn_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned int raw_flag, const void *data, unsigned int sizeof_data); int gnutls_x509_crq_set_version(gnutls_x509_crq_t crq, unsigned int version); int gnutls_x509_crq_get_version(gnutls_x509_crq_t crq); int gnutls_x509_crq_set_key(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key); int gnutls_x509_crq_set_extension_by_oid(gnutls_x509_crq_t crq, const char *oid, const void *buf, size_t sizeof_buf, unsigned int critical); int gnutls_x509_crq_set_challenge_password(gnutls_x509_crq_t crq, const char *pass); int gnutls_x509_crq_get_challenge_password(gnutls_x509_crq_t crq, char *pass, size_t * sizeof_pass); int gnutls_x509_crq_set_attribute_by_oid(gnutls_x509_crq_t crq, const char *oid, void *buf, size_t sizeof_buf); int gnutls_x509_crq_get_attribute_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, void *buf, size_t * sizeof_buf); int gnutls_x509_crq_export(gnutls_x509_crq_t crq, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_crq_export2(gnutls_x509_crq_t crq, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_crt_set_crq(gnutls_x509_crt_t crt, gnutls_x509_crq_t crq); int gnutls_x509_crt_set_crq_extensions(gnutls_x509_crt_t crt, gnutls_x509_crq_t crq); int gnutls_x509_crt_set_crq_extension_by_oid(gnutls_x509_crt_t crt, gnutls_x509_crq_t crq, const char *oid, unsigned flags); int gnutls_x509_crq_set_private_key_usage_period(gnutls_x509_crq_t crq, time_t activation, time_t expiration); int gnutls_x509_crq_set_key_rsa_raw(gnutls_x509_crq_t crq, const gnutls_datum_t * m, const gnutls_datum_t * e); int gnutls_x509_crq_set_subject_alt_name(gnutls_x509_crq_t crq, gnutls_x509_subject_alt_name_t nt, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crq_set_subject_alt_othername(gnutls_x509_crq_t crq, const char *oid, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crq_set_key_usage(gnutls_x509_crq_t crq, unsigned int usage); int gnutls_x509_crq_set_basic_constraints(gnutls_x509_crq_t crq, unsigned int ca, int pathLenConstraint); int gnutls_x509_crq_set_key_purpose_oid(gnutls_x509_crq_t crq, const void *oid, unsigned int critical); int gnutls_x509_crq_get_key_purpose_oid(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical); int gnutls_x509_crq_get_extension_data(gnutls_x509_crq_t crq, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crq_get_extension_data2(gnutls_x509_crq_t crq, unsigned indx, gnutls_datum_t * data); int gnutls_x509_crq_get_extension_info(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical); int gnutls_x509_crq_get_attribute_data(gnutls_x509_crq_t crq, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crq_get_attribute_info(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crq_get_pk_algorithm(gnutls_x509_crq_t crq, unsigned int *bits); int gnutls_x509_crq_get_spki(gnutls_x509_crq_t crq, gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crq_set_spki(gnutls_x509_crq_t crq, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crq_get_signature_oid(gnutls_x509_crq_t crq, char *oid, size_t *oid_size); int gnutls_x509_crq_get_pk_oid(gnutls_x509_crq_t crq, char *oid, size_t *oid_size); int gnutls_x509_crq_get_key_id(gnutls_x509_crq_t crq, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_x509_crq_get_key_rsa_raw(gnutls_x509_crq_t crq, gnutls_datum_t * m, gnutls_datum_t * e); int gnutls_x509_crq_get_key_usage(gnutls_x509_crq_t crq, unsigned int *key_usage, unsigned int *critical); int gnutls_x509_crq_get_basic_constraints(gnutls_x509_crq_t crq, unsigned int *critical, unsigned int *ca, int *pathlen); int gnutls_x509_crq_get_subject_alt_name(gnutls_x509_crq_t crq, unsigned int seq, void *ret, size_t * ret_size, unsigned int *ret_type, unsigned int *critical); int gnutls_x509_crq_get_subject_alt_othername_oid(gnutls_x509_crq_t crq, unsigned int seq, void *ret, size_t * ret_size); int gnutls_x509_crq_get_extension_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, void *buf, size_t * sizeof_buf, unsigned int *critical); int gnutls_x509_crq_get_tlsfeatures(gnutls_x509_crq_t crq, gnutls_x509_tlsfeatures_t features, unsigned flags, unsigned int *critical); int gnutls_x509_crq_set_tlsfeatures(gnutls_x509_crq_t crq, gnutls_x509_tlsfeatures_t features); int gnutls_x509_crt_get_extension_by_oid2(gnutls_x509_crt_t cert, const char *oid, unsigned indx, gnutls_datum_t *output, unsigned int *critical); typedef struct gnutls_x509_trust_list_st *gnutls_x509_trust_list_t; typedef struct gnutls_x509_trust_list_iter *gnutls_x509_trust_list_iter_t; int gnutls_x509_trust_list_init(gnutls_x509_trust_list_t * list, unsigned int size); void gnutls_x509_trust_list_deinit(gnutls_x509_trust_list_t list, unsigned int all); int gnutls_x509_trust_list_get_issuer(gnutls_x509_trust_list_t list, gnutls_x509_crt_t cert, gnutls_x509_crt_t * issuer, unsigned int flags); int gnutls_x509_trust_list_get_issuer_by_dn(gnutls_x509_trust_list_t list, const gnutls_datum_t *dn, gnutls_x509_crt_t *issuer, unsigned int flags); int gnutls_x509_trust_list_get_issuer_by_subject_key_id(gnutls_x509_trust_list_t list, const gnutls_datum_t *dn, const gnutls_datum_t *spki, gnutls_x509_crt_t *issuer, unsigned int flags); /** * gnutls_trust_list_flags_t: * @GNUTLS_TL_VERIFY_CRL: If any CRLs are provided they will be verified for validity * prior to be added. The CA certificates that will be used for verification are the * ones already added in the trusted list. * @GNUTLS_TL_USE_IN_TLS: Internal flag used by GnuTLS. If provided the trust list * structure will cache a copy of CA DNs to be used in the certificate request * TLS message. * @GNUTLS_TL_NO_DUPLICATES: If this flag is specified, a function adding certificates * will check and eliminate any duplicates. * @GNUTLS_TL_NO_DUPLICATE_KEY: If this flag is specified, a certificate sharing the * same key as a previously added on will not be added. * @GNUTLS_TL_GET_COPY: The semantics of this flag are documented to the functions which * are applicable. In general, on returned value, the function will provide a copy * if this flag is provided, rather than a pointer to internal data. * @GNUTLS_TL_FAIL_ON_INVALID_CRL: If an CRL is added which cannot be validated return * an error instead of ignoring (must be used with %GNUTLS_TL_VERIFY_CRL). * * Enumeration of different certificate trust list flags. */ typedef enum gnutls_trust_list_flags_t { GNUTLS_TL_VERIFY_CRL = 1, #define GNUTLS_TL_VERIFY_CRL 1 GNUTLS_TL_USE_IN_TLS = (1<<1), #define GNUTLS_TL_USE_IN_TLS (1<<1) GNUTLS_TL_NO_DUPLICATES = (1<<2), #define GNUTLS_TL_NO_DUPLICATES (1<<2) GNUTLS_TL_NO_DUPLICATE_KEY = (1<<3), #define GNUTLS_TL_NO_DUPLICATE_KEY (1<<3) GNUTLS_TL_GET_COPY = (1<<4), #define GNUTLS_TL_GET_COPY (1<<4) GNUTLS_TL_FAIL_ON_INVALID_CRL = (1<<5) #define GNUTLS_TL_FAIL_ON_INVALID_CRL (1<<5) } gnutls_trust_list_flags_t; int gnutls_x509_trust_list_add_cas(gnutls_x509_trust_list_t list, const gnutls_x509_crt_t * clist, unsigned clist_size, unsigned int flags); int gnutls_x509_trust_list_remove_cas(gnutls_x509_trust_list_t list, const gnutls_x509_crt_t * clist, unsigned clist_size); int gnutls_x509_trust_list_add_named_crt(gnutls_x509_trust_list_t list, gnutls_x509_crt_t cert, const void *name, size_t name_size, unsigned int flags); int gnutls_x509_trust_list_add_crls(gnutls_x509_trust_list_t list, const gnutls_x509_crl_t * crl_list, unsigned crl_size, unsigned int flags, unsigned int verification_flags); int gnutls_x509_trust_list_iter_get_ca(gnutls_x509_trust_list_t list, gnutls_x509_trust_list_iter_t *iter, gnutls_x509_crt_t *crt); void gnutls_x509_trust_list_iter_deinit(gnutls_x509_trust_list_iter_t iter); typedef int gnutls_verify_output_function(gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer, /* The issuer if verification failed * because of him. might be null. */ gnutls_x509_crl_t crl, /* The CRL that caused verification failure * if any. Might be null. */ unsigned int verification_output); void gnutls_session_set_verify_output_function(gnutls_session_t session, gnutls_verify_output_function * func); int gnutls_x509_trust_list_verify_named_crt (gnutls_x509_trust_list_t list, gnutls_x509_crt_t cert, const void *name, size_t name_size, unsigned int flags, unsigned int *verify, gnutls_verify_output_function func); int gnutls_x509_trust_list_verify_crt2(gnutls_x509_trust_list_t list, gnutls_x509_crt_t * cert_list, unsigned int cert_list_size, gnutls_typed_vdata_st * data, unsigned int elements, unsigned int flags, unsigned int *voutput, gnutls_verify_output_function func); int gnutls_x509_trust_list_verify_crt(gnutls_x509_trust_list_t list, gnutls_x509_crt_t * cert_list, unsigned int cert_list_size, unsigned int flags, unsigned int *verify, gnutls_verify_output_function func); /* trust list convenience functions */ int gnutls_x509_trust_list_add_trust_mem(gnutls_x509_trust_list_t list, const gnutls_datum_t * cas, const gnutls_datum_t * crls, gnutls_x509_crt_fmt_t type, unsigned int tl_flags, unsigned int tl_vflags); int gnutls_x509_trust_list_add_trust_file(gnutls_x509_trust_list_t list, const char *ca_file, const char *crl_file, gnutls_x509_crt_fmt_t type, unsigned int tl_flags, unsigned int tl_vflags); int gnutls_x509_trust_list_add_trust_dir(gnutls_x509_trust_list_t list, const char *ca_dir, const char *crl_dir, gnutls_x509_crt_fmt_t type, unsigned int tl_flags, unsigned int tl_vflags); int gnutls_x509_trust_list_remove_trust_file(gnutls_x509_trust_list_t list, const char *ca_file, gnutls_x509_crt_fmt_t type); int gnutls_x509_trust_list_remove_trust_mem(gnutls_x509_trust_list_t list, const gnutls_datum_t * cas, gnutls_x509_crt_fmt_t type); int gnutls_x509_trust_list_add_system_trust(gnutls_x509_trust_list_t list, unsigned int tl_flags, unsigned int tl_vflags); typedef int gnutls_x509_trust_list_getissuer_function(gnutls_x509_trust_list_t list, const gnutls_x509_crt_t cert, gnutls_x509_crt_t **issuers, unsigned int *issuers_size); void gnutls_x509_trust_list_set_getissuer_function(gnutls_x509_trust_list_t tlist, gnutls_x509_trust_list_getissuer_function *func); void gnutls_x509_trust_list_set_ptr(gnutls_x509_trust_list_t tlist, void *ptr); void *gnutls_x509_trust_list_get_ptr(gnutls_x509_trust_list_t tlist); void gnutls_certificate_set_trust_list (gnutls_certificate_credentials_t res, gnutls_x509_trust_list_t tlist, unsigned flags); void gnutls_certificate_get_trust_list (gnutls_certificate_credentials_t res, gnutls_x509_trust_list_t *tlist); typedef struct gnutls_x509_ext_st { char *oid; unsigned int critical; gnutls_datum_t data; } gnutls_x509_ext_st; void gnutls_x509_ext_deinit(gnutls_x509_ext_st *ext); int gnutls_x509_ext_print(gnutls_x509_ext_st *exts, unsigned int exts_size, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); #include /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_X509_H */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/HTMLparser.h ================================================ /* * Summary: interface for an HTML 4.0 non-verifying parser * Description: this module implements an HTML 4.0 non-verifying parser * with API compatible with the XML parser ones. It should * be able to parse "real world" HTML, even if severely * broken from a specification point of view. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __HTML_PARSER_H__ #define __HTML_PARSER_H__ #include #include #ifdef LIBXML_HTML_ENABLED #ifdef __cplusplus extern "C" { #endif /* * Most of the back-end structures from XML and HTML are shared. */ typedef xmlParserCtxt htmlParserCtxt; typedef xmlParserCtxtPtr htmlParserCtxtPtr; typedef xmlParserNodeInfo htmlParserNodeInfo; typedef xmlSAXHandler htmlSAXHandler; typedef xmlSAXHandlerPtr htmlSAXHandlerPtr; typedef xmlParserInput htmlParserInput; typedef xmlParserInputPtr htmlParserInputPtr; typedef xmlDocPtr htmlDocPtr; typedef xmlNodePtr htmlNodePtr; /* * Internal description of an HTML element, representing HTML 4.01 * and XHTML 1.0 (which share the same structure). */ typedef struct _htmlElemDesc htmlElemDesc; typedef htmlElemDesc *htmlElemDescPtr; struct _htmlElemDesc { const char *name; /* The tag name */ char startTag; /* Whether the start tag can be implied */ char endTag; /* Whether the end tag can be implied */ char saveEndTag; /* Whether the end tag should be saved */ char empty; /* Is this an empty element ? */ char depr; /* Is this a deprecated element ? */ char dtd; /* 1: only in Loose DTD, 2: only Frameset one */ char isinline; /* is this a block 0 or inline 1 element */ const char *desc; /* the description */ /* NRK Jan.2003 * New fields encapsulating HTML structure * * Bugs: * This is a very limited representation. It fails to tell us when * an element *requires* subelements (we only have whether they're * allowed or not), and it doesn't tell us where CDATA and PCDATA * are allowed. Some element relationships are not fully represented: * these are flagged with the word MODIFIER */ const char** subelts; /* allowed sub-elements of this element */ const char* defaultsubelt; /* subelement for suggested auto-repair if necessary or NULL */ const char** attrs_opt; /* Optional Attributes */ const char** attrs_depr; /* Additional deprecated attributes */ const char** attrs_req; /* Required attributes */ }; /* * Internal description of an HTML entity. */ typedef struct _htmlEntityDesc htmlEntityDesc; typedef htmlEntityDesc *htmlEntityDescPtr; struct _htmlEntityDesc { unsigned int value; /* the UNICODE value for the character */ const char *name; /* The entity name */ const char *desc; /* the description */ }; /* * There is only few public functions. */ XML_DEPRECATED XMLPUBFUN void htmlInitAutoClose (void); XMLPUBFUN const htmlElemDesc * htmlTagLookup (const xmlChar *tag); XMLPUBFUN const htmlEntityDesc * htmlEntityLookup(const xmlChar *name); XMLPUBFUN const htmlEntityDesc * htmlEntityValueLookup(unsigned int value); XMLPUBFUN int htmlIsAutoClosed(htmlDocPtr doc, htmlNodePtr elem); XMLPUBFUN int htmlAutoCloseTag(htmlDocPtr doc, const xmlChar *name, htmlNodePtr elem); XML_DEPRECATED XMLPUBFUN const htmlEntityDesc * htmlParseEntityRef(htmlParserCtxtPtr ctxt, const xmlChar **str); XML_DEPRECATED XMLPUBFUN int htmlParseCharRef(htmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void htmlParseElement(htmlParserCtxtPtr ctxt); XMLPUBFUN htmlParserCtxtPtr htmlNewParserCtxt(void); XMLPUBFUN htmlParserCtxtPtr htmlNewSAXParserCtxt(const htmlSAXHandler *sax, void *userData); XMLPUBFUN htmlParserCtxtPtr htmlCreateMemoryParserCtxt(const char *buffer, int size); XMLPUBFUN int htmlParseDocument(htmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN htmlDocPtr htmlSAXParseDoc (const xmlChar *cur, const char *encoding, htmlSAXHandlerPtr sax, void *userData); XMLPUBFUN htmlDocPtr htmlParseDoc (const xmlChar *cur, const char *encoding); XMLPUBFUN htmlParserCtxtPtr htmlCreateFileParserCtxt(const char *filename, const char *encoding); XML_DEPRECATED XMLPUBFUN htmlDocPtr htmlSAXParseFile(const char *filename, const char *encoding, htmlSAXHandlerPtr sax, void *userData); XMLPUBFUN htmlDocPtr htmlParseFile (const char *filename, const char *encoding); XMLPUBFUN int UTF8ToHtml (unsigned char *out, int *outlen, const unsigned char *in, int *inlen); XMLPUBFUN int htmlEncodeEntities(unsigned char *out, int *outlen, const unsigned char *in, int *inlen, int quoteChar); XMLPUBFUN int htmlIsScriptAttribute(const xmlChar *name); XMLPUBFUN int htmlHandleOmittedElem(int val); #ifdef LIBXML_PUSH_ENABLED /** * Interfaces for the Push mode. */ XMLPUBFUN htmlParserCtxtPtr htmlCreatePushParserCtxt(htmlSAXHandlerPtr sax, void *user_data, const char *chunk, int size, const char *filename, xmlCharEncoding enc); XMLPUBFUN int htmlParseChunk (htmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate); #endif /* LIBXML_PUSH_ENABLED */ XMLPUBFUN void htmlFreeParserCtxt (htmlParserCtxtPtr ctxt); /* * New set of simpler/more flexible APIs */ /** * xmlParserOption: * * This is the set of XML parser options that can be passed down * to the xmlReadDoc() and similar calls. */ typedef enum { HTML_PARSE_RECOVER = 1<<0, /* Relaxed parsing */ HTML_PARSE_NODEFDTD = 1<<2, /* do not default a doctype if not found */ HTML_PARSE_NOERROR = 1<<5, /* suppress error reports */ HTML_PARSE_NOWARNING= 1<<6, /* suppress warning reports */ HTML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */ HTML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */ HTML_PARSE_NONET = 1<<11,/* Forbid network access */ HTML_PARSE_NOIMPLIED= 1<<13,/* Do not add implied html/body... elements */ HTML_PARSE_COMPACT = 1<<16,/* compact small text nodes */ HTML_PARSE_IGNORE_ENC=1<<21 /* ignore internal document encoding hint */ } htmlParserOption; XMLPUBFUN void htmlCtxtReset (htmlParserCtxtPtr ctxt); XMLPUBFUN int htmlCtxtUseOptions (htmlParserCtxtPtr ctxt, int options); XMLPUBFUN htmlDocPtr htmlReadDoc (const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadFile (const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadMemory (const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadFd (int fd, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadDoc (xmlParserCtxtPtr ctxt, const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadFile (xmlParserCtxtPtr ctxt, const char *filename, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadMemory (xmlParserCtxtPtr ctxt, const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadFd (xmlParserCtxtPtr ctxt, int fd, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadIO (xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); /* NRK/Jan2003: further knowledge of HTML structure */ typedef enum { HTML_NA = 0 , /* something we don't check at all */ HTML_INVALID = 0x1 , HTML_DEPRECATED = 0x2 , HTML_VALID = 0x4 , HTML_REQUIRED = 0xc /* VALID bit set so ( & HTML_VALID ) is TRUE */ } htmlStatus ; /* Using htmlElemDesc rather than name here, to emphasise the fact that otherwise there's a lookup overhead */ XMLPUBFUN htmlStatus htmlAttrAllowed(const htmlElemDesc*, const xmlChar*, int) ; XMLPUBFUN int htmlElementAllowedHere(const htmlElemDesc*, const xmlChar*) ; XMLPUBFUN htmlStatus htmlElementStatusHere(const htmlElemDesc*, const htmlElemDesc*) ; XMLPUBFUN htmlStatus htmlNodeStatus(const htmlNodePtr, int) ; /** * htmlDefaultSubelement: * @elt: HTML element * * Returns the default subelement for this element */ #define htmlDefaultSubelement(elt) elt->defaultsubelt /** * htmlElementAllowedHereDesc: * @parent: HTML parent element * @elt: HTML element * * Checks whether an HTML element description may be a * direct child of the specified element. * * Returns 1 if allowed; 0 otherwise. */ #define htmlElementAllowedHereDesc(parent,elt) \ htmlElementAllowedHere((parent), (elt)->name) /** * htmlRequiredAttrs: * @elt: HTML element * * Returns the attributes required for the specified element. */ #define htmlRequiredAttrs(elt) (elt)->attrs_req #ifdef __cplusplus } #endif #endif /* LIBXML_HTML_ENABLED */ #endif /* __HTML_PARSER_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/HTMLtree.h ================================================ /* * Summary: specific APIs to process HTML tree, especially serialization * Description: this module implements a few function needed to process * tree in an HTML specific way. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __HTML_TREE_H__ #define __HTML_TREE_H__ #include #include #include #include #ifdef LIBXML_HTML_ENABLED #ifdef __cplusplus extern "C" { #endif /** * HTML_TEXT_NODE: * * Macro. A text node in a HTML document is really implemented * the same way as a text node in an XML document. */ #define HTML_TEXT_NODE XML_TEXT_NODE /** * HTML_ENTITY_REF_NODE: * * Macro. An entity reference in a HTML document is really implemented * the same way as an entity reference in an XML document. */ #define HTML_ENTITY_REF_NODE XML_ENTITY_REF_NODE /** * HTML_COMMENT_NODE: * * Macro. A comment in a HTML document is really implemented * the same way as a comment in an XML document. */ #define HTML_COMMENT_NODE XML_COMMENT_NODE /** * HTML_PRESERVE_NODE: * * Macro. A preserved node in a HTML document is really implemented * the same way as a CDATA section in an XML document. */ #define HTML_PRESERVE_NODE XML_CDATA_SECTION_NODE /** * HTML_PI_NODE: * * Macro. A processing instruction in a HTML document is really implemented * the same way as a processing instruction in an XML document. */ #define HTML_PI_NODE XML_PI_NODE XMLPUBFUN htmlDocPtr htmlNewDoc (const xmlChar *URI, const xmlChar *ExternalID); XMLPUBFUN htmlDocPtr htmlNewDocNoDtD (const xmlChar *URI, const xmlChar *ExternalID); XMLPUBFUN const xmlChar * htmlGetMetaEncoding (htmlDocPtr doc); XMLPUBFUN int htmlSetMetaEncoding (htmlDocPtr doc, const xmlChar *encoding); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void htmlDocDumpMemory (xmlDocPtr cur, xmlChar **mem, int *size); XMLPUBFUN void htmlDocDumpMemoryFormat (xmlDocPtr cur, xmlChar **mem, int *size, int format); XMLPUBFUN int htmlDocDump (FILE *f, xmlDocPtr cur); XMLPUBFUN int htmlSaveFile (const char *filename, xmlDocPtr cur); XMLPUBFUN int htmlNodeDump (xmlBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur); XMLPUBFUN void htmlNodeDumpFile (FILE *out, xmlDocPtr doc, xmlNodePtr cur); XMLPUBFUN int htmlNodeDumpFileFormat (FILE *out, xmlDocPtr doc, xmlNodePtr cur, const char *encoding, int format); XMLPUBFUN int htmlSaveFileEnc (const char *filename, xmlDocPtr cur, const char *encoding); XMLPUBFUN int htmlSaveFileFormat (const char *filename, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN void htmlNodeDumpFormatOutput(xmlOutputBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, const char *encoding, int format); XMLPUBFUN void htmlDocContentDumpOutput(xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding); XMLPUBFUN void htmlDocContentDumpFormatOutput(xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN void htmlNodeDumpOutput (xmlOutputBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, const char *encoding); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN int htmlIsBooleanAttr (const xmlChar *name); #ifdef __cplusplus } #endif #endif /* LIBXML_HTML_ENABLED */ #endif /* __HTML_TREE_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/SAX.h ================================================ /* * Summary: Old SAX version 1 handler, deprecated * Description: DEPRECATED set of SAX version 1 interfaces used to * build the DOM tree. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SAX_H__ #define __XML_SAX_H__ #include #include #include #include #ifdef LIBXML_LEGACY_ENABLED #ifdef __cplusplus extern "C" { #endif XML_DEPRECATED XMLPUBFUN const xmlChar * getPublicId (void *ctx); XML_DEPRECATED XMLPUBFUN const xmlChar * getSystemId (void *ctx); XML_DEPRECATED XMLPUBFUN void setDocumentLocator (void *ctx, xmlSAXLocatorPtr loc); XML_DEPRECATED XMLPUBFUN int getLineNumber (void *ctx); XML_DEPRECATED XMLPUBFUN int getColumnNumber (void *ctx); XML_DEPRECATED XMLPUBFUN int isStandalone (void *ctx); XML_DEPRECATED XMLPUBFUN int hasInternalSubset (void *ctx); XML_DEPRECATED XMLPUBFUN int hasExternalSubset (void *ctx); XML_DEPRECATED XMLPUBFUN void internalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XML_DEPRECATED XMLPUBFUN void externalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XML_DEPRECATED XMLPUBFUN xmlEntityPtr getEntity (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN xmlEntityPtr getParameterEntity (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN xmlParserInputPtr resolveEntity (void *ctx, const xmlChar *publicId, const xmlChar *systemId); XML_DEPRECATED XMLPUBFUN void entityDecl (void *ctx, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content); XML_DEPRECATED XMLPUBFUN void attributeDecl (void *ctx, const xmlChar *elem, const xmlChar *fullname, int type, int def, const xmlChar *defaultValue, xmlEnumerationPtr tree); XML_DEPRECATED XMLPUBFUN void elementDecl (void *ctx, const xmlChar *name, int type, xmlElementContentPtr content); XML_DEPRECATED XMLPUBFUN void notationDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId); XML_DEPRECATED XMLPUBFUN void unparsedEntityDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName); XML_DEPRECATED XMLPUBFUN void startDocument (void *ctx); XML_DEPRECATED XMLPUBFUN void endDocument (void *ctx); XML_DEPRECATED XMLPUBFUN void attribute (void *ctx, const xmlChar *fullname, const xmlChar *value); XML_DEPRECATED XMLPUBFUN void startElement (void *ctx, const xmlChar *fullname, const xmlChar **atts); XML_DEPRECATED XMLPUBFUN void endElement (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN void reference (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN void characters (void *ctx, const xmlChar *ch, int len); XML_DEPRECATED XMLPUBFUN void ignorableWhitespace (void *ctx, const xmlChar *ch, int len); XML_DEPRECATED XMLPUBFUN void processingInstruction (void *ctx, const xmlChar *target, const xmlChar *data); XML_DEPRECATED XMLPUBFUN void globalNamespace (void *ctx, const xmlChar *href, const xmlChar *prefix); XML_DEPRECATED XMLPUBFUN void setNamespace (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN xmlNsPtr getNamespace (void *ctx); XML_DEPRECATED XMLPUBFUN int checkNamespace (void *ctx, xmlChar *nameSpace); XML_DEPRECATED XMLPUBFUN void namespaceDecl (void *ctx, const xmlChar *href, const xmlChar *prefix); XML_DEPRECATED XMLPUBFUN void comment (void *ctx, const xmlChar *value); XML_DEPRECATED XMLPUBFUN void cdataBlock (void *ctx, const xmlChar *value, int len); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN void initxmlDefaultSAXHandler (xmlSAXHandlerV1 *hdlr, int warning); #ifdef LIBXML_HTML_ENABLED XML_DEPRECATED XMLPUBFUN void inithtmlDefaultSAXHandler (xmlSAXHandlerV1 *hdlr); #endif #endif /* LIBXML_SAX1_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_LEGACY_ENABLED */ #endif /* __XML_SAX_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/SAX2.h ================================================ /* * Summary: SAX2 parser interface used to build the DOM tree * Description: those are the default SAX2 interfaces used by * the library when building DOM tree. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SAX2_H__ #define __XML_SAX2_H__ #include #include #include #include #ifdef __cplusplus extern "C" { #endif XMLPUBFUN const xmlChar * xmlSAX2GetPublicId (void *ctx); XMLPUBFUN const xmlChar * xmlSAX2GetSystemId (void *ctx); XMLPUBFUN void xmlSAX2SetDocumentLocator (void *ctx, xmlSAXLocatorPtr loc); XMLPUBFUN int xmlSAX2GetLineNumber (void *ctx); XMLPUBFUN int xmlSAX2GetColumnNumber (void *ctx); XMLPUBFUN int xmlSAX2IsStandalone (void *ctx); XMLPUBFUN int xmlSAX2HasInternalSubset (void *ctx); XMLPUBFUN int xmlSAX2HasExternalSubset (void *ctx); XMLPUBFUN void xmlSAX2InternalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN void xmlSAX2ExternalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlEntityPtr xmlSAX2GetEntity (void *ctx, const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlSAX2GetParameterEntity (void *ctx, const xmlChar *name); XMLPUBFUN xmlParserInputPtr xmlSAX2ResolveEntity (void *ctx, const xmlChar *publicId, const xmlChar *systemId); XMLPUBFUN void xmlSAX2EntityDecl (void *ctx, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content); XMLPUBFUN void xmlSAX2AttributeDecl (void *ctx, const xmlChar *elem, const xmlChar *fullname, int type, int def, const xmlChar *defaultValue, xmlEnumerationPtr tree); XMLPUBFUN void xmlSAX2ElementDecl (void *ctx, const xmlChar *name, int type, xmlElementContentPtr content); XMLPUBFUN void xmlSAX2NotationDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId); XMLPUBFUN void xmlSAX2UnparsedEntityDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName); XMLPUBFUN void xmlSAX2StartDocument (void *ctx); XMLPUBFUN void xmlSAX2EndDocument (void *ctx); #if defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ defined(LIBXML_WRITER_ENABLED) || defined(LIBXML_LEGACY_ENABLED) XMLPUBFUN void xmlSAX2StartElement (void *ctx, const xmlChar *fullname, const xmlChar **atts); XMLPUBFUN void xmlSAX2EndElement (void *ctx, const xmlChar *name); #endif /* LIBXML_SAX1_ENABLED or LIBXML_HTML_ENABLED or LIBXML_LEGACY_ENABLED */ XMLPUBFUN void xmlSAX2StartElementNs (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes); XMLPUBFUN void xmlSAX2EndElementNs (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI); XMLPUBFUN void xmlSAX2Reference (void *ctx, const xmlChar *name); XMLPUBFUN void xmlSAX2Characters (void *ctx, const xmlChar *ch, int len); XMLPUBFUN void xmlSAX2IgnorableWhitespace (void *ctx, const xmlChar *ch, int len); XMLPUBFUN void xmlSAX2ProcessingInstruction (void *ctx, const xmlChar *target, const xmlChar *data); XMLPUBFUN void xmlSAX2Comment (void *ctx, const xmlChar *value); XMLPUBFUN void xmlSAX2CDataBlock (void *ctx, const xmlChar *value, int len); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN int xmlSAXDefaultVersion (int version); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN int xmlSAXVersion (xmlSAXHandler *hdlr, int version); XMLPUBFUN void xmlSAX2InitDefaultSAXHandler (xmlSAXHandler *hdlr, int warning); #ifdef LIBXML_HTML_ENABLED XMLPUBFUN void xmlSAX2InitHtmlDefaultSAXHandler(xmlSAXHandler *hdlr); XML_DEPRECATED XMLPUBFUN void htmlDefaultSAXHandlerInit (void); #endif XML_DEPRECATED XMLPUBFUN void xmlDefaultSAXHandlerInit (void); #ifdef __cplusplus } #endif #endif /* __XML_SAX2_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/c14n.h ================================================ /* * Summary: Provide Canonical XML and Exclusive XML Canonicalization * Description: the c14n modules provides a * * "Canonical XML" implementation * http://www.w3.org/TR/xml-c14n * * and an * * "Exclusive XML Canonicalization" implementation * http://www.w3.org/TR/xml-exc-c14n * Copy: See Copyright for the status of this software. * * Author: Aleksey Sanin */ #ifndef __XML_C14N_H__ #define __XML_C14N_H__ #include #ifdef LIBXML_C14N_ENABLED #ifdef LIBXML_OUTPUT_ENABLED #include #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * XML Canonicalization * http://www.w3.org/TR/xml-c14n * * Exclusive XML Canonicalization * http://www.w3.org/TR/xml-exc-c14n * * Canonical form of an XML document could be created if and only if * a) default attributes (if any) are added to all nodes * b) all character and parsed entity references are resolved * In order to achieve this in libxml2 the document MUST be loaded with * following global settings: * * xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS; * xmlSubstituteEntitiesDefault(1); * * or corresponding parser context setting: * xmlParserCtxtPtr ctxt; * * ... * ctxt->loadsubset = XML_DETECT_IDS | XML_COMPLETE_ATTRS; * ctxt->replaceEntities = 1; * ... */ /* * xmlC14NMode: * * Predefined values for C14N modes * */ typedef enum { XML_C14N_1_0 = 0, /* Original C14N 1.0 spec */ XML_C14N_EXCLUSIVE_1_0 = 1, /* Exclusive C14N 1.0 spec */ XML_C14N_1_1 = 2 /* C14N 1.1 spec */ } xmlC14NMode; XMLPUBFUN int xmlC14NDocSaveTo (xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf); XMLPUBFUN int xmlC14NDocDumpMemory (xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, xmlChar **doc_txt_ptr); XMLPUBFUN int xmlC14NDocSave (xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, const char* filename, int compression); /** * This is the core C14N function */ /** * xmlC14NIsVisibleCallback: * @user_data: user data * @node: the current node * @parent: the parent node * * Signature for a C14N callback on visible nodes * * Returns 1 if the node should be included */ typedef int (*xmlC14NIsVisibleCallback) (void* user_data, xmlNodePtr node, xmlNodePtr parent); XMLPUBFUN int xmlC14NExecute (xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback, void* user_data, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_C14N_ENABLED */ #endif /* __XML_C14N_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/catalog.h ================================================ /** * Summary: interfaces to the Catalog handling system * Description: the catalog module implements the support for * XML Catalogs and SGML catalogs * * SGML Open Technical Resolution TR9401:1997. * http://www.jclark.com/sp/catalog.htm * * XML Catalogs Working Draft 06 August 2001 * http://www.oasis-open.org/committees/entity/spec-2001-08-06.html * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_CATALOG_H__ #define __XML_CATALOG_H__ #include #include #include #include #ifdef LIBXML_CATALOG_ENABLED #ifdef __cplusplus extern "C" { #endif /** * XML_CATALOGS_NAMESPACE: * * The namespace for the XML Catalogs elements. */ #define XML_CATALOGS_NAMESPACE \ (const xmlChar *) "urn:oasis:names:tc:entity:xmlns:xml:catalog" /** * XML_CATALOG_PI: * * The specific XML Catalog Processing Instruction name. */ #define XML_CATALOG_PI \ (const xmlChar *) "oasis-xml-catalog" /* * The API is voluntarily limited to general cataloging. */ typedef enum { XML_CATA_PREFER_NONE = 0, XML_CATA_PREFER_PUBLIC = 1, XML_CATA_PREFER_SYSTEM } xmlCatalogPrefer; typedef enum { XML_CATA_ALLOW_NONE = 0, XML_CATA_ALLOW_GLOBAL = 1, XML_CATA_ALLOW_DOCUMENT = 2, XML_CATA_ALLOW_ALL = 3 } xmlCatalogAllow; typedef struct _xmlCatalog xmlCatalog; typedef xmlCatalog *xmlCatalogPtr; /* * Operations on a given catalog. */ XMLPUBFUN xmlCatalogPtr xmlNewCatalog (int sgml); XMLPUBFUN xmlCatalogPtr xmlLoadACatalog (const char *filename); XMLPUBFUN xmlCatalogPtr xmlLoadSGMLSuperCatalog (const char *filename); XMLPUBFUN int xmlConvertSGMLCatalog (xmlCatalogPtr catal); XMLPUBFUN int xmlACatalogAdd (xmlCatalogPtr catal, const xmlChar *type, const xmlChar *orig, const xmlChar *replace); XMLPUBFUN int xmlACatalogRemove (xmlCatalogPtr catal, const xmlChar *value); XMLPUBFUN xmlChar * xmlACatalogResolve (xmlCatalogPtr catal, const xmlChar *pubID, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlACatalogResolveSystem(xmlCatalogPtr catal, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlACatalogResolvePublic(xmlCatalogPtr catal, const xmlChar *pubID); XMLPUBFUN xmlChar * xmlACatalogResolveURI (xmlCatalogPtr catal, const xmlChar *URI); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlACatalogDump (xmlCatalogPtr catal, FILE *out); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN void xmlFreeCatalog (xmlCatalogPtr catal); XMLPUBFUN int xmlCatalogIsEmpty (xmlCatalogPtr catal); /* * Global operations. */ XMLPUBFUN void xmlInitializeCatalog (void); XMLPUBFUN int xmlLoadCatalog (const char *filename); XMLPUBFUN void xmlLoadCatalogs (const char *paths); XMLPUBFUN void xmlCatalogCleanup (void); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlCatalogDump (FILE *out); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN xmlChar * xmlCatalogResolve (const xmlChar *pubID, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlCatalogResolveSystem (const xmlChar *sysID); XMLPUBFUN xmlChar * xmlCatalogResolvePublic (const xmlChar *pubID); XMLPUBFUN xmlChar * xmlCatalogResolveURI (const xmlChar *URI); XMLPUBFUN int xmlCatalogAdd (const xmlChar *type, const xmlChar *orig, const xmlChar *replace); XMLPUBFUN int xmlCatalogRemove (const xmlChar *value); XMLPUBFUN xmlDocPtr xmlParseCatalogFile (const char *filename); XMLPUBFUN int xmlCatalogConvert (void); /* * Strictly minimal interfaces for per-document catalogs used * by the parser. */ XMLPUBFUN void xmlCatalogFreeLocal (void *catalogs); XMLPUBFUN void * xmlCatalogAddLocal (void *catalogs, const xmlChar *URL); XMLPUBFUN xmlChar * xmlCatalogLocalResolve (void *catalogs, const xmlChar *pubID, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlCatalogLocalResolveURI(void *catalogs, const xmlChar *URI); /* * Preference settings. */ XMLPUBFUN int xmlCatalogSetDebug (int level); XMLPUBFUN xmlCatalogPrefer xmlCatalogSetDefaultPrefer(xmlCatalogPrefer prefer); XMLPUBFUN void xmlCatalogSetDefaults (xmlCatalogAllow allow); XMLPUBFUN xmlCatalogAllow xmlCatalogGetDefaults (void); /* DEPRECATED interfaces */ XMLPUBFUN const xmlChar * xmlCatalogGetSystem (const xmlChar *sysID); XMLPUBFUN const xmlChar * xmlCatalogGetPublic (const xmlChar *pubID); #ifdef __cplusplus } #endif #endif /* LIBXML_CATALOG_ENABLED */ #endif /* __XML_CATALOG_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/chvalid.h ================================================ /* * Summary: Unicode character range checking * Description: this module exports interfaces for the character * range validation APIs * * This file is automatically generated from the cvs source * definition files using the genChRanges.py Python script * * Generation date: Mon Mar 27 11:09:48 2006 * Sources: chvalid.def * Author: William Brack */ #ifndef __XML_CHVALID_H__ #define __XML_CHVALID_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * Define our typedefs and structures * */ typedef struct _xmlChSRange xmlChSRange; typedef xmlChSRange *xmlChSRangePtr; struct _xmlChSRange { unsigned short low; unsigned short high; }; typedef struct _xmlChLRange xmlChLRange; typedef xmlChLRange *xmlChLRangePtr; struct _xmlChLRange { unsigned int low; unsigned int high; }; typedef struct _xmlChRangeGroup xmlChRangeGroup; typedef xmlChRangeGroup *xmlChRangeGroupPtr; struct _xmlChRangeGroup { int nbShortRange; int nbLongRange; const xmlChSRange *shortRange; /* points to an array of ranges */ const xmlChLRange *longRange; }; /** * Range checking routine */ XMLPUBFUN int xmlCharInRange(unsigned int val, const xmlChRangeGroup *group); /** * xmlIsBaseChar_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBaseChar_ch(c) (((0x41 <= (c)) && ((c) <= 0x5a)) || \ ((0x61 <= (c)) && ((c) <= 0x7a)) || \ ((0xc0 <= (c)) && ((c) <= 0xd6)) || \ ((0xd8 <= (c)) && ((c) <= 0xf6)) || \ (0xf8 <= (c))) /** * xmlIsBaseCharQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBaseCharQ(c) (((c) < 0x100) ? \ xmlIsBaseChar_ch((c)) : \ xmlCharInRange((c), &xmlIsBaseCharGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsBaseCharGroup; /** * xmlIsBlank_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBlank_ch(c) (((c) == 0x20) || \ ((0x9 <= (c)) && ((c) <= 0xa)) || \ ((c) == 0xd)) /** * xmlIsBlankQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBlankQ(c) (((c) < 0x100) ? \ xmlIsBlank_ch((c)) : 0) /** * xmlIsChar_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsChar_ch(c) (((0x9 <= (c)) && ((c) <= 0xa)) || \ ((c) == 0xd) || \ (0x20 <= (c))) /** * xmlIsCharQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsCharQ(c) (((c) < 0x100) ? \ xmlIsChar_ch((c)) :\ (((0x100 <= (c)) && ((c) <= 0xd7ff)) || \ ((0xe000 <= (c)) && ((c) <= 0xfffd)) || \ ((0x10000 <= (c)) && ((c) <= 0x10ffff)))) XMLPUBVAR const xmlChRangeGroup xmlIsCharGroup; /** * xmlIsCombiningQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsCombiningQ(c) (((c) < 0x100) ? \ 0 : \ xmlCharInRange((c), &xmlIsCombiningGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsCombiningGroup; /** * xmlIsDigit_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsDigit_ch(c) (((0x30 <= (c)) && ((c) <= 0x39))) /** * xmlIsDigitQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsDigitQ(c) (((c) < 0x100) ? \ xmlIsDigit_ch((c)) : \ xmlCharInRange((c), &xmlIsDigitGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsDigitGroup; /** * xmlIsExtender_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsExtender_ch(c) (((c) == 0xb7)) /** * xmlIsExtenderQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsExtenderQ(c) (((c) < 0x100) ? \ xmlIsExtender_ch((c)) : \ xmlCharInRange((c), &xmlIsExtenderGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsExtenderGroup; /** * xmlIsIdeographicQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsIdeographicQ(c) (((c) < 0x100) ? \ 0 :\ (((0x4e00 <= (c)) && ((c) <= 0x9fa5)) || \ ((c) == 0x3007) || \ ((0x3021 <= (c)) && ((c) <= 0x3029)))) XMLPUBVAR const xmlChRangeGroup xmlIsIdeographicGroup; XMLPUBVAR const unsigned char xmlIsPubidChar_tab[256]; /** * xmlIsPubidChar_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsPubidChar_ch(c) (xmlIsPubidChar_tab[(c)]) /** * xmlIsPubidCharQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsPubidCharQ(c) (((c) < 0x100) ? \ xmlIsPubidChar_ch((c)) : 0) XMLPUBFUN int xmlIsBaseChar(unsigned int ch); XMLPUBFUN int xmlIsBlank(unsigned int ch); XMLPUBFUN int xmlIsChar(unsigned int ch); XMLPUBFUN int xmlIsCombining(unsigned int ch); XMLPUBFUN int xmlIsDigit(unsigned int ch); XMLPUBFUN int xmlIsExtender(unsigned int ch); XMLPUBFUN int xmlIsIdeographic(unsigned int ch); XMLPUBFUN int xmlIsPubidChar(unsigned int ch); #ifdef __cplusplus } #endif #endif /* __XML_CHVALID_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/debugXML.h ================================================ /* * Summary: Tree debugging APIs * Description: Interfaces to a set of routines used for debugging the tree * produced by the XML parser. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __DEBUG_XML__ #define __DEBUG_XML__ #include #include #include #ifdef LIBXML_DEBUG_ENABLED #include #ifdef __cplusplus extern "C" { #endif /* * The standard Dump routines. */ XMLPUBFUN void xmlDebugDumpString (FILE *output, const xmlChar *str); XMLPUBFUN void xmlDebugDumpAttr (FILE *output, xmlAttrPtr attr, int depth); XMLPUBFUN void xmlDebugDumpAttrList (FILE *output, xmlAttrPtr attr, int depth); XMLPUBFUN void xmlDebugDumpOneNode (FILE *output, xmlNodePtr node, int depth); XMLPUBFUN void xmlDebugDumpNode (FILE *output, xmlNodePtr node, int depth); XMLPUBFUN void xmlDebugDumpNodeList (FILE *output, xmlNodePtr node, int depth); XMLPUBFUN void xmlDebugDumpDocumentHead(FILE *output, xmlDocPtr doc); XMLPUBFUN void xmlDebugDumpDocument (FILE *output, xmlDocPtr doc); XMLPUBFUN void xmlDebugDumpDTD (FILE *output, xmlDtdPtr dtd); XMLPUBFUN void xmlDebugDumpEntities (FILE *output, xmlDocPtr doc); /**************************************************************** * * * Checking routines * * * ****************************************************************/ XMLPUBFUN int xmlDebugCheckDocument (FILE * output, xmlDocPtr doc); /**************************************************************** * * * XML shell helpers * * * ****************************************************************/ XMLPUBFUN void xmlLsOneNode (FILE *output, xmlNodePtr node); XMLPUBFUN int xmlLsCountNode (xmlNodePtr node); XMLPUBFUN const char * xmlBoolToText (int boolval); /**************************************************************** * * * The XML shell related structures and functions * * * ****************************************************************/ #ifdef LIBXML_XPATH_ENABLED /** * xmlShellReadlineFunc: * @prompt: a string prompt * * This is a generic signature for the XML shell input function. * * Returns a string which will be freed by the Shell. */ typedef char * (* xmlShellReadlineFunc)(char *prompt); /** * xmlShellCtxt: * * A debugging shell context. * TODO: add the defined function tables. */ typedef struct _xmlShellCtxt xmlShellCtxt; typedef xmlShellCtxt *xmlShellCtxtPtr; struct _xmlShellCtxt { char *filename; xmlDocPtr doc; xmlNodePtr node; xmlXPathContextPtr pctxt; int loaded; FILE *output; xmlShellReadlineFunc input; }; /** * xmlShellCmd: * @ctxt: a shell context * @arg: a string argument * @node: a first node * @node2: a second node * * This is a generic signature for the XML shell functions. * * Returns an int, negative returns indicating errors. */ typedef int (* xmlShellCmd) (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN void xmlShellPrintXPathError (int errorType, const char *arg); XMLPUBFUN void xmlShellPrintXPathResult(xmlXPathObjectPtr list); XMLPUBFUN int xmlShellList (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellBase (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellDir (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellLoad (xmlShellCtxtPtr ctxt, char *filename, xmlNodePtr node, xmlNodePtr node2); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlShellPrintNode (xmlNodePtr node); XMLPUBFUN int xmlShellCat (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellWrite (xmlShellCtxtPtr ctxt, char *filename, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellSave (xmlShellCtxtPtr ctxt, char *filename, xmlNodePtr node, xmlNodePtr node2); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_VALID_ENABLED XMLPUBFUN int xmlShellValidate (xmlShellCtxtPtr ctxt, char *dtd, xmlNodePtr node, xmlNodePtr node2); #endif /* LIBXML_VALID_ENABLED */ XMLPUBFUN int xmlShellDu (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr tree, xmlNodePtr node2); XMLPUBFUN int xmlShellPwd (xmlShellCtxtPtr ctxt, char *buffer, xmlNodePtr node, xmlNodePtr node2); /* * The Shell interface. */ XMLPUBFUN void xmlShell (xmlDocPtr doc, char *filename, xmlShellReadlineFunc input, FILE *output); #endif /* LIBXML_XPATH_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_DEBUG_ENABLED */ #endif /* __DEBUG_XML__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/dict.h ================================================ /* * Summary: string dictionary * Description: dictionary of reusable strings, just used to avoid allocation * and freeing operations. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_DICT_H__ #define __XML_DICT_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * The dictionary. */ typedef struct _xmlDict xmlDict; typedef xmlDict *xmlDictPtr; /* * Initializer */ XML_DEPRECATED XMLPUBFUN int xmlInitializeDict(void); /* * Constructor and destructor. */ XMLPUBFUN xmlDictPtr xmlDictCreate (void); XMLPUBFUN size_t xmlDictSetLimit (xmlDictPtr dict, size_t limit); XMLPUBFUN size_t xmlDictGetUsage (xmlDictPtr dict); XMLPUBFUN xmlDictPtr xmlDictCreateSub(xmlDictPtr sub); XMLPUBFUN int xmlDictReference(xmlDictPtr dict); XMLPUBFUN void xmlDictFree (xmlDictPtr dict); /* * Lookup of entry in the dictionary. */ XMLPUBFUN const xmlChar * xmlDictLookup (xmlDictPtr dict, const xmlChar *name, int len); XMLPUBFUN const xmlChar * xmlDictExists (xmlDictPtr dict, const xmlChar *name, int len); XMLPUBFUN const xmlChar * xmlDictQLookup (xmlDictPtr dict, const xmlChar *prefix, const xmlChar *name); XMLPUBFUN int xmlDictOwns (xmlDictPtr dict, const xmlChar *str); XMLPUBFUN int xmlDictSize (xmlDictPtr dict); /* * Cleanup function */ XML_DEPRECATED XMLPUBFUN void xmlDictCleanup (void); #ifdef __cplusplus } #endif #endif /* ! __XML_DICT_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/encoding.h ================================================ /* * Summary: interface for the encoding conversion functions * Description: interface for the encoding conversion functions needed for * XML basic encoding and iconv() support. * * Related specs are * rfc2044 (UTF-8 and UTF-16) F. Yergeau Alis Technologies * [ISO-10646] UTF-8 and UTF-16 in Annexes * [ISO-8859-1] ISO Latin-1 characters codes. * [UNICODE] The Unicode Consortium, "The Unicode Standard -- * Worldwide Character Encoding -- Version 1.0", Addison- * Wesley, Volume 1, 1991, Volume 2, 1992. UTF-8 is * described in Unicode Technical Report #4. * [US-ASCII] Coded Character Set--7-bit American Standard Code for * Information Interchange, ANSI X3.4-1986. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_CHAR_ENCODING_H__ #define __XML_CHAR_ENCODING_H__ #include #ifdef LIBXML_ICONV_ENABLED #include #endif #ifdef __cplusplus extern "C" { #endif /* * xmlCharEncoding: * * Predefined values for some standard encodings. * Libxml does not do beforehand translation on UTF8 and ISOLatinX. * It also supports ASCII, ISO-8859-1, and UTF16 (LE and BE) by default. * * Anything else would have to be translated to UTF8 before being * given to the parser itself. The BOM for UTF16 and the encoding * declaration are looked at and a converter is looked for at that * point. If not found the parser stops here as asked by the XML REC. A * converter can be registered by the user using xmlRegisterCharEncodingHandler * but the current form doesn't allow stateful transcoding (a serious * problem agreed !). If iconv has been found it will be used * automatically and allow stateful transcoding, the simplest is then * to be sure to enable iconv and to provide iconv libs for the encoding * support needed. * * Note that the generic "UTF-16" is not a predefined value. Instead, only * the specific UTF-16LE and UTF-16BE are present. */ typedef enum { XML_CHAR_ENCODING_ERROR= -1, /* No char encoding detected */ XML_CHAR_ENCODING_NONE= 0, /* No char encoding detected */ XML_CHAR_ENCODING_UTF8= 1, /* UTF-8 */ XML_CHAR_ENCODING_UTF16LE= 2, /* UTF-16 little endian */ XML_CHAR_ENCODING_UTF16BE= 3, /* UTF-16 big endian */ XML_CHAR_ENCODING_UCS4LE= 4, /* UCS-4 little endian */ XML_CHAR_ENCODING_UCS4BE= 5, /* UCS-4 big endian */ XML_CHAR_ENCODING_EBCDIC= 6, /* EBCDIC uh! */ XML_CHAR_ENCODING_UCS4_2143=7, /* UCS-4 unusual ordering */ XML_CHAR_ENCODING_UCS4_3412=8, /* UCS-4 unusual ordering */ XML_CHAR_ENCODING_UCS2= 9, /* UCS-2 */ XML_CHAR_ENCODING_8859_1= 10,/* ISO-8859-1 ISO Latin 1 */ XML_CHAR_ENCODING_8859_2= 11,/* ISO-8859-2 ISO Latin 2 */ XML_CHAR_ENCODING_8859_3= 12,/* ISO-8859-3 */ XML_CHAR_ENCODING_8859_4= 13,/* ISO-8859-4 */ XML_CHAR_ENCODING_8859_5= 14,/* ISO-8859-5 */ XML_CHAR_ENCODING_8859_6= 15,/* ISO-8859-6 */ XML_CHAR_ENCODING_8859_7= 16,/* ISO-8859-7 */ XML_CHAR_ENCODING_8859_8= 17,/* ISO-8859-8 */ XML_CHAR_ENCODING_8859_9= 18,/* ISO-8859-9 */ XML_CHAR_ENCODING_2022_JP= 19,/* ISO-2022-JP */ XML_CHAR_ENCODING_SHIFT_JIS=20,/* Shift_JIS */ XML_CHAR_ENCODING_EUC_JP= 21,/* EUC-JP */ XML_CHAR_ENCODING_ASCII= 22 /* pure ASCII */ } xmlCharEncoding; /** * xmlCharEncodingInputFunc: * @out: a pointer to an array of bytes to store the UTF-8 result * @outlen: the length of @out * @in: a pointer to an array of chars in the original encoding * @inlen: the length of @in * * Take a block of chars in the original encoding and try to convert * it to an UTF-8 block of chars out. * * Returns the number of bytes written, -1 if lack of space, or -2 * if the transcoding failed. * The value of @inlen after return is the number of octets consumed * if the return value is positive, else unpredictiable. * The value of @outlen after return is the number of octets consumed. */ typedef int (* xmlCharEncodingInputFunc)(unsigned char *out, int *outlen, const unsigned char *in, int *inlen); /** * xmlCharEncodingOutputFunc: * @out: a pointer to an array of bytes to store the result * @outlen: the length of @out * @in: a pointer to an array of UTF-8 chars * @inlen: the length of @in * * Take a block of UTF-8 chars in and try to convert it to another * encoding. * Note: a first call designed to produce heading info is called with * in = NULL. If stateful this should also initialize the encoder state. * * Returns the number of bytes written, -1 if lack of space, or -2 * if the transcoding failed. * The value of @inlen after return is the number of octets consumed * if the return value is positive, else unpredictiable. * The value of @outlen after return is the number of octets produced. */ typedef int (* xmlCharEncodingOutputFunc)(unsigned char *out, int *outlen, const unsigned char *in, int *inlen); /* * Block defining the handlers for non UTF-8 encodings. * If iconv is supported, there are two extra fields. */ typedef struct _xmlCharEncodingHandler xmlCharEncodingHandler; typedef xmlCharEncodingHandler *xmlCharEncodingHandlerPtr; struct _xmlCharEncodingHandler { char *name; xmlCharEncodingInputFunc input; xmlCharEncodingOutputFunc output; #ifdef LIBXML_ICONV_ENABLED iconv_t iconv_in; iconv_t iconv_out; #endif /* LIBXML_ICONV_ENABLED */ #ifdef LIBXML_ICU_ENABLED struct _uconv_t *uconv_in; struct _uconv_t *uconv_out; #endif /* LIBXML_ICU_ENABLED */ }; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif /* * Interfaces for encoding handlers. */ XML_DEPRECATED XMLPUBFUN void xmlInitCharEncodingHandlers (void); XML_DEPRECATED XMLPUBFUN void xmlCleanupCharEncodingHandlers (void); XMLPUBFUN void xmlRegisterCharEncodingHandler (xmlCharEncodingHandlerPtr handler); XMLPUBFUN xmlCharEncodingHandlerPtr xmlGetCharEncodingHandler (xmlCharEncoding enc); XMLPUBFUN xmlCharEncodingHandlerPtr xmlFindCharEncodingHandler (const char *name); XMLPUBFUN xmlCharEncodingHandlerPtr xmlNewCharEncodingHandler (const char *name, xmlCharEncodingInputFunc input, xmlCharEncodingOutputFunc output); /* * Interfaces for encoding names and aliases. */ XMLPUBFUN int xmlAddEncodingAlias (const char *name, const char *alias); XMLPUBFUN int xmlDelEncodingAlias (const char *alias); XMLPUBFUN const char * xmlGetEncodingAlias (const char *alias); XMLPUBFUN void xmlCleanupEncodingAliases (void); XMLPUBFUN xmlCharEncoding xmlParseCharEncoding (const char *name); XMLPUBFUN const char * xmlGetCharEncodingName (xmlCharEncoding enc); /* * Interfaces directly used by the parsers. */ XMLPUBFUN xmlCharEncoding xmlDetectCharEncoding (const unsigned char *in, int len); XMLPUBFUN int xmlCharEncOutFunc (xmlCharEncodingHandler *handler, xmlBufferPtr out, xmlBufferPtr in); XMLPUBFUN int xmlCharEncInFunc (xmlCharEncodingHandler *handler, xmlBufferPtr out, xmlBufferPtr in); XML_DEPRECATED XMLPUBFUN int xmlCharEncFirstLine (xmlCharEncodingHandler *handler, xmlBufferPtr out, xmlBufferPtr in); XMLPUBFUN int xmlCharEncCloseFunc (xmlCharEncodingHandler *handler); /* * Export a few useful functions */ #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN int UTF8Toisolat1 (unsigned char *out, int *outlen, const unsigned char *in, int *inlen); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN int isolat1ToUTF8 (unsigned char *out, int *outlen, const unsigned char *in, int *inlen); #ifdef __cplusplus } #endif #endif /* __XML_CHAR_ENCODING_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/entities.h ================================================ /* * Summary: interface for the XML entities handling * Description: this module provides some of the entity API needed * for the parser and applications. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_ENTITIES_H__ #define __XML_ENTITIES_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * The different valid entity types. */ typedef enum { XML_INTERNAL_GENERAL_ENTITY = 1, XML_EXTERNAL_GENERAL_PARSED_ENTITY = 2, XML_EXTERNAL_GENERAL_UNPARSED_ENTITY = 3, XML_INTERNAL_PARAMETER_ENTITY = 4, XML_EXTERNAL_PARAMETER_ENTITY = 5, XML_INTERNAL_PREDEFINED_ENTITY = 6 } xmlEntityType; /* * An unit of storage for an entity, contains the string, the value * and the linkind data needed for the linking in the hash table. */ struct _xmlEntity { void *_private; /* application data */ xmlElementType type; /* XML_ENTITY_DECL, must be second ! */ const xmlChar *name; /* Entity name */ struct _xmlNode *children; /* First child link */ struct _xmlNode *last; /* Last child link */ struct _xmlDtd *parent; /* -> DTD */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ xmlChar *orig; /* content without ref substitution */ xmlChar *content; /* content or ndata if unparsed */ int length; /* the content length */ xmlEntityType etype; /* The entity type */ const xmlChar *ExternalID; /* External identifier for PUBLIC */ const xmlChar *SystemID; /* URI for a SYSTEM or PUBLIC Entity */ struct _xmlEntity *nexte; /* unused */ const xmlChar *URI; /* the full URI as computed */ int owner; /* does the entity own the childrens */ int flags; /* various flags */ unsigned long expandedSize; /* expanded size */ }; /* * All entities are stored in an hash table. * There is 2 separate hash tables for global and parameter entities. */ typedef struct _xmlHashTable xmlEntitiesTable; typedef xmlEntitiesTable *xmlEntitiesTablePtr; /* * External functions: */ #ifdef LIBXML_LEGACY_ENABLED XML_DEPRECATED XMLPUBFUN void xmlInitializePredefinedEntities (void); #endif /* LIBXML_LEGACY_ENABLED */ XMLPUBFUN xmlEntityPtr xmlNewEntity (xmlDocPtr doc, const xmlChar *name, int type, const xmlChar *ExternalID, const xmlChar *SystemID, const xmlChar *content); XMLPUBFUN xmlEntityPtr xmlAddDocEntity (xmlDocPtr doc, const xmlChar *name, int type, const xmlChar *ExternalID, const xmlChar *SystemID, const xmlChar *content); XMLPUBFUN xmlEntityPtr xmlAddDtdEntity (xmlDocPtr doc, const xmlChar *name, int type, const xmlChar *ExternalID, const xmlChar *SystemID, const xmlChar *content); XMLPUBFUN xmlEntityPtr xmlGetPredefinedEntity (const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlGetDocEntity (const xmlDoc *doc, const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlGetDtdEntity (xmlDocPtr doc, const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlGetParameterEntity (xmlDocPtr doc, const xmlChar *name); #ifdef LIBXML_LEGACY_ENABLED XML_DEPRECATED XMLPUBFUN const xmlChar * xmlEncodeEntities (xmlDocPtr doc, const xmlChar *input); #endif /* LIBXML_LEGACY_ENABLED */ XMLPUBFUN xmlChar * xmlEncodeEntitiesReentrant(xmlDocPtr doc, const xmlChar *input); XMLPUBFUN xmlChar * xmlEncodeSpecialChars (const xmlDoc *doc, const xmlChar *input); XMLPUBFUN xmlEntitiesTablePtr xmlCreateEntitiesTable (void); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlEntitiesTablePtr xmlCopyEntitiesTable (xmlEntitiesTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeEntitiesTable (xmlEntitiesTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpEntitiesTable (xmlBufferPtr buf, xmlEntitiesTablePtr table); XMLPUBFUN void xmlDumpEntityDecl (xmlBufferPtr buf, xmlEntityPtr ent); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_LEGACY_ENABLED XMLPUBFUN void xmlCleanupPredefinedEntities(void); #endif /* LIBXML_LEGACY_ENABLED */ #ifdef __cplusplus } #endif # endif /* __XML_ENTITIES_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/globals.h ================================================ /* * Summary: interface for all global variables of the library * Description: all the global variables and thread handling for * those variables is handled by this module. * * The bottom of this file is automatically generated by build_glob.py * based on the description file global.data * * Copy: See Copyright for the status of this software. * * Author: Gary Pennington , Daniel Veillard */ #ifndef __XML_GLOBALS_H #define __XML_GLOBALS_H #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif XML_DEPRECATED XMLPUBFUN void xmlInitGlobals(void); XML_DEPRECATED XMLPUBFUN void xmlCleanupGlobals(void); /** * xmlParserInputBufferCreateFilenameFunc: * @URI: the URI to read from * @enc: the requested source encoding * * Signature for the function doing the lookup for a suitable input method * corresponding to an URI. * * Returns the new xmlParserInputBufferPtr in case of success or NULL if no * method was found. */ typedef xmlParserInputBufferPtr (*xmlParserInputBufferCreateFilenameFunc) (const char *URI, xmlCharEncoding enc); /** * xmlOutputBufferCreateFilenameFunc: * @URI: the URI to write to * @enc: the requested target encoding * * Signature for the function doing the lookup for a suitable output method * corresponding to an URI. * * Returns the new xmlOutputBufferPtr in case of success or NULL if no * method was found. */ typedef xmlOutputBufferPtr (*xmlOutputBufferCreateFilenameFunc) (const char *URI, xmlCharEncodingHandlerPtr encoder, int compression); XMLPUBFUN xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameDefault (xmlParserInputBufferCreateFilenameFunc func); XMLPUBFUN xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameDefault (xmlOutputBufferCreateFilenameFunc func); /* * Externally global symbols which need to be protected for backwards * compatibility support. */ #undef htmlDefaultSAXHandler #undef oldXMLWDcompatibility #undef xmlBufferAllocScheme #undef xmlDefaultBufferSize #undef xmlDefaultSAXHandler #undef xmlDefaultSAXLocator #undef xmlDoValidityCheckingDefaultValue #undef xmlFree #undef xmlGenericError #undef xmlStructuredError #undef xmlGenericErrorContext #undef xmlStructuredErrorContext #undef xmlGetWarningsDefaultValue #undef xmlIndentTreeOutput #undef xmlTreeIndentString #undef xmlKeepBlanksDefaultValue #undef xmlLineNumbersDefaultValue #undef xmlLoadExtDtdDefaultValue #undef xmlMalloc #undef xmlMallocAtomic #undef xmlMemStrdup #undef xmlParserDebugEntities #undef xmlParserVersion #undef xmlPedanticParserDefaultValue #undef xmlRealloc #undef xmlSaveNoEmptyTags #undef xmlSubstituteEntitiesDefaultValue #undef xmlRegisterNodeDefaultValue #undef xmlDeregisterNodeDefaultValue #undef xmlLastError #undef xmlParserInputBufferCreateFilenameValue #undef xmlOutputBufferCreateFilenameValue /** * xmlRegisterNodeFunc: * @node: the current node * * Signature for the registration callback of a created node */ typedef void (*xmlRegisterNodeFunc) (xmlNodePtr node); /** * xmlDeregisterNodeFunc: * @node: the current node * * Signature for the deregistration callback of a discarded node */ typedef void (*xmlDeregisterNodeFunc) (xmlNodePtr node); typedef struct _xmlGlobalState xmlGlobalState; typedef xmlGlobalState *xmlGlobalStatePtr; struct _xmlGlobalState { const char *xmlParserVersion; xmlSAXLocator xmlDefaultSAXLocator; xmlSAXHandlerV1 xmlDefaultSAXHandler; xmlSAXHandlerV1 docbDefaultSAXHandler; /* unused */ xmlSAXHandlerV1 htmlDefaultSAXHandler; xmlFreeFunc xmlFree; xmlMallocFunc xmlMalloc; xmlStrdupFunc xmlMemStrdup; xmlReallocFunc xmlRealloc; xmlGenericErrorFunc xmlGenericError; xmlStructuredErrorFunc xmlStructuredError; void *xmlGenericErrorContext; int oldXMLWDcompatibility; xmlBufferAllocationScheme xmlBufferAllocScheme; int xmlDefaultBufferSize; int xmlSubstituteEntitiesDefaultValue; int xmlDoValidityCheckingDefaultValue; int xmlGetWarningsDefaultValue; int xmlKeepBlanksDefaultValue; int xmlLineNumbersDefaultValue; int xmlLoadExtDtdDefaultValue; int xmlParserDebugEntities; int xmlPedanticParserDefaultValue; int xmlSaveNoEmptyTags; int xmlIndentTreeOutput; const char *xmlTreeIndentString; xmlRegisterNodeFunc xmlRegisterNodeDefaultValue; xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue; xmlMallocFunc xmlMallocAtomic; xmlError xmlLastError; xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValue; xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue; void *xmlStructuredErrorContext; }; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif XMLPUBFUN void xmlInitializeGlobalState(xmlGlobalStatePtr gs); XMLPUBFUN void xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler); XMLPUBFUN void xmlThrDefSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler); XMLPUBFUN xmlRegisterNodeFunc xmlRegisterNodeDefault(xmlRegisterNodeFunc func); XMLPUBFUN xmlRegisterNodeFunc xmlThrDefRegisterNodeDefault(xmlRegisterNodeFunc func); XMLPUBFUN xmlDeregisterNodeFunc xmlDeregisterNodeDefault(xmlDeregisterNodeFunc func); XMLPUBFUN xmlDeregisterNodeFunc xmlThrDefDeregisterNodeDefault(xmlDeregisterNodeFunc func); XMLPUBFUN xmlOutputBufferCreateFilenameFunc xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func); XMLPUBFUN xmlParserInputBufferCreateFilenameFunc xmlThrDefParserInputBufferCreateFilenameDefault( xmlParserInputBufferCreateFilenameFunc func); /* * In general the memory allocation entry points are not kept * thread specific but this can be overridden by LIBXML_THREAD_ALLOC_ENABLED * - xmlMalloc * - xmlMallocAtomic * - xmlRealloc * - xmlMemStrdup * - xmlFree */ #ifdef LIBXML_THREAD_ALLOC_ENABLED /** DOC_DISABLE */ #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlMallocFunc * __xmlMalloc(void); #define xmlMalloc \ (*(__xmlMalloc())) #else XMLPUBVAR xmlMallocFunc xmlMalloc; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlMallocFunc * __xmlMallocAtomic(void); #define xmlMallocAtomic \ (*(__xmlMallocAtomic())) #else XMLPUBVAR xmlMallocFunc xmlMallocAtomic; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlReallocFunc * __xmlRealloc(void); #define xmlRealloc \ (*(__xmlRealloc())) #else XMLPUBVAR xmlReallocFunc xmlRealloc; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlFreeFunc * __xmlFree(void); #define xmlFree \ (*(__xmlFree())) #else XMLPUBVAR xmlFreeFunc xmlFree; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlStrdupFunc * __xmlMemStrdup(void); #define xmlMemStrdup \ (*(__xmlMemStrdup())) #else XMLPUBVAR xmlStrdupFunc xmlMemStrdup; #endif /** DOC_ENABLE */ #else /* !LIBXML_THREAD_ALLOC_ENABLED */ XMLPUBVAR xmlMallocFunc xmlMalloc; XMLPUBVAR xmlMallocFunc xmlMallocAtomic; XMLPUBVAR xmlReallocFunc xmlRealloc; XMLPUBVAR xmlFreeFunc xmlFree; XMLPUBVAR xmlStrdupFunc xmlMemStrdup; #endif /* LIBXML_THREAD_ALLOC_ENABLED */ #ifdef LIBXML_HTML_ENABLED XML_DEPRECATED XMLPUBFUN xmlSAXHandlerV1 * __htmlDefaultSAXHandler(void); #ifdef LIBXML_THREAD_ENABLED #define htmlDefaultSAXHandler \ (*(__htmlDefaultSAXHandler())) #else XML_DEPRECATED XMLPUBVAR xmlSAXHandlerV1 htmlDefaultSAXHandler; #endif #endif XMLPUBFUN xmlError * __xmlLastError(void); #ifdef LIBXML_THREAD_ENABLED #define xmlLastError \ (*(__xmlLastError())) #else XMLPUBVAR xmlError xmlLastError; #endif /* * Everything starting from the line below is * Automatically generated by build_glob.py. * Do not modify the previous line. */ XML_DEPRECATED XMLPUBFUN int * __oldXMLWDcompatibility(void); #ifdef LIBXML_THREAD_ENABLED #define oldXMLWDcompatibility \ (*(__oldXMLWDcompatibility())) #else XML_DEPRECATED XMLPUBVAR int oldXMLWDcompatibility; #endif XML_DEPRECATED XMLPUBFUN xmlBufferAllocationScheme * __xmlBufferAllocScheme(void); #ifdef LIBXML_THREAD_ENABLED #define xmlBufferAllocScheme \ (*(__xmlBufferAllocScheme())) #else XML_DEPRECATED XMLPUBVAR xmlBufferAllocationScheme xmlBufferAllocScheme; #endif XML_DEPRECATED XMLPUBFUN xmlBufferAllocationScheme xmlThrDefBufferAllocScheme(xmlBufferAllocationScheme v); XML_DEPRECATED XMLPUBFUN int * __xmlDefaultBufferSize(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDefaultBufferSize \ (*(__xmlDefaultBufferSize())) #else XML_DEPRECATED XMLPUBVAR int xmlDefaultBufferSize; #endif XML_DEPRECATED XMLPUBFUN int xmlThrDefDefaultBufferSize(int v); XML_DEPRECATED XMLPUBFUN xmlSAXHandlerV1 * __xmlDefaultSAXHandler(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDefaultSAXHandler \ (*(__xmlDefaultSAXHandler())) #else XML_DEPRECATED XMLPUBVAR xmlSAXHandlerV1 xmlDefaultSAXHandler; #endif XML_DEPRECATED XMLPUBFUN xmlSAXLocator * __xmlDefaultSAXLocator(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDefaultSAXLocator \ (*(__xmlDefaultSAXLocator())) #else XML_DEPRECATED XMLPUBVAR xmlSAXLocator xmlDefaultSAXLocator; #endif XMLPUBFUN int * __xmlDoValidityCheckingDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDoValidityCheckingDefaultValue \ (*(__xmlDoValidityCheckingDefaultValue())) #else XMLPUBVAR int xmlDoValidityCheckingDefaultValue; #endif XMLPUBFUN int xmlThrDefDoValidityCheckingDefaultValue(int v); XMLPUBFUN xmlGenericErrorFunc * __xmlGenericError(void); #ifdef LIBXML_THREAD_ENABLED #define xmlGenericError \ (*(__xmlGenericError())) #else XMLPUBVAR xmlGenericErrorFunc xmlGenericError; #endif XMLPUBFUN xmlStructuredErrorFunc * __xmlStructuredError(void); #ifdef LIBXML_THREAD_ENABLED #define xmlStructuredError \ (*(__xmlStructuredError())) #else XMLPUBVAR xmlStructuredErrorFunc xmlStructuredError; #endif XMLPUBFUN void * * __xmlGenericErrorContext(void); #ifdef LIBXML_THREAD_ENABLED #define xmlGenericErrorContext \ (*(__xmlGenericErrorContext())) #else XMLPUBVAR void * xmlGenericErrorContext; #endif XMLPUBFUN void * * __xmlStructuredErrorContext(void); #ifdef LIBXML_THREAD_ENABLED #define xmlStructuredErrorContext \ (*(__xmlStructuredErrorContext())) #else XMLPUBVAR void * xmlStructuredErrorContext; #endif XMLPUBFUN int * __xmlGetWarningsDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlGetWarningsDefaultValue \ (*(__xmlGetWarningsDefaultValue())) #else XMLPUBVAR int xmlGetWarningsDefaultValue; #endif XMLPUBFUN int xmlThrDefGetWarningsDefaultValue(int v); XMLPUBFUN int * __xmlIndentTreeOutput(void); #ifdef LIBXML_THREAD_ENABLED #define xmlIndentTreeOutput \ (*(__xmlIndentTreeOutput())) #else XMLPUBVAR int xmlIndentTreeOutput; #endif XMLPUBFUN int xmlThrDefIndentTreeOutput(int v); XMLPUBFUN const char * * __xmlTreeIndentString(void); #ifdef LIBXML_THREAD_ENABLED #define xmlTreeIndentString \ (*(__xmlTreeIndentString())) #else XMLPUBVAR const char * xmlTreeIndentString; #endif XMLPUBFUN const char * xmlThrDefTreeIndentString(const char * v); XMLPUBFUN int * __xmlKeepBlanksDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlKeepBlanksDefaultValue \ (*(__xmlKeepBlanksDefaultValue())) #else XMLPUBVAR int xmlKeepBlanksDefaultValue; #endif XMLPUBFUN int xmlThrDefKeepBlanksDefaultValue(int v); XML_DEPRECATED XMLPUBFUN int * __xmlLineNumbersDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlLineNumbersDefaultValue \ (*(__xmlLineNumbersDefaultValue())) #else XML_DEPRECATED XMLPUBVAR int xmlLineNumbersDefaultValue; #endif XML_DEPRECATED XMLPUBFUN int xmlThrDefLineNumbersDefaultValue(int v); XMLPUBFUN int * __xmlLoadExtDtdDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlLoadExtDtdDefaultValue \ (*(__xmlLoadExtDtdDefaultValue())) #else XMLPUBVAR int xmlLoadExtDtdDefaultValue; #endif XMLPUBFUN int xmlThrDefLoadExtDtdDefaultValue(int v); XMLPUBFUN int * __xmlParserDebugEntities(void); #ifdef LIBXML_THREAD_ENABLED #define xmlParserDebugEntities \ (*(__xmlParserDebugEntities())) #else XMLPUBVAR int xmlParserDebugEntities; #endif XMLPUBFUN int xmlThrDefParserDebugEntities(int v); XMLPUBFUN const char * * __xmlParserVersion(void); #ifdef LIBXML_THREAD_ENABLED #define xmlParserVersion \ (*(__xmlParserVersion())) #else XMLPUBVAR const char * xmlParserVersion; #endif XML_DEPRECATED XMLPUBFUN int * __xmlPedanticParserDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlPedanticParserDefaultValue \ (*(__xmlPedanticParserDefaultValue())) #else XML_DEPRECATED XMLPUBVAR int xmlPedanticParserDefaultValue; #endif XML_DEPRECATED XMLPUBFUN int xmlThrDefPedanticParserDefaultValue(int v); XMLPUBFUN int * __xmlSaveNoEmptyTags(void); #ifdef LIBXML_THREAD_ENABLED #define xmlSaveNoEmptyTags \ (*(__xmlSaveNoEmptyTags())) #else XMLPUBVAR int xmlSaveNoEmptyTags; #endif XMLPUBFUN int xmlThrDefSaveNoEmptyTags(int v); XMLPUBFUN int * __xmlSubstituteEntitiesDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlSubstituteEntitiesDefaultValue \ (*(__xmlSubstituteEntitiesDefaultValue())) #else XMLPUBVAR int xmlSubstituteEntitiesDefaultValue; #endif XMLPUBFUN int xmlThrDefSubstituteEntitiesDefaultValue(int v); XML_DEPRECATED XMLPUBFUN xmlRegisterNodeFunc * __xmlRegisterNodeDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlRegisterNodeDefaultValue \ (*(__xmlRegisterNodeDefaultValue())) #else XML_DEPRECATED XMLPUBVAR xmlRegisterNodeFunc xmlRegisterNodeDefaultValue; #endif XML_DEPRECATED XMLPUBFUN xmlDeregisterNodeFunc * __xmlDeregisterNodeDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDeregisterNodeDefaultValue \ (*(__xmlDeregisterNodeDefaultValue())) #else XML_DEPRECATED XMLPUBVAR xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue; #endif XML_DEPRECATED XMLPUBFUN xmlParserInputBufferCreateFilenameFunc * \ __xmlParserInputBufferCreateFilenameValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlParserInputBufferCreateFilenameValue \ (*(__xmlParserInputBufferCreateFilenameValue())) #else XML_DEPRECATED XMLPUBVAR xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValue; #endif XML_DEPRECATED XMLPUBFUN xmlOutputBufferCreateFilenameFunc * __xmlOutputBufferCreateFilenameValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlOutputBufferCreateFilenameValue \ (*(__xmlOutputBufferCreateFilenameValue())) #else XML_DEPRECATED XMLPUBVAR xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue; #endif #ifdef __cplusplus } #endif #endif /* __XML_GLOBALS_H */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/hash.h ================================================ /* * Summary: Chained hash tables * Description: This module implements the hash table support used in * various places in the library. * * Copy: See Copyright for the status of this software. * * Author: Bjorn Reese */ #ifndef __XML_HASH_H__ #define __XML_HASH_H__ #ifdef __cplusplus extern "C" { #endif /* * The hash table. */ typedef struct _xmlHashTable xmlHashTable; typedef xmlHashTable *xmlHashTablePtr; #ifdef __cplusplus } #endif #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Recent version of gcc produce a warning when a function pointer is assigned * to an object pointer, or vice versa. The following macro is a dirty hack * to allow suppression of the warning. If your architecture has function * pointers which are a different size than a void pointer, there may be some * serious trouble within the library. */ /** * XML_CAST_FPTR: * @fptr: pointer to a function * * Macro to do a casting from an object pointer to a * function pointer without encountering a warning from * gcc * * #define XML_CAST_FPTR(fptr) (*(void **)(&fptr)) * This macro violated ISO C aliasing rules (gcc4 on s390 broke) * so it is disabled now */ #define XML_CAST_FPTR(fptr) fptr /* * function types: */ /** * xmlHashDeallocator: * @payload: the data in the hash * @name: the name associated * * Callback to free data from a hash. */ typedef void (*xmlHashDeallocator)(void *payload, const xmlChar *name); /** * xmlHashCopier: * @payload: the data in the hash * @name: the name associated * * Callback to copy data from a hash. * * Returns a copy of the data or NULL in case of error. */ typedef void *(*xmlHashCopier)(void *payload, const xmlChar *name); /** * xmlHashScanner: * @payload: the data in the hash * @data: extra scanner data * @name: the name associated * * Callback when scanning data in a hash with the simple scanner. */ typedef void (*xmlHashScanner)(void *payload, void *data, const xmlChar *name); /** * xmlHashScannerFull: * @payload: the data in the hash * @data: extra scanner data * @name: the name associated * @name2: the second name associated * @name3: the third name associated * * Callback when scanning data in a hash with the full scanner. */ typedef void (*xmlHashScannerFull)(void *payload, void *data, const xmlChar *name, const xmlChar *name2, const xmlChar *name3); /* * Constructor and destructor. */ XMLPUBFUN xmlHashTablePtr xmlHashCreate (int size); XMLPUBFUN xmlHashTablePtr xmlHashCreateDict(int size, xmlDictPtr dict); XMLPUBFUN void xmlHashFree (xmlHashTablePtr table, xmlHashDeallocator f); XMLPUBFUN void xmlHashDefaultDeallocator(void *entry, const xmlChar *name); /* * Add a new entry to the hash table. */ XMLPUBFUN int xmlHashAddEntry (xmlHashTablePtr table, const xmlChar *name, void *userdata); XMLPUBFUN int xmlHashUpdateEntry(xmlHashTablePtr table, const xmlChar *name, void *userdata, xmlHashDeallocator f); XMLPUBFUN int xmlHashAddEntry2(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, void *userdata); XMLPUBFUN int xmlHashUpdateEntry2(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, void *userdata, xmlHashDeallocator f); XMLPUBFUN int xmlHashAddEntry3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, void *userdata); XMLPUBFUN int xmlHashUpdateEntry3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, void *userdata, xmlHashDeallocator f); /* * Remove an entry from the hash table. */ XMLPUBFUN int xmlHashRemoveEntry(xmlHashTablePtr table, const xmlChar *name, xmlHashDeallocator f); XMLPUBFUN int xmlHashRemoveEntry2(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, xmlHashDeallocator f); XMLPUBFUN int xmlHashRemoveEntry3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, xmlHashDeallocator f); /* * Retrieve the userdata. */ XMLPUBFUN void * xmlHashLookup (xmlHashTablePtr table, const xmlChar *name); XMLPUBFUN void * xmlHashLookup2 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2); XMLPUBFUN void * xmlHashLookup3 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3); XMLPUBFUN void * xmlHashQLookup (xmlHashTablePtr table, const xmlChar *name, const xmlChar *prefix); XMLPUBFUN void * xmlHashQLookup2 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *prefix, const xmlChar *name2, const xmlChar *prefix2); XMLPUBFUN void * xmlHashQLookup3 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *prefix, const xmlChar *name2, const xmlChar *prefix2, const xmlChar *name3, const xmlChar *prefix3); /* * Helpers. */ XMLPUBFUN xmlHashTablePtr xmlHashCopy (xmlHashTablePtr table, xmlHashCopier f); XMLPUBFUN int xmlHashSize (xmlHashTablePtr table); XMLPUBFUN void xmlHashScan (xmlHashTablePtr table, xmlHashScanner f, void *data); XMLPUBFUN void xmlHashScan3 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, xmlHashScanner f, void *data); XMLPUBFUN void xmlHashScanFull (xmlHashTablePtr table, xmlHashScannerFull f, void *data); XMLPUBFUN void xmlHashScanFull3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, xmlHashScannerFull f, void *data); #ifdef __cplusplus } #endif #endif /* ! __XML_HASH_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/list.h ================================================ /* * Summary: lists interfaces * Description: this module implement the list support used in * various place in the library. * * Copy: See Copyright for the status of this software. * * Author: Gary Pennington */ #ifndef __XML_LINK_INCLUDE__ #define __XML_LINK_INCLUDE__ #include #ifdef __cplusplus extern "C" { #endif typedef struct _xmlLink xmlLink; typedef xmlLink *xmlLinkPtr; typedef struct _xmlList xmlList; typedef xmlList *xmlListPtr; /** * xmlListDeallocator: * @lk: the data to deallocate * * Callback function used to free data from a list. */ typedef void (*xmlListDeallocator) (xmlLinkPtr lk); /** * xmlListDataCompare: * @data0: the first data * @data1: the second data * * Callback function used to compare 2 data. * * Returns 0 is equality, -1 or 1 otherwise depending on the ordering. */ typedef int (*xmlListDataCompare) (const void *data0, const void *data1); /** * xmlListWalker: * @data: the data found in the list * @user: extra user provided data to the walker * * Callback function used when walking a list with xmlListWalk(). * * Returns 0 to stop walking the list, 1 otherwise. */ typedef int (*xmlListWalker) (const void *data, void *user); /* Creation/Deletion */ XMLPUBFUN xmlListPtr xmlListCreate (xmlListDeallocator deallocator, xmlListDataCompare compare); XMLPUBFUN void xmlListDelete (xmlListPtr l); /* Basic Operators */ XMLPUBFUN void * xmlListSearch (xmlListPtr l, void *data); XMLPUBFUN void * xmlListReverseSearch (xmlListPtr l, void *data); XMLPUBFUN int xmlListInsert (xmlListPtr l, void *data) ; XMLPUBFUN int xmlListAppend (xmlListPtr l, void *data) ; XMLPUBFUN int xmlListRemoveFirst (xmlListPtr l, void *data); XMLPUBFUN int xmlListRemoveLast (xmlListPtr l, void *data); XMLPUBFUN int xmlListRemoveAll (xmlListPtr l, void *data); XMLPUBFUN void xmlListClear (xmlListPtr l); XMLPUBFUN int xmlListEmpty (xmlListPtr l); XMLPUBFUN xmlLinkPtr xmlListFront (xmlListPtr l); XMLPUBFUN xmlLinkPtr xmlListEnd (xmlListPtr l); XMLPUBFUN int xmlListSize (xmlListPtr l); XMLPUBFUN void xmlListPopFront (xmlListPtr l); XMLPUBFUN void xmlListPopBack (xmlListPtr l); XMLPUBFUN int xmlListPushFront (xmlListPtr l, void *data); XMLPUBFUN int xmlListPushBack (xmlListPtr l, void *data); /* Advanced Operators */ XMLPUBFUN void xmlListReverse (xmlListPtr l); XMLPUBFUN void xmlListSort (xmlListPtr l); XMLPUBFUN void xmlListWalk (xmlListPtr l, xmlListWalker walker, void *user); XMLPUBFUN void xmlListReverseWalk (xmlListPtr l, xmlListWalker walker, void *user); XMLPUBFUN void xmlListMerge (xmlListPtr l1, xmlListPtr l2); XMLPUBFUN xmlListPtr xmlListDup (const xmlListPtr old); XMLPUBFUN int xmlListCopy (xmlListPtr cur, const xmlListPtr old); /* Link operators */ XMLPUBFUN void * xmlLinkGetData (xmlLinkPtr lk); /* xmlListUnique() */ /* xmlListSwap */ #ifdef __cplusplus } #endif #endif /* __XML_LINK_INCLUDE__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/nanoftp.h ================================================ /* * Summary: minimal FTP implementation * Description: minimal FTP implementation allowing to fetch resources * like external subset. This module is DEPRECATED, do not * use any of its functions. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __NANO_FTP_H__ #define __NANO_FTP_H__ #include #ifdef LIBXML_FTP_ENABLED /* Needed for portability to Windows 64 bits */ #if defined(_WIN32) #include #else /** * SOCKET: * * macro used to provide portability of code to windows sockets */ #define SOCKET int /** * INVALID_SOCKET: * * macro used to provide portability of code to windows sockets * the value to be used when the socket is not valid */ #undef INVALID_SOCKET #define INVALID_SOCKET (-1) #endif #ifdef __cplusplus extern "C" { #endif /** * ftpListCallback: * @userData: user provided data for the callback * @filename: the file name (including "->" when links are shown) * @attrib: the attribute string * @owner: the owner string * @group: the group string * @size: the file size * @links: the link count * @year: the year * @month: the month * @day: the day * @hour: the hour * @minute: the minute * * A callback for the xmlNanoFTPList command. * Note that only one of year and day:minute are specified. */ typedef void (*ftpListCallback) (void *userData, const char *filename, const char *attrib, const char *owner, const char *group, unsigned long size, int links, int year, const char *month, int day, int hour, int minute); /** * ftpDataCallback: * @userData: the user provided context * @data: the data received * @len: its size in bytes * * A callback for the xmlNanoFTPGet command. */ typedef void (*ftpDataCallback) (void *userData, const char *data, int len); /* * Init */ XML_DEPRECATED XMLPUBFUN void xmlNanoFTPInit (void); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPCleanup (void); /* * Creating/freeing contexts. */ XML_DEPRECATED XMLPUBFUN void * xmlNanoFTPNewCtxt (const char *URL); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPFreeCtxt (void * ctx); XML_DEPRECATED XMLPUBFUN void * xmlNanoFTPConnectTo (const char *server, int port); /* * Opening/closing session connections. */ XML_DEPRECATED XMLPUBFUN void * xmlNanoFTPOpen (const char *URL); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPConnect (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPClose (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPQuit (void *ctx); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPScanProxy (const char *URL); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPProxy (const char *host, int port, const char *user, const char *passwd, int type); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPUpdateURL (void *ctx, const char *URL); /* * Rather internal commands. */ XML_DEPRECATED XMLPUBFUN int xmlNanoFTPGetResponse (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPCheckResponse (void *ctx); /* * CD/DIR/GET handlers. */ XML_DEPRECATED XMLPUBFUN int xmlNanoFTPCwd (void *ctx, const char *directory); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPDele (void *ctx, const char *file); XML_DEPRECATED XMLPUBFUN SOCKET xmlNanoFTPGetConnection (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPCloseConnection(void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPList (void *ctx, ftpListCallback callback, void *userData, const char *filename); XML_DEPRECATED XMLPUBFUN SOCKET xmlNanoFTPGetSocket (void *ctx, const char *filename); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPGet (void *ctx, ftpDataCallback callback, void *userData, const char *filename); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPRead (void *ctx, void *dest, int len); #ifdef __cplusplus } #endif #endif /* LIBXML_FTP_ENABLED */ #endif /* __NANO_FTP_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/nanohttp.h ================================================ /* * Summary: minimal HTTP implementation * Description: minimal HTTP implementation allowing to fetch resources * like external subset. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __NANO_HTTP_H__ #define __NANO_HTTP_H__ #include #ifdef LIBXML_HTTP_ENABLED #ifdef __cplusplus extern "C" { #endif XMLPUBFUN void xmlNanoHTTPInit (void); XMLPUBFUN void xmlNanoHTTPCleanup (void); XMLPUBFUN void xmlNanoHTTPScanProxy (const char *URL); XMLPUBFUN int xmlNanoHTTPFetch (const char *URL, const char *filename, char **contentType); XMLPUBFUN void * xmlNanoHTTPMethod (const char *URL, const char *method, const char *input, char **contentType, const char *headers, int ilen); XMLPUBFUN void * xmlNanoHTTPMethodRedir (const char *URL, const char *method, const char *input, char **contentType, char **redir, const char *headers, int ilen); XMLPUBFUN void * xmlNanoHTTPOpen (const char *URL, char **contentType); XMLPUBFUN void * xmlNanoHTTPOpenRedir (const char *URL, char **contentType, char **redir); XMLPUBFUN int xmlNanoHTTPReturnCode (void *ctx); XMLPUBFUN const char * xmlNanoHTTPAuthHeader (void *ctx); XMLPUBFUN const char * xmlNanoHTTPRedir (void *ctx); XMLPUBFUN int xmlNanoHTTPContentLength( void * ctx ); XMLPUBFUN const char * xmlNanoHTTPEncoding (void *ctx); XMLPUBFUN const char * xmlNanoHTTPMimeType (void *ctx); XMLPUBFUN int xmlNanoHTTPRead (void *ctx, void *dest, int len); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN int xmlNanoHTTPSave (void *ctxt, const char *filename); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN void xmlNanoHTTPClose (void *ctx); #ifdef __cplusplus } #endif #endif /* LIBXML_HTTP_ENABLED */ #endif /* __NANO_HTTP_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/parser.h ================================================ /* * Summary: the core parser module * Description: Interfaces, constants and types related to the XML parser * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_PARSER_H__ #define __XML_PARSER_H__ #include #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif /** * XML_DEFAULT_VERSION: * * The default version of XML used: 1.0 */ #define XML_DEFAULT_VERSION "1.0" /** * xmlParserInput: * * An xmlParserInput is an input flow for the XML processor. * Each entity parsed is associated an xmlParserInput (except the * few predefined ones). This is the case both for internal entities * - in which case the flow is already completely in memory - or * external entities - in which case we use the buf structure for * progressive reading and I18N conversions to the internal UTF-8 format. */ /** * xmlParserInputDeallocate: * @str: the string to deallocate * * Callback for freeing some parser input allocations. */ typedef void (* xmlParserInputDeallocate)(xmlChar *str); struct _xmlParserInput { /* Input buffer */ xmlParserInputBufferPtr buf; /* UTF-8 encoded buffer */ const char *filename; /* The file analyzed, if any */ const char *directory; /* the directory/base of the file */ const xmlChar *base; /* Base of the array to parse */ const xmlChar *cur; /* Current char being parsed */ const xmlChar *end; /* end of the array to parse */ int length; /* length if known */ int line; /* Current line */ int col; /* Current column */ unsigned long consumed; /* How many xmlChars already consumed */ xmlParserInputDeallocate free; /* function to deallocate the base */ const xmlChar *encoding; /* the encoding string for entity */ const xmlChar *version; /* the version string for entity */ int standalone; /* Was that entity marked standalone */ int id; /* an unique identifier for the entity */ unsigned long parentConsumed; /* consumed bytes from parents */ xmlEntityPtr entity; /* entity, if any */ }; /** * xmlParserNodeInfo: * * The parser can be asked to collect Node information, i.e. at what * place in the file they were detected. * NOTE: This is off by default and not very well tested. */ typedef struct _xmlParserNodeInfo xmlParserNodeInfo; typedef xmlParserNodeInfo *xmlParserNodeInfoPtr; struct _xmlParserNodeInfo { const struct _xmlNode* node; /* Position & line # that text that created the node begins & ends on */ unsigned long begin_pos; unsigned long begin_line; unsigned long end_pos; unsigned long end_line; }; typedef struct _xmlParserNodeInfoSeq xmlParserNodeInfoSeq; typedef xmlParserNodeInfoSeq *xmlParserNodeInfoSeqPtr; struct _xmlParserNodeInfoSeq { unsigned long maximum; unsigned long length; xmlParserNodeInfo* buffer; }; /** * xmlParserInputState: * * The parser is now working also as a state based parser. * The recursive one use the state info for entities processing. */ typedef enum { XML_PARSER_EOF = -1, /* nothing is to be parsed */ XML_PARSER_START = 0, /* nothing has been parsed */ XML_PARSER_MISC, /* Misc* before int subset */ XML_PARSER_PI, /* Within a processing instruction */ XML_PARSER_DTD, /* within some DTD content */ XML_PARSER_PROLOG, /* Misc* after internal subset */ XML_PARSER_COMMENT, /* within a comment */ XML_PARSER_START_TAG, /* within a start tag */ XML_PARSER_CONTENT, /* within the content */ XML_PARSER_CDATA_SECTION, /* within a CDATA section */ XML_PARSER_END_TAG, /* within a closing tag */ XML_PARSER_ENTITY_DECL, /* within an entity declaration */ XML_PARSER_ENTITY_VALUE, /* within an entity value in a decl */ XML_PARSER_ATTRIBUTE_VALUE, /* within an attribute value */ XML_PARSER_SYSTEM_LITERAL, /* within a SYSTEM value */ XML_PARSER_EPILOG, /* the Misc* after the last end tag */ XML_PARSER_IGNORE, /* within an IGNORED section */ XML_PARSER_PUBLIC_LITERAL /* within a PUBLIC value */ } xmlParserInputState; /** * XML_DETECT_IDS: * * Bit in the loadsubset context field to tell to do ID/REFs lookups. * Use it to initialize xmlLoadExtDtdDefaultValue. */ #define XML_DETECT_IDS 2 /** * XML_COMPLETE_ATTRS: * * Bit in the loadsubset context field to tell to do complete the * elements attributes lists with the ones defaulted from the DTDs. * Use it to initialize xmlLoadExtDtdDefaultValue. */ #define XML_COMPLETE_ATTRS 4 /** * XML_SKIP_IDS: * * Bit in the loadsubset context field to tell to not do ID/REFs registration. * Used to initialize xmlLoadExtDtdDefaultValue in some special cases. */ #define XML_SKIP_IDS 8 /** * xmlParserMode: * * A parser can operate in various modes */ typedef enum { XML_PARSE_UNKNOWN = 0, XML_PARSE_DOM = 1, XML_PARSE_SAX = 2, XML_PARSE_PUSH_DOM = 3, XML_PARSE_PUSH_SAX = 4, XML_PARSE_READER = 5 } xmlParserMode; typedef struct _xmlStartTag xmlStartTag; /** * xmlParserCtxt: * * The parser context. * NOTE This doesn't completely define the parser state, the (current ?) * design of the parser uses recursive function calls since this allow * and easy mapping from the production rules of the specification * to the actual code. The drawback is that the actual function call * also reflect the parser state. However most of the parsing routines * takes as the only argument the parser context pointer, so migrating * to a state based parser for progressive parsing shouldn't be too hard. */ struct _xmlParserCtxt { struct _xmlSAXHandler *sax; /* The SAX handler */ void *userData; /* For SAX interface only, used by DOM build */ xmlDocPtr myDoc; /* the document being built */ int wellFormed; /* is the document well formed */ int replaceEntities; /* shall we replace entities ? */ const xmlChar *version; /* the XML version string */ const xmlChar *encoding; /* the declared encoding, if any */ int standalone; /* standalone document */ int html; /* an HTML(1) document * 3 is HTML after * 10 is HTML after */ /* Input stream stack */ xmlParserInputPtr input; /* Current input stream */ int inputNr; /* Number of current input streams */ int inputMax; /* Max number of input streams */ xmlParserInputPtr *inputTab; /* stack of inputs */ /* Node analysis stack only used for DOM building */ xmlNodePtr node; /* Current parsed Node */ int nodeNr; /* Depth of the parsing stack */ int nodeMax; /* Max depth of the parsing stack */ xmlNodePtr *nodeTab; /* array of nodes */ int record_info; /* Whether node info should be kept */ xmlParserNodeInfoSeq node_seq; /* info about each node parsed */ int errNo; /* error code */ int hasExternalSubset; /* reference and external subset */ int hasPErefs; /* the internal subset has PE refs */ int external; /* are we parsing an external entity */ int valid; /* is the document valid */ int validate; /* shall we try to validate ? */ xmlValidCtxt vctxt; /* The validity context */ xmlParserInputState instate; /* current type of input */ int token; /* next char look-ahead */ char *directory; /* the data directory */ /* Node name stack */ const xmlChar *name; /* Current parsed Node */ int nameNr; /* Depth of the parsing stack */ int nameMax; /* Max depth of the parsing stack */ const xmlChar * *nameTab; /* array of nodes */ long nbChars; /* unused */ long checkIndex; /* used by progressive parsing lookup */ int keepBlanks; /* ugly but ... */ int disableSAX; /* SAX callbacks are disabled */ int inSubset; /* Parsing is in int 1/ext 2 subset */ const xmlChar * intSubName; /* name of subset */ xmlChar * extSubURI; /* URI of external subset */ xmlChar * extSubSystem; /* SYSTEM ID of external subset */ /* xml:space values */ int * space; /* Should the parser preserve spaces */ int spaceNr; /* Depth of the parsing stack */ int spaceMax; /* Max depth of the parsing stack */ int * spaceTab; /* array of space infos */ int depth; /* to prevent entity substitution loops */ xmlParserInputPtr entity; /* used to check entities boundaries */ int charset; /* encoding of the in-memory content actually an xmlCharEncoding */ int nodelen; /* Those two fields are there to */ int nodemem; /* Speed up large node parsing */ int pedantic; /* signal pedantic warnings */ void *_private; /* For user data, libxml won't touch it */ int loadsubset; /* should the external subset be loaded */ int linenumbers; /* set line number in element content */ void *catalogs; /* document's own catalog */ int recovery; /* run in recovery mode */ int progressive; /* is this a progressive parsing */ xmlDictPtr dict; /* dictionary for the parser */ const xmlChar * *atts; /* array for the attributes callbacks */ int maxatts; /* the size of the array */ int docdict; /* use strings from dict to build tree */ /* * pre-interned strings */ const xmlChar *str_xml; const xmlChar *str_xmlns; const xmlChar *str_xml_ns; /* * Everything below is used only by the new SAX mode */ int sax2; /* operating in the new SAX mode */ int nsNr; /* the number of inherited namespaces */ int nsMax; /* the size of the arrays */ const xmlChar * *nsTab; /* the array of prefix/namespace name */ int *attallocs; /* which attribute were allocated */ xmlStartTag *pushTab; /* array of data for push */ xmlHashTablePtr attsDefault; /* defaulted attributes if any */ xmlHashTablePtr attsSpecial; /* non-CDATA attributes if any */ int nsWellFormed; /* is the document XML Namespace okay */ int options; /* Extra options */ /* * Those fields are needed only for streaming parsing so far */ int dictNames; /* Use dictionary names for the tree */ int freeElemsNr; /* number of freed element nodes */ xmlNodePtr freeElems; /* List of freed element nodes */ int freeAttrsNr; /* number of freed attributes nodes */ xmlAttrPtr freeAttrs; /* List of freed attributes nodes */ /* * the complete error information for the last error. */ xmlError lastError; xmlParserMode parseMode; /* the parser mode */ unsigned long nbentities; /* unused */ unsigned long sizeentities; /* size of parsed entities */ /* for use by HTML non-recursive parser */ xmlParserNodeInfo *nodeInfo; /* Current NodeInfo */ int nodeInfoNr; /* Depth of the parsing stack */ int nodeInfoMax; /* Max depth of the parsing stack */ xmlParserNodeInfo *nodeInfoTab; /* array of nodeInfos */ int input_id; /* we need to label inputs */ unsigned long sizeentcopy; /* volume of entity copy */ int endCheckState; /* quote state for push parser */ unsigned short nbErrors; /* number of errors */ unsigned short nbWarnings; /* number of warnings */ }; /** * xmlSAXLocator: * * A SAX Locator. */ struct _xmlSAXLocator { const xmlChar *(*getPublicId)(void *ctx); const xmlChar *(*getSystemId)(void *ctx); int (*getLineNumber)(void *ctx); int (*getColumnNumber)(void *ctx); }; /** * xmlSAXHandler: * * A SAX handler is bunch of callbacks called by the parser when processing * of the input generate data or structure information. */ /** * resolveEntitySAXFunc: * @ctx: the user data (XML parser context) * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * Callback: * The entity loader, to control the loading of external entities, * the application can either: * - override this resolveEntity() callback in the SAX block * - or better use the xmlSetExternalEntityLoader() function to * set up it's own entity resolution routine * * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour. */ typedef xmlParserInputPtr (*resolveEntitySAXFunc) (void *ctx, const xmlChar *publicId, const xmlChar *systemId); /** * internalSubsetSAXFunc: * @ctx: the user data (XML parser context) * @name: the root element name * @ExternalID: the external ID * @SystemID: the SYSTEM ID (e.g. filename or URL) * * Callback on internal subset declaration. */ typedef void (*internalSubsetSAXFunc) (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); /** * externalSubsetSAXFunc: * @ctx: the user data (XML parser context) * @name: the root element name * @ExternalID: the external ID * @SystemID: the SYSTEM ID (e.g. filename or URL) * * Callback on external subset declaration. */ typedef void (*externalSubsetSAXFunc) (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); /** * getEntitySAXFunc: * @ctx: the user data (XML parser context) * @name: The entity name * * Get an entity by name. * * Returns the xmlEntityPtr if found. */ typedef xmlEntityPtr (*getEntitySAXFunc) (void *ctx, const xmlChar *name); /** * getParameterEntitySAXFunc: * @ctx: the user data (XML parser context) * @name: The entity name * * Get a parameter entity by name. * * Returns the xmlEntityPtr if found. */ typedef xmlEntityPtr (*getParameterEntitySAXFunc) (void *ctx, const xmlChar *name); /** * entityDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: the entity name * @type: the entity type * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @content: the entity value (without processing). * * An entity definition has been parsed. */ typedef void (*entityDeclSAXFunc) (void *ctx, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content); /** * notationDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: The name of the notation * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * What to do when a notation declaration has been parsed. */ typedef void (*notationDeclSAXFunc)(void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId); /** * attributeDeclSAXFunc: * @ctx: the user data (XML parser context) * @elem: the name of the element * @fullname: the attribute name * @type: the attribute type * @def: the type of default value * @defaultValue: the attribute default value * @tree: the tree of enumerated value set * * An attribute definition has been parsed. */ typedef void (*attributeDeclSAXFunc)(void *ctx, const xmlChar *elem, const xmlChar *fullname, int type, int def, const xmlChar *defaultValue, xmlEnumerationPtr tree); /** * elementDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: the element name * @type: the element type * @content: the element value tree * * An element definition has been parsed. */ typedef void (*elementDeclSAXFunc)(void *ctx, const xmlChar *name, int type, xmlElementContentPtr content); /** * unparsedEntityDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: The name of the entity * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @notationName: the name of the notation * * What to do when an unparsed entity declaration is parsed. */ typedef void (*unparsedEntityDeclSAXFunc)(void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName); /** * setDocumentLocatorSAXFunc: * @ctx: the user data (XML parser context) * @loc: A SAX Locator * * Receive the document locator at startup, actually xmlDefaultSAXLocator. * Everything is available on the context, so this is useless in our case. */ typedef void (*setDocumentLocatorSAXFunc) (void *ctx, xmlSAXLocatorPtr loc); /** * startDocumentSAXFunc: * @ctx: the user data (XML parser context) * * Called when the document start being processed. */ typedef void (*startDocumentSAXFunc) (void *ctx); /** * endDocumentSAXFunc: * @ctx: the user data (XML parser context) * * Called when the document end has been detected. */ typedef void (*endDocumentSAXFunc) (void *ctx); /** * startElementSAXFunc: * @ctx: the user data (XML parser context) * @name: The element name, including namespace prefix * @atts: An array of name/value attributes pairs, NULL terminated * * Called when an opening tag has been processed. */ typedef void (*startElementSAXFunc) (void *ctx, const xmlChar *name, const xmlChar **atts); /** * endElementSAXFunc: * @ctx: the user data (XML parser context) * @name: The element name * * Called when the end of an element has been detected. */ typedef void (*endElementSAXFunc) (void *ctx, const xmlChar *name); /** * attributeSAXFunc: * @ctx: the user data (XML parser context) * @name: The attribute name, including namespace prefix * @value: The attribute value * * Handle an attribute that has been read by the parser. * The default handling is to convert the attribute into an * DOM subtree and past it in a new xmlAttr element added to * the element. */ typedef void (*attributeSAXFunc) (void *ctx, const xmlChar *name, const xmlChar *value); /** * referenceSAXFunc: * @ctx: the user data (XML parser context) * @name: The entity name * * Called when an entity reference is detected. */ typedef void (*referenceSAXFunc) (void *ctx, const xmlChar *name); /** * charactersSAXFunc: * @ctx: the user data (XML parser context) * @ch: a xmlChar string * @len: the number of xmlChar * * Receiving some chars from the parser. */ typedef void (*charactersSAXFunc) (void *ctx, const xmlChar *ch, int len); /** * ignorableWhitespaceSAXFunc: * @ctx: the user data (XML parser context) * @ch: a xmlChar string * @len: the number of xmlChar * * Receiving some ignorable whitespaces from the parser. * UNUSED: by default the DOM building will use characters. */ typedef void (*ignorableWhitespaceSAXFunc) (void *ctx, const xmlChar *ch, int len); /** * processingInstructionSAXFunc: * @ctx: the user data (XML parser context) * @target: the target name * @data: the PI data's * * A processing instruction has been parsed. */ typedef void (*processingInstructionSAXFunc) (void *ctx, const xmlChar *target, const xmlChar *data); /** * commentSAXFunc: * @ctx: the user data (XML parser context) * @value: the comment content * * A comment has been parsed. */ typedef void (*commentSAXFunc) (void *ctx, const xmlChar *value); /** * cdataBlockSAXFunc: * @ctx: the user data (XML parser context) * @value: The pcdata content * @len: the block length * * Called when a pcdata block has been parsed. */ typedef void (*cdataBlockSAXFunc) ( void *ctx, const xmlChar *value, int len); /** * warningSAXFunc: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a warning messages, callback. */ typedef void (*warningSAXFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * errorSAXFunc: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format an error messages, callback. */ typedef void (*errorSAXFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * fatalErrorSAXFunc: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format fatal error messages, callback. * Note: so far fatalError() SAX callbacks are not used, error() * get all the callbacks for errors. */ typedef void (*fatalErrorSAXFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * isStandaloneSAXFunc: * @ctx: the user data (XML parser context) * * Is this document tagged standalone? * * Returns 1 if true */ typedef int (*isStandaloneSAXFunc) (void *ctx); /** * hasInternalSubsetSAXFunc: * @ctx: the user data (XML parser context) * * Does this document has an internal subset. * * Returns 1 if true */ typedef int (*hasInternalSubsetSAXFunc) (void *ctx); /** * hasExternalSubsetSAXFunc: * @ctx: the user data (XML parser context) * * Does this document has an external subset? * * Returns 1 if true */ typedef int (*hasExternalSubsetSAXFunc) (void *ctx); /************************************************************************ * * * The SAX version 2 API extensions * * * ************************************************************************/ /** * XML_SAX2_MAGIC: * * Special constant found in SAX2 blocks initialized fields */ #define XML_SAX2_MAGIC 0xDEEDBEAF /** * startElementNsSAX2Func: * @ctx: the user data (XML parser context) * @localname: the local name of the element * @prefix: the element namespace prefix if available * @URI: the element namespace name if available * @nb_namespaces: number of namespace definitions on that node * @namespaces: pointer to the array of prefix/URI pairs namespace definitions * @nb_attributes: the number of attributes on that node * @nb_defaulted: the number of defaulted attributes. The defaulted * ones are at the end of the array * @attributes: pointer to the array of (localname/prefix/URI/value/end) * attribute values. * * SAX2 callback when an element start has been detected by the parser. * It provides the namespace information for the element, as well as * the new namespace declarations on the element. */ typedef void (*startElementNsSAX2Func) (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes); /** * endElementNsSAX2Func: * @ctx: the user data (XML parser context) * @localname: the local name of the element * @prefix: the element namespace prefix if available * @URI: the element namespace name if available * * SAX2 callback when an element end has been detected by the parser. * It provides the namespace information for the element. */ typedef void (*endElementNsSAX2Func) (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI); struct _xmlSAXHandler { internalSubsetSAXFunc internalSubset; isStandaloneSAXFunc isStandalone; hasInternalSubsetSAXFunc hasInternalSubset; hasExternalSubsetSAXFunc hasExternalSubset; resolveEntitySAXFunc resolveEntity; getEntitySAXFunc getEntity; entityDeclSAXFunc entityDecl; notationDeclSAXFunc notationDecl; attributeDeclSAXFunc attributeDecl; elementDeclSAXFunc elementDecl; unparsedEntityDeclSAXFunc unparsedEntityDecl; setDocumentLocatorSAXFunc setDocumentLocator; startDocumentSAXFunc startDocument; endDocumentSAXFunc endDocument; startElementSAXFunc startElement; endElementSAXFunc endElement; referenceSAXFunc reference; charactersSAXFunc characters; ignorableWhitespaceSAXFunc ignorableWhitespace; processingInstructionSAXFunc processingInstruction; commentSAXFunc comment; warningSAXFunc warning; errorSAXFunc error; fatalErrorSAXFunc fatalError; /* unused error() get all the errors */ getParameterEntitySAXFunc getParameterEntity; cdataBlockSAXFunc cdataBlock; externalSubsetSAXFunc externalSubset; unsigned int initialized; /* The following fields are extensions available only on version 2 */ void *_private; startElementNsSAX2Func startElementNs; endElementNsSAX2Func endElementNs; xmlStructuredErrorFunc serror; }; /* * SAX Version 1 */ typedef struct _xmlSAXHandlerV1 xmlSAXHandlerV1; typedef xmlSAXHandlerV1 *xmlSAXHandlerV1Ptr; struct _xmlSAXHandlerV1 { internalSubsetSAXFunc internalSubset; isStandaloneSAXFunc isStandalone; hasInternalSubsetSAXFunc hasInternalSubset; hasExternalSubsetSAXFunc hasExternalSubset; resolveEntitySAXFunc resolveEntity; getEntitySAXFunc getEntity; entityDeclSAXFunc entityDecl; notationDeclSAXFunc notationDecl; attributeDeclSAXFunc attributeDecl; elementDeclSAXFunc elementDecl; unparsedEntityDeclSAXFunc unparsedEntityDecl; setDocumentLocatorSAXFunc setDocumentLocator; startDocumentSAXFunc startDocument; endDocumentSAXFunc endDocument; startElementSAXFunc startElement; endElementSAXFunc endElement; referenceSAXFunc reference; charactersSAXFunc characters; ignorableWhitespaceSAXFunc ignorableWhitespace; processingInstructionSAXFunc processingInstruction; commentSAXFunc comment; warningSAXFunc warning; errorSAXFunc error; fatalErrorSAXFunc fatalError; /* unused error() get all the errors */ getParameterEntitySAXFunc getParameterEntity; cdataBlockSAXFunc cdataBlock; externalSubsetSAXFunc externalSubset; unsigned int initialized; }; /** * xmlExternalEntityLoader: * @URL: The System ID of the resource requested * @ID: The Public ID of the resource requested * @context: the XML parser context * * External entity loaders types. * * Returns the entity input parser. */ typedef xmlParserInputPtr (*xmlExternalEntityLoader) (const char *URL, const char *ID, xmlParserCtxtPtr context); #ifdef __cplusplus } #endif #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Init/Cleanup */ XMLPUBFUN void xmlInitParser (void); XMLPUBFUN void xmlCleanupParser (void); /* * Input functions */ XML_DEPRECATED XMLPUBFUN int xmlParserInputRead (xmlParserInputPtr in, int len); XML_DEPRECATED XMLPUBFUN int xmlParserInputGrow (xmlParserInputPtr in, int len); /* * Basic parsing Interfaces */ #ifdef LIBXML_SAX1_ENABLED XMLPUBFUN xmlDocPtr xmlParseDoc (const xmlChar *cur); XMLPUBFUN xmlDocPtr xmlParseFile (const char *filename); XMLPUBFUN xmlDocPtr xmlParseMemory (const char *buffer, int size); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN int xmlSubstituteEntitiesDefault(int val); XMLPUBFUN int xmlKeepBlanksDefault (int val); XMLPUBFUN void xmlStopParser (xmlParserCtxtPtr ctxt); XMLPUBFUN int xmlPedanticParserDefault(int val); XMLPUBFUN int xmlLineNumbersDefault (int val); #ifdef LIBXML_SAX1_ENABLED /* * Recovery mode */ XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlRecoverDoc (const xmlChar *cur); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlRecoverMemory (const char *buffer, int size); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlRecoverFile (const char *filename); #endif /* LIBXML_SAX1_ENABLED */ /* * Less common routines and SAX interfaces */ XMLPUBFUN int xmlParseDocument (xmlParserCtxtPtr ctxt); XMLPUBFUN int xmlParseExtParsedEnt (xmlParserCtxtPtr ctxt); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN int xmlSAXUserParseFile (xmlSAXHandlerPtr sax, void *user_data, const char *filename); XML_DEPRECATED XMLPUBFUN int xmlSAXUserParseMemory (xmlSAXHandlerPtr sax, void *user_data, const char *buffer, int size); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseDoc (xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseMemory (xmlSAXHandlerPtr sax, const char *buffer, int size, int recovery); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseMemoryWithData (xmlSAXHandlerPtr sax, const char *buffer, int size, int recovery, void *data); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseFile (xmlSAXHandlerPtr sax, const char *filename, int recovery); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseFileWithData (xmlSAXHandlerPtr sax, const char *filename, int recovery, void *data); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseEntity (xmlSAXHandlerPtr sax, const char *filename); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlParseEntity (const char *filename); #endif /* LIBXML_SAX1_ENABLED */ #ifdef LIBXML_VALID_ENABLED XML_DEPRECATED XMLPUBFUN xmlDtdPtr xmlSAXParseDTD (xmlSAXHandlerPtr sax, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlParseDTD (const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlIOParseDTD (xmlSAXHandlerPtr sax, xmlParserInputBufferPtr input, xmlCharEncoding enc); #endif /* LIBXML_VALID_ENABLE */ #ifdef LIBXML_SAX1_ENABLED XMLPUBFUN int xmlParseBalancedChunkMemory(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN xmlParserErrors xmlParseInNodeContext (xmlNodePtr node, const char *data, int datalen, int options, xmlNodePtr *lst); #ifdef LIBXML_SAX1_ENABLED XMLPUBFUN int xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst, int recover); XML_DEPRECATED XMLPUBFUN int xmlParseExternalEntity (xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN int xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst); /* * Parser contexts handling. */ XMLPUBFUN xmlParserCtxtPtr xmlNewParserCtxt (void); XMLPUBFUN xmlParserCtxtPtr xmlNewSAXParserCtxt (const xmlSAXHandler *sax, void *userData); XMLPUBFUN int xmlInitParserCtxt (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlClearParserCtxt (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlFreeParserCtxt (xmlParserCtxtPtr ctxt); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN void xmlSetupParserForBuffer (xmlParserCtxtPtr ctxt, const xmlChar* buffer, const char *filename); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN xmlParserCtxtPtr xmlCreateDocParserCtxt (const xmlChar *cur); #ifdef LIBXML_LEGACY_ENABLED /* * Reading/setting optional parsing features. */ XML_DEPRECATED XMLPUBFUN int xmlGetFeaturesList (int *len, const char **result); XML_DEPRECATED XMLPUBFUN int xmlGetFeature (xmlParserCtxtPtr ctxt, const char *name, void *result); XML_DEPRECATED XMLPUBFUN int xmlSetFeature (xmlParserCtxtPtr ctxt, const char *name, void *value); #endif /* LIBXML_LEGACY_ENABLED */ #ifdef LIBXML_PUSH_ENABLED /* * Interfaces for the Push mode. */ XMLPUBFUN xmlParserCtxtPtr xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax, void *user_data, const char *chunk, int size, const char *filename); XMLPUBFUN int xmlParseChunk (xmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate); #endif /* LIBXML_PUSH_ENABLED */ /* * Special I/O mode. */ XMLPUBFUN xmlParserCtxtPtr xmlCreateIOParserCtxt (xmlSAXHandlerPtr sax, void *user_data, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, xmlCharEncoding enc); XMLPUBFUN xmlParserInputPtr xmlNewIOInputStream (xmlParserCtxtPtr ctxt, xmlParserInputBufferPtr input, xmlCharEncoding enc); /* * Node infos. */ XMLPUBFUN const xmlParserNodeInfo* xmlParserFindNodeInfo (const xmlParserCtxtPtr ctxt, const xmlNodePtr node); XMLPUBFUN void xmlInitNodeInfoSeq (xmlParserNodeInfoSeqPtr seq); XMLPUBFUN void xmlClearNodeInfoSeq (xmlParserNodeInfoSeqPtr seq); XMLPUBFUN unsigned long xmlParserFindNodeInfoIndex(const xmlParserNodeInfoSeqPtr seq, const xmlNodePtr node); XMLPUBFUN void xmlParserAddNodeInfo (xmlParserCtxtPtr ctxt, const xmlParserNodeInfoPtr info); /* * External entities handling actually implemented in xmlIO. */ XMLPUBFUN void xmlSetExternalEntityLoader(xmlExternalEntityLoader f); XMLPUBFUN xmlExternalEntityLoader xmlGetExternalEntityLoader(void); XMLPUBFUN xmlParserInputPtr xmlLoadExternalEntity (const char *URL, const char *ID, xmlParserCtxtPtr ctxt); /* * Index lookup, actually implemented in the encoding module */ XMLPUBFUN long xmlByteConsumed (xmlParserCtxtPtr ctxt); /* * New set of simpler/more flexible APIs */ /** * xmlParserOption: * * This is the set of XML parser options that can be passed down * to the xmlReadDoc() and similar calls. */ typedef enum { XML_PARSE_RECOVER = 1<<0, /* recover on errors */ XML_PARSE_NOENT = 1<<1, /* substitute entities */ XML_PARSE_DTDLOAD = 1<<2, /* load the external subset */ XML_PARSE_DTDATTR = 1<<3, /* default DTD attributes */ XML_PARSE_DTDVALID = 1<<4, /* validate with the DTD */ XML_PARSE_NOERROR = 1<<5, /* suppress error reports */ XML_PARSE_NOWARNING = 1<<6, /* suppress warning reports */ XML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */ XML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */ XML_PARSE_SAX1 = 1<<9, /* use the SAX1 interface internally */ XML_PARSE_XINCLUDE = 1<<10,/* Implement XInclude substitution */ XML_PARSE_NONET = 1<<11,/* Forbid network access */ XML_PARSE_NODICT = 1<<12,/* Do not reuse the context dictionary */ XML_PARSE_NSCLEAN = 1<<13,/* remove redundant namespaces declarations */ XML_PARSE_NOCDATA = 1<<14,/* merge CDATA as text nodes */ XML_PARSE_NOXINCNODE= 1<<15,/* do not generate XINCLUDE START/END nodes */ XML_PARSE_COMPACT = 1<<16,/* compact small text nodes; no modification of the tree allowed afterwards (will possibly crash if you try to modify the tree) */ XML_PARSE_OLD10 = 1<<17,/* parse using XML-1.0 before update 5 */ XML_PARSE_NOBASEFIX = 1<<18,/* do not fixup XINCLUDE xml:base uris */ XML_PARSE_HUGE = 1<<19,/* relax any hardcoded limit from the parser */ XML_PARSE_OLDSAX = 1<<20,/* parse using SAX2 interface before 2.7.0 */ XML_PARSE_IGNORE_ENC= 1<<21,/* ignore internal document encoding hint */ XML_PARSE_BIG_LINES = 1<<22 /* Store big lines numbers in text PSVI field */ } xmlParserOption; XMLPUBFUN void xmlCtxtReset (xmlParserCtxtPtr ctxt); XMLPUBFUN int xmlCtxtResetPush (xmlParserCtxtPtr ctxt, const char *chunk, int size, const char *filename, const char *encoding); XMLPUBFUN int xmlCtxtUseOptions (xmlParserCtxtPtr ctxt, int options); XMLPUBFUN xmlDocPtr xmlReadDoc (const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadFile (const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadMemory (const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadFd (int fd, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadDoc (xmlParserCtxtPtr ctxt, const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadFile (xmlParserCtxtPtr ctxt, const char *filename, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadMemory (xmlParserCtxtPtr ctxt, const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadFd (xmlParserCtxtPtr ctxt, int fd, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadIO (xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); /* * Library wide options */ /** * xmlFeature: * * Used to examine the existence of features that can be enabled * or disabled at compile-time. * They used to be called XML_FEATURE_xxx but this clashed with Expat */ typedef enum { XML_WITH_THREAD = 1, XML_WITH_TREE = 2, XML_WITH_OUTPUT = 3, XML_WITH_PUSH = 4, XML_WITH_READER = 5, XML_WITH_PATTERN = 6, XML_WITH_WRITER = 7, XML_WITH_SAX1 = 8, XML_WITH_FTP = 9, XML_WITH_HTTP = 10, XML_WITH_VALID = 11, XML_WITH_HTML = 12, XML_WITH_LEGACY = 13, XML_WITH_C14N = 14, XML_WITH_CATALOG = 15, XML_WITH_XPATH = 16, XML_WITH_XPTR = 17, XML_WITH_XINCLUDE = 18, XML_WITH_ICONV = 19, XML_WITH_ISO8859X = 20, XML_WITH_UNICODE = 21, XML_WITH_REGEXP = 22, XML_WITH_AUTOMATA = 23, XML_WITH_EXPR = 24, XML_WITH_SCHEMAS = 25, XML_WITH_SCHEMATRON = 26, XML_WITH_MODULES = 27, XML_WITH_DEBUG = 28, XML_WITH_DEBUG_MEM = 29, XML_WITH_DEBUG_RUN = 30, XML_WITH_ZLIB = 31, XML_WITH_ICU = 32, XML_WITH_LZMA = 33, XML_WITH_NONE = 99999 /* just to be sure of allocation size */ } xmlFeature; XMLPUBFUN int xmlHasFeature (xmlFeature feature); #ifdef __cplusplus } #endif #endif /* __XML_PARSER_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/parserInternals.h ================================================ /* * Summary: internals routines and limits exported by the parser. * Description: this module exports a number of internal parsing routines * they are not really all intended for applications but * can prove useful doing low level processing. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_PARSER_INTERNALS_H__ #define __XML_PARSER_INTERNALS_H__ #include #include #include #include #ifdef __cplusplus extern "C" { #endif /** * xmlParserMaxDepth: * * arbitrary depth limit for the XML documents that we allow to * process. This is not a limitation of the parser but a safety * boundary feature, use XML_PARSE_HUGE option to override it. */ XMLPUBVAR unsigned int xmlParserMaxDepth; /** * XML_MAX_TEXT_LENGTH: * * Maximum size allowed for a single text node when building a tree. * This is not a limitation of the parser but a safety boundary feature, * use XML_PARSE_HUGE option to override it. * Introduced in 2.9.0 */ #define XML_MAX_TEXT_LENGTH 10000000 /** * XML_MAX_HUGE_LENGTH: * * Maximum size allowed when XML_PARSE_HUGE is set. */ #define XML_MAX_HUGE_LENGTH 1000000000 /** * XML_MAX_NAME_LENGTH: * * Maximum size allowed for a markup identifier. * This is not a limitation of the parser but a safety boundary feature, * use XML_PARSE_HUGE option to override it. * Note that with the use of parsing dictionaries overriding the limit * may result in more runtime memory usage in face of "unfriendly' content * Introduced in 2.9.0 */ #define XML_MAX_NAME_LENGTH 50000 /** * XML_MAX_DICTIONARY_LIMIT: * * Maximum size allowed by the parser for a dictionary by default * This is not a limitation of the parser but a safety boundary feature, * use XML_PARSE_HUGE option to override it. * Introduced in 2.9.0 */ #define XML_MAX_DICTIONARY_LIMIT 10000000 /** * XML_MAX_LOOKUP_LIMIT: * * Maximum size allowed by the parser for ahead lookup * This is an upper boundary enforced by the parser to avoid bad * behaviour on "unfriendly' content * Introduced in 2.9.0 */ #define XML_MAX_LOOKUP_LIMIT 10000000 /** * XML_MAX_NAMELEN: * * Identifiers can be longer, but this will be more costly * at runtime. */ #define XML_MAX_NAMELEN 100 /** * INPUT_CHUNK: * * The parser tries to always have that amount of input ready. * One of the point is providing context when reporting errors. */ #define INPUT_CHUNK 250 /************************************************************************ * * * UNICODE version of the macros. * * * ************************************************************************/ /** * IS_BYTE_CHAR: * @c: an byte value (int) * * Macro to check the following production in the XML spec: * * [2] Char ::= #x9 | #xA | #xD | [#x20...] * any byte character in the accepted range */ #define IS_BYTE_CHAR(c) xmlIsChar_ch(c) /** * IS_CHAR: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] * | [#x10000-#x10FFFF] * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */ #define IS_CHAR(c) xmlIsCharQ(c) /** * IS_CHAR_CH: * @c: an xmlChar (usually an unsigned char) * * Behaves like IS_CHAR on single-byte value */ #define IS_CHAR_CH(c) xmlIsChar_ch(c) /** * IS_BLANK: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [3] S ::= (#x20 | #x9 | #xD | #xA)+ */ #define IS_BLANK(c) xmlIsBlankQ(c) /** * IS_BLANK_CH: * @c: an xmlChar value (normally unsigned char) * * Behaviour same as IS_BLANK */ #define IS_BLANK_CH(c) xmlIsBlank_ch(c) /** * IS_BASECHAR: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [85] BaseChar ::= ... long list see REC ... */ #define IS_BASECHAR(c) xmlIsBaseCharQ(c) /** * IS_DIGIT: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [88] Digit ::= ... long list see REC ... */ #define IS_DIGIT(c) xmlIsDigitQ(c) /** * IS_DIGIT_CH: * @c: an xmlChar value (usually an unsigned char) * * Behaves like IS_DIGIT but with a single byte argument */ #define IS_DIGIT_CH(c) xmlIsDigit_ch(c) /** * IS_COMBINING: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [87] CombiningChar ::= ... long list see REC ... */ #define IS_COMBINING(c) xmlIsCombiningQ(c) /** * IS_COMBINING_CH: * @c: an xmlChar (usually an unsigned char) * * Always false (all combining chars > 0xff) */ #define IS_COMBINING_CH(c) 0 /** * IS_EXTENDER: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [89] Extender ::= #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | * #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] | * [#x309D-#x309E] | [#x30FC-#x30FE] */ #define IS_EXTENDER(c) xmlIsExtenderQ(c) /** * IS_EXTENDER_CH: * @c: an xmlChar value (usually an unsigned char) * * Behaves like IS_EXTENDER but with a single-byte argument */ #define IS_EXTENDER_CH(c) xmlIsExtender_ch(c) /** * IS_IDEOGRAPHIC: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [86] Ideographic ::= [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029] */ #define IS_IDEOGRAPHIC(c) xmlIsIdeographicQ(c) /** * IS_LETTER: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [84] Letter ::= BaseChar | Ideographic */ #define IS_LETTER(c) (IS_BASECHAR(c) || IS_IDEOGRAPHIC(c)) /** * IS_LETTER_CH: * @c: an xmlChar value (normally unsigned char) * * Macro behaves like IS_LETTER, but only check base chars * */ #define IS_LETTER_CH(c) xmlIsBaseChar_ch(c) /** * IS_ASCII_LETTER: * @c: an xmlChar value * * Macro to check [a-zA-Z] * */ #define IS_ASCII_LETTER(c) (((0x41 <= (c)) && ((c) <= 0x5a)) || \ ((0x61 <= (c)) && ((c) <= 0x7a))) /** * IS_ASCII_DIGIT: * @c: an xmlChar value * * Macro to check [0-9] * */ #define IS_ASCII_DIGIT(c) ((0x30 <= (c)) && ((c) <= 0x39)) /** * IS_PUBIDCHAR: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] */ #define IS_PUBIDCHAR(c) xmlIsPubidCharQ(c) /** * IS_PUBIDCHAR_CH: * @c: an xmlChar value (normally unsigned char) * * Same as IS_PUBIDCHAR but for single-byte value */ #define IS_PUBIDCHAR_CH(c) xmlIsPubidChar_ch(c) /** * Global variables used for predefined strings. */ XMLPUBVAR const xmlChar xmlStringText[]; XMLPUBVAR const xmlChar xmlStringTextNoenc[]; XMLPUBVAR const xmlChar xmlStringComment[]; /* * Function to finish the work of the macros where needed. */ XMLPUBFUN int xmlIsLetter (int c); /** * Parser context. */ XMLPUBFUN xmlParserCtxtPtr xmlCreateFileParserCtxt (const char *filename); XMLPUBFUN xmlParserCtxtPtr xmlCreateURLParserCtxt (const char *filename, int options); XMLPUBFUN xmlParserCtxtPtr xmlCreateMemoryParserCtxt(const char *buffer, int size); XMLPUBFUN xmlParserCtxtPtr xmlCreateEntityParserCtxt(const xmlChar *URL, const xmlChar *ID, const xmlChar *base); XMLPUBFUN int xmlSwitchEncoding (xmlParserCtxtPtr ctxt, xmlCharEncoding enc); XMLPUBFUN int xmlSwitchToEncoding (xmlParserCtxtPtr ctxt, xmlCharEncodingHandlerPtr handler); XML_DEPRECATED XMLPUBFUN int xmlSwitchInputEncoding (xmlParserCtxtPtr ctxt, xmlParserInputPtr input, xmlCharEncodingHandlerPtr handler); /** * Input Streams. */ XMLPUBFUN xmlParserInputPtr xmlNewStringInputStream (xmlParserCtxtPtr ctxt, const xmlChar *buffer); XML_DEPRECATED XMLPUBFUN xmlParserInputPtr xmlNewEntityInputStream (xmlParserCtxtPtr ctxt, xmlEntityPtr entity); XMLPUBFUN int xmlPushInput (xmlParserCtxtPtr ctxt, xmlParserInputPtr input); XMLPUBFUN xmlChar xmlPopInput (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlFreeInputStream (xmlParserInputPtr input); XMLPUBFUN xmlParserInputPtr xmlNewInputFromFile (xmlParserCtxtPtr ctxt, const char *filename); XMLPUBFUN xmlParserInputPtr xmlNewInputStream (xmlParserCtxtPtr ctxt); /** * Namespaces. */ XMLPUBFUN xmlChar * xmlSplitQName (xmlParserCtxtPtr ctxt, const xmlChar *name, xmlChar **prefix); /** * Generic production rules. */ XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseNmtoken (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseEntityValue (xmlParserCtxtPtr ctxt, xmlChar **orig); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseAttValue (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseSystemLiteral (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParsePubidLiteral (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseCharData (xmlParserCtxtPtr ctxt, int cdata); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseExternalID (xmlParserCtxtPtr ctxt, xmlChar **publicID, int strict); XML_DEPRECATED XMLPUBFUN void xmlParseComment (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParsePITarget (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParsePI (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseNotationDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseEntityDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseDefaultDecl (xmlParserCtxtPtr ctxt, xmlChar **value); XML_DEPRECATED XMLPUBFUN xmlEnumerationPtr xmlParseNotationType (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlEnumerationPtr xmlParseEnumerationType (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseEnumeratedType (xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree); XML_DEPRECATED XMLPUBFUN int xmlParseAttributeType (xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree); XML_DEPRECATED XMLPUBFUN void xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlElementContentPtr xmlParseElementMixedContentDecl (xmlParserCtxtPtr ctxt, int inputchk); XML_DEPRECATED XMLPUBFUN xmlElementContentPtr xmlParseElementChildrenContentDecl (xmlParserCtxtPtr ctxt, int inputchk); XML_DEPRECATED XMLPUBFUN int xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlElementContentPtr *result); XML_DEPRECATED XMLPUBFUN int xmlParseElementDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseMarkupDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseCharRef (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlEntityPtr xmlParseEntityRef (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseReference (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParsePEReference (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseDocTypeDecl (xmlParserCtxtPtr ctxt); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseAttribute (xmlParserCtxtPtr ctxt, xmlChar **value); XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseStartTag (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseEndTag (xmlParserCtxtPtr ctxt); #endif /* LIBXML_SAX1_ENABLED */ XML_DEPRECATED XMLPUBFUN void xmlParseCDSect (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlParseContent (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseElement (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseVersionNum (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseVersionInfo (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseEncName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseEncodingDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseSDDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseXMLDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseTextDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseMisc (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlParseExternalSubset (xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, const xmlChar *SystemID); /** * XML_SUBSTITUTE_NONE: * * If no entities need to be substituted. */ #define XML_SUBSTITUTE_NONE 0 /** * XML_SUBSTITUTE_REF: * * Whether general entities need to be substituted. */ #define XML_SUBSTITUTE_REF 1 /** * XML_SUBSTITUTE_PEREF: * * Whether parameter entities need to be substituted. */ #define XML_SUBSTITUTE_PEREF 2 /** * XML_SUBSTITUTE_BOTH: * * Both general and parameter entities need to be substituted. */ #define XML_SUBSTITUTE_BOTH 3 XML_DEPRECATED XMLPUBFUN xmlChar * xmlStringDecodeEntities (xmlParserCtxtPtr ctxt, const xmlChar *str, int what, xmlChar end, xmlChar end2, xmlChar end3); XML_DEPRECATED XMLPUBFUN xmlChar * xmlStringLenDecodeEntities (xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3); /* * Generated by MACROS on top of parser.c c.f. PUSH_AND_POP. */ XML_DEPRECATED XMLPUBFUN int nodePush (xmlParserCtxtPtr ctxt, xmlNodePtr value); XML_DEPRECATED XMLPUBFUN xmlNodePtr nodePop (xmlParserCtxtPtr ctxt); XMLPUBFUN int inputPush (xmlParserCtxtPtr ctxt, xmlParserInputPtr value); XMLPUBFUN xmlParserInputPtr inputPop (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN const xmlChar * namePop (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int namePush (xmlParserCtxtPtr ctxt, const xmlChar *value); /* * other commodities shared between parser.c and parserInternals. */ XML_DEPRECATED XMLPUBFUN int xmlSkipBlankChars (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlStringCurrentChar (xmlParserCtxtPtr ctxt, const xmlChar *cur, int *len); XML_DEPRECATED XMLPUBFUN void xmlParserHandlePEReference(xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlCheckLanguageID (const xmlChar *lang); /* * Really core function shared with HTML parser. */ XML_DEPRECATED XMLPUBFUN int xmlCurrentChar (xmlParserCtxtPtr ctxt, int *len); XMLPUBFUN int xmlCopyCharMultiByte (xmlChar *out, int val); XMLPUBFUN int xmlCopyChar (int len, xmlChar *out, int val); XML_DEPRECATED XMLPUBFUN void xmlNextChar (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParserInputShrink (xmlParserInputPtr in); /* * Specific function to keep track of entities references * and used by the XSLT debugger. */ #ifdef LIBXML_LEGACY_ENABLED /** * xmlEntityReferenceFunc: * @ent: the entity * @firstNode: the fist node in the chunk * @lastNode: the last nod in the chunk * * Callback function used when one needs to be able to track back the * provenance of a chunk of nodes inherited from an entity replacement. */ typedef void (*xmlEntityReferenceFunc) (xmlEntityPtr ent, xmlNodePtr firstNode, xmlNodePtr lastNode); XML_DEPRECATED XMLPUBFUN void xmlSetEntityReferenceFunc (xmlEntityReferenceFunc func); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseQuotedString (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseNamespace (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlNamespaceParseNSDef (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlScanName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlNamespaceParseNCName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParserHandleReference(xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlNamespaceParseQName (xmlParserCtxtPtr ctxt, xmlChar **prefix); /** * Entities */ XML_DEPRECATED XMLPUBFUN xmlChar * xmlDecodeEntities (xmlParserCtxtPtr ctxt, int len, int what, xmlChar end, xmlChar end2, xmlChar end3); XML_DEPRECATED XMLPUBFUN void xmlHandleEntity (xmlParserCtxtPtr ctxt, xmlEntityPtr entity); #endif /* LIBXML_LEGACY_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_PARSER_INTERNALS_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/pattern.h ================================================ /* * Summary: pattern expression handling * Description: allows to compile and test pattern expressions for nodes * either in a tree or based on a parser state. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_PATTERN_H__ #define __XML_PATTERN_H__ #include #include #include #ifdef LIBXML_PATTERN_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlPattern: * * A compiled (XPath based) pattern to select nodes */ typedef struct _xmlPattern xmlPattern; typedef xmlPattern *xmlPatternPtr; /** * xmlPatternFlags: * * This is the set of options affecting the behaviour of pattern * matching with this module * */ typedef enum { XML_PATTERN_DEFAULT = 0, /* simple pattern match */ XML_PATTERN_XPATH = 1<<0, /* standard XPath pattern */ XML_PATTERN_XSSEL = 1<<1, /* XPath subset for schema selector */ XML_PATTERN_XSFIELD = 1<<2 /* XPath subset for schema field */ } xmlPatternFlags; XMLPUBFUN void xmlFreePattern (xmlPatternPtr comp); XMLPUBFUN void xmlFreePatternList (xmlPatternPtr comp); XMLPUBFUN xmlPatternPtr xmlPatterncompile (const xmlChar *pattern, xmlDict *dict, int flags, const xmlChar **namespaces); XMLPUBFUN int xmlPatternMatch (xmlPatternPtr comp, xmlNodePtr node); /* streaming interfaces */ typedef struct _xmlStreamCtxt xmlStreamCtxt; typedef xmlStreamCtxt *xmlStreamCtxtPtr; XMLPUBFUN int xmlPatternStreamable (xmlPatternPtr comp); XMLPUBFUN int xmlPatternMaxDepth (xmlPatternPtr comp); XMLPUBFUN int xmlPatternMinDepth (xmlPatternPtr comp); XMLPUBFUN int xmlPatternFromRoot (xmlPatternPtr comp); XMLPUBFUN xmlStreamCtxtPtr xmlPatternGetStreamCtxt (xmlPatternPtr comp); XMLPUBFUN void xmlFreeStreamCtxt (xmlStreamCtxtPtr stream); XMLPUBFUN int xmlStreamPushNode (xmlStreamCtxtPtr stream, const xmlChar *name, const xmlChar *ns, int nodeType); XMLPUBFUN int xmlStreamPush (xmlStreamCtxtPtr stream, const xmlChar *name, const xmlChar *ns); XMLPUBFUN int xmlStreamPushAttr (xmlStreamCtxtPtr stream, const xmlChar *name, const xmlChar *ns); XMLPUBFUN int xmlStreamPop (xmlStreamCtxtPtr stream); XMLPUBFUN int xmlStreamWantsAnyNode (xmlStreamCtxtPtr stream); #ifdef __cplusplus } #endif #endif /* LIBXML_PATTERN_ENABLED */ #endif /* __XML_PATTERN_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/relaxng.h ================================================ /* * Summary: implementation of the Relax-NG validation * Description: implementation of the Relax-NG validation * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_RELAX_NG__ #define __XML_RELAX_NG__ #include #include #include #ifdef LIBXML_SCHEMAS_ENABLED #ifdef __cplusplus extern "C" { #endif typedef struct _xmlRelaxNG xmlRelaxNG; typedef xmlRelaxNG *xmlRelaxNGPtr; /** * xmlRelaxNGValidityErrorFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of an error callback from a Relax-NG validation */ typedef void (*xmlRelaxNGValidityErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlRelaxNGValidityWarningFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of a warning callback from a Relax-NG validation */ typedef void (*xmlRelaxNGValidityWarningFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * A schemas validation context */ typedef struct _xmlRelaxNGParserCtxt xmlRelaxNGParserCtxt; typedef xmlRelaxNGParserCtxt *xmlRelaxNGParserCtxtPtr; typedef struct _xmlRelaxNGValidCtxt xmlRelaxNGValidCtxt; typedef xmlRelaxNGValidCtxt *xmlRelaxNGValidCtxtPtr; /* * xmlRelaxNGValidErr: * * List of possible Relax NG validation errors */ typedef enum { XML_RELAXNG_OK = 0, XML_RELAXNG_ERR_MEMORY, XML_RELAXNG_ERR_TYPE, XML_RELAXNG_ERR_TYPEVAL, XML_RELAXNG_ERR_DUPID, XML_RELAXNG_ERR_TYPECMP, XML_RELAXNG_ERR_NOSTATE, XML_RELAXNG_ERR_NODEFINE, XML_RELAXNG_ERR_LISTEXTRA, XML_RELAXNG_ERR_LISTEMPTY, XML_RELAXNG_ERR_INTERNODATA, XML_RELAXNG_ERR_INTERSEQ, XML_RELAXNG_ERR_INTEREXTRA, XML_RELAXNG_ERR_ELEMNAME, XML_RELAXNG_ERR_ATTRNAME, XML_RELAXNG_ERR_ELEMNONS, XML_RELAXNG_ERR_ATTRNONS, XML_RELAXNG_ERR_ELEMWRONGNS, XML_RELAXNG_ERR_ATTRWRONGNS, XML_RELAXNG_ERR_ELEMEXTRANS, XML_RELAXNG_ERR_ATTREXTRANS, XML_RELAXNG_ERR_ELEMNOTEMPTY, XML_RELAXNG_ERR_NOELEM, XML_RELAXNG_ERR_NOTELEM, XML_RELAXNG_ERR_ATTRVALID, XML_RELAXNG_ERR_CONTENTVALID, XML_RELAXNG_ERR_EXTRACONTENT, XML_RELAXNG_ERR_INVALIDATTR, XML_RELAXNG_ERR_DATAELEM, XML_RELAXNG_ERR_VALELEM, XML_RELAXNG_ERR_LISTELEM, XML_RELAXNG_ERR_DATATYPE, XML_RELAXNG_ERR_VALUE, XML_RELAXNG_ERR_LIST, XML_RELAXNG_ERR_NOGRAMMAR, XML_RELAXNG_ERR_EXTRADATA, XML_RELAXNG_ERR_LACKDATA, XML_RELAXNG_ERR_INTERNAL, XML_RELAXNG_ERR_ELEMWRONG, XML_RELAXNG_ERR_TEXTWRONG } xmlRelaxNGValidErr; /* * xmlRelaxNGParserFlags: * * List of possible Relax NG Parser flags */ typedef enum { XML_RELAXNGP_NONE = 0, XML_RELAXNGP_FREE_DOC = 1, XML_RELAXNGP_CRNG = 2 } xmlRelaxNGParserFlag; XMLPUBFUN int xmlRelaxNGInitTypes (void); XML_DEPRECATED XMLPUBFUN void xmlRelaxNGCleanupTypes (void); /* * Interfaces for parsing. */ XMLPUBFUN xmlRelaxNGParserCtxtPtr xmlRelaxNGNewParserCtxt (const char *URL); XMLPUBFUN xmlRelaxNGParserCtxtPtr xmlRelaxNGNewMemParserCtxt (const char *buffer, int size); XMLPUBFUN xmlRelaxNGParserCtxtPtr xmlRelaxNGNewDocParserCtxt (xmlDocPtr doc); XMLPUBFUN int xmlRelaxParserSetFlag (xmlRelaxNGParserCtxtPtr ctxt, int flag); XMLPUBFUN void xmlRelaxNGFreeParserCtxt (xmlRelaxNGParserCtxtPtr ctxt); XMLPUBFUN void xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc err, xmlRelaxNGValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc *err, xmlRelaxNGValidityWarningFunc *warn, void **ctx); XMLPUBFUN void xmlRelaxNGSetParserStructuredErrors( xmlRelaxNGParserCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN xmlRelaxNGPtr xmlRelaxNGParse (xmlRelaxNGParserCtxtPtr ctxt); XMLPUBFUN void xmlRelaxNGFree (xmlRelaxNGPtr schema); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlRelaxNGDump (FILE *output, xmlRelaxNGPtr schema); XMLPUBFUN void xmlRelaxNGDumpTree (FILE * output, xmlRelaxNGPtr schema); #endif /* LIBXML_OUTPUT_ENABLED */ /* * Interfaces for validating */ XMLPUBFUN void xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc err, xmlRelaxNGValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc *err, xmlRelaxNGValidityWarningFunc *warn, void **ctx); XMLPUBFUN void xmlRelaxNGSetValidStructuredErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN xmlRelaxNGValidCtxtPtr xmlRelaxNGNewValidCtxt (xmlRelaxNGPtr schema); XMLPUBFUN void xmlRelaxNGFreeValidCtxt (xmlRelaxNGValidCtxtPtr ctxt); XMLPUBFUN int xmlRelaxNGValidateDoc (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc); /* * Interfaces for progressive validation when possible */ XMLPUBFUN int xmlRelaxNGValidatePushElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlRelaxNGValidatePushCData (xmlRelaxNGValidCtxtPtr ctxt, const xmlChar *data, int len); XMLPUBFUN int xmlRelaxNGValidatePopElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlRelaxNGValidateFullElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_RELAX_NG__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/schemasInternals.h ================================================ /* * Summary: internal interfaces for XML Schemas * Description: internal interfaces for the XML Schemas handling * and schema validity checking * The Schemas development is a Work In Progress. * Some of those interfaces are not guaranteed to be API or ABI stable ! * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMA_INTERNALS_H__ #define __XML_SCHEMA_INTERNALS_H__ #include #ifdef LIBXML_SCHEMAS_ENABLED #include #include #include #ifdef __cplusplus extern "C" { #endif typedef enum { XML_SCHEMAS_UNKNOWN = 0, XML_SCHEMAS_STRING = 1, XML_SCHEMAS_NORMSTRING = 2, XML_SCHEMAS_DECIMAL = 3, XML_SCHEMAS_TIME = 4, XML_SCHEMAS_GDAY = 5, XML_SCHEMAS_GMONTH = 6, XML_SCHEMAS_GMONTHDAY = 7, XML_SCHEMAS_GYEAR = 8, XML_SCHEMAS_GYEARMONTH = 9, XML_SCHEMAS_DATE = 10, XML_SCHEMAS_DATETIME = 11, XML_SCHEMAS_DURATION = 12, XML_SCHEMAS_FLOAT = 13, XML_SCHEMAS_DOUBLE = 14, XML_SCHEMAS_BOOLEAN = 15, XML_SCHEMAS_TOKEN = 16, XML_SCHEMAS_LANGUAGE = 17, XML_SCHEMAS_NMTOKEN = 18, XML_SCHEMAS_NMTOKENS = 19, XML_SCHEMAS_NAME = 20, XML_SCHEMAS_QNAME = 21, XML_SCHEMAS_NCNAME = 22, XML_SCHEMAS_ID = 23, XML_SCHEMAS_IDREF = 24, XML_SCHEMAS_IDREFS = 25, XML_SCHEMAS_ENTITY = 26, XML_SCHEMAS_ENTITIES = 27, XML_SCHEMAS_NOTATION = 28, XML_SCHEMAS_ANYURI = 29, XML_SCHEMAS_INTEGER = 30, XML_SCHEMAS_NPINTEGER = 31, XML_SCHEMAS_NINTEGER = 32, XML_SCHEMAS_NNINTEGER = 33, XML_SCHEMAS_PINTEGER = 34, XML_SCHEMAS_INT = 35, XML_SCHEMAS_UINT = 36, XML_SCHEMAS_LONG = 37, XML_SCHEMAS_ULONG = 38, XML_SCHEMAS_SHORT = 39, XML_SCHEMAS_USHORT = 40, XML_SCHEMAS_BYTE = 41, XML_SCHEMAS_UBYTE = 42, XML_SCHEMAS_HEXBINARY = 43, XML_SCHEMAS_BASE64BINARY = 44, XML_SCHEMAS_ANYTYPE = 45, XML_SCHEMAS_ANYSIMPLETYPE = 46 } xmlSchemaValType; /* * XML Schemas defines multiple type of types. */ typedef enum { XML_SCHEMA_TYPE_BASIC = 1, /* A built-in datatype */ XML_SCHEMA_TYPE_ANY, XML_SCHEMA_TYPE_FACET, XML_SCHEMA_TYPE_SIMPLE, XML_SCHEMA_TYPE_COMPLEX, XML_SCHEMA_TYPE_SEQUENCE = 6, XML_SCHEMA_TYPE_CHOICE, XML_SCHEMA_TYPE_ALL, XML_SCHEMA_TYPE_SIMPLE_CONTENT, XML_SCHEMA_TYPE_COMPLEX_CONTENT, XML_SCHEMA_TYPE_UR, XML_SCHEMA_TYPE_RESTRICTION, XML_SCHEMA_TYPE_EXTENSION, XML_SCHEMA_TYPE_ELEMENT, XML_SCHEMA_TYPE_ATTRIBUTE, XML_SCHEMA_TYPE_ATTRIBUTEGROUP, XML_SCHEMA_TYPE_GROUP, XML_SCHEMA_TYPE_NOTATION, XML_SCHEMA_TYPE_LIST, XML_SCHEMA_TYPE_UNION, XML_SCHEMA_TYPE_ANY_ATTRIBUTE, XML_SCHEMA_TYPE_IDC_UNIQUE, XML_SCHEMA_TYPE_IDC_KEY, XML_SCHEMA_TYPE_IDC_KEYREF, XML_SCHEMA_TYPE_PARTICLE = 25, XML_SCHEMA_TYPE_ATTRIBUTE_USE, XML_SCHEMA_FACET_MININCLUSIVE = 1000, XML_SCHEMA_FACET_MINEXCLUSIVE, XML_SCHEMA_FACET_MAXINCLUSIVE, XML_SCHEMA_FACET_MAXEXCLUSIVE, XML_SCHEMA_FACET_TOTALDIGITS, XML_SCHEMA_FACET_FRACTIONDIGITS, XML_SCHEMA_FACET_PATTERN, XML_SCHEMA_FACET_ENUMERATION, XML_SCHEMA_FACET_WHITESPACE, XML_SCHEMA_FACET_LENGTH, XML_SCHEMA_FACET_MAXLENGTH, XML_SCHEMA_FACET_MINLENGTH, XML_SCHEMA_EXTRA_QNAMEREF = 2000, XML_SCHEMA_EXTRA_ATTR_USE_PROHIB } xmlSchemaTypeType; typedef enum { XML_SCHEMA_CONTENT_UNKNOWN = 0, XML_SCHEMA_CONTENT_EMPTY = 1, XML_SCHEMA_CONTENT_ELEMENTS, XML_SCHEMA_CONTENT_MIXED, XML_SCHEMA_CONTENT_SIMPLE, XML_SCHEMA_CONTENT_MIXED_OR_ELEMENTS, /* Obsolete */ XML_SCHEMA_CONTENT_BASIC, XML_SCHEMA_CONTENT_ANY } xmlSchemaContentType; typedef struct _xmlSchemaVal xmlSchemaVal; typedef xmlSchemaVal *xmlSchemaValPtr; typedef struct _xmlSchemaType xmlSchemaType; typedef xmlSchemaType *xmlSchemaTypePtr; typedef struct _xmlSchemaFacet xmlSchemaFacet; typedef xmlSchemaFacet *xmlSchemaFacetPtr; /** * Annotation */ typedef struct _xmlSchemaAnnot xmlSchemaAnnot; typedef xmlSchemaAnnot *xmlSchemaAnnotPtr; struct _xmlSchemaAnnot { struct _xmlSchemaAnnot *next; xmlNodePtr content; /* the annotation */ }; /** * XML_SCHEMAS_ANYATTR_SKIP: * * Skip unknown attribute from validation * Obsolete, not used anymore. */ #define XML_SCHEMAS_ANYATTR_SKIP 1 /** * XML_SCHEMAS_ANYATTR_LAX: * * Ignore validation non definition on attributes * Obsolete, not used anymore. */ #define XML_SCHEMAS_ANYATTR_LAX 2 /** * XML_SCHEMAS_ANYATTR_STRICT: * * Apply strict validation rules on attributes * Obsolete, not used anymore. */ #define XML_SCHEMAS_ANYATTR_STRICT 3 /** * XML_SCHEMAS_ANY_SKIP: * * Skip unknown attribute from validation */ #define XML_SCHEMAS_ANY_SKIP 1 /** * XML_SCHEMAS_ANY_LAX: * * Used by wildcards. * Validate if type found, don't worry if not found */ #define XML_SCHEMAS_ANY_LAX 2 /** * XML_SCHEMAS_ANY_STRICT: * * Used by wildcards. * Apply strict validation rules */ #define XML_SCHEMAS_ANY_STRICT 3 /** * XML_SCHEMAS_ATTR_USE_PROHIBITED: * * Used by wildcards. * The attribute is prohibited. */ #define XML_SCHEMAS_ATTR_USE_PROHIBITED 0 /** * XML_SCHEMAS_ATTR_USE_REQUIRED: * * The attribute is required. */ #define XML_SCHEMAS_ATTR_USE_REQUIRED 1 /** * XML_SCHEMAS_ATTR_USE_OPTIONAL: * * The attribute is optional. */ #define XML_SCHEMAS_ATTR_USE_OPTIONAL 2 /** * XML_SCHEMAS_ATTR_GLOBAL: * * allow elements in no namespace */ #define XML_SCHEMAS_ATTR_GLOBAL 1 << 0 /** * XML_SCHEMAS_ATTR_NSDEFAULT: * * allow elements in no namespace */ #define XML_SCHEMAS_ATTR_NSDEFAULT 1 << 7 /** * XML_SCHEMAS_ATTR_INTERNAL_RESOLVED: * * this is set when the "type" and "ref" references * have been resolved. */ #define XML_SCHEMAS_ATTR_INTERNAL_RESOLVED 1 << 8 /** * XML_SCHEMAS_ATTR_FIXED: * * the attribute has a fixed value */ #define XML_SCHEMAS_ATTR_FIXED 1 << 9 /** * xmlSchemaAttribute: * An attribute definition. */ typedef struct _xmlSchemaAttribute xmlSchemaAttribute; typedef xmlSchemaAttribute *xmlSchemaAttributePtr; struct _xmlSchemaAttribute { xmlSchemaTypeType type; struct _xmlSchemaAttribute *next; /* the next attribute (not used?) */ const xmlChar *name; /* the name of the declaration */ const xmlChar *id; /* Deprecated; not used */ const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ const xmlChar *typeName; /* the local name of the type definition */ const xmlChar *typeNs; /* the ns URI of the type definition */ xmlSchemaAnnotPtr annot; xmlSchemaTypePtr base; /* Deprecated; not used */ int occurs; /* Deprecated; not used */ const xmlChar *defValue; /* The initial value of the value constraint */ xmlSchemaTypePtr subtypes; /* the type definition */ xmlNodePtr node; const xmlChar *targetNamespace; int flags; const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaValPtr defVal; /* The compiled value constraint */ xmlSchemaAttributePtr refDecl; /* Deprecated; not used */ }; /** * xmlSchemaAttributeLink: * Used to build a list of attribute uses on complexType definitions. * WARNING: Deprecated; not used. */ typedef struct _xmlSchemaAttributeLink xmlSchemaAttributeLink; typedef xmlSchemaAttributeLink *xmlSchemaAttributeLinkPtr; struct _xmlSchemaAttributeLink { struct _xmlSchemaAttributeLink *next;/* the next attribute link ... */ struct _xmlSchemaAttribute *attr;/* the linked attribute */ }; /** * XML_SCHEMAS_WILDCARD_COMPLETE: * * If the wildcard is complete. */ #define XML_SCHEMAS_WILDCARD_COMPLETE 1 << 0 /** * xmlSchemaCharValueLink: * Used to build a list of namespaces on wildcards. */ typedef struct _xmlSchemaWildcardNs xmlSchemaWildcardNs; typedef xmlSchemaWildcardNs *xmlSchemaWildcardNsPtr; struct _xmlSchemaWildcardNs { struct _xmlSchemaWildcardNs *next;/* the next constraint link ... */ const xmlChar *value;/* the value */ }; /** * xmlSchemaWildcard. * A wildcard. */ typedef struct _xmlSchemaWildcard xmlSchemaWildcard; typedef xmlSchemaWildcard *xmlSchemaWildcardPtr; struct _xmlSchemaWildcard { xmlSchemaTypeType type; /* The kind of type */ const xmlChar *id; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlNodePtr node; int minOccurs; /* Deprecated; not used */ int maxOccurs; /* Deprecated; not used */ int processContents; int any; /* Indicates if the ns constraint is of ##any */ xmlSchemaWildcardNsPtr nsSet; /* The list of allowed namespaces */ xmlSchemaWildcardNsPtr negNsSet; /* The negated namespace */ int flags; }; /** * XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED: * * The attribute wildcard has been built. */ #define XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED 1 << 0 /** * XML_SCHEMAS_ATTRGROUP_GLOBAL: * * The attribute group has been defined. */ #define XML_SCHEMAS_ATTRGROUP_GLOBAL 1 << 1 /** * XML_SCHEMAS_ATTRGROUP_MARKED: * * Marks the attr group as marked; used for circular checks. */ #define XML_SCHEMAS_ATTRGROUP_MARKED 1 << 2 /** * XML_SCHEMAS_ATTRGROUP_REDEFINED: * * The attr group was redefined. */ #define XML_SCHEMAS_ATTRGROUP_REDEFINED 1 << 3 /** * XML_SCHEMAS_ATTRGROUP_HAS_REFS: * * Whether this attr. group contains attr. group references. */ #define XML_SCHEMAS_ATTRGROUP_HAS_REFS 1 << 4 /** * An attribute group definition. * * xmlSchemaAttribute and xmlSchemaAttributeGroup start of structures * must be kept similar */ typedef struct _xmlSchemaAttributeGroup xmlSchemaAttributeGroup; typedef xmlSchemaAttributeGroup *xmlSchemaAttributeGroupPtr; struct _xmlSchemaAttributeGroup { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaAttribute *next;/* the next attribute if in a group ... */ const xmlChar *name; const xmlChar *id; const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlSchemaAttributePtr attributes; /* Deprecated; not used */ xmlNodePtr node; int flags; xmlSchemaWildcardPtr attributeWildcard; const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaAttributeGroupPtr refItem; /* Deprecated; not used */ const xmlChar *targetNamespace; void *attrUses; }; /** * xmlSchemaTypeLink: * Used to build a list of types (e.g. member types of * simpleType with variety "union"). */ typedef struct _xmlSchemaTypeLink xmlSchemaTypeLink; typedef xmlSchemaTypeLink *xmlSchemaTypeLinkPtr; struct _xmlSchemaTypeLink { struct _xmlSchemaTypeLink *next;/* the next type link ... */ xmlSchemaTypePtr type;/* the linked type */ }; /** * xmlSchemaFacetLink: * Used to build a list of facets. */ typedef struct _xmlSchemaFacetLink xmlSchemaFacetLink; typedef xmlSchemaFacetLink *xmlSchemaFacetLinkPtr; struct _xmlSchemaFacetLink { struct _xmlSchemaFacetLink *next;/* the next facet link ... */ xmlSchemaFacetPtr facet;/* the linked facet */ }; /** * XML_SCHEMAS_TYPE_MIXED: * * the element content type is mixed */ #define XML_SCHEMAS_TYPE_MIXED 1 << 0 /** * XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION: * * the simple or complex type has a derivation method of "extension". */ #define XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION 1 << 1 /** * XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION: * * the simple or complex type has a derivation method of "restriction". */ #define XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION 1 << 2 /** * XML_SCHEMAS_TYPE_GLOBAL: * * the type is global */ #define XML_SCHEMAS_TYPE_GLOBAL 1 << 3 /** * XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD: * * the complexType owns an attribute wildcard, i.e. * it can be freed by the complexType */ #define XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD 1 << 4 /* Obsolete. */ /** * XML_SCHEMAS_TYPE_VARIETY_ABSENT: * * the simpleType has a variety of "absent". * TODO: Actually not necessary :-/, since if * none of the variety flags occur then it's * automatically absent. */ #define XML_SCHEMAS_TYPE_VARIETY_ABSENT 1 << 5 /** * XML_SCHEMAS_TYPE_VARIETY_LIST: * * the simpleType has a variety of "list". */ #define XML_SCHEMAS_TYPE_VARIETY_LIST 1 << 6 /** * XML_SCHEMAS_TYPE_VARIETY_UNION: * * the simpleType has a variety of "union". */ #define XML_SCHEMAS_TYPE_VARIETY_UNION 1 << 7 /** * XML_SCHEMAS_TYPE_VARIETY_ATOMIC: * * the simpleType has a variety of "union". */ #define XML_SCHEMAS_TYPE_VARIETY_ATOMIC 1 << 8 /** * XML_SCHEMAS_TYPE_FINAL_EXTENSION: * * the complexType has a final of "extension". */ #define XML_SCHEMAS_TYPE_FINAL_EXTENSION 1 << 9 /** * XML_SCHEMAS_TYPE_FINAL_RESTRICTION: * * the simpleType/complexType has a final of "restriction". */ #define XML_SCHEMAS_TYPE_FINAL_RESTRICTION 1 << 10 /** * XML_SCHEMAS_TYPE_FINAL_LIST: * * the simpleType has a final of "list". */ #define XML_SCHEMAS_TYPE_FINAL_LIST 1 << 11 /** * XML_SCHEMAS_TYPE_FINAL_UNION: * * the simpleType has a final of "union". */ #define XML_SCHEMAS_TYPE_FINAL_UNION 1 << 12 /** * XML_SCHEMAS_TYPE_FINAL_DEFAULT: * * the simpleType has a final of "default". */ #define XML_SCHEMAS_TYPE_FINAL_DEFAULT 1 << 13 /** * XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE: * * Marks the item as a builtin primitive. */ #define XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE 1 << 14 /** * XML_SCHEMAS_TYPE_MARKED: * * Marks the item as marked; used for circular checks. */ #define XML_SCHEMAS_TYPE_MARKED 1 << 16 /** * XML_SCHEMAS_TYPE_BLOCK_DEFAULT: * * the complexType did not specify 'block' so use the default of the * item. */ #define XML_SCHEMAS_TYPE_BLOCK_DEFAULT 1 << 17 /** * XML_SCHEMAS_TYPE_BLOCK_EXTENSION: * * the complexType has a 'block' of "extension". */ #define XML_SCHEMAS_TYPE_BLOCK_EXTENSION 1 << 18 /** * XML_SCHEMAS_TYPE_BLOCK_RESTRICTION: * * the complexType has a 'block' of "restriction". */ #define XML_SCHEMAS_TYPE_BLOCK_RESTRICTION 1 << 19 /** * XML_SCHEMAS_TYPE_ABSTRACT: * * the simple/complexType is abstract. */ #define XML_SCHEMAS_TYPE_ABSTRACT 1 << 20 /** * XML_SCHEMAS_TYPE_FACETSNEEDVALUE: * * indicates if the facets need a computed value */ #define XML_SCHEMAS_TYPE_FACETSNEEDVALUE 1 << 21 /** * XML_SCHEMAS_TYPE_INTERNAL_RESOLVED: * * indicates that the type was typefixed */ #define XML_SCHEMAS_TYPE_INTERNAL_RESOLVED 1 << 22 /** * XML_SCHEMAS_TYPE_INTERNAL_INVALID: * * indicates that the type is invalid */ #define XML_SCHEMAS_TYPE_INTERNAL_INVALID 1 << 23 /** * XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE: * * a whitespace-facet value of "preserve" */ #define XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE 1 << 24 /** * XML_SCHEMAS_TYPE_WHITESPACE_REPLACE: * * a whitespace-facet value of "replace" */ #define XML_SCHEMAS_TYPE_WHITESPACE_REPLACE 1 << 25 /** * XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE: * * a whitespace-facet value of "collapse" */ #define XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE 1 << 26 /** * XML_SCHEMAS_TYPE_HAS_FACETS: * * has facets */ #define XML_SCHEMAS_TYPE_HAS_FACETS 1 << 27 /** * XML_SCHEMAS_TYPE_NORMVALUENEEDED: * * indicates if the facets (pattern) need a normalized value */ #define XML_SCHEMAS_TYPE_NORMVALUENEEDED 1 << 28 /** * XML_SCHEMAS_TYPE_FIXUP_1: * * First stage of fixup was done. */ #define XML_SCHEMAS_TYPE_FIXUP_1 1 << 29 /** * XML_SCHEMAS_TYPE_REDEFINED: * * The type was redefined. */ #define XML_SCHEMAS_TYPE_REDEFINED 1 << 30 /** * XML_SCHEMAS_TYPE_REDEFINING: * * The type redefines an other type. */ /* #define XML_SCHEMAS_TYPE_REDEFINING 1 << 31 */ /** * _xmlSchemaType: * * Schemas type definition. */ struct _xmlSchemaType { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaType *next; /* the next type if in a sequence ... */ const xmlChar *name; const xmlChar *id ; /* Deprecated; not used */ const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlSchemaTypePtr subtypes; xmlSchemaAttributePtr attributes; /* Deprecated; not used */ xmlNodePtr node; int minOccurs; /* Deprecated; not used */ int maxOccurs; /* Deprecated; not used */ int flags; xmlSchemaContentType contentType; const xmlChar *base; /* Base type's local name */ const xmlChar *baseNs; /* Base type's target namespace */ xmlSchemaTypePtr baseType; /* The base type component */ xmlSchemaFacetPtr facets; /* Local facets */ struct _xmlSchemaType *redef; /* Deprecated; not used */ int recurse; /* Obsolete */ xmlSchemaAttributeLinkPtr *attributeUses; /* Deprecated; not used */ xmlSchemaWildcardPtr attributeWildcard; int builtInType; /* Type of built-in types. */ xmlSchemaTypeLinkPtr memberTypes; /* member-types if a union type. */ xmlSchemaFacetLinkPtr facetSet; /* All facets (incl. inherited) */ const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaTypePtr contentTypeDef; /* Used for the simple content of complex types. Could we use @subtypes for this? */ xmlRegexpPtr contModel; /* Holds the automaton of the content model */ const xmlChar *targetNamespace; void *attrUses; }; /* * xmlSchemaElement: * An element definition. * * xmlSchemaType, xmlSchemaFacet and xmlSchemaElement start of * structures must be kept similar */ /** * XML_SCHEMAS_ELEM_NILLABLE: * * the element is nillable */ #define XML_SCHEMAS_ELEM_NILLABLE 1 << 0 /** * XML_SCHEMAS_ELEM_GLOBAL: * * the element is global */ #define XML_SCHEMAS_ELEM_GLOBAL 1 << 1 /** * XML_SCHEMAS_ELEM_DEFAULT: * * the element has a default value */ #define XML_SCHEMAS_ELEM_DEFAULT 1 << 2 /** * XML_SCHEMAS_ELEM_FIXED: * * the element has a fixed value */ #define XML_SCHEMAS_ELEM_FIXED 1 << 3 /** * XML_SCHEMAS_ELEM_ABSTRACT: * * the element is abstract */ #define XML_SCHEMAS_ELEM_ABSTRACT 1 << 4 /** * XML_SCHEMAS_ELEM_TOPLEVEL: * * the element is top level * obsolete: use XML_SCHEMAS_ELEM_GLOBAL instead */ #define XML_SCHEMAS_ELEM_TOPLEVEL 1 << 5 /** * XML_SCHEMAS_ELEM_REF: * * the element is a reference to a type */ #define XML_SCHEMAS_ELEM_REF 1 << 6 /** * XML_SCHEMAS_ELEM_NSDEFAULT: * * allow elements in no namespace * Obsolete, not used anymore. */ #define XML_SCHEMAS_ELEM_NSDEFAULT 1 << 7 /** * XML_SCHEMAS_ELEM_INTERNAL_RESOLVED: * * this is set when "type", "ref", "substitutionGroup" * references have been resolved. */ #define XML_SCHEMAS_ELEM_INTERNAL_RESOLVED 1 << 8 /** * XML_SCHEMAS_ELEM_CIRCULAR: * * a helper flag for the search of circular references. */ #define XML_SCHEMAS_ELEM_CIRCULAR 1 << 9 /** * XML_SCHEMAS_ELEM_BLOCK_ABSENT: * * the "block" attribute is absent */ #define XML_SCHEMAS_ELEM_BLOCK_ABSENT 1 << 10 /** * XML_SCHEMAS_ELEM_BLOCK_EXTENSION: * * disallowed substitutions are absent */ #define XML_SCHEMAS_ELEM_BLOCK_EXTENSION 1 << 11 /** * XML_SCHEMAS_ELEM_BLOCK_RESTRICTION: * * disallowed substitutions: "restriction" */ #define XML_SCHEMAS_ELEM_BLOCK_RESTRICTION 1 << 12 /** * XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION: * * disallowed substitutions: "substitution" */ #define XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION 1 << 13 /** * XML_SCHEMAS_ELEM_FINAL_ABSENT: * * substitution group exclusions are absent */ #define XML_SCHEMAS_ELEM_FINAL_ABSENT 1 << 14 /** * XML_SCHEMAS_ELEM_FINAL_EXTENSION: * * substitution group exclusions: "extension" */ #define XML_SCHEMAS_ELEM_FINAL_EXTENSION 1 << 15 /** * XML_SCHEMAS_ELEM_FINAL_RESTRICTION: * * substitution group exclusions: "restriction" */ #define XML_SCHEMAS_ELEM_FINAL_RESTRICTION 1 << 16 /** * XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD: * * the declaration is a substitution group head */ #define XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD 1 << 17 /** * XML_SCHEMAS_ELEM_INTERNAL_CHECKED: * * this is set when the elem decl has been checked against * all constraints */ #define XML_SCHEMAS_ELEM_INTERNAL_CHECKED 1 << 18 typedef struct _xmlSchemaElement xmlSchemaElement; typedef xmlSchemaElement *xmlSchemaElementPtr; struct _xmlSchemaElement { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaType *next; /* Not used? */ const xmlChar *name; const xmlChar *id; /* Deprecated; not used */ const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlSchemaTypePtr subtypes; /* the type definition */ xmlSchemaAttributePtr attributes; xmlNodePtr node; int minOccurs; /* Deprecated; not used */ int maxOccurs; /* Deprecated; not used */ int flags; const xmlChar *targetNamespace; const xmlChar *namedType; const xmlChar *namedTypeNs; const xmlChar *substGroup; const xmlChar *substGroupNs; const xmlChar *scope; const xmlChar *value; /* The original value of the value constraint. */ struct _xmlSchemaElement *refDecl; /* This will now be used for the substitution group affiliation */ xmlRegexpPtr contModel; /* Obsolete for WXS, maybe used for RelaxNG */ xmlSchemaContentType contentType; const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaValPtr defVal; /* The compiled value constraint. */ void *idcs; /* The identity-constraint defs */ }; /* * XML_SCHEMAS_FACET_UNKNOWN: * * unknown facet handling */ #define XML_SCHEMAS_FACET_UNKNOWN 0 /* * XML_SCHEMAS_FACET_PRESERVE: * * preserve the type of the facet */ #define XML_SCHEMAS_FACET_PRESERVE 1 /* * XML_SCHEMAS_FACET_REPLACE: * * replace the type of the facet */ #define XML_SCHEMAS_FACET_REPLACE 2 /* * XML_SCHEMAS_FACET_COLLAPSE: * * collapse the types of the facet */ #define XML_SCHEMAS_FACET_COLLAPSE 3 /** * A facet definition. */ struct _xmlSchemaFacet { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaFacet *next;/* the next type if in a sequence ... */ const xmlChar *value; /* The original value */ const xmlChar *id; /* Obsolete */ xmlSchemaAnnotPtr annot; xmlNodePtr node; int fixed; /* XML_SCHEMAS_FACET_PRESERVE, etc. */ int whitespace; xmlSchemaValPtr val; /* The compiled value */ xmlRegexpPtr regexp; /* The regex for patterns */ }; /** * A notation definition. */ typedef struct _xmlSchemaNotation xmlSchemaNotation; typedef xmlSchemaNotation *xmlSchemaNotationPtr; struct _xmlSchemaNotation { xmlSchemaTypeType type; /* The kind of type */ const xmlChar *name; xmlSchemaAnnotPtr annot; const xmlChar *identifier; const xmlChar *targetNamespace; }; /* * TODO: Actually all those flags used for the schema should sit * on the schema parser context, since they are used only * during parsing an XML schema document, and not available * on the component level as per spec. */ /** * XML_SCHEMAS_QUALIF_ELEM: * * Reflects elementFormDefault == qualified in * an XML schema document. */ #define XML_SCHEMAS_QUALIF_ELEM 1 << 0 /** * XML_SCHEMAS_QUALIF_ATTR: * * Reflects attributeFormDefault == qualified in * an XML schema document. */ #define XML_SCHEMAS_QUALIF_ATTR 1 << 1 /** * XML_SCHEMAS_FINAL_DEFAULT_EXTENSION: * * the schema has "extension" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_EXTENSION 1 << 2 /** * XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION: * * the schema has "restriction" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION 1 << 3 /** * XML_SCHEMAS_FINAL_DEFAULT_LIST: * * the schema has "list" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_LIST 1 << 4 /** * XML_SCHEMAS_FINAL_DEFAULT_UNION: * * the schema has "union" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_UNION 1 << 5 /** * XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION: * * the schema has "extension" in the set of blockDefault. */ #define XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION 1 << 6 /** * XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION: * * the schema has "restriction" in the set of blockDefault. */ #define XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION 1 << 7 /** * XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION: * * the schema has "substitution" in the set of blockDefault. */ #define XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION 1 << 8 /** * XML_SCHEMAS_INCLUDING_CONVERT_NS: * * the schema is currently including an other schema with * no target namespace. */ #define XML_SCHEMAS_INCLUDING_CONVERT_NS 1 << 9 /** * _xmlSchema: * * A Schemas definition */ struct _xmlSchema { const xmlChar *name; /* schema name */ const xmlChar *targetNamespace; /* the target namespace */ const xmlChar *version; const xmlChar *id; /* Obsolete */ xmlDocPtr doc; xmlSchemaAnnotPtr annot; int flags; xmlHashTablePtr typeDecl; xmlHashTablePtr attrDecl; xmlHashTablePtr attrgrpDecl; xmlHashTablePtr elemDecl; xmlHashTablePtr notaDecl; xmlHashTablePtr schemasImports; void *_private; /* unused by the library for users or bindings */ xmlHashTablePtr groupDecl; xmlDictPtr dict; void *includes; /* the includes, this is opaque for now */ int preserve; /* whether to free the document */ int counter; /* used to give anonymous components unique names */ xmlHashTablePtr idcDef; /* All identity-constraint defs. */ void *volatiles; /* Obsolete */ }; XMLPUBFUN void xmlSchemaFreeType (xmlSchemaTypePtr type); XMLPUBFUN void xmlSchemaFreeWildcard(xmlSchemaWildcardPtr wildcard); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_SCHEMA_INTERNALS_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/schematron.h ================================================ /* * Summary: XML Schematron implementation * Description: interface to the XML Schematron validity checking. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMATRON_H__ #define __XML_SCHEMATRON_H__ #include #ifdef LIBXML_SCHEMATRON_ENABLED #include #ifdef __cplusplus extern "C" { #endif typedef enum { XML_SCHEMATRON_OUT_QUIET = 1 << 0, /* quiet no report */ XML_SCHEMATRON_OUT_TEXT = 1 << 1, /* build a textual report */ XML_SCHEMATRON_OUT_XML = 1 << 2, /* output SVRL */ XML_SCHEMATRON_OUT_ERROR = 1 << 3, /* output via xmlStructuredErrorFunc */ XML_SCHEMATRON_OUT_FILE = 1 << 8, /* output to a file descriptor */ XML_SCHEMATRON_OUT_BUFFER = 1 << 9, /* output to a buffer */ XML_SCHEMATRON_OUT_IO = 1 << 10 /* output to I/O mechanism */ } xmlSchematronValidOptions; /** * The schemas related types are kept internal */ typedef struct _xmlSchematron xmlSchematron; typedef xmlSchematron *xmlSchematronPtr; /** * xmlSchematronValidityErrorFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of an error callback from a Schematron validation */ typedef void (*xmlSchematronValidityErrorFunc) (void *ctx, const char *msg, ...); /** * xmlSchematronValidityWarningFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of a warning callback from a Schematron validation */ typedef void (*xmlSchematronValidityWarningFunc) (void *ctx, const char *msg, ...); /** * A schemas validation context */ typedef struct _xmlSchematronParserCtxt xmlSchematronParserCtxt; typedef xmlSchematronParserCtxt *xmlSchematronParserCtxtPtr; typedef struct _xmlSchematronValidCtxt xmlSchematronValidCtxt; typedef xmlSchematronValidCtxt *xmlSchematronValidCtxtPtr; /* * Interfaces for parsing. */ XMLPUBFUN xmlSchematronParserCtxtPtr xmlSchematronNewParserCtxt (const char *URL); XMLPUBFUN xmlSchematronParserCtxtPtr xmlSchematronNewMemParserCtxt(const char *buffer, int size); XMLPUBFUN xmlSchematronParserCtxtPtr xmlSchematronNewDocParserCtxt(xmlDocPtr doc); XMLPUBFUN void xmlSchematronFreeParserCtxt (xmlSchematronParserCtxtPtr ctxt); /***** XMLPUBFUN void xmlSchematronSetParserErrors(xmlSchematronParserCtxtPtr ctxt, xmlSchematronValidityErrorFunc err, xmlSchematronValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlSchematronGetParserErrors(xmlSchematronParserCtxtPtr ctxt, xmlSchematronValidityErrorFunc * err, xmlSchematronValidityWarningFunc * warn, void **ctx); XMLPUBFUN int xmlSchematronIsValid (xmlSchematronValidCtxtPtr ctxt); *****/ XMLPUBFUN xmlSchematronPtr xmlSchematronParse (xmlSchematronParserCtxtPtr ctxt); XMLPUBFUN void xmlSchematronFree (xmlSchematronPtr schema); /* * Interfaces for validating */ XMLPUBFUN void xmlSchematronSetValidStructuredErrors( xmlSchematronValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); /****** XMLPUBFUN void xmlSchematronSetValidErrors (xmlSchematronValidCtxtPtr ctxt, xmlSchematronValidityErrorFunc err, xmlSchematronValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlSchematronGetValidErrors (xmlSchematronValidCtxtPtr ctxt, xmlSchematronValidityErrorFunc *err, xmlSchematronValidityWarningFunc *warn, void **ctx); XMLPUBFUN int xmlSchematronSetValidOptions(xmlSchematronValidCtxtPtr ctxt, int options); XMLPUBFUN int xmlSchematronValidCtxtGetOptions(xmlSchematronValidCtxtPtr ctxt); XMLPUBFUN int xmlSchematronValidateOneElement (xmlSchematronValidCtxtPtr ctxt, xmlNodePtr elem); *******/ XMLPUBFUN xmlSchematronValidCtxtPtr xmlSchematronNewValidCtxt (xmlSchematronPtr schema, int options); XMLPUBFUN void xmlSchematronFreeValidCtxt (xmlSchematronValidCtxtPtr ctxt); XMLPUBFUN int xmlSchematronValidateDoc (xmlSchematronValidCtxtPtr ctxt, xmlDocPtr instance); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMATRON_ENABLED */ #endif /* __XML_SCHEMATRON_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/threads.h ================================================ /** * Summary: interfaces for thread handling * Description: set of generic threading related routines * should work with pthreads, Windows native or TLS threads * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_THREADS_H__ #define __XML_THREADS_H__ #include #ifdef __cplusplus extern "C" { #endif /* * xmlMutex are a simple mutual exception locks. */ typedef struct _xmlMutex xmlMutex; typedef xmlMutex *xmlMutexPtr; /* * xmlRMutex are reentrant mutual exception locks. */ typedef struct _xmlRMutex xmlRMutex; typedef xmlRMutex *xmlRMutexPtr; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif XMLPUBFUN xmlMutexPtr xmlNewMutex (void); XMLPUBFUN void xmlMutexLock (xmlMutexPtr tok); XMLPUBFUN void xmlMutexUnlock (xmlMutexPtr tok); XMLPUBFUN void xmlFreeMutex (xmlMutexPtr tok); XMLPUBFUN xmlRMutexPtr xmlNewRMutex (void); XMLPUBFUN void xmlRMutexLock (xmlRMutexPtr tok); XMLPUBFUN void xmlRMutexUnlock (xmlRMutexPtr tok); XMLPUBFUN void xmlFreeRMutex (xmlRMutexPtr tok); /* * Library wide APIs. */ XML_DEPRECATED XMLPUBFUN void xmlInitThreads (void); XMLPUBFUN void xmlLockLibrary (void); XMLPUBFUN void xmlUnlockLibrary(void); XML_DEPRECATED XMLPUBFUN int xmlGetThreadId (void); XML_DEPRECATED XMLPUBFUN int xmlIsMainThread (void); XML_DEPRECATED XMLPUBFUN void xmlCleanupThreads(void); XML_DEPRECATED XMLPUBFUN xmlGlobalStatePtr xmlGetGlobalState(void); /** DOC_DISABLE */ #if defined(LIBXML_THREAD_ENABLED) && defined(_WIN32) && \ !defined(HAVE_COMPILER_TLS) && defined(LIBXML_STATIC_FOR_DLL) int xmlDllMain(void *hinstDLL, unsigned long fdwReason, void *lpvReserved); #endif /** DOC_ENABLE */ #ifdef __cplusplus } #endif #endif /* __XML_THREADS_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/tree.h ================================================ /* * Summary: interfaces for tree manipulation * Description: this module describes the structures found in an tree resulting * from an XML or HTML parsing, as well as the API provided for * various processing on that tree * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_TREE_H__ #define __XML_TREE_H__ #include #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Some of the basic types pointer to structures: */ /* xmlIO.h */ typedef struct _xmlParserInputBuffer xmlParserInputBuffer; typedef xmlParserInputBuffer *xmlParserInputBufferPtr; typedef struct _xmlOutputBuffer xmlOutputBuffer; typedef xmlOutputBuffer *xmlOutputBufferPtr; /* parser.h */ typedef struct _xmlParserInput xmlParserInput; typedef xmlParserInput *xmlParserInputPtr; typedef struct _xmlParserCtxt xmlParserCtxt; typedef xmlParserCtxt *xmlParserCtxtPtr; typedef struct _xmlSAXLocator xmlSAXLocator; typedef xmlSAXLocator *xmlSAXLocatorPtr; typedef struct _xmlSAXHandler xmlSAXHandler; typedef xmlSAXHandler *xmlSAXHandlerPtr; /* entities.h */ typedef struct _xmlEntity xmlEntity; typedef xmlEntity *xmlEntityPtr; /** * BASE_BUFFER_SIZE: * * default buffer size 4000. */ #define BASE_BUFFER_SIZE 4096 /** * LIBXML_NAMESPACE_DICT: * * Defines experimental behaviour: * 1) xmlNs gets an additional field @context (a xmlDoc) * 2) when creating a tree, xmlNs->href is stored in the dict of xmlDoc. */ /* #define LIBXML_NAMESPACE_DICT */ /** * xmlBufferAllocationScheme: * * A buffer allocation scheme can be defined to either match exactly the * need or double it's allocated size each time it is found too small. */ typedef enum { XML_BUFFER_ALLOC_DOUBLEIT, /* double each time one need to grow */ XML_BUFFER_ALLOC_EXACT, /* grow only to the minimal size */ XML_BUFFER_ALLOC_IMMUTABLE, /* immutable buffer, deprecated */ XML_BUFFER_ALLOC_IO, /* special allocation scheme used for I/O */ XML_BUFFER_ALLOC_HYBRID, /* exact up to a threshold, and doubleit thereafter */ XML_BUFFER_ALLOC_BOUNDED /* limit the upper size of the buffer */ } xmlBufferAllocationScheme; /** * xmlBuffer: * * A buffer structure, this old construct is limited to 2GB and * is being deprecated, use API with xmlBuf instead */ typedef struct _xmlBuffer xmlBuffer; typedef xmlBuffer *xmlBufferPtr; struct _xmlBuffer { xmlChar *content; /* The buffer content UTF8 */ unsigned int use; /* The buffer size used */ unsigned int size; /* The buffer size */ xmlBufferAllocationScheme alloc; /* The realloc method */ xmlChar *contentIO; /* in IO mode we may have a different base */ }; /** * xmlBuf: * * A buffer structure, new one, the actual structure internals are not public */ typedef struct _xmlBuf xmlBuf; /** * xmlBufPtr: * * A pointer to a buffer structure, the actual structure internals are not * public */ typedef xmlBuf *xmlBufPtr; /* * A few public routines for xmlBuf. As those are expected to be used * mostly internally the bulk of the routines are internal in buf.h */ XMLPUBFUN xmlChar* xmlBufContent (const xmlBuf* buf); XMLPUBFUN xmlChar* xmlBufEnd (xmlBufPtr buf); XMLPUBFUN size_t xmlBufUse (const xmlBufPtr buf); XMLPUBFUN size_t xmlBufShrink (xmlBufPtr buf, size_t len); /* * LIBXML2_NEW_BUFFER: * * Macro used to express that the API use the new buffers for * xmlParserInputBuffer and xmlOutputBuffer. The change was * introduced in 2.9.0. */ #define LIBXML2_NEW_BUFFER /** * XML_XML_NAMESPACE: * * This is the namespace for the special xml: prefix predefined in the * XML Namespace specification. */ #define XML_XML_NAMESPACE \ (const xmlChar *) "http://www.w3.org/XML/1998/namespace" /** * XML_XML_ID: * * This is the name for the special xml:id attribute */ #define XML_XML_ID (const xmlChar *) "xml:id" /* * The different element types carried by an XML tree. * * NOTE: This is synchronized with DOM Level1 values * See http://www.w3.org/TR/REC-DOM-Level-1/ * * Actually this had diverged a bit, and now XML_DOCUMENT_TYPE_NODE should * be deprecated to use an XML_DTD_NODE. */ typedef enum { XML_ELEMENT_NODE= 1, XML_ATTRIBUTE_NODE= 2, XML_TEXT_NODE= 3, XML_CDATA_SECTION_NODE= 4, XML_ENTITY_REF_NODE= 5, XML_ENTITY_NODE= 6, XML_PI_NODE= 7, XML_COMMENT_NODE= 8, XML_DOCUMENT_NODE= 9, XML_DOCUMENT_TYPE_NODE= 10, XML_DOCUMENT_FRAG_NODE= 11, XML_NOTATION_NODE= 12, XML_HTML_DOCUMENT_NODE= 13, XML_DTD_NODE= 14, XML_ELEMENT_DECL= 15, XML_ATTRIBUTE_DECL= 16, XML_ENTITY_DECL= 17, XML_NAMESPACE_DECL= 18, XML_XINCLUDE_START= 19, XML_XINCLUDE_END= 20 /* XML_DOCB_DOCUMENT_NODE= 21 */ /* removed */ } xmlElementType; /** DOC_DISABLE */ /* For backward compatibility */ #define XML_DOCB_DOCUMENT_NODE 21 /** DOC_ENABLE */ /** * xmlNotation: * * A DTD Notation definition. */ typedef struct _xmlNotation xmlNotation; typedef xmlNotation *xmlNotationPtr; struct _xmlNotation { const xmlChar *name; /* Notation name */ const xmlChar *PublicID; /* Public identifier, if any */ const xmlChar *SystemID; /* System identifier, if any */ }; /** * xmlAttributeType: * * A DTD Attribute type definition. */ typedef enum { XML_ATTRIBUTE_CDATA = 1, XML_ATTRIBUTE_ID, XML_ATTRIBUTE_IDREF , XML_ATTRIBUTE_IDREFS, XML_ATTRIBUTE_ENTITY, XML_ATTRIBUTE_ENTITIES, XML_ATTRIBUTE_NMTOKEN, XML_ATTRIBUTE_NMTOKENS, XML_ATTRIBUTE_ENUMERATION, XML_ATTRIBUTE_NOTATION } xmlAttributeType; /** * xmlAttributeDefault: * * A DTD Attribute default definition. */ typedef enum { XML_ATTRIBUTE_NONE = 1, XML_ATTRIBUTE_REQUIRED, XML_ATTRIBUTE_IMPLIED, XML_ATTRIBUTE_FIXED } xmlAttributeDefault; /** * xmlEnumeration: * * List structure used when there is an enumeration in DTDs. */ typedef struct _xmlEnumeration xmlEnumeration; typedef xmlEnumeration *xmlEnumerationPtr; struct _xmlEnumeration { struct _xmlEnumeration *next; /* next one */ const xmlChar *name; /* Enumeration name */ }; /** * xmlAttribute: * * An Attribute declaration in a DTD. */ typedef struct _xmlAttribute xmlAttribute; typedef xmlAttribute *xmlAttributePtr; struct _xmlAttribute { void *_private; /* application data */ xmlElementType type; /* XML_ATTRIBUTE_DECL, must be second ! */ const xmlChar *name; /* Attribute name */ struct _xmlNode *children; /* NULL */ struct _xmlNode *last; /* NULL */ struct _xmlDtd *parent; /* -> DTD */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ struct _xmlAttribute *nexth; /* next in hash table */ xmlAttributeType atype; /* The attribute type */ xmlAttributeDefault def; /* the default */ const xmlChar *defaultValue; /* or the default value */ xmlEnumerationPtr tree; /* or the enumeration tree if any */ const xmlChar *prefix; /* the namespace prefix if any */ const xmlChar *elem; /* Element holding the attribute */ }; /** * xmlElementContentType: * * Possible definitions of element content types. */ typedef enum { XML_ELEMENT_CONTENT_PCDATA = 1, XML_ELEMENT_CONTENT_ELEMENT, XML_ELEMENT_CONTENT_SEQ, XML_ELEMENT_CONTENT_OR } xmlElementContentType; /** * xmlElementContentOccur: * * Possible definitions of element content occurrences. */ typedef enum { XML_ELEMENT_CONTENT_ONCE = 1, XML_ELEMENT_CONTENT_OPT, XML_ELEMENT_CONTENT_MULT, XML_ELEMENT_CONTENT_PLUS } xmlElementContentOccur; /** * xmlElementContent: * * An XML Element content as stored after parsing an element definition * in a DTD. */ typedef struct _xmlElementContent xmlElementContent; typedef xmlElementContent *xmlElementContentPtr; struct _xmlElementContent { xmlElementContentType type; /* PCDATA, ELEMENT, SEQ or OR */ xmlElementContentOccur ocur; /* ONCE, OPT, MULT or PLUS */ const xmlChar *name; /* Element name */ struct _xmlElementContent *c1; /* first child */ struct _xmlElementContent *c2; /* second child */ struct _xmlElementContent *parent; /* parent */ const xmlChar *prefix; /* Namespace prefix */ }; /** * xmlElementTypeVal: * * The different possibilities for an element content type. */ typedef enum { XML_ELEMENT_TYPE_UNDEFINED = 0, XML_ELEMENT_TYPE_EMPTY = 1, XML_ELEMENT_TYPE_ANY, XML_ELEMENT_TYPE_MIXED, XML_ELEMENT_TYPE_ELEMENT } xmlElementTypeVal; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif /** * xmlElement: * * An XML Element declaration from a DTD. */ typedef struct _xmlElement xmlElement; typedef xmlElement *xmlElementPtr; struct _xmlElement { void *_private; /* application data */ xmlElementType type; /* XML_ELEMENT_DECL, must be second ! */ const xmlChar *name; /* Element name */ struct _xmlNode *children; /* NULL */ struct _xmlNode *last; /* NULL */ struct _xmlDtd *parent; /* -> DTD */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ xmlElementTypeVal etype; /* The type */ xmlElementContentPtr content; /* the allowed element content */ xmlAttributePtr attributes; /* List of the declared attributes */ const xmlChar *prefix; /* the namespace prefix if any */ #ifdef LIBXML_REGEXP_ENABLED xmlRegexpPtr contModel; /* the validating regexp */ #else void *contModel; #endif }; /** * XML_LOCAL_NAMESPACE: * * A namespace declaration node. */ #define XML_LOCAL_NAMESPACE XML_NAMESPACE_DECL typedef xmlElementType xmlNsType; /** * xmlNs: * * An XML namespace. * Note that prefix == NULL is valid, it defines the default namespace * within the subtree (until overridden). * * xmlNsType is unified with xmlElementType. */ typedef struct _xmlNs xmlNs; typedef xmlNs *xmlNsPtr; struct _xmlNs { struct _xmlNs *next; /* next Ns link for this node */ xmlNsType type; /* global or local */ const xmlChar *href; /* URL for the namespace */ const xmlChar *prefix; /* prefix for the namespace */ void *_private; /* application data */ struct _xmlDoc *context; /* normally an xmlDoc */ }; /** * xmlDtd: * * An XML DTD, as defined by parent link */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ /* End of common part */ void *notations; /* Hash table for notations if any */ void *elements; /* Hash table for elements if any */ void *attributes; /* Hash table for attributes if any */ void *entities; /* Hash table for entities if any */ const xmlChar *ExternalID; /* External identifier for PUBLIC DTD */ const xmlChar *SystemID; /* URI for a SYSTEM or PUBLIC DTD */ void *pentities; /* Hash table for param entities if any */ }; /** * xmlAttr: * * An attribute on an XML node. */ typedef struct _xmlAttr xmlAttr; typedef xmlAttr *xmlAttrPtr; struct _xmlAttr { void *_private; /* application data */ xmlElementType type; /* XML_ATTRIBUTE_NODE, must be second ! */ const xmlChar *name; /* the name of the property */ struct _xmlNode *children; /* the value of the property */ struct _xmlNode *last; /* NULL */ struct _xmlNode *parent; /* child->parent link */ struct _xmlAttr *next; /* next sibling link */ struct _xmlAttr *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ xmlNs *ns; /* pointer to the associated namespace */ xmlAttributeType atype; /* the attribute type if validating */ void *psvi; /* for type/PSVI information */ }; /** * xmlID: * * An XML ID instance. */ typedef struct _xmlID xmlID; typedef xmlID *xmlIDPtr; struct _xmlID { struct _xmlID *next; /* next ID */ const xmlChar *value; /* The ID name */ xmlAttrPtr attr; /* The attribute holding it */ const xmlChar *name; /* The attribute if attr is not available */ int lineno; /* The line number if attr is not available */ struct _xmlDoc *doc; /* The document holding the ID */ }; /** * xmlRef: * * An XML IDREF instance. */ typedef struct _xmlRef xmlRef; typedef xmlRef *xmlRefPtr; struct _xmlRef { struct _xmlRef *next; /* next Ref */ const xmlChar *value; /* The Ref name */ xmlAttrPtr attr; /* The attribute holding it */ const xmlChar *name; /* The attribute if attr is not available */ int lineno; /* The line number if attr is not available */ }; /** * xmlNode: * * A node in an XML tree. */ typedef struct _xmlNode xmlNode; typedef xmlNode *xmlNodePtr; struct _xmlNode { void *_private; /* application data */ xmlElementType type; /* type number, must be second ! */ const xmlChar *name; /* the name of the node, or the entity */ struct _xmlNode *children; /* parent->childs link */ struct _xmlNode *last; /* last child link */ struct _xmlNode *parent; /* child->parent link */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ /* End of common part */ xmlNs *ns; /* pointer to the associated namespace */ xmlChar *content; /* the content */ struct _xmlAttr *properties;/* properties list */ xmlNs *nsDef; /* namespace definitions on this node */ void *psvi; /* for type/PSVI information */ unsigned short line; /* line number */ unsigned short extra; /* extra data for XPath/XSLT */ }; /** * XML_GET_CONTENT: * * Macro to extract the content pointer of a node. */ #define XML_GET_CONTENT(n) \ ((n)->type == XML_ELEMENT_NODE ? NULL : (n)->content) /** * XML_GET_LINE: * * Macro to extract the line number of an element node. */ #define XML_GET_LINE(n) \ (xmlGetLineNo(n)) /** * xmlDocProperty * * Set of properties of the document as found by the parser * Some of them are linked to similarly named xmlParserOption */ typedef enum { XML_DOC_WELLFORMED = 1<<0, /* document is XML well formed */ XML_DOC_NSVALID = 1<<1, /* document is Namespace valid */ XML_DOC_OLD10 = 1<<2, /* parsed with old XML-1.0 parser */ XML_DOC_DTDVALID = 1<<3, /* DTD validation was successful */ XML_DOC_XINCLUDE = 1<<4, /* XInclude substitution was done */ XML_DOC_USERBUILT = 1<<5, /* Document was built using the API and not by parsing an instance */ XML_DOC_INTERNAL = 1<<6, /* built for internal processing */ XML_DOC_HTML = 1<<7 /* parsed or built HTML document */ } xmlDocProperties; /** * xmlDoc: * * An XML document. */ typedef struct _xmlDoc xmlDoc; typedef xmlDoc *xmlDocPtr; struct _xmlDoc { void *_private; /* application data */ xmlElementType type; /* XML_DOCUMENT_NODE, must be second ! */ char *name; /* name/filename/URI of the document */ struct _xmlNode *children; /* the document tree */ struct _xmlNode *last; /* last child link */ struct _xmlNode *parent; /* child->parent link */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* autoreference to itself */ /* End of common part */ int compression;/* level of zlib compression */ int standalone; /* standalone document (no external refs) 1 if standalone="yes" 0 if standalone="no" -1 if there is no XML declaration -2 if there is an XML declaration, but no standalone attribute was specified */ struct _xmlDtd *intSubset; /* the document internal subset */ struct _xmlDtd *extSubset; /* the document external subset */ struct _xmlNs *oldNs; /* Global namespace, the old way */ const xmlChar *version; /* the XML version string */ const xmlChar *encoding; /* external initial encoding, if any */ void *ids; /* Hash table for ID attributes if any */ void *refs; /* Hash table for IDREFs attributes if any */ const xmlChar *URL; /* The URI for that document */ int charset; /* Internal flag for charset handling, actually an xmlCharEncoding */ struct _xmlDict *dict; /* dict used to allocate names or NULL */ void *psvi; /* for type/PSVI information */ int parseFlags; /* set of xmlParserOption used to parse the document */ int properties; /* set of xmlDocProperties for this document set at the end of parsing */ }; typedef struct _xmlDOMWrapCtxt xmlDOMWrapCtxt; typedef xmlDOMWrapCtxt *xmlDOMWrapCtxtPtr; /** * xmlDOMWrapAcquireNsFunction: * @ctxt: a DOM wrapper context * @node: the context node (element or attribute) * @nsName: the requested namespace name * @nsPrefix: the requested namespace prefix * * A function called to acquire namespaces (xmlNs) from the wrapper. * * Returns an xmlNsPtr or NULL in case of an error. */ typedef xmlNsPtr (*xmlDOMWrapAcquireNsFunction) (xmlDOMWrapCtxtPtr ctxt, xmlNodePtr node, const xmlChar *nsName, const xmlChar *nsPrefix); /** * xmlDOMWrapCtxt: * * Context for DOM wrapper-operations. */ struct _xmlDOMWrapCtxt { void * _private; /* * The type of this context, just in case we need specialized * contexts in the future. */ int type; /* * Internal namespace map used for various operations. */ void * namespaceMap; /* * Use this one to acquire an xmlNsPtr intended for node->ns. * (Note that this is not intended for elem->nsDef). */ xmlDOMWrapAcquireNsFunction getNsForNodeFunc; }; /** * xmlChildrenNode: * * Macro for compatibility naming layer with libxml1. Maps * to "children." */ #ifndef xmlChildrenNode #define xmlChildrenNode children #endif /** * xmlRootNode: * * Macro for compatibility naming layer with libxml1. Maps * to "children". */ #ifndef xmlRootNode #define xmlRootNode children #endif /* * Variables. */ /* * Some helper functions */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_DEBUG_ENABLED) || \ defined (LIBXML_HTML_ENABLED) || defined(LIBXML_SAX1_ENABLED) || \ defined(LIBXML_HTML_ENABLED) || defined(LIBXML_WRITER_ENABLED) || \ defined(LIBXML_LEGACY_ENABLED) XMLPUBFUN int xmlValidateNCName (const xmlChar *value, int space); #endif #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN int xmlValidateQName (const xmlChar *value, int space); XMLPUBFUN int xmlValidateName (const xmlChar *value, int space); XMLPUBFUN int xmlValidateNMToken (const xmlChar *value, int space); #endif XMLPUBFUN xmlChar * xmlBuildQName (const xmlChar *ncname, const xmlChar *prefix, xmlChar *memory, int len); XMLPUBFUN xmlChar * xmlSplitQName2 (const xmlChar *name, xmlChar **prefix); XMLPUBFUN const xmlChar * xmlSplitQName3 (const xmlChar *name, int *len); /* * Handling Buffers, the old ones see @xmlBuf for the new ones. */ XMLPUBFUN void xmlSetBufferAllocationScheme(xmlBufferAllocationScheme scheme); XMLPUBFUN xmlBufferAllocationScheme xmlGetBufferAllocationScheme(void); XMLPUBFUN xmlBufferPtr xmlBufferCreate (void); XMLPUBFUN xmlBufferPtr xmlBufferCreateSize (size_t size); XMLPUBFUN xmlBufferPtr xmlBufferCreateStatic (void *mem, size_t size); XMLPUBFUN int xmlBufferResize (xmlBufferPtr buf, unsigned int size); XMLPUBFUN void xmlBufferFree (xmlBufferPtr buf); XMLPUBFUN int xmlBufferDump (FILE *file, xmlBufferPtr buf); XMLPUBFUN int xmlBufferAdd (xmlBufferPtr buf, const xmlChar *str, int len); XMLPUBFUN int xmlBufferAddHead (xmlBufferPtr buf, const xmlChar *str, int len); XMLPUBFUN int xmlBufferCat (xmlBufferPtr buf, const xmlChar *str); XMLPUBFUN int xmlBufferCCat (xmlBufferPtr buf, const char *str); XMLPUBFUN int xmlBufferShrink (xmlBufferPtr buf, unsigned int len); XMLPUBFUN int xmlBufferGrow (xmlBufferPtr buf, unsigned int len); XMLPUBFUN void xmlBufferEmpty (xmlBufferPtr buf); XMLPUBFUN const xmlChar* xmlBufferContent (const xmlBuffer *buf); XMLPUBFUN xmlChar* xmlBufferDetach (xmlBufferPtr buf); XMLPUBFUN void xmlBufferSetAllocationScheme(xmlBufferPtr buf, xmlBufferAllocationScheme scheme); XMLPUBFUN int xmlBufferLength (const xmlBuffer *buf); /* * Creating/freeing new structures. */ XMLPUBFUN xmlDtdPtr xmlCreateIntSubset (xmlDocPtr doc, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlNewDtd (xmlDocPtr doc, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlGetIntSubset (const xmlDoc *doc); XMLPUBFUN void xmlFreeDtd (xmlDtdPtr cur); #ifdef LIBXML_LEGACY_ENABLED XML_DEPRECATED XMLPUBFUN xmlNsPtr xmlNewGlobalNs (xmlDocPtr doc, const xmlChar *href, const xmlChar *prefix); #endif /* LIBXML_LEGACY_ENABLED */ XMLPUBFUN xmlNsPtr xmlNewNs (xmlNodePtr node, const xmlChar *href, const xmlChar *prefix); XMLPUBFUN void xmlFreeNs (xmlNsPtr cur); XMLPUBFUN void xmlFreeNsList (xmlNsPtr cur); XMLPUBFUN xmlDocPtr xmlNewDoc (const xmlChar *version); XMLPUBFUN void xmlFreeDoc (xmlDocPtr cur); XMLPUBFUN xmlAttrPtr xmlNewDocProp (xmlDocPtr doc, const xmlChar *name, const xmlChar *value); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlAttrPtr xmlNewProp (xmlNodePtr node, const xmlChar *name, const xmlChar *value); #endif XMLPUBFUN xmlAttrPtr xmlNewNsProp (xmlNodePtr node, xmlNsPtr ns, const xmlChar *name, const xmlChar *value); XMLPUBFUN xmlAttrPtr xmlNewNsPropEatName (xmlNodePtr node, xmlNsPtr ns, xmlChar *name, const xmlChar *value); XMLPUBFUN void xmlFreePropList (xmlAttrPtr cur); XMLPUBFUN void xmlFreeProp (xmlAttrPtr cur); XMLPUBFUN xmlAttrPtr xmlCopyProp (xmlNodePtr target, xmlAttrPtr cur); XMLPUBFUN xmlAttrPtr xmlCopyPropList (xmlNodePtr target, xmlAttrPtr cur); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlDtdPtr xmlCopyDtd (xmlDtdPtr dtd); #endif /* LIBXML_TREE_ENABLED */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlDocPtr xmlCopyDoc (xmlDocPtr doc, int recursive); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) */ /* * Creating new nodes. */ XMLPUBFUN xmlNodePtr xmlNewDocNode (xmlDocPtr doc, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocNodeEatName (xmlDocPtr doc, xmlNsPtr ns, xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewNode (xmlNsPtr ns, const xmlChar *name); XMLPUBFUN xmlNodePtr xmlNewNodeEatName (xmlNsPtr ns, xmlChar *name); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlNodePtr xmlNewChild (xmlNodePtr parent, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); #endif XMLPUBFUN xmlNodePtr xmlNewDocText (const xmlDoc *doc, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewText (const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocPI (xmlDocPtr doc, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewPI (const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocTextLen (xmlDocPtr doc, const xmlChar *content, int len); XMLPUBFUN xmlNodePtr xmlNewTextLen (const xmlChar *content, int len); XMLPUBFUN xmlNodePtr xmlNewDocComment (xmlDocPtr doc, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewComment (const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewCDataBlock (xmlDocPtr doc, const xmlChar *content, int len); XMLPUBFUN xmlNodePtr xmlNewCharRef (xmlDocPtr doc, const xmlChar *name); XMLPUBFUN xmlNodePtr xmlNewReference (const xmlDoc *doc, const xmlChar *name); XMLPUBFUN xmlNodePtr xmlCopyNode (xmlNodePtr node, int recursive); XMLPUBFUN xmlNodePtr xmlDocCopyNode (xmlNodePtr node, xmlDocPtr doc, int recursive); XMLPUBFUN xmlNodePtr xmlDocCopyNodeList (xmlDocPtr doc, xmlNodePtr node); XMLPUBFUN xmlNodePtr xmlCopyNodeList (xmlNodePtr node); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlNodePtr xmlNewTextChild (xmlNodePtr parent, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocRawNode (xmlDocPtr doc, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocFragment (xmlDocPtr doc); #endif /* LIBXML_TREE_ENABLED */ /* * Navigating. */ XMLPUBFUN long xmlGetLineNo (const xmlNode *node); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) XMLPUBFUN xmlChar * xmlGetNodePath (const xmlNode *node); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) */ XMLPUBFUN xmlNodePtr xmlDocGetRootElement (const xmlDoc *doc); XMLPUBFUN xmlNodePtr xmlGetLastChild (const xmlNode *parent); XMLPUBFUN int xmlNodeIsText (const xmlNode *node); XMLPUBFUN int xmlIsBlankNode (const xmlNode *node); /* * Changing the structure. */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) XMLPUBFUN xmlNodePtr xmlDocSetRootElement (xmlDocPtr doc, xmlNodePtr root); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */ #ifdef LIBXML_TREE_ENABLED XMLPUBFUN void xmlNodeSetName (xmlNodePtr cur, const xmlChar *name); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN xmlNodePtr xmlAddChild (xmlNodePtr parent, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlAddChildList (xmlNodePtr parent, xmlNodePtr cur); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) XMLPUBFUN xmlNodePtr xmlReplaceNode (xmlNodePtr old, xmlNodePtr cur); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) XMLPUBFUN xmlNodePtr xmlAddPrevSibling (xmlNodePtr cur, xmlNodePtr elem); #endif /* LIBXML_TREE_ENABLED || LIBXML_HTML_ENABLED || LIBXML_SCHEMAS_ENABLED */ XMLPUBFUN xmlNodePtr xmlAddSibling (xmlNodePtr cur, xmlNodePtr elem); XMLPUBFUN xmlNodePtr xmlAddNextSibling (xmlNodePtr cur, xmlNodePtr elem); XMLPUBFUN void xmlUnlinkNode (xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlTextMerge (xmlNodePtr first, xmlNodePtr second); XMLPUBFUN int xmlTextConcat (xmlNodePtr node, const xmlChar *content, int len); XMLPUBFUN void xmlFreeNodeList (xmlNodePtr cur); XMLPUBFUN void xmlFreeNode (xmlNodePtr cur); XMLPUBFUN void xmlSetTreeDoc (xmlNodePtr tree, xmlDocPtr doc); XMLPUBFUN void xmlSetListDoc (xmlNodePtr list, xmlDocPtr doc); /* * Namespaces. */ XMLPUBFUN xmlNsPtr xmlSearchNs (xmlDocPtr doc, xmlNodePtr node, const xmlChar *nameSpace); XMLPUBFUN xmlNsPtr xmlSearchNsByHref (xmlDocPtr doc, xmlNodePtr node, const xmlChar *href); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlNsPtr * xmlGetNsList (const xmlDoc *doc, const xmlNode *node); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) */ XMLPUBFUN void xmlSetNs (xmlNodePtr node, xmlNsPtr ns); XMLPUBFUN xmlNsPtr xmlCopyNamespace (xmlNsPtr cur); XMLPUBFUN xmlNsPtr xmlCopyNamespaceList (xmlNsPtr cur); /* * Changing the content. */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) XMLPUBFUN xmlAttrPtr xmlSetProp (xmlNodePtr node, const xmlChar *name, const xmlChar *value); XMLPUBFUN xmlAttrPtr xmlSetNsProp (xmlNodePtr node, xmlNsPtr ns, const xmlChar *name, const xmlChar *value); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) */ XMLPUBFUN xmlChar * xmlGetNoNsProp (const xmlNode *node, const xmlChar *name); XMLPUBFUN xmlChar * xmlGetProp (const xmlNode *node, const xmlChar *name); XMLPUBFUN xmlAttrPtr xmlHasProp (const xmlNode *node, const xmlChar *name); XMLPUBFUN xmlAttrPtr xmlHasNsProp (const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace); XMLPUBFUN xmlChar * xmlGetNsProp (const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace); XMLPUBFUN xmlNodePtr xmlStringGetNodeList (const xmlDoc *doc, const xmlChar *value); XMLPUBFUN xmlNodePtr xmlStringLenGetNodeList (const xmlDoc *doc, const xmlChar *value, int len); XMLPUBFUN xmlChar * xmlNodeListGetString (xmlDocPtr doc, const xmlNode *list, int inLine); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlChar * xmlNodeListGetRawString (const xmlDoc *doc, const xmlNode *list, int inLine); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlNodeSetContent (xmlNodePtr cur, const xmlChar *content); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN void xmlNodeSetContentLen (xmlNodePtr cur, const xmlChar *content, int len); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlNodeAddContent (xmlNodePtr cur, const xmlChar *content); XMLPUBFUN void xmlNodeAddContentLen (xmlNodePtr cur, const xmlChar *content, int len); XMLPUBFUN xmlChar * xmlNodeGetContent (const xmlNode *cur); XMLPUBFUN int xmlNodeBufGetContent (xmlBufferPtr buffer, const xmlNode *cur); XMLPUBFUN int xmlBufGetNodeContent (xmlBufPtr buf, const xmlNode *cur); XMLPUBFUN xmlChar * xmlNodeGetLang (const xmlNode *cur); XMLPUBFUN int xmlNodeGetSpacePreserve (const xmlNode *cur); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN void xmlNodeSetLang (xmlNodePtr cur, const xmlChar *lang); XMLPUBFUN void xmlNodeSetSpacePreserve (xmlNodePtr cur, int val); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN xmlChar * xmlNodeGetBase (const xmlDoc *doc, const xmlNode *cur); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) XMLPUBFUN void xmlNodeSetBase (xmlNodePtr cur, const xmlChar *uri); #endif /* * Removing content. */ XMLPUBFUN int xmlRemoveProp (xmlAttrPtr cur); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN int xmlUnsetNsProp (xmlNodePtr node, xmlNsPtr ns, const xmlChar *name); XMLPUBFUN int xmlUnsetProp (xmlNodePtr node, const xmlChar *name); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) */ /* * Internal, don't use. */ XMLPUBFUN void xmlBufferWriteCHAR (xmlBufferPtr buf, const xmlChar *string); XMLPUBFUN void xmlBufferWriteChar (xmlBufferPtr buf, const char *string); XMLPUBFUN void xmlBufferWriteQuotedString(xmlBufferPtr buf, const xmlChar *string); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlAttrSerializeTxtContent(xmlBufferPtr buf, xmlDocPtr doc, xmlAttrPtr attr, const xmlChar *string); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_TREE_ENABLED /* * Namespace handling. */ XMLPUBFUN int xmlReconciliateNs (xmlDocPtr doc, xmlNodePtr tree); #endif #ifdef LIBXML_OUTPUT_ENABLED /* * Saving. */ XMLPUBFUN void xmlDocDumpFormatMemory (xmlDocPtr cur, xmlChar **mem, int *size, int format); XMLPUBFUN void xmlDocDumpMemory (xmlDocPtr cur, xmlChar **mem, int *size); XMLPUBFUN void xmlDocDumpMemoryEnc (xmlDocPtr out_doc, xmlChar **doc_txt_ptr, int * doc_txt_len, const char *txt_encoding); XMLPUBFUN void xmlDocDumpFormatMemoryEnc(xmlDocPtr out_doc, xmlChar **doc_txt_ptr, int * doc_txt_len, const char *txt_encoding, int format); XMLPUBFUN int xmlDocFormatDump (FILE *f, xmlDocPtr cur, int format); XMLPUBFUN int xmlDocDump (FILE *f, xmlDocPtr cur); XMLPUBFUN void xmlElemDump (FILE *f, xmlDocPtr doc, xmlNodePtr cur); XMLPUBFUN int xmlSaveFile (const char *filename, xmlDocPtr cur); XMLPUBFUN int xmlSaveFormatFile (const char *filename, xmlDocPtr cur, int format); XMLPUBFUN size_t xmlBufNodeDump (xmlBufPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format); XMLPUBFUN int xmlNodeDump (xmlBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format); XMLPUBFUN int xmlSaveFileTo (xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding); XMLPUBFUN int xmlSaveFormatFileTo (xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN void xmlNodeDumpOutput (xmlOutputBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format, const char *encoding); XMLPUBFUN int xmlSaveFormatFileEnc (const char *filename, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN int xmlSaveFileEnc (const char *filename, xmlDocPtr cur, const char *encoding); #endif /* LIBXML_OUTPUT_ENABLED */ /* * XHTML */ XMLPUBFUN int xmlIsXHTML (const xmlChar *systemID, const xmlChar *publicID); /* * Compression. */ XMLPUBFUN int xmlGetDocCompressMode (const xmlDoc *doc); XMLPUBFUN void xmlSetDocCompressMode (xmlDocPtr doc, int mode); XMLPUBFUN int xmlGetCompressMode (void); XMLPUBFUN void xmlSetCompressMode (int mode); /* * DOM-wrapper helper functions. */ XMLPUBFUN xmlDOMWrapCtxtPtr xmlDOMWrapNewCtxt (void); XMLPUBFUN void xmlDOMWrapFreeCtxt (xmlDOMWrapCtxtPtr ctxt); XMLPUBFUN int xmlDOMWrapReconcileNamespaces(xmlDOMWrapCtxtPtr ctxt, xmlNodePtr elem, int options); XMLPUBFUN int xmlDOMWrapAdoptNode (xmlDOMWrapCtxtPtr ctxt, xmlDocPtr sourceDoc, xmlNodePtr node, xmlDocPtr destDoc, xmlNodePtr destParent, int options); XMLPUBFUN int xmlDOMWrapRemoveNode (xmlDOMWrapCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr node, int options); XMLPUBFUN int xmlDOMWrapCloneNode (xmlDOMWrapCtxtPtr ctxt, xmlDocPtr sourceDoc, xmlNodePtr node, xmlNodePtr *clonedNode, xmlDocPtr destDoc, xmlNodePtr destParent, int deep, int options); #ifdef LIBXML_TREE_ENABLED /* * 5 interfaces from DOM ElementTraversal, but different in entities * traversal. */ XMLPUBFUN unsigned long xmlChildElementCount (xmlNodePtr parent); XMLPUBFUN xmlNodePtr xmlNextElementSibling (xmlNodePtr node); XMLPUBFUN xmlNodePtr xmlFirstElementChild (xmlNodePtr parent); XMLPUBFUN xmlNodePtr xmlLastElementChild (xmlNodePtr parent); XMLPUBFUN xmlNodePtr xmlPreviousElementSibling (xmlNodePtr node); #endif #ifdef __cplusplus } #endif #ifndef __XML_PARSER_H__ #include #endif #endif /* __XML_TREE_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/uri.h ================================================ /** * Summary: library of generic URI related routines * Description: library of generic URI related routines * Implements RFC 2396 * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_URI_H__ #define __XML_URI_H__ #include #include #ifdef __cplusplus extern "C" { #endif /** * xmlURI: * * A parsed URI reference. This is a struct containing the various fields * as described in RFC 2396 but separated for further processing. * * Note: query is a deprecated field which is incorrectly unescaped. * query_raw takes precedence over query if the former is set. * See: http://mail.gnome.org/archives/xml/2007-April/thread.html#00127 */ typedef struct _xmlURI xmlURI; typedef xmlURI *xmlURIPtr; struct _xmlURI { char *scheme; /* the URI scheme */ char *opaque; /* opaque part */ char *authority; /* the authority part */ char *server; /* the server part */ char *user; /* the user part */ int port; /* the port number */ char *path; /* the path string */ char *query; /* the query string (deprecated - use with caution) */ char *fragment; /* the fragment identifier */ int cleanup; /* parsing potentially unclean URI */ char *query_raw; /* the query string (as it appears in the URI) */ }; /* * This function is in tree.h: * xmlChar * xmlNodeGetBase (xmlDocPtr doc, * xmlNodePtr cur); */ XMLPUBFUN xmlURIPtr xmlCreateURI (void); XMLPUBFUN xmlChar * xmlBuildURI (const xmlChar *URI, const xmlChar *base); XMLPUBFUN xmlChar * xmlBuildRelativeURI (const xmlChar *URI, const xmlChar *base); XMLPUBFUN xmlURIPtr xmlParseURI (const char *str); XMLPUBFUN xmlURIPtr xmlParseURIRaw (const char *str, int raw); XMLPUBFUN int xmlParseURIReference (xmlURIPtr uri, const char *str); XMLPUBFUN xmlChar * xmlSaveUri (xmlURIPtr uri); XMLPUBFUN void xmlPrintURI (FILE *stream, xmlURIPtr uri); XMLPUBFUN xmlChar * xmlURIEscapeStr (const xmlChar *str, const xmlChar *list); XMLPUBFUN char * xmlURIUnescapeString (const char *str, int len, char *target); XMLPUBFUN int xmlNormalizeURIPath (char *path); XMLPUBFUN xmlChar * xmlURIEscape (const xmlChar *str); XMLPUBFUN void xmlFreeURI (xmlURIPtr uri); XMLPUBFUN xmlChar* xmlCanonicPath (const xmlChar *path); XMLPUBFUN xmlChar* xmlPathToURI (const xmlChar *path); #ifdef __cplusplus } #endif #endif /* __XML_URI_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/valid.h ================================================ /* * Summary: The DTD validation * Description: API for the DTD handling and the validity checking * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_VALID_H__ #define __XML_VALID_H__ #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Validation state added for non-determinist content model. */ typedef struct _xmlValidState xmlValidState; typedef xmlValidState *xmlValidStatePtr; /** * xmlValidityErrorFunc: * @ctx: usually an xmlValidCtxtPtr to a validity error context, * but comes from ctxt->userData (which normally contains such * a pointer); ctxt->userData can be changed by the user. * @msg: the string to format *printf like vararg * @...: remaining arguments to the format * * Callback called when a validity error is found. This is a message * oriented function similar to an *printf function. */ typedef void (*xmlValidityErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlValidityWarningFunc: * @ctx: usually an xmlValidCtxtPtr to a validity error context, * but comes from ctxt->userData (which normally contains such * a pointer); ctxt->userData can be changed by the user. * @msg: the string to format *printf like vararg * @...: remaining arguments to the format * * Callback called when a validity warning is found. This is a message * oriented function similar to an *printf function. */ typedef void (*xmlValidityWarningFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /* * xmlValidCtxt: * An xmlValidCtxt is used for error reporting when validating. */ typedef struct _xmlValidCtxt xmlValidCtxt; typedef xmlValidCtxt *xmlValidCtxtPtr; struct _xmlValidCtxt { void *userData; /* user specific data block */ xmlValidityErrorFunc error; /* the callback in case of errors */ xmlValidityWarningFunc warning; /* the callback in case of warning */ /* Node analysis stack used when validating within entities */ xmlNodePtr node; /* Current parsed Node */ int nodeNr; /* Depth of the parsing stack */ int nodeMax; /* Max depth of the parsing stack */ xmlNodePtr *nodeTab; /* array of nodes */ unsigned int flags; /* internal flags */ xmlDocPtr doc; /* the document */ int valid; /* temporary validity check result */ /* state state used for non-determinist content validation */ xmlValidState *vstate; /* current state */ int vstateNr; /* Depth of the validation stack */ int vstateMax; /* Max depth of the validation stack */ xmlValidState *vstateTab; /* array of validation states */ #ifdef LIBXML_REGEXP_ENABLED xmlAutomataPtr am; /* the automata */ xmlAutomataStatePtr state; /* used to build the automata */ #else void *am; void *state; #endif }; /* * ALL notation declarations are stored in a table. * There is one table per DTD. */ typedef struct _xmlHashTable xmlNotationTable; typedef xmlNotationTable *xmlNotationTablePtr; /* * ALL element declarations are stored in a table. * There is one table per DTD. */ typedef struct _xmlHashTable xmlElementTable; typedef xmlElementTable *xmlElementTablePtr; /* * ALL attribute declarations are stored in a table. * There is one table per DTD. */ typedef struct _xmlHashTable xmlAttributeTable; typedef xmlAttributeTable *xmlAttributeTablePtr; /* * ALL IDs attributes are stored in a table. * There is one table per document. */ typedef struct _xmlHashTable xmlIDTable; typedef xmlIDTable *xmlIDTablePtr; /* * ALL Refs attributes are stored in a table. * There is one table per document. */ typedef struct _xmlHashTable xmlRefTable; typedef xmlRefTable *xmlRefTablePtr; /* Notation */ XMLPUBFUN xmlNotationPtr xmlAddNotationDecl (xmlValidCtxtPtr ctxt, xmlDtdPtr dtd, const xmlChar *name, const xmlChar *PublicID, const xmlChar *SystemID); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlNotationTablePtr xmlCopyNotationTable (xmlNotationTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeNotationTable (xmlNotationTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpNotationDecl (xmlBufferPtr buf, xmlNotationPtr nota); XMLPUBFUN void xmlDumpNotationTable (xmlBufferPtr buf, xmlNotationTablePtr table); #endif /* LIBXML_OUTPUT_ENABLED */ /* Element Content */ /* the non Doc version are being deprecated */ XMLPUBFUN xmlElementContentPtr xmlNewElementContent (const xmlChar *name, xmlElementContentType type); XMLPUBFUN xmlElementContentPtr xmlCopyElementContent (xmlElementContentPtr content); XMLPUBFUN void xmlFreeElementContent (xmlElementContentPtr cur); /* the new versions with doc argument */ XMLPUBFUN xmlElementContentPtr xmlNewDocElementContent (xmlDocPtr doc, const xmlChar *name, xmlElementContentType type); XMLPUBFUN xmlElementContentPtr xmlCopyDocElementContent(xmlDocPtr doc, xmlElementContentPtr content); XMLPUBFUN void xmlFreeDocElementContent(xmlDocPtr doc, xmlElementContentPtr cur); XMLPUBFUN void xmlSnprintfElementContent(char *buf, int size, xmlElementContentPtr content, int englob); #ifdef LIBXML_OUTPUT_ENABLED /* DEPRECATED */ XMLPUBFUN void xmlSprintfElementContent(char *buf, xmlElementContentPtr content, int englob); #endif /* LIBXML_OUTPUT_ENABLED */ /* DEPRECATED */ /* Element */ XMLPUBFUN xmlElementPtr xmlAddElementDecl (xmlValidCtxtPtr ctxt, xmlDtdPtr dtd, const xmlChar *name, xmlElementTypeVal type, xmlElementContentPtr content); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlElementTablePtr xmlCopyElementTable (xmlElementTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeElementTable (xmlElementTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpElementTable (xmlBufferPtr buf, xmlElementTablePtr table); XMLPUBFUN void xmlDumpElementDecl (xmlBufferPtr buf, xmlElementPtr elem); #endif /* LIBXML_OUTPUT_ENABLED */ /* Enumeration */ XMLPUBFUN xmlEnumerationPtr xmlCreateEnumeration (const xmlChar *name); XMLPUBFUN void xmlFreeEnumeration (xmlEnumerationPtr cur); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlEnumerationPtr xmlCopyEnumeration (xmlEnumerationPtr cur); #endif /* LIBXML_TREE_ENABLED */ /* Attribute */ XMLPUBFUN xmlAttributePtr xmlAddAttributeDecl (xmlValidCtxtPtr ctxt, xmlDtdPtr dtd, const xmlChar *elem, const xmlChar *name, const xmlChar *ns, xmlAttributeType type, xmlAttributeDefault def, const xmlChar *defaultValue, xmlEnumerationPtr tree); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlAttributeTablePtr xmlCopyAttributeTable (xmlAttributeTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeAttributeTable (xmlAttributeTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpAttributeTable (xmlBufferPtr buf, xmlAttributeTablePtr table); XMLPUBFUN void xmlDumpAttributeDecl (xmlBufferPtr buf, xmlAttributePtr attr); #endif /* LIBXML_OUTPUT_ENABLED */ /* IDs */ XMLPUBFUN xmlIDPtr xmlAddID (xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *value, xmlAttrPtr attr); XMLPUBFUN void xmlFreeIDTable (xmlIDTablePtr table); XMLPUBFUN xmlAttrPtr xmlGetID (xmlDocPtr doc, const xmlChar *ID); XMLPUBFUN int xmlIsID (xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr); XMLPUBFUN int xmlRemoveID (xmlDocPtr doc, xmlAttrPtr attr); /* IDREFs */ XML_DEPRECATED XMLPUBFUN xmlRefPtr xmlAddRef (xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *value, xmlAttrPtr attr); XML_DEPRECATED XMLPUBFUN void xmlFreeRefTable (xmlRefTablePtr table); XML_DEPRECATED XMLPUBFUN int xmlIsRef (xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr); XML_DEPRECATED XMLPUBFUN int xmlRemoveRef (xmlDocPtr doc, xmlAttrPtr attr); XML_DEPRECATED XMLPUBFUN xmlListPtr xmlGetRefs (xmlDocPtr doc, const xmlChar *ID); /** * The public function calls related to validity checking. */ #ifdef LIBXML_VALID_ENABLED /* Allocate/Release Validation Contexts */ XMLPUBFUN xmlValidCtxtPtr xmlNewValidCtxt(void); XMLPUBFUN void xmlFreeValidCtxt(xmlValidCtxtPtr); XMLPUBFUN int xmlValidateRoot (xmlValidCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN int xmlValidateElementDecl (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlElementPtr elem); XMLPUBFUN xmlChar * xmlValidNormalizeAttributeValue(xmlDocPtr doc, xmlNodePtr elem, const xmlChar *name, const xmlChar *value); XMLPUBFUN xmlChar * xmlValidCtxtNormalizeAttributeValue(xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *name, const xmlChar *value); XMLPUBFUN int xmlValidateAttributeDecl(xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlAttributePtr attr); XMLPUBFUN int xmlValidateAttributeValue(xmlAttributeType type, const xmlChar *value); XMLPUBFUN int xmlValidateNotationDecl (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNotationPtr nota); XMLPUBFUN int xmlValidateDtd (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlDtdPtr dtd); XMLPUBFUN int xmlValidateDtdFinal (xmlValidCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN int xmlValidateDocument (xmlValidCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN int xmlValidateElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlValidateOneElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlValidateOneAttribute (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr, const xmlChar *value); XMLPUBFUN int xmlValidateOneNamespace (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *prefix, xmlNsPtr ns, const xmlChar *value); XMLPUBFUN int xmlValidateDocumentFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc); #endif /* LIBXML_VALID_ENABLED */ #if defined(LIBXML_VALID_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN int xmlValidateNotationUse (xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *notationName); #endif /* LIBXML_VALID_ENABLED or LIBXML_SCHEMAS_ENABLED */ XMLPUBFUN int xmlIsMixedElement (xmlDocPtr doc, const xmlChar *name); XMLPUBFUN xmlAttributePtr xmlGetDtdAttrDesc (xmlDtdPtr dtd, const xmlChar *elem, const xmlChar *name); XMLPUBFUN xmlAttributePtr xmlGetDtdQAttrDesc (xmlDtdPtr dtd, const xmlChar *elem, const xmlChar *name, const xmlChar *prefix); XMLPUBFUN xmlNotationPtr xmlGetDtdNotationDesc (xmlDtdPtr dtd, const xmlChar *name); XMLPUBFUN xmlElementPtr xmlGetDtdQElementDesc (xmlDtdPtr dtd, const xmlChar *name, const xmlChar *prefix); XMLPUBFUN xmlElementPtr xmlGetDtdElementDesc (xmlDtdPtr dtd, const xmlChar *name); #ifdef LIBXML_VALID_ENABLED XMLPUBFUN int xmlValidGetPotentialChildren(xmlElementContent *ctree, const xmlChar **names, int *len, int max); XMLPUBFUN int xmlValidGetValidElements(xmlNode *prev, xmlNode *next, const xmlChar **names, int max); XMLPUBFUN int xmlValidateNameValue (const xmlChar *value); XMLPUBFUN int xmlValidateNamesValue (const xmlChar *value); XMLPUBFUN int xmlValidateNmtokenValue (const xmlChar *value); XMLPUBFUN int xmlValidateNmtokensValue(const xmlChar *value); #ifdef LIBXML_REGEXP_ENABLED /* * Validation based on the regexp support */ XMLPUBFUN int xmlValidBuildContentModel(xmlValidCtxtPtr ctxt, xmlElementPtr elem); XMLPUBFUN int xmlValidatePushElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *qname); XMLPUBFUN int xmlValidatePushCData (xmlValidCtxtPtr ctxt, const xmlChar *data, int len); XMLPUBFUN int xmlValidatePopElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *qname); #endif /* LIBXML_REGEXP_ENABLED */ #endif /* LIBXML_VALID_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_VALID_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xinclude.h ================================================ /* * Summary: implementation of XInclude * Description: API to handle XInclude processing, * implements the * World Wide Web Consortium Last Call Working Draft 10 November 2003 * http://www.w3.org/TR/2003/WD-xinclude-20031110 * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XINCLUDE_H__ #define __XML_XINCLUDE_H__ #include #include #ifdef LIBXML_XINCLUDE_ENABLED #ifdef __cplusplus extern "C" { #endif /** * XINCLUDE_NS: * * Macro defining the Xinclude namespace: http://www.w3.org/2003/XInclude */ #define XINCLUDE_NS (const xmlChar *) "http://www.w3.org/2003/XInclude" /** * XINCLUDE_OLD_NS: * * Macro defining the draft Xinclude namespace: http://www.w3.org/2001/XInclude */ #define XINCLUDE_OLD_NS (const xmlChar *) "http://www.w3.org/2001/XInclude" /** * XINCLUDE_NODE: * * Macro defining "include" */ #define XINCLUDE_NODE (const xmlChar *) "include" /** * XINCLUDE_FALLBACK: * * Macro defining "fallback" */ #define XINCLUDE_FALLBACK (const xmlChar *) "fallback" /** * XINCLUDE_HREF: * * Macro defining "href" */ #define XINCLUDE_HREF (const xmlChar *) "href" /** * XINCLUDE_PARSE: * * Macro defining "parse" */ #define XINCLUDE_PARSE (const xmlChar *) "parse" /** * XINCLUDE_PARSE_XML: * * Macro defining "xml" */ #define XINCLUDE_PARSE_XML (const xmlChar *) "xml" /** * XINCLUDE_PARSE_TEXT: * * Macro defining "text" */ #define XINCLUDE_PARSE_TEXT (const xmlChar *) "text" /** * XINCLUDE_PARSE_ENCODING: * * Macro defining "encoding" */ #define XINCLUDE_PARSE_ENCODING (const xmlChar *) "encoding" /** * XINCLUDE_PARSE_XPOINTER: * * Macro defining "xpointer" */ #define XINCLUDE_PARSE_XPOINTER (const xmlChar *) "xpointer" typedef struct _xmlXIncludeCtxt xmlXIncludeCtxt; typedef xmlXIncludeCtxt *xmlXIncludeCtxtPtr; /* * standalone processing */ XMLPUBFUN int xmlXIncludeProcess (xmlDocPtr doc); XMLPUBFUN int xmlXIncludeProcessFlags (xmlDocPtr doc, int flags); XMLPUBFUN int xmlXIncludeProcessFlagsData(xmlDocPtr doc, int flags, void *data); XMLPUBFUN int xmlXIncludeProcessTreeFlagsData(xmlNodePtr tree, int flags, void *data); XMLPUBFUN int xmlXIncludeProcessTree (xmlNodePtr tree); XMLPUBFUN int xmlXIncludeProcessTreeFlags(xmlNodePtr tree, int flags); /* * contextual processing */ XMLPUBFUN xmlXIncludeCtxtPtr xmlXIncludeNewContext (xmlDocPtr doc); XMLPUBFUN int xmlXIncludeSetFlags (xmlXIncludeCtxtPtr ctxt, int flags); XMLPUBFUN void xmlXIncludeFreeContext (xmlXIncludeCtxtPtr ctxt); XMLPUBFUN int xmlXIncludeProcessNode (xmlXIncludeCtxtPtr ctxt, xmlNodePtr tree); #ifdef __cplusplus } #endif #endif /* LIBXML_XINCLUDE_ENABLED */ #endif /* __XML_XINCLUDE_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xlink.h ================================================ /* * Summary: unfinished XLink detection module * Description: unfinished XLink detection module * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XLINK_H__ #define __XML_XLINK_H__ #include #include #ifdef LIBXML_XPTR_ENABLED #ifdef __cplusplus extern "C" { #endif /** * Various defines for the various Link properties. * * NOTE: the link detection layer will try to resolve QName expansion * of namespaces. If "foo" is the prefix for "http://foo.com/" * then the link detection layer will expand role="foo:myrole" * to "http://foo.com/:myrole". * NOTE: the link detection layer will expand URI-References found on * href attributes by using the base mechanism if found. */ typedef xmlChar *xlinkHRef; typedef xmlChar *xlinkRole; typedef xmlChar *xlinkTitle; typedef enum { XLINK_TYPE_NONE = 0, XLINK_TYPE_SIMPLE, XLINK_TYPE_EXTENDED, XLINK_TYPE_EXTENDED_SET } xlinkType; typedef enum { XLINK_SHOW_NONE = 0, XLINK_SHOW_NEW, XLINK_SHOW_EMBED, XLINK_SHOW_REPLACE } xlinkShow; typedef enum { XLINK_ACTUATE_NONE = 0, XLINK_ACTUATE_AUTO, XLINK_ACTUATE_ONREQUEST } xlinkActuate; /** * xlinkNodeDetectFunc: * @ctx: user data pointer * @node: the node to check * * This is the prototype for the link detection routine. * It calls the default link detection callbacks upon link detection. */ typedef void (*xlinkNodeDetectFunc) (void *ctx, xmlNodePtr node); /* * The link detection module interact with the upper layers using * a set of callback registered at parsing time. */ /** * xlinkSimpleLinkFunk: * @ctx: user data pointer * @node: the node carrying the link * @href: the target of the link * @role: the role string * @title: the link title * * This is the prototype for a simple link detection callback. */ typedef void (*xlinkSimpleLinkFunk) (void *ctx, xmlNodePtr node, const xlinkHRef href, const xlinkRole role, const xlinkTitle title); /** * xlinkExtendedLinkFunk: * @ctx: user data pointer * @node: the node carrying the link * @nbLocators: the number of locators detected on the link * @hrefs: pointer to the array of locator hrefs * @roles: pointer to the array of locator roles * @nbArcs: the number of arcs detected on the link * @from: pointer to the array of source roles found on the arcs * @to: pointer to the array of target roles found on the arcs * @show: array of values for the show attributes found on the arcs * @actuate: array of values for the actuate attributes found on the arcs * @nbTitles: the number of titles detected on the link * @title: array of titles detected on the link * @langs: array of xml:lang values for the titles * * This is the prototype for a extended link detection callback. */ typedef void (*xlinkExtendedLinkFunk)(void *ctx, xmlNodePtr node, int nbLocators, const xlinkHRef *hrefs, const xlinkRole *roles, int nbArcs, const xlinkRole *from, const xlinkRole *to, xlinkShow *show, xlinkActuate *actuate, int nbTitles, const xlinkTitle *titles, const xmlChar **langs); /** * xlinkExtendedLinkSetFunk: * @ctx: user data pointer * @node: the node carrying the link * @nbLocators: the number of locators detected on the link * @hrefs: pointer to the array of locator hrefs * @roles: pointer to the array of locator roles * @nbTitles: the number of titles detected on the link * @title: array of titles detected on the link * @langs: array of xml:lang values for the titles * * This is the prototype for a extended link set detection callback. */ typedef void (*xlinkExtendedLinkSetFunk) (void *ctx, xmlNodePtr node, int nbLocators, const xlinkHRef *hrefs, const xlinkRole *roles, int nbTitles, const xlinkTitle *titles, const xmlChar **langs); /** * This is the structure containing a set of Links detection callbacks. * * There is no default xlink callbacks, if one want to get link * recognition activated, those call backs must be provided before parsing. */ typedef struct _xlinkHandler xlinkHandler; typedef xlinkHandler *xlinkHandlerPtr; struct _xlinkHandler { xlinkSimpleLinkFunk simple; xlinkExtendedLinkFunk extended; xlinkExtendedLinkSetFunk set; }; /* * The default detection routine, can be overridden, they call the default * detection callbacks. */ XMLPUBFUN xlinkNodeDetectFunc xlinkGetDefaultDetect (void); XMLPUBFUN void xlinkSetDefaultDetect (xlinkNodeDetectFunc func); /* * Routines to set/get the default handlers. */ XMLPUBFUN xlinkHandlerPtr xlinkGetDefaultHandler (void); XMLPUBFUN void xlinkSetDefaultHandler (xlinkHandlerPtr handler); /* * Link detection module itself. */ XMLPUBFUN xlinkType xlinkIsLink (xmlDocPtr doc, xmlNodePtr node); #ifdef __cplusplus } #endif #endif /* LIBXML_XPTR_ENABLED */ #endif /* __XML_XLINK_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlIO.h ================================================ /* * Summary: interface for the I/O interfaces used by the parser * Description: interface for the I/O interfaces used by the parser * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_IO_H__ #define __XML_IO_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * Those are the functions and datatypes for the parser input * I/O structures. */ /** * xmlInputMatchCallback: * @filename: the filename or URI * * Callback used in the I/O Input API to detect if the current handler * can provide input functionality for this resource. * * Returns 1 if yes and 0 if another Input module should be used */ typedef int (*xmlInputMatchCallback) (char const *filename); /** * xmlInputOpenCallback: * @filename: the filename or URI * * Callback used in the I/O Input API to open the resource * * Returns an Input context or NULL in case or error */ typedef void * (*xmlInputOpenCallback) (char const *filename); /** * xmlInputReadCallback: * @context: an Input context * @buffer: the buffer to store data read * @len: the length of the buffer in bytes * * Callback used in the I/O Input API to read the resource * * Returns the number of bytes read or -1 in case of error */ typedef int (*xmlInputReadCallback) (void * context, char * buffer, int len); /** * xmlInputCloseCallback: * @context: an Input context * * Callback used in the I/O Input API to close the resource * * Returns 0 or -1 in case of error */ typedef int (*xmlInputCloseCallback) (void * context); #ifdef LIBXML_OUTPUT_ENABLED /* * Those are the functions and datatypes for the library output * I/O structures. */ /** * xmlOutputMatchCallback: * @filename: the filename or URI * * Callback used in the I/O Output API to detect if the current handler * can provide output functionality for this resource. * * Returns 1 if yes and 0 if another Output module should be used */ typedef int (*xmlOutputMatchCallback) (char const *filename); /** * xmlOutputOpenCallback: * @filename: the filename or URI * * Callback used in the I/O Output API to open the resource * * Returns an Output context or NULL in case or error */ typedef void * (*xmlOutputOpenCallback) (char const *filename); /** * xmlOutputWriteCallback: * @context: an Output context * @buffer: the buffer of data to write * @len: the length of the buffer in bytes * * Callback used in the I/O Output API to write to the resource * * Returns the number of bytes written or -1 in case of error */ typedef int (*xmlOutputWriteCallback) (void * context, const char * buffer, int len); /** * xmlOutputCloseCallback: * @context: an Output context * * Callback used in the I/O Output API to close the resource * * Returns 0 or -1 in case of error */ typedef int (*xmlOutputCloseCallback) (void * context); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef __cplusplus } #endif #include #include #include #include #ifdef __cplusplus extern "C" { #endif struct _xmlParserInputBuffer { void* context; xmlInputReadCallback readcallback; xmlInputCloseCallback closecallback; xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */ xmlBufPtr buffer; /* Local buffer encoded in UTF-8 */ xmlBufPtr raw; /* if encoder != NULL buffer for raw input */ int compressed; /* -1=unknown, 0=not compressed, 1=compressed */ int error; unsigned long rawconsumed;/* amount consumed from raw */ }; #ifdef LIBXML_OUTPUT_ENABLED struct _xmlOutputBuffer { void* context; xmlOutputWriteCallback writecallback; xmlOutputCloseCallback closecallback; xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */ xmlBufPtr buffer; /* Local buffer encoded in UTF-8 or ISOLatin */ xmlBufPtr conv; /* if encoder != NULL buffer for output */ int written; /* total number of byte written */ int error; }; #endif /* LIBXML_OUTPUT_ENABLED */ /* * Interfaces for input */ XMLPUBFUN void xmlCleanupInputCallbacks (void); XMLPUBFUN int xmlPopInputCallbacks (void); XMLPUBFUN void xmlRegisterDefaultInputCallbacks (void); XMLPUBFUN xmlParserInputBufferPtr xmlAllocParserInputBuffer (xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateFilename (const char *URI, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateFile (FILE *file, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateFd (int fd, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateMem (const char *mem, int size, xmlCharEncoding enc); XML_DEPRECATED XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateStatic (const char *mem, int size, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, xmlCharEncoding enc); XMLPUBFUN int xmlParserInputBufferRead (xmlParserInputBufferPtr in, int len); XMLPUBFUN int xmlParserInputBufferGrow (xmlParserInputBufferPtr in, int len); XMLPUBFUN int xmlParserInputBufferPush (xmlParserInputBufferPtr in, int len, const char *buf); XMLPUBFUN void xmlFreeParserInputBuffer (xmlParserInputBufferPtr in); XMLPUBFUN char * xmlParserGetDirectory (const char *filename); XMLPUBFUN int xmlRegisterInputCallbacks (xmlInputMatchCallback matchFunc, xmlInputOpenCallback openFunc, xmlInputReadCallback readFunc, xmlInputCloseCallback closeFunc); xmlParserInputBufferPtr __xmlParserInputBufferCreateFilename(const char *URI, xmlCharEncoding enc); #ifdef LIBXML_OUTPUT_ENABLED /* * Interfaces for output */ XMLPUBFUN void xmlCleanupOutputCallbacks (void); XMLPUBFUN int xmlPopOutputCallbacks (void); XMLPUBFUN void xmlRegisterDefaultOutputCallbacks(void); XMLPUBFUN xmlOutputBufferPtr xmlAllocOutputBuffer (xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateFilename (const char *URI, xmlCharEncodingHandlerPtr encoder, int compression); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateFile (FILE *file, xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateBuffer (xmlBufferPtr buffer, xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateFd (int fd, xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateIO (xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose, void *ioctx, xmlCharEncodingHandlerPtr encoder); /* Couple of APIs to get the output without digging into the buffers */ XMLPUBFUN const xmlChar * xmlOutputBufferGetContent (xmlOutputBufferPtr out); XMLPUBFUN size_t xmlOutputBufferGetSize (xmlOutputBufferPtr out); XMLPUBFUN int xmlOutputBufferWrite (xmlOutputBufferPtr out, int len, const char *buf); XMLPUBFUN int xmlOutputBufferWriteString (xmlOutputBufferPtr out, const char *str); XMLPUBFUN int xmlOutputBufferWriteEscape (xmlOutputBufferPtr out, const xmlChar *str, xmlCharEncodingOutputFunc escaping); XMLPUBFUN int xmlOutputBufferFlush (xmlOutputBufferPtr out); XMLPUBFUN int xmlOutputBufferClose (xmlOutputBufferPtr out); XMLPUBFUN int xmlRegisterOutputCallbacks (xmlOutputMatchCallback matchFunc, xmlOutputOpenCallback openFunc, xmlOutputWriteCallback writeFunc, xmlOutputCloseCallback closeFunc); xmlOutputBufferPtr __xmlOutputBufferCreateFilename(const char *URI, xmlCharEncodingHandlerPtr encoder, int compression); #ifdef LIBXML_HTTP_ENABLED /* This function only exists if HTTP support built into the library */ XMLPUBFUN void xmlRegisterHTTPPostCallbacks (void ); #endif /* LIBXML_HTTP_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN xmlParserInputPtr xmlCheckHTTPInput (xmlParserCtxtPtr ctxt, xmlParserInputPtr ret); /* * A predefined entity loader disabling network accesses */ XMLPUBFUN xmlParserInputPtr xmlNoNetExternalEntityLoader (const char *URL, const char *ID, xmlParserCtxtPtr ctxt); /* * xmlNormalizeWindowsPath is obsolete, don't use it. * Check xmlCanonicPath in uri.h for a better alternative. */ XMLPUBFUN xmlChar * xmlNormalizeWindowsPath (const xmlChar *path); XMLPUBFUN int xmlCheckFilename (const char *path); /** * Default 'file://' protocol callbacks */ XMLPUBFUN int xmlFileMatch (const char *filename); XMLPUBFUN void * xmlFileOpen (const char *filename); XMLPUBFUN int xmlFileRead (void * context, char * buffer, int len); XMLPUBFUN int xmlFileClose (void * context); /** * Default 'http://' protocol callbacks */ #ifdef LIBXML_HTTP_ENABLED XMLPUBFUN int xmlIOHTTPMatch (const char *filename); XMLPUBFUN void * xmlIOHTTPOpen (const char *filename); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void * xmlIOHTTPOpenW (const char * post_uri, int compression ); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN int xmlIOHTTPRead (void * context, char * buffer, int len); XMLPUBFUN int xmlIOHTTPClose (void * context); #endif /* LIBXML_HTTP_ENABLED */ /** * Default 'ftp://' protocol callbacks */ #ifdef LIBXML_FTP_ENABLED XMLPUBFUN int xmlIOFTPMatch (const char *filename); XMLPUBFUN void * xmlIOFTPOpen (const char *filename); XMLPUBFUN int xmlIOFTPRead (void * context, char * buffer, int len); XMLPUBFUN int xmlIOFTPClose (void * context); #endif /* LIBXML_FTP_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_IO_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlautomata.h ================================================ /* * Summary: API to build regexp automata * Description: the API to build regexp automata * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_AUTOMATA_H__ #define __XML_AUTOMATA_H__ #include #ifdef LIBXML_REGEXP_ENABLED #ifdef LIBXML_AUTOMATA_ENABLED #include #ifdef __cplusplus extern "C" { #endif /** * xmlAutomataPtr: * * A libxml automata description, It can be compiled into a regexp */ typedef struct _xmlAutomata xmlAutomata; typedef xmlAutomata *xmlAutomataPtr; /** * xmlAutomataStatePtr: * * A state int the automata description, */ typedef struct _xmlAutomataState xmlAutomataState; typedef xmlAutomataState *xmlAutomataStatePtr; /* * Building API */ XMLPUBFUN xmlAutomataPtr xmlNewAutomata (void); XMLPUBFUN void xmlFreeAutomata (xmlAutomataPtr am); XMLPUBFUN xmlAutomataStatePtr xmlAutomataGetInitState (xmlAutomataPtr am); XMLPUBFUN int xmlAutomataSetFinalState (xmlAutomataPtr am, xmlAutomataStatePtr state); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewState (xmlAutomataPtr am); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewTransition (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewTransition2 (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewNegTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCountTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCountTrans2 (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewOnceTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewOnceTrans2 (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewAllTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int lax); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewEpsilon (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCountedTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int counter); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCounterTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int counter); XMLPUBFUN int xmlAutomataNewCounter (xmlAutomataPtr am, int min, int max); XMLPUBFUN struct _xmlRegexp * xmlAutomataCompile (xmlAutomataPtr am); XMLPUBFUN int xmlAutomataIsDeterminist (xmlAutomataPtr am); #ifdef __cplusplus } #endif #endif /* LIBXML_AUTOMATA_ENABLED */ #endif /* LIBXML_REGEXP_ENABLED */ #endif /* __XML_AUTOMATA_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlerror.h ================================================ /* * Summary: error handling * Description: the API used to report errors * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #include #ifndef __XML_ERROR_H__ #define __XML_ERROR_H__ #ifdef __cplusplus extern "C" { #endif /** * xmlErrorLevel: * * Indicates the level of an error */ typedef enum { XML_ERR_NONE = 0, XML_ERR_WARNING = 1, /* A simple warning */ XML_ERR_ERROR = 2, /* A recoverable error */ XML_ERR_FATAL = 3 /* A fatal error */ } xmlErrorLevel; /** * xmlErrorDomain: * * Indicates where an error may have come from */ typedef enum { XML_FROM_NONE = 0, XML_FROM_PARSER, /* The XML parser */ XML_FROM_TREE, /* The tree module */ XML_FROM_NAMESPACE, /* The XML Namespace module */ XML_FROM_DTD, /* The XML DTD validation with parser context*/ XML_FROM_HTML, /* The HTML parser */ XML_FROM_MEMORY, /* The memory allocator */ XML_FROM_OUTPUT, /* The serialization code */ XML_FROM_IO, /* The Input/Output stack */ XML_FROM_FTP, /* The FTP module */ XML_FROM_HTTP, /* The HTTP module */ XML_FROM_XINCLUDE, /* The XInclude processing */ XML_FROM_XPATH, /* The XPath module */ XML_FROM_XPOINTER, /* The XPointer module */ XML_FROM_REGEXP, /* The regular expressions module */ XML_FROM_DATATYPE, /* The W3C XML Schemas Datatype module */ XML_FROM_SCHEMASP, /* The W3C XML Schemas parser module */ XML_FROM_SCHEMASV, /* The W3C XML Schemas validation module */ XML_FROM_RELAXNGP, /* The Relax-NG parser module */ XML_FROM_RELAXNGV, /* The Relax-NG validator module */ XML_FROM_CATALOG, /* The Catalog module */ XML_FROM_C14N, /* The Canonicalization module */ XML_FROM_XSLT, /* The XSLT engine from libxslt */ XML_FROM_VALID, /* The XML DTD validation with valid context */ XML_FROM_CHECK, /* The error checking module */ XML_FROM_WRITER, /* The xmlwriter module */ XML_FROM_MODULE, /* The dynamically loaded module module*/ XML_FROM_I18N, /* The module handling character conversion */ XML_FROM_SCHEMATRONV,/* The Schematron validator module */ XML_FROM_BUFFER, /* The buffers module */ XML_FROM_URI /* The URI module */ } xmlErrorDomain; /** * xmlError: * * An XML Error instance. */ typedef struct _xmlError xmlError; typedef xmlError *xmlErrorPtr; struct _xmlError { int domain; /* What part of the library raised this error */ int code; /* The error code, e.g. an xmlParserError */ char *message;/* human-readable informative error message */ xmlErrorLevel level;/* how consequent is the error */ char *file; /* the filename */ int line; /* the line number if available */ char *str1; /* extra string information */ char *str2; /* extra string information */ char *str3; /* extra string information */ int int1; /* extra number information */ int int2; /* error column # or 0 if N/A (todo: rename field when we would brk ABI) */ void *ctxt; /* the parser context if available */ void *node; /* the node in the tree */ }; /** * xmlParserError: * * This is an error that the XML (or HTML) parser can generate */ typedef enum { XML_ERR_OK = 0, XML_ERR_INTERNAL_ERROR, /* 1 */ XML_ERR_NO_MEMORY, /* 2 */ XML_ERR_DOCUMENT_START, /* 3 */ XML_ERR_DOCUMENT_EMPTY, /* 4 */ XML_ERR_DOCUMENT_END, /* 5 */ XML_ERR_INVALID_HEX_CHARREF, /* 6 */ XML_ERR_INVALID_DEC_CHARREF, /* 7 */ XML_ERR_INVALID_CHARREF, /* 8 */ XML_ERR_INVALID_CHAR, /* 9 */ XML_ERR_CHARREF_AT_EOF, /* 10 */ XML_ERR_CHARREF_IN_PROLOG, /* 11 */ XML_ERR_CHARREF_IN_EPILOG, /* 12 */ XML_ERR_CHARREF_IN_DTD, /* 13 */ XML_ERR_ENTITYREF_AT_EOF, /* 14 */ XML_ERR_ENTITYREF_IN_PROLOG, /* 15 */ XML_ERR_ENTITYREF_IN_EPILOG, /* 16 */ XML_ERR_ENTITYREF_IN_DTD, /* 17 */ XML_ERR_PEREF_AT_EOF, /* 18 */ XML_ERR_PEREF_IN_PROLOG, /* 19 */ XML_ERR_PEREF_IN_EPILOG, /* 20 */ XML_ERR_PEREF_IN_INT_SUBSET, /* 21 */ XML_ERR_ENTITYREF_NO_NAME, /* 22 */ XML_ERR_ENTITYREF_SEMICOL_MISSING, /* 23 */ XML_ERR_PEREF_NO_NAME, /* 24 */ XML_ERR_PEREF_SEMICOL_MISSING, /* 25 */ XML_ERR_UNDECLARED_ENTITY, /* 26 */ XML_WAR_UNDECLARED_ENTITY, /* 27 */ XML_ERR_UNPARSED_ENTITY, /* 28 */ XML_ERR_ENTITY_IS_EXTERNAL, /* 29 */ XML_ERR_ENTITY_IS_PARAMETER, /* 30 */ XML_ERR_UNKNOWN_ENCODING, /* 31 */ XML_ERR_UNSUPPORTED_ENCODING, /* 32 */ XML_ERR_STRING_NOT_STARTED, /* 33 */ XML_ERR_STRING_NOT_CLOSED, /* 34 */ XML_ERR_NS_DECL_ERROR, /* 35 */ XML_ERR_ENTITY_NOT_STARTED, /* 36 */ XML_ERR_ENTITY_NOT_FINISHED, /* 37 */ XML_ERR_LT_IN_ATTRIBUTE, /* 38 */ XML_ERR_ATTRIBUTE_NOT_STARTED, /* 39 */ XML_ERR_ATTRIBUTE_NOT_FINISHED, /* 40 */ XML_ERR_ATTRIBUTE_WITHOUT_VALUE, /* 41 */ XML_ERR_ATTRIBUTE_REDEFINED, /* 42 */ XML_ERR_LITERAL_NOT_STARTED, /* 43 */ XML_ERR_LITERAL_NOT_FINISHED, /* 44 */ XML_ERR_COMMENT_NOT_FINISHED, /* 45 */ XML_ERR_PI_NOT_STARTED, /* 46 */ XML_ERR_PI_NOT_FINISHED, /* 47 */ XML_ERR_NOTATION_NOT_STARTED, /* 48 */ XML_ERR_NOTATION_NOT_FINISHED, /* 49 */ XML_ERR_ATTLIST_NOT_STARTED, /* 50 */ XML_ERR_ATTLIST_NOT_FINISHED, /* 51 */ XML_ERR_MIXED_NOT_STARTED, /* 52 */ XML_ERR_MIXED_NOT_FINISHED, /* 53 */ XML_ERR_ELEMCONTENT_NOT_STARTED, /* 54 */ XML_ERR_ELEMCONTENT_NOT_FINISHED, /* 55 */ XML_ERR_XMLDECL_NOT_STARTED, /* 56 */ XML_ERR_XMLDECL_NOT_FINISHED, /* 57 */ XML_ERR_CONDSEC_NOT_STARTED, /* 58 */ XML_ERR_CONDSEC_NOT_FINISHED, /* 59 */ XML_ERR_EXT_SUBSET_NOT_FINISHED, /* 60 */ XML_ERR_DOCTYPE_NOT_FINISHED, /* 61 */ XML_ERR_MISPLACED_CDATA_END, /* 62 */ XML_ERR_CDATA_NOT_FINISHED, /* 63 */ XML_ERR_RESERVED_XML_NAME, /* 64 */ XML_ERR_SPACE_REQUIRED, /* 65 */ XML_ERR_SEPARATOR_REQUIRED, /* 66 */ XML_ERR_NMTOKEN_REQUIRED, /* 67 */ XML_ERR_NAME_REQUIRED, /* 68 */ XML_ERR_PCDATA_REQUIRED, /* 69 */ XML_ERR_URI_REQUIRED, /* 70 */ XML_ERR_PUBID_REQUIRED, /* 71 */ XML_ERR_LT_REQUIRED, /* 72 */ XML_ERR_GT_REQUIRED, /* 73 */ XML_ERR_LTSLASH_REQUIRED, /* 74 */ XML_ERR_EQUAL_REQUIRED, /* 75 */ XML_ERR_TAG_NAME_MISMATCH, /* 76 */ XML_ERR_TAG_NOT_FINISHED, /* 77 */ XML_ERR_STANDALONE_VALUE, /* 78 */ XML_ERR_ENCODING_NAME, /* 79 */ XML_ERR_HYPHEN_IN_COMMENT, /* 80 */ XML_ERR_INVALID_ENCODING, /* 81 */ XML_ERR_EXT_ENTITY_STANDALONE, /* 82 */ XML_ERR_CONDSEC_INVALID, /* 83 */ XML_ERR_VALUE_REQUIRED, /* 84 */ XML_ERR_NOT_WELL_BALANCED, /* 85 */ XML_ERR_EXTRA_CONTENT, /* 86 */ XML_ERR_ENTITY_CHAR_ERROR, /* 87 */ XML_ERR_ENTITY_PE_INTERNAL, /* 88 */ XML_ERR_ENTITY_LOOP, /* 89 */ XML_ERR_ENTITY_BOUNDARY, /* 90 */ XML_ERR_INVALID_URI, /* 91 */ XML_ERR_URI_FRAGMENT, /* 92 */ XML_WAR_CATALOG_PI, /* 93 */ XML_ERR_NO_DTD, /* 94 */ XML_ERR_CONDSEC_INVALID_KEYWORD, /* 95 */ XML_ERR_VERSION_MISSING, /* 96 */ XML_WAR_UNKNOWN_VERSION, /* 97 */ XML_WAR_LANG_VALUE, /* 98 */ XML_WAR_NS_URI, /* 99 */ XML_WAR_NS_URI_RELATIVE, /* 100 */ XML_ERR_MISSING_ENCODING, /* 101 */ XML_WAR_SPACE_VALUE, /* 102 */ XML_ERR_NOT_STANDALONE, /* 103 */ XML_ERR_ENTITY_PROCESSING, /* 104 */ XML_ERR_NOTATION_PROCESSING, /* 105 */ XML_WAR_NS_COLUMN, /* 106 */ XML_WAR_ENTITY_REDEFINED, /* 107 */ XML_ERR_UNKNOWN_VERSION, /* 108 */ XML_ERR_VERSION_MISMATCH, /* 109 */ XML_ERR_NAME_TOO_LONG, /* 110 */ XML_ERR_USER_STOP, /* 111 */ XML_ERR_COMMENT_ABRUPTLY_ENDED, /* 112 */ XML_NS_ERR_XML_NAMESPACE = 200, XML_NS_ERR_UNDEFINED_NAMESPACE, /* 201 */ XML_NS_ERR_QNAME, /* 202 */ XML_NS_ERR_ATTRIBUTE_REDEFINED, /* 203 */ XML_NS_ERR_EMPTY, /* 204 */ XML_NS_ERR_COLON, /* 205 */ XML_DTD_ATTRIBUTE_DEFAULT = 500, XML_DTD_ATTRIBUTE_REDEFINED, /* 501 */ XML_DTD_ATTRIBUTE_VALUE, /* 502 */ XML_DTD_CONTENT_ERROR, /* 503 */ XML_DTD_CONTENT_MODEL, /* 504 */ XML_DTD_CONTENT_NOT_DETERMINIST, /* 505 */ XML_DTD_DIFFERENT_PREFIX, /* 506 */ XML_DTD_ELEM_DEFAULT_NAMESPACE, /* 507 */ XML_DTD_ELEM_NAMESPACE, /* 508 */ XML_DTD_ELEM_REDEFINED, /* 509 */ XML_DTD_EMPTY_NOTATION, /* 510 */ XML_DTD_ENTITY_TYPE, /* 511 */ XML_DTD_ID_FIXED, /* 512 */ XML_DTD_ID_REDEFINED, /* 513 */ XML_DTD_ID_SUBSET, /* 514 */ XML_DTD_INVALID_CHILD, /* 515 */ XML_DTD_INVALID_DEFAULT, /* 516 */ XML_DTD_LOAD_ERROR, /* 517 */ XML_DTD_MISSING_ATTRIBUTE, /* 518 */ XML_DTD_MIXED_CORRUPT, /* 519 */ XML_DTD_MULTIPLE_ID, /* 520 */ XML_DTD_NO_DOC, /* 521 */ XML_DTD_NO_DTD, /* 522 */ XML_DTD_NO_ELEM_NAME, /* 523 */ XML_DTD_NO_PREFIX, /* 524 */ XML_DTD_NO_ROOT, /* 525 */ XML_DTD_NOTATION_REDEFINED, /* 526 */ XML_DTD_NOTATION_VALUE, /* 527 */ XML_DTD_NOT_EMPTY, /* 528 */ XML_DTD_NOT_PCDATA, /* 529 */ XML_DTD_NOT_STANDALONE, /* 530 */ XML_DTD_ROOT_NAME, /* 531 */ XML_DTD_STANDALONE_WHITE_SPACE, /* 532 */ XML_DTD_UNKNOWN_ATTRIBUTE, /* 533 */ XML_DTD_UNKNOWN_ELEM, /* 534 */ XML_DTD_UNKNOWN_ENTITY, /* 535 */ XML_DTD_UNKNOWN_ID, /* 536 */ XML_DTD_UNKNOWN_NOTATION, /* 537 */ XML_DTD_STANDALONE_DEFAULTED, /* 538 */ XML_DTD_XMLID_VALUE, /* 539 */ XML_DTD_XMLID_TYPE, /* 540 */ XML_DTD_DUP_TOKEN, /* 541 */ XML_HTML_STRUCURE_ERROR = 800, XML_HTML_UNKNOWN_TAG, /* 801 */ XML_HTML_INCORRECTLY_OPENED_COMMENT, /* 802 */ XML_RNGP_ANYNAME_ATTR_ANCESTOR = 1000, XML_RNGP_ATTR_CONFLICT, /* 1001 */ XML_RNGP_ATTRIBUTE_CHILDREN, /* 1002 */ XML_RNGP_ATTRIBUTE_CONTENT, /* 1003 */ XML_RNGP_ATTRIBUTE_EMPTY, /* 1004 */ XML_RNGP_ATTRIBUTE_NOOP, /* 1005 */ XML_RNGP_CHOICE_CONTENT, /* 1006 */ XML_RNGP_CHOICE_EMPTY, /* 1007 */ XML_RNGP_CREATE_FAILURE, /* 1008 */ XML_RNGP_DATA_CONTENT, /* 1009 */ XML_RNGP_DEF_CHOICE_AND_INTERLEAVE, /* 1010 */ XML_RNGP_DEFINE_CREATE_FAILED, /* 1011 */ XML_RNGP_DEFINE_EMPTY, /* 1012 */ XML_RNGP_DEFINE_MISSING, /* 1013 */ XML_RNGP_DEFINE_NAME_MISSING, /* 1014 */ XML_RNGP_ELEM_CONTENT_EMPTY, /* 1015 */ XML_RNGP_ELEM_CONTENT_ERROR, /* 1016 */ XML_RNGP_ELEMENT_EMPTY, /* 1017 */ XML_RNGP_ELEMENT_CONTENT, /* 1018 */ XML_RNGP_ELEMENT_NAME, /* 1019 */ XML_RNGP_ELEMENT_NO_CONTENT, /* 1020 */ XML_RNGP_ELEM_TEXT_CONFLICT, /* 1021 */ XML_RNGP_EMPTY, /* 1022 */ XML_RNGP_EMPTY_CONSTRUCT, /* 1023 */ XML_RNGP_EMPTY_CONTENT, /* 1024 */ XML_RNGP_EMPTY_NOT_EMPTY, /* 1025 */ XML_RNGP_ERROR_TYPE_LIB, /* 1026 */ XML_RNGP_EXCEPT_EMPTY, /* 1027 */ XML_RNGP_EXCEPT_MISSING, /* 1028 */ XML_RNGP_EXCEPT_MULTIPLE, /* 1029 */ XML_RNGP_EXCEPT_NO_CONTENT, /* 1030 */ XML_RNGP_EXTERNALREF_EMTPY, /* 1031 */ XML_RNGP_EXTERNAL_REF_FAILURE, /* 1032 */ XML_RNGP_EXTERNALREF_RECURSE, /* 1033 */ XML_RNGP_FORBIDDEN_ATTRIBUTE, /* 1034 */ XML_RNGP_FOREIGN_ELEMENT, /* 1035 */ XML_RNGP_GRAMMAR_CONTENT, /* 1036 */ XML_RNGP_GRAMMAR_EMPTY, /* 1037 */ XML_RNGP_GRAMMAR_MISSING, /* 1038 */ XML_RNGP_GRAMMAR_NO_START, /* 1039 */ XML_RNGP_GROUP_ATTR_CONFLICT, /* 1040 */ XML_RNGP_HREF_ERROR, /* 1041 */ XML_RNGP_INCLUDE_EMPTY, /* 1042 */ XML_RNGP_INCLUDE_FAILURE, /* 1043 */ XML_RNGP_INCLUDE_RECURSE, /* 1044 */ XML_RNGP_INTERLEAVE_ADD, /* 1045 */ XML_RNGP_INTERLEAVE_CREATE_FAILED, /* 1046 */ XML_RNGP_INTERLEAVE_EMPTY, /* 1047 */ XML_RNGP_INTERLEAVE_NO_CONTENT, /* 1048 */ XML_RNGP_INVALID_DEFINE_NAME, /* 1049 */ XML_RNGP_INVALID_URI, /* 1050 */ XML_RNGP_INVALID_VALUE, /* 1051 */ XML_RNGP_MISSING_HREF, /* 1052 */ XML_RNGP_NAME_MISSING, /* 1053 */ XML_RNGP_NEED_COMBINE, /* 1054 */ XML_RNGP_NOTALLOWED_NOT_EMPTY, /* 1055 */ XML_RNGP_NSNAME_ATTR_ANCESTOR, /* 1056 */ XML_RNGP_NSNAME_NO_NS, /* 1057 */ XML_RNGP_PARAM_FORBIDDEN, /* 1058 */ XML_RNGP_PARAM_NAME_MISSING, /* 1059 */ XML_RNGP_PARENTREF_CREATE_FAILED, /* 1060 */ XML_RNGP_PARENTREF_NAME_INVALID, /* 1061 */ XML_RNGP_PARENTREF_NO_NAME, /* 1062 */ XML_RNGP_PARENTREF_NO_PARENT, /* 1063 */ XML_RNGP_PARENTREF_NOT_EMPTY, /* 1064 */ XML_RNGP_PARSE_ERROR, /* 1065 */ XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME, /* 1066 */ XML_RNGP_PAT_ATTR_ATTR, /* 1067 */ XML_RNGP_PAT_ATTR_ELEM, /* 1068 */ XML_RNGP_PAT_DATA_EXCEPT_ATTR, /* 1069 */ XML_RNGP_PAT_DATA_EXCEPT_ELEM, /* 1070 */ XML_RNGP_PAT_DATA_EXCEPT_EMPTY, /* 1071 */ XML_RNGP_PAT_DATA_EXCEPT_GROUP, /* 1072 */ XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE, /* 1073 */ XML_RNGP_PAT_DATA_EXCEPT_LIST, /* 1074 */ XML_RNGP_PAT_DATA_EXCEPT_ONEMORE, /* 1075 */ XML_RNGP_PAT_DATA_EXCEPT_REF, /* 1076 */ XML_RNGP_PAT_DATA_EXCEPT_TEXT, /* 1077 */ XML_RNGP_PAT_LIST_ATTR, /* 1078 */ XML_RNGP_PAT_LIST_ELEM, /* 1079 */ XML_RNGP_PAT_LIST_INTERLEAVE, /* 1080 */ XML_RNGP_PAT_LIST_LIST, /* 1081 */ XML_RNGP_PAT_LIST_REF, /* 1082 */ XML_RNGP_PAT_LIST_TEXT, /* 1083 */ XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME, /* 1084 */ XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME, /* 1085 */ XML_RNGP_PAT_ONEMORE_GROUP_ATTR, /* 1086 */ XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR, /* 1087 */ XML_RNGP_PAT_START_ATTR, /* 1088 */ XML_RNGP_PAT_START_DATA, /* 1089 */ XML_RNGP_PAT_START_EMPTY, /* 1090 */ XML_RNGP_PAT_START_GROUP, /* 1091 */ XML_RNGP_PAT_START_INTERLEAVE, /* 1092 */ XML_RNGP_PAT_START_LIST, /* 1093 */ XML_RNGP_PAT_START_ONEMORE, /* 1094 */ XML_RNGP_PAT_START_TEXT, /* 1095 */ XML_RNGP_PAT_START_VALUE, /* 1096 */ XML_RNGP_PREFIX_UNDEFINED, /* 1097 */ XML_RNGP_REF_CREATE_FAILED, /* 1098 */ XML_RNGP_REF_CYCLE, /* 1099 */ XML_RNGP_REF_NAME_INVALID, /* 1100 */ XML_RNGP_REF_NO_DEF, /* 1101 */ XML_RNGP_REF_NO_NAME, /* 1102 */ XML_RNGP_REF_NOT_EMPTY, /* 1103 */ XML_RNGP_START_CHOICE_AND_INTERLEAVE, /* 1104 */ XML_RNGP_START_CONTENT, /* 1105 */ XML_RNGP_START_EMPTY, /* 1106 */ XML_RNGP_START_MISSING, /* 1107 */ XML_RNGP_TEXT_EXPECTED, /* 1108 */ XML_RNGP_TEXT_HAS_CHILD, /* 1109 */ XML_RNGP_TYPE_MISSING, /* 1110 */ XML_RNGP_TYPE_NOT_FOUND, /* 1111 */ XML_RNGP_TYPE_VALUE, /* 1112 */ XML_RNGP_UNKNOWN_ATTRIBUTE, /* 1113 */ XML_RNGP_UNKNOWN_COMBINE, /* 1114 */ XML_RNGP_UNKNOWN_CONSTRUCT, /* 1115 */ XML_RNGP_UNKNOWN_TYPE_LIB, /* 1116 */ XML_RNGP_URI_FRAGMENT, /* 1117 */ XML_RNGP_URI_NOT_ABSOLUTE, /* 1118 */ XML_RNGP_VALUE_EMPTY, /* 1119 */ XML_RNGP_VALUE_NO_CONTENT, /* 1120 */ XML_RNGP_XMLNS_NAME, /* 1121 */ XML_RNGP_XML_NS, /* 1122 */ XML_XPATH_EXPRESSION_OK = 1200, XML_XPATH_NUMBER_ERROR, /* 1201 */ XML_XPATH_UNFINISHED_LITERAL_ERROR, /* 1202 */ XML_XPATH_START_LITERAL_ERROR, /* 1203 */ XML_XPATH_VARIABLE_REF_ERROR, /* 1204 */ XML_XPATH_UNDEF_VARIABLE_ERROR, /* 1205 */ XML_XPATH_INVALID_PREDICATE_ERROR, /* 1206 */ XML_XPATH_EXPR_ERROR, /* 1207 */ XML_XPATH_UNCLOSED_ERROR, /* 1208 */ XML_XPATH_UNKNOWN_FUNC_ERROR, /* 1209 */ XML_XPATH_INVALID_OPERAND, /* 1210 */ XML_XPATH_INVALID_TYPE, /* 1211 */ XML_XPATH_INVALID_ARITY, /* 1212 */ XML_XPATH_INVALID_CTXT_SIZE, /* 1213 */ XML_XPATH_INVALID_CTXT_POSITION, /* 1214 */ XML_XPATH_MEMORY_ERROR, /* 1215 */ XML_XPTR_SYNTAX_ERROR, /* 1216 */ XML_XPTR_RESOURCE_ERROR, /* 1217 */ XML_XPTR_SUB_RESOURCE_ERROR, /* 1218 */ XML_XPATH_UNDEF_PREFIX_ERROR, /* 1219 */ XML_XPATH_ENCODING_ERROR, /* 1220 */ XML_XPATH_INVALID_CHAR_ERROR, /* 1221 */ XML_TREE_INVALID_HEX = 1300, XML_TREE_INVALID_DEC, /* 1301 */ XML_TREE_UNTERMINATED_ENTITY, /* 1302 */ XML_TREE_NOT_UTF8, /* 1303 */ XML_SAVE_NOT_UTF8 = 1400, XML_SAVE_CHAR_INVALID, /* 1401 */ XML_SAVE_NO_DOCTYPE, /* 1402 */ XML_SAVE_UNKNOWN_ENCODING, /* 1403 */ XML_REGEXP_COMPILE_ERROR = 1450, XML_IO_UNKNOWN = 1500, XML_IO_EACCES, /* 1501 */ XML_IO_EAGAIN, /* 1502 */ XML_IO_EBADF, /* 1503 */ XML_IO_EBADMSG, /* 1504 */ XML_IO_EBUSY, /* 1505 */ XML_IO_ECANCELED, /* 1506 */ XML_IO_ECHILD, /* 1507 */ XML_IO_EDEADLK, /* 1508 */ XML_IO_EDOM, /* 1509 */ XML_IO_EEXIST, /* 1510 */ XML_IO_EFAULT, /* 1511 */ XML_IO_EFBIG, /* 1512 */ XML_IO_EINPROGRESS, /* 1513 */ XML_IO_EINTR, /* 1514 */ XML_IO_EINVAL, /* 1515 */ XML_IO_EIO, /* 1516 */ XML_IO_EISDIR, /* 1517 */ XML_IO_EMFILE, /* 1518 */ XML_IO_EMLINK, /* 1519 */ XML_IO_EMSGSIZE, /* 1520 */ XML_IO_ENAMETOOLONG, /* 1521 */ XML_IO_ENFILE, /* 1522 */ XML_IO_ENODEV, /* 1523 */ XML_IO_ENOENT, /* 1524 */ XML_IO_ENOEXEC, /* 1525 */ XML_IO_ENOLCK, /* 1526 */ XML_IO_ENOMEM, /* 1527 */ XML_IO_ENOSPC, /* 1528 */ XML_IO_ENOSYS, /* 1529 */ XML_IO_ENOTDIR, /* 1530 */ XML_IO_ENOTEMPTY, /* 1531 */ XML_IO_ENOTSUP, /* 1532 */ XML_IO_ENOTTY, /* 1533 */ XML_IO_ENXIO, /* 1534 */ XML_IO_EPERM, /* 1535 */ XML_IO_EPIPE, /* 1536 */ XML_IO_ERANGE, /* 1537 */ XML_IO_EROFS, /* 1538 */ XML_IO_ESPIPE, /* 1539 */ XML_IO_ESRCH, /* 1540 */ XML_IO_ETIMEDOUT, /* 1541 */ XML_IO_EXDEV, /* 1542 */ XML_IO_NETWORK_ATTEMPT, /* 1543 */ XML_IO_ENCODER, /* 1544 */ XML_IO_FLUSH, /* 1545 */ XML_IO_WRITE, /* 1546 */ XML_IO_NO_INPUT, /* 1547 */ XML_IO_BUFFER_FULL, /* 1548 */ XML_IO_LOAD_ERROR, /* 1549 */ XML_IO_ENOTSOCK, /* 1550 */ XML_IO_EISCONN, /* 1551 */ XML_IO_ECONNREFUSED, /* 1552 */ XML_IO_ENETUNREACH, /* 1553 */ XML_IO_EADDRINUSE, /* 1554 */ XML_IO_EALREADY, /* 1555 */ XML_IO_EAFNOSUPPORT, /* 1556 */ XML_XINCLUDE_RECURSION=1600, XML_XINCLUDE_PARSE_VALUE, /* 1601 */ XML_XINCLUDE_ENTITY_DEF_MISMATCH, /* 1602 */ XML_XINCLUDE_NO_HREF, /* 1603 */ XML_XINCLUDE_NO_FALLBACK, /* 1604 */ XML_XINCLUDE_HREF_URI, /* 1605 */ XML_XINCLUDE_TEXT_FRAGMENT, /* 1606 */ XML_XINCLUDE_TEXT_DOCUMENT, /* 1607 */ XML_XINCLUDE_INVALID_CHAR, /* 1608 */ XML_XINCLUDE_BUILD_FAILED, /* 1609 */ XML_XINCLUDE_UNKNOWN_ENCODING, /* 1610 */ XML_XINCLUDE_MULTIPLE_ROOT, /* 1611 */ XML_XINCLUDE_XPTR_FAILED, /* 1612 */ XML_XINCLUDE_XPTR_RESULT, /* 1613 */ XML_XINCLUDE_INCLUDE_IN_INCLUDE, /* 1614 */ XML_XINCLUDE_FALLBACKS_IN_INCLUDE, /* 1615 */ XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE, /* 1616 */ XML_XINCLUDE_DEPRECATED_NS, /* 1617 */ XML_XINCLUDE_FRAGMENT_ID, /* 1618 */ XML_CATALOG_MISSING_ATTR = 1650, XML_CATALOG_ENTRY_BROKEN, /* 1651 */ XML_CATALOG_PREFER_VALUE, /* 1652 */ XML_CATALOG_NOT_CATALOG, /* 1653 */ XML_CATALOG_RECURSION, /* 1654 */ XML_SCHEMAP_PREFIX_UNDEFINED = 1700, XML_SCHEMAP_ATTRFORMDEFAULT_VALUE, /* 1701 */ XML_SCHEMAP_ATTRGRP_NONAME_NOREF, /* 1702 */ XML_SCHEMAP_ATTR_NONAME_NOREF, /* 1703 */ XML_SCHEMAP_COMPLEXTYPE_NONAME_NOREF, /* 1704 */ XML_SCHEMAP_ELEMFORMDEFAULT_VALUE, /* 1705 */ XML_SCHEMAP_ELEM_NONAME_NOREF, /* 1706 */ XML_SCHEMAP_EXTENSION_NO_BASE, /* 1707 */ XML_SCHEMAP_FACET_NO_VALUE, /* 1708 */ XML_SCHEMAP_FAILED_BUILD_IMPORT, /* 1709 */ XML_SCHEMAP_GROUP_NONAME_NOREF, /* 1710 */ XML_SCHEMAP_IMPORT_NAMESPACE_NOT_URI, /* 1711 */ XML_SCHEMAP_IMPORT_REDEFINE_NSNAME, /* 1712 */ XML_SCHEMAP_IMPORT_SCHEMA_NOT_URI, /* 1713 */ XML_SCHEMAP_INVALID_BOOLEAN, /* 1714 */ XML_SCHEMAP_INVALID_ENUM, /* 1715 */ XML_SCHEMAP_INVALID_FACET, /* 1716 */ XML_SCHEMAP_INVALID_FACET_VALUE, /* 1717 */ XML_SCHEMAP_INVALID_MAXOCCURS, /* 1718 */ XML_SCHEMAP_INVALID_MINOCCURS, /* 1719 */ XML_SCHEMAP_INVALID_REF_AND_SUBTYPE, /* 1720 */ XML_SCHEMAP_INVALID_WHITE_SPACE, /* 1721 */ XML_SCHEMAP_NOATTR_NOREF, /* 1722 */ XML_SCHEMAP_NOTATION_NO_NAME, /* 1723 */ XML_SCHEMAP_NOTYPE_NOREF, /* 1724 */ XML_SCHEMAP_REF_AND_SUBTYPE, /* 1725 */ XML_SCHEMAP_RESTRICTION_NONAME_NOREF, /* 1726 */ XML_SCHEMAP_SIMPLETYPE_NONAME, /* 1727 */ XML_SCHEMAP_TYPE_AND_SUBTYPE, /* 1728 */ XML_SCHEMAP_UNKNOWN_ALL_CHILD, /* 1729 */ XML_SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD, /* 1730 */ XML_SCHEMAP_UNKNOWN_ATTR_CHILD, /* 1731 */ XML_SCHEMAP_UNKNOWN_ATTRGRP_CHILD, /* 1732 */ XML_SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP, /* 1733 */ XML_SCHEMAP_UNKNOWN_BASE_TYPE, /* 1734 */ XML_SCHEMAP_UNKNOWN_CHOICE_CHILD, /* 1735 */ XML_SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD, /* 1736 */ XML_SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD, /* 1737 */ XML_SCHEMAP_UNKNOWN_ELEM_CHILD, /* 1738 */ XML_SCHEMAP_UNKNOWN_EXTENSION_CHILD, /* 1739 */ XML_SCHEMAP_UNKNOWN_FACET_CHILD, /* 1740 */ XML_SCHEMAP_UNKNOWN_FACET_TYPE, /* 1741 */ XML_SCHEMAP_UNKNOWN_GROUP_CHILD, /* 1742 */ XML_SCHEMAP_UNKNOWN_IMPORT_CHILD, /* 1743 */ XML_SCHEMAP_UNKNOWN_LIST_CHILD, /* 1744 */ XML_SCHEMAP_UNKNOWN_NOTATION_CHILD, /* 1745 */ XML_SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD, /* 1746 */ XML_SCHEMAP_UNKNOWN_REF, /* 1747 */ XML_SCHEMAP_UNKNOWN_RESTRICTION_CHILD, /* 1748 */ XML_SCHEMAP_UNKNOWN_SCHEMAS_CHILD, /* 1749 */ XML_SCHEMAP_UNKNOWN_SEQUENCE_CHILD, /* 1750 */ XML_SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD, /* 1751 */ XML_SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD, /* 1752 */ XML_SCHEMAP_UNKNOWN_TYPE, /* 1753 */ XML_SCHEMAP_UNKNOWN_UNION_CHILD, /* 1754 */ XML_SCHEMAP_ELEM_DEFAULT_FIXED, /* 1755 */ XML_SCHEMAP_REGEXP_INVALID, /* 1756 */ XML_SCHEMAP_FAILED_LOAD, /* 1757 */ XML_SCHEMAP_NOTHING_TO_PARSE, /* 1758 */ XML_SCHEMAP_NOROOT, /* 1759 */ XML_SCHEMAP_REDEFINED_GROUP, /* 1760 */ XML_SCHEMAP_REDEFINED_TYPE, /* 1761 */ XML_SCHEMAP_REDEFINED_ELEMENT, /* 1762 */ XML_SCHEMAP_REDEFINED_ATTRGROUP, /* 1763 */ XML_SCHEMAP_REDEFINED_ATTR, /* 1764 */ XML_SCHEMAP_REDEFINED_NOTATION, /* 1765 */ XML_SCHEMAP_FAILED_PARSE, /* 1766 */ XML_SCHEMAP_UNKNOWN_PREFIX, /* 1767 */ XML_SCHEMAP_DEF_AND_PREFIX, /* 1768 */ XML_SCHEMAP_UNKNOWN_INCLUDE_CHILD, /* 1769 */ XML_SCHEMAP_INCLUDE_SCHEMA_NOT_URI, /* 1770 */ XML_SCHEMAP_INCLUDE_SCHEMA_NO_URI, /* 1771 */ XML_SCHEMAP_NOT_SCHEMA, /* 1772 */ XML_SCHEMAP_UNKNOWN_MEMBER_TYPE, /* 1773 */ XML_SCHEMAP_INVALID_ATTR_USE, /* 1774 */ XML_SCHEMAP_RECURSIVE, /* 1775 */ XML_SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE, /* 1776 */ XML_SCHEMAP_INVALID_ATTR_COMBINATION, /* 1777 */ XML_SCHEMAP_INVALID_ATTR_INLINE_COMBINATION, /* 1778 */ XML_SCHEMAP_MISSING_SIMPLETYPE_CHILD, /* 1779 */ XML_SCHEMAP_INVALID_ATTR_NAME, /* 1780 */ XML_SCHEMAP_REF_AND_CONTENT, /* 1781 */ XML_SCHEMAP_CT_PROPS_CORRECT_1, /* 1782 */ XML_SCHEMAP_CT_PROPS_CORRECT_2, /* 1783 */ XML_SCHEMAP_CT_PROPS_CORRECT_3, /* 1784 */ XML_SCHEMAP_CT_PROPS_CORRECT_4, /* 1785 */ XML_SCHEMAP_CT_PROPS_CORRECT_5, /* 1786 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, /* 1787 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1, /* 1788 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2, /* 1789 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2, /* 1790 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3, /* 1791 */ XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER, /* 1792 */ XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE, /* 1793 */ XML_SCHEMAP_UNION_NOT_EXPRESSIBLE, /* 1794 */ XML_SCHEMAP_SRC_IMPORT_3_1, /* 1795 */ XML_SCHEMAP_SRC_IMPORT_3_2, /* 1796 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1, /* 1797 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2, /* 1798 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_3, /* 1799 */ XML_SCHEMAP_COS_CT_EXTENDS_1_3, /* 1800 */ XML_SCHEMAV_NOROOT = 1801, XML_SCHEMAV_UNDECLAREDELEM, /* 1802 */ XML_SCHEMAV_NOTTOPLEVEL, /* 1803 */ XML_SCHEMAV_MISSING, /* 1804 */ XML_SCHEMAV_WRONGELEM, /* 1805 */ XML_SCHEMAV_NOTYPE, /* 1806 */ XML_SCHEMAV_NOROLLBACK, /* 1807 */ XML_SCHEMAV_ISABSTRACT, /* 1808 */ XML_SCHEMAV_NOTEMPTY, /* 1809 */ XML_SCHEMAV_ELEMCONT, /* 1810 */ XML_SCHEMAV_HAVEDEFAULT, /* 1811 */ XML_SCHEMAV_NOTNILLABLE, /* 1812 */ XML_SCHEMAV_EXTRACONTENT, /* 1813 */ XML_SCHEMAV_INVALIDATTR, /* 1814 */ XML_SCHEMAV_INVALIDELEM, /* 1815 */ XML_SCHEMAV_NOTDETERMINIST, /* 1816 */ XML_SCHEMAV_CONSTRUCT, /* 1817 */ XML_SCHEMAV_INTERNAL, /* 1818 */ XML_SCHEMAV_NOTSIMPLE, /* 1819 */ XML_SCHEMAV_ATTRUNKNOWN, /* 1820 */ XML_SCHEMAV_ATTRINVALID, /* 1821 */ XML_SCHEMAV_VALUE, /* 1822 */ XML_SCHEMAV_FACET, /* 1823 */ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1, /* 1824 */ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2, /* 1825 */ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3, /* 1826 */ XML_SCHEMAV_CVC_TYPE_3_1_1, /* 1827 */ XML_SCHEMAV_CVC_TYPE_3_1_2, /* 1828 */ XML_SCHEMAV_CVC_FACET_VALID, /* 1829 */ XML_SCHEMAV_CVC_LENGTH_VALID, /* 1830 */ XML_SCHEMAV_CVC_MINLENGTH_VALID, /* 1831 */ XML_SCHEMAV_CVC_MAXLENGTH_VALID, /* 1832 */ XML_SCHEMAV_CVC_MININCLUSIVE_VALID, /* 1833 */ XML_SCHEMAV_CVC_MAXINCLUSIVE_VALID, /* 1834 */ XML_SCHEMAV_CVC_MINEXCLUSIVE_VALID, /* 1835 */ XML_SCHEMAV_CVC_MAXEXCLUSIVE_VALID, /* 1836 */ XML_SCHEMAV_CVC_TOTALDIGITS_VALID, /* 1837 */ XML_SCHEMAV_CVC_FRACTIONDIGITS_VALID, /* 1838 */ XML_SCHEMAV_CVC_PATTERN_VALID, /* 1839 */ XML_SCHEMAV_CVC_ENUMERATION_VALID, /* 1840 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1, /* 1841 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2, /* 1842 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3, /* 1843 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_4, /* 1844 */ XML_SCHEMAV_CVC_ELT_1, /* 1845 */ XML_SCHEMAV_CVC_ELT_2, /* 1846 */ XML_SCHEMAV_CVC_ELT_3_1, /* 1847 */ XML_SCHEMAV_CVC_ELT_3_2_1, /* 1848 */ XML_SCHEMAV_CVC_ELT_3_2_2, /* 1849 */ XML_SCHEMAV_CVC_ELT_4_1, /* 1850 */ XML_SCHEMAV_CVC_ELT_4_2, /* 1851 */ XML_SCHEMAV_CVC_ELT_4_3, /* 1852 */ XML_SCHEMAV_CVC_ELT_5_1_1, /* 1853 */ XML_SCHEMAV_CVC_ELT_5_1_2, /* 1854 */ XML_SCHEMAV_CVC_ELT_5_2_1, /* 1855 */ XML_SCHEMAV_CVC_ELT_5_2_2_1, /* 1856 */ XML_SCHEMAV_CVC_ELT_5_2_2_2_1, /* 1857 */ XML_SCHEMAV_CVC_ELT_5_2_2_2_2, /* 1858 */ XML_SCHEMAV_CVC_ELT_6, /* 1859 */ XML_SCHEMAV_CVC_ELT_7, /* 1860 */ XML_SCHEMAV_CVC_ATTRIBUTE_1, /* 1861 */ XML_SCHEMAV_CVC_ATTRIBUTE_2, /* 1862 */ XML_SCHEMAV_CVC_ATTRIBUTE_3, /* 1863 */ XML_SCHEMAV_CVC_ATTRIBUTE_4, /* 1864 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_1, /* 1865 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1, /* 1866 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_2, /* 1867 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_4, /* 1868 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_1, /* 1869 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_2, /* 1870 */ XML_SCHEMAV_ELEMENT_CONTENT, /* 1871 */ XML_SCHEMAV_DOCUMENT_ELEMENT_MISSING, /* 1872 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_1, /* 1873 */ XML_SCHEMAV_CVC_AU, /* 1874 */ XML_SCHEMAV_CVC_TYPE_1, /* 1875 */ XML_SCHEMAV_CVC_TYPE_2, /* 1876 */ XML_SCHEMAV_CVC_IDC, /* 1877 */ XML_SCHEMAV_CVC_WILDCARD, /* 1878 */ XML_SCHEMAV_MISC, /* 1879 */ XML_XPTR_UNKNOWN_SCHEME = 1900, XML_XPTR_CHILDSEQ_START, /* 1901 */ XML_XPTR_EVAL_FAILED, /* 1902 */ XML_XPTR_EXTRA_OBJECTS, /* 1903 */ XML_C14N_CREATE_CTXT = 1950, XML_C14N_REQUIRES_UTF8, /* 1951 */ XML_C14N_CREATE_STACK, /* 1952 */ XML_C14N_INVALID_NODE, /* 1953 */ XML_C14N_UNKNOW_NODE, /* 1954 */ XML_C14N_RELATIVE_NAMESPACE, /* 1955 */ XML_FTP_PASV_ANSWER = 2000, XML_FTP_EPSV_ANSWER, /* 2001 */ XML_FTP_ACCNT, /* 2002 */ XML_FTP_URL_SYNTAX, /* 2003 */ XML_HTTP_URL_SYNTAX = 2020, XML_HTTP_USE_IP, /* 2021 */ XML_HTTP_UNKNOWN_HOST, /* 2022 */ XML_SCHEMAP_SRC_SIMPLE_TYPE_1 = 3000, XML_SCHEMAP_SRC_SIMPLE_TYPE_2, /* 3001 */ XML_SCHEMAP_SRC_SIMPLE_TYPE_3, /* 3002 */ XML_SCHEMAP_SRC_SIMPLE_TYPE_4, /* 3003 */ XML_SCHEMAP_SRC_RESOLVE, /* 3004 */ XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE, /* 3005 */ XML_SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE, /* 3006 */ XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES, /* 3007 */ XML_SCHEMAP_ST_PROPS_CORRECT_1, /* 3008 */ XML_SCHEMAP_ST_PROPS_CORRECT_2, /* 3009 */ XML_SCHEMAP_ST_PROPS_CORRECT_3, /* 3010 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_1, /* 3011 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_2, /* 3012 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1, /* 3013 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_2, /* 3014 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_1, /* 3015 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1, /* 3016 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2, /* 3017 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1, /* 3018 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2, /* 3019 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3, /* 3020 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4, /* 3021 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_5, /* 3022 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_1, /* 3023 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1, /* 3024 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2, /* 3025 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2, /* 3026 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1, /* 3027 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3, /* 3028 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4, /* 3029 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_5, /* 3030 */ XML_SCHEMAP_COS_ST_DERIVED_OK_2_1, /* 3031 */ XML_SCHEMAP_COS_ST_DERIVED_OK_2_2, /* 3032 */ XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, /* 3033 */ XML_SCHEMAP_S4S_ELEM_MISSING, /* 3034 */ XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, /* 3035 */ XML_SCHEMAP_S4S_ATTR_MISSING, /* 3036 */ XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* 3037 */ XML_SCHEMAP_SRC_ELEMENT_1, /* 3038 */ XML_SCHEMAP_SRC_ELEMENT_2_1, /* 3039 */ XML_SCHEMAP_SRC_ELEMENT_2_2, /* 3040 */ XML_SCHEMAP_SRC_ELEMENT_3, /* 3041 */ XML_SCHEMAP_P_PROPS_CORRECT_1, /* 3042 */ XML_SCHEMAP_P_PROPS_CORRECT_2_1, /* 3043 */ XML_SCHEMAP_P_PROPS_CORRECT_2_2, /* 3044 */ XML_SCHEMAP_E_PROPS_CORRECT_2, /* 3045 */ XML_SCHEMAP_E_PROPS_CORRECT_3, /* 3046 */ XML_SCHEMAP_E_PROPS_CORRECT_4, /* 3047 */ XML_SCHEMAP_E_PROPS_CORRECT_5, /* 3048 */ XML_SCHEMAP_E_PROPS_CORRECT_6, /* 3049 */ XML_SCHEMAP_SRC_INCLUDE, /* 3050 */ XML_SCHEMAP_SRC_ATTRIBUTE_1, /* 3051 */ XML_SCHEMAP_SRC_ATTRIBUTE_2, /* 3052 */ XML_SCHEMAP_SRC_ATTRIBUTE_3_1, /* 3053 */ XML_SCHEMAP_SRC_ATTRIBUTE_3_2, /* 3054 */ XML_SCHEMAP_SRC_ATTRIBUTE_4, /* 3055 */ XML_SCHEMAP_NO_XMLNS, /* 3056 */ XML_SCHEMAP_NO_XSI, /* 3057 */ XML_SCHEMAP_COS_VALID_DEFAULT_1, /* 3058 */ XML_SCHEMAP_COS_VALID_DEFAULT_2_1, /* 3059 */ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_1, /* 3060 */ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_2, /* 3061 */ XML_SCHEMAP_CVC_SIMPLE_TYPE, /* 3062 */ XML_SCHEMAP_COS_CT_EXTENDS_1_1, /* 3063 */ XML_SCHEMAP_SRC_IMPORT_1_1, /* 3064 */ XML_SCHEMAP_SRC_IMPORT_1_2, /* 3065 */ XML_SCHEMAP_SRC_IMPORT_2, /* 3066 */ XML_SCHEMAP_SRC_IMPORT_2_1, /* 3067 */ XML_SCHEMAP_SRC_IMPORT_2_2, /* 3068 */ XML_SCHEMAP_INTERNAL, /* 3069 non-W3C */ XML_SCHEMAP_NOT_DETERMINISTIC, /* 3070 non-W3C */ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_1, /* 3071 */ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_2, /* 3072 */ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_3, /* 3073 */ XML_SCHEMAP_MG_PROPS_CORRECT_1, /* 3074 */ XML_SCHEMAP_MG_PROPS_CORRECT_2, /* 3075 */ XML_SCHEMAP_SRC_CT_1, /* 3076 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3, /* 3077 */ XML_SCHEMAP_AU_PROPS_CORRECT_2, /* 3078 */ XML_SCHEMAP_A_PROPS_CORRECT_2, /* 3079 */ XML_SCHEMAP_C_PROPS_CORRECT, /* 3080 */ XML_SCHEMAP_SRC_REDEFINE, /* 3081 */ XML_SCHEMAP_SRC_IMPORT, /* 3082 */ XML_SCHEMAP_WARN_SKIP_SCHEMA, /* 3083 */ XML_SCHEMAP_WARN_UNLOCATED_SCHEMA, /* 3084 */ XML_SCHEMAP_WARN_ATTR_REDECL_PROH, /* 3085 */ XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH, /* 3085 */ XML_SCHEMAP_AG_PROPS_CORRECT, /* 3086 */ XML_SCHEMAP_COS_CT_EXTENDS_1_2, /* 3087 */ XML_SCHEMAP_AU_PROPS_CORRECT, /* 3088 */ XML_SCHEMAP_A_PROPS_CORRECT_3, /* 3089 */ XML_SCHEMAP_COS_ALL_LIMITED, /* 3090 */ XML_SCHEMATRONV_ASSERT = 4000, /* 4000 */ XML_SCHEMATRONV_REPORT, XML_MODULE_OPEN = 4900, /* 4900 */ XML_MODULE_CLOSE, /* 4901 */ XML_CHECK_FOUND_ELEMENT = 5000, XML_CHECK_FOUND_ATTRIBUTE, /* 5001 */ XML_CHECK_FOUND_TEXT, /* 5002 */ XML_CHECK_FOUND_CDATA, /* 5003 */ XML_CHECK_FOUND_ENTITYREF, /* 5004 */ XML_CHECK_FOUND_ENTITY, /* 5005 */ XML_CHECK_FOUND_PI, /* 5006 */ XML_CHECK_FOUND_COMMENT, /* 5007 */ XML_CHECK_FOUND_DOCTYPE, /* 5008 */ XML_CHECK_FOUND_FRAGMENT, /* 5009 */ XML_CHECK_FOUND_NOTATION, /* 5010 */ XML_CHECK_UNKNOWN_NODE, /* 5011 */ XML_CHECK_ENTITY_TYPE, /* 5012 */ XML_CHECK_NO_PARENT, /* 5013 */ XML_CHECK_NO_DOC, /* 5014 */ XML_CHECK_NO_NAME, /* 5015 */ XML_CHECK_NO_ELEM, /* 5016 */ XML_CHECK_WRONG_DOC, /* 5017 */ XML_CHECK_NO_PREV, /* 5018 */ XML_CHECK_WRONG_PREV, /* 5019 */ XML_CHECK_NO_NEXT, /* 5020 */ XML_CHECK_WRONG_NEXT, /* 5021 */ XML_CHECK_NOT_DTD, /* 5022 */ XML_CHECK_NOT_ATTR, /* 5023 */ XML_CHECK_NOT_ATTR_DECL, /* 5024 */ XML_CHECK_NOT_ELEM_DECL, /* 5025 */ XML_CHECK_NOT_ENTITY_DECL, /* 5026 */ XML_CHECK_NOT_NS_DECL, /* 5027 */ XML_CHECK_NO_HREF, /* 5028 */ XML_CHECK_WRONG_PARENT,/* 5029 */ XML_CHECK_NS_SCOPE, /* 5030 */ XML_CHECK_NS_ANCESTOR, /* 5031 */ XML_CHECK_NOT_UTF8, /* 5032 */ XML_CHECK_NO_DICT, /* 5033 */ XML_CHECK_NOT_NCNAME, /* 5034 */ XML_CHECK_OUTSIDE_DICT, /* 5035 */ XML_CHECK_WRONG_NAME, /* 5036 */ XML_CHECK_NAME_NOT_NULL, /* 5037 */ XML_I18N_NO_NAME = 6000, XML_I18N_NO_HANDLER, /* 6001 */ XML_I18N_EXCESS_HANDLER, /* 6002 */ XML_I18N_CONV_FAILED, /* 6003 */ XML_I18N_NO_OUTPUT, /* 6004 */ XML_BUF_OVERFLOW = 7000 } xmlParserErrors; /** * xmlGenericErrorFunc: * @ctx: a parsing context * @msg: the message * @...: the extra arguments of the varargs to format the message * * Signature of the function to use when there is an error and * no parsing or validity context available . */ typedef void (*xmlGenericErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlStructuredErrorFunc: * @userData: user provided data for the error callback * @error: the error being raised. * * Signature of the function to use when there is an error and * the module handles the new error reporting mechanism. */ typedef void (*xmlStructuredErrorFunc) (void *userData, xmlErrorPtr error); /* * Use the following function to reset the two global variables * xmlGenericError and xmlGenericErrorContext. */ XMLPUBFUN void xmlSetGenericErrorFunc (void *ctx, xmlGenericErrorFunc handler); XML_DEPRECATED XMLPUBFUN void initGenericErrorDefaultFunc (xmlGenericErrorFunc *handler); XMLPUBFUN void xmlSetStructuredErrorFunc (void *ctx, xmlStructuredErrorFunc handler); /* * Default message routines used by SAX and Valid context for error * and warning reporting. */ XMLPUBFUN void xmlParserError (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserWarning (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserValidityError (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserValidityWarning (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserPrintFileInfo (xmlParserInputPtr input); XMLPUBFUN void xmlParserPrintFileContext (xmlParserInputPtr input); /* * Extended error information routines */ XMLPUBFUN xmlErrorPtr xmlGetLastError (void); XMLPUBFUN void xmlResetLastError (void); XMLPUBFUN xmlErrorPtr xmlCtxtGetLastError (void *ctx); XMLPUBFUN void xmlCtxtResetLastError (void *ctx); XMLPUBFUN void xmlResetError (xmlErrorPtr err); XMLPUBFUN int xmlCopyError (xmlErrorPtr from, xmlErrorPtr to); #ifdef __cplusplus } #endif #endif /* __XML_ERROR_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlexports.h ================================================ /* * Summary: macros for marking symbols as exportable/importable. * Description: macros for marking symbols as exportable/importable. * * Copy: See Copyright for the status of this software. */ #ifndef __XML_EXPORTS_H__ #define __XML_EXPORTS_H__ /** DOC_DISABLE */ #if defined(_WIN32) || defined(__CYGWIN__) #ifdef LIBXML_STATIC #define XMLPUBLIC #elif defined(IN_LIBXML) #define XMLPUBLIC __declspec(dllexport) #else #define XMLPUBLIC __declspec(dllimport) #endif #else /* not Windows */ #define XMLPUBLIC #endif /* platform switch */ /** DOC_ENABLE */ /* * XMLPUBFUN: * * Macro which declares an exportable function */ #define XMLPUBFUN XMLPUBLIC /** * XMLPUBVAR: * * Macro which declares an exportable variable */ #define XMLPUBVAR XMLPUBLIC extern /** DOC_DISABLE */ /* Compatibility */ #define XMLCALL #define XMLCDECL #if !defined(LIBXML_DLL_IMPORT) #define LIBXML_DLL_IMPORT XMLPUBVAR #endif /** DOC_ENABLE */ #endif /* __XML_EXPORTS_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlmemory.h ================================================ /* * Summary: interface for the memory allocator * Description: provides interfaces for the memory allocator, * including debugging capabilities. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __DEBUG_MEMORY_ALLOC__ #define __DEBUG_MEMORY_ALLOC__ #include #include /** * DEBUG_MEMORY: * * DEBUG_MEMORY replaces the allocator with a collect and debug * shell to the libc allocator. * DEBUG_MEMORY should only be activated when debugging * libxml i.e. if libxml has been configured with --with-debug-mem too. */ /* #define DEBUG_MEMORY_FREED */ /* #define DEBUG_MEMORY_LOCATION */ #ifdef DEBUG #ifndef DEBUG_MEMORY #define DEBUG_MEMORY #endif #endif /** * DEBUG_MEMORY_LOCATION: * * DEBUG_MEMORY_LOCATION should be activated only when debugging * libxml i.e. if libxml has been configured with --with-debug-mem too. */ #ifdef DEBUG_MEMORY_LOCATION #endif #ifdef __cplusplus extern "C" { #endif /* * The XML memory wrapper support 4 basic overloadable functions. */ /** * xmlFreeFunc: * @mem: an already allocated block of memory * * Signature for a free() implementation. */ typedef void (*xmlFreeFunc)(void *mem); /** * xmlMallocFunc: * @size: the size requested in bytes * * Signature for a malloc() implementation. * * Returns a pointer to the newly allocated block or NULL in case of error. */ typedef void *(LIBXML_ATTR_ALLOC_SIZE(1) *xmlMallocFunc)(size_t size); /** * xmlReallocFunc: * @mem: an already allocated block of memory * @size: the new size requested in bytes * * Signature for a realloc() implementation. * * Returns a pointer to the newly reallocated block or NULL in case of error. */ typedef void *(*xmlReallocFunc)(void *mem, size_t size); /** * xmlStrdupFunc: * @str: a zero terminated string * * Signature for an strdup() implementation. * * Returns the copy of the string or NULL in case of error. */ typedef char *(*xmlStrdupFunc)(const char *str); /* * The 4 interfaces used for all memory handling within libxml. LIBXML_DLL_IMPORT xmlFreeFunc xmlFree; LIBXML_DLL_IMPORT xmlMallocFunc xmlMalloc; LIBXML_DLL_IMPORT xmlMallocFunc xmlMallocAtomic; LIBXML_DLL_IMPORT xmlReallocFunc xmlRealloc; LIBXML_DLL_IMPORT xmlStrdupFunc xmlMemStrdup; */ /* * The way to overload the existing functions. * The xmlGc function have an extra entry for atomic block * allocations useful for garbage collected memory allocators */ XMLPUBFUN int xmlMemSetup (xmlFreeFunc freeFunc, xmlMallocFunc mallocFunc, xmlReallocFunc reallocFunc, xmlStrdupFunc strdupFunc); XMLPUBFUN int xmlMemGet (xmlFreeFunc *freeFunc, xmlMallocFunc *mallocFunc, xmlReallocFunc *reallocFunc, xmlStrdupFunc *strdupFunc); XMLPUBFUN int xmlGcMemSetup (xmlFreeFunc freeFunc, xmlMallocFunc mallocFunc, xmlMallocFunc mallocAtomicFunc, xmlReallocFunc reallocFunc, xmlStrdupFunc strdupFunc); XMLPUBFUN int xmlGcMemGet (xmlFreeFunc *freeFunc, xmlMallocFunc *mallocFunc, xmlMallocFunc *mallocAtomicFunc, xmlReallocFunc *reallocFunc, xmlStrdupFunc *strdupFunc); /* * Initialization of the memory layer. */ XML_DEPRECATED XMLPUBFUN int xmlInitMemory (void); /* * Cleanup of the memory layer. */ XML_DEPRECATED XMLPUBFUN void xmlCleanupMemory (void); /* * These are specific to the XML debug memory wrapper. */ XMLPUBFUN size_t xmlMemSize (void *ptr); XMLPUBFUN int xmlMemUsed (void); XMLPUBFUN int xmlMemBlocks (void); XMLPUBFUN void xmlMemDisplay (FILE *fp); XMLPUBFUN void xmlMemDisplayLast(FILE *fp, long nbBytes); XMLPUBFUN void xmlMemShow (FILE *fp, int nr); XMLPUBFUN void xmlMemoryDump (void); XMLPUBFUN void * xmlMemMalloc (size_t size) LIBXML_ATTR_ALLOC_SIZE(1); XMLPUBFUN void * xmlMemRealloc (void *ptr,size_t size); XMLPUBFUN void xmlMemFree (void *ptr); XMLPUBFUN char * xmlMemoryStrdup (const char *str); XMLPUBFUN void * xmlMallocLoc (size_t size, const char *file, int line) LIBXML_ATTR_ALLOC_SIZE(1); XMLPUBFUN void * xmlReallocLoc (void *ptr, size_t size, const char *file, int line); XMLPUBFUN void * xmlMallocAtomicLoc (size_t size, const char *file, int line) LIBXML_ATTR_ALLOC_SIZE(1); XMLPUBFUN char * xmlMemStrdupLoc (const char *str, const char *file, int line); #ifdef DEBUG_MEMORY_LOCATION /** * xmlMalloc: * @size: number of bytes to allocate * * Wrapper for the malloc() function used in the XML library. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlMalloc(size) xmlMallocLoc((size), __FILE__, __LINE__) /** * xmlMallocAtomic: * @size: number of bytes to allocate * * Wrapper for the malloc() function used in the XML library for allocation * of block not containing pointers to other areas. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlMallocAtomic(size) xmlMallocAtomicLoc((size), __FILE__, __LINE__) /** * xmlRealloc: * @ptr: pointer to the existing allocated area * @size: number of bytes to allocate * * Wrapper for the realloc() function used in the XML library. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlRealloc(ptr, size) xmlReallocLoc((ptr), (size), __FILE__, __LINE__) /** * xmlMemStrdup: * @str: pointer to the existing string * * Wrapper for the strdup() function, xmlStrdup() is usually preferred. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlMemStrdup(str) xmlMemStrdupLoc((str), __FILE__, __LINE__) #endif /* DEBUG_MEMORY_LOCATION */ #ifdef __cplusplus } #endif /* __cplusplus */ #ifndef __XML_GLOBALS_H #ifndef __XML_THREADS_H__ #include #include #endif #endif #endif /* __DEBUG_MEMORY_ALLOC__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlmodule.h ================================================ /* * Summary: dynamic module loading * Description: basic API for dynamic module loading, used by * libexslt added in 2.6.17 * * Copy: See Copyright for the status of this software. * * Author: Joel W. Reed */ #ifndef __XML_MODULE_H__ #define __XML_MODULE_H__ #include #ifdef LIBXML_MODULES_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlModulePtr: * * A handle to a dynamically loaded module */ typedef struct _xmlModule xmlModule; typedef xmlModule *xmlModulePtr; /** * xmlModuleOption: * * enumeration of options that can be passed down to xmlModuleOpen() */ typedef enum { XML_MODULE_LAZY = 1, /* lazy binding */ XML_MODULE_LOCAL= 2 /* local binding */ } xmlModuleOption; XMLPUBFUN xmlModulePtr xmlModuleOpen (const char *filename, int options); XMLPUBFUN int xmlModuleSymbol (xmlModulePtr module, const char* name, void **result); XMLPUBFUN int xmlModuleClose (xmlModulePtr module); XMLPUBFUN int xmlModuleFree (xmlModulePtr module); #ifdef __cplusplus } #endif #endif /* LIBXML_MODULES_ENABLED */ #endif /*__XML_MODULE_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlreader.h ================================================ /* * Summary: the XMLReader implementation * Description: API of the XML streaming API based on C# interfaces. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XMLREADER_H__ #define __XML_XMLREADER_H__ #include #include #include #ifdef LIBXML_SCHEMAS_ENABLED #include #include #endif #ifdef __cplusplus extern "C" { #endif /** * xmlParserSeverities: * * How severe an error callback is when the per-reader error callback API * is used. */ typedef enum { XML_PARSER_SEVERITY_VALIDITY_WARNING = 1, XML_PARSER_SEVERITY_VALIDITY_ERROR = 2, XML_PARSER_SEVERITY_WARNING = 3, XML_PARSER_SEVERITY_ERROR = 4 } xmlParserSeverities; #ifdef LIBXML_READER_ENABLED /** * xmlTextReaderMode: * * Internal state values for the reader. */ typedef enum { XML_TEXTREADER_MODE_INITIAL = 0, XML_TEXTREADER_MODE_INTERACTIVE = 1, XML_TEXTREADER_MODE_ERROR = 2, XML_TEXTREADER_MODE_EOF =3, XML_TEXTREADER_MODE_CLOSED = 4, XML_TEXTREADER_MODE_READING = 5 } xmlTextReaderMode; /** * xmlParserProperties: * * Some common options to use with xmlTextReaderSetParserProp, but it * is better to use xmlParserOption and the xmlReaderNewxxx and * xmlReaderForxxx APIs now. */ typedef enum { XML_PARSER_LOADDTD = 1, XML_PARSER_DEFAULTATTRS = 2, XML_PARSER_VALIDATE = 3, XML_PARSER_SUBST_ENTITIES = 4 } xmlParserProperties; /** * xmlReaderTypes: * * Predefined constants for the different types of nodes. */ typedef enum { XML_READER_TYPE_NONE = 0, XML_READER_TYPE_ELEMENT = 1, XML_READER_TYPE_ATTRIBUTE = 2, XML_READER_TYPE_TEXT = 3, XML_READER_TYPE_CDATA = 4, XML_READER_TYPE_ENTITY_REFERENCE = 5, XML_READER_TYPE_ENTITY = 6, XML_READER_TYPE_PROCESSING_INSTRUCTION = 7, XML_READER_TYPE_COMMENT = 8, XML_READER_TYPE_DOCUMENT = 9, XML_READER_TYPE_DOCUMENT_TYPE = 10, XML_READER_TYPE_DOCUMENT_FRAGMENT = 11, XML_READER_TYPE_NOTATION = 12, XML_READER_TYPE_WHITESPACE = 13, XML_READER_TYPE_SIGNIFICANT_WHITESPACE = 14, XML_READER_TYPE_END_ELEMENT = 15, XML_READER_TYPE_END_ENTITY = 16, XML_READER_TYPE_XML_DECLARATION = 17 } xmlReaderTypes; /** * xmlTextReader: * * Structure for an xmlReader context. */ typedef struct _xmlTextReader xmlTextReader; /** * xmlTextReaderPtr: * * Pointer to an xmlReader context. */ typedef xmlTextReader *xmlTextReaderPtr; /* * Constructors & Destructor */ XMLPUBFUN xmlTextReaderPtr xmlNewTextReader (xmlParserInputBufferPtr input, const char *URI); XMLPUBFUN xmlTextReaderPtr xmlNewTextReaderFilename(const char *URI); XMLPUBFUN void xmlFreeTextReader (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderSetup(xmlTextReaderPtr reader, xmlParserInputBufferPtr input, const char *URL, const char *encoding, int options); /* * Iterators */ XMLPUBFUN int xmlTextReaderRead (xmlTextReaderPtr reader); #ifdef LIBXML_WRITER_ENABLED XMLPUBFUN xmlChar * xmlTextReaderReadInnerXml(xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderReadOuterXml(xmlTextReaderPtr reader); #endif XMLPUBFUN xmlChar * xmlTextReaderReadString (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderReadAttributeValue(xmlTextReaderPtr reader); /* * Attributes of the node */ XMLPUBFUN int xmlTextReaderAttributeCount(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderDepth (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderHasAttributes(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderHasValue(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsDefault (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsEmptyElement(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNodeType (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderQuoteChar (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderReadState (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsNamespaceDecl(xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstBaseUri (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstLocalName (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstName (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstNamespaceUri(xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstPrefix (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstXmlLang (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstString (xmlTextReaderPtr reader, const xmlChar *str); XMLPUBFUN const xmlChar * xmlTextReaderConstValue (xmlTextReaderPtr reader); /* * use the Const version of the routine for * better performance and simpler code */ XMLPUBFUN xmlChar * xmlTextReaderBaseUri (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderLocalName (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderName (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderNamespaceUri(xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderPrefix (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderXmlLang (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderValue (xmlTextReaderPtr reader); /* * Methods of the XmlTextReader */ XMLPUBFUN int xmlTextReaderClose (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderGetAttributeNo (xmlTextReaderPtr reader, int no); XMLPUBFUN xmlChar * xmlTextReaderGetAttribute (xmlTextReaderPtr reader, const xmlChar *name); XMLPUBFUN xmlChar * xmlTextReaderGetAttributeNs (xmlTextReaderPtr reader, const xmlChar *localName, const xmlChar *namespaceURI); XMLPUBFUN xmlParserInputBufferPtr xmlTextReaderGetRemainder (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderLookupNamespace(xmlTextReaderPtr reader, const xmlChar *prefix); XMLPUBFUN int xmlTextReaderMoveToAttributeNo(xmlTextReaderPtr reader, int no); XMLPUBFUN int xmlTextReaderMoveToAttribute(xmlTextReaderPtr reader, const xmlChar *name); XMLPUBFUN int xmlTextReaderMoveToAttributeNs(xmlTextReaderPtr reader, const xmlChar *localName, const xmlChar *namespaceURI); XMLPUBFUN int xmlTextReaderMoveToFirstAttribute(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderMoveToNextAttribute(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderMoveToElement (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNormalization (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstEncoding (xmlTextReaderPtr reader); /* * Extensions */ XMLPUBFUN int xmlTextReaderSetParserProp (xmlTextReaderPtr reader, int prop, int value); XMLPUBFUN int xmlTextReaderGetParserProp (xmlTextReaderPtr reader, int prop); XMLPUBFUN xmlNodePtr xmlTextReaderCurrentNode (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderGetParserLineNumber(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderGetParserColumnNumber(xmlTextReaderPtr reader); XMLPUBFUN xmlNodePtr xmlTextReaderPreserve (xmlTextReaderPtr reader); #ifdef LIBXML_PATTERN_ENABLED XMLPUBFUN int xmlTextReaderPreservePattern(xmlTextReaderPtr reader, const xmlChar *pattern, const xmlChar **namespaces); #endif /* LIBXML_PATTERN_ENABLED */ XMLPUBFUN xmlDocPtr xmlTextReaderCurrentDoc (xmlTextReaderPtr reader); XMLPUBFUN xmlNodePtr xmlTextReaderExpand (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNext (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNextSibling (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsValid (xmlTextReaderPtr reader); #ifdef LIBXML_SCHEMAS_ENABLED XMLPUBFUN int xmlTextReaderRelaxNGValidate(xmlTextReaderPtr reader, const char *rng); XMLPUBFUN int xmlTextReaderRelaxNGValidateCtxt(xmlTextReaderPtr reader, xmlRelaxNGValidCtxtPtr ctxt, int options); XMLPUBFUN int xmlTextReaderRelaxNGSetSchema(xmlTextReaderPtr reader, xmlRelaxNGPtr schema); XMLPUBFUN int xmlTextReaderSchemaValidate (xmlTextReaderPtr reader, const char *xsd); XMLPUBFUN int xmlTextReaderSchemaValidateCtxt(xmlTextReaderPtr reader, xmlSchemaValidCtxtPtr ctxt, int options); XMLPUBFUN int xmlTextReaderSetSchema (xmlTextReaderPtr reader, xmlSchemaPtr schema); #endif XMLPUBFUN const xmlChar * xmlTextReaderConstXmlVersion(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderStandalone (xmlTextReaderPtr reader); /* * Index lookup */ XMLPUBFUN long xmlTextReaderByteConsumed (xmlTextReaderPtr reader); /* * New more complete APIs for simpler creation and reuse of readers */ XMLPUBFUN xmlTextReaderPtr xmlReaderWalker (xmlDocPtr doc); XMLPUBFUN xmlTextReaderPtr xmlReaderForDoc (const xmlChar * cur, const char *URL, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForFile (const char *filename, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForMemory (const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForFd (int fd, const char *URL, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewWalker (xmlTextReaderPtr reader, xmlDocPtr doc); XMLPUBFUN int xmlReaderNewDoc (xmlTextReaderPtr reader, const xmlChar * cur, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewFile (xmlTextReaderPtr reader, const char *filename, const char *encoding, int options); XMLPUBFUN int xmlReaderNewMemory (xmlTextReaderPtr reader, const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewFd (xmlTextReaderPtr reader, int fd, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewIO (xmlTextReaderPtr reader, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); /* * Error handling extensions */ typedef void * xmlTextReaderLocatorPtr; /** * xmlTextReaderErrorFunc: * @arg: the user argument * @msg: the message * @severity: the severity of the error * @locator: a locator indicating where the error occurred * * Signature of an error callback from a reader parser */ typedef void (*xmlTextReaderErrorFunc)(void *arg, const char *msg, xmlParserSeverities severity, xmlTextReaderLocatorPtr locator); XMLPUBFUN int xmlTextReaderLocatorLineNumber(xmlTextReaderLocatorPtr locator); XMLPUBFUN xmlChar * xmlTextReaderLocatorBaseURI (xmlTextReaderLocatorPtr locator); XMLPUBFUN void xmlTextReaderSetErrorHandler(xmlTextReaderPtr reader, xmlTextReaderErrorFunc f, void *arg); XMLPUBFUN void xmlTextReaderSetStructuredErrorHandler(xmlTextReaderPtr reader, xmlStructuredErrorFunc f, void *arg); XMLPUBFUN void xmlTextReaderGetErrorHandler(xmlTextReaderPtr reader, xmlTextReaderErrorFunc *f, void **arg); #endif /* LIBXML_READER_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_XMLREADER_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlregexp.h ================================================ /* * Summary: regular expressions handling * Description: basic API for libxml regular expressions handling used * for XML Schemas and validation. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_REGEXP_H__ #define __XML_REGEXP_H__ #include #ifdef LIBXML_REGEXP_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlRegexpPtr: * * A libxml regular expression, they can actually be far more complex * thank the POSIX regex expressions. */ typedef struct _xmlRegexp xmlRegexp; typedef xmlRegexp *xmlRegexpPtr; /** * xmlRegExecCtxtPtr: * * A libxml progressive regular expression evaluation context */ typedef struct _xmlRegExecCtxt xmlRegExecCtxt; typedef xmlRegExecCtxt *xmlRegExecCtxtPtr; #ifdef __cplusplus } #endif #include #include #ifdef __cplusplus extern "C" { #endif /* * The POSIX like API */ XMLPUBFUN xmlRegexpPtr xmlRegexpCompile (const xmlChar *regexp); XMLPUBFUN void xmlRegFreeRegexp(xmlRegexpPtr regexp); XMLPUBFUN int xmlRegexpExec (xmlRegexpPtr comp, const xmlChar *value); XMLPUBFUN void xmlRegexpPrint (FILE *output, xmlRegexpPtr regexp); XMLPUBFUN int xmlRegexpIsDeterminist(xmlRegexpPtr comp); /** * xmlRegExecCallbacks: * @exec: the regular expression context * @token: the current token string * @transdata: transition data * @inputdata: input data * * Callback function when doing a transition in the automata */ typedef void (*xmlRegExecCallbacks) (xmlRegExecCtxtPtr exec, const xmlChar *token, void *transdata, void *inputdata); /* * The progressive API */ XMLPUBFUN xmlRegExecCtxtPtr xmlRegNewExecCtxt (xmlRegexpPtr comp, xmlRegExecCallbacks callback, void *data); XMLPUBFUN void xmlRegFreeExecCtxt (xmlRegExecCtxtPtr exec); XMLPUBFUN int xmlRegExecPushString(xmlRegExecCtxtPtr exec, const xmlChar *value, void *data); XMLPUBFUN int xmlRegExecPushString2(xmlRegExecCtxtPtr exec, const xmlChar *value, const xmlChar *value2, void *data); XMLPUBFUN int xmlRegExecNextValues(xmlRegExecCtxtPtr exec, int *nbval, int *nbneg, xmlChar **values, int *terminal); XMLPUBFUN int xmlRegExecErrInfo (xmlRegExecCtxtPtr exec, const xmlChar **string, int *nbval, int *nbneg, xmlChar **values, int *terminal); #ifdef LIBXML_EXPR_ENABLED /* * Formal regular expression handling * Its goal is to do some formal work on content models */ /* expressions are used within a context */ typedef struct _xmlExpCtxt xmlExpCtxt; typedef xmlExpCtxt *xmlExpCtxtPtr; XMLPUBFUN void xmlExpFreeCtxt (xmlExpCtxtPtr ctxt); XMLPUBFUN xmlExpCtxtPtr xmlExpNewCtxt (int maxNodes, xmlDictPtr dict); XMLPUBFUN int xmlExpCtxtNbNodes(xmlExpCtxtPtr ctxt); XMLPUBFUN int xmlExpCtxtNbCons(xmlExpCtxtPtr ctxt); /* Expressions are trees but the tree is opaque */ typedef struct _xmlExpNode xmlExpNode; typedef xmlExpNode *xmlExpNodePtr; typedef enum { XML_EXP_EMPTY = 0, XML_EXP_FORBID = 1, XML_EXP_ATOM = 2, XML_EXP_SEQ = 3, XML_EXP_OR = 4, XML_EXP_COUNT = 5 } xmlExpNodeType; /* * 2 core expressions shared by all for the empty language set * and for the set with just the empty token */ XMLPUBVAR xmlExpNodePtr forbiddenExp; XMLPUBVAR xmlExpNodePtr emptyExp; /* * Expressions are reference counted internally */ XMLPUBFUN void xmlExpFree (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr); XMLPUBFUN void xmlExpRef (xmlExpNodePtr expr); /* * constructors can be either manual or from a string */ XMLPUBFUN xmlExpNodePtr xmlExpParse (xmlExpCtxtPtr ctxt, const char *expr); XMLPUBFUN xmlExpNodePtr xmlExpNewAtom (xmlExpCtxtPtr ctxt, const xmlChar *name, int len); XMLPUBFUN xmlExpNodePtr xmlExpNewOr (xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right); XMLPUBFUN xmlExpNodePtr xmlExpNewSeq (xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right); XMLPUBFUN xmlExpNodePtr xmlExpNewRange (xmlExpCtxtPtr ctxt, xmlExpNodePtr subset, int min, int max); /* * The really interesting APIs */ XMLPUBFUN int xmlExpIsNillable(xmlExpNodePtr expr); XMLPUBFUN int xmlExpMaxToken (xmlExpNodePtr expr); XMLPUBFUN int xmlExpGetLanguage(xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, const xmlChar**langList, int len); XMLPUBFUN int xmlExpGetStart (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, const xmlChar**tokList, int len); XMLPUBFUN xmlExpNodePtr xmlExpStringDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, const xmlChar *str, int len); XMLPUBFUN xmlExpNodePtr xmlExpExpDerive (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, xmlExpNodePtr sub); XMLPUBFUN int xmlExpSubsume (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, xmlExpNodePtr sub); XMLPUBFUN void xmlExpDump (xmlBufferPtr buf, xmlExpNodePtr expr); #endif /* LIBXML_EXPR_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_REGEXP_ENABLED */ #endif /*__XML_REGEXP_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlsave.h ================================================ /* * Summary: the XML document serializer * Description: API to save document or subtree of document * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XMLSAVE_H__ #define __XML_XMLSAVE_H__ #include #include #include #include #ifdef LIBXML_OUTPUT_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlSaveOption: * * This is the set of XML save options that can be passed down * to the xmlSaveToFd() and similar calls. */ typedef enum { XML_SAVE_FORMAT = 1<<0, /* format save output */ XML_SAVE_NO_DECL = 1<<1, /* drop the xml declaration */ XML_SAVE_NO_EMPTY = 1<<2, /* no empty tags */ XML_SAVE_NO_XHTML = 1<<3, /* disable XHTML1 specific rules */ XML_SAVE_XHTML = 1<<4, /* force XHTML1 specific rules */ XML_SAVE_AS_XML = 1<<5, /* force XML serialization on HTML doc */ XML_SAVE_AS_HTML = 1<<6, /* force HTML serialization on XML doc */ XML_SAVE_WSNONSIG = 1<<7 /* format with non-significant whitespace */ } xmlSaveOption; typedef struct _xmlSaveCtxt xmlSaveCtxt; typedef xmlSaveCtxt *xmlSaveCtxtPtr; XMLPUBFUN xmlSaveCtxtPtr xmlSaveToFd (int fd, const char *encoding, int options); XMLPUBFUN xmlSaveCtxtPtr xmlSaveToFilename (const char *filename, const char *encoding, int options); XMLPUBFUN xmlSaveCtxtPtr xmlSaveToBuffer (xmlBufferPtr buffer, const char *encoding, int options); XMLPUBFUN xmlSaveCtxtPtr xmlSaveToIO (xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose, void *ioctx, const char *encoding, int options); XMLPUBFUN long xmlSaveDoc (xmlSaveCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN long xmlSaveTree (xmlSaveCtxtPtr ctxt, xmlNodePtr node); XMLPUBFUN int xmlSaveFlush (xmlSaveCtxtPtr ctxt); XMLPUBFUN int xmlSaveClose (xmlSaveCtxtPtr ctxt); XMLPUBFUN int xmlSaveSetEscape (xmlSaveCtxtPtr ctxt, xmlCharEncodingOutputFunc escape); XMLPUBFUN int xmlSaveSetAttrEscape (xmlSaveCtxtPtr ctxt, xmlCharEncodingOutputFunc escape); #ifdef __cplusplus } #endif #endif /* LIBXML_OUTPUT_ENABLED */ #endif /* __XML_XMLSAVE_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlschemas.h ================================================ /* * Summary: incomplete XML Schemas structure implementation * Description: interface to the XML Schemas handling and schema validity * checking, it is incomplete right now. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMA_H__ #define __XML_SCHEMA_H__ #include #ifdef LIBXML_SCHEMAS_ENABLED #include #ifdef __cplusplus extern "C" { #endif /** * This error codes are obsolete; not used any more. */ typedef enum { XML_SCHEMAS_ERR_OK = 0, XML_SCHEMAS_ERR_NOROOT = 1, XML_SCHEMAS_ERR_UNDECLAREDELEM, XML_SCHEMAS_ERR_NOTTOPLEVEL, XML_SCHEMAS_ERR_MISSING, XML_SCHEMAS_ERR_WRONGELEM, XML_SCHEMAS_ERR_NOTYPE, XML_SCHEMAS_ERR_NOROLLBACK, XML_SCHEMAS_ERR_ISABSTRACT, XML_SCHEMAS_ERR_NOTEMPTY, XML_SCHEMAS_ERR_ELEMCONT, XML_SCHEMAS_ERR_HAVEDEFAULT, XML_SCHEMAS_ERR_NOTNILLABLE, XML_SCHEMAS_ERR_EXTRACONTENT, XML_SCHEMAS_ERR_INVALIDATTR, XML_SCHEMAS_ERR_INVALIDELEM, XML_SCHEMAS_ERR_NOTDETERMINIST, XML_SCHEMAS_ERR_CONSTRUCT, XML_SCHEMAS_ERR_INTERNAL, XML_SCHEMAS_ERR_NOTSIMPLE, XML_SCHEMAS_ERR_ATTRUNKNOWN, XML_SCHEMAS_ERR_ATTRINVALID, XML_SCHEMAS_ERR_VALUE, XML_SCHEMAS_ERR_FACET, XML_SCHEMAS_ERR_, XML_SCHEMAS_ERR_XXX } xmlSchemaValidError; /* * ATTENTION: Change xmlSchemaSetValidOptions's check * for invalid values, if adding to the validation * options below. */ /** * xmlSchemaValidOption: * * This is the set of XML Schema validation options. */ typedef enum { XML_SCHEMA_VAL_VC_I_CREATE = 1<<0 /* Default/fixed: create an attribute node * or an element's text node on the instance. */ } xmlSchemaValidOption; /* XML_SCHEMA_VAL_XSI_ASSEMBLE = 1<<1, * assemble schemata using * xsi:schemaLocation and * xsi:noNamespaceSchemaLocation */ /** * The schemas related types are kept internal */ typedef struct _xmlSchema xmlSchema; typedef xmlSchema *xmlSchemaPtr; /** * xmlSchemaValidityErrorFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of an error callback from an XSD validation */ typedef void (*xmlSchemaValidityErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlSchemaValidityWarningFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of a warning callback from an XSD validation */ typedef void (*xmlSchemaValidityWarningFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * A schemas validation context */ typedef struct _xmlSchemaParserCtxt xmlSchemaParserCtxt; typedef xmlSchemaParserCtxt *xmlSchemaParserCtxtPtr; typedef struct _xmlSchemaValidCtxt xmlSchemaValidCtxt; typedef xmlSchemaValidCtxt *xmlSchemaValidCtxtPtr; /** * xmlSchemaValidityLocatorFunc: * @ctx: user provided context * @file: returned file information * @line: returned line information * * A schemas validation locator, a callback called by the validator. * This is used when file or node information are not available * to find out what file and line number are affected * * Returns: 0 in case of success and -1 in case of error */ typedef int (*xmlSchemaValidityLocatorFunc) (void *ctx, const char **file, unsigned long *line); /* * Interfaces for parsing. */ XMLPUBFUN xmlSchemaParserCtxtPtr xmlSchemaNewParserCtxt (const char *URL); XMLPUBFUN xmlSchemaParserCtxtPtr xmlSchemaNewMemParserCtxt (const char *buffer, int size); XMLPUBFUN xmlSchemaParserCtxtPtr xmlSchemaNewDocParserCtxt (xmlDocPtr doc); XMLPUBFUN void xmlSchemaFreeParserCtxt (xmlSchemaParserCtxtPtr ctxt); XMLPUBFUN void xmlSchemaSetParserErrors (xmlSchemaParserCtxtPtr ctxt, xmlSchemaValidityErrorFunc err, xmlSchemaValidityWarningFunc warn, void *ctx); XMLPUBFUN void xmlSchemaSetParserStructuredErrors(xmlSchemaParserCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN int xmlSchemaGetParserErrors(xmlSchemaParserCtxtPtr ctxt, xmlSchemaValidityErrorFunc * err, xmlSchemaValidityWarningFunc * warn, void **ctx); XMLPUBFUN int xmlSchemaIsValid (xmlSchemaValidCtxtPtr ctxt); XMLPUBFUN xmlSchemaPtr xmlSchemaParse (xmlSchemaParserCtxtPtr ctxt); XMLPUBFUN void xmlSchemaFree (xmlSchemaPtr schema); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlSchemaDump (FILE *output, xmlSchemaPtr schema); #endif /* LIBXML_OUTPUT_ENABLED */ /* * Interfaces for validating */ XMLPUBFUN void xmlSchemaSetValidErrors (xmlSchemaValidCtxtPtr ctxt, xmlSchemaValidityErrorFunc err, xmlSchemaValidityWarningFunc warn, void *ctx); XMLPUBFUN void xmlSchemaSetValidStructuredErrors(xmlSchemaValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN int xmlSchemaGetValidErrors (xmlSchemaValidCtxtPtr ctxt, xmlSchemaValidityErrorFunc *err, xmlSchemaValidityWarningFunc *warn, void **ctx); XMLPUBFUN int xmlSchemaSetValidOptions (xmlSchemaValidCtxtPtr ctxt, int options); XMLPUBFUN void xmlSchemaValidateSetFilename(xmlSchemaValidCtxtPtr vctxt, const char *filename); XMLPUBFUN int xmlSchemaValidCtxtGetOptions(xmlSchemaValidCtxtPtr ctxt); XMLPUBFUN xmlSchemaValidCtxtPtr xmlSchemaNewValidCtxt (xmlSchemaPtr schema); XMLPUBFUN void xmlSchemaFreeValidCtxt (xmlSchemaValidCtxtPtr ctxt); XMLPUBFUN int xmlSchemaValidateDoc (xmlSchemaValidCtxtPtr ctxt, xmlDocPtr instance); XMLPUBFUN int xmlSchemaValidateOneElement (xmlSchemaValidCtxtPtr ctxt, xmlNodePtr elem); XMLPUBFUN int xmlSchemaValidateStream (xmlSchemaValidCtxtPtr ctxt, xmlParserInputBufferPtr input, xmlCharEncoding enc, xmlSAXHandlerPtr sax, void *user_data); XMLPUBFUN int xmlSchemaValidateFile (xmlSchemaValidCtxtPtr ctxt, const char * filename, int options); XMLPUBFUN xmlParserCtxtPtr xmlSchemaValidCtxtGetParserCtxt(xmlSchemaValidCtxtPtr ctxt); /* * Interface to insert Schemas SAX validation in a SAX stream */ typedef struct _xmlSchemaSAXPlug xmlSchemaSAXPlugStruct; typedef xmlSchemaSAXPlugStruct *xmlSchemaSAXPlugPtr; XMLPUBFUN xmlSchemaSAXPlugPtr xmlSchemaSAXPlug (xmlSchemaValidCtxtPtr ctxt, xmlSAXHandlerPtr *sax, void **user_data); XMLPUBFUN int xmlSchemaSAXUnplug (xmlSchemaSAXPlugPtr plug); XMLPUBFUN void xmlSchemaValidateSetLocator (xmlSchemaValidCtxtPtr vctxt, xmlSchemaValidityLocatorFunc f, void *ctxt); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_SCHEMA_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlschemastypes.h ================================================ /* * Summary: implementation of XML Schema Datatypes * Description: module providing the XML Schema Datatypes implementation * both definition and validity checking * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMA_TYPES_H__ #define __XML_SCHEMA_TYPES_H__ #include #ifdef LIBXML_SCHEMAS_ENABLED #include #include #ifdef __cplusplus extern "C" { #endif typedef enum { XML_SCHEMA_WHITESPACE_UNKNOWN = 0, XML_SCHEMA_WHITESPACE_PRESERVE = 1, XML_SCHEMA_WHITESPACE_REPLACE = 2, XML_SCHEMA_WHITESPACE_COLLAPSE = 3 } xmlSchemaWhitespaceValueType; XMLPUBFUN int xmlSchemaInitTypes (void); XML_DEPRECATED XMLPUBFUN void xmlSchemaCleanupTypes (void); XMLPUBFUN xmlSchemaTypePtr xmlSchemaGetPredefinedType (const xmlChar *name, const xmlChar *ns); XMLPUBFUN int xmlSchemaValidatePredefinedType (xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val); XMLPUBFUN int xmlSchemaValPredefTypeNode (xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val, xmlNodePtr node); XMLPUBFUN int xmlSchemaValidateFacet (xmlSchemaTypePtr base, xmlSchemaFacetPtr facet, const xmlChar *value, xmlSchemaValPtr val); XMLPUBFUN int xmlSchemaValidateFacetWhtsp (xmlSchemaFacetPtr facet, xmlSchemaWhitespaceValueType fws, xmlSchemaValType valType, const xmlChar *value, xmlSchemaValPtr val, xmlSchemaWhitespaceValueType ws); XMLPUBFUN void xmlSchemaFreeValue (xmlSchemaValPtr val); XMLPUBFUN xmlSchemaFacetPtr xmlSchemaNewFacet (void); XMLPUBFUN int xmlSchemaCheckFacet (xmlSchemaFacetPtr facet, xmlSchemaTypePtr typeDecl, xmlSchemaParserCtxtPtr ctxt, const xmlChar *name); XMLPUBFUN void xmlSchemaFreeFacet (xmlSchemaFacetPtr facet); XMLPUBFUN int xmlSchemaCompareValues (xmlSchemaValPtr x, xmlSchemaValPtr y); XMLPUBFUN xmlSchemaTypePtr xmlSchemaGetBuiltInListSimpleTypeItemType (xmlSchemaTypePtr type); XMLPUBFUN int xmlSchemaValidateListSimpleTypeFacet (xmlSchemaFacetPtr facet, const xmlChar *value, unsigned long actualLen, unsigned long *expectedLen); XMLPUBFUN xmlSchemaTypePtr xmlSchemaGetBuiltInType (xmlSchemaValType type); XMLPUBFUN int xmlSchemaIsBuiltInTypeFacet (xmlSchemaTypePtr type, int facetType); XMLPUBFUN xmlChar * xmlSchemaCollapseString (const xmlChar *value); XMLPUBFUN xmlChar * xmlSchemaWhiteSpaceReplace (const xmlChar *value); XMLPUBFUN unsigned long xmlSchemaGetFacetValueAsULong (xmlSchemaFacetPtr facet); XMLPUBFUN int xmlSchemaValidateLengthFacet (xmlSchemaTypePtr type, xmlSchemaFacetPtr facet, const xmlChar *value, xmlSchemaValPtr val, unsigned long *length); XMLPUBFUN int xmlSchemaValidateLengthFacetWhtsp(xmlSchemaFacetPtr facet, xmlSchemaValType valType, const xmlChar *value, xmlSchemaValPtr val, unsigned long *length, xmlSchemaWhitespaceValueType ws); XMLPUBFUN int xmlSchemaValPredefTypeNodeNoNorm(xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val, xmlNodePtr node); XMLPUBFUN int xmlSchemaGetCanonValue (xmlSchemaValPtr val, const xmlChar **retValue); XMLPUBFUN int xmlSchemaGetCanonValueWhtsp (xmlSchemaValPtr val, const xmlChar **retValue, xmlSchemaWhitespaceValueType ws); XMLPUBFUN int xmlSchemaValueAppend (xmlSchemaValPtr prev, xmlSchemaValPtr cur); XMLPUBFUN xmlSchemaValPtr xmlSchemaValueGetNext (xmlSchemaValPtr cur); XMLPUBFUN const xmlChar * xmlSchemaValueGetAsString (xmlSchemaValPtr val); XMLPUBFUN int xmlSchemaValueGetAsBoolean (xmlSchemaValPtr val); XMLPUBFUN xmlSchemaValPtr xmlSchemaNewStringValue (xmlSchemaValType type, const xmlChar *value); XMLPUBFUN xmlSchemaValPtr xmlSchemaNewNOTATIONValue (const xmlChar *name, const xmlChar *ns); XMLPUBFUN xmlSchemaValPtr xmlSchemaNewQNameValue (const xmlChar *namespaceName, const xmlChar *localName); XMLPUBFUN int xmlSchemaCompareValuesWhtsp (xmlSchemaValPtr x, xmlSchemaWhitespaceValueType xws, xmlSchemaValPtr y, xmlSchemaWhitespaceValueType yws); XMLPUBFUN xmlSchemaValPtr xmlSchemaCopyValue (xmlSchemaValPtr val); XMLPUBFUN xmlSchemaValType xmlSchemaGetValType (xmlSchemaValPtr val); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_SCHEMA_TYPES_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlstring.h ================================================ /* * Summary: set of routines to process strings * Description: type and interfaces needed for the internal string handling * of the library, especially UTF8 processing. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_STRING_H__ #define __XML_STRING_H__ #include #include #ifdef __cplusplus extern "C" { #endif /** * xmlChar: * * This is a basic byte in an UTF-8 encoded string. * It's unsigned allowing to pinpoint case where char * are assigned * to xmlChar * (possibly making serialization back impossible). */ typedef unsigned char xmlChar; /** * BAD_CAST: * * Macro to cast a string to an xmlChar * when one know its safe. */ #define BAD_CAST (xmlChar *) /* * xmlChar handling */ XMLPUBFUN xmlChar * xmlStrdup (const xmlChar *cur); XMLPUBFUN xmlChar * xmlStrndup (const xmlChar *cur, int len); XMLPUBFUN xmlChar * xmlCharStrndup (const char *cur, int len); XMLPUBFUN xmlChar * xmlCharStrdup (const char *cur); XMLPUBFUN xmlChar * xmlStrsub (const xmlChar *str, int start, int len); XMLPUBFUN const xmlChar * xmlStrchr (const xmlChar *str, xmlChar val); XMLPUBFUN const xmlChar * xmlStrstr (const xmlChar *str, const xmlChar *val); XMLPUBFUN const xmlChar * xmlStrcasestr (const xmlChar *str, const xmlChar *val); XMLPUBFUN int xmlStrcmp (const xmlChar *str1, const xmlChar *str2); XMLPUBFUN int xmlStrncmp (const xmlChar *str1, const xmlChar *str2, int len); XMLPUBFUN int xmlStrcasecmp (const xmlChar *str1, const xmlChar *str2); XMLPUBFUN int xmlStrncasecmp (const xmlChar *str1, const xmlChar *str2, int len); XMLPUBFUN int xmlStrEqual (const xmlChar *str1, const xmlChar *str2); XMLPUBFUN int xmlStrQEqual (const xmlChar *pref, const xmlChar *name, const xmlChar *str); XMLPUBFUN int xmlStrlen (const xmlChar *str); XMLPUBFUN xmlChar * xmlStrcat (xmlChar *cur, const xmlChar *add); XMLPUBFUN xmlChar * xmlStrncat (xmlChar *cur, const xmlChar *add, int len); XMLPUBFUN xmlChar * xmlStrncatNew (const xmlChar *str1, const xmlChar *str2, int len); XMLPUBFUN int xmlStrPrintf (xmlChar *buf, int len, const char *msg, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlStrVPrintf (xmlChar *buf, int len, const char *msg, va_list ap) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlGetUTF8Char (const unsigned char *utf, int *len); XMLPUBFUN int xmlCheckUTF8 (const unsigned char *utf); XMLPUBFUN int xmlUTF8Strsize (const xmlChar *utf, int len); XMLPUBFUN xmlChar * xmlUTF8Strndup (const xmlChar *utf, int len); XMLPUBFUN const xmlChar * xmlUTF8Strpos (const xmlChar *utf, int pos); XMLPUBFUN int xmlUTF8Strloc (const xmlChar *utf, const xmlChar *utfchar); XMLPUBFUN xmlChar * xmlUTF8Strsub (const xmlChar *utf, int start, int len); XMLPUBFUN int xmlUTF8Strlen (const xmlChar *utf); XMLPUBFUN int xmlUTF8Size (const xmlChar *utf); XMLPUBFUN int xmlUTF8Charcmp (const xmlChar *utf1, const xmlChar *utf2); #ifdef __cplusplus } #endif #endif /* __XML_STRING_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlunicode.h ================================================ /* * Summary: Unicode character APIs * Description: API for the Unicode character APIs * * This file is automatically generated from the * UCS description files of the Unicode Character Database * http://www.unicode.org/Public/4.0-Update1/UCD-4.0.1.html * using the genUnicode.py Python script. * * Generation date: Mon Mar 27 11:09:52 2006 * Sources: Blocks-4.0.1.txt UnicodeData-4.0.1.txt * Author: Daniel Veillard */ #ifndef __XML_UNICODE_H__ #define __XML_UNICODE_H__ #include #ifdef LIBXML_UNICODE_ENABLED #ifdef __cplusplus extern "C" { #endif XMLPUBFUN int xmlUCSIsAegeanNumbers (int code); XMLPUBFUN int xmlUCSIsAlphabeticPresentationForms (int code); XMLPUBFUN int xmlUCSIsArabic (int code); XMLPUBFUN int xmlUCSIsArabicPresentationFormsA (int code); XMLPUBFUN int xmlUCSIsArabicPresentationFormsB (int code); XMLPUBFUN int xmlUCSIsArmenian (int code); XMLPUBFUN int xmlUCSIsArrows (int code); XMLPUBFUN int xmlUCSIsBasicLatin (int code); XMLPUBFUN int xmlUCSIsBengali (int code); XMLPUBFUN int xmlUCSIsBlockElements (int code); XMLPUBFUN int xmlUCSIsBopomofo (int code); XMLPUBFUN int xmlUCSIsBopomofoExtended (int code); XMLPUBFUN int xmlUCSIsBoxDrawing (int code); XMLPUBFUN int xmlUCSIsBraillePatterns (int code); XMLPUBFUN int xmlUCSIsBuhid (int code); XMLPUBFUN int xmlUCSIsByzantineMusicalSymbols (int code); XMLPUBFUN int xmlUCSIsCJKCompatibility (int code); XMLPUBFUN int xmlUCSIsCJKCompatibilityForms (int code); XMLPUBFUN int xmlUCSIsCJKCompatibilityIdeographs (int code); XMLPUBFUN int xmlUCSIsCJKCompatibilityIdeographsSupplement (int code); XMLPUBFUN int xmlUCSIsCJKRadicalsSupplement (int code); XMLPUBFUN int xmlUCSIsCJKSymbolsandPunctuation (int code); XMLPUBFUN int xmlUCSIsCJKUnifiedIdeographs (int code); XMLPUBFUN int xmlUCSIsCJKUnifiedIdeographsExtensionA (int code); XMLPUBFUN int xmlUCSIsCJKUnifiedIdeographsExtensionB (int code); XMLPUBFUN int xmlUCSIsCherokee (int code); XMLPUBFUN int xmlUCSIsCombiningDiacriticalMarks (int code); XMLPUBFUN int xmlUCSIsCombiningDiacriticalMarksforSymbols (int code); XMLPUBFUN int xmlUCSIsCombiningHalfMarks (int code); XMLPUBFUN int xmlUCSIsCombiningMarksforSymbols (int code); XMLPUBFUN int xmlUCSIsControlPictures (int code); XMLPUBFUN int xmlUCSIsCurrencySymbols (int code); XMLPUBFUN int xmlUCSIsCypriotSyllabary (int code); XMLPUBFUN int xmlUCSIsCyrillic (int code); XMLPUBFUN int xmlUCSIsCyrillicSupplement (int code); XMLPUBFUN int xmlUCSIsDeseret (int code); XMLPUBFUN int xmlUCSIsDevanagari (int code); XMLPUBFUN int xmlUCSIsDingbats (int code); XMLPUBFUN int xmlUCSIsEnclosedAlphanumerics (int code); XMLPUBFUN int xmlUCSIsEnclosedCJKLettersandMonths (int code); XMLPUBFUN int xmlUCSIsEthiopic (int code); XMLPUBFUN int xmlUCSIsGeneralPunctuation (int code); XMLPUBFUN int xmlUCSIsGeometricShapes (int code); XMLPUBFUN int xmlUCSIsGeorgian (int code); XMLPUBFUN int xmlUCSIsGothic (int code); XMLPUBFUN int xmlUCSIsGreek (int code); XMLPUBFUN int xmlUCSIsGreekExtended (int code); XMLPUBFUN int xmlUCSIsGreekandCoptic (int code); XMLPUBFUN int xmlUCSIsGujarati (int code); XMLPUBFUN int xmlUCSIsGurmukhi (int code); XMLPUBFUN int xmlUCSIsHalfwidthandFullwidthForms (int code); XMLPUBFUN int xmlUCSIsHangulCompatibilityJamo (int code); XMLPUBFUN int xmlUCSIsHangulJamo (int code); XMLPUBFUN int xmlUCSIsHangulSyllables (int code); XMLPUBFUN int xmlUCSIsHanunoo (int code); XMLPUBFUN int xmlUCSIsHebrew (int code); XMLPUBFUN int xmlUCSIsHighPrivateUseSurrogates (int code); XMLPUBFUN int xmlUCSIsHighSurrogates (int code); XMLPUBFUN int xmlUCSIsHiragana (int code); XMLPUBFUN int xmlUCSIsIPAExtensions (int code); XMLPUBFUN int xmlUCSIsIdeographicDescriptionCharacters (int code); XMLPUBFUN int xmlUCSIsKanbun (int code); XMLPUBFUN int xmlUCSIsKangxiRadicals (int code); XMLPUBFUN int xmlUCSIsKannada (int code); XMLPUBFUN int xmlUCSIsKatakana (int code); XMLPUBFUN int xmlUCSIsKatakanaPhoneticExtensions (int code); XMLPUBFUN int xmlUCSIsKhmer (int code); XMLPUBFUN int xmlUCSIsKhmerSymbols (int code); XMLPUBFUN int xmlUCSIsLao (int code); XMLPUBFUN int xmlUCSIsLatin1Supplement (int code); XMLPUBFUN int xmlUCSIsLatinExtendedA (int code); XMLPUBFUN int xmlUCSIsLatinExtendedB (int code); XMLPUBFUN int xmlUCSIsLatinExtendedAdditional (int code); XMLPUBFUN int xmlUCSIsLetterlikeSymbols (int code); XMLPUBFUN int xmlUCSIsLimbu (int code); XMLPUBFUN int xmlUCSIsLinearBIdeograms (int code); XMLPUBFUN int xmlUCSIsLinearBSyllabary (int code); XMLPUBFUN int xmlUCSIsLowSurrogates (int code); XMLPUBFUN int xmlUCSIsMalayalam (int code); XMLPUBFUN int xmlUCSIsMathematicalAlphanumericSymbols (int code); XMLPUBFUN int xmlUCSIsMathematicalOperators (int code); XMLPUBFUN int xmlUCSIsMiscellaneousMathematicalSymbolsA (int code); XMLPUBFUN int xmlUCSIsMiscellaneousMathematicalSymbolsB (int code); XMLPUBFUN int xmlUCSIsMiscellaneousSymbols (int code); XMLPUBFUN int xmlUCSIsMiscellaneousSymbolsandArrows (int code); XMLPUBFUN int xmlUCSIsMiscellaneousTechnical (int code); XMLPUBFUN int xmlUCSIsMongolian (int code); XMLPUBFUN int xmlUCSIsMusicalSymbols (int code); XMLPUBFUN int xmlUCSIsMyanmar (int code); XMLPUBFUN int xmlUCSIsNumberForms (int code); XMLPUBFUN int xmlUCSIsOgham (int code); XMLPUBFUN int xmlUCSIsOldItalic (int code); XMLPUBFUN int xmlUCSIsOpticalCharacterRecognition (int code); XMLPUBFUN int xmlUCSIsOriya (int code); XMLPUBFUN int xmlUCSIsOsmanya (int code); XMLPUBFUN int xmlUCSIsPhoneticExtensions (int code); XMLPUBFUN int xmlUCSIsPrivateUse (int code); XMLPUBFUN int xmlUCSIsPrivateUseArea (int code); XMLPUBFUN int xmlUCSIsRunic (int code); XMLPUBFUN int xmlUCSIsShavian (int code); XMLPUBFUN int xmlUCSIsSinhala (int code); XMLPUBFUN int xmlUCSIsSmallFormVariants (int code); XMLPUBFUN int xmlUCSIsSpacingModifierLetters (int code); XMLPUBFUN int xmlUCSIsSpecials (int code); XMLPUBFUN int xmlUCSIsSuperscriptsandSubscripts (int code); XMLPUBFUN int xmlUCSIsSupplementalArrowsA (int code); XMLPUBFUN int xmlUCSIsSupplementalArrowsB (int code); XMLPUBFUN int xmlUCSIsSupplementalMathematicalOperators (int code); XMLPUBFUN int xmlUCSIsSupplementaryPrivateUseAreaA (int code); XMLPUBFUN int xmlUCSIsSupplementaryPrivateUseAreaB (int code); XMLPUBFUN int xmlUCSIsSyriac (int code); XMLPUBFUN int xmlUCSIsTagalog (int code); XMLPUBFUN int xmlUCSIsTagbanwa (int code); XMLPUBFUN int xmlUCSIsTags (int code); XMLPUBFUN int xmlUCSIsTaiLe (int code); XMLPUBFUN int xmlUCSIsTaiXuanJingSymbols (int code); XMLPUBFUN int xmlUCSIsTamil (int code); XMLPUBFUN int xmlUCSIsTelugu (int code); XMLPUBFUN int xmlUCSIsThaana (int code); XMLPUBFUN int xmlUCSIsThai (int code); XMLPUBFUN int xmlUCSIsTibetan (int code); XMLPUBFUN int xmlUCSIsUgaritic (int code); XMLPUBFUN int xmlUCSIsUnifiedCanadianAboriginalSyllabics (int code); XMLPUBFUN int xmlUCSIsVariationSelectors (int code); XMLPUBFUN int xmlUCSIsVariationSelectorsSupplement (int code); XMLPUBFUN int xmlUCSIsYiRadicals (int code); XMLPUBFUN int xmlUCSIsYiSyllables (int code); XMLPUBFUN int xmlUCSIsYijingHexagramSymbols (int code); XMLPUBFUN int xmlUCSIsBlock (int code, const char *block); XMLPUBFUN int xmlUCSIsCatC (int code); XMLPUBFUN int xmlUCSIsCatCc (int code); XMLPUBFUN int xmlUCSIsCatCf (int code); XMLPUBFUN int xmlUCSIsCatCo (int code); XMLPUBFUN int xmlUCSIsCatCs (int code); XMLPUBFUN int xmlUCSIsCatL (int code); XMLPUBFUN int xmlUCSIsCatLl (int code); XMLPUBFUN int xmlUCSIsCatLm (int code); XMLPUBFUN int xmlUCSIsCatLo (int code); XMLPUBFUN int xmlUCSIsCatLt (int code); XMLPUBFUN int xmlUCSIsCatLu (int code); XMLPUBFUN int xmlUCSIsCatM (int code); XMLPUBFUN int xmlUCSIsCatMc (int code); XMLPUBFUN int xmlUCSIsCatMe (int code); XMLPUBFUN int xmlUCSIsCatMn (int code); XMLPUBFUN int xmlUCSIsCatN (int code); XMLPUBFUN int xmlUCSIsCatNd (int code); XMLPUBFUN int xmlUCSIsCatNl (int code); XMLPUBFUN int xmlUCSIsCatNo (int code); XMLPUBFUN int xmlUCSIsCatP (int code); XMLPUBFUN int xmlUCSIsCatPc (int code); XMLPUBFUN int xmlUCSIsCatPd (int code); XMLPUBFUN int xmlUCSIsCatPe (int code); XMLPUBFUN int xmlUCSIsCatPf (int code); XMLPUBFUN int xmlUCSIsCatPi (int code); XMLPUBFUN int xmlUCSIsCatPo (int code); XMLPUBFUN int xmlUCSIsCatPs (int code); XMLPUBFUN int xmlUCSIsCatS (int code); XMLPUBFUN int xmlUCSIsCatSc (int code); XMLPUBFUN int xmlUCSIsCatSk (int code); XMLPUBFUN int xmlUCSIsCatSm (int code); XMLPUBFUN int xmlUCSIsCatSo (int code); XMLPUBFUN int xmlUCSIsCatZ (int code); XMLPUBFUN int xmlUCSIsCatZl (int code); XMLPUBFUN int xmlUCSIsCatZp (int code); XMLPUBFUN int xmlUCSIsCatZs (int code); XMLPUBFUN int xmlUCSIsCat (int code, const char *cat); #ifdef __cplusplus } #endif #endif /* LIBXML_UNICODE_ENABLED */ #endif /* __XML_UNICODE_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlversion.h ================================================ /* * Summary: compile-time version information * Description: compile-time version information for the XML library * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_VERSION_H__ #define __XML_VERSION_H__ #include #ifdef __cplusplus extern "C" { #endif /* * use those to be sure nothing nasty will happen if * your library and includes mismatch */ #ifndef LIBXML2_COMPILING_MSCCDEF XMLPUBFUN void xmlCheckVersion(int version); #endif /* LIBXML2_COMPILING_MSCCDEF */ /** * LIBXML_DOTTED_VERSION: * * the version string like "1.2.3" */ #define LIBXML_DOTTED_VERSION "2.11.5" /** * LIBXML_VERSION: * * the version number: 1.2.3 value is 10203 */ #define LIBXML_VERSION 21105 /** * LIBXML_VERSION_STRING: * * the version number string, 1.2.3 value is "10203" */ #define LIBXML_VERSION_STRING "21105" /** * LIBXML_VERSION_EXTRA: * * extra version information, used to show a git commit description */ #define LIBXML_VERSION_EXTRA "" /** * LIBXML_TEST_VERSION: * * Macro to check that the libxml version in use is compatible with * the version the software has been compiled against */ #define LIBXML_TEST_VERSION xmlCheckVersion(21105); #ifndef VMS #if 0 /** * WITH_TRIO: * * defined if the trio support need to be configured in */ #define WITH_TRIO #else /** * WITHOUT_TRIO: * * defined if the trio support should not be configured in */ #define WITHOUT_TRIO #endif #else /* VMS */ /** * WITH_TRIO: * * defined if the trio support need to be configured in */ #define WITH_TRIO 1 #endif /* VMS */ /** * LIBXML_THREAD_ENABLED: * * Whether the thread support is configured in */ #if 0 #define LIBXML_THREAD_ENABLED #endif /** * LIBXML_THREAD_ALLOC_ENABLED: * * Whether the allocation hooks are per-thread */ #if 0 #define LIBXML_THREAD_ALLOC_ENABLED #endif /** * LIBXML_TREE_ENABLED: * * Whether the DOM like tree manipulation API support is configured in */ #if 1 #define LIBXML_TREE_ENABLED #endif /** * LIBXML_OUTPUT_ENABLED: * * Whether the serialization/saving support is configured in */ #if 1 #define LIBXML_OUTPUT_ENABLED #endif /** * LIBXML_PUSH_ENABLED: * * Whether the push parsing interfaces are configured in */ #if 1 #define LIBXML_PUSH_ENABLED #endif /** * LIBXML_READER_ENABLED: * * Whether the xmlReader parsing interface is configured in */ #if 1 #define LIBXML_READER_ENABLED #endif /** * LIBXML_PATTERN_ENABLED: * * Whether the xmlPattern node selection interface is configured in */ #if 1 #define LIBXML_PATTERN_ENABLED #endif /** * LIBXML_WRITER_ENABLED: * * Whether the xmlWriter saving interface is configured in */ #if 1 #define LIBXML_WRITER_ENABLED #endif /** * LIBXML_SAX1_ENABLED: * * Whether the older SAX1 interface is configured in */ #if 1 #define LIBXML_SAX1_ENABLED #endif /** * LIBXML_FTP_ENABLED: * * Whether the FTP support is configured in */ #if 0 #define LIBXML_FTP_ENABLED #endif /** * LIBXML_HTTP_ENABLED: * * Whether the HTTP support is configured in */ #if 0 #define LIBXML_HTTP_ENABLED #endif /** * LIBXML_VALID_ENABLED: * * Whether the DTD validation support is configured in */ #if 1 #define LIBXML_VALID_ENABLED #endif /** * LIBXML_HTML_ENABLED: * * Whether the HTML support is configured in */ #if 1 #define LIBXML_HTML_ENABLED #endif /** * LIBXML_LEGACY_ENABLED: * * Whether the deprecated APIs are compiled in for compatibility */ #if 0 #define LIBXML_LEGACY_ENABLED #endif /** * LIBXML_C14N_ENABLED: * * Whether the Canonicalization support is configured in */ #if 1 #define LIBXML_C14N_ENABLED #endif /** * LIBXML_CATALOG_ENABLED: * * Whether the Catalog support is configured in */ #if 1 #define LIBXML_CATALOG_ENABLED #endif /** * LIBXML_XPATH_ENABLED: * * Whether XPath is configured in */ #if 1 #define LIBXML_XPATH_ENABLED #endif /** * LIBXML_XPTR_ENABLED: * * Whether XPointer is configured in */ #if 1 #define LIBXML_XPTR_ENABLED #endif /** * LIBXML_XPTR_LOCS_ENABLED: * * Whether support for XPointer locations is configured in */ #if 0 #define LIBXML_XPTR_LOCS_ENABLED #endif /** * LIBXML_XINCLUDE_ENABLED: * * Whether XInclude is configured in */ #if 1 #define LIBXML_XINCLUDE_ENABLED #endif /** * LIBXML_ICONV_ENABLED: * * Whether iconv support is available */ #if 0 #define LIBXML_ICONV_ENABLED #endif /** * LIBXML_ICU_ENABLED: * * Whether icu support is available */ #if 0 #define LIBXML_ICU_ENABLED #endif /** * LIBXML_ISO8859X_ENABLED: * * Whether ISO-8859-* support is made available in case iconv is not */ #if 1 #define LIBXML_ISO8859X_ENABLED #endif /** * LIBXML_DEBUG_ENABLED: * * Whether Debugging module is configured in */ #if 1 #define LIBXML_DEBUG_ENABLED #endif /** * DEBUG_MEMORY_LOCATION: * * Whether the memory debugging is configured in */ #if 0 #define DEBUG_MEMORY_LOCATION #endif /** * LIBXML_DEBUG_RUNTIME: * * Removed */ #if 0 #define LIBXML_DEBUG_RUNTIME #endif /** * LIBXML_UNICODE_ENABLED: * * Whether the Unicode related interfaces are compiled in */ #if 1 #define LIBXML_UNICODE_ENABLED #endif /** * LIBXML_REGEXP_ENABLED: * * Whether the regular expressions interfaces are compiled in */ #if 1 #define LIBXML_REGEXP_ENABLED #endif /** * LIBXML_AUTOMATA_ENABLED: * * Whether the automata interfaces are compiled in */ #if 1 #define LIBXML_AUTOMATA_ENABLED #endif /** * LIBXML_EXPR_ENABLED: * * Whether the formal expressions interfaces are compiled in * * This code is unused and disabled unconditionally for now. */ #if 0 #define LIBXML_EXPR_ENABLED #endif /** * LIBXML_SCHEMAS_ENABLED: * * Whether the Schemas validation interfaces are compiled in */ #if 1 #define LIBXML_SCHEMAS_ENABLED #endif /** * LIBXML_SCHEMATRON_ENABLED: * * Whether the Schematron validation interfaces are compiled in */ #if 1 #define LIBXML_SCHEMATRON_ENABLED #endif /** * LIBXML_MODULES_ENABLED: * * Whether the module interfaces are compiled in */ #if 1 #define LIBXML_MODULES_ENABLED /** * LIBXML_MODULE_EXTENSION: * * the string suffix used by dynamic modules (usually shared libraries) */ #define LIBXML_MODULE_EXTENSION ".dll" #endif /** * LIBXML_ZLIB_ENABLED: * * Whether the Zlib support is compiled in */ #if 1 #define LIBXML_ZLIB_ENABLED #endif /** * LIBXML_LZMA_ENABLED: * * Whether the Lzma support is compiled in */ #if 0 #define LIBXML_LZMA_ENABLED #endif #ifdef __GNUC__ /** DOC_DISABLE */ #ifndef ATTRIBUTE_UNUSED # if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 7))) # define ATTRIBUTE_UNUSED __attribute__((unused)) # else # define ATTRIBUTE_UNUSED # endif #endif #ifndef LIBXML_ATTR_ALLOC_SIZE # if (!defined(__clang__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) # define LIBXML_ATTR_ALLOC_SIZE(x) __attribute__((alloc_size(x))) # else # define LIBXML_ATTR_ALLOC_SIZE(x) # endif #else # define LIBXML_ATTR_ALLOC_SIZE(x) #endif #ifndef LIBXML_ATTR_FORMAT # if ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3))) # define LIBXML_ATTR_FORMAT(fmt,args) __attribute__((__format__(__printf__,fmt,args))) # else # define LIBXML_ATTR_FORMAT(fmt,args) # endif #else # define LIBXML_ATTR_FORMAT(fmt,args) #endif #ifndef XML_DEPRECATED # if defined (IN_LIBXML) || (__GNUC__ * 100 + __GNUC_MINOR__ < 301) # define XML_DEPRECATED /* Available since at least GCC 3.1 */ # else # define XML_DEPRECATED __attribute__((deprecated)) # endif #endif #if defined(__clang__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 406) #define XML_IGNORE_FPTR_CAST_WARNINGS \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wpedantic\"") \ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #define XML_POP_WARNINGS \ _Pragma("GCC diagnostic pop") #else #define XML_IGNORE_FPTR_CAST_WARNINGS #define XML_POP_WARNINGS #endif /** DOC_ENABLE */ #else /* ! __GNUC__ */ /** * ATTRIBUTE_UNUSED: * * Macro used to signal to GCC unused function parameters */ #define ATTRIBUTE_UNUSED /** * LIBXML_ATTR_ALLOC_SIZE: * * Macro used to indicate to GCC this is an allocator function */ #define LIBXML_ATTR_ALLOC_SIZE(x) /** * LIBXML_ATTR_FORMAT: * * Macro used to indicate to GCC the parameter are printf like */ #define LIBXML_ATTR_FORMAT(fmt,args) /** * XML_DEPRECATED: * * Macro used to indicate that a function, variable, type or struct member * is deprecated. */ #ifndef XML_DEPRECATED # if defined (IN_LIBXML) || !defined (_MSC_VER) # define XML_DEPRECATED /* Available since Visual Studio 2005 */ # elif defined (_MSC_VER) && (_MSC_VER >= 1400) # define XML_DEPRECATED __declspec(deprecated) # endif #endif /** * LIBXML_IGNORE_FPTR_CAST_WARNINGS: * * Macro used to ignore pointer cast warnings that can't be worked around. */ #if defined (_MSC_VER) && (_MSC_VER >= 1400) # define XML_IGNORE_FPTR_CAST_WARNINGS __pragma(warning(push)) #else # define XML_IGNORE_FPTR_CAST_WARNINGS #endif /** * XML_POP_WARNINGS: * * Macro used to restore warnings state. */ #ifndef XML_POP_WARNINGS # if defined (_MSC_VER) && (_MSC_VER >= 1400) # define XML_POP_WARNINGS __pragma(warning(pop)) # else # define XML_POP_WARNINGS # endif #endif #endif /* __GNUC__ */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif ================================================ FILE: thirdparty/32/include/libxml2/libxml/xmlwriter.h ================================================ /* * Summary: text writing API for XML * Description: text writing API for XML * * Copy: See Copyright for the status of this software. * * Author: Alfred Mickautsch */ #ifndef __XML_XMLWRITER_H__ #define __XML_XMLWRITER_H__ #include #ifdef LIBXML_WRITER_ENABLED #include #include #include #include #ifdef __cplusplus extern "C" { #endif typedef struct _xmlTextWriter xmlTextWriter; typedef xmlTextWriter *xmlTextWriterPtr; /* * Constructors & Destructor */ XMLPUBFUN xmlTextWriterPtr xmlNewTextWriter(xmlOutputBufferPtr out); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterFilename(const char *uri, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterMemory(xmlBufferPtr buf, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterPushParser(xmlParserCtxtPtr ctxt, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterDoc(xmlDocPtr * doc, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterTree(xmlDocPtr doc, xmlNodePtr node, int compression); XMLPUBFUN void xmlFreeTextWriter(xmlTextWriterPtr writer); /* * Functions */ /* * Document */ XMLPUBFUN int xmlTextWriterStartDocument(xmlTextWriterPtr writer, const char *version, const char *encoding, const char *standalone); XMLPUBFUN int xmlTextWriterEndDocument(xmlTextWriterPtr writer); /* * Comments */ XMLPUBFUN int xmlTextWriterStartComment(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterEndComment(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterWriteFormatComment(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatComment(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteComment(xmlTextWriterPtr writer, const xmlChar * content); /* * Elements */ XMLPUBFUN int xmlTextWriterStartElement(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterStartElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI); XMLPUBFUN int xmlTextWriterEndElement(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterFullEndElement(xmlTextWriterPtr writer); /* * Elements conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteElement(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteFormatElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, ...) LIBXML_ATTR_FORMAT(5,6); XMLPUBFUN int xmlTextWriterWriteVFormatElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(5,0); XMLPUBFUN int xmlTextWriterWriteElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const xmlChar * content); /* * Text */ XMLPUBFUN int xmlTextWriterWriteFormatRaw(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatRaw(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteRawLen(xmlTextWriterPtr writer, const xmlChar * content, int len); XMLPUBFUN int xmlTextWriterWriteRaw(xmlTextWriterPtr writer, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteFormatString(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatString(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteString(xmlTextWriterPtr writer, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteBase64(xmlTextWriterPtr writer, const char *data, int start, int len); XMLPUBFUN int xmlTextWriterWriteBinHex(xmlTextWriterPtr writer, const char *data, int start, int len); /* * Attributes */ XMLPUBFUN int xmlTextWriterStartAttribute(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterStartAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI); XMLPUBFUN int xmlTextWriterEndAttribute(xmlTextWriterPtr writer); /* * Attributes conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatAttribute(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatAttribute(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteAttribute(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteFormatAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, ...) LIBXML_ATTR_FORMAT(5,6); XMLPUBFUN int xmlTextWriterWriteVFormatAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(5,0); XMLPUBFUN int xmlTextWriterWriteAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const xmlChar * content); /* * PI's */ XMLPUBFUN int xmlTextWriterStartPI(xmlTextWriterPtr writer, const xmlChar * target); XMLPUBFUN int xmlTextWriterEndPI(xmlTextWriterPtr writer); /* * PI conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatPI(xmlTextWriterPtr writer, const xmlChar * target, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatPI(xmlTextWriterPtr writer, const xmlChar * target, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWritePI(xmlTextWriterPtr writer, const xmlChar * target, const xmlChar * content); /** * xmlTextWriterWriteProcessingInstruction: * * This macro maps to xmlTextWriterWritePI */ #define xmlTextWriterWriteProcessingInstruction xmlTextWriterWritePI /* * CDATA */ XMLPUBFUN int xmlTextWriterStartCDATA(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterEndCDATA(xmlTextWriterPtr writer); /* * CDATA conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatCDATA(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatCDATA(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteCDATA(xmlTextWriterPtr writer, const xmlChar * content); /* * DTD */ XMLPUBFUN int xmlTextWriterStartDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid); XMLPUBFUN int xmlTextWriterEndDTD(xmlTextWriterPtr writer); /* * DTD conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const char *format, ...) LIBXML_ATTR_FORMAT(5,6); XMLPUBFUN int xmlTextWriterWriteVFormatDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(5,0); XMLPUBFUN int xmlTextWriterWriteDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * subset); /** * xmlTextWriterWriteDocType: * * this macro maps to xmlTextWriterWriteDTD */ #define xmlTextWriterWriteDocType xmlTextWriterWriteDTD /* * DTD element definition */ XMLPUBFUN int xmlTextWriterStartDTDElement(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterEndDTDElement(xmlTextWriterPtr writer); /* * DTD element definition conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTDElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatDTDElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteDTDElement(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); /* * DTD attribute list definition */ XMLPUBFUN int xmlTextWriterStartDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterEndDTDAttlist(xmlTextWriterPtr writer); /* * DTD attribute list definition conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); /* * DTD entity definition */ XMLPUBFUN int xmlTextWriterStartDTDEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name); XMLPUBFUN int xmlTextWriterEndDTDEntity(xmlTextWriterPtr writer); /* * DTD entity definition conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTDInternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(4,5); XMLPUBFUN int xmlTextWriterWriteVFormatDTDInternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(4,0); XMLPUBFUN int xmlTextWriterWriteDTDInternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteDTDExternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * ndataid); XMLPUBFUN int xmlTextWriterWriteDTDExternalEntityContents(xmlTextWriterPtr writer, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * ndataid); XMLPUBFUN int xmlTextWriterWriteDTDEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * ndataid, const xmlChar * content); /* * DTD notation definition */ XMLPUBFUN int xmlTextWriterWriteDTDNotation(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid); /* * Indentation */ XMLPUBFUN int xmlTextWriterSetIndent(xmlTextWriterPtr writer, int indent); XMLPUBFUN int xmlTextWriterSetIndentString(xmlTextWriterPtr writer, const xmlChar * str); XMLPUBFUN int xmlTextWriterSetQuoteChar(xmlTextWriterPtr writer, xmlChar quotechar); /* * misc */ XMLPUBFUN int xmlTextWriterFlush(xmlTextWriterPtr writer); #ifdef __cplusplus } #endif #endif /* LIBXML_WRITER_ENABLED */ #endif /* __XML_XMLWRITER_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xpath.h ================================================ /* * Summary: XML Path Language implementation * Description: API for the XML Path Language implementation * * XML Path Language implementation * XPath is a language for addressing parts of an XML document, * designed to be used by both XSLT and XPointer * http://www.w3.org/TR/xpath * * Implements * W3C Recommendation 16 November 1999 * http://www.w3.org/TR/1999/REC-xpath-19991116 * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XPATH_H__ #define __XML_XPATH_H__ #include #ifdef LIBXML_XPATH_ENABLED #include #include #include #endif /* LIBXML_XPATH_ENABLED */ #if defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) #ifdef __cplusplus extern "C" { #endif #endif /* LIBXML_XPATH_ENABLED or LIBXML_SCHEMAS_ENABLED */ #ifdef LIBXML_XPATH_ENABLED typedef struct _xmlXPathContext xmlXPathContext; typedef xmlXPathContext *xmlXPathContextPtr; typedef struct _xmlXPathParserContext xmlXPathParserContext; typedef xmlXPathParserContext *xmlXPathParserContextPtr; /** * The set of XPath error codes. */ typedef enum { XPATH_EXPRESSION_OK = 0, XPATH_NUMBER_ERROR, XPATH_UNFINISHED_LITERAL_ERROR, XPATH_START_LITERAL_ERROR, XPATH_VARIABLE_REF_ERROR, XPATH_UNDEF_VARIABLE_ERROR, XPATH_INVALID_PREDICATE_ERROR, XPATH_EXPR_ERROR, XPATH_UNCLOSED_ERROR, XPATH_UNKNOWN_FUNC_ERROR, XPATH_INVALID_OPERAND, XPATH_INVALID_TYPE, XPATH_INVALID_ARITY, XPATH_INVALID_CTXT_SIZE, XPATH_INVALID_CTXT_POSITION, XPATH_MEMORY_ERROR, XPTR_SYNTAX_ERROR, XPTR_RESOURCE_ERROR, XPTR_SUB_RESOURCE_ERROR, XPATH_UNDEF_PREFIX_ERROR, XPATH_ENCODING_ERROR, XPATH_INVALID_CHAR_ERROR, XPATH_INVALID_CTXT, XPATH_STACK_ERROR, XPATH_FORBID_VARIABLE_ERROR, XPATH_OP_LIMIT_EXCEEDED, XPATH_RECURSION_LIMIT_EXCEEDED } xmlXPathError; /* * A node-set (an unordered collection of nodes without duplicates). */ typedef struct _xmlNodeSet xmlNodeSet; typedef xmlNodeSet *xmlNodeSetPtr; struct _xmlNodeSet { int nodeNr; /* number of nodes in the set */ int nodeMax; /* size of the array as allocated */ xmlNodePtr *nodeTab; /* array of nodes in no particular order */ /* @@ with_ns to check whether namespace nodes should be looked at @@ */ }; /* * An expression is evaluated to yield an object, which * has one of the following four basic types: * - node-set * - boolean * - number * - string * * @@ XPointer will add more types ! */ typedef enum { XPATH_UNDEFINED = 0, XPATH_NODESET = 1, XPATH_BOOLEAN = 2, XPATH_NUMBER = 3, XPATH_STRING = 4, #ifdef LIBXML_XPTR_LOCS_ENABLED XPATH_POINT = 5, XPATH_RANGE = 6, XPATH_LOCATIONSET = 7, #endif XPATH_USERS = 8, XPATH_XSLT_TREE = 9 /* An XSLT value tree, non modifiable */ } xmlXPathObjectType; #ifndef LIBXML_XPTR_LOCS_ENABLED /** DOC_DISABLE */ #define XPATH_POINT 5 #define XPATH_RANGE 6 #define XPATH_LOCATIONSET 7 /** DOC_ENABLE */ #endif typedef struct _xmlXPathObject xmlXPathObject; typedef xmlXPathObject *xmlXPathObjectPtr; struct _xmlXPathObject { xmlXPathObjectType type; xmlNodeSetPtr nodesetval; int boolval; double floatval; xmlChar *stringval; void *user; int index; void *user2; int index2; }; /** * xmlXPathConvertFunc: * @obj: an XPath object * @type: the number of the target type * * A conversion function is associated to a type and used to cast * the new type to primitive values. * * Returns -1 in case of error, 0 otherwise */ typedef int (*xmlXPathConvertFunc) (xmlXPathObjectPtr obj, int type); /* * Extra type: a name and a conversion function. */ typedef struct _xmlXPathType xmlXPathType; typedef xmlXPathType *xmlXPathTypePtr; struct _xmlXPathType { const xmlChar *name; /* the type name */ xmlXPathConvertFunc func; /* the conversion function */ }; /* * Extra variable: a name and a value. */ typedef struct _xmlXPathVariable xmlXPathVariable; typedef xmlXPathVariable *xmlXPathVariablePtr; struct _xmlXPathVariable { const xmlChar *name; /* the variable name */ xmlXPathObjectPtr value; /* the value */ }; /** * xmlXPathEvalFunc: * @ctxt: an XPath parser context * @nargs: the number of arguments passed to the function * * An XPath evaluation function, the parameters are on the XPath context stack. */ typedef void (*xmlXPathEvalFunc)(xmlXPathParserContextPtr ctxt, int nargs); /* * Extra function: a name and a evaluation function. */ typedef struct _xmlXPathFunct xmlXPathFunct; typedef xmlXPathFunct *xmlXPathFuncPtr; struct _xmlXPathFunct { const xmlChar *name; /* the function name */ xmlXPathEvalFunc func; /* the evaluation function */ }; /** * xmlXPathAxisFunc: * @ctxt: the XPath interpreter context * @cur: the previous node being explored on that axis * * An axis traversal function. To traverse an axis, the engine calls * the first time with cur == NULL and repeat until the function returns * NULL indicating the end of the axis traversal. * * Returns the next node in that axis or NULL if at the end of the axis. */ typedef xmlXPathObjectPtr (*xmlXPathAxisFunc) (xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr cur); /* * Extra axis: a name and an axis function. */ typedef struct _xmlXPathAxis xmlXPathAxis; typedef xmlXPathAxis *xmlXPathAxisPtr; struct _xmlXPathAxis { const xmlChar *name; /* the axis name */ xmlXPathAxisFunc func; /* the search function */ }; /** * xmlXPathFunction: * @ctxt: the XPath interprestation context * @nargs: the number of arguments * * An XPath function. * The arguments (if any) are popped out from the context stack * and the result is pushed on the stack. */ typedef void (*xmlXPathFunction) (xmlXPathParserContextPtr ctxt, int nargs); /* * Function and Variable Lookup. */ /** * xmlXPathVariableLookupFunc: * @ctxt: an XPath context * @name: name of the variable * @ns_uri: the namespace name hosting this variable * * Prototype for callbacks used to plug variable lookup in the XPath * engine. * * Returns the XPath object value or NULL if not found. */ typedef xmlXPathObjectPtr (*xmlXPathVariableLookupFunc) (void *ctxt, const xmlChar *name, const xmlChar *ns_uri); /** * xmlXPathFuncLookupFunc: * @ctxt: an XPath context * @name: name of the function * @ns_uri: the namespace name hosting this function * * Prototype for callbacks used to plug function lookup in the XPath * engine. * * Returns the XPath function or NULL if not found. */ typedef xmlXPathFunction (*xmlXPathFuncLookupFunc) (void *ctxt, const xmlChar *name, const xmlChar *ns_uri); /** * xmlXPathFlags: * Flags for XPath engine compilation and runtime */ /** * XML_XPATH_CHECKNS: * * check namespaces at compilation */ #define XML_XPATH_CHECKNS (1<<0) /** * XML_XPATH_NOVAR: * * forbid variables in expression */ #define XML_XPATH_NOVAR (1<<1) /** * xmlXPathContext: * * Expression evaluation occurs with respect to a context. * he context consists of: * - a node (the context node) * - a node list (the context node list) * - a set of variable bindings * - a function library * - the set of namespace declarations in scope for the expression * Following the switch to hash tables, this need to be trimmed up at * the next binary incompatible release. * The node may be modified when the context is passed to libxml2 * for an XPath evaluation so you may need to initialize it again * before the next call. */ struct _xmlXPathContext { xmlDocPtr doc; /* The current document */ xmlNodePtr node; /* The current node */ int nb_variables_unused; /* unused (hash table) */ int max_variables_unused; /* unused (hash table) */ xmlHashTablePtr varHash; /* Hash table of defined variables */ int nb_types; /* number of defined types */ int max_types; /* max number of types */ xmlXPathTypePtr types; /* Array of defined types */ int nb_funcs_unused; /* unused (hash table) */ int max_funcs_unused; /* unused (hash table) */ xmlHashTablePtr funcHash; /* Hash table of defined funcs */ int nb_axis; /* number of defined axis */ int max_axis; /* max number of axis */ xmlXPathAxisPtr axis; /* Array of defined axis */ /* the namespace nodes of the context node */ xmlNsPtr *namespaces; /* Array of namespaces */ int nsNr; /* number of namespace in scope */ void *user; /* function to free */ /* extra variables */ int contextSize; /* the context size */ int proximityPosition; /* the proximity position */ /* extra stuff for XPointer */ int xptr; /* is this an XPointer context? */ xmlNodePtr here; /* for here() */ xmlNodePtr origin; /* for origin() */ /* the set of namespace declarations in scope for the expression */ xmlHashTablePtr nsHash; /* The namespaces hash table */ xmlXPathVariableLookupFunc varLookupFunc;/* variable lookup func */ void *varLookupData; /* variable lookup data */ /* Possibility to link in an extra item */ void *extra; /* needed for XSLT */ /* The function name and URI when calling a function */ const xmlChar *function; const xmlChar *functionURI; /* function lookup function and data */ xmlXPathFuncLookupFunc funcLookupFunc;/* function lookup func */ void *funcLookupData; /* function lookup data */ /* temporary namespace lists kept for walking the namespace axis */ xmlNsPtr *tmpNsList; /* Array of namespaces */ int tmpNsNr; /* number of namespaces in scope */ /* error reporting mechanism */ void *userData; /* user specific data block */ xmlStructuredErrorFunc error; /* the callback in case of errors */ xmlError lastError; /* the last error */ xmlNodePtr debugNode; /* the source node XSLT */ /* dictionary */ xmlDictPtr dict; /* dictionary if any */ int flags; /* flags to control compilation */ /* Cache for reusal of XPath objects */ void *cache; /* Resource limits */ unsigned long opLimit; unsigned long opCount; int depth; }; /* * The structure of a compiled expression form is not public. */ typedef struct _xmlXPathCompExpr xmlXPathCompExpr; typedef xmlXPathCompExpr *xmlXPathCompExprPtr; /** * xmlXPathParserContext: * * An XPath parser context. It contains pure parsing information, * an xmlXPathContext, and the stack of objects. */ struct _xmlXPathParserContext { const xmlChar *cur; /* the current char being parsed */ const xmlChar *base; /* the full expression */ int error; /* error code */ xmlXPathContextPtr context; /* the evaluation context */ xmlXPathObjectPtr value; /* the current value */ int valueNr; /* number of values stacked */ int valueMax; /* max number of values stacked */ xmlXPathObjectPtr *valueTab; /* stack of values */ xmlXPathCompExprPtr comp; /* the precompiled expression */ int xptr; /* it this an XPointer expression */ xmlNodePtr ancestor; /* used for walking preceding axis */ int valueFrame; /* unused */ }; /************************************************************************ * * * Public API * * * ************************************************************************/ /** * Objects and Nodesets handling */ XMLPUBVAR double xmlXPathNAN; XMLPUBVAR double xmlXPathPINF; XMLPUBVAR double xmlXPathNINF; /* These macros may later turn into functions */ /** * xmlXPathNodeSetGetLength: * @ns: a node-set * * Implement a functionality similar to the DOM NodeList.length. * * Returns the number of nodes in the node-set. */ #define xmlXPathNodeSetGetLength(ns) ((ns) ? (ns)->nodeNr : 0) /** * xmlXPathNodeSetItem: * @ns: a node-set * @index: index of a node in the set * * Implements a functionality similar to the DOM NodeList.item(). * * Returns the xmlNodePtr at the given @index in @ns or NULL if * @index is out of range (0 to length-1) */ #define xmlXPathNodeSetItem(ns, index) \ ((((ns) != NULL) && \ ((index) >= 0) && ((index) < (ns)->nodeNr)) ? \ (ns)->nodeTab[(index)] \ : NULL) /** * xmlXPathNodeSetIsEmpty: * @ns: a node-set * * Checks whether @ns is empty or not. * * Returns %TRUE if @ns is an empty node-set. */ #define xmlXPathNodeSetIsEmpty(ns) \ (((ns) == NULL) || ((ns)->nodeNr == 0) || ((ns)->nodeTab == NULL)) XMLPUBFUN void xmlXPathFreeObject (xmlXPathObjectPtr obj); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeSetCreate (xmlNodePtr val); XMLPUBFUN void xmlXPathFreeNodeSetList (xmlXPathObjectPtr obj); XMLPUBFUN void xmlXPathFreeNodeSet (xmlNodeSetPtr obj); XMLPUBFUN xmlXPathObjectPtr xmlXPathObjectCopy (xmlXPathObjectPtr val); XMLPUBFUN int xmlXPathCmpNodes (xmlNodePtr node1, xmlNodePtr node2); /** * Conversion functions to basic types. */ XMLPUBFUN int xmlXPathCastNumberToBoolean (double val); XMLPUBFUN int xmlXPathCastStringToBoolean (const xmlChar * val); XMLPUBFUN int xmlXPathCastNodeSetToBoolean(xmlNodeSetPtr ns); XMLPUBFUN int xmlXPathCastToBoolean (xmlXPathObjectPtr val); XMLPUBFUN double xmlXPathCastBooleanToNumber (int val); XMLPUBFUN double xmlXPathCastStringToNumber (const xmlChar * val); XMLPUBFUN double xmlXPathCastNodeToNumber (xmlNodePtr node); XMLPUBFUN double xmlXPathCastNodeSetToNumber (xmlNodeSetPtr ns); XMLPUBFUN double xmlXPathCastToNumber (xmlXPathObjectPtr val); XMLPUBFUN xmlChar * xmlXPathCastBooleanToString (int val); XMLPUBFUN xmlChar * xmlXPathCastNumberToString (double val); XMLPUBFUN xmlChar * xmlXPathCastNodeToString (xmlNodePtr node); XMLPUBFUN xmlChar * xmlXPathCastNodeSetToString (xmlNodeSetPtr ns); XMLPUBFUN xmlChar * xmlXPathCastToString (xmlXPathObjectPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathConvertBoolean (xmlXPathObjectPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathConvertNumber (xmlXPathObjectPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathConvertString (xmlXPathObjectPtr val); /** * Context handling. */ XMLPUBFUN xmlXPathContextPtr xmlXPathNewContext (xmlDocPtr doc); XMLPUBFUN void xmlXPathFreeContext (xmlXPathContextPtr ctxt); XMLPUBFUN int xmlXPathContextSetCache(xmlXPathContextPtr ctxt, int active, int value, int options); /** * Evaluation functions. */ XMLPUBFUN long xmlXPathOrderDocElems (xmlDocPtr doc); XMLPUBFUN int xmlXPathSetContextNode (xmlNodePtr node, xmlXPathContextPtr ctx); XMLPUBFUN xmlXPathObjectPtr xmlXPathNodeEval (xmlNodePtr node, const xmlChar *str, xmlXPathContextPtr ctx); XMLPUBFUN xmlXPathObjectPtr xmlXPathEval (const xmlChar *str, xmlXPathContextPtr ctx); XMLPUBFUN xmlXPathObjectPtr xmlXPathEvalExpression (const xmlChar *str, xmlXPathContextPtr ctxt); XMLPUBFUN int xmlXPathEvalPredicate (xmlXPathContextPtr ctxt, xmlXPathObjectPtr res); /** * Separate compilation/evaluation entry points. */ XMLPUBFUN xmlXPathCompExprPtr xmlXPathCompile (const xmlChar *str); XMLPUBFUN xmlXPathCompExprPtr xmlXPathCtxtCompile (xmlXPathContextPtr ctxt, const xmlChar *str); XMLPUBFUN xmlXPathObjectPtr xmlXPathCompiledEval (xmlXPathCompExprPtr comp, xmlXPathContextPtr ctx); XMLPUBFUN int xmlXPathCompiledEvalToBoolean(xmlXPathCompExprPtr comp, xmlXPathContextPtr ctxt); XMLPUBFUN void xmlXPathFreeCompExpr (xmlXPathCompExprPtr comp); #endif /* LIBXML_XPATH_ENABLED */ #if defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XML_DEPRECATED XMLPUBFUN void xmlXPathInit (void); XMLPUBFUN int xmlXPathIsNaN (double val); XMLPUBFUN int xmlXPathIsInf (double val); #ifdef __cplusplus } #endif #endif /* LIBXML_XPATH_ENABLED or LIBXML_SCHEMAS_ENABLED*/ #endif /* ! __XML_XPATH_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xpathInternals.h ================================================ /* * Summary: internal interfaces for XML Path Language implementation * Description: internal interfaces for XML Path Language implementation * used to build new modules on top of XPath like XPointer and * XSLT * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XPATH_INTERNALS_H__ #define __XML_XPATH_INTERNALS_H__ #include #include #ifdef LIBXML_XPATH_ENABLED #ifdef __cplusplus extern "C" { #endif /************************************************************************ * * * Helpers * * * ************************************************************************/ /* * Many of these macros may later turn into functions. They * shouldn't be used in #ifdef's preprocessor instructions. */ /** * xmlXPathSetError: * @ctxt: an XPath parser context * @err: an xmlXPathError code * * Raises an error. */ #define xmlXPathSetError(ctxt, err) \ { xmlXPatherror((ctxt), __FILE__, __LINE__, (err)); \ if ((ctxt) != NULL) (ctxt)->error = (err); } /** * xmlXPathSetArityError: * @ctxt: an XPath parser context * * Raises an XPATH_INVALID_ARITY error. */ #define xmlXPathSetArityError(ctxt) \ xmlXPathSetError((ctxt), XPATH_INVALID_ARITY) /** * xmlXPathSetTypeError: * @ctxt: an XPath parser context * * Raises an XPATH_INVALID_TYPE error. */ #define xmlXPathSetTypeError(ctxt) \ xmlXPathSetError((ctxt), XPATH_INVALID_TYPE) /** * xmlXPathGetError: * @ctxt: an XPath parser context * * Get the error code of an XPath context. * * Returns the context error. */ #define xmlXPathGetError(ctxt) ((ctxt)->error) /** * xmlXPathCheckError: * @ctxt: an XPath parser context * * Check if an XPath error was raised. * * Returns true if an error has been raised, false otherwise. */ #define xmlXPathCheckError(ctxt) ((ctxt)->error != XPATH_EXPRESSION_OK) /** * xmlXPathGetDocument: * @ctxt: an XPath parser context * * Get the document of an XPath context. * * Returns the context document. */ #define xmlXPathGetDocument(ctxt) ((ctxt)->context->doc) /** * xmlXPathGetContextNode: * @ctxt: an XPath parser context * * Get the context node of an XPath context. * * Returns the context node. */ #define xmlXPathGetContextNode(ctxt) ((ctxt)->context->node) XMLPUBFUN int xmlXPathPopBoolean (xmlXPathParserContextPtr ctxt); XMLPUBFUN double xmlXPathPopNumber (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlChar * xmlXPathPopString (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlNodeSetPtr xmlXPathPopNodeSet (xmlXPathParserContextPtr ctxt); XMLPUBFUN void * xmlXPathPopExternal (xmlXPathParserContextPtr ctxt); /** * xmlXPathReturnBoolean: * @ctxt: an XPath parser context * @val: a boolean * * Pushes the boolean @val on the context stack. */ #define xmlXPathReturnBoolean(ctxt, val) \ valuePush((ctxt), xmlXPathNewBoolean(val)) /** * xmlXPathReturnTrue: * @ctxt: an XPath parser context * * Pushes true on the context stack. */ #define xmlXPathReturnTrue(ctxt) xmlXPathReturnBoolean((ctxt), 1) /** * xmlXPathReturnFalse: * @ctxt: an XPath parser context * * Pushes false on the context stack. */ #define xmlXPathReturnFalse(ctxt) xmlXPathReturnBoolean((ctxt), 0) /** * xmlXPathReturnNumber: * @ctxt: an XPath parser context * @val: a double * * Pushes the double @val on the context stack. */ #define xmlXPathReturnNumber(ctxt, val) \ valuePush((ctxt), xmlXPathNewFloat(val)) /** * xmlXPathReturnString: * @ctxt: an XPath parser context * @str: a string * * Pushes the string @str on the context stack. */ #define xmlXPathReturnString(ctxt, str) \ valuePush((ctxt), xmlXPathWrapString(str)) /** * xmlXPathReturnEmptyString: * @ctxt: an XPath parser context * * Pushes an empty string on the stack. */ #define xmlXPathReturnEmptyString(ctxt) \ valuePush((ctxt), xmlXPathNewCString("")) /** * xmlXPathReturnNodeSet: * @ctxt: an XPath parser context * @ns: a node-set * * Pushes the node-set @ns on the context stack. */ #define xmlXPathReturnNodeSet(ctxt, ns) \ valuePush((ctxt), xmlXPathWrapNodeSet(ns)) /** * xmlXPathReturnEmptyNodeSet: * @ctxt: an XPath parser context * * Pushes an empty node-set on the context stack. */ #define xmlXPathReturnEmptyNodeSet(ctxt) \ valuePush((ctxt), xmlXPathNewNodeSet(NULL)) /** * xmlXPathReturnExternal: * @ctxt: an XPath parser context * @val: user data * * Pushes user data on the context stack. */ #define xmlXPathReturnExternal(ctxt, val) \ valuePush((ctxt), xmlXPathWrapExternal(val)) /** * xmlXPathStackIsNodeSet: * @ctxt: an XPath parser context * * Check if the current value on the XPath stack is a node set or * an XSLT value tree. * * Returns true if the current object on the stack is a node-set. */ #define xmlXPathStackIsNodeSet(ctxt) \ (((ctxt)->value != NULL) \ && (((ctxt)->value->type == XPATH_NODESET) \ || ((ctxt)->value->type == XPATH_XSLT_TREE))) /** * xmlXPathStackIsExternal: * @ctxt: an XPath parser context * * Checks if the current value on the XPath stack is an external * object. * * Returns true if the current object on the stack is an external * object. */ #define xmlXPathStackIsExternal(ctxt) \ ((ctxt->value != NULL) && (ctxt->value->type == XPATH_USERS)) /** * xmlXPathEmptyNodeSet: * @ns: a node-set * * Empties a node-set. */ #define xmlXPathEmptyNodeSet(ns) \ { while ((ns)->nodeNr > 0) (ns)->nodeTab[--(ns)->nodeNr] = NULL; } /** * CHECK_ERROR: * * Macro to return from the function if an XPath error was detected. */ #define CHECK_ERROR \ if (ctxt->error != XPATH_EXPRESSION_OK) return /** * CHECK_ERROR0: * * Macro to return 0 from the function if an XPath error was detected. */ #define CHECK_ERROR0 \ if (ctxt->error != XPATH_EXPRESSION_OK) return(0) /** * XP_ERROR: * @X: the error code * * Macro to raise an XPath error and return. */ #define XP_ERROR(X) \ { xmlXPathErr(ctxt, X); return; } /** * XP_ERROR0: * @X: the error code * * Macro to raise an XPath error and return 0. */ #define XP_ERROR0(X) \ { xmlXPathErr(ctxt, X); return(0); } /** * CHECK_TYPE: * @typeval: the XPath type * * Macro to check that the value on top of the XPath stack is of a given * type. */ #define CHECK_TYPE(typeval) \ if ((ctxt->value == NULL) || (ctxt->value->type != typeval)) \ XP_ERROR(XPATH_INVALID_TYPE) /** * CHECK_TYPE0: * @typeval: the XPath type * * Macro to check that the value on top of the XPath stack is of a given * type. Return(0) in case of failure */ #define CHECK_TYPE0(typeval) \ if ((ctxt->value == NULL) || (ctxt->value->type != typeval)) \ XP_ERROR0(XPATH_INVALID_TYPE) /** * CHECK_ARITY: * @x: the number of expected args * * Macro to check that the number of args passed to an XPath function matches. */ #define CHECK_ARITY(x) \ if (ctxt == NULL) return; \ if (nargs != (x)) \ XP_ERROR(XPATH_INVALID_ARITY); \ if (ctxt->valueNr < ctxt->valueFrame + (x)) \ XP_ERROR(XPATH_STACK_ERROR); /** * CAST_TO_STRING: * * Macro to try to cast the value on the top of the XPath stack to a string. */ #define CAST_TO_STRING \ if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_STRING)) \ xmlXPathStringFunction(ctxt, 1); /** * CAST_TO_NUMBER: * * Macro to try to cast the value on the top of the XPath stack to a number. */ #define CAST_TO_NUMBER \ if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_NUMBER)) \ xmlXPathNumberFunction(ctxt, 1); /** * CAST_TO_BOOLEAN: * * Macro to try to cast the value on the top of the XPath stack to a boolean. */ #define CAST_TO_BOOLEAN \ if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_BOOLEAN)) \ xmlXPathBooleanFunction(ctxt, 1); /* * Variable Lookup forwarding. */ XMLPUBFUN void xmlXPathRegisterVariableLookup (xmlXPathContextPtr ctxt, xmlXPathVariableLookupFunc f, void *data); /* * Function Lookup forwarding. */ XMLPUBFUN void xmlXPathRegisterFuncLookup (xmlXPathContextPtr ctxt, xmlXPathFuncLookupFunc f, void *funcCtxt); /* * Error reporting. */ XMLPUBFUN void xmlXPatherror (xmlXPathParserContextPtr ctxt, const char *file, int line, int no); XMLPUBFUN void xmlXPathErr (xmlXPathParserContextPtr ctxt, int error); #ifdef LIBXML_DEBUG_ENABLED XMLPUBFUN void xmlXPathDebugDumpObject (FILE *output, xmlXPathObjectPtr cur, int depth); XMLPUBFUN void xmlXPathDebugDumpCompExpr(FILE *output, xmlXPathCompExprPtr comp, int depth); #endif /** * NodeSet handling. */ XMLPUBFUN int xmlXPathNodeSetContains (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN xmlNodeSetPtr xmlXPathDifference (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathIntersection (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathDistinctSorted (xmlNodeSetPtr nodes); XMLPUBFUN xmlNodeSetPtr xmlXPathDistinct (xmlNodeSetPtr nodes); XMLPUBFUN int xmlXPathHasSameNodes (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeLeadingSorted (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathLeadingSorted (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeLeading (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathLeading (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeTrailingSorted (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathTrailingSorted (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeTrailing (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathTrailing (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); /** * Extending a context. */ XMLPUBFUN int xmlXPathRegisterNs (xmlXPathContextPtr ctxt, const xmlChar *prefix, const xmlChar *ns_uri); XMLPUBFUN const xmlChar * xmlXPathNsLookup (xmlXPathContextPtr ctxt, const xmlChar *prefix); XMLPUBFUN void xmlXPathRegisteredNsCleanup (xmlXPathContextPtr ctxt); XMLPUBFUN int xmlXPathRegisterFunc (xmlXPathContextPtr ctxt, const xmlChar *name, xmlXPathFunction f); XMLPUBFUN int xmlXPathRegisterFuncNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri, xmlXPathFunction f); XMLPUBFUN int xmlXPathRegisterVariable (xmlXPathContextPtr ctxt, const xmlChar *name, xmlXPathObjectPtr value); XMLPUBFUN int xmlXPathRegisterVariableNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri, xmlXPathObjectPtr value); XMLPUBFUN xmlXPathFunction xmlXPathFunctionLookup (xmlXPathContextPtr ctxt, const xmlChar *name); XMLPUBFUN xmlXPathFunction xmlXPathFunctionLookupNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri); XMLPUBFUN void xmlXPathRegisteredFuncsCleanup (xmlXPathContextPtr ctxt); XMLPUBFUN xmlXPathObjectPtr xmlXPathVariableLookup (xmlXPathContextPtr ctxt, const xmlChar *name); XMLPUBFUN xmlXPathObjectPtr xmlXPathVariableLookupNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri); XMLPUBFUN void xmlXPathRegisteredVariablesCleanup(xmlXPathContextPtr ctxt); /** * Utilities to extend XPath. */ XMLPUBFUN xmlXPathParserContextPtr xmlXPathNewParserContext (const xmlChar *str, xmlXPathContextPtr ctxt); XMLPUBFUN void xmlXPathFreeParserContext (xmlXPathParserContextPtr ctxt); /* TODO: remap to xmlXPathValuePop and Push. */ XMLPUBFUN xmlXPathObjectPtr valuePop (xmlXPathParserContextPtr ctxt); XMLPUBFUN int valuePush (xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr value); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewString (const xmlChar *val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewCString (const char *val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapString (xmlChar *val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapCString (char * val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewFloat (double val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewBoolean (int val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewNodeSet (xmlNodePtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewValueTree (xmlNodePtr val); XMLPUBFUN int xmlXPathNodeSetAdd (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN int xmlXPathNodeSetAddUnique (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN int xmlXPathNodeSetAddNs (xmlNodeSetPtr cur, xmlNodePtr node, xmlNsPtr ns); XMLPUBFUN void xmlXPathNodeSetSort (xmlNodeSetPtr set); XMLPUBFUN void xmlXPathRoot (xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathEvalExpr (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlChar * xmlXPathParseName (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlChar * xmlXPathParseNCName (xmlXPathParserContextPtr ctxt); /* * Existing functions. */ XMLPUBFUN double xmlXPathStringEvalNumber (const xmlChar *str); XMLPUBFUN int xmlXPathEvaluatePredicateResult (xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr res); XMLPUBFUN void xmlXPathRegisterAllFunctions (xmlXPathContextPtr ctxt); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeSetMerge (xmlNodeSetPtr val1, xmlNodeSetPtr val2); XMLPUBFUN void xmlXPathNodeSetDel (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN void xmlXPathNodeSetRemove (xmlNodeSetPtr cur, int val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewNodeSetList (xmlNodeSetPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapNodeSet (xmlNodeSetPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapExternal (void *val); XMLPUBFUN int xmlXPathEqualValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN int xmlXPathNotEqualValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN int xmlXPathCompareValues(xmlXPathParserContextPtr ctxt, int inf, int strict); XMLPUBFUN void xmlXPathValueFlipSign(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathAddValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathSubValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathMultValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathDivValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathModValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN int xmlXPathIsNodeType(const xmlChar *name); /* * Some of the axis navigation routines. */ XMLPUBFUN xmlNodePtr xmlXPathNextSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextChild(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextDescendant(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextDescendantOrSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextParent(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextAncestorOrSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextFollowingSibling(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextFollowing(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextNamespace(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextAttribute(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextPreceding(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextAncestor(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextPrecedingSibling(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); /* * The official core of XPath functions. */ XMLPUBFUN void xmlXPathLastFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathPositionFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathCountFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathIdFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathLocalNameFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNamespaceURIFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathStringFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathStringLengthFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathConcatFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathContainsFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathStartsWithFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSubstringFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSubstringBeforeFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSubstringAfterFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNormalizeFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathTranslateFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNotFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathTrueFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathFalseFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathLangFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNumberFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSumFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathFloorFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathCeilingFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathRoundFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathBooleanFunction(xmlXPathParserContextPtr ctxt, int nargs); /** * Really internal functions */ XMLPUBFUN void xmlXPathNodeSetFreeNs(xmlNsPtr ns); #ifdef __cplusplus } #endif #endif /* LIBXML_XPATH_ENABLED */ #endif /* ! __XML_XPATH_INTERNALS_H__ */ ================================================ FILE: thirdparty/32/include/libxml2/libxml/xpointer.h ================================================ /* * Summary: API to handle XML Pointers * Description: API to handle XML Pointers * Base implementation was made accordingly to * W3C Candidate Recommendation 7 June 2000 * http://www.w3.org/TR/2000/CR-xptr-20000607 * * Added support for the element() scheme described in: * W3C Proposed Recommendation 13 November 2002 * http://www.w3.org/TR/2002/PR-xptr-element-20021113/ * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XPTR_H__ #define __XML_XPTR_H__ #include #ifdef LIBXML_XPTR_ENABLED #include #include #ifdef __cplusplus extern "C" { #endif #ifdef LIBXML_XPTR_LOCS_ENABLED /* * A Location Set */ typedef struct _xmlLocationSet xmlLocationSet; typedef xmlLocationSet *xmlLocationSetPtr; struct _xmlLocationSet { int locNr; /* number of locations in the set */ int locMax; /* size of the array as allocated */ xmlXPathObjectPtr *locTab;/* array of locations */ }; /* * Handling of location sets. */ XML_DEPRECATED XMLPUBFUN xmlLocationSetPtr xmlXPtrLocationSetCreate (xmlXPathObjectPtr val); XML_DEPRECATED XMLPUBFUN void xmlXPtrFreeLocationSet (xmlLocationSetPtr obj); XML_DEPRECATED XMLPUBFUN xmlLocationSetPtr xmlXPtrLocationSetMerge (xmlLocationSetPtr val1, xmlLocationSetPtr val2); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRange (xmlNodePtr start, int startindex, xmlNodePtr end, int endindex); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangePoints (xmlXPathObjectPtr start, xmlXPathObjectPtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangeNodePoint (xmlNodePtr start, xmlXPathObjectPtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangePointNode (xmlXPathObjectPtr start, xmlNodePtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangeNodes (xmlNodePtr start, xmlNodePtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewLocationSetNodes (xmlNodePtr start, xmlNodePtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewLocationSetNodeSet(xmlNodeSetPtr set); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangeNodeObject (xmlNodePtr start, xmlXPathObjectPtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewCollapsedRange (xmlNodePtr start); XML_DEPRECATED XMLPUBFUN void xmlXPtrLocationSetAdd (xmlLocationSetPtr cur, xmlXPathObjectPtr val); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrWrapLocationSet (xmlLocationSetPtr val); XML_DEPRECATED XMLPUBFUN void xmlXPtrLocationSetDel (xmlLocationSetPtr cur, xmlXPathObjectPtr val); XML_DEPRECATED XMLPUBFUN void xmlXPtrLocationSetRemove (xmlLocationSetPtr cur, int val); #endif /* LIBXML_XPTR_LOCS_ENABLED */ /* * Functions. */ XMLPUBFUN xmlXPathContextPtr xmlXPtrNewContext (xmlDocPtr doc, xmlNodePtr here, xmlNodePtr origin); XMLPUBFUN xmlXPathObjectPtr xmlXPtrEval (const xmlChar *str, xmlXPathContextPtr ctx); #ifdef LIBXML_XPTR_LOCS_ENABLED XML_DEPRECATED XMLPUBFUN void xmlXPtrRangeToFunction (xmlXPathParserContextPtr ctxt, int nargs); XML_DEPRECATED XMLPUBFUN xmlNodePtr xmlXPtrBuildNodeList (xmlXPathObjectPtr obj); XML_DEPRECATED XMLPUBFUN void xmlXPtrEvalRangePredicate (xmlXPathParserContextPtr ctxt); #endif /* LIBXML_XPTR_LOCS_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_XPTR_ENABLED */ #endif /* __XML_XPTR_H__ */ ================================================ FILE: thirdparty/32/include/nettle/aes.h ================================================ /* aes.h The aes/rijndael block cipher. Copyright (C) 2001, 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_AES_H_INCLUDED #define NETTLE_AES_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define aes_set_encrypt_key nettle_aes_set_encrypt_key #define aes_set_decrypt_key nettle_aes_set_decrypt_key #define aes_invert_key nettle_aes_invert_key #define aes_encrypt nettle_aes_encrypt #define aes_decrypt nettle_aes_decrypt #define aes128_set_encrypt_key nettle_aes128_set_encrypt_key #define aes128_set_decrypt_key nettle_aes128_set_decrypt_key #define aes128_invert_key nettle_aes128_invert_key #define aes128_encrypt nettle_aes128_encrypt #define aes128_decrypt nettle_aes128_decrypt #define aes192_set_encrypt_key nettle_aes192_set_encrypt_key #define aes192_set_decrypt_key nettle_aes192_set_decrypt_key #define aes192_invert_key nettle_aes192_invert_key #define aes192_encrypt nettle_aes192_encrypt #define aes192_decrypt nettle_aes192_decrypt #define aes256_set_encrypt_key nettle_aes256_set_encrypt_key #define aes256_set_decrypt_key nettle_aes256_set_decrypt_key #define aes256_invert_key nettle_aes256_invert_key #define aes256_encrypt nettle_aes256_encrypt #define aes256_decrypt nettle_aes256_decrypt #define AES_BLOCK_SIZE 16 #define AES128_KEY_SIZE 16 #define AES192_KEY_SIZE 24 #define AES256_KEY_SIZE 32 #define _AES128_ROUNDS 10 #define _AES192_ROUNDS 12 #define _AES256_ROUNDS 14 struct aes128_ctx { uint32_t keys[4 * (_AES128_ROUNDS + 1)]; }; void aes128_set_encrypt_key(struct aes128_ctx *ctx, const uint8_t *key); void aes128_set_decrypt_key(struct aes128_ctx *ctx, const uint8_t *key); void aes128_invert_key(struct aes128_ctx *dst, const struct aes128_ctx *src); void aes128_encrypt(const struct aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void aes128_decrypt(const struct aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); struct aes192_ctx { uint32_t keys[4 * (_AES192_ROUNDS + 1)]; }; void aes192_set_encrypt_key(struct aes192_ctx *ctx, const uint8_t *key); void aes192_set_decrypt_key(struct aes192_ctx *ctx, const uint8_t *key); void aes192_invert_key(struct aes192_ctx *dst, const struct aes192_ctx *src); void aes192_encrypt(const struct aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void aes192_decrypt(const struct aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); struct aes256_ctx { uint32_t keys[4 * (_AES256_ROUNDS + 1)]; }; void aes256_set_encrypt_key(struct aes256_ctx *ctx, const uint8_t *key); void aes256_set_decrypt_key(struct aes256_ctx *ctx, const uint8_t *key); void aes256_invert_key(struct aes256_ctx *dst, const struct aes256_ctx *src); void aes256_encrypt(const struct aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void aes256_decrypt(const struct aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* The older nettle-2.7 AES interface is deprecated, please migrate to the newer interface where each algorithm has a fixed key size. */ /* Variable key size between 128 and 256 bits. But the only valid * values are 16 (128 bits), 24 (192 bits) and 32 (256 bits). */ #define AES_MIN_KEY_SIZE AES128_KEY_SIZE #define AES_MAX_KEY_SIZE AES256_KEY_SIZE #define AES_KEY_SIZE 32 struct aes_ctx { unsigned key_size; /* In octets */ union { struct aes128_ctx ctx128; struct aes192_ctx ctx192; struct aes256_ctx ctx256; } u; }; void aes_set_encrypt_key(struct aes_ctx *ctx, size_t length, const uint8_t *key) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_set_decrypt_key(struct aes_ctx *ctx, size_t length, const uint8_t *key) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_invert_key(struct aes_ctx *dst, const struct aes_ctx *src) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_encrypt(const struct aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_decrypt(const struct aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; #ifdef __cplusplus } #endif #endif /* NETTLE_AES_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/arcfour.h ================================================ /* arcfour.h The arcfour/rc4 stream cipher. Copyright (C) 2001, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_ARCFOUR_H_INCLUDED #define NETTLE_ARCFOUR_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define arcfour128_set_key nettle_arcfour128_set_key #define arcfour_set_key nettle_arcfour_set_key #define arcfour_crypt nettle_arcfour_crypt /* Minimum and maximum keysizes, and a reasonable default. In * octets.*/ #define ARCFOUR_MIN_KEY_SIZE 1 #define ARCFOUR_MAX_KEY_SIZE 256 #define ARCFOUR_KEY_SIZE 16 #define ARCFOUR128_KEY_SIZE 16 struct arcfour_ctx { uint8_t S[256]; uint8_t i; uint8_t j; }; void arcfour_set_key(struct arcfour_ctx *ctx, size_t length, const uint8_t *key); void arcfour128_set_key(struct arcfour_ctx *ctx, const uint8_t *key); void arcfour_crypt(struct arcfour_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_ARCFOUR_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/arctwo.h ================================================ /* arctwo.h The arctwo/rfc2268 block cipher. Copyright (C) 2004 Simon Josefsson Copyright (C) 2002, 2004, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_ARCTWO_H_INCLUDED #define NETTLE_ARCTWO_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define arctwo_set_key nettle_arctwo_set_key #define arctwo_set_key_ekb nettle_arctwo_set_key_ekb #define arctwo_set_key_gutmann nettle_arctwo_set_key_gutmann #define arctwo40_set_key nettle_arctwo40_set_key #define arctwo64_set_key nettle_arctwo64_set_key #define arctwo128_set_key nettle_arctwo128_set_key #define arctwo128_set_key_gutmann nettle_arctwo128_set_key_gutmann #define arctwo_encrypt nettle_arctwo_encrypt #define arctwo_decrypt nettle_arctwo_decrypt #define ARCTWO_BLOCK_SIZE 8 /* Variable key size from 1 byte to 128 bytes. */ #define ARCTWO_MIN_KEY_SIZE 1 #define ARCTWO_MAX_KEY_SIZE 128 #define ARCTWO_KEY_SIZE 8 struct arctwo_ctx { uint16_t S[64]; }; /* Key expansion function that takes the "effective key bits", 1-1024, as an explicit argument. 0 means maximum key bits. */ void arctwo_set_key_ekb (struct arctwo_ctx *ctx, size_t length, const uint8_t * key, unsigned ekb); /* Equvivalent to arctwo_set_key_ekb, with ekb = 8 * length */ void arctwo_set_key (struct arctwo_ctx *ctx, size_t length, const uint8_t *key); void arctwo40_set_key (struct arctwo_ctx *ctx, const uint8_t *key); void arctwo64_set_key (struct arctwo_ctx *ctx, const uint8_t *key); void arctwo128_set_key (struct arctwo_ctx *ctx, const uint8_t *key); /* Equvivalent to arctwo_set_key_ekb, with ekb = 1024 */ void arctwo_set_key_gutmann (struct arctwo_ctx *ctx, size_t length, const uint8_t *key); void arctwo128_set_key_gutmann (struct arctwo_ctx *ctx, const uint8_t *key); void arctwo_encrypt (struct arctwo_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void arctwo_decrypt (struct arctwo_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_ARCTWO_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/asn1.h ================================================ /* asn1.h Limited support for ASN.1 DER decoding. Copyright (C) 2005 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_ASN1_H_INCLUDED #define NETTLE_ASN1_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define asn1_der_iterator_first nettle_asn1_der_iterator_first #define asn1_der_iterator_next nettle_asn1_der_iterator_next #define asn1_der_decode_constructed nettle_asn1_der_decode_constructed #define asn1_der_decode_constructed_last nettle_asn1_der_decode_constructed_last #define asn1_der_decode_bitstring nettle_asn1_der_decode_bitstring #define asn1_der_decode_bitstring_last nettle_asn1_der_decode_bitstring_last #define asn1_der_get_uint32 nettle_asn1_der_get_uint32 #define asn1_der_get_bignum nettle_asn1_der_get_bignum /* enum asn1_type keeps the class number and the constructive in bits 13-14, and the constructive flag in bit 12. The remaining 14 bits are the tag (although currently, only tags in the range 0-30 are supported). */ enum { ASN1_TYPE_CONSTRUCTED = 1 << 12, ASN1_CLASS_UNIVERSAL = 0, ASN1_CLASS_APPLICATION = 1 << 13, ASN1_CLASS_CONTEXT_SPECIFIC = 2 << 13, ASN1_CLASS_PRIVATE = 3 << 13, ASN1_CLASS_MASK = 3 << 13, ASN1_CLASS_SHIFT = 13, }; enum asn1_type { ASN1_BOOLEAN = 1, ASN1_INTEGER = 2, ASN1_BITSTRING = 3, ASN1_OCTETSTRING = 4, ASN1_NULL = 5, ASN1_IDENTIFIER = 6, ASN1_REAL = 9, ASN1_ENUMERATED = 10, ASN1_UTF8STRING = 12, ASN1_SEQUENCE = 16 | ASN1_TYPE_CONSTRUCTED, ASN1_SET = 17 | ASN1_TYPE_CONSTRUCTED, ASN1_PRINTABLESTRING = 19, ASN1_TELETEXSTRING = 20, ASN1_IA5STRING = 22, ASN1_UTC = 23, ASN1_UNIVERSALSTRING = 28, ASN1_BMPSTRING = 30, }; enum asn1_iterator_result { ASN1_ITERATOR_ERROR, ASN1_ITERATOR_PRIMITIVE, ASN1_ITERATOR_CONSTRUCTED, ASN1_ITERATOR_END, }; /* Parsing DER objects. */ struct asn1_der_iterator { size_t buffer_length; const uint8_t *buffer; /* Next object to parse. */ size_t pos; enum asn1_type type; /* Pointer to the current object */ size_t length; const uint8_t *data; }; /* Initializes the iterator. */ enum asn1_iterator_result asn1_der_iterator_first(struct asn1_der_iterator *iterator, size_t length, const uint8_t *input); enum asn1_iterator_result asn1_der_iterator_next(struct asn1_der_iterator *iterator); /* Starts parsing of a constructed object. */ enum asn1_iterator_result asn1_der_decode_constructed(struct asn1_der_iterator *i, struct asn1_der_iterator *contents); /* For the common case that we have a sequence at the end of the object. Checks that the current object is the final one, and then reinitializes the iterator to parse its ontents. */ enum asn1_iterator_result asn1_der_decode_constructed_last(struct asn1_der_iterator *i); enum asn1_iterator_result asn1_der_decode_bitstring(struct asn1_der_iterator *i, struct asn1_der_iterator *contents); enum asn1_iterator_result asn1_der_decode_bitstring_last(struct asn1_der_iterator *i); /* All these functions return 1 on success, 0 on failure */ int asn1_der_get_uint32(struct asn1_der_iterator *i, uint32_t *x); #ifdef __cplusplus } #endif #endif /* NETTLE_ASN1_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/balloon.h ================================================ /* balloon.h Balloon password-hashing algorithm. Copyright (C) 2022 Zoltan Fridrich Copyright (C) 2022 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* For a description of the algorithm, see: * Boneh, D., Corrigan-Gibbs, H., Schechter, S. (2017, May 12). Balloon Hashing: * A Memory-Hard Function Providing Provable Protection Against Sequential Attacks. * Retrieved Sep 1, 2022, from https://eprint.iacr.org/2016/027.pdf */ #ifndef NETTLE_BALLOON_H_INCLUDED #define NETTLE_BALLOON_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define balloon nettle_balloon #define balloon_itch nettle_balloon_itch #define balloon_sha1 nettle_balloon_sha1 #define balloon_sha256 nettle_balloon_sha256 #define balloon_sha384 nettle_balloon_sha384 #define balloon_sha512 nettle_balloon_sha512 void balloon(void *hash_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); size_t balloon_itch(size_t digest_size, size_t s_cost); void balloon_sha1(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); void balloon_sha256(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); void balloon_sha384(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); void balloon_sha512(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_BALLOON_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/base16.h ================================================ /* base16.h Hex encoding and decoding, following spki conventions (i.e. allowing whitespace between digits). Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BASE16_H_INCLUDED #define NETTLE_BASE16_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define base16_encode_single nettle_base16_encode_single #define base16_encode_update nettle_base16_encode_update #define base16_decode_init nettle_base16_decode_init #define base16_decode_single nettle_base16_decode_single #define base16_decode_update nettle_base16_decode_update #define base16_decode_final nettle_base16_decode_final /* Base16 encoding */ /* Maximum length of output for base16_encode_update. */ #define BASE16_ENCODE_LENGTH(length) ((length) * 2) /* Encodes a single byte. Always stores two digits in dst[0] and dst[1]. */ void base16_encode_single(char *dst, uint8_t src); /* Always stores BASE16_ENCODE_LENGTH(length) digits in dst. */ void base16_encode_update(char *dst, size_t length, const uint8_t *src); /* Base16 decoding */ /* Maximum length of output for base16_decode_update. */ /* We have at most 4 buffered bits, and a total of (length + 1) * 4 bits. */ #define BASE16_DECODE_LENGTH(length) (((length) + 1) / 2) struct base16_decode_ctx { unsigned char word; /* Leftover bits */ unsigned char bits; /* Number buffered bits */ }; void base16_decode_init(struct base16_decode_ctx *ctx); /* Decodes a single byte. Returns amount of output (0 or 1), or -1 on * errors. */ int base16_decode_single(struct base16_decode_ctx *ctx, uint8_t *dst, char src); /* Returns 1 on success, 0 on error. DST should point to an area of * size at least BASE16_DECODE_LENGTH(length). The amount of data * generated is returned in *DST_LENGTH. */ int base16_decode_update(struct base16_decode_ctx *ctx, size_t *dst_length, uint8_t *dst, size_t src_length, const char *src); /* Returns 1 on success. */ int base16_decode_final(struct base16_decode_ctx *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_BASE16_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/base64.h ================================================ /* base64.h Base-64 encoding and decoding. Copyright (C) 2002 Niels Möller, Dan Egnor This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BASE64_H_INCLUDED #define NETTLE_BASE64_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define base64_encode_init nettle_base64_encode_init #define base64url_encode_init nettle_base64url_encode_init #define base64_encode_single nettle_base64_encode_single #define base64_encode_update nettle_base64_encode_update #define base64_encode_final nettle_base64_encode_final #define base64_encode_raw nettle_base64_encode_raw #define base64_encode_group nettle_base64_encode_group #define base64_decode_init nettle_base64_decode_init #define base64url_decode_init nettle_base64url_decode_init #define base64_decode_single nettle_base64_decode_single #define base64_decode_update nettle_base64_decode_update #define base64_decode_final nettle_base64_decode_final #define BASE64_BINARY_BLOCK_SIZE 3 #define BASE64_TEXT_BLOCK_SIZE 4 /* Base64 encoding */ /* Maximum length of output for base64_encode_update. NOTE: Doesn't * include any padding that base64_encode_final may add. */ /* We have at most 4 buffered bits, and a total of (4 + length * 8) bits. */ #define BASE64_ENCODE_LENGTH(length) (((length) * 8 + 4)/6) /* Maximum length of output generated by base64_encode_final. */ #define BASE64_ENCODE_FINAL_LENGTH 3 /* Exact length of output generated by base64_encode_raw, including * padding. */ #define BASE64_ENCODE_RAW_LENGTH(length) ((((length) + 2)/3)*4) struct base64_encode_ctx { const char *alphabet; /* Alphabet to use for encoding */ unsigned short word; /* Leftover bits */ unsigned char bits; /* Number of bits, always 0, 2, or 4. */ }; /* Initialize encoding context for base-64 */ void base64_encode_init(struct base64_encode_ctx *ctx); /* Initialize encoding context for URL safe alphabet, RFC 4648. */ void base64url_encode_init(struct base64_encode_ctx *ctx); /* Encodes a single byte. Returns amount of output (always 1 or 2). */ size_t base64_encode_single(struct base64_encode_ctx *ctx, char *dst, uint8_t src); /* Returns the number of output characters. DST should point to an * area of size at least BASE64_ENCODE_LENGTH(length). */ size_t base64_encode_update(struct base64_encode_ctx *ctx, char *dst, size_t length, const uint8_t *src); /* DST should point to an area of size at least * BASE64_ENCODE_FINAL_LENGTH */ size_t base64_encode_final(struct base64_encode_ctx *ctx, char *dst); /* Lower level functions */ /* Encodes a string in one go, including any padding at the end. * Generates exactly BASE64_ENCODE_RAW_LENGTH(length) bytes of output. * Supports overlapped operation, if src <= dst. FIXME: Use of overlap * is deprecated, if needed there should be a separate public fucntion * to do that.*/ void base64_encode_raw(char *dst, size_t length, const uint8_t *src); void base64_encode_group(char *dst, uint32_t group); /* Base64 decoding */ /* Maximum length of output for base64_decode_update. */ /* We have at most 6 buffered bits, and a total of (length + 1) * 6 bits. */ #define BASE64_DECODE_LENGTH(length) ((((length) + 1) * 6) / 8) struct base64_decode_ctx { const signed char *table; /* Decoding table */ unsigned short word; /* Leftover bits */ unsigned char bits; /* Number buffered bits */ /* Number of padding characters encountered */ unsigned char padding; }; /* Initialize decoding context for base-64 */ void base64_decode_init(struct base64_decode_ctx *ctx); /* Initialize encoding context for URL safe alphabet, RFC 4648. */ void base64url_decode_init(struct base64_decode_ctx *ctx); /* Decodes a single byte. Returns amount of output (0 or 1), or -1 on * errors. */ int base64_decode_single(struct base64_decode_ctx *ctx, uint8_t *dst, char src); /* Returns 1 on success, 0 on error. DST should point to an area of * size at least BASE64_DECODE_LENGTH(length). The amount of data * generated is returned in *DST_LENGTH. */ int base64_decode_update(struct base64_decode_ctx *ctx, size_t *dst_length, uint8_t *dst, size_t src_length, const char *src); /* Returns 1 on success. */ int base64_decode_final(struct base64_decode_ctx *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_BASE64_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/bignum.h ================================================ /* bignum.h Bignum operations that are missing from gmp. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BIGNUM_H_INCLUDED #define NETTLE_BIGNUM_H_INCLUDED #include "nettle-types.h" /* For NETTLE_USE_MINI_GMP */ #include "version.h" #if NETTLE_USE_MINI_GMP # include "mini-gmp.h" # define GMP_NUMB_MASK (~(mp_limb_t) 0) /* Side-channel silent powm not available in mini-gmp. */ # define mpz_powm_sec mpz_powm #else # include #endif #ifdef __cplusplus extern "C" { #endif /* Size needed for signed encoding, including extra sign byte if * necessary. */ size_t nettle_mpz_sizeinbase_256_s(const mpz_t x); /* Size needed for unsigned encoding */ size_t nettle_mpz_sizeinbase_256_u(const mpz_t x); /* Writes an integer as length octets, using big endian byte order, * and two's complement for negative numbers. */ void nettle_mpz_get_str_256(size_t length, uint8_t *s, const mpz_t x); /* Reads a big endian, two's complement, integer. */ void nettle_mpz_set_str_256_s(mpz_t x, size_t length, const uint8_t *s); void nettle_mpz_init_set_str_256_s(mpz_t x, size_t length, const uint8_t *s); /* Similar, but for unsigned format. These function don't interpret * the most significant bit as the sign. */ void nettle_mpz_set_str_256_u(mpz_t x, size_t length, const uint8_t *s); void nettle_mpz_init_set_str_256_u(mpz_t x, size_t length, const uint8_t *s); /* Returns a uniformly distributed random number 0 <= x < 2^n */ void nettle_mpz_random_size(mpz_t x, void *ctx, nettle_random_func *random, unsigned bits); /* Returns a number x, almost uniformly random in the range * 0 <= x < n. */ void nettle_mpz_random(mpz_t x, void *ctx, nettle_random_func *random, const mpz_t n); void nettle_random_prime(mpz_t p, unsigned bits, int top_bits_set, void *ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress); /* sexp parsing */ struct sexp_iterator; /* If LIMIT is non-zero, the number must be at most LIMIT bits. * Implies sexp_iterator_next. */ int nettle_mpz_set_sexp(mpz_t x, unsigned limit, struct sexp_iterator *i); /* der parsing */ struct asn1_der_iterator; int nettle_asn1_der_get_bignum(struct asn1_der_iterator *iterator, mpz_t x, unsigned max_bits); #ifdef __cplusplus } #endif #endif /* NETTLE_BIGNUM_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/blowfish.h ================================================ /* blowfish.h Blowfish block cipher. Copyright (C) 2014 Niels Möller Copyright (C) 1998, 2001 FSF, Ray Dassen, Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BLOWFISH_H_INCLUDED #define NETTLE_BLOWFISH_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define blowfish_set_key nettle_blowfish_set_key #define blowfish128_set_key nettle_blowfish128_set_key #define blowfish_encrypt nettle_blowfish_encrypt #define blowfish_decrypt nettle_blowfish_decrypt #define blowfish_bcrypt_hash nettle_blowfish_bcrypt_hash #define blowfish_bcrypt_verify nettle_blowfish_bcrypt_verify #define BLOWFISH_BLOCK_SIZE 8 /* Variable key size between 64 and 448 bits. */ #define BLOWFISH_MIN_KEY_SIZE 8 #define BLOWFISH_MAX_KEY_SIZE 56 /* Default to 128 bits */ #define BLOWFISH_KEY_SIZE 16 #define BLOWFISH128_KEY_SIZE 16 #define _BLOWFISH_ROUNDS 16 #define BLOWFISH_BCRYPT_HASH_SIZE (60 + 1) /* Including null-terminator */ #define BLOWFISH_BCRYPT_BINSALT_SIZE 16 /* Binary string size */ struct blowfish_ctx { uint32_t s[4][256]; uint32_t p[_BLOWFISH_ROUNDS+2]; }; /* Returns 0 for weak keys, otherwise 1. */ int blowfish_set_key(struct blowfish_ctx *ctx, size_t length, const uint8_t *key); int blowfish128_set_key(struct blowfish_ctx *ctx, const uint8_t *key); void blowfish_encrypt(const struct blowfish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void blowfish_decrypt(const struct blowfish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* dst parameter must point to a buffer of minimally * BLOWFISH_BCRYPT_HASH_SIZE bytes */ int blowfish_bcrypt_hash(uint8_t *dst, size_t lenkey, const uint8_t *key, size_t lenscheme, const uint8_t *scheme, int log2rounds, const uint8_t *salt); int blowfish_bcrypt_verify(size_t lenkey, const uint8_t *key, size_t lenhashed, const uint8_t *hashed); #ifdef __cplusplus } #endif #endif /* NETTLE_BLOWFISH_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/buffer.h ================================================ /* buffer.h A bare-bones string stream. Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BUFFER_H_INCLUDED #define NETTLE_BUFFER_H_INCLUDED #include "realloc.h" #ifdef __cplusplus extern "C" { #endif struct nettle_buffer { uint8_t *contents; /* Allocated size */ size_t alloc; void *realloc_ctx; nettle_realloc_func *realloc; /* Current size */ size_t size; }; /* Initializes a buffer that uses plain realloc */ void nettle_buffer_init(struct nettle_buffer *buffer); void nettle_buffer_init_realloc(struct nettle_buffer *buffer, void *realloc_ctx, nettle_realloc_func *realloc); /* Initializes a buffer of fix size */ void nettle_buffer_init_size(struct nettle_buffer *buffer, size_t length, uint8_t *space); void nettle_buffer_clear(struct nettle_buffer *buffer); /* Resets the buffer, without freeing the buffer space. */ void nettle_buffer_reset(struct nettle_buffer *buffer); int nettle_buffer_grow(struct nettle_buffer *buffer, size_t length); #define NETTLE_BUFFER_PUTC(buffer, c) \ ( (((buffer)->size < (buffer)->alloc) || nettle_buffer_grow((buffer), 1)) \ && ((buffer)->contents[(buffer)->size++] = (c), 1) ) int nettle_buffer_write(struct nettle_buffer *buffer, size_t length, const uint8_t *data); /* Like nettle_buffer_write, but instead of copying data to the * buffer, it returns a pointer to the area where the caller can copy * the data. The pointer is valid only until the next call that can * reallocate the buffer. */ uint8_t * nettle_buffer_space(struct nettle_buffer *buffer, size_t length); /* Copy the contents of SRC to the end of DST. */ int nettle_buffer_copy(struct nettle_buffer *dst, const struct nettle_buffer *src); #ifdef __cplusplus } #endif #endif /* NETTLE_BUFFER_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/camellia.h ================================================ /* camellia.h Copyright (C) 2006,2007 NTT (Nippon Telegraph and Telephone Corporation). Copyright (C) 2010, 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CAMELLIA_H_INCLUDED #define NETTLE_CAMELLIA_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define camellia128_set_encrypt_key nettle_camellia128_set_encrypt_key #define camellia128_set_decrypt_key nettle_camellia_set_decrypt_key #define camellia128_invert_key nettle_camellia128_invert_key #define camellia128_crypt nettle_camellia128_crypt #define camellia192_set_encrypt_key nettle_camellia192_set_encrypt_key #define camellia192_set_decrypt_key nettle_camellia192_set_decrypt_key #define camellia256_set_encrypt_key nettle_camellia256_set_encrypt_key #define camellia256_set_decrypt_key nettle_camellia256_set_decrypt_key #define camellia256_invert_key nettle_camellia256_invert_key #define camellia256_crypt nettle_camellia256_crypt #define CAMELLIA_BLOCK_SIZE 16 /* Valid key sizes are 128, 192 or 256 bits (16, 24 or 32 bytes) */ #define CAMELLIA128_KEY_SIZE 16 #define CAMELLIA192_KEY_SIZE 24 #define CAMELLIA256_KEY_SIZE 32 /* For 128-bit keys, there are 18 regular rounds, pre- and post-whitening, and two FL and FLINV rounds, using a total of 26 subkeys, each of 64 bit. For 192- and 256-bit keys, there are 6 additional regular rounds and one additional FL and FLINV, using a total of 34 subkeys. */ /* The clever combination of subkeys imply one of the pre- and post-whitening keys is folded with the round keys, so that subkey #1 and the last one (#25 or #33) is not used. The result is that we have only 24 or 32 subkeys at the end of key setup. */ #define _CAMELLIA128_NKEYS 24 #define _CAMELLIA256_NKEYS 32 struct camellia128_ctx { uint64_t keys[_CAMELLIA128_NKEYS]; }; void camellia128_set_encrypt_key(struct camellia128_ctx *ctx, const uint8_t *key); void camellia128_set_decrypt_key(struct camellia128_ctx *ctx, const uint8_t *key); void camellia128_invert_key(struct camellia128_ctx *dst, const struct camellia128_ctx *src); void camellia128_crypt(const struct camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); struct camellia256_ctx { uint64_t keys[_CAMELLIA256_NKEYS]; }; void camellia256_set_encrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); void camellia256_set_decrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); void camellia256_invert_key(struct camellia256_ctx *dst, const struct camellia256_ctx *src); void camellia256_crypt(const struct camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* camellia192 is the same as camellia256, except for the key schedule. */ /* Slightly ugly with a #define on a struct tag, since it might cause surprises if also used as a name of a variable. */ #define camellia192_ctx camellia256_ctx void camellia192_set_encrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); void camellia192_set_decrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); #define camellia192_invert_key camellia256_invert_key #define camellia192_crypt camellia256_crypt #ifdef __cplusplus } #endif #endif /* NETTLE_CAMELLIA_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/cast128.h ================================================ /* cast128.h The CAST-128 block cipher. Copyright (C) 2001, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CAST128_H_INCLUDED #define NETTLE_CAST128_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cast5_set_key nettle_cast5_set_key #define cast128_set_key nettle_cast128_set_key #define cast128_encrypt nettle_cast128_encrypt #define cast128_decrypt nettle_cast128_decrypt #define CAST128_BLOCK_SIZE 8 /* Variable key size between 40 and 128. */ #define CAST5_MIN_KEY_SIZE 5 #define CAST5_MAX_KEY_SIZE 16 #define CAST128_KEY_SIZE 16 struct cast128_ctx { unsigned rounds; /* Number of rounds to use, 12 or 16 */ /* Expanded key, rotations (5 bits only) and 32-bit masks. */ unsigned char Kr[16]; uint32_t Km[16]; }; /* Using variable key size. */ void cast5_set_key(struct cast128_ctx *ctx, size_t length, const uint8_t *key); void cast128_set_key(struct cast128_ctx *ctx, const uint8_t *key); void cast128_encrypt(const struct cast128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void cast128_decrypt(const struct cast128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CAST128_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/cbc.h ================================================ /* cbc.h Cipher block chaining mode. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CBC_H_INCLUDED #define NETTLE_CBC_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cbc_encrypt nettle_cbc_encrypt #define cbc_decrypt nettle_cbc_decrypt #define cbc_aes128_encrypt nettle_cbc_aes128_encrypt #define cbc_aes192_encrypt nettle_cbc_aes192_encrypt #define cbc_aes256_encrypt nettle_cbc_aes256_encrypt void cbc_encrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cbc_decrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); #define CBC_CTX(type, size) \ { type ctx; uint8_t iv[size]; } #define CBC_SET_IV(ctx, data) \ memcpy((ctx)->iv, (data), sizeof((ctx)->iv)) /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CBC_ENCRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cbc_encrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CBC_DECRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cbc_decrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) void cbc_aes128_encrypt(const struct aes128_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cbc_aes192_encrypt(const struct aes192_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cbc_aes256_encrypt(const struct aes256_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CBC_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/ccm.h ================================================ /* ccm.h Counter with CBC-MAC mode, specified by NIST, http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf Copyright (C) 2014 Exegin Technologies Limited Copyright (C) 2014 Owen Kirby Contributed to GNU Nettle by Owen Kirby This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* NIST SP800-38C doesn't specify the particular formatting and * counter generation algorithm for CCM, but it does include an * example algorithm. This example has become the de-factor standard, * and has been adopted by both the IETF and IEEE across a wide * variety of protocols. */ #ifndef NETTLE_CCM_H_INCLUDED #define NETTLE_CCM_H_INCLUDED #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ccm_set_nonce nettle_ccm_set_nonce #define ccm_update nettle_ccm_update #define ccm_encrypt nettle_ccm_encrypt #define ccm_decrypt nettle_ccm_decrypt #define ccm_digest nettle_ccm_digest #define ccm_encrypt_message nettle_ccm_encrypt_message #define ccm_decrypt_message nettle_ccm_decrypt_message #define ccm_aes128_set_key nettle_ccm_aes128_set_key #define ccm_aes128_set_nonce nettle_ccm_aes128_set_nonce #define ccm_aes128_update nettle_ccm_aes128_update #define ccm_aes128_encrypt nettle_ccm_aes128_encrypt #define ccm_aes128_decrypt nettle_ccm_aes128_decrypt #define ccm_aes128_digest nettle_ccm_aes128_digest #define ccm_aes128_encrypt_message nettle_ccm_aes128_encrypt_message #define ccm_aes128_decrypt_message nettle_ccm_aes128_decrypt_message #define ccm_aes192_set_key nettle_ccm_aes192_set_key #define ccm_aes192_set_nonce nettle_ccm_aes192_set_nonce #define ccm_aes192_update nettle_ccm_aes192_update #define ccm_aes192_encrypt nettle_ccm_aes192_encrypt #define ccm_aes192_decrypt nettle_ccm_aes192_decrypt #define ccm_aes192_digest nettle_ccm_aes192_digest #define ccm_aes192_encrypt_message nettle_ccm_aes192_encrypt_message #define ccm_aes192_decrypt_message nettle_ccm_aes192_decrypt_message #define ccm_aes256_set_key nettle_ccm_aes256_set_key #define ccm_aes256_set_nonce nettle_ccm_aes256_set_nonce #define ccm_aes256_update nettle_ccm_aes256_update #define ccm_aes256_encrypt nettle_ccm_aes256_encrypt #define ccm_aes256_decrypt nettle_ccm_aes256_decrypt #define ccm_aes256_digest nettle_ccm_aes256_digest #define ccm_aes256_encrypt_message nettle_ccm_aes256_encrypt_message #define ccm_aes256_decrypt_message nettle_ccm_aes256_decrypt_message /* For CCM, the block size of the block cipher shall be 128 bits. */ #define CCM_BLOCK_SIZE 16 #define CCM_DIGEST_SIZE 16 #define CCM_MIN_NONCE_SIZE 7 #define CCM_MAX_NONCE_SIZE 14 /* Maximum cleartext message size, as a function of the nonce size N. The length field is L octets, with L = 15 - N, and then the maximum size M = 2^{8L} - 1. */ #define CCM_MAX_MSG_SIZE(N) \ ((sizeof(size_t) + (N) <= 15) \ ? ~(size_t) 0 \ : ((size_t) 1 << (8*(15 - N))) - 1) /* Per-message state */ struct ccm_ctx { union nettle_block16 ctr; /* Counter for CTR encryption. */ union nettle_block16 tag; /* CBC-MAC message tag. */ /* Length of data processed by the CBC-MAC modulus the block size */ unsigned int blength; }; /* * CCM mode requires the adata and message lengths when building the IV, which * prevents streaming processing and it incompatible with the AEAD API. */ void ccm_set_nonce(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t noncelen, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_update(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, const uint8_t *data); void ccm_encrypt(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void ccm_decrypt(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void ccm_digest(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); /* * All-in-one encryption and decryption API: * tlength = sizeof(digest) * mlength = sizeof(cleartext) * clength = sizeof(ciphertext) = mlength + tlength * * The ciphertext will contain the encrypted payload with the message digest * appended to the end. */ void ccm_encrypt_message(const void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); /* * The decryption function will write the plaintext to dst and parse the digest * from the final tlength bytes of the ciphertext. If the digest matched the * value computed during decryption then this will return 1, or it will return * 0 if the digest was invalid. */ int ccm_decrypt_message(const void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); /* CCM Mode with AES-128 */ struct ccm_aes128_ctx { struct ccm_ctx ccm; struct aes128_ctx cipher; }; void ccm_aes128_set_key(struct ccm_aes128_ctx *ctx, const uint8_t *key); void ccm_aes128_set_nonce(struct ccm_aes128_ctx *ctx, size_t length, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_aes128_update (struct ccm_aes128_ctx *ctx, size_t length, const uint8_t *data); void ccm_aes128_encrypt(struct ccm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes128_decrypt(struct ccm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes128_digest(struct ccm_aes128_ctx *ctx, size_t length, uint8_t *digest); /* FIXME: For next API/ABI break: first argument should be const struct aes128_ctx *, and similarly for other ccm_*_message functions below. */ void ccm_aes128_encrypt_message(struct ccm_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ccm_aes128_decrypt_message(struct ccm_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); struct ccm_aes192_ctx { struct ccm_ctx ccm; struct aes192_ctx cipher; }; /* CCM Mode with AES-192 */ void ccm_aes192_set_key(struct ccm_aes192_ctx *ctx, const uint8_t *key); void ccm_aes192_set_nonce(struct ccm_aes192_ctx *ctx, size_t length, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_aes192_update(struct ccm_aes192_ctx *ctx, size_t length, const uint8_t *data); void ccm_aes192_encrypt(struct ccm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes192_decrypt(struct ccm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes192_digest(struct ccm_aes192_ctx *ctx, size_t length, uint8_t *digest); void ccm_aes192_encrypt_message(struct ccm_aes192_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ccm_aes192_decrypt_message(struct ccm_aes192_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); /* CCM Mode with AES-256 */ struct ccm_aes256_ctx { struct ccm_ctx ccm; struct aes256_ctx cipher; }; void ccm_aes256_set_key(struct ccm_aes256_ctx *ctx, const uint8_t *key); void ccm_aes256_set_nonce(struct ccm_aes256_ctx *ctx, size_t length, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_aes256_update(struct ccm_aes256_ctx *ctx, size_t length, const uint8_t *data); void ccm_aes256_encrypt(struct ccm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes256_decrypt(struct ccm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes256_digest(struct ccm_aes256_ctx *ctx, size_t length, uint8_t *digest); void ccm_aes256_encrypt_message(struct ccm_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ccm_aes256_decrypt_message(struct ccm_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CCM_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/cfb.h ================================================ /* cfb.h Cipher feedback mode. Copyright (C) 2015, 2017 Dmitry Eremin-Solenikov Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CFB_H_INCLUDED #define NETTLE_CFB_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cfb_encrypt nettle_cfb_encrypt #define cfb_decrypt nettle_cfb_decrypt #define cfb8_encrypt nettle_cfb8_encrypt #define cfb8_decrypt nettle_cfb8_decrypt void cfb_encrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cfb_decrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cfb8_encrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cfb8_decrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); #define CFB_CTX(type, size) \ { type ctx; uint8_t iv[size]; } #define CFB_SET_IV(ctx, data) \ memcpy((ctx)->iv, (data), sizeof((ctx)->iv)) #define CFB8_CTX CFB_CTX #define CFB8_SET_IV CFB_SET_IV /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CFB_ENCRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb_encrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CFB_DECRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb_decrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CFB8_ENCRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb8_encrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CFB8_DECRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb8_decrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #ifdef __cplusplus } #endif #endif /* NETTLE_CFB_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/chacha-poly1305.h ================================================ /* chacha-poly1305.h AEAD mechanism based on chacha and poly1305. See draft-agl-tls-chacha20poly1305-04. Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CHACHA_POLY1305_H_INCLUDED #define NETTLE_CHACHA_POLY1305_H_INCLUDED #include "chacha.h" #include "poly1305.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define chacha_poly1305_set_key nettle_chacha_poly1305_set_key #define chacha_poly1305_set_nonce nettle_chacha_poly1305_set_nonce #define chacha_poly1305_update nettle_chacha_poly1305_update #define chacha_poly1305_decrypt nettle_chacha_poly1305_decrypt #define chacha_poly1305_encrypt nettle_chacha_poly1305_encrypt #define chacha_poly1305_digest nettle_chacha_poly1305_digest #define CHACHA_POLY1305_BLOCK_SIZE 64 /* FIXME: Any need for 128-bit variant? */ #define CHACHA_POLY1305_KEY_SIZE 32 #define CHACHA_POLY1305_NONCE_SIZE CHACHA_NONCE96_SIZE #define CHACHA_POLY1305_DIGEST_SIZE 16 struct chacha_poly1305_ctx { struct chacha_ctx chacha; struct poly1305_ctx poly1305; union nettle_block16 s; uint64_t auth_size; uint64_t data_size; /* poly1305 block */ uint8_t block[POLY1305_BLOCK_SIZE]; unsigned index; }; void chacha_poly1305_set_key (struct chacha_poly1305_ctx *ctx, const uint8_t *key); void chacha_poly1305_set_nonce (struct chacha_poly1305_ctx *ctx, const uint8_t *nonce); void chacha_poly1305_update (struct chacha_poly1305_ctx *ctx, size_t length, const uint8_t *data); void chacha_poly1305_encrypt (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void chacha_poly1305_decrypt (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void chacha_poly1305_digest (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_CHACHA_POLY1305_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/chacha.h ================================================ /* chacha.h The ChaCha stream cipher. Copyright (C) 2013 Joachim Strömbergson Copyright (C) 2012 Simon Josefsson Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CHACHA_H_INCLUDED #define NETTLE_CHACHA_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define chacha_set_key nettle_chacha_set_key #define chacha_set_nonce nettle_chacha_set_nonce #define chacha_set_nonce96 nettle_chacha_set_nonce96 #define chacha_set_counter nettle_chacha_set_counter #define chacha_set_counter32 nettle_chacha_set_counter32 #define chacha_crypt nettle_chacha_crypt #define chacha_crypt32 nettle_chacha_crypt32 /* Currently, only 256-bit keys are supported. */ #define CHACHA_KEY_SIZE 32 #define CHACHA_BLOCK_SIZE 64 #define CHACHA_NONCE_SIZE 8 #define CHACHA_NONCE96_SIZE 12 #define CHACHA_COUNTER_SIZE 8 #define CHACHA_COUNTER32_SIZE 4 #define _CHACHA_STATE_LENGTH 16 struct chacha_ctx { /* Indices 0-3 holds a constant (SIGMA or TAU). Indices 4-11 holds the key. Indices 12-13 holds the block counter. Indices 14-15 holds the IV: This creates the state matrix: C C C C K K K K K K K K B B I I */ uint32_t state[_CHACHA_STATE_LENGTH]; }; void chacha_set_key(struct chacha_ctx *ctx, const uint8_t *key); void chacha_set_nonce(struct chacha_ctx *ctx, const uint8_t *nonce); void chacha_set_nonce96(struct chacha_ctx *ctx, const uint8_t *nonce); void chacha_set_counter(struct chacha_ctx *ctx, const uint8_t *counter); void chacha_set_counter32(struct chacha_ctx *ctx, const uint8_t *counter); void chacha_crypt(struct chacha_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void chacha_crypt32(struct chacha_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CHACHA_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/cmac.h ================================================ /* cmac.h CMAC mode, as specified in RFC4493 Copyright (C) 2017 Red Hat, Inc. Contributed by Nikos Mavrogiannopoulos This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CMAC_H_INCLUDED #define NETTLE_CMAC_H_INCLUDED #include "aes.h" #include "des.h" #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif #define CMAC128_DIGEST_SIZE 16 #define CMAC64_DIGEST_SIZE 8 #define cmac128_set_key nettle_cmac128_set_key #define cmac128_init nettle_cmac128_init #define cmac128_update nettle_cmac128_update #define cmac128_digest nettle_cmac128_digest #define cmac_aes128_set_key nettle_cmac_aes128_set_key #define cmac_aes128_update nettle_cmac_aes128_update #define cmac_aes128_digest nettle_cmac_aes128_digest #define cmac_aes256_set_key nettle_cmac_aes256_set_key #define cmac_aes256_update nettle_cmac_aes256_update #define cmac_aes256_digest nettle_cmac_aes256_digest #define cmac64_set_key nettle_cmac64_set_key #define cmac64_init nettle_cmac64_init #define cmac64_update nettle_cmac64_update #define cmac64_digest nettle_cmac64_digest #define cmac_des3_set_key nettle_cmac_des3_set_key #define cmac_des3_update nettle_cmac_des3_update #define cmac_des3_digest nettle_cmac_des3_digest struct cmac128_key { union nettle_block16 K1; union nettle_block16 K2; }; struct cmac128_ctx { /* MAC state */ union nettle_block16 X; /* Block buffer */ union nettle_block16 block; size_t index; }; struct cmac64_key { union nettle_block8 K1; union nettle_block8 K2; }; struct cmac64_ctx { /* MAC state */ union nettle_block8 X; /* Block buffer */ union nettle_block8 block; size_t index; }; void cmac128_set_key(struct cmac128_key *key, const void *cipher, nettle_cipher_func *encrypt); void cmac128_init(struct cmac128_ctx *ctx); void cmac128_update(struct cmac128_ctx *ctx, const void *cipher, nettle_cipher_func *encrypt, size_t msg_len, const uint8_t *msg); void cmac128_digest(struct cmac128_ctx *ctx, const struct cmac128_key *key, const void *cipher, nettle_cipher_func *encrypt, unsigned length, uint8_t *digest); #define CMAC128_CTX(type) \ { struct cmac128_key key; struct cmac128_ctx ctx; type cipher; } /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CMAC128_SET_KEY(self, set_key, encrypt, cmac_key) \ do { \ (set_key)(&(self)->cipher, (cmac_key)); \ if (0) (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ cmac128_set_key(&(self)->key, &(self)->cipher, \ (nettle_cipher_func *) (encrypt)); \ cmac128_init(&(self)->ctx); \ } while (0) #define CMAC128_UPDATE(self, encrypt, length, src) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac128_update(&(self)->ctx, &(self)->cipher, \ (nettle_cipher_func *)encrypt, \ (length), (src))) #define CMAC128_DIGEST(self, encrypt, length, digest) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac128_digest(&(self)->ctx, &(self)->key, \ &(self)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (digest))) void cmac64_set_key(struct cmac64_key *key, const void *cipher, nettle_cipher_func *encrypt); void cmac64_init(struct cmac64_ctx *ctx); void cmac64_update(struct cmac64_ctx *ctx, const void *cipher, nettle_cipher_func *encrypt, size_t msg_len, const uint8_t *msg); void cmac64_digest(struct cmac64_ctx *ctx, const struct cmac64_key *key, const void *cipher, nettle_cipher_func *encrypt, unsigned length, uint8_t *digest); #define CMAC64_CTX(type) \ { struct cmac64_key key; struct cmac64_ctx ctx; type cipher; } /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CMAC64_SET_KEY(self, set_key, encrypt, cmac_key) \ do { \ (set_key)(&(self)->cipher, (cmac_key)); \ if (0) (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ cmac64_set_key(&(self)->key, &(self)->cipher, \ (nettle_cipher_func *) (encrypt)); \ cmac64_init(&(self)->ctx); \ } while (0) #define CMAC64_UPDATE(self, encrypt, length, src) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac64_update(&(self)->ctx, &(self)->cipher, \ (nettle_cipher_func *)encrypt, \ (length), (src))) #define CMAC64_DIGEST(self, encrypt, length, digest) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac64_digest(&(self)->ctx, &(self)->key, \ &(self)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (digest))) struct cmac_aes128_ctx CMAC128_CTX(struct aes128_ctx); void cmac_aes128_set_key(struct cmac_aes128_ctx *ctx, const uint8_t *key); void cmac_aes128_update(struct cmac_aes128_ctx *ctx, size_t length, const uint8_t *data); void cmac_aes128_digest(struct cmac_aes128_ctx *ctx, size_t length, uint8_t *digest); struct cmac_aes256_ctx CMAC128_CTX(struct aes256_ctx); void cmac_aes256_set_key(struct cmac_aes256_ctx *ctx, const uint8_t *key); void cmac_aes256_update(struct cmac_aes256_ctx *ctx, size_t length, const uint8_t *data); void cmac_aes256_digest(struct cmac_aes256_ctx *ctx, size_t length, uint8_t *digest); struct cmac_des3_ctx CMAC64_CTX(struct des3_ctx); void cmac_des3_set_key(struct cmac_des3_ctx *ctx, const uint8_t *key); void cmac_des3_update(struct cmac_des3_ctx *ctx, size_t length, const uint8_t *data); void cmac_des3_digest(struct cmac_des3_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* CMAC_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/ctr.h ================================================ /* ctr.h Counter mode, using an network byte order incremented counter, matching the testcases of NIST 800-38A. Copyright (C) 2005 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CTR_H_INCLUDED #define NETTLE_CTR_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ctr_crypt nettle_ctr_crypt void ctr_crypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *ctr, size_t length, uint8_t *dst, const uint8_t *src); #define CTR_CTX(type, size) \ { type ctx; uint8_t ctr[size]; } #define CTR_SET_COUNTER(ctx, data) \ memcpy((ctx)->ctr, (data), sizeof((ctx)->ctr)) #define CTR_CRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : ctr_crypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->ctr), (self)->ctr, \ (length), (dst), (src))) #ifdef __cplusplus } #endif #endif /* NETTLE_CTR_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/curve25519.h ================================================ /* curve25519.h Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CURVE25519_H #define NETTLE_CURVE25519_H #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define curve25519_mul_g nettle_curve25519_mul_g #define curve25519_mul nettle_curve25519_mul #define CURVE25519_SIZE 32 /* Indicates that curve25519_mul conforms to RFC 7748. */ #define NETTLE_CURVE25519_RFC7748 1 void curve25519_mul_g (uint8_t *q, const uint8_t *n); void curve25519_mul (uint8_t *q, const uint8_t *n, const uint8_t *p); #ifdef __cplusplus } #endif #endif /* NETTLE_CURVE25519_H */ ================================================ FILE: thirdparty/32/include/nettle/curve448.h ================================================ /* curve448.h Copyright (C) 2017 Daiki Ueno Copyright (C) 2017 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CURVE448_H #define NETTLE_CURVE448_H #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define curve448_mul_g nettle_curve448_mul_g #define curve448_mul nettle_curve448_mul #define CURVE448_SIZE 56 void curve448_mul_g (uint8_t *q, const uint8_t *n); void curve448_mul (uint8_t *q, const uint8_t *n, const uint8_t *p); #ifdef __cplusplus } #endif #endif /* NETTLE_CURVE448_H */ ================================================ FILE: thirdparty/32/include/nettle/des.h ================================================ /* des.h The des block cipher. And triple des. Copyright (C) 1992 Dana L. How Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* * des - fast & portable DES encryption & decryption. * Copyright (C) 1992 Dana L. How * Please see the file `../lib/descore.README' for the complete copyright * notice. * * Slightly edited by Niels Möller, 1997 */ #ifndef NETTLE_DES_H_INCLUDED #define NETTLE_DES_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define des_set_key nettle_des_set_key #define des_encrypt nettle_des_encrypt #define des_decrypt nettle_des_decrypt #define des_check_parity nettle_des_check_parity #define des_fix_parity nettle_des_fix_parity #define des3_set_key nettle_des3_set_key #define des3_encrypt nettle_des3_encrypt #define des3_decrypt nettle_des3_decrypt #define DES_KEY_SIZE 8 #define DES_BLOCK_SIZE 8 /* Expanded key length */ #define _DES_KEY_LENGTH 32 struct des_ctx { uint32_t key[_DES_KEY_LENGTH]; }; /* Returns 1 for good keys and 0 for weak keys. */ int des_set_key(struct des_ctx *ctx, const uint8_t *key); void des_encrypt(const struct des_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void des_decrypt(const struct des_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); int des_check_parity(size_t length, const uint8_t *key); void des_fix_parity(size_t length, uint8_t *dst, const uint8_t *src); #define DES3_KEY_SIZE 24 #define DES3_BLOCK_SIZE DES_BLOCK_SIZE struct des3_ctx { struct des_ctx des[3]; }; /* Returns 1 for good keys and 0 for weak keys. */ int des3_set_key(struct des3_ctx *ctx, const uint8_t *key); void des3_encrypt(const struct des3_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void des3_decrypt(const struct des3_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_DES_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/dsa-compat.h ================================================ /* dsa-compat.h Old DSA publickey interface. Copyright (C) 2002, 2013, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_DSA_COMPAT_H_INCLUDED #define NETTLE_DSA_COMPAT_H_INCLUDED #include "dsa.h" #include "sha1.h" #include "sha2.h" /* Name mangling */ #define dsa_public_key_init nettle_dsa_public_key_init #define dsa_public_key_clear nettle_dsa_public_key_clear #define dsa_private_key_init nettle_dsa_private_key_init #define dsa_private_key_clear nettle_dsa_private_key_clear #define dsa_sha1_sign nettle_dsa_sha1_sign #define dsa_sha1_verify nettle_dsa_sha1_verify #define dsa_sha256_sign nettle_dsa_sha256_sign #define dsa_sha256_verify nettle_dsa_sha256_verify #define dsa_sha1_sign_digest nettle_dsa_sha1_sign_digest #define dsa_sha1_verify_digest nettle_dsa_sha1_verify_digest #define dsa_sha256_sign_digest nettle_dsa_sha256_sign_digest #define dsa_sha256_verify_digest nettle_dsa_sha256_verify_digest #define dsa_compat_generate_keypair nettle_dsa_compat_generate_keypair /* Switch meaning of dsa_generate_keypair */ #undef dsa_generate_keypair #define dsa_generate_keypair nettle_dsa_compat_generate_keypair #ifdef __cplusplus extern "C" { #endif struct dsa_public_key { /* Same as struct dsa_params, but can't use that struct here without breaking backwards compatibility. Layout must be identical, since this is cast to a struct dsa_param pointer for calling _dsa_sign and _dsa_verify */ mpz_t p; mpz_t q; mpz_t g; /* Public value */ mpz_t y; }; struct dsa_private_key { /* Unlike an rsa public key, private key operations will need both * the private and the public information. */ mpz_t x; }; /* Signing a message works as follows: * * Store the private key in a dsa_private_key struct. * * Initialize a hashing context, by callling * sha1_init * * Hash the message by calling * sha1_update * * Create the signature by calling * dsa_sha1_sign * * The signature is represented as a struct dsa_signature. This call also * resets the hashing context. * * When done with the key and signature, don't forget to call * dsa_signature_clear. */ /* Calls mpz_init to initialize bignum storage. */ void dsa_public_key_init(struct dsa_public_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void dsa_public_key_clear(struct dsa_public_key *key); /* Calls mpz_init to initialize bignum storage. */ void dsa_private_key_init(struct dsa_private_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void dsa_private_key_clear(struct dsa_private_key *key); int dsa_sha1_sign(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha1_ctx *hash, struct dsa_signature *signature); int dsa_sha256_sign(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha256_ctx *hash, struct dsa_signature *signature); int dsa_sha1_verify(const struct dsa_public_key *key, struct sha1_ctx *hash, const struct dsa_signature *signature); int dsa_sha256_verify(const struct dsa_public_key *key, struct sha256_ctx *hash, const struct dsa_signature *signature); int dsa_sha1_sign_digest(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, struct dsa_signature *signature); int dsa_sha256_sign_digest(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, struct dsa_signature *signature); int dsa_sha1_verify_digest(const struct dsa_public_key *key, const uint8_t *digest, const struct dsa_signature *signature); int dsa_sha256_verify_digest(const struct dsa_public_key *key, const uint8_t *digest, const struct dsa_signature *signature); /* Key generation */ int dsa_generate_keypair(struct dsa_public_key *pub, struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress, unsigned p_bits, unsigned q_bits); #ifdef __cplusplus } #endif #endif /* NETTLE_DSA_COMPAT_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/dsa.h ================================================ /* dsa.h The DSA publickey algorithm. Copyright (C) 2002, 2013, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_DSA_H_INCLUDED #define NETTLE_DSA_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define dsa_params_init nettle_dsa_params_init #define dsa_params_clear nettle_dsa_params_clear #define dsa_signature_init nettle_dsa_signature_init #define dsa_signature_clear nettle_dsa_signature_clear #define dsa_sign nettle_dsa_sign #define dsa_verify nettle_dsa_verify #define dsa_generate_params nettle_dsa_generate_params #define dsa_generate_keypair nettle_dsa_generate_keypair #define dsa_signature_from_sexp nettle_dsa_signature_from_sexp #define dsa_keypair_to_sexp nettle_dsa_keypair_to_sexp #define dsa_keypair_from_sexp_alist nettle_dsa_keypair_from_sexp_alist #define dsa_sha1_keypair_from_sexp nettle_dsa_sha1_keypair_from_sexp #define dsa_sha256_keypair_from_sexp nettle_dsa_sha256_keypair_from_sexp #define dsa_params_from_der_iterator nettle_dsa_params_from_der_iterator #define dsa_public_key_from_der_iterator nettle_dsa_public_key_from_der_iterator #define dsa_openssl_private_key_from_der_iterator nettle_dsa_openssl_private_key_from_der_iterator #define dsa_openssl_private_key_from_der nettle_openssl_provate_key_from_der /* For FIPS approved parameters */ #define DSA_SHA1_MIN_P_BITS 512 #define DSA_SHA1_Q_OCTETS 20 #define DSA_SHA1_Q_BITS 160 #define DSA_SHA256_MIN_P_BITS 1024 #define DSA_SHA256_Q_OCTETS 32 #define DSA_SHA256_Q_BITS 256 struct dsa_params { /* Modulo */ mpz_t p; /* Group order */ mpz_t q; /* Generator */ mpz_t g; }; void dsa_params_init (struct dsa_params *params); void dsa_params_clear (struct dsa_params *params); struct dsa_signature { mpz_t r; mpz_t s; }; /* Calls mpz_init to initialize bignum storage. */ void dsa_signature_init(struct dsa_signature *signature); /* Calls mpz_clear to deallocate bignum storage. */ void dsa_signature_clear(struct dsa_signature *signature); int dsa_sign(const struct dsa_params *params, const mpz_t x, void *random_ctx, nettle_random_func *random, size_t digest_size, const uint8_t *digest, struct dsa_signature *signature); int dsa_verify(const struct dsa_params *params, const mpz_t y, size_t digest_size, const uint8_t *digest, const struct dsa_signature *signature); /* Key generation */ int dsa_generate_params(struct dsa_params *params, void *random_ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress, unsigned p_bits, unsigned q_bits); void dsa_generate_keypair (const struct dsa_params *params, mpz_t pub, mpz_t key, void *random_ctx, nettle_random_func *random); /* Keys in sexp form. */ struct nettle_buffer; /* Generates a public-key expression if PRIV is NULL .*/ int dsa_keypair_to_sexp(struct nettle_buffer *buffer, const char *algorithm_name, /* NULL means "dsa" */ const struct dsa_params *params, const mpz_t pub, const mpz_t priv); struct sexp_iterator; int dsa_signature_from_sexp(struct dsa_signature *rs, struct sexp_iterator *i, unsigned q_bits); int dsa_keypair_from_sexp_alist(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, unsigned q_bits, struct sexp_iterator *i); /* If PRIV is NULL, expect a public-key expression. If PUB is NULL, * expect a private key expression and ignore the parts not needed for * the public key. */ /* Keys must be initialized before calling this function, as usual. */ int dsa_sha1_keypair_from_sexp(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, size_t length, const uint8_t *expr); int dsa_sha256_keypair_from_sexp(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, size_t length, const uint8_t *expr); /* Keys in X.509 andd OpenSSL format. */ struct asn1_der_iterator; int dsa_params_from_der_iterator(struct dsa_params *params, unsigned max_bits, unsigned q_bits, struct asn1_der_iterator *i); int dsa_public_key_from_der_iterator(const struct dsa_params *params, mpz_t pub, struct asn1_der_iterator *i); int dsa_openssl_private_key_from_der_iterator(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, struct asn1_der_iterator *i); int dsa_openssl_private_key_from_der(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, size_t length, const uint8_t *data); #ifdef __cplusplus } #endif #endif /* NETTLE_DSA_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/eax.h ================================================ /* eax.h EAX mode, see http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_EAX_H_INCLUDED #define NETTLE_EAX_H_INCLUDED #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define eax_set_key nettle_eax_set_key #define eax_set_nonce nettle_eax_set_nonce #define eax_update nettle_eax_update #define eax_encrypt nettle_eax_encrypt #define eax_decrypt nettle_eax_decrypt #define eax_digest nettle_eax_digest #define eax_aes128_set_key nettle_eax_aes128_set_key #define eax_aes128_set_nonce nettle_eax_aes128_set_nonce #define eax_aes128_update nettle_eax_aes128_update #define eax_aes128_encrypt nettle_eax_aes128_encrypt #define eax_aes128_decrypt nettle_eax_aes128_decrypt #define eax_aes128_digest nettle_eax_aes128_digest /* Restricted to block ciphers with 128 bit block size. FIXME: Reflect this in naming? */ #define EAX_BLOCK_SIZE 16 #define EAX_DIGEST_SIZE 16 /* FIXME: Reasonable default? */ #define EAX_IV_SIZE 16 /* Values independent of message and nonce */ struct eax_key { union nettle_block16 pad_block; union nettle_block16 pad_partial; }; struct eax_ctx { union nettle_block16 omac_nonce; union nettle_block16 omac_data; union nettle_block16 omac_message; union nettle_block16 ctr; }; void eax_set_key (struct eax_key *key, const void *cipher, nettle_cipher_func *f); void eax_set_nonce (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t nonce_length, const uint8_t *nonce); void eax_update (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t data_length, const uint8_t *data); void eax_encrypt (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void eax_decrypt (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void eax_digest (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); /* Put the cipher last, to get cipher-independent offsets for the EAX * state. */ #define EAX_CTX(type) \ { struct eax_key key; struct eax_ctx eax; type cipher; } #define EAX_SET_KEY(ctx, set_key, encrypt, data) \ do { \ (set_key)(&(ctx)->cipher, (data)); \ if (0) (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ eax_set_key (&(ctx)->key, &(ctx)->cipher, (nettle_cipher_func *) encrypt); \ } while (0) #define EAX_SET_NONCE(ctx, encrypt, length, nonce) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_set_nonce (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (nonce))) #define EAX_UPDATE(ctx, encrypt, length, data) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_update (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (data))) #define EAX_ENCRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_encrypt (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define EAX_DECRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_decrypt (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define EAX_DIGEST(ctx, encrypt, length, digest) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_digest (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (digest))) struct eax_aes128_ctx EAX_CTX(struct aes128_ctx); void eax_aes128_set_key(struct eax_aes128_ctx *ctx, const uint8_t *key); void eax_aes128_set_nonce(struct eax_aes128_ctx *ctx, size_t length, const uint8_t *iv); void eax_aes128_update(struct eax_aes128_ctx *ctx, size_t length, const uint8_t *data); void eax_aes128_encrypt(struct eax_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void eax_aes128_decrypt(struct eax_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void eax_aes128_digest(struct eax_aes128_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_EAX_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/ecc-curve.h ================================================ /* ecc-curve.h Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ #ifndef NETTLE_ECC_CURVE_H_INCLUDED #define NETTLE_ECC_CURVE_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* The contents of this struct is internal. */ struct ecc_curve; const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_gost_gc256b(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_gost_gc512a(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_192r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_224r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_256r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_384r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_521r1(void); #ifdef __cplusplus } #endif #endif /* NETTLE_ECC_CURVE_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/ecc.h ================================================ /* ecc.h Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ #ifndef NETTLE_ECC_H_INCLUDED #define NETTLE_ECC_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ecc_point_init nettle_ecc_point_init #define ecc_point_clear nettle_ecc_point_clear #define ecc_point_set nettle_ecc_point_set #define ecc_point_get nettle_ecc_point_get #define ecc_point_mul nettle_ecc_point_mul #define ecc_point_mul_g nettle_ecc_point_mul_g #define ecc_scalar_init nettle_ecc_scalar_init #define ecc_scalar_clear nettle_ecc_scalar_clear #define ecc_scalar_set nettle_ecc_scalar_set #define ecc_scalar_get nettle_ecc_scalar_get #define ecc_scalar_random nettle_ecc_scalar_random #define ecc_point_mul nettle_ecc_point_mul #define ecc_bit_size nettle_ecc_bit_size #define ecc_size nettle_ecc_size #define ecc_size_a nettle_ecc_size_a #define ecc_size_j nettle_ecc_size_j struct ecc_curve; /* High level interface, for ECDSA, DH, etc */ /* Represents a point on the ECC curve */ struct ecc_point { const struct ecc_curve *ecc; /* Allocated using the same allocation function as GMP. */ mp_limb_t *p; }; /* Represents a non-zero scalar, an element of Z_q^*, where q is the group order of the curve. */ struct ecc_scalar { const struct ecc_curve *ecc; /* Allocated using the same allocation function as GMP. */ mp_limb_t *p; }; void ecc_point_init (struct ecc_point *p, const struct ecc_curve *ecc); void ecc_point_clear (struct ecc_point *p); /* Fails and returns zero if the point is not on the curve. */ int ecc_point_set (struct ecc_point *p, const mpz_t x, const mpz_t y); void ecc_point_get (const struct ecc_point *p, mpz_t x, mpz_t y); void ecc_scalar_init (struct ecc_scalar *s, const struct ecc_curve *ecc); void ecc_scalar_clear (struct ecc_scalar *s); /* Fails and returns zero if the scalar is not in the proper range. */ int ecc_scalar_set (struct ecc_scalar *s, const mpz_t z); void ecc_scalar_get (const struct ecc_scalar *s, mpz_t z); /* Generates a random scalar, suitable as an ECDSA private key or a ECDH exponent. */ void ecc_scalar_random (struct ecc_scalar *s, void *random_ctx, nettle_random_func *random); /* Computes r = n p */ void ecc_point_mul (struct ecc_point *r, const struct ecc_scalar *n, const struct ecc_point *p); /* Computes r = n g */ void ecc_point_mul_g (struct ecc_point *r, const struct ecc_scalar *n); /* Low-level interface */ /* Points on a curve are represented as arrays of mp_limb_t, with curve-specific representation. For the secp curves, we use Jacobian coordinates (possibly in Montgomery form for mod multiplication). For curve25519 we use homogeneous coordinates on an equivalent Edwards curve. The suffix "_h" denotes this internal representation. Since we use additive notation for the groups, the infinity point on the curve is denoted 0. The infinity point can be represented with x = y = 0 in affine coordinates, and Z = 0 in Jacobian coordinates. However, note that most of the ECC functions do *not* support infinity as an input or output. */ /* Returns the bit size of a single coordinate (and of the prime p). */ unsigned ecc_bit_size (const struct ecc_curve *ecc); /* Returns the size of a single coordinate. */ mp_size_t ecc_size (const struct ecc_curve *ecc); /* Size of a point, using affine coordinates x, y. */ mp_size_t ecc_size_a (const struct ecc_curve *ecc); /* Size of a point, using jacobian coordinates X, Y and Z. */ mp_size_t ecc_size_j (const struct ecc_curve *ecc); /* FIXME: Define a generic ecc_dup, ecc_add, for any type of curve. Do they need to handle infinity points? */ #ifdef __cplusplus } #endif #endif /* NETTLE_ECC_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/ecdsa.h ================================================ /* ecdsa.h Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ #ifndef NETTLE_ECDSA_H_INCLUDED #define NETTLE_ECDSA_H_INCLUDED #include "ecc.h" #include "dsa.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ecdsa_sign nettle_ecdsa_sign #define ecdsa_verify nettle_ecdsa_verify #define ecdsa_generate_keypair nettle_ecdsa_generate_keypair #define ecc_ecdsa_sign nettle_ecc_ecdsa_sign #define ecc_ecdsa_sign_itch nettle_ecc_ecdsa_sign_itch #define ecc_ecdsa_verify nettle_ecc_ecdsa_verify #define ecc_ecdsa_verify_itch nettle_ecc_ecdsa_verify_itch /* High level ECDSA functions. * * A public key is represented as a struct ecc_point, and a private * key as a struct ecc_scalar. */ void ecdsa_sign (const struct ecc_scalar *key, void *random_ctx, nettle_random_func *random, size_t digest_length, const uint8_t *digest, struct dsa_signature *signature); int ecdsa_verify (const struct ecc_point *pub, size_t length, const uint8_t *digest, const struct dsa_signature *signature); void ecdsa_generate_keypair (struct ecc_point *pub, struct ecc_scalar *key, void *random_ctx, nettle_random_func *random); /* Low-level ECDSA functions. */ mp_size_t ecc_ecdsa_sign_itch (const struct ecc_curve *ecc); void ecc_ecdsa_sign (const struct ecc_curve *ecc, const mp_limb_t *zp, /* Random nonce, must be invertible mod ecc group order. */ const mp_limb_t *kp, size_t length, const uint8_t *digest, mp_limb_t *rp, mp_limb_t *sp, mp_limb_t *scratch); mp_size_t ecc_ecdsa_verify_itch (const struct ecc_curve *ecc); int ecc_ecdsa_verify (const struct ecc_curve *ecc, const mp_limb_t *pp, /* Public key */ size_t length, const uint8_t *digest, const mp_limb_t *rp, const mp_limb_t *sp, mp_limb_t *scratch); #ifdef __cplusplus } #endif #endif /* NETTLE_ECDSA_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/eddsa.h ================================================ /* eddsa.h Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_EDDSA_H #define NETTLE_EDDSA_H #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ed25519_sha512_set_private_key nettle_ed25519_sha512_set_private_key #define ed25519_sha512_public_key nettle_ed25519_sha512_public_key #define ed25519_sha512_sign nettle_ed25519_sha512_sign #define ed25519_sha512_verify nettle_ed25519_sha512_verify #define ed448_shake256_public_key nettle_ed448_shake256_public_key #define ed448_shake256_sign nettle_ed448_shake256_sign #define ed448_shake256_verify nettle_ed448_shake256_verify #define ED25519_KEY_SIZE 32 #define ED25519_SIGNATURE_SIZE 64 void ed25519_sha512_public_key (uint8_t *pub, const uint8_t *priv); void ed25519_sha512_sign (const uint8_t *pub, const uint8_t *priv, size_t length, const uint8_t *msg, uint8_t *signature); int ed25519_sha512_verify (const uint8_t *pub, size_t length, const uint8_t *msg, const uint8_t *signature); #define ED448_KEY_SIZE 57 #define ED448_SIGNATURE_SIZE 114 void ed448_shake256_public_key (uint8_t *pub, const uint8_t *priv); void ed448_shake256_sign (const uint8_t *pub, const uint8_t *priv, size_t length, const uint8_t *msg, uint8_t *signature); int ed448_shake256_verify (const uint8_t *pub, size_t length, const uint8_t *msg, const uint8_t *signature); #ifdef __cplusplus } #endif #endif /* NETTLE_EDDSA_H */ ================================================ FILE: thirdparty/32/include/nettle/gcm.h ================================================ /* gcm.h Galois counter mode, specified by NIST, http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf Copyright (C) 2011 Katholieke Universiteit Leuven Copyright (C) 2011, 2014 Niels Möller Contributed by Nikos Mavrogiannopoulos This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_GCM_H_INCLUDED #define NETTLE_GCM_H_INCLUDED #include "aes.h" #include "camellia.h" #include "sm4.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define gcm_set_key nettle_gcm_set_key #define gcm_set_iv nettle_gcm_set_iv #define gcm_update nettle_gcm_update #define gcm_encrypt nettle_gcm_encrypt #define gcm_decrypt nettle_gcm_decrypt #define gcm_digest nettle_gcm_digest #define gcm_aes128_set_key nettle_gcm_aes128_set_key #define gcm_aes128_set_iv nettle_gcm_aes128_set_iv #define gcm_aes128_update nettle_gcm_aes128_update #define gcm_aes128_encrypt nettle_gcm_aes128_encrypt #define gcm_aes128_decrypt nettle_gcm_aes128_decrypt #define gcm_aes128_digest nettle_gcm_aes128_digest #define gcm_aes192_set_key nettle_gcm_aes192_set_key #define gcm_aes192_set_iv nettle_gcm_aes192_set_iv #define gcm_aes192_update nettle_gcm_aes192_update #define gcm_aes192_encrypt nettle_gcm_aes192_encrypt #define gcm_aes192_decrypt nettle_gcm_aes192_decrypt #define gcm_aes192_digest nettle_gcm_aes192_digest #define gcm_aes256_set_key nettle_gcm_aes256_set_key #define gcm_aes256_set_iv nettle_gcm_aes256_set_iv #define gcm_aes256_update nettle_gcm_aes256_update #define gcm_aes256_encrypt nettle_gcm_aes256_encrypt #define gcm_aes256_decrypt nettle_gcm_aes256_decrypt #define gcm_aes256_digest nettle_gcm_aes256_digest #define gcm_aes_set_key nettle_gcm_aes_set_key #define gcm_aes_set_iv nettle_gcm_aes_set_iv #define gcm_aes_update nettle_gcm_aes_update #define gcm_aes_encrypt nettle_gcm_aes_encrypt #define gcm_aes_decrypt nettle_gcm_aes_decrypt #define gcm_aes_digest nettle_gcm_aes_digest #define gcm_camellia128_set_key nettle_gcm_camellia128_set_key #define gcm_camellia128_set_iv nettle_gcm_camellia128_set_iv #define gcm_camellia128_update nettle_gcm_camellia128_update #define gcm_camellia128_encrypt nettle_gcm_camellia128_encrypt #define gcm_camellia128_decrypt nettle_gcm_camellia128_decrypt #define gcm_camellia128_digest nettle_gcm_camellia128_digest #define gcm_camellia256_set_key nettle_gcm_camellia256_set_key #define gcm_camellia256_set_iv nettle_gcm_camellia256_set_iv #define gcm_camellia256_update nettle_gcm_camellia256_update #define gcm_camellia256_encrypt nettle_gcm_camellia256_encrypt #define gcm_camellia256_decrypt nettle_gcm_camellia256_decrypt #define gcm_camellia256_digest nettle_gcm_camellia256_digest #define gcm_sm4_set_key nettle_gcm_sm4_set_key #define gcm_sm4_set_iv nettle_gcm_sm4_set_iv #define gcm_sm4_update nettle_gcm_sm4_update #define gcm_sm4_encrypt nettle_gcm_sm4_encrypt #define gcm_sm4_decrypt nettle_gcm_sm4_decrypt #define gcm_sm4_digest nettle_gcm_sm4_digest #define GCM_BLOCK_SIZE 16 #define GCM_IV_SIZE (GCM_BLOCK_SIZE - 4) #define GCM_DIGEST_SIZE 16 #define GCM_TABLE_BITS 8 /* Hashing subkey */ struct gcm_key { union nettle_block16 h[1 << GCM_TABLE_BITS]; }; /* Per-message state, depending on the iv */ struct gcm_ctx { /* Original counter block */ union nettle_block16 iv; /* Updated for each block. */ union nettle_block16 ctr; /* Hashing state */ union nettle_block16 x; uint64_t auth_size; uint64_t data_size; }; void gcm_set_key(struct gcm_key *key, const void *cipher, nettle_cipher_func *f); void gcm_set_iv(struct gcm_ctx *ctx, const struct gcm_key *key, size_t length, const uint8_t *iv); void gcm_update(struct gcm_ctx *ctx, const struct gcm_key *key, size_t length, const uint8_t *data); void gcm_encrypt(struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void gcm_decrypt(struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void gcm_digest(struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); /* Convenience macrology (not sure how useful it is) */ /* All-in-one context, with hash subkey, message state, and cipher. */ #define GCM_CTX(type) \ { struct gcm_key key; struct gcm_ctx gcm; type cipher; } /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define GCM_SET_KEY(ctx, set_key, encrypt, gcm_key) \ do { \ (set_key)(&(ctx)->cipher, (gcm_key)); \ if (0) (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ gcm_set_key(&(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt)); \ } while (0) #define GCM_SET_IV(ctx, length, data) \ gcm_set_iv(&(ctx)->gcm, &(ctx)->key, (length), (data)) #define GCM_UPDATE(ctx, length, data) \ gcm_update(&(ctx)->gcm, &(ctx)->key, (length), (data)) #define GCM_ENCRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : gcm_encrypt(&(ctx)->gcm, &(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define GCM_DECRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : gcm_decrypt(&(ctx)->gcm, &(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define GCM_DIGEST(ctx, encrypt, length, digest) \ (0 ? (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : gcm_digest(&(ctx)->gcm, &(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (digest))) struct gcm_aes128_ctx GCM_CTX(struct aes128_ctx); void gcm_aes128_set_key(struct gcm_aes128_ctx *ctx, const uint8_t *key); /* FIXME: Define _update and _set_iv as some kind of aliaes, there's nothing aes-specific. */ void gcm_aes128_update (struct gcm_aes128_ctx *ctx, size_t length, const uint8_t *data); void gcm_aes128_set_iv (struct gcm_aes128_ctx *ctx, size_t length, const uint8_t *iv); void gcm_aes128_encrypt(struct gcm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes128_decrypt(struct gcm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes128_digest(struct gcm_aes128_ctx *ctx, size_t length, uint8_t *digest); struct gcm_aes192_ctx GCM_CTX(struct aes192_ctx); void gcm_aes192_set_key(struct gcm_aes192_ctx *ctx, const uint8_t *key); void gcm_aes192_update (struct gcm_aes192_ctx *ctx, size_t length, const uint8_t *data); void gcm_aes192_set_iv (struct gcm_aes192_ctx *ctx, size_t length, const uint8_t *iv); void gcm_aes192_encrypt(struct gcm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes192_decrypt(struct gcm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes192_digest(struct gcm_aes192_ctx *ctx, size_t length, uint8_t *digest); struct gcm_aes256_ctx GCM_CTX(struct aes256_ctx); void gcm_aes256_set_key(struct gcm_aes256_ctx *ctx, const uint8_t *key); void gcm_aes256_update (struct gcm_aes256_ctx *ctx, size_t length, const uint8_t *data); void gcm_aes256_set_iv (struct gcm_aes256_ctx *ctx, size_t length, const uint8_t *iv); void gcm_aes256_encrypt(struct gcm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes256_decrypt(struct gcm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes256_digest(struct gcm_aes256_ctx *ctx, size_t length, uint8_t *digest); /* Old deprecated aes interface, for backwards compatibility */ struct gcm_aes_ctx GCM_CTX(struct aes_ctx); void gcm_aes_set_key(struct gcm_aes_ctx *ctx, size_t length, const uint8_t *key) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_set_iv(struct gcm_aes_ctx *ctx, size_t length, const uint8_t *iv) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_update(struct gcm_aes_ctx *ctx, size_t length, const uint8_t *data) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_encrypt(struct gcm_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_decrypt(struct gcm_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_digest(struct gcm_aes_ctx *ctx, size_t length, uint8_t *digest) _NETTLE_ATTRIBUTE_DEPRECATED; struct gcm_camellia128_ctx GCM_CTX(struct camellia128_ctx); void gcm_camellia128_set_key(struct gcm_camellia128_ctx *ctx, const uint8_t *key); void gcm_camellia128_set_iv(struct gcm_camellia128_ctx *ctx, size_t length, const uint8_t *iv); void gcm_camellia128_update(struct gcm_camellia128_ctx *ctx, size_t length, const uint8_t *data); void gcm_camellia128_encrypt(struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia128_decrypt(struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia128_digest(struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *digest); struct gcm_camellia256_ctx GCM_CTX(struct camellia256_ctx); void gcm_camellia256_set_key(struct gcm_camellia256_ctx *ctx, const uint8_t *key); void gcm_camellia256_set_iv(struct gcm_camellia256_ctx *ctx, size_t length, const uint8_t *iv); void gcm_camellia256_update(struct gcm_camellia256_ctx *ctx, size_t length, const uint8_t *data); void gcm_camellia256_encrypt(struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia256_decrypt(struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia256_digest(struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *digest); struct gcm_sm4_ctx GCM_CTX(struct sm4_ctx); void gcm_sm4_set_key(struct gcm_sm4_ctx *ctx, const uint8_t *key); void gcm_sm4_set_iv(struct gcm_sm4_ctx *ctx, size_t length, const uint8_t *iv); void gcm_sm4_update(struct gcm_sm4_ctx *ctx, size_t length, const uint8_t *data); void gcm_sm4_encrypt(struct gcm_sm4_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_sm4_decrypt(struct gcm_sm4_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_sm4_digest(struct gcm_sm4_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_GCM_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/gostdsa.h ================================================ /* gostdsa.h Copyright (C) 2015 Dmity Eremin-Solenikov Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_GOSTDSA_H_INCLUDED #define NETTLE_GOSTDSA_H_INCLUDED #include "ecc.h" #include "dsa.h" #include "ecdsa.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define gostdsa_sign nettle_gostdsa_sign #define gostdsa_verify nettle_gostdsa_verify #define gostdsa_vko nettle_gostdsa_vko #define ecc_gostdsa_sign nettle_ecc_gostdsa_sign #define ecc_gostdsa_sign_itch nettle_ecc_gostdsa_sign_itch #define ecc_gostdsa_verify nettle_ecc_gostdsa_verify #define ecc_gostdsa_verify_itch nettle_ecc_gostdsa_verify_itch /* Just use ECDSA function for key generation */ #define gostdsa_generate_keypair ecdsa_generate_keypair /* High level GOST DSA functions. * * A public key is represented as a struct ecc_point, and a private * key as a struct ecc_scalar. */ void gostdsa_sign (const struct ecc_scalar *key, void *random_ctx, nettle_random_func *random, size_t digest_length, const uint8_t *digest, struct dsa_signature *signature); int gostdsa_verify (const struct ecc_point *pub, size_t length, const uint8_t *digest, const struct dsa_signature *signature); void gostdsa_vko (const struct ecc_scalar *key, const struct ecc_point *pub, size_t ukm_length, const uint8_t *ukm, uint8_t *out); /* Low-level GOSTDSA functions. */ mp_size_t ecc_gostdsa_sign_itch (const struct ecc_curve *ecc); void ecc_gostdsa_sign (const struct ecc_curve *ecc, const mp_limb_t *zp, /* Random nonce, must be invertible mod ecc group order. */ const mp_limb_t *kp, size_t length, const uint8_t *digest, mp_limb_t *rp, mp_limb_t *sp, mp_limb_t *scratch); mp_size_t ecc_gostdsa_verify_itch (const struct ecc_curve *ecc); int ecc_gostdsa_verify (const struct ecc_curve *ecc, const mp_limb_t *pp, /* Public key */ size_t length, const uint8_t *digest, const mp_limb_t *rp, const mp_limb_t *sp, mp_limb_t *scratch); #ifdef __cplusplus } #endif #endif /* NETTLE_GOSTDSA_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/gosthash94.h ================================================ /* gosthash94.h The GOST R 34.11-94 hash function, described in RFC 5831. Copyright (C) 2012 Nikos Mavrogiannopoulos, Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Based on rhash gost.h. */ /* Copyright: 2009-2012 Aleksey Kravchenko * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * Ported to nettle by Nikos Mavrogiannopoulos. */ #ifndef NETTLE_GOSTHASH94_H_INCLUDED #define NETTLE_GOSTHASH94_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif #define gosthash94_init nettle_gosthash94_init #define gosthash94_update nettle_gosthash94_update #define gosthash94_digest nettle_gosthash94_digest #define gosthash94cp_update nettle_gosthash94cp_update #define gosthash94cp_digest nettle_gosthash94cp_digest #define GOSTHASH94_BLOCK_SIZE 32 #define GOSTHASH94_DIGEST_SIZE 32 /* For backwards compatibility */ #define GOSTHASH94_DATA_SIZE GOSTHASH94_BLOCK_SIZE #define GOSTHASH94CP_BLOCK_SIZE GOSTHASH94_BLOCK_SIZE #define GOSTHASH94CP_DIGEST_SIZE GOSTHASH94_DIGEST_SIZE struct gosthash94_ctx { uint32_t hash[8]; /* algorithm 256-bit state */ uint32_t sum[8]; /* sum of processed message blocks */ uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[GOSTHASH94_BLOCK_SIZE]; /* 256-bit buffer for leftovers */ }; #define gosthash94cp_ctx gosthash94_ctx void gosthash94_init(struct gosthash94_ctx *ctx); void gosthash94_update(struct gosthash94_ctx *ctx, size_t length, const uint8_t *msg); void gosthash94_digest(struct gosthash94_ctx *ctx, size_t length, uint8_t *result); #define gosthash94cp_init gosthash94_init void gosthash94cp_update(struct gosthash94_ctx *ctx, size_t length, const uint8_t *msg); void gosthash94cp_digest(struct gosthash94_ctx *ctx, size_t length, uint8_t *result); #ifdef __cplusplus } #endif #endif /* NETTLE_GOSTHASH94_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/hkdf.h ================================================ /* hkdf.h TLS PRF code (RFC-5246, RFC-2246). Copyright (C) 2017 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_HKDF_H_INCLUDED #define NETTLE_HKDF_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define hkdf_extract nettle_hkdf_extract #define hkdf_expand nettle_hkdf_expand void hkdf_extract(void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, size_t secret_size, const uint8_t *secret, uint8_t *dst); void hkdf_expand(void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, size_t info_size, const uint8_t *info, size_t length, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_HKDF_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/hmac.h ================================================ /* hmac.h HMAC message authentication code (RFC-2104). Copyright (C) 2001, 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_HMAC_H_INCLUDED #define NETTLE_HMAC_H_INCLUDED #include "nettle-meta.h" #include "gosthash94.h" #include "md5.h" #include "ripemd160.h" #include "sha1.h" #include "sha2.h" #include "streebog.h" #include "sm3.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define hmac_set_key nettle_hmac_set_key #define hmac_update nettle_hmac_update #define hmac_digest nettle_hmac_digest #define hmac_md5_set_key nettle_hmac_md5_set_key #define hmac_md5_update nettle_hmac_md5_update #define hmac_md5_digest nettle_hmac_md5_digest #define hmac_ripemd160_set_key nettle_hmac_ripemd160_set_key #define hmac_ripemd160_update nettle_hmac_ripemd160_update #define hmac_ripemd160_digest nettle_hmac_ripemd160_digest #define hmac_sha1_set_key nettle_hmac_sha1_set_key #define hmac_sha1_update nettle_hmac_sha1_update #define hmac_sha1_digest nettle_hmac_sha1_digest #define hmac_sha224_set_key nettle_hmac_sha224_set_key #define hmac_sha224_digest nettle_hmac_sha224_digest #define hmac_sha256_set_key nettle_hmac_sha256_set_key #define hmac_sha256_update nettle_hmac_sha256_update #define hmac_sha256_digest nettle_hmac_sha256_digest #define hmac_sha384_set_key nettle_hmac_sha384_set_key #define hmac_sha384_digest nettle_hmac_sha384_digest #define hmac_sha512_set_key nettle_hmac_sha512_set_key #define hmac_sha512_update nettle_hmac_sha512_update #define hmac_sha512_digest nettle_hmac_sha512_digest #define hmac_gosthash94_set_key nettle_hmac_gosthash94_set_key #define hmac_gosthash94_update nettle_hmac_gosthash94_update #define hmac_gosthash94_digest nettle_hmac_gosthash94_digest #define hmac_gosthash94cp_set_key nettle_hmac_gosthash94cp_set_key #define hmac_gosthash94cp_update nettle_hmac_gosthash94cp_update #define hmac_gosthash94cp_digest nettle_hmac_gosthash94cp_digest #define hmac_streebog256_set_key nettle_hmac_streebog256_set_key #define hmac_streebog256_digest nettle_hmac_streebog256_digest #define hmac_streebog512_set_key nettle_hmac_streebog512_set_key #define hmac_streebog512_update nettle_hmac_streebog512_update #define hmac_streebog512_digest nettle_hmac_streebog512_digest #define hmac_sm3_set_key nettle_hmac_sm3_set_key #define hmac_sm3_update nettle_hmac_sm3_update #define hmac_sm3_digest nettle_hmac_sm3_digest void hmac_set_key(void *outer, void *inner, void *state, const struct nettle_hash *hash, size_t length, const uint8_t *key); /* This function is not strictly needed, it's s just the same as the * hash update function. */ void hmac_update(void *state, const struct nettle_hash *hash, size_t length, const uint8_t *data); void hmac_digest(const void *outer, const void *inner, void *state, const struct nettle_hash *hash, size_t length, uint8_t *digest); #define HMAC_CTX(type) \ { type outer; type inner; type state; } #define HMAC_SET_KEY(ctx, hash, length, key) \ hmac_set_key( &(ctx)->outer, &(ctx)->inner, &(ctx)->state, \ (hash), (length), (key) ) #define HMAC_DIGEST(ctx, hash, length, digest) \ hmac_digest( &(ctx)->outer, &(ctx)->inner, &(ctx)->state, \ (hash), (length), (digest) ) /* HMAC using specific hash functions */ /* hmac-md5 */ struct hmac_md5_ctx HMAC_CTX(struct md5_ctx); void hmac_md5_set_key(struct hmac_md5_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_md5_update(struct hmac_md5_ctx *ctx, size_t length, const uint8_t *data); void hmac_md5_digest(struct hmac_md5_ctx *ctx, size_t length, uint8_t *digest); /* hmac-ripemd160 */ struct hmac_ripemd160_ctx HMAC_CTX(struct ripemd160_ctx); void hmac_ripemd160_set_key(struct hmac_ripemd160_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_ripemd160_update(struct hmac_ripemd160_ctx *ctx, size_t length, const uint8_t *data); void hmac_ripemd160_digest(struct hmac_ripemd160_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha1 */ struct hmac_sha1_ctx HMAC_CTX(struct sha1_ctx); void hmac_sha1_set_key(struct hmac_sha1_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sha1_update(struct hmac_sha1_ctx *ctx, size_t length, const uint8_t *data); void hmac_sha1_digest(struct hmac_sha1_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha256 */ struct hmac_sha256_ctx HMAC_CTX(struct sha256_ctx); void hmac_sha256_set_key(struct hmac_sha256_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sha256_update(struct hmac_sha256_ctx *ctx, size_t length, const uint8_t *data); void hmac_sha256_digest(struct hmac_sha256_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha224 */ #define hmac_sha224_ctx hmac_sha256_ctx void hmac_sha224_set_key(struct hmac_sha224_ctx *ctx, size_t key_length, const uint8_t *key); #define hmac_sha224_update nettle_hmac_sha256_update void hmac_sha224_digest(struct hmac_sha224_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha512 */ struct hmac_sha512_ctx HMAC_CTX(struct sha512_ctx); void hmac_sha512_set_key(struct hmac_sha512_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sha512_update(struct hmac_sha512_ctx *ctx, size_t length, const uint8_t *data); void hmac_sha512_digest(struct hmac_sha512_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha384 */ #define hmac_sha384_ctx hmac_sha512_ctx void hmac_sha384_set_key(struct hmac_sha512_ctx *ctx, size_t key_length, const uint8_t *key); #define hmac_sha384_update nettle_hmac_sha512_update void hmac_sha384_digest(struct hmac_sha512_ctx *ctx, size_t length, uint8_t *digest); /* hmac-gosthash94 */ struct hmac_gosthash94_ctx HMAC_CTX(struct gosthash94_ctx); void hmac_gosthash94_set_key(struct hmac_gosthash94_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_gosthash94_update(struct hmac_gosthash94_ctx *ctx, size_t length, const uint8_t *data); void hmac_gosthash94_digest(struct hmac_gosthash94_ctx *ctx, size_t length, uint8_t *digest); struct hmac_gosthash94cp_ctx HMAC_CTX(struct gosthash94cp_ctx); void hmac_gosthash94cp_set_key(struct hmac_gosthash94cp_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_gosthash94cp_update(struct hmac_gosthash94cp_ctx *ctx, size_t length, const uint8_t *data); void hmac_gosthash94cp_digest(struct hmac_gosthash94cp_ctx *ctx, size_t length, uint8_t *digest); /* hmac-streebog */ struct hmac_streebog512_ctx HMAC_CTX(struct streebog512_ctx); void hmac_streebog512_set_key(struct hmac_streebog512_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_streebog512_update(struct hmac_streebog512_ctx *ctx, size_t length, const uint8_t *data); void hmac_streebog512_digest(struct hmac_streebog512_ctx *ctx, size_t length, uint8_t *digest); #define hmac_streebog256_ctx hmac_streebog512_ctx void hmac_streebog256_set_key(struct hmac_streebog256_ctx *ctx, size_t key_length, const uint8_t *key); #define hmac_streebog256_update hmac_streebog512_update void hmac_streebog256_digest(struct hmac_streebog256_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sm3 */ struct hmac_sm3_ctx HMAC_CTX(struct sm3_ctx); void hmac_sm3_set_key(struct hmac_sm3_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sm3_update(struct hmac_sm3_ctx *ctx, size_t length, const uint8_t *data); void hmac_sm3_digest(struct hmac_sm3_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_HMAC_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/knuth-lfib.h ================================================ /* knuth-lfib.h The "lagged fibonacci" pseudorandomness generator, described in Knuth, TAoCP, 3.6 This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* NOTE: This generator is totally inappropriate for cryptographic * applications. It is useful for generating deterministic but * random-looking test data, and is used by the Nettle testsuite. */ #ifndef NETTLE_KNUTH_LFIB_H_INCLUDED #define NETTLE_KNUTH_LFIB_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define knuth_lfib_init nettle_knuth_lfib_init #define knuth_lfib_get nettle_knuth_lfib_get #define knuth_lfib_get_array nettle_knuth_lfib_get_array #define knuth_lfib_random nettle_knuth_lfib_random #define _KNUTH_LFIB_KK 100 struct knuth_lfib_ctx { uint32_t x[_KNUTH_LFIB_KK]; unsigned index; }; void knuth_lfib_init(struct knuth_lfib_ctx *ctx, uint32_t seed); /* Get's a single number in the range 0 ... 2^30-1 */ uint32_t knuth_lfib_get(struct knuth_lfib_ctx *ctx); /* Get an array of numbers */ void knuth_lfib_get_array(struct knuth_lfib_ctx *ctx, size_t n, uint32_t *a); /* Get an array of octets. */ void knuth_lfib_random(struct knuth_lfib_ctx *ctx, size_t n, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_KNUTH_LFIB_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/macros.h ================================================ /* macros.h Copyright (C) 2001, 2010 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MACROS_H_INCLUDED #define NETTLE_MACROS_H_INCLUDED /* Reads a 64-bit integer, in network, big-endian, byte order */ #define READ_UINT64(p) \ ( (((uint64_t) (p)[0]) << 56) \ | (((uint64_t) (p)[1]) << 48) \ | (((uint64_t) (p)[2]) << 40) \ | (((uint64_t) (p)[3]) << 32) \ | (((uint64_t) (p)[4]) << 24) \ | (((uint64_t) (p)[5]) << 16) \ | (((uint64_t) (p)[6]) << 8) \ | ((uint64_t) (p)[7])) #define WRITE_UINT64(p, i) \ do { \ (p)[0] = ((i) >> 56) & 0xff; \ (p)[1] = ((i) >> 48) & 0xff; \ (p)[2] = ((i) >> 40) & 0xff; \ (p)[3] = ((i) >> 32) & 0xff; \ (p)[4] = ((i) >> 24) & 0xff; \ (p)[5] = ((i) >> 16) & 0xff; \ (p)[6] = ((i) >> 8) & 0xff; \ (p)[7] = (i) & 0xff; \ } while(0) /* Reads a 32-bit integer, in network, big-endian, byte order */ #define READ_UINT32(p) \ ( (((uint32_t) (p)[0]) << 24) \ | (((uint32_t) (p)[1]) << 16) \ | (((uint32_t) (p)[2]) << 8) \ | ((uint32_t) (p)[3])) #define WRITE_UINT32(p, i) \ do { \ (p)[0] = ((i) >> 24) & 0xff; \ (p)[1] = ((i) >> 16) & 0xff; \ (p)[2] = ((i) >> 8) & 0xff; \ (p)[3] = (i) & 0xff; \ } while(0) /* Analogous macros, for 24 and 16 bit numbers */ #define READ_UINT24(p) \ ( (((uint32_t) (p)[0]) << 16) \ | (((uint32_t) (p)[1]) << 8) \ | ((uint32_t) (p)[2])) #define WRITE_UINT24(p, i) \ do { \ (p)[0] = ((i) >> 16) & 0xff; \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[2] = (i) & 0xff; \ } while(0) #define READ_UINT16(p) \ ( (((uint32_t) (p)[0]) << 8) \ | ((uint32_t) (p)[1])) #define WRITE_UINT16(p, i) \ do { \ (p)[0] = ((i) >> 8) & 0xff; \ (p)[1] = (i) & 0xff; \ } while(0) /* And the other, little-endian, byteorder */ #define LE_READ_UINT64(p) \ ( (((uint64_t) (p)[7]) << 56) \ | (((uint64_t) (p)[6]) << 48) \ | (((uint64_t) (p)[5]) << 40) \ | (((uint64_t) (p)[4]) << 32) \ | (((uint64_t) (p)[3]) << 24) \ | (((uint64_t) (p)[2]) << 16) \ | (((uint64_t) (p)[1]) << 8) \ | ((uint64_t) (p)[0])) #define LE_WRITE_UINT64(p, i) \ do { \ (p)[7] = ((i) >> 56) & 0xff; \ (p)[6] = ((i) >> 48) & 0xff; \ (p)[5] = ((i) >> 40) & 0xff; \ (p)[4] = ((i) >> 32) & 0xff; \ (p)[3] = ((i) >> 24) & 0xff; \ (p)[2] = ((i) >> 16) & 0xff; \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[0] = (i) & 0xff; \ } while (0) #define LE_READ_UINT32(p) \ ( (((uint32_t) (p)[3]) << 24) \ | (((uint32_t) (p)[2]) << 16) \ | (((uint32_t) (p)[1]) << 8) \ | ((uint32_t) (p)[0])) #define LE_WRITE_UINT32(p, i) \ do { \ (p)[3] = ((i) >> 24) & 0xff; \ (p)[2] = ((i) >> 16) & 0xff; \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[0] = (i) & 0xff; \ } while(0) /* Analogous macros, for 16 bit numbers */ #define LE_READ_UINT16(p) \ ( (((uint32_t) (p)[1]) << 8) \ | ((uint32_t) (p)[0])) #define LE_WRITE_UINT16(p, i) \ do { \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[0] = (i) & 0xff; \ } while(0) /* Macro to make it easier to loop over several blocks. */ #define FOR_BLOCKS(length, dst, src, blocksize) \ assert( !((length) % (blocksize))); \ for (; (length); ((length) -= (blocksize), \ (dst) += (blocksize), \ (src) += (blocksize)) ) /* The masking of the right shift is needed to allow n == 0 (using just 32 - n and 64 - n results in undefined behaviour). Most uses of these macros use a constant and non-zero rotation count. */ #define ROTL32(n,x) (((x)<<(n)) | ((x)>>((-(n)&31)))) #define ROTL64(n,x) (((x)<<(n)) | ((x)>>((-(n))&63))) /* Requires that size > 0 */ #define INCREMENT(size, ctr) \ do { \ unsigned increment_i = (size) - 1; \ if (++(ctr)[increment_i] == 0) \ while (increment_i > 0 \ && ++(ctr)[--increment_i] == 0 ) \ ; \ } while (0) /* Helper macro for Merkle-Damgård hash functions. Assumes the context structs includes the following fields: uint8_t block[...]; // Buffer holding one block unsigned int index; // Index into block */ /* Currently used by sha512 (and sha384) only. */ #define MD_INCR(ctx) ((ctx)->count_high += !++(ctx)->count_low) /* Takes the compression function f as argument. NOTE: also clobbers length and data. */ #define MD_UPDATE(ctx, length, data, f, incr) \ do { \ if ((ctx)->index) \ { \ /* Try to fill partial block */ \ unsigned __md_left = sizeof((ctx)->block) - (ctx)->index; \ if ((length) < __md_left) \ { \ memcpy((ctx)->block + (ctx)->index, (data), (length)); \ (ctx)->index += (length); \ goto __md_done; /* Finished */ \ } \ else \ { \ memcpy((ctx)->block + (ctx)->index, (data), __md_left); \ \ f((ctx), (ctx)->block); \ (incr); \ \ (data) += __md_left; \ (length) -= __md_left; \ } \ } \ while ((length) >= sizeof((ctx)->block)) \ { \ f((ctx), (data)); \ (incr); \ \ (data) += sizeof((ctx)->block); \ (length) -= sizeof((ctx)->block); \ } \ memcpy ((ctx)->block, (data), (length)); \ (ctx)->index = (length); \ __md_done: \ ; \ } while (0) /* Pads the block to a block boundary with the bit pattern 1 0*, leaving size octets for the length field at the end. If needed, compresses the block and starts a new one. */ #define MD_PAD(ctx, size, f) \ do { \ unsigned __md_i; \ __md_i = (ctx)->index; \ \ /* Set the first char of padding to 0x80. This is safe since there \ is always at least one byte free */ \ \ assert(__md_i < sizeof((ctx)->block)); \ (ctx)->block[__md_i++] = 0x80; \ \ if (__md_i > (sizeof((ctx)->block) - (size))) \ { /* No room for length in this block. Process it and \ pad with another one */ \ memset((ctx)->block + __md_i, 0, sizeof((ctx)->block) - __md_i); \ \ f((ctx), (ctx)->block); \ __md_i = 0; \ } \ memset((ctx)->block + __md_i, 0, \ sizeof((ctx)->block) - (size) - __md_i); \ \ } while (0) #endif /* NETTLE_MACROS_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/md2.h ================================================ /* md2.h The MD2 hash function, described in RFC 1319. Copyright (C) 2003 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD2_H_INCLUDED #define NETTLE_MD2_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define md2_init nettle_md2_init #define md2_update nettle_md2_update #define md2_digest nettle_md2_digest #define MD2_DIGEST_SIZE 16 #define MD2_BLOCK_SIZE 16 /* For backwards compatibility */ #define MD2_DATA_SIZE MD2_BLOCK_SIZE struct md2_ctx { uint8_t C[MD2_BLOCK_SIZE]; uint8_t X[3 * MD2_BLOCK_SIZE]; unsigned index; /* Into buffer */ uint8_t block[MD2_BLOCK_SIZE]; /* Block buffer */ }; void md2_init(struct md2_ctx *ctx); void md2_update(struct md2_ctx *ctx, size_t length, const uint8_t *data); void md2_digest(struct md2_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_MD2_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/md4.h ================================================ /* md4.h The MD4 hash function, described in RFC 1320. Copyright (C) 2003 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD4_H_INCLUDED #define NETTLE_MD4_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define md4_init nettle_md4_init #define md4_update nettle_md4_update #define md4_digest nettle_md4_digest #define MD4_DIGEST_SIZE 16 #define MD4_BLOCK_SIZE 64 /* For backwards compatibility */ #define MD4_DATA_SIZE MD4_BLOCK_SIZE /* Digest is kept internally as 4 32-bit words. */ #define _MD4_DIGEST_LENGTH 4 /* FIXME: Identical to md5_ctx */ struct md4_ctx { uint32_t state[_MD4_DIGEST_LENGTH]; uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[MD4_BLOCK_SIZE]; /* Block buffer */ }; void md4_init(struct md4_ctx *ctx); void md4_update(struct md4_ctx *ctx, size_t length, const uint8_t *data); void md4_digest(struct md4_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_MD4_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/md5-compat.h ================================================ /* md5-compat.h The md5 hash function, RFC 1321-style interface. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD5_COMPAT_H_INCLUDED #define NETTLE_MD5_COMPAT_H_INCLUDED #include "md5.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define MD5Init nettle_MD5Init #define MD5Update nettle_MD5Update #define MD5Final nettle_MD5Final typedef struct md5_ctx MD5_CTX; void MD5Init(MD5_CTX *ctx); void MD5Update(MD5_CTX *ctx, const unsigned char *data, unsigned int length); void MD5Final(unsigned char *out, MD5_CTX *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_MD5_COMPAT_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/md5.h ================================================ /* md5.h The MD5 hash function, described in RFC 1321. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD5_H_INCLUDED #define NETTLE_MD5_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define md5_init nettle_md5_init #define md5_update nettle_md5_update #define md5_digest nettle_md5_digest #define md5_compress nettle_md5_compress #define MD5_DIGEST_SIZE 16 #define MD5_BLOCK_SIZE 64 /* For backwards compatibility */ #define MD5_DATA_SIZE MD5_BLOCK_SIZE /* Digest is kept internally as 4 32-bit words. */ #define _MD5_DIGEST_LENGTH 4 struct md5_ctx { uint32_t state[_MD5_DIGEST_LENGTH]; uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[MD5_BLOCK_SIZE]; /* Block buffer */ }; void md5_init(struct md5_ctx *ctx); void md5_update(struct md5_ctx *ctx, size_t length, const uint8_t *data); void md5_digest(struct md5_ctx *ctx, size_t length, uint8_t *digest); /* MD5 compression function. STATE points to 4 uint32_t words, and DATA points to 64 bytes of input data, possibly unaligned. */ void md5_compress(uint32_t *state, const uint8_t *data); /* Old name, for backwards compatibility. */ #define _nettle_md5_compress nettle_md5_compress #ifdef __cplusplus } #endif #endif /* NETTLE_MD5_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/memops.h ================================================ /* memops.h Copyright (C) 2016 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MEMOPS_H_INCLUDED #define NETTLE_MEMOPS_H_INCLUDED #include "memxor.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cnd_memcpy nettle_cnd_memcpy #define memeql_sec nettle_memeql_sec int memeql_sec (const void *a, const void *b, size_t n); /* Side-channel silent conditional memcpy. cnd must be 0 (nop) or 1 (copy). */ void cnd_memcpy(int cnd, volatile void *dst, const volatile void *src, size_t n); #ifdef __cplusplus } #endif #endif /* NETTLE_MEMOPS_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/memxor.h ================================================ /* memxor.h * */ #ifndef NETTLE_MEMXOR_H_INCLUDED #define NETTLE_MEMXOR_H_INCLUDED #include #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define memxor nettle_memxor #define memxor3 nettle_memxor3 void *memxor(void *dst, const void *src, size_t n); void *memxor3(void *dst, const void *a, const void *b, size_t n); #ifdef __cplusplus } #endif #endif /* NETTLE_MEMXOR_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/nettle-meta.h ================================================ /* nettle-meta.h Information about algorithms. Copyright (C) 2002, 2014, 2020 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_META_H_INCLUDED #define NETTLE_META_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif struct nettle_cipher { const char *name; unsigned context_size; /* Zero for stream ciphers */ unsigned block_size; /* Suggested key size; other sizes are sometimes possible. */ unsigned key_size; nettle_set_key_func *set_encrypt_key; nettle_set_key_func *set_decrypt_key; nettle_cipher_func *encrypt; nettle_cipher_func *decrypt; }; /* null-terminated list of ciphers implemented by this version of nettle */ const struct nettle_cipher * const * _NETTLE_ATTRIBUTE_PURE nettle_get_ciphers (void); #define nettle_ciphers (nettle_get_ciphers()) extern const struct nettle_cipher nettle_aes128; extern const struct nettle_cipher nettle_aes192; extern const struct nettle_cipher nettle_aes256; extern const struct nettle_cipher nettle_camellia128; extern const struct nettle_cipher nettle_camellia192; extern const struct nettle_cipher nettle_camellia256; extern const struct nettle_cipher nettle_cast128; extern const struct nettle_cipher nettle_serpent128; extern const struct nettle_cipher nettle_serpent192; extern const struct nettle_cipher nettle_serpent256; extern const struct nettle_cipher nettle_twofish128; extern const struct nettle_cipher nettle_twofish192; extern const struct nettle_cipher nettle_twofish256; extern const struct nettle_cipher nettle_arctwo40; extern const struct nettle_cipher nettle_arctwo64; extern const struct nettle_cipher nettle_arctwo128; extern const struct nettle_cipher nettle_arctwo_gutmann128; extern const struct nettle_cipher nettle_sm4; struct nettle_hash { const char *name; /* Size of the context struct */ unsigned context_size; /* Size of digests */ unsigned digest_size; /* Internal block size */ unsigned block_size; nettle_hash_init_func *init; nettle_hash_update_func *update; nettle_hash_digest_func *digest; }; #define _NETTLE_HASH(name, NAME) { \ #name, \ sizeof(struct name##_ctx), \ NAME##_DIGEST_SIZE, \ NAME##_BLOCK_SIZE, \ (nettle_hash_init_func *) name##_init, \ (nettle_hash_update_func *) name##_update, \ (nettle_hash_digest_func *) name##_digest \ } /* null-terminated list of digests implemented by this version of nettle */ const struct nettle_hash * const * _NETTLE_ATTRIBUTE_PURE nettle_get_hashes (void); #define nettle_hashes (nettle_get_hashes()) const struct nettle_hash * nettle_lookup_hash (const char *name); extern const struct nettle_hash nettle_md2; extern const struct nettle_hash nettle_md4; extern const struct nettle_hash nettle_md5; extern const struct nettle_hash nettle_gosthash94; extern const struct nettle_hash nettle_gosthash94cp; extern const struct nettle_hash nettle_ripemd160; extern const struct nettle_hash nettle_sha1; extern const struct nettle_hash nettle_sha224; extern const struct nettle_hash nettle_sha256; extern const struct nettle_hash nettle_sha384; extern const struct nettle_hash nettle_sha512; extern const struct nettle_hash nettle_sha512_224; extern const struct nettle_hash nettle_sha512_256; extern const struct nettle_hash nettle_sha3_224; extern const struct nettle_hash nettle_sha3_256; extern const struct nettle_hash nettle_sha3_384; extern const struct nettle_hash nettle_sha3_512; extern const struct nettle_hash nettle_streebog256; extern const struct nettle_hash nettle_streebog512; extern const struct nettle_hash nettle_sm3; struct nettle_mac { const char *name; /* Size of the context struct */ unsigned context_size; /* Size of digests */ unsigned digest_size; /* Key size */ unsigned key_size; nettle_set_key_func *set_key; nettle_hash_update_func *update; nettle_hash_digest_func *digest; }; struct nettle_aead { const char *name; unsigned context_size; /* Block size for encrypt and decrypt. */ unsigned block_size; unsigned key_size; unsigned nonce_size; unsigned digest_size; nettle_set_key_func *set_encrypt_key; nettle_set_key_func *set_decrypt_key; nettle_set_key_func *set_nonce; nettle_hash_update_func *update; nettle_crypt_func *encrypt; nettle_crypt_func *decrypt; /* FIXME: Drop length argument? */ nettle_hash_digest_func *digest; }; /* null-terminated list of aead constructions implemented by this version of nettle */ const struct nettle_aead * const * _NETTLE_ATTRIBUTE_PURE nettle_get_aeads (void); #define nettle_aeads (nettle_get_aeads()) extern const struct nettle_aead nettle_gcm_aes128; extern const struct nettle_aead nettle_gcm_aes192; extern const struct nettle_aead nettle_gcm_aes256; extern const struct nettle_aead nettle_gcm_camellia128; extern const struct nettle_aead nettle_gcm_camellia256; extern const struct nettle_aead nettle_gcm_sm4; extern const struct nettle_aead nettle_eax_aes128; extern const struct nettle_aead nettle_chacha_poly1305; struct nettle_armor { const char *name; unsigned encode_context_size; unsigned decode_context_size; unsigned encode_final_length; nettle_armor_init_func *encode_init; nettle_armor_length_func *encode_length; nettle_armor_encode_update_func *encode_update; nettle_armor_encode_final_func *encode_final; nettle_armor_init_func *decode_init; nettle_armor_length_func *decode_length; nettle_armor_decode_update_func *decode_update; nettle_armor_decode_final_func *decode_final; }; #define _NETTLE_ARMOR(name, NAME) { \ #name, \ sizeof(struct name##_encode_ctx), \ sizeof(struct name##_decode_ctx), \ NAME##_ENCODE_FINAL_LENGTH, \ (nettle_armor_init_func *) name##_encode_init, \ (nettle_armor_length_func *) name##_encode_length, \ (nettle_armor_encode_update_func *) name##_encode_update, \ (nettle_armor_encode_final_func *) name##_encode_final, \ (nettle_armor_init_func *) name##_decode_init, \ (nettle_armor_length_func *) name##_decode_length, \ (nettle_armor_decode_update_func *) name##_decode_update, \ (nettle_armor_decode_final_func *) name##_decode_final, \ } #define _NETTLE_ARMOR_0(name, NAME) { \ #name, \ 0, \ sizeof(struct name##_decode_ctx), \ NAME##_ENCODE_FINAL_LENGTH, \ (nettle_armor_init_func *) name##_encode_init, \ (nettle_armor_length_func *) name##_encode_length, \ (nettle_armor_encode_update_func *) name##_encode_update, \ (nettle_armor_encode_final_func *) name##_encode_final, \ (nettle_armor_init_func *) name##_decode_init, \ (nettle_armor_length_func *) name##_decode_length, \ (nettle_armor_decode_update_func *) name##_decode_update, \ (nettle_armor_decode_final_func *) name##_decode_final, \ } /* null-terminated list of armor schemes implemented by this version of nettle */ const struct nettle_armor * const * _NETTLE_ATTRIBUTE_PURE nettle_get_armors (void); #define nettle_armors (nettle_get_armors()) extern const struct nettle_armor nettle_base64; extern const struct nettle_armor nettle_base64url; extern const struct nettle_armor nettle_base16; #define _NETTLE_HMAC(name, HASH) { \ #name, \ sizeof(struct name##_ctx), \ HASH##_DIGEST_SIZE, \ HASH##_DIGEST_SIZE, \ name##_set_key_wrapper, \ (nettle_hash_update_func *) name##_update, \ (nettle_hash_digest_func *) name##_digest, \ } /* null-terminated list of macs implemented by this version of nettle */ const struct nettle_mac * const * _NETTLE_ATTRIBUTE_PURE nettle_get_macs (void); #define nettle_macs (nettle_get_macs()) extern const struct nettle_mac nettle_cmac_aes128; extern const struct nettle_mac nettle_cmac_aes256; extern const struct nettle_mac nettle_cmac_des3; /* HMAC variants with key size = digest size */ extern const struct nettle_mac nettle_hmac_md5; extern const struct nettle_mac nettle_hmac_ripemd160; extern const struct nettle_mac nettle_hmac_sha1; extern const struct nettle_mac nettle_hmac_sha224; extern const struct nettle_mac nettle_hmac_sha256; extern const struct nettle_mac nettle_hmac_sha384; extern const struct nettle_mac nettle_hmac_sha512; extern const struct nettle_mac nettle_hmac_streebog256; extern const struct nettle_mac nettle_hmac_streebog512; extern const struct nettle_mac nettle_hmac_sm3; #ifdef __cplusplus } #endif #endif /* NETTLE_META_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/nettle-types.h ================================================ /* nettle-types.h Copyright (C) 2005, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_TYPES_H #define NETTLE_TYPES_H /* For size_t */ #include #include /* Attributes we want to use in installed header files, and hence can't rely on config.h. */ #ifdef __GNUC__ #define _NETTLE_ATTRIBUTE_PURE __attribute__((pure)) #ifndef _NETTLE_ATTRIBUTE_DEPRECATED /* Variant without message is supported since gcc-3.1 or so. */ #define _NETTLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated)) #endif #else /* !__GNUC__ */ #define _NETTLE_ATTRIBUTE_PURE #define _NETTLE_ATTRIBUTE_DEPRECATED #endif /* !__GNUC__ */ #ifdef __cplusplus extern "C" { #endif /* An aligned 16-byte block. */ union nettle_block16 { uint8_t b[16]; unsigned long w[16 / sizeof(unsigned long)] _NETTLE_ATTRIBUTE_DEPRECATED; uint64_t u64[2]; }; union nettle_block8 { uint8_t b[8]; uint64_t u64; }; /* Randomness. Used by key generation and dsa signature creation. */ typedef void nettle_random_func(void *ctx, size_t length, uint8_t *dst); /* Progress report function, mainly for key generation. */ typedef void nettle_progress_func(void *ctx, int c); /* Realloc function, used by struct nettle_buffer. */ typedef void *nettle_realloc_func(void *ctx, void *p, size_t length); /* Ciphers */ typedef void nettle_set_key_func(void *ctx, const uint8_t *key); /* For block ciphers, const context. */ typedef void nettle_cipher_func(const void *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* Uses a void * for cipher contexts. Used for crypt operations where the internal state changes during the encryption. */ typedef void nettle_crypt_func(void *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* Hash algorithms */ typedef void nettle_hash_init_func(void *ctx); typedef void nettle_hash_update_func(void *ctx, size_t length, const uint8_t *src); typedef void nettle_hash_digest_func(void *ctx, size_t length, uint8_t *dst); /* ASCII armor codecs. NOTE: Experimental and subject to change. */ typedef size_t nettle_armor_length_func(size_t length); typedef void nettle_armor_init_func(void *ctx); typedef size_t nettle_armor_encode_update_func(void *ctx, char *dst, size_t src_length, const uint8_t *src); typedef size_t nettle_armor_encode_final_func(void *ctx, char *dst); typedef int nettle_armor_decode_update_func(void *ctx, size_t *dst_length, uint8_t *dst, size_t src_length, const char *src); typedef int nettle_armor_decode_final_func(void *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_TYPES_H */ ================================================ FILE: thirdparty/32/include/nettle/nist-keywrap.h ================================================ /* nist-keywrap.h AES Key Wrap function. implements RFC 3394 https://tools.ietf.org/html/rfc3394 Copyright (C) 2021 Nicolas Mora 2021 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_NIST_KEYWRAP_H_INCLUDED #define NETTLE_NIST_KEYWRAP_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define nist_keywrap16 nettle_nist_keywrap16 #define nist_keyunwrap16 nettle_nist_keyunwrap16 #define aes128_keywrap nettle_aes128_keywrap #define aes192_keywrap nettle_aes192_keywrap #define aes256_keywrap nettle_aes256_keywrap #define aes128_keyunwrap nettle_aes128_keyunwrap #define aes192_keyunwrap nettle_aes192_keyunwrap #define aes256_keyunwrap nettle_aes256_keyunwrap void nist_keywrap16 (const void *ctx, nettle_cipher_func *encrypt, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); int nist_keyunwrap16 (const void *ctx, nettle_cipher_func *decrypt, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); void aes128_keywrap (struct aes128_ctx *ctx, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); void aes192_keywrap (struct aes192_ctx *ctx, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); void aes256_keywrap (struct aes256_ctx *ctx, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); int aes128_keyunwrap (struct aes128_ctx *ctx, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); int aes192_keyunwrap (struct aes192_ctx *ctx, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); int aes256_keyunwrap (struct aes256_ctx *ctx, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); #ifdef __cplusplus } #endif #endif /* NETTLE_NIST_KEYWRAP_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/ocb.h ================================================ /* ocb.h OCB AEAD mode, RFC 7253 Copyright (C) 2021 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_OCB_H_INCLUDED #define NETTLE_OCB_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ocb_set_key nettle_ocb_set_key #define ocb_set_nonce nettle_ocb_set_nonce #define ocb_update nettle_ocb_update #define ocb_encrypt nettle_ocb_encrypt #define ocb_decrypt nettle_ocb_decrypt #define ocb_digest nettle_ocb_digest #define ocb_encrypt_message nettle_ocb_encrypt_message #define ocb_decrypt_message nettle_ocb_decrypt_message #define ocb_aes128_set_encrypt_key nettle_ocb_aes128_set_encrypt_key #define ocb_aes128_set_decrypt_key nettle_ocb_aes128_set_decrypt_key #define ocb_aes128_set_nonce nettle_ocb_aes128_set_nonce #define ocb_aes128_update nettle_ocb_aes128_update #define ocb_aes128_encrypt nettle_ocb_aes128_encrypt #define ocb_aes128_decrypt nettle_ocb_aes128_decrypt #define ocb_aes128_digest nettle_ocb_aes128_digest #define ocb_aes128_encrypt_message nettle_ocb_aes128_encrypt_message #define ocb_aes128_decrypt_message nettle_ocb_aes128_decrypt_message #define OCB_BLOCK_SIZE 16 #define OCB_DIGEST_SIZE 16 #define OCB_MAX_NONCE_SIZE 15 struct ocb_key { /* L_*, L_$ and L_0, and one reserved entry */ union nettle_block16 L[4]; }; struct ocb_ctx { /* Initial offset, Offset_0 in the spec. */ union nettle_block16 initial; /* Offset, updated per block. */ union nettle_block16 offset; /* Authentication for the associated data */ union nettle_block16 sum; /* Authentication for the message */ union nettle_block16 checksum; /* Count of processed blocks. */ size_t data_count; size_t message_count; }; void ocb_set_key (struct ocb_key *key, const void *cipher, nettle_cipher_func *f); void ocb_set_nonce (struct ocb_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t tag_length, size_t nonce_length, const uint8_t *nonce); void ocb_update (struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, const uint8_t *data); void ocb_encrypt (struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void ocb_decrypt (struct ocb_ctx *ctx, const struct ocb_key *key, const void *encrypt_ctx, nettle_cipher_func *encrypt, const void *decrypt_ctx, nettle_cipher_func *decrypt, size_t length, uint8_t *dst, const uint8_t *src); void ocb_digest (const struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); void ocb_encrypt_message (const struct ocb_key *ocb_key, const void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ocb_decrypt_message (const struct ocb_key *ocb_key, const void *encrypt_ctx, nettle_cipher_func *encrypt, const void *decrypt_ctx, nettle_cipher_func *decrypt, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); /* OCB-AES */ /* This struct represents an expanded key for ocb-aes encryption. For decryption, a separate decryption context is needed as well. */ struct ocb_aes128_encrypt_key { struct ocb_key ocb; struct aes128_ctx encrypt; }; void ocb_aes128_set_encrypt_key (struct ocb_aes128_encrypt_key *ocb, const uint8_t *key); void ocb_aes128_set_decrypt_key (struct ocb_aes128_encrypt_key *ocb, struct aes128_ctx *decrypt, const uint8_t *key); void ocb_aes128_set_nonce (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t tag_length, size_t nonce_length, const uint8_t *nonce); void ocb_aes128_update (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, const uint8_t *data); void ocb_aes128_encrypt(struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, uint8_t *dst, const uint8_t *src); void ocb_aes128_decrypt(struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, const struct aes128_ctx *decrypt, size_t length, uint8_t *dst, const uint8_t *src); void ocb_aes128_digest(struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, uint8_t *digest); void ocb_aes128_encrypt_message (const struct ocb_aes128_encrypt_key *key, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ocb_aes128_decrypt_message (const struct ocb_aes128_encrypt_key *key, const struct aes128_ctx *decrypt, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_OCB_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/pbkdf2.h ================================================ /* pbkdf2.h PKCS #5 password-based key derivation function PBKDF2, see RFC 2898. Copyright (C) 2012 Simon Josefsson This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PBKDF2_H_INCLUDED #define NETTLE_PBKDF2_H_INCLUDED #include "nettle-meta.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define pbkdf2 nettle_pbkdf2 #define pbkdf2_hmac_sha1 nettle_pbkdf2_hmac_sha1 #define pbkdf2_hmac_sha256 nettle_pbkdf2_hmac_sha256 #define pbkdf2_hmac_sha384 nettle_pbkdf2_hmac_sha384 #define pbkdf2_hmac_sha512 nettle_pbkdf2_hmac_sha512 #define pbkdf2_hmac_gosthash94cp nettle_pbkdf2_hmac_gosthash94cp void pbkdf2 (void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); #define PBKDF2(ctx, update, digest, digest_size, \ iterations, salt_length, salt, length, dst) \ (0 ? ((update)((ctx), 0, (uint8_t *) 0), \ (digest)((ctx), 0, (uint8_t *) 0)) \ : pbkdf2 ((ctx), \ (nettle_hash_update_func *)(update), \ (nettle_hash_digest_func *)(digest), \ (digest_size), (iterations), \ (salt_length), (salt), (length), (dst))) /* PBKDF2 with specific PRFs. */ void pbkdf2_hmac_sha1 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_sha256 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_sha384 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_sha512 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_gosthash94cp (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_PBKDF2_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/pgp.h ================================================ /* pgp.h PGP related functions. Copyright (C) 2001, 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PGP_H_INCLUDED #define NETTLE_PGP_H_INCLUDED #include #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define pgp_put_uint32 nettle_pgp_put_uint32 #define pgp_put_uint16 nettle_pgp_put_uint16 #define pgp_put_mpi nettle_pgp_put_mpi #define pgp_put_string nettle_pgp_put_string #define pgp_put_length nettle_pgp_put_length #define pgp_put_header nettle_pgp_put_header #define pgp_put_header_length nettle_pgp_put_header_length #define pgp_sub_packet_start nettle_pgp_sub_packet_start #define pgp_put_sub_packet nettle_pgp_put_sub_packet #define pgp_sub_packet_end nettle_pgp_sub_packet_end #define pgp_put_public_rsa_key nettle_pgp_put_public_rsa_key #define pgp_put_rsa_sha1_signature nettle_pgp_put_rsa_sha1_signature #define pgp_put_userid nettle_pgp_put_userid #define pgp_crc24 nettle_pgp_crc24 #define pgp_armor nettle_pgp_armor struct nettle_buffer; struct rsa_public_key; struct rsa_private_key; struct sha1_ctx; int pgp_put_uint32(struct nettle_buffer *buffer, uint32_t i); int pgp_put_uint16(struct nettle_buffer *buffer, unsigned i); int pgp_put_mpi(struct nettle_buffer *buffer, const mpz_t x); int pgp_put_string(struct nettle_buffer *buffer, unsigned length, const uint8_t *s); int pgp_put_length(struct nettle_buffer *buffer, unsigned length); int pgp_put_header(struct nettle_buffer *buffer, unsigned tag, unsigned length); void pgp_put_header_length(struct nettle_buffer *buffer, /* start of the header */ unsigned start, unsigned field_size); unsigned pgp_sub_packet_start(struct nettle_buffer *buffer); int pgp_put_sub_packet(struct nettle_buffer *buffer, unsigned type, unsigned length, const uint8_t *data); void pgp_sub_packet_end(struct nettle_buffer *buffer, unsigned start); int pgp_put_public_rsa_key(struct nettle_buffer *, const struct rsa_public_key *key, time_t timestamp); int pgp_put_rsa_sha1_signature(struct nettle_buffer *buffer, const struct rsa_private_key *key, const uint8_t *keyid, unsigned type, struct sha1_ctx *hash); int pgp_put_userid(struct nettle_buffer *buffer, unsigned length, const uint8_t *name); uint32_t pgp_crc24(unsigned length, const uint8_t *data); int pgp_armor(struct nettle_buffer *buffer, const char *tag, unsigned length, const uint8_t *data); /* Values that can be passed to pgp_put_header when the size of the * length field, but not the length itself, is known. Also the minimum length * for the given field size. */ enum pgp_lengths { PGP_LENGTH_ONE_OCTET = 0, PGP_LENGTH_TWO_OCTETS = 192, PGP_LENGTH_FOUR_OCTETS = 8384, }; enum pgp_public_key_algorithm { PGP_RSA = 1, PGP_RSA_ENCRYPT = 2, PGP_RSA_SIGN = 3, PGP_EL_GAMAL_ENCRYPT = 16, PGP_DSA = 17, PGP_EL_GAMAL = 20, }; enum pgp_symmetric_algorithm { PGP_PLAINTEXT = 0, PGP_IDEA = 1, PGP_3DES = 2, PGP_CAST5 = 3, PGP_BLOWFISH = 4, PGP_SAFER_SK = 5, PGP_AES128 = 7, PGP_AES192 = 8, PGP_AES256 = 9, }; enum pgp_compression_algorithm { PGP_UNCOMPRESSED = 0, PGP_ZIP = 1, PGP_ZLIB = 2, }; enum pgp_hash_algorithm { PGP_MD5 = 1, PGP_SHA1 = 2, PGP_RIPEMD = 3, PGP_MD2 = 5, PGP_TIGER192 = 6, PGP_HAVAL = 7, }; enum pgp_tag { PGP_TAG_PUBLIC_SESSION_KEY = 1, PGP_TAG_SIGNATURE = 2, PGP_TAG_SYMMETRIC_SESSION_KEY = 3, PGP_TAG_ONE_PASS_SIGNATURE = 4, PGP_TAG_SECRET_KEY = 5, PGP_TAG_PUBLIC_KEY = 6, PGP_TAG_SECRET_SUBKEY = 7, PGP_TAG_COMPRESSED = 8, PGP_TAG_ENCRYPTED = 9, PGP_TAG_MARKER = 10, PGP_TAG_LITERAL = 11, PGP_TAG_TRUST = 12, PGP_TAG_USERID = 13, PGP_TAG_PUBLIC_SUBKEY = 14, }; enum pgp_signature_type { PGP_SIGN_BINARY = 0, PGP_SIGN_TEXT = 1, PGP_SIGN_STANDALONE = 2, PGP_SIGN_CERTIFICATION = 0x10, PGP_SIGN_CERTIFICATION_PERSONA = 0x11, PGP_SIGN_CERTIFICATION_CASUAL = 0x12, PGP_SIGN_CERTIFICATION_POSITIVE = 0x13, PGP_SIGN_SUBKEY = 0x18, PGP_SIGN_KEY = 0x1f, PGP_SIGN_REVOCATION = 0x20, PGP_SIGN_REVOCATION_SUBKEY = 0x28, PGP_SIGN_REVOCATION_CERTIFICATE = 0x30, PGP_SIGN_TIMESTAMP = 0x40, }; enum pgp_subpacket_tag { PGP_SUBPACKET_CREATION_TIME = 2, PGP_SUBPACKET_SIGNATURE_EXPIRATION_TIME = 3, PGP_SUBPACKET_EXPORTABLE_CERTIFICATION = 4, PGP_SUBPACKET_TRUST_SIGNATURE = 5, PGP_SUBPACKET_REGULAR_EXPRESSION = 6, PGP_SUBPACKET_REVOCABLE = 7, PGP_SUBPACKET_KEY_EXPIRATION_TIME = 9, PGP_SUBPACKET_PLACEHOLDER = 10 , PGP_SUBPACKET_PREFERRED_SYMMETRIC_ALGORITHMS = 11, PGP_SUBPACKET_REVOCATION_KEY = 12, PGP_SUBPACKET_ISSUER_KEY_ID = 16, PGP_SUBPACKET_NOTATION_DATA = 20, PGP_SUBPACKET_PREFERRED_HASH_ALGORITHMS = 21, PGP_SUBPACKET_PREFERRED_COMPRESSION_ALGORITHMS = 22, PGP_SUBPACKET_KEY_SERVER_PREFERENCES = 23, PGP_SUBPACKET_PREFERRED_KEY_SERVER = 24, PGP_SUBPACKET_PRIMARY_USER_ID = 25, PGP_SUBPACKET_POLICY_URL = 26, PGP_SUBPACKET_KEY_FLAGS = 27, PGP_SUBPACKET_SIGNERS_USER_ID = 28, PGP_SUBPACKET_REASON_FOR_REVOCATION = 29, }; #ifdef __cplusplus } #endif #endif /* NETTLE_PGP_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/pkcs1.h ================================================ /* pkcs1.h PKCS1 embedding. Copyright (C) 2003 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PKCS1_H_INCLUDED #define NETTLE_PKCS1_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define pkcs1_rsa_digest_encode nettle_pkcs1_rsa_digest_encode #define pkcs1_rsa_md5_encode nettle_pkcs1_rsa_md5_encode #define pkcs1_rsa_md5_encode_digest nettle_pkcs1_rsa_md5_encode_digest #define pkcs1_rsa_sha1_encode nettle_pkcs1_rsa_sha1_encode #define pkcs1_rsa_sha1_encode_digest nettle_pkcs1_rsa_sha1_encode_digest #define pkcs1_rsa_sha256_encode nettle_pkcs1_rsa_sha256_encode #define pkcs1_rsa_sha256_encode_digest nettle_pkcs1_rsa_sha256_encode_digest #define pkcs1_rsa_sha512_encode nettle_pkcs1_rsa_sha512_encode #define pkcs1_rsa_sha512_encode_digest nettle_pkcs1_rsa_sha512_encode_digest #define pkcs1_encrypt nettle_pkcs1_encrypt #define pkcs1_decrypt nettle_pkcs1_decrypt struct md5_ctx; struct sha1_ctx; struct sha256_ctx; struct sha512_ctx; int pkcs1_encrypt (size_t key_size, /* For padding */ void *random_ctx, nettle_random_func *random, size_t length, const uint8_t *message, mpz_t m); int pkcs1_decrypt (size_t key_size, const mpz_t m, size_t *length, uint8_t *message); int pkcs1_rsa_digest_encode(mpz_t m, size_t key_size, size_t di_length, const uint8_t *digest_info); int pkcs1_rsa_md5_encode(mpz_t m, size_t length, struct md5_ctx *hash); int pkcs1_rsa_md5_encode_digest(mpz_t m, size_t length, const uint8_t *digest); int pkcs1_rsa_sha1_encode(mpz_t m, size_t length, struct sha1_ctx *hash); int pkcs1_rsa_sha1_encode_digest(mpz_t m, size_t length, const uint8_t *digest); int pkcs1_rsa_sha256_encode(mpz_t m, size_t length, struct sha256_ctx *hash); int pkcs1_rsa_sha256_encode_digest(mpz_t m, size_t length, const uint8_t *digest); int pkcs1_rsa_sha512_encode(mpz_t m, size_t length, struct sha512_ctx *hash); int pkcs1_rsa_sha512_encode_digest(mpz_t m, size_t length, const uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_PKCS1_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/poly1305.h ================================================ /* poly1305.h Poly1305 message authentication code. Copyright (C) 2013 Nikos Mavrogiannopoulos Copyright (C) 2013, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_POLY1305_H_INCLUDED #define NETTLE_POLY1305_H_INCLUDED #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define poly1305_aes_set_key nettle_poly1305_aes_set_key #define poly1305_aes_set_nonce nettle_poly1305_aes_set_nonce #define poly1305_aes_update nettle_poly1305_aes_update #define poly1305_aes_digest nettle_poly1305_aes_digest /* Low level functions/macros for the poly1305 construction. */ #define POLY1305_BLOCK_SIZE 16 struct poly1305_ctx { /* Key, 128-bit value and some cached multiples. */ union { uint32_t r32[6]; uint64_t r64[3]; } r; uint32_t s32[3]; /* State, represented as words of 26, 32 or 64 bits, depending on implementation. */ /* High bits first, to maintain alignment. */ uint32_t hh; union { uint32_t h32[4]; uint64_t h64[2]; } h; }; /* poly1305-aes */ #define POLY1305_AES_KEY_SIZE 32 #define POLY1305_AES_DIGEST_SIZE 16 #define POLY1305_AES_NONCE_SIZE 16 struct poly1305_aes_ctx { /* Keep aes context last, to make it possible to use a general poly1305_update if other variants are added. */ struct poly1305_ctx pctx; uint8_t block[POLY1305_BLOCK_SIZE]; unsigned index; uint8_t nonce[POLY1305_BLOCK_SIZE]; struct aes128_ctx aes; }; /* Also initialize the nonce to zero. */ void poly1305_aes_set_key (struct poly1305_aes_ctx *ctx, const uint8_t *key); /* Optional, if not used, messages get incrementing nonces starting from zero. */ void poly1305_aes_set_nonce (struct poly1305_aes_ctx *ctx, const uint8_t *nonce); /* Update is not aes-specific, but since this is the only implemented variant, we need no more general poly1305_update. */ void poly1305_aes_update (struct poly1305_aes_ctx *ctx, size_t length, const uint8_t *data); /* Also increments the nonce */ void poly1305_aes_digest (struct poly1305_aes_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_POLY1305_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/pss-mgf1.h ================================================ /* pss-mgf1.h PKCS#1 mask generation function 1, used in RSA-PSS (RFC-3447). Copyright (C) 2017 Daiki Ueno This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PSS_MGF1_H_INCLUDED #define NETTLE_PSS_MGF1_H_INCLUDED #include "nettle-meta.h" #include "sha1.h" #include "sha2.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define pss_mgf1 nettle_pss_mgf1 void pss_mgf1(const void *seed, const struct nettle_hash *hash, size_t length, uint8_t *mask); #ifdef __cplusplus } #endif #endif /* NETTLE_PSS_MGF1_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/pss.h ================================================ /* pss.h PKCS#1 RSA-PSS (RFC-3447). Copyright (C) 2017 Daiki Ueno This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PSS_H_INCLUDED #define NETTLE_PSS_H_INCLUDED #include "nettle-meta.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define pss_encode_mgf1 nettle_pss_encode_mgf1 #define pss_verify_mgf1 nettle_pss_verify_mgf1 int pss_encode_mgf1(mpz_t m, size_t bits, const struct nettle_hash *hash, size_t salt_length, const uint8_t *salt, const uint8_t *digest); int pss_verify_mgf1(const mpz_t m, size_t bits, const struct nettle_hash *hash, size_t salt_length, const uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_PSS_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/realloc.h ================================================ /* realloc.h Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_REALLOC_H_INCLUDED #define NETTLE_REALLOC_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif nettle_realloc_func nettle_realloc; nettle_realloc_func nettle_xrealloc; #ifdef __cplusplus } #endif #endif /* NETTLE_REALLOC_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/ripemd160.h ================================================ /* ripemd160.h RIPEMD-160 hash function. Copyright (C) 2011 Andres Mejia This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_RIPEMD160_H_INCLUDED #define NETTLE_RIPEMD160_H_INCLUDED #ifdef __cplusplus extern "C" { #endif #include "nettle-types.h" /* Name mangling */ #define ripemd160_init nettle_ripemd160_init #define ripemd160_update nettle_ripemd160_update #define ripemd160_digest nettle_ripemd160_digest /* RIPEMD160 */ #define RIPEMD160_DIGEST_SIZE 20 #define RIPEMD160_BLOCK_SIZE 64 /* For backwards compatibility */ #define RIPEMD160_DATA_SIZE RIPEMD160_BLOCK_SIZE /* Digest is kept internally as 5 32-bit words. */ #define _RIPEMD160_DIGEST_LENGTH 5 struct ripemd160_ctx { uint32_t state[_RIPEMD160_DIGEST_LENGTH]; uint64_t count; /* 64-bit block count */ unsigned int index; uint8_t block[RIPEMD160_BLOCK_SIZE]; }; void ripemd160_init(struct ripemd160_ctx *ctx); void ripemd160_update(struct ripemd160_ctx *ctx, size_t length, const uint8_t *data); void ripemd160_digest(struct ripemd160_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_RIPEMD160_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/rsa.h ================================================ /* rsa.h The RSA publickey algorithm. Copyright (C) 2001, 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_RSA_H_INCLUDED #define NETTLE_RSA_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #include "md5.h" #include "sha1.h" #include "sha2.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define rsa_public_key_init nettle_rsa_public_key_init #define rsa_public_key_clear nettle_rsa_public_key_clear #define rsa_public_key_prepare nettle_rsa_public_key_prepare #define rsa_private_key_init nettle_rsa_private_key_init #define rsa_private_key_clear nettle_rsa_private_key_clear #define rsa_private_key_prepare nettle_rsa_private_key_prepare #define rsa_pkcs1_verify nettle_rsa_pkcs1_verify #define rsa_pkcs1_sign nettle_rsa_pkcs1_sign #define rsa_pkcs1_sign_tr nettle_rsa_pkcs1_sign_tr #define rsa_md5_sign nettle_rsa_md5_sign #define rsa_md5_sign_tr nettle_rsa_md5_sign_tr #define rsa_md5_verify nettle_rsa_md5_verify #define rsa_sha1_sign nettle_rsa_sha1_sign #define rsa_sha1_sign_tr nettle_rsa_sha1_sign_tr #define rsa_sha1_verify nettle_rsa_sha1_verify #define rsa_sha256_sign nettle_rsa_sha256_sign #define rsa_sha256_sign_tr nettle_rsa_sha256_sign_tr #define rsa_sha256_verify nettle_rsa_sha256_verify #define rsa_sha512_sign nettle_rsa_sha512_sign #define rsa_sha512_sign_tr nettle_rsa_sha512_sign_tr #define rsa_sha512_verify nettle_rsa_sha512_verify #define rsa_md5_sign_digest nettle_rsa_md5_sign_digest #define rsa_md5_sign_digest_tr nettle_rsa_md5_sign_digest_tr #define rsa_md5_verify_digest nettle_rsa_md5_verify_digest #define rsa_sha1_sign_digest nettle_rsa_sha1_sign_digest #define rsa_sha1_sign_digest_tr nettle_rsa_sha1_sign_digest_tr #define rsa_sha1_verify_digest nettle_rsa_sha1_verify_digest #define rsa_sha256_sign_digest nettle_rsa_sha256_sign_digest #define rsa_sha256_sign_digest_tr nettle_rsa_sha256_sign_digest_tr #define rsa_sha256_verify_digest nettle_rsa_sha256_verify_digest #define rsa_sha512_sign_digest nettle_rsa_sha512_sign_digest #define rsa_sha512_sign_digest_tr nettle_rsa_sha512_sign_digest_tr #define rsa_sha512_verify_digest nettle_rsa_sha512_verify_digest #define rsa_pss_sha256_sign_digest_tr nettle_rsa_pss_sha256_sign_digest_tr #define rsa_pss_sha256_verify_digest nettle_rsa_pss_sha256_verify_digest #define rsa_pss_sha384_sign_digest_tr nettle_rsa_pss_sha384_sign_digest_tr #define rsa_pss_sha384_verify_digest nettle_rsa_pss_sha384_verify_digest #define rsa_pss_sha512_sign_digest_tr nettle_rsa_pss_sha512_sign_digest_tr #define rsa_pss_sha512_verify_digest nettle_rsa_pss_sha512_verify_digest #define rsa_encrypt nettle_rsa_encrypt #define rsa_decrypt nettle_rsa_decrypt #define rsa_decrypt_tr nettle_rsa_decrypt_tr #define rsa_sec_decrypt nettle_rsa_sec_decrypt #define rsa_compute_root nettle_rsa_compute_root #define rsa_compute_root_tr nettle_rsa_compute_root_tr #define rsa_generate_keypair nettle_rsa_generate_keypair #define rsa_keypair_to_sexp nettle_rsa_keypair_to_sexp #define rsa_keypair_from_sexp_alist nettle_rsa_keypair_from_sexp_alist #define rsa_keypair_from_sexp nettle_rsa_keypair_from_sexp #define rsa_public_key_from_der_iterator nettle_rsa_public_key_from_der_iterator #define rsa_private_key_from_der_iterator nettle_rsa_private_key_from_der_iterator #define rsa_keypair_from_der nettle_rsa_keypair_from_der #define rsa_keypair_to_openpgp nettle_rsa_keypair_to_openpgp /* This limit is somewhat arbitrary. Technically, the smallest modulo which makes sense at all is 15 = 3*5, phi(15) = 8, size 4 bits. But for ridiculously small keys, not all odd e are possible (e.g., for 5 bits, the only possible modulo is 3*7 = 21, phi(21) = 12, and e = 3 don't work). The smallest size that makes sense with pkcs#1, and which allows RSA encryption of one byte messages, is 12 octets, 89 bits. */ #define RSA_MINIMUM_N_OCTETS 12 #define RSA_MINIMUM_N_BITS (8*RSA_MINIMUM_N_OCTETS - 7) struct rsa_public_key { /* Size of the modulo, in octets. This is also the size of all * signatures that are created or verified with this key. */ size_t size; /* Modulo */ mpz_t n; /* Public exponent */ mpz_t e; }; struct rsa_private_key { size_t size; /* d is filled in by the key generation function; otherwise it's * completely unused. */ mpz_t d; /* The two factors */ mpz_t p; mpz_t q; /* d % (p-1), i.e. a e = 1 (mod (p-1)) */ mpz_t a; /* d % (q-1), i.e. b e = 1 (mod (q-1)) */ mpz_t b; /* modular inverse of q , i.e. c q = 1 (mod p) */ mpz_t c; }; /* Signing a message works as follows: * * Store the private key in a rsa_private_key struct. * * Call rsa_private_key_prepare. This initializes the size attribute * to the length of a signature. * * Initialize a hashing context, by callling * md5_init * * Hash the message by calling * md5_update * * Create the signature by calling * rsa_md5_sign * * The signature is represented as a mpz_t bignum. This call also * resets the hashing context. * * When done with the key and signature, don't forget to call * mpz_clear. */ /* Calls mpz_init to initialize bignum storage. */ void rsa_public_key_init(struct rsa_public_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void rsa_public_key_clear(struct rsa_public_key *key); int rsa_public_key_prepare(struct rsa_public_key *key); /* Calls mpz_init to initialize bignum storage. */ void rsa_private_key_init(struct rsa_private_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void rsa_private_key_clear(struct rsa_private_key *key); int rsa_private_key_prepare(struct rsa_private_key *key); /* PKCS#1 style signatures */ int rsa_pkcs1_sign(const struct rsa_private_key *key, size_t length, const uint8_t *digest_info, mpz_t s); int rsa_pkcs1_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t length, const uint8_t *digest_info, mpz_t s); int rsa_pkcs1_verify(const struct rsa_public_key *key, size_t length, const uint8_t *digest_info, const mpz_t signature); int rsa_md5_sign(const struct rsa_private_key *key, struct md5_ctx *hash, mpz_t signature); int rsa_md5_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct md5_ctx *hash, mpz_t s); int rsa_md5_verify(const struct rsa_public_key *key, struct md5_ctx *hash, const mpz_t signature); int rsa_sha1_sign(const struct rsa_private_key *key, struct sha1_ctx *hash, mpz_t signature); int rsa_sha1_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha1_ctx *hash, mpz_t s); int rsa_sha1_verify(const struct rsa_public_key *key, struct sha1_ctx *hash, const mpz_t signature); int rsa_sha256_sign(const struct rsa_private_key *key, struct sha256_ctx *hash, mpz_t signature); int rsa_sha256_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha256_ctx *hash, mpz_t s); int rsa_sha256_verify(const struct rsa_public_key *key, struct sha256_ctx *hash, const mpz_t signature); int rsa_sha512_sign(const struct rsa_private_key *key, struct sha512_ctx *hash, mpz_t signature); int rsa_sha512_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha512_ctx *hash, mpz_t s); int rsa_sha512_verify(const struct rsa_public_key *key, struct sha512_ctx *hash, const mpz_t signature); /* Variants taking the digest as argument. */ int rsa_md5_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_md5_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_md5_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); int rsa_sha1_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_sha1_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_sha1_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); int rsa_sha256_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_sha256_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_sha256_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); int rsa_sha512_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_sha512_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_sha512_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); /* PSS style signatures */ int rsa_pss_sha256_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t salt_length, const uint8_t *salt, const uint8_t *digest, mpz_t s); int rsa_pss_sha256_verify_digest(const struct rsa_public_key *key, size_t salt_length, const uint8_t *digest, const mpz_t signature); int rsa_pss_sha384_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t salt_length, const uint8_t *salt, const uint8_t *digest, mpz_t s); int rsa_pss_sha384_verify_digest(const struct rsa_public_key *key, size_t salt_length, const uint8_t *digest, const mpz_t signature); int rsa_pss_sha512_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t salt_length, const uint8_t *salt, const uint8_t *digest, mpz_t s); int rsa_pss_sha512_verify_digest(const struct rsa_public_key *key, size_t salt_length, const uint8_t *digest, const mpz_t signature); /* RSA encryption, using PKCS#1 */ /* These functions uses the v1.5 padding. What should the v2 (OAEP) * functions be called? */ /* Returns 1 on success, 0 on failure, which happens if the * message is too long for the key. */ int rsa_encrypt(const struct rsa_public_key *key, /* For padding */ void *random_ctx, nettle_random_func *random, size_t length, const uint8_t *cleartext, mpz_t cipher); /* Message must point to a buffer of size *LENGTH. KEY->size is enough * for all valid messages. On success, *LENGTH is updated to reflect * the actual length of the message. Returns 1 on success, 0 on * failure, which happens if decryption failed or if the message * didn't fit. */ int rsa_decrypt(const struct rsa_private_key *key, size_t *length, uint8_t *cleartext, const mpz_t ciphertext); /* Timing-resistant version, using randomized RSA blinding. */ int rsa_decrypt_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t *length, uint8_t *message, const mpz_t gibberish); /* like rsa_decrypt_tr but with additional side-channel resistance. * NOTE: the length of the final message must be known in advance. */ int rsa_sec_decrypt(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t length, uint8_t *message, const mpz_t gibberish); /* Compute x, the e:th root of m. Calling it with x == m is allowed. It is required that 0 <= m < n. */ void rsa_compute_root(const struct rsa_private_key *key, mpz_t x, const mpz_t m); /* Safer variant, using RSA blinding, and checking the result after CRT. It is required that 0 <= m < n. */ int rsa_compute_root_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, mpz_t x, const mpz_t m); /* Key generation */ /* Note that the key structs must be initialized first. */ int rsa_generate_keypair(struct rsa_public_key *pub, struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress, /* Desired size of modulo, in bits */ unsigned n_size, /* Desired size of public exponent, in bits. If * zero, the passed in value pub->e is used. */ unsigned e_size); #define RSA_SIGN(key, algorithm, ctx, length, data, signature) ( \ algorithm##_update(ctx, length, data), \ rsa_##algorithm##_sign(key, ctx, signature) \ ) #define RSA_VERIFY(key, algorithm, ctx, length, data, signature) ( \ algorithm##_update(ctx, length, data), \ rsa_##algorithm##_verify(key, ctx, signature) \ ) /* Keys in sexp form. */ struct nettle_buffer; /* Generates a public-key expression if PRIV is NULL .*/ int rsa_keypair_to_sexp(struct nettle_buffer *buffer, const char *algorithm_name, /* NULL means "rsa" */ const struct rsa_public_key *pub, const struct rsa_private_key *priv); struct sexp_iterator; int rsa_keypair_from_sexp_alist(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, struct sexp_iterator *i); /* If PRIV is NULL, expect a public-key expression. If PUB is NULL, * expect a private key expression and ignore the parts not needed for * the public key. */ /* Keys must be initialized before calling this function, as usual. */ int rsa_keypair_from_sexp(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, size_t length, const uint8_t *expr); /* Keys in PKCS#1 format. */ struct asn1_der_iterator; int rsa_public_key_from_der_iterator(struct rsa_public_key *pub, unsigned limit, struct asn1_der_iterator *i); int rsa_private_key_from_der_iterator(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, struct asn1_der_iterator *i); /* For public keys, use PRIV == NULL */ int rsa_keypair_from_der(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, size_t length, const uint8_t *data); /* OpenPGP format. Experimental interface, subject to change. */ int rsa_keypair_to_openpgp(struct nettle_buffer *buffer, const struct rsa_public_key *pub, const struct rsa_private_key *priv, /* A single user id. NUL-terminated utf8. */ const char *userid); #ifdef __cplusplus } #endif #endif /* NETTLE_RSA_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/salsa20.h ================================================ /* salsa20.h The Salsa20 stream cipher. Copyright (C) 2012 Simon Josefsson Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SALSA20_H_INCLUDED #define NETTLE_SALSA20_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define salsa20_set_key nettle_salsa20_set_key #define salsa20_128_set_key nettle_salsa20_128_set_key #define salsa20_256_set_key nettle_salsa20_256_set_key #define salsa20_set_nonce nettle_salsa20_set_nonce #define salsa20_crypt nettle_salsa20_crypt #define salsa20r12_crypt nettle_salsa20r12_crypt /* Alias for backwards compatibility */ #define salsa20_set_iv nettle_salsa20_set_nonce /* In octets.*/ #define SALSA20_128_KEY_SIZE 16 #define SALSA20_256_KEY_SIZE 32 #define SALSA20_BLOCK_SIZE 64 #define SALSA20_NONCE_SIZE 8 #define SALSA20_IV_SIZE SALSA20_NONCE_SIZE /* Aliases */ #define SALSA20_MIN_KEY_SIZE 16 #define SALSA20_MAX_KEY_SIZE 32 #define SALSA20_KEY_SIZE 32 #define _SALSA20_INPUT_LENGTH 16 struct salsa20_ctx { /* Indices 1-4 and 11-14 holds the key (two identical copies for the shorter key size), indices 0, 5, 10, 15 are constant, indices 6, 7 are the IV, and indices 8, 9 are the block counter: C K K K K C I I B B C K K K K C */ uint32_t input[_SALSA20_INPUT_LENGTH]; }; void salsa20_128_set_key(struct salsa20_ctx *ctx, const uint8_t *key); void salsa20_256_set_key(struct salsa20_ctx *ctx, const uint8_t *key); void salsa20_set_key(struct salsa20_ctx *ctx, size_t length, const uint8_t *key); void salsa20_set_nonce(struct salsa20_ctx *ctx, const uint8_t *nonce); void salsa20_crypt(struct salsa20_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void salsa20r12_crypt(struct salsa20_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SALSA20_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/serpent.h ================================================ /* serpent.h The serpent block cipher. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Serpent is a 128-bit block cipher that accepts a key size of 256 * bits, designed by Ross Anderson, Eli Biham, and Lars Knudsen. See * http://www.cl.cam.ac.uk/~rja14/serpent.html for details. */ #ifndef NETTLE_SERPENT_H_INCLUDED #define NETTLE_SERPENT_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define serpent_set_key nettle_serpent_set_key #define serpent128_set_key nettle_serpent128_set_key #define serpent192_set_key nettle_serpent192_set_key #define serpent256_set_key nettle_serpent256_set_key #define serpent_encrypt nettle_serpent_encrypt #define serpent_decrypt nettle_serpent_decrypt #define SERPENT_BLOCK_SIZE 16 /* Other key lengths are possible, but the design of Serpent makes * smaller key lengths quite pointless; they cheated with the AES * requirements, using a 256-bit key length exclusively and just * padding it out if the desired key length was less, so there really * is no advantage to using key lengths less than 256 bits. */ #define SERPENT_KEY_SIZE 32 /* Allow keys of size 128 <= bits <= 256 */ #define SERPENT_MIN_KEY_SIZE 16 #define SERPENT_MAX_KEY_SIZE 32 #define SERPENT128_KEY_SIZE 16 #define SERPENT192_KEY_SIZE 24 #define SERPENT256_KEY_SIZE 32 struct serpent_ctx { uint32_t keys[33][4]; /* key schedule */ }; void serpent_set_key(struct serpent_ctx *ctx, size_t length, const uint8_t *key); void serpent128_set_key(struct serpent_ctx *ctx, const uint8_t *key); void serpent192_set_key(struct serpent_ctx *ctx, const uint8_t *key); void serpent256_set_key(struct serpent_ctx *ctx, const uint8_t *key); void serpent_encrypt(const struct serpent_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void serpent_decrypt(const struct serpent_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SERPENT_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/sexp.h ================================================ /* sexp.h Parsing s-expressions. Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SEXP_H_INCLUDED #define NETTLE_SEXP_H_INCLUDED #include #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sexp_iterator_first nettle_sexp_iterator_first #define sexp_transport_iterator_first nettle_sexp_transport_iterator_first #define sexp_iterator_next nettle_sexp_iterator_next #define sexp_iterator_enter_list nettle_sexp_iterator_enter_list #define sexp_iterator_exit_list nettle_sexp_iterator_exit_list #define sexp_iterator_subexpr nettle_sexp_iterator_subexpr #define sexp_iterator_get_uint32 nettle_sexp_iterator_get_uint32 #define sexp_iterator_check_type nettle_sexp_iterator_check_type #define sexp_iterator_check_types nettle_sexp_iterator_check_types #define sexp_iterator_assoc nettle_sexp_iterator_assoc #define sexp_format nettle_sexp_format #define sexp_vformat nettle_sexp_vformat #define sexp_transport_format nettle_sexp_transport_format #define sexp_transport_vformat nettle_sexp_transport_vformat #define sexp_token_chars nettle_sexp_token_chars enum sexp_type { SEXP_ATOM, SEXP_LIST, SEXP_END }; struct sexp_iterator { size_t length; const uint8_t *buffer; /* Points at the start of the current sub expression. */ size_t start; /* If type is SEXP_LIST, pos points at the start of the current * element. Otherwise, it points at the end. */ size_t pos; unsigned level; enum sexp_type type; size_t display_length; const uint8_t *display; size_t atom_length; const uint8_t *atom; }; /* All these functions return 1 on success, 0 on failure */ /* Initializes the iterator. */ int sexp_iterator_first(struct sexp_iterator *iterator, size_t length, const uint8_t *input); /* NOTE: Decodes the input string in place */ int sexp_transport_iterator_first(struct sexp_iterator *iterator, size_t length, uint8_t *input); int sexp_iterator_next(struct sexp_iterator *iterator); /* Current element must be a list. */ int sexp_iterator_enter_list(struct sexp_iterator *iterator); /* Skips the rest of the current list */ int sexp_iterator_exit_list(struct sexp_iterator *iterator); #if 0 /* Skips out of as many lists as necessary to get back to the given * level. */ int sexp_iterator_exit_lists(struct sexp_iterator *iterator, unsigned level); #endif /* Gets start and length of the current subexpression. Implies * sexp_iterator_next. */ const uint8_t * sexp_iterator_subexpr(struct sexp_iterator *iterator, size_t *length); int sexp_iterator_get_uint32(struct sexp_iterator *iterator, uint32_t *x); /* Checks the type of the current expression, which should be a list * * ( ...) */ int sexp_iterator_check_type(struct sexp_iterator *iterator, const char *type); const char * sexp_iterator_check_types(struct sexp_iterator *iterator, unsigned ntypes, const char * const *types); /* Current element must be a list. Looks up element of type * * (key rest...) * * For a matching key, the corresponding iterator is initialized * pointing at the start of REST. * * On success, exits the current list. */ int sexp_iterator_assoc(struct sexp_iterator *iterator, unsigned nkeys, const char * const *keys, struct sexp_iterator *values); /* Output functions. What is a reasonable API for this? It seems * ugly to have to reimplement string streams. */ /* Declared for real in buffer.h */ struct nettle_buffer; /* Returns the number of output characters, or 0 on out of memory. If * buffer == NULL, just compute length. * * Format strings can contained matched parentheses, tokens ("foo" in * the format string is formatted as "3:foo"), whitespace (which * separates tokens but is otherwise ignored) and the following * formatting specifiers: * * %s String represented as size_t length, const uint8_t *data. * * %t Optional display type, represented as * size_t display_length, const uint8_t *display, * display == NULL means no display type. * * %i Non-negative small integer, uint32_t. * * %b Non-negative bignum, mpz_t. * * %l Literal string (no length added), typically a balanced * subexpression. Represented as size_t length, const uint8_t * *data. * * %(, %) Allows insertion of unbalanced parenthesis. * * Modifiers: * * %0 For %s, %t and %l, says that there's no length argument, * instead the string is NUL-terminated, and there's only one * const uint8_t * argument. */ size_t sexp_format(struct nettle_buffer *buffer, const char *format, ...); size_t sexp_vformat(struct nettle_buffer *buffer, const char *format, va_list args); size_t sexp_transport_format(struct nettle_buffer *buffer, const char *format, ...); size_t sexp_transport_vformat(struct nettle_buffer *buffer, const char *format, va_list args); #ifdef __cplusplus } #endif #endif /* NETTLE_SEXP_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/sha.h ================================================ /* sha.h This file is deprecated, and provided only for backwards compatibility with earlier versions of Nettle. Please use sha1.h and/or sha2.h instead. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA_H_INCLUDED #define NETTLE_SHA_H_INCLUDED #include "sha1.h" #include "sha2.h" #endif /* NETTLE_SHA_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/sha1.h ================================================ /* sha1.h The sha1 hash function. Copyright (C) 2001, 2012 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA1_H_INCLUDED #define NETTLE_SHA1_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sha1_init nettle_sha1_init #define sha1_update nettle_sha1_update #define sha1_digest nettle_sha1_digest #define sha1_compress nettle_sha1_compress /* SHA1 */ #define SHA1_DIGEST_SIZE 20 #define SHA1_BLOCK_SIZE 64 /* For backwards compatibility */ #define SHA1_DATA_SIZE SHA1_BLOCK_SIZE /* Digest is kept internally as 5 32-bit words. */ #define _SHA1_DIGEST_LENGTH 5 struct sha1_ctx { uint32_t state[_SHA1_DIGEST_LENGTH]; /* State variables */ uint64_t count; /* 64-bit block count */ unsigned int index; /* index into buffer */ uint8_t block[SHA1_BLOCK_SIZE]; /* SHA1 data buffer */ }; void sha1_init(struct sha1_ctx *ctx); void sha1_update(struct sha1_ctx *ctx, size_t length, const uint8_t *data); void sha1_digest(struct sha1_ctx *ctx, size_t length, uint8_t *digest); /* SHA1 compression function. STATE points to 5 uint32_t words, and DATA points to 64 bytes of input data, possibly unaligned. */ void sha1_compress(uint32_t *state, const uint8_t *data); /* Old name, for backwards compatibility. */ #define _nettle_sha1_compress nettle_sha1_compress #ifdef __cplusplus } #endif #endif /* NETTLE_SHA1_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/sha2.h ================================================ /* sha2.h The sha2 family of hash functions. Copyright (C) 2001, 2012 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA2_H_INCLUDED #define NETTLE_SHA2_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sha224_init nettle_sha224_init #define sha224_digest nettle_sha224_digest #define sha256_init nettle_sha256_init #define sha256_update nettle_sha256_update #define sha256_digest nettle_sha256_digest #define sha256_compress nettle_sha256_compress #define sha384_init nettle_sha384_init #define sha384_digest nettle_sha384_digest #define sha512_init nettle_sha512_init #define sha512_update nettle_sha512_update #define sha512_digest nettle_sha512_digest #define sha512_compress nettle_sha512_compress #define sha512_224_init nettle_sha512_224_init #define sha512_224_digest nettle_sha512_224_digest #define sha512_256_init nettle_sha512_256_init #define sha512_256_digest nettle_sha512_256_digest /* For backwards compatibility */ #define SHA224_DATA_SIZE SHA256_BLOCK_SIZE #define SHA256_DATA_SIZE SHA256_BLOCK_SIZE #define SHA512_DATA_SIZE SHA512_BLOCK_SIZE #define SHA384_DATA_SIZE SHA512_BLOCK_SIZE /* SHA256 */ #define SHA256_DIGEST_SIZE 32 #define SHA256_BLOCK_SIZE 64 /* Digest is kept internally as 8 32-bit words. */ #define _SHA256_DIGEST_LENGTH 8 struct sha256_ctx { uint32_t state[_SHA256_DIGEST_LENGTH]; /* State variables */ uint64_t count; /* 64-bit block count */ unsigned int index; /* index into buffer */ uint8_t block[SHA256_BLOCK_SIZE]; /* SHA256 data buffer */ }; void sha256_init(struct sha256_ctx *ctx); void sha256_update(struct sha256_ctx *ctx, size_t length, const uint8_t *data); void sha256_digest(struct sha256_ctx *ctx, size_t length, uint8_t *digest); void sha256_compress(uint32_t *state, const uint8_t *input); /* SHA224, a truncated SHA256 with different initial state. */ #define SHA224_DIGEST_SIZE 28 #define SHA224_BLOCK_SIZE SHA256_BLOCK_SIZE #define sha224_ctx sha256_ctx void sha224_init(struct sha256_ctx *ctx); #define sha224_update nettle_sha256_update void sha224_digest(struct sha256_ctx *ctx, size_t length, uint8_t *digest); /* SHA512 */ #define SHA512_DIGEST_SIZE 64 #define SHA512_BLOCK_SIZE 128 /* Digest is kept internally as 8 64-bit words. */ #define _SHA512_DIGEST_LENGTH 8 struct sha512_ctx { uint64_t state[_SHA512_DIGEST_LENGTH]; /* State variables */ uint64_t count_low, count_high; /* 128-bit block count */ unsigned int index; /* index into buffer */ uint8_t block[SHA512_BLOCK_SIZE]; /* SHA512 data buffer */ }; void sha512_init(struct sha512_ctx *ctx); void sha512_update(struct sha512_ctx *ctx, size_t length, const uint8_t *data); void sha512_digest(struct sha512_ctx *ctx, size_t length, uint8_t *digest); void sha512_compress(uint64_t *state, const uint8_t *input); /* SHA384, a truncated SHA512 with different initial state. */ #define SHA384_DIGEST_SIZE 48 #define SHA384_BLOCK_SIZE SHA512_BLOCK_SIZE #define sha384_ctx sha512_ctx void sha384_init(struct sha512_ctx *ctx); #define sha384_update nettle_sha512_update void sha384_digest(struct sha512_ctx *ctx, size_t length, uint8_t *digest); /* SHA512_224 and SHA512_256, two truncated versions of SHA512 with different initial states. */ #define SHA512_224_DIGEST_SIZE 28 #define SHA512_224_BLOCK_SIZE SHA512_BLOCK_SIZE #define sha512_224_ctx sha512_ctx void sha512_224_init(struct sha512_224_ctx *ctx); #define sha512_224_update nettle_sha512_update void sha512_224_digest(struct sha512_224_ctx *ctx, size_t length, uint8_t *digest); #define SHA512_256_DIGEST_SIZE 32 #define SHA512_256_BLOCK_SIZE SHA512_BLOCK_SIZE #define sha512_256_ctx sha512_ctx void sha512_256_init(struct sha512_256_ctx *ctx); #define sha512_256_update nettle_sha512_update void sha512_256_digest(struct sha512_256_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_SHA2_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/sha3.h ================================================ /* sha3.h The sha3 hash function (aka Keccak). Copyright (C) 2012 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA3_H_INCLUDED #define NETTLE_SHA3_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sha3_permute nettle_sha3_permute #define sha3_224_init nettle_sha3_224_init #define sha3_224_update nettle_sha3_224_update #define sha3_224_digest nettle_sha3_224_digest #define sha3_256_init nettle_sha3_256_init #define sha3_256_update nettle_sha3_256_update #define sha3_256_digest nettle_sha3_256_digest #define sha3_256_shake nettle_sha3_256_shake #define sha3_384_init nettle_sha3_384_init #define sha3_384_update nettle_sha3_384_update #define sha3_384_digest nettle_sha3_384_digest #define sha3_512_init nettle_sha3_512_init #define sha3_512_update nettle_sha3_512_update #define sha3_512_digest nettle_sha3_512_digest /* Indicates that SHA3 is the NIST FIPS 202 version. */ #define NETTLE_SHA3_FIPS202 1 /* The sha3 state is a 5x5 matrix of 64-bit words. In the notation of Keccak description, S[x,y] is element x + 5*y, so if x is interpreted as the row index and y the column index, it is stored in column-major order. */ #define SHA3_STATE_LENGTH 25 /* The "width" is 1600 bits or 200 octets */ struct sha3_state { uint64_t a[SHA3_STATE_LENGTH]; }; void sha3_permute (struct sha3_state *state); /* The "capacity" is set to 2*(digest size), 512 bits or 64 octets. The "rate" is the width - capacity, or width - 2 * (digest size). */ #define SHA3_224_DIGEST_SIZE 28 #define SHA3_224_BLOCK_SIZE 144 #define SHA3_256_DIGEST_SIZE 32 #define SHA3_256_BLOCK_SIZE 136 #define SHA3_384_DIGEST_SIZE 48 #define SHA3_384_BLOCK_SIZE 104 #define SHA3_512_DIGEST_SIZE 64 #define SHA3_512_BLOCK_SIZE 72 /* For backwards compatibility */ #define SHA3_224_DATA_SIZE SHA3_224_BLOCK_SIZE #define SHA3_256_DATA_SIZE SHA3_256_BLOCK_SIZE #define SHA3_384_DATA_SIZE SHA3_384_BLOCK_SIZE #define SHA3_512_DATA_SIZE SHA3_512_BLOCK_SIZE struct sha3_224_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_224_BLOCK_SIZE]; }; void sha3_224_init (struct sha3_224_ctx *ctx); void sha3_224_update (struct sha3_224_ctx *ctx, size_t length, const uint8_t *data); void sha3_224_digest(struct sha3_224_ctx *ctx, size_t length, uint8_t *digest); struct sha3_256_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_256_BLOCK_SIZE]; }; void sha3_256_init (struct sha3_256_ctx *ctx); void sha3_256_update (struct sha3_256_ctx *ctx, size_t length, const uint8_t *data); void sha3_256_digest(struct sha3_256_ctx *ctx, size_t length, uint8_t *digest); /* Alternative digest function implementing shake256, with arbitrary digest size */ void sha3_256_shake(struct sha3_256_ctx *ctx, size_t length, uint8_t *digest); struct sha3_384_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_384_BLOCK_SIZE]; }; void sha3_384_init (struct sha3_384_ctx *ctx); void sha3_384_update (struct sha3_384_ctx *ctx, size_t length, const uint8_t *data); void sha3_384_digest(struct sha3_384_ctx *ctx, size_t length, uint8_t *digest); struct sha3_512_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_512_BLOCK_SIZE]; }; void sha3_512_init (struct sha3_512_ctx *ctx); void sha3_512_update (struct sha3_512_ctx *ctx, size_t length, const uint8_t *data); void sha3_512_digest(struct sha3_512_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_SHA3_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/siv-cmac.h ================================================ /* siv-cmac.h AES-SIV, RFC5297 Copyright (C) 2017 Nikos Mavrogiannopoulos This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SIV_H_INCLUDED #define NETTLE_SIV_H_INCLUDED #include "nettle-types.h" #include "nettle-meta.h" #include "cmac.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define siv_cmac_set_key nettle_siv_cmac_set_key #define siv_cmac_encrypt_message nettle_siv_cmac_encrypt_message #define siv_cmac_decrypt_message nettle_siv_cmac_decrypt_message #define siv_cmac_aes128_set_key nettle_siv_cmac_aes128_set_key #define siv_cmac_aes128_encrypt_message nettle_siv_cmac_aes128_encrypt_message #define siv_cmac_aes128_decrypt_message nettle_siv_cmac_aes128_decrypt_message #define siv_cmac_aes256_set_key nettle_siv_cmac_aes256_set_key #define siv_cmac_aes256_encrypt_message nettle_siv_cmac_aes256_encrypt_message #define siv_cmac_aes256_decrypt_message nettle_siv_cmac_aes256_decrypt_message /* For SIV, the block size of the underlying cipher shall be 128 bits. */ #define SIV_BLOCK_SIZE 16 #define SIV_DIGEST_SIZE 16 #define SIV_MIN_NONCE_SIZE 1 void siv_cmac_set_key(struct cmac128_key *cmac_key, void *cmac_cipher, void *ctr_cipher, const struct nettle_cipher *nc, const uint8_t *key); void siv_cmac_encrypt_message(const struct cmac128_key *cmac_key, const void *cmac_cipher_ctx, const struct nettle_cipher *nc, const void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_cmac_decrypt_message(const struct cmac128_key *cmac_key, const void *cmac_cipher, const struct nettle_cipher *nc, const void *ctr_cipher, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* * SIV mode requires the aad and plaintext when building the IV, which * prevents streaming processing and it incompatible with the AEAD API. */ #define SIV_CMAC_CTX(type) { struct cmac128_key cmac_key; type cmac_cipher; type ctr_cipher; } /* SIV_CMAC_AES128 */ #define SIV_CMAC_AES128_KEY_SIZE 32 struct siv_cmac_aes128_ctx SIV_CMAC_CTX(struct aes128_ctx); void siv_cmac_aes128_set_key(struct siv_cmac_aes128_ctx *ctx, const uint8_t *key); void siv_cmac_aes128_encrypt_message(const struct siv_cmac_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_cmac_aes128_decrypt_message(const struct siv_cmac_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* SIV_CMAC_AES256 */ #define SIV_CMAC_AES256_KEY_SIZE 64 struct siv_cmac_aes256_ctx SIV_CMAC_CTX(struct aes256_ctx); void siv_cmac_aes256_set_key(struct siv_cmac_aes256_ctx *ctx, const uint8_t *key); void siv_cmac_aes256_encrypt_message(const struct siv_cmac_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_cmac_aes256_decrypt_message(const struct siv_cmac_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SIV_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/siv-gcm.h ================================================ /* siv-gcm.h AES-GCM-SIV, RFC8452 Copyright (C) 2022 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SIV_GCM_H_INCLUDED #define NETTLE_SIV_GCM_H_INCLUDED #include "nettle-types.h" #include "nettle-meta.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define siv_gcm_encrypt_message nettle_siv_gcm_encrypt_message #define siv_gcm_decrypt_message nettle_siv_gcm_decrypt_message #define siv_gcm_aes128_encrypt_message nettle_siv_gcm_aes128_encrypt_message #define siv_gcm_aes128_decrypt_message nettle_siv_gcm_aes128_decrypt_message #define siv_gcm_aes256_encrypt_message nettle_siv_gcm_aes256_encrypt_message #define siv_gcm_aes256_decrypt_message nettle_siv_gcm_aes256_decrypt_message /* For AES-GCM-SIV, the block size of the underlying cipher shall be 128 bits. */ #define SIV_GCM_BLOCK_SIZE 16 #define SIV_GCM_DIGEST_SIZE 16 #define SIV_GCM_NONCE_SIZE 12 /* Generic interface. NC must be a block cipher with 128-bit block size, and keysize that is a multiple of 64 bits, such as AES-128 or AES-256. */ void siv_gcm_encrypt_message (const struct nettle_cipher *nc, const void *ctx, void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_gcm_decrypt_message (const struct nettle_cipher *nc, const void *ctx, void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* AEAD_AES_128_GCM_SIV */ void siv_gcm_aes128_encrypt_message (const struct aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_gcm_aes128_decrypt_message (const struct aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* AEAD_AES_256_GCM_SIV */ void siv_gcm_aes256_encrypt_message (const struct aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_gcm_aes256_decrypt_message (const struct aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SIV_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/sm3.h ================================================ /* sm3.h The SM3 hash function. Copyright (C) 2017 Jia Zhang Copyright (C) 2021 Tianjia Zhang This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SM3_H_INCLUDED #define NETTLE_SM3_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sm3_init nettle_sm3_init #define sm3_update nettle_sm3_update #define sm3_digest nettle_sm3_digest #define SM3_DIGEST_SIZE 32 #define SM3_BLOCK_SIZE 64 /* Digest is kept internally as 8 32-bit words. */ #define _SM3_DIGEST_LENGTH 8 struct sm3_ctx { uint32_t state[_SM3_DIGEST_LENGTH]; uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[SM3_BLOCK_SIZE]; /* Block buffer */ }; void sm3_init(struct sm3_ctx *ctx); void sm3_update(struct sm3_ctx *ctx, size_t length, const uint8_t *data); void sm3_digest(struct sm3_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_SM3_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/sm4.h ================================================ /* sm4.h Copyright (C) 2022 Tianjia Zhang This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SM4_H_INCLUDED #define NETTLE_SM4_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sm4_set_encrypt_key nettle_sm4_set_encrypt_key #define sm4_set_decrypt_key nettle_sm4_set_decrypt_key #define sm4_crypt nettle_sm4_crypt #define SM4_BLOCK_SIZE 16 #define SM4_KEY_SIZE 16 struct sm4_ctx { uint32_t rkey[32]; }; void sm4_set_encrypt_key(struct sm4_ctx *ctx, const uint8_t *key); void sm4_set_decrypt_key(struct sm4_ctx *ctx, const uint8_t *key); void sm4_crypt(const struct sm4_ctx *context, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SM4_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/streebog.h ================================================ /* streebog.h The Streebog family of hash functions. Copyright (C) 2020 Dmitry Baryshkov This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_STREEBOG_H_INCLUDED #define NETTLE_STREEBOG_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define streebog256_init nettle_streebog256_init #define streebog256_digest nettle_streebog256_digest #define streebog512_init nettle_streebog512_init #define streebog512_update nettle_streebog512_update #define streebog512_digest nettle_streebog512_digest /* STREEBOG512 */ #define STREEBOG512_DIGEST_SIZE 64 #define STREEBOG512_BLOCK_SIZE 64 /* Digest is kept internally as 8 64-bit words. */ #define _STREEBOG512_DIGEST_LENGTH 8 struct streebog512_ctx { uint64_t state[_STREEBOG512_DIGEST_LENGTH]; /* State variables */ uint64_t count[_STREEBOG512_DIGEST_LENGTH]; uint64_t sigma[_STREEBOG512_DIGEST_LENGTH]; unsigned int index; /* index into buffer */ uint8_t block[STREEBOG512_BLOCK_SIZE]; /* STREEBOG512 data buffer */ }; void streebog512_init(struct streebog512_ctx *ctx); void streebog512_update(struct streebog512_ctx *ctx, size_t length, const uint8_t *data); void streebog512_digest(struct streebog512_ctx *ctx, size_t length, uint8_t *digest); #define STREEBOG256_DIGEST_SIZE 32 #define STREEBOG256_BLOCK_SIZE STREEBOG512_BLOCK_SIZE #define streebog256_ctx streebog512_ctx void streebog256_init(struct streebog256_ctx *ctx); #define streebog256_update nettle_streebog512_update void streebog256_digest(struct streebog256_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_STREEBOG_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/twofish.h ================================================ /* twofish.h The twofish block cipher. Copyright (C) 2001, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* * Twofish is a 128-bit block cipher that accepts a variable-length * key up to 256 bits, designed by Bruce Schneier and others. See * http://www.counterpane.com/twofish.html for details. */ #ifndef NETTLE_TWOFISH_H_INCLUDED #define NETTLE_TWOFISH_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define twofish_set_key nettle_twofish_set_key #define twofish128_set_key nettle_twofish128_set_key #define twofish192_set_key nettle_twofish192_set_key #define twofish256_set_key nettle_twofish256_set_key #define twofish_encrypt nettle_twofish_encrypt #define twofish_decrypt nettle_twofish_decrypt #define TWOFISH_BLOCK_SIZE 16 /* Variable key size between 128 and 256 bits. But the only valid * values are 16 (128 bits), 24 (192 bits) and 32 (256 bits). */ #define TWOFISH_MIN_KEY_SIZE 16 #define TWOFISH_MAX_KEY_SIZE 32 #define TWOFISH_KEY_SIZE 32 #define TWOFISH128_KEY_SIZE 16 #define TWOFISH192_KEY_SIZE 24 #define TWOFISH256_KEY_SIZE 32 struct twofish_ctx { uint32_t keys[40]; uint32_t s_box[4][256]; }; void twofish_set_key(struct twofish_ctx *ctx, size_t length, const uint8_t *key); void twofish128_set_key(struct twofish_ctx *context, const uint8_t *key); void twofish192_set_key(struct twofish_ctx *context, const uint8_t *key); void twofish256_set_key(struct twofish_ctx *context, const uint8_t *key); void twofish_encrypt(const struct twofish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void twofish_decrypt(const struct twofish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_TWOFISH_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/umac.h ================================================ /* umac.h UMAC message authentication code (RFC-4418). Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_UMAC_H_INCLUDED #define NETTLE_UMAC_H_INCLUDED #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define umac32_set_key nettle_umac32_set_key #define umac64_set_key nettle_umac64_set_key #define umac96_set_key nettle_umac96_set_key #define umac128_set_key nettle_umac128_set_key #define umac32_set_nonce nettle_umac32_set_nonce #define umac64_set_nonce nettle_umac64_set_nonce #define umac96_set_nonce nettle_umac96_set_nonce #define umac128_set_nonce nettle_umac128_set_nonce #define umac32_update nettle_umac32_update #define umac64_update nettle_umac64_update #define umac96_update nettle_umac96_update #define umac128_update nettle_umac128_update #define umac32_digest nettle_umac32_digest #define umac64_digest nettle_umac64_digest #define umac96_digest nettle_umac96_digest #define umac128_digest nettle_umac128_digest #include "nettle-types.h" #include "aes.h" #define UMAC_KEY_SIZE AES128_KEY_SIZE #define UMAC32_DIGEST_SIZE 4 #define UMAC64_DIGEST_SIZE 8 #define UMAC96_DIGEST_SIZE 12 #define UMAC128_DIGEST_SIZE 16 #define UMAC_BLOCK_SIZE 1024 #define UMAC_MIN_NONCE_SIZE 1 #define UMAC_MAX_NONCE_SIZE AES_BLOCK_SIZE /* For backwards compatibility */ #define UMAC_DATA_SIZE UMAC_BLOCK_SIZE /* Subkeys and state for UMAC with tag size 32*n bits. */ #define _UMAC_STATE(n) \ uint32_t l1_key[UMAC_BLOCK_SIZE/4 + 4*((n)-1)]; \ /* Keys in 32-bit pieces, high first */ \ uint32_t l2_key[6*(n)]; \ uint64_t l3_key1[8*(n)]; \ uint32_t l3_key2[(n)]; \ /* AES cipher for encrypting the nonce */ \ struct aes128_ctx pdf_key; \ /* The l2_state consists of 2*n uint64_t, for poly64 \ and poly128 hashing, followed by n additional \ uint64_t used as an input buffer. */ \ uint64_t l2_state[3*(n)]; \ /* Input to the pdf_key, zero-padded and low bits \ cleared if appropriate. */ \ uint8_t nonce[AES_BLOCK_SIZE]; \ unsigned short nonce_length /* For incrementing */ /* Buffering */ #define _UMAC_BUFFER \ unsigned index; \ /* Complete blocks processed */ \ uint64_t count; \ uint8_t block[UMAC_BLOCK_SIZE] #define _UMAC_NONCE_CACHED 0x80 struct umac32_ctx { _UMAC_STATE(1); /* Low bits and cache flag. */ unsigned short nonce_low; /* Previous padding block */ uint32_t pad_cache[AES_BLOCK_SIZE / 4]; _UMAC_BUFFER; }; struct umac64_ctx { _UMAC_STATE(2); /* Low bit and cache flag. */ unsigned short nonce_low; /* Previous padding block */ uint32_t pad_cache[AES_BLOCK_SIZE/4]; _UMAC_BUFFER; }; struct umac96_ctx { _UMAC_STATE(3); _UMAC_BUFFER; }; struct umac128_ctx { _UMAC_STATE(4); _UMAC_BUFFER; }; /* The _set_key function initialize the nonce to zero. */ void umac32_set_key (struct umac32_ctx *ctx, const uint8_t *key); void umac64_set_key (struct umac64_ctx *ctx, const uint8_t *key); void umac96_set_key (struct umac96_ctx *ctx, const uint8_t *key); void umac128_set_key (struct umac128_ctx *ctx, const uint8_t *key); /* Optional, if not used, messages get incrementing nonces starting from zero. */ void umac32_set_nonce (struct umac32_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac64_set_nonce (struct umac64_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac96_set_nonce (struct umac96_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac128_set_nonce (struct umac128_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac32_update (struct umac32_ctx *ctx, size_t length, const uint8_t *data); void umac64_update (struct umac64_ctx *ctx, size_t length, const uint8_t *data); void umac96_update (struct umac96_ctx *ctx, size_t length, const uint8_t *data); void umac128_update (struct umac128_ctx *ctx, size_t length, const uint8_t *data); /* The _digest functions increment the nonce */ void umac32_digest (struct umac32_ctx *ctx, size_t length, uint8_t *digest); void umac64_digest (struct umac64_ctx *ctx, size_t length, uint8_t *digest); void umac96_digest (struct umac96_ctx *ctx, size_t length, uint8_t *digest); void umac128_digest (struct umac128_ctx *ctx, size_t length, uint8_t *digest); /* Internal functions */ #define UMAC_POLY64_BLOCKS 16384 #define UMAC_P64_OFFSET 59 #define UMAC_P64 (- (uint64_t) UMAC_P64_OFFSET) #define UMAC_P128_OFFSET 159 #define UMAC_P128_HI (~(uint64_t) 0) #define UMAC_P128_LO (-(uint64_t) UMAC_P128_OFFSET) #ifdef __cplusplus } #endif #endif /* NETTLE_UMAC_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/version.h ================================================ /* version.h Information about library version. Copyright (C) 2015 Red Hat, Inc. Copyright (C) 2015 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_VERSION_H_INCLUDED #define NETTLE_VERSION_H_INCLUDED #ifdef __cplusplus extern "C" { #endif /* Individual version numbers in decimal */ #define NETTLE_VERSION_MAJOR 3 #define NETTLE_VERSION_MINOR 9 #define NETTLE_USE_MINI_GMP 0 /* We need a preprocessor constant for GMP_NUMB_BITS, simply using sizeof(mp_limb_t) * CHAR_BIT is not good enough. */ #if NETTLE_USE_MINI_GMP # define GMP_NUMB_BITS n/a #endif int nettle_version_major (void); int nettle_version_minor (void); #ifdef __cplusplus } #endif #endif /* NETTLE_VERSION_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/xts.h ================================================ /* xts.h XEX-based tweaked-codebook mode with ciphertext stealing (XTS) Copyright (C) 2005 Niels Möller Copyright (C) 2018 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_XTS_H_INCLUDED #define NETTLE_XTS_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define xts_encrypt_message nettle_xts_encrypt_message #define xts_decrypt_message nettle_xts_decrypt_message #define xts_aes128_set_encrypt_key nettle_xts_aes128_set_encrypt_key #define xts_aes128_set_decrypt_key nettle_xts_aes128_set_decrypt_key #define xts_aes128_encrypt_message nettle_xts_aes128_encrypt_message #define xts_aes128_decrypt_message nettle_xts_aes128_decrypt_message #define xts_aes256_set_encrypt_key nettle_xts_aes256_set_encrypt_key #define xts_aes256_set_decrypt_key nettle_xts_aes256_set_decrypt_key #define xts_aes256_encrypt_message nettle_xts_aes256_encrypt_message #define xts_aes256_decrypt_message nettle_xts_aes256_decrypt_message #define XTS_BLOCK_SIZE 16 void xts_encrypt_message(const void *enc_ctx, const void *twk_ctx, nettle_cipher_func *encf, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); void xts_decrypt_message(const void *dec_ctx, const void *twk_ctx, nettle_cipher_func *decf, nettle_cipher_func *encf, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); /* XTS Mode with AES-128 */ struct xts_aes128_key { struct aes128_ctx cipher; struct aes128_ctx tweak_cipher; }; void xts_aes128_set_encrypt_key(struct xts_aes128_key *xts_key, const uint8_t *key); void xts_aes128_set_decrypt_key(struct xts_aes128_key *xts_key, const uint8_t *key); void xts_aes128_encrypt_message(const struct xts_aes128_key *xtskey, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); void xts_aes128_decrypt_message(const struct xts_aes128_key *xts_key, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); /* XTS Mode with AES-256 */ struct xts_aes256_key { struct aes256_ctx cipher; struct aes256_ctx tweak_cipher; }; void xts_aes256_set_encrypt_key(struct xts_aes256_key *xts_key, const uint8_t *key); void xts_aes256_set_decrypt_key(struct xts_aes256_key *xts_key, const uint8_t *key); void xts_aes256_encrypt_message(const struct xts_aes256_key *xts_key, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); void xts_aes256_decrypt_message(const struct xts_aes256_key *xts_key, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_XTS_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/nettle/yarrow.h ================================================ /* yarrow.h The yarrow pseudo-randomness generator. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_YARROW_H_INCLUDED #define NETTLE_YARROW_H_INCLUDED #include "aes.h" #include "sha2.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define yarrow256_init nettle_yarrow256_init #define yarrow256_seed nettle_yarrow256_seed #define yarrow256_update nettle_yarrow256_update #define yarrow256_random nettle_yarrow256_random #define yarrow256_is_seeded nettle_yarrow256_is_seeded #define yarrow256_needed_sources nettle_yarrow256_needed_sources #define yarrow256_fast_reseed nettle_yarrow256_fast_reseed #define yarrow256_slow_reseed nettle_yarrow256_slow_reseed #define yarrow_key_event_init nettle_yarrow_key_event_init #define yarrow_key_event_estimate nettle_yarrow_key_event_estimate /* Obsolete alias for backwards compatibility. Will be deleted in some later version. */ #define yarrow256_force_reseed yarrow256_slow_reseed enum yarrow_pool_id { YARROW_FAST = 0, YARROW_SLOW = 1 }; struct yarrow_source { /* Indexed by yarrow_pool_id */ uint32_t estimate[2]; /* The pool next sample should go to. */ enum yarrow_pool_id next; }; #define YARROW256_SEED_FILE_SIZE (2 * AES_BLOCK_SIZE) /* Yarrow-256, based on SHA-256 and AES-256 */ struct yarrow256_ctx { /* Indexed by yarrow_pool_id */ struct sha256_ctx pools[2]; int seeded; /* The current key and counter block */ struct aes256_ctx key; uint8_t counter[AES_BLOCK_SIZE]; /* The entropy sources */ unsigned nsources; struct yarrow_source *sources; }; void yarrow256_init(struct yarrow256_ctx *ctx, unsigned nsources, struct yarrow_source *sources); void yarrow256_seed(struct yarrow256_ctx *ctx, size_t length, const uint8_t *seed_file); /* Returns 1 on reseed */ int yarrow256_update(struct yarrow256_ctx *ctx, unsigned source, unsigned entropy, size_t length, const uint8_t *data); void yarrow256_random(struct yarrow256_ctx *ctx, size_t length, uint8_t *dst); int yarrow256_is_seeded(struct yarrow256_ctx *ctx); unsigned yarrow256_needed_sources(struct yarrow256_ctx *ctx); void yarrow256_fast_reseed(struct yarrow256_ctx *ctx); void yarrow256_slow_reseed(struct yarrow256_ctx *ctx); /* Key event estimator */ #define YARROW_KEY_EVENT_BUFFER 16 struct yarrow_key_event_ctx { /* Counter for initial priming of the state */ unsigned index; unsigned chars[YARROW_KEY_EVENT_BUFFER]; unsigned previous; }; void yarrow_key_event_init(struct yarrow_key_event_ctx *ctx); unsigned yarrow_key_event_estimate(struct yarrow_key_event_ctx *ctx, unsigned key, unsigned time); #ifdef __cplusplus } #endif #endif /* NETTLE_YARROW_H_INCLUDED */ ================================================ FILE: thirdparty/32/include/opencore-amrnb/interf_dec.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRNB_INTERF_DEC_H #define OPENCORE_AMRNB_INTERF_DEC_H #ifdef __cplusplus extern "C" { #endif void* Decoder_Interface_init(void); void Decoder_Interface_exit(void* state); void Decoder_Interface_Decode(void* state, const unsigned char* in, short* out, int bfi); #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/32/include/opencore-amrnb/interf_enc.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRNB_INTERF_ENC_H #define OPENCORE_AMRNB_INTERF_ENC_H #ifdef __cplusplus extern "C" { #endif #ifndef AMRNB_WRAPPER_INTERNAL /* Copied from enc/src/gsmamr_enc.h */ enum Mode { MR475 = 0,/* 4.75 kbps */ MR515, /* 5.15 kbps */ MR59, /* 5.90 kbps */ MR67, /* 6.70 kbps */ MR74, /* 7.40 kbps */ MR795, /* 7.95 kbps */ MR102, /* 10.2 kbps */ MR122, /* 12.2 kbps */ MRDTX, /* DTX */ N_MODES /* Not Used */ }; #endif void* Encoder_Interface_init(int dtx); void Encoder_Interface_exit(void* state); int Encoder_Interface_Encode(void* state, enum Mode mode, const short* speech, unsigned char* out, int forceSpeech); #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/32/include/opencore-amrwb/dec_if.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRWB_DEC_IF_H #define OPENCORE_AMRWB_DEC_IF_H #ifdef __cplusplus extern "C" { #endif #define _good_frame 0 void* D_IF_init(void); void D_IF_decode(void* state, const unsigned char* bits, short* synth, int bfi); void D_IF_exit(void* state); #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/32/include/opencore-amrwb/if_rom.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRWB_IF_ROM_H #define OPENCORE_AMRWB_IF_ROM_H #ifdef __cplusplus extern "C" { #endif #include typedef int16_t Word16; #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/32/include/speex/speex.h ================================================ /* Copyright (C) 2002-2006 Jean-Marc Valin*/ /** @file speex.h @brief Describes the different modes of the codec */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPEEX_H #define SPEEX_H /** @defgroup Codec Speex encoder and decoder * This is the Speex codec itself. * @{ */ #include "speex_types.h" #include "speex_bits.h" #ifdef __cplusplus extern "C" { #endif /* Values allowed for *ctl() requests */ /** Set enhancement on/off (decoder only) */ #define SPEEX_SET_ENH 0 /** Get enhancement state (decoder only) */ #define SPEEX_GET_ENH 1 /*Would be SPEEX_SET_FRAME_SIZE, but it's (currently) invalid*/ /** Obtain frame size used by encoder/decoder */ #define SPEEX_GET_FRAME_SIZE 3 /** Set quality value */ #define SPEEX_SET_QUALITY 4 /** Get current quality setting */ /* #define SPEEX_GET_QUALITY 5 -- Doesn't make much sense, does it? */ /** Set sub-mode to use */ #define SPEEX_SET_MODE 6 /** Get current sub-mode in use */ #define SPEEX_GET_MODE 7 /** Set low-band sub-mode to use (wideband only)*/ #define SPEEX_SET_LOW_MODE 8 /** Get current low-band mode in use (wideband only)*/ #define SPEEX_GET_LOW_MODE 9 /** Set high-band sub-mode to use (wideband only)*/ #define SPEEX_SET_HIGH_MODE 10 /** Get current high-band mode in use (wideband only)*/ #define SPEEX_GET_HIGH_MODE 11 /** Set VBR on (1) or off (0) */ #define SPEEX_SET_VBR 12 /** Get VBR status (1 for on, 0 for off) */ #define SPEEX_GET_VBR 13 /** Set quality value for VBR encoding (0-10) */ #define SPEEX_SET_VBR_QUALITY 14 /** Get current quality value for VBR encoding (0-10) */ #define SPEEX_GET_VBR_QUALITY 15 /** Set complexity of the encoder (0-10) */ #define SPEEX_SET_COMPLEXITY 16 /** Get current complexity of the encoder (0-10) */ #define SPEEX_GET_COMPLEXITY 17 /** Set bit-rate used by the encoder (or lower) */ #define SPEEX_SET_BITRATE 18 /** Get current bit-rate used by the encoder or decoder */ #define SPEEX_GET_BITRATE 19 /** Define a handler function for in-band Speex request*/ #define SPEEX_SET_HANDLER 20 /** Define a handler function for in-band user-defined request*/ #define SPEEX_SET_USER_HANDLER 22 /** Set sampling rate used in bit-rate computation */ #define SPEEX_SET_SAMPLING_RATE 24 /** Get sampling rate used in bit-rate computation */ #define SPEEX_GET_SAMPLING_RATE 25 /** Reset the encoder/decoder memories to zero*/ #define SPEEX_RESET_STATE 26 /** Get VBR info (mostly used internally) */ #define SPEEX_GET_RELATIVE_QUALITY 29 /** Set VAD status (1 for on, 0 for off) */ #define SPEEX_SET_VAD 30 /** Get VAD status (1 for on, 0 for off) */ #define SPEEX_GET_VAD 31 /** Set Average Bit-Rate (ABR) to n bits per seconds */ #define SPEEX_SET_ABR 32 /** Get Average Bit-Rate (ABR) setting (in bps) */ #define SPEEX_GET_ABR 33 /** Set DTX status (1 for on, 0 for off) */ #define SPEEX_SET_DTX 34 /** Get DTX status (1 for on, 0 for off) */ #define SPEEX_GET_DTX 35 /** Set submode encoding in each frame (1 for yes, 0 for no, setting to no breaks the standard) */ #define SPEEX_SET_SUBMODE_ENCODING 36 /** Get submode encoding in each frame */ #define SPEEX_GET_SUBMODE_ENCODING 37 /*#define SPEEX_SET_LOOKAHEAD 38*/ /** Returns the lookahead used by Speex separately for an encoder and a decoder. * Sum encoder and decoder lookahead values to get the total codec lookahead. */ #define SPEEX_GET_LOOKAHEAD 39 /** Sets tuning for packet-loss concealment (expected loss rate) */ #define SPEEX_SET_PLC_TUNING 40 /** Gets tuning for PLC */ #define SPEEX_GET_PLC_TUNING 41 /** Sets the max bit-rate allowed in VBR mode */ #define SPEEX_SET_VBR_MAX_BITRATE 42 /** Gets the max bit-rate allowed in VBR mode */ #define SPEEX_GET_VBR_MAX_BITRATE 43 /** Turn on/off input/output high-pass filtering */ #define SPEEX_SET_HIGHPASS 44 /** Get status of input/output high-pass filtering */ #define SPEEX_GET_HIGHPASS 45 /** Get "activity level" of the last decoded frame, i.e. how much damage we cause if we remove the frame */ #define SPEEX_GET_ACTIVITY 47 /* Preserving compatibility:*/ /** Equivalent to SPEEX_SET_ENH */ #define SPEEX_SET_PF 0 /** Equivalent to SPEEX_GET_ENH */ #define SPEEX_GET_PF 1 /* Values allowed for mode queries */ /** Query the frame size of a mode */ #define SPEEX_MODE_FRAME_SIZE 0 /** Query the size of an encoded frame for a particular sub-mode */ #define SPEEX_SUBMODE_BITS_PER_FRAME 1 /** Get major Speex version */ #define SPEEX_LIB_GET_MAJOR_VERSION 1 /** Get minor Speex version */ #define SPEEX_LIB_GET_MINOR_VERSION 3 /** Get micro Speex version */ #define SPEEX_LIB_GET_MICRO_VERSION 5 /** Get extra Speex version */ #define SPEEX_LIB_GET_EXTRA_VERSION 7 /** Get Speex version string */ #define SPEEX_LIB_GET_VERSION_STRING 9 /*#define SPEEX_LIB_SET_ALLOC_FUNC 10 #define SPEEX_LIB_GET_ALLOC_FUNC 11 #define SPEEX_LIB_SET_FREE_FUNC 12 #define SPEEX_LIB_GET_FREE_FUNC 13 #define SPEEX_LIB_SET_WARNING_FUNC 14 #define SPEEX_LIB_GET_WARNING_FUNC 15 #define SPEEX_LIB_SET_ERROR_FUNC 16 #define SPEEX_LIB_GET_ERROR_FUNC 17 */ /** Number of defined modes in Speex */ #define SPEEX_NB_MODES 3 /** modeID for the defined narrowband mode */ #define SPEEX_MODEID_NB 0 /** modeID for the defined wideband mode */ #define SPEEX_MODEID_WB 1 /** modeID for the defined ultra-wideband mode */ #define SPEEX_MODEID_UWB 2 struct SpeexMode; /* Prototypes for mode function pointers */ /** Encoder state initialization function */ typedef void *(*encoder_init_func)(const struct SpeexMode *mode); /** Encoder state destruction function */ typedef void (*encoder_destroy_func)(void *st); /** Main encoding function */ typedef int (*encode_func)(void *state, void *in, SpeexBits *bits); /** Function for controlling the encoder options */ typedef int (*encoder_ctl_func)(void *state, int request, void *ptr); /** Decoder state initialization function */ typedef void *(*decoder_init_func)(const struct SpeexMode *mode); /** Decoder state destruction function */ typedef void (*decoder_destroy_func)(void *st); /** Main decoding function */ typedef int (*decode_func)(void *state, SpeexBits *bits, void *out); /** Function for controlling the decoder options */ typedef int (*decoder_ctl_func)(void *state, int request, void *ptr); /** Query function for a mode */ typedef int (*mode_query_func)(const void *mode, int request, void *ptr); /** Struct defining a Speex mode */ typedef struct SpeexMode { /** Pointer to the low-level mode data */ const void *mode; /** Pointer to the mode query function */ mode_query_func query; /** The name of the mode (you should not rely on this to identify the mode)*/ const char *modeName; /**ID of the mode*/ int modeID; /**Version number of the bitstream (incremented every time we break bitstream compatibility*/ int bitstream_version; /** Pointer to encoder initialization function */ encoder_init_func enc_init; /** Pointer to encoder destruction function */ encoder_destroy_func enc_destroy; /** Pointer to frame encoding function */ encode_func enc; /** Pointer to decoder initialization function */ decoder_init_func dec_init; /** Pointer to decoder destruction function */ decoder_destroy_func dec_destroy; /** Pointer to frame decoding function */ decode_func dec; /** ioctl-like requests for encoder */ encoder_ctl_func enc_ctl; /** ioctl-like requests for decoder */ decoder_ctl_func dec_ctl; } SpeexMode; /** * Returns a handle to a newly created Speex encoder state structure. For now, * the "mode" argument can be &nb_mode or &wb_mode . In the future, more modes * may be added. Note that for now if you have more than one channels to * encode, you need one state per channel. * * @param mode The mode to use (either speex_nb_mode or speex_wb.mode) * @return A newly created encoder state or NULL if state allocation fails */ void *speex_encoder_init(const SpeexMode *mode); /** Frees all resources associated to an existing Speex encoder state. * @param state Encoder state to be destroyed */ void speex_encoder_destroy(void *state); /** Uses an existing encoder state to encode one frame of speech pointed to by "in". The encoded bit-stream is saved in "bits". @param state Encoder state @param in Frame that will be encoded with a +-2^15 range. This data MAY be overwritten by the encoder and should be considered uninitialised after the call. @param bits Bit-stream where the data will be written @return 0 if frame needs not be transmitted (DTX only), 1 otherwise */ int speex_encode(void *state, float *in, SpeexBits *bits); /** Uses an existing encoder state to encode one frame of speech pointed to by "in". The encoded bit-stream is saved in "bits". @param state Encoder state @param in Frame that will be encoded with a +-2^15 range @param bits Bit-stream where the data will be written @return 0 if frame needs not be transmitted (DTX only), 1 otherwise */ int speex_encode_int(void *state, spx_int16_t *in, SpeexBits *bits); /** Used like the ioctl function to control the encoder parameters * * @param state Encoder state * @param request ioctl-type request (one of the SPEEX_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_encoder_ctl(void *state, int request, void *ptr); /** Returns a handle to a newly created decoder state structure. For now, * the mode argument can be &nb_mode or &wb_mode . In the future, more modes * may be added. Note that for now if you have more than one channels to * decode, you need one state per channel. * * @param mode Speex mode (one of speex_nb_mode or speex_wb_mode) * @return A newly created decoder state or NULL if state allocation fails */ void *speex_decoder_init(const SpeexMode *mode); /** Frees all resources associated to an existing decoder state. * * @param state State to be destroyed */ void speex_decoder_destroy(void *state); /** Uses an existing decoder state to decode one frame of speech from * bit-stream bits. The output speech is saved written to out. * * @param state Decoder state * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) * @param out Where to write the decoded frame * @return return status (0 for no error, -1 for end of stream, -2 corrupt stream) */ int speex_decode(void *state, SpeexBits *bits, float *out); /** Uses an existing decoder state to decode one frame of speech from * bit-stream bits. The output speech is saved written to out. * * @param state Decoder state * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) * @param out Where to write the decoded frame * @return return status (0 for no error, -1 for end of stream, -2 corrupt stream) */ int speex_decode_int(void *state, SpeexBits *bits, spx_int16_t *out); /** Used like the ioctl function to control the encoder parameters * * @param state Decoder state * @param request ioctl-type request (one of the SPEEX_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_decoder_ctl(void *state, int request, void *ptr); /** Query function for mode information * * @param mode Speex mode * @param request ioctl-type request (one of the SPEEX_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_mode_query(const SpeexMode *mode, int request, void *ptr); /** Functions for controlling the behavior of libspeex * @param request ioctl-type request (one of the SPEEX_LIB_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_lib_ctl(int request, void *ptr); /** Default narrowband mode */ extern const SpeexMode speex_nb_mode; /** Default wideband mode */ extern const SpeexMode speex_wb_mode; /** Default "ultra-wideband" mode */ extern const SpeexMode speex_uwb_mode; /** List of all modes available */ extern const SpeexMode * const speex_mode_list[SPEEX_NB_MODES]; /** Obtain one of the modes available */ const SpeexMode * speex_lib_get_mode (int mode); #ifndef _WIN32 /* We actually override the function in the narrowband case so that we can avoid linking in the wideband stuff */ #define speex_lib_get_mode(mode) ((mode)==SPEEX_MODEID_NB ? &speex_nb_mode : speex_lib_get_mode (mode)) #endif #ifdef __cplusplus } #endif /** @}*/ #endif ================================================ FILE: thirdparty/32/include/speex/speex_bits.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin */ /** @file speex_bits.h @brief Handles bit packing/unpacking */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BITS_H #define BITS_H /** @defgroup SpeexBits SpeexBits: Bit-stream manipulations * This is the structure that holds the bit-stream when encoding or decoding * with Speex. It allows some manipulations as well. * @{ */ #ifdef __cplusplus extern "C" { #endif /** Bit-packing data structure representing (part of) a bit-stream. */ typedef struct SpeexBits { char *chars; /**< "raw" data */ int nbBits; /**< Total number of bits stored in the stream*/ int charPtr; /**< Position of the byte "cursor" */ int bitPtr; /**< Position of the bit "cursor" within the current char */ int owner; /**< Does the struct "own" the "raw" buffer (member "chars") */ int overflow;/**< Set to one if we try to read past the valid data */ int buf_size;/**< Allocated size for buffer */ int reserved1; /**< Reserved for future use */ void *reserved2; /**< Reserved for future use */ } SpeexBits; /** Initializes and allocates resources for a SpeexBits struct */ void speex_bits_init(SpeexBits *bits); /** Initializes SpeexBits struct using a pre-allocated buffer*/ void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size); /** Sets the bits in a SpeexBits struct to use data from an existing buffer (for decoding without copying data) */ void speex_bits_set_bit_buffer(SpeexBits *bits, void *buff, int buf_size); /** Frees all resources associated to a SpeexBits struct. Right now this does nothing since no resources are allocated, but this could change in the future.*/ void speex_bits_destroy(SpeexBits *bits); /** Resets bits to initial value (just after initialization, erasing content)*/ void speex_bits_reset(SpeexBits *bits); /** Rewind the bit-stream to the beginning (ready for read) without erasing the content */ void speex_bits_rewind(SpeexBits *bits); /** Initializes the bit-stream from the data in an area of memory */ void speex_bits_read_from(SpeexBits *bits, const char *bytes, int len); /** Append bytes to the bit-stream * * @param bits Bit-stream to operate on * @param bytes pointer to the bytes what will be appended * @param len Number of bytes of append */ void speex_bits_read_whole_bytes(SpeexBits *bits, const char *bytes, int len); /** Write the content of a bit-stream to an area of memory * * @param bits Bit-stream to operate on * @param bytes Memory location where to write the bits * @param max_len Maximum number of bytes to write (i.e. size of the "bytes" buffer) * @return Number of bytes written to the "bytes" buffer */ int speex_bits_write(SpeexBits *bits, char *bytes, int max_len); /** Like speex_bits_write, but writes only the complete bytes in the stream. Also removes the written bytes from the stream */ int speex_bits_write_whole_bytes(SpeexBits *bits, char *bytes, int max_len); /** Append bits to the bit-stream * @param bits Bit-stream to operate on * @param data Value to append as integer * @param nbBits number of bits to consider in "data" */ void speex_bits_pack(SpeexBits *bits, int data, int nbBits); /** Interpret the next bits in the bit-stream as a signed integer * * @param bits Bit-stream to operate on * @param nbBits Number of bits to interpret * @return A signed integer represented by the bits read */ int speex_bits_unpack_signed(SpeexBits *bits, int nbBits); /** Interpret the next bits in the bit-stream as an unsigned integer * * @param bits Bit-stream to operate on * @param nbBits Number of bits to interpret * @return An unsigned integer represented by the bits read */ unsigned int speex_bits_unpack_unsigned(SpeexBits *bits, int nbBits); /** Returns the number of bytes in the bit-stream, including the last one even if it is not "full" * * @param bits Bit-stream to operate on * @return Number of bytes in the stream */ int speex_bits_nbytes(SpeexBits *bits); /** Same as speex_bits_unpack_unsigned, but without modifying the cursor position * * @param bits Bit-stream to operate on * @param nbBits Number of bits to look for * @return Value of the bits peeked, interpreted as unsigned */ unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits); /** Get the value of the next bit in the stream, without modifying the * "cursor" position * * @param bits Bit-stream to operate on * @return Value of the bit peeked (one bit only) */ int speex_bits_peek(SpeexBits *bits); /** Advances the position of the "bit cursor" in the stream * * @param bits Bit-stream to operate on * @param n Number of bits to advance */ void speex_bits_advance(SpeexBits *bits, int n); /** Returns the number of bits remaining to be read in a stream * * @param bits Bit-stream to operate on * @return Number of bits that can still be read from the stream */ int speex_bits_remaining(SpeexBits *bits); /** Insert a terminator so that the data can be sent as a packet while auto-detecting * the number of frames in each packet * * @param bits Bit-stream to operate on */ void speex_bits_insert_terminator(SpeexBits *bits); #ifdef __cplusplus } #endif /* @} */ #endif ================================================ FILE: thirdparty/32/include/speex/speex_callbacks.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin*/ /** @file speex_callbacks.h @brief Describes callback handling and in-band signalling */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPEEX_CALLBACKS_H #define SPEEX_CALLBACKS_H /** @defgroup SpeexCallbacks Various definitions for Speex callbacks supported by the decoder. * @{ */ #include "speex.h" #ifdef __cplusplus extern "C" { #endif /** Total number of callbacks */ #define SPEEX_MAX_CALLBACKS 16 /* Describes all the in-band requests */ /*These are 1-bit requests*/ /** Request for perceptual enhancement (1 for on, 0 for off) */ #define SPEEX_INBAND_ENH_REQUEST 0 /** Reserved */ #define SPEEX_INBAND_RESERVED1 1 /*These are 4-bit requests*/ /** Request for a mode change */ #define SPEEX_INBAND_MODE_REQUEST 2 /** Request for a low mode change */ #define SPEEX_INBAND_LOW_MODE_REQUEST 3 /** Request for a high mode change */ #define SPEEX_INBAND_HIGH_MODE_REQUEST 4 /** Request for VBR (1 on, 0 off) */ #define SPEEX_INBAND_VBR_QUALITY_REQUEST 5 /** Request to be sent acknowledge */ #define SPEEX_INBAND_ACKNOWLEDGE_REQUEST 6 /** Request for VBR (1 for on, 0 for off) */ #define SPEEX_INBAND_VBR_REQUEST 7 /*These are 8-bit requests*/ /** Send a character in-band */ #define SPEEX_INBAND_CHAR 8 /** Intensity stereo information */ #define SPEEX_INBAND_STEREO 9 /*These are 16-bit requests*/ /** Transmit max bit-rate allowed */ #define SPEEX_INBAND_MAX_BITRATE 10 /*These are 32-bit requests*/ /** Acknowledge packet reception */ #define SPEEX_INBAND_ACKNOWLEDGE 12 /** Callback function type */ typedef int (*speex_callback_func)(SpeexBits *bits, void *state, void *data); /** Callback information */ typedef struct SpeexCallback { int callback_id; /**< ID associated to the callback */ speex_callback_func func; /**< Callback handler function */ void *data; /**< Data that will be sent to the handler */ void *reserved1; /**< Reserved for future use */ int reserved2; /**< Reserved for future use */ } SpeexCallback; /** Handle in-band request */ int speex_inband_handler(SpeexBits *bits, SpeexCallback *callback_list, void *state); /** Standard handler for mode request (change mode, no questions asked) */ int speex_std_mode_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for high mode request (change high mode, no questions asked) */ int speex_std_high_mode_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for in-band characters (write to stderr) */ int speex_std_char_handler(SpeexBits *bits, void *state, void *data); /** Default handler for user-defined requests: in this case, just ignore */ int speex_default_user_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for low mode request (change low mode, no questions asked) */ int speex_std_low_mode_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for VBR request (Set VBR, no questions asked) */ int speex_std_vbr_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for enhancer request (Turn enhancer on/off, no questions asked) */ int speex_std_enh_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for VBR quality request (Set VBR quality, no questions asked) */ int speex_std_vbr_quality_request_handler(SpeexBits *bits, void *state, void *data); #ifdef __cplusplus } #endif /** @} */ #endif ================================================ FILE: thirdparty/32/include/speex/speex_config_types.h ================================================ #ifndef __SPEEX_TYPES_H__ #define __SPEEX_TYPES_H__ #include typedef int16_t spx_int16_t; typedef uint16_t spx_uint16_t; typedef int32_t spx_int32_t; typedef uint32_t spx_uint32_t; #endif ================================================ FILE: thirdparty/32/include/speex/speex_header.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin */ /** @file speex_header.h @brief Describes the Speex header */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPEEX_HEADER_H #define SPEEX_HEADER_H /** @defgroup SpeexHeader SpeexHeader: Makes it easy to write/parse an Ogg/Speex header * This is the Speex header for the Ogg encapsulation. You don't need that if you just use RTP. * @{ */ #include "speex_types.h" #ifdef __cplusplus extern "C" { #endif struct SpeexMode; /** Length of the Speex header identifier */ #define SPEEX_HEADER_STRING_LENGTH 8 /** Maximum number of characters for encoding the Speex version number in the header */ #define SPEEX_HEADER_VERSION_LENGTH 20 /** Speex header info for file-based formats */ typedef struct SpeexHeader { char speex_string[SPEEX_HEADER_STRING_LENGTH]; /**< Identifies a Speex bit-stream, always set to "Speex " */ char speex_version[SPEEX_HEADER_VERSION_LENGTH]; /**< Speex version */ spx_int32_t speex_version_id; /**< Version for Speex (for checking compatibility) */ spx_int32_t header_size; /**< Total size of the header ( sizeof(SpeexHeader) ) */ spx_int32_t rate; /**< Sampling rate used */ spx_int32_t mode; /**< Mode used (0 for narrowband, 1 for wideband) */ spx_int32_t mode_bitstream_version; /**< Version ID of the bit-stream */ spx_int32_t nb_channels; /**< Number of channels encoded */ spx_int32_t bitrate; /**< Bit-rate used */ spx_int32_t frame_size; /**< Size of frames */ spx_int32_t vbr; /**< 1 for a VBR encoding, 0 otherwise */ spx_int32_t frames_per_packet; /**< Number of frames stored per Ogg packet */ spx_int32_t extra_headers; /**< Number of additional headers after the comments */ spx_int32_t reserved1; /**< Reserved for future use, must be zero */ spx_int32_t reserved2; /**< Reserved for future use, must be zero */ } SpeexHeader; /** Initializes a SpeexHeader using basic information */ void speex_init_header(SpeexHeader *header, int rate, int nb_channels, const struct SpeexMode *m); /** Creates the header packet from the header itself (mostly involves endianness conversion) */ char *speex_header_to_packet(SpeexHeader *header, int *size); /** Creates a SpeexHeader from a packet */ SpeexHeader *speex_packet_to_header(char *packet, int size); /** Frees the memory allocated by either speex_header_to_packet() or speex_packet_to_header() */ void speex_header_free(void *ptr); #ifdef __cplusplus } #endif /** @} */ #endif ================================================ FILE: thirdparty/32/include/speex/speex_stereo.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin*/ /** @file speex_stereo.h @brief Describes the handling for intensity stereo */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef STEREO_H #define STEREO_H /** @defgroup SpeexStereoState SpeexStereoState: Handling Speex stereo files * This describes the Speex intensity stereo encoding/decoding * @{ */ #include "speex_types.h" #include "speex_bits.h" #ifdef __cplusplus extern "C" { #endif /** If you access any of these fields directly, I'll personally come and bite you */ typedef struct SpeexStereoState { float balance; /**< Left/right balance info */ float e_ratio; /**< Ratio of energies: E(left+right)/[E(left)+E(right)] */ float smooth_left; /**< Smoothed left channel gain */ float smooth_right; /**< Smoothed right channel gain */ float reserved1; /**< Reserved for future use */ float reserved2; /**< Reserved for future use */ } SpeexStereoState; /** Deprecated. Use speex_stereo_state_init() instead. */ #define SPEEX_STEREO_STATE_INIT {1,.5,1,1,0,0} /** Initialise/create a stereo stereo state */ SpeexStereoState *speex_stereo_state_init(void); /** Reset/re-initialise an already allocated stereo state */ void speex_stereo_state_reset(SpeexStereoState *stereo); /** Destroy a stereo stereo state */ void speex_stereo_state_destroy(SpeexStereoState *stereo); /** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */ void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits); /** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */ void speex_encode_stereo_int(spx_int16_t *data, int frame_size, SpeexBits *bits); /** Transforms a mono frame into a stereo frame using intensity stereo info */ void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *stereo); /** Transforms a mono frame into a stereo frame using intensity stereo info */ void speex_decode_stereo_int(spx_int16_t *data, int frame_size, SpeexStereoState *stereo); /** Callback handler for intensity stereo info */ int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data); #ifdef __cplusplus } #endif /** @} */ #endif ================================================ FILE: thirdparty/32/include/speex/speex_types.h ================================================ /* speex_types.h taken from libogg */ /******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * by the Xiph.Org Foundation http://www.xiph.org/ * * * ******************************************************************** function: #ifdef jail to whip a few platforms into the UNIX ideal. last mod: $Id: os_types.h 7524 2004-08-11 04:20:36Z conrad $ ********************************************************************/ /** @file speex_types.h @brief Speex types */ #ifndef _SPEEX_TYPES_H #define _SPEEX_TYPES_H #if defined(_WIN32) # if defined(__CYGWIN__) # include <_G_config.h> typedef _G_int32_t spx_int32_t; typedef _G_uint32_t spx_uint32_t; typedef _G_int16_t spx_int16_t; typedef _G_uint16_t spx_uint16_t; # elif defined(__MINGW32__) typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; # elif defined(__MWERKS__) typedef int spx_int32_t; typedef unsigned int spx_uint32_t; typedef short spx_int16_t; typedef unsigned short spx_uint16_t; # else /* MSVC/Borland */ typedef __int32 spx_int32_t; typedef unsigned __int32 spx_uint32_t; typedef __int16 spx_int16_t; typedef unsigned __int16 spx_uint16_t; # endif #elif defined(__MACOS__) # include typedef SInt16 spx_int16_t; typedef UInt16 spx_uint16_t; typedef SInt32 spx_int32_t; typedef UInt32 spx_uint32_t; #elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */ # include typedef int16_t spx_int16_t; typedef u_int16_t spx_uint16_t; typedef int32_t spx_int32_t; typedef u_int32_t spx_uint32_t; #elif defined(__BEOS__) /* Be */ # include typedef int16_t spx_int16_t; typedef u_int16_t spx_uint16_t; typedef int32_t spx_int32_t; typedef u_int32_t spx_uint32_t; #elif defined (__EMX__) /* OS/2 GCC */ typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; #elif defined (DJGPP) /* DJGPP */ typedef short spx_int16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; #elif defined(R5900) /* PS2 EE */ typedef int spx_int32_t; typedef unsigned spx_uint32_t; typedef short spx_int16_t; #elif defined(__SYMBIAN32__) /* Symbian GCC */ typedef signed short spx_int16_t; typedef unsigned short spx_uint16_t; typedef signed int spx_int32_t; typedef unsigned int spx_uint32_t; #elif defined(CONFIG_TI_C54X) || defined (CONFIG_TI_C55X) typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef long spx_int32_t; typedef unsigned long spx_uint32_t; #elif defined(CONFIG_TI_C6X) typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; #else #include "speex_config_types.h" #endif #endif /* _SPEEX_TYPES_H */ ================================================ FILE: thirdparty/32/lib/pkgconfig/dav1d.pc ================================================ prefix=. includedir=${prefix}/include libdir=${prefix}/lib Name: libdav1d Description: AV1 decoding library Version: 1.5.1 Libs: -L${libdir} -ldav1d Cflags: -I${includedir} ================================================ FILE: thirdparty/32/lib/pkgconfig/gmp.pc ================================================ prefix=. exec_prefix=${prefix} includedir=${prefix}/include libdir=${exec_prefix}/lib Name: GNU MP Description: GNU Multiple Precision Arithmetic Library URL: https://gmplib.org Version: 6.3.0 Cflags: -I${includedir} Libs: -L${libdir} -lgmp ================================================ FILE: thirdparty/32/lib/pkgconfig/gnutls.pc ================================================ # Process this file with autoconf to produce a pkg-config metadata file. # Copyright (C) 2004-2012 Free Software Foundation, Inc. # Copying and distribution of this file, with or without modification, # are permitted in any medium without royalty provided the copyright # notice and this notice are preserved. This file is offered as-is, # without any warranty. # Author: Simon Josefsson prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: GnuTLS Description: Transport Security Layer implementation for the GNU system URL: https://www.gnutls.org/ Version: 3.7.10 Libs: -L${libdir} -lgnutls Libs.private: -lz -lws2_32 -L${libdir} -latomic -ladvapi32 -lcrypt32 -lncrypt -lbcrypt Requires.private: nettle, hogweed Cflags: -I${includedir} ================================================ FILE: thirdparty/32/lib/pkgconfig/hogweed.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include # Uses Requires.private and Libs.private, under the assumption that # when using shared libraries, the ELF dependencies from libhogweed.so # to nettle and gmp work. Name: Hogweed Description: Nettle low-level cryptographic library (public-key algorithms) URL: http://www.lysator.liu.se/~nisse/nettle Version: 3.9.1 Requires: nettle Requires.private: # nettle Libs: -L${libdir} -lhogweed -lgmp -lnettle Libs.private: # -lgmp Cflags: -I${includedir} ================================================ FILE: thirdparty/32/lib/pkgconfig/libxml-2.0.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include modules=1 Name: libXML Version: 2.11.5 Description: libXML library version2. Requires: Libs: -L${libdir} -lxml2 Libs.private: -lz -lm Cflags: -I${includedir}/libxml2 -DLIBXML_STATIC ================================================ FILE: thirdparty/32/lib/pkgconfig/nettle.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: Nettle Description: Nettle low-level cryptographic library (symmetric algorithms) URL: http://www.lysator.liu.se/~nisse/nettle Version: 3.9.1 Libs: -L${libdir} -lnettle Cflags: -I${includedir} ================================================ FILE: thirdparty/32/lib/pkgconfig/opencore-amrnb.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: OpenCORE AMR-NB Description: Adaptive Multi-Rate speech codec library Version: 0.1.6 Libs: -L${libdir} -lopencore-amrnb Cflags: -I${includedir} ================================================ FILE: thirdparty/32/lib/pkgconfig/opencore-amrwb.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: OpenCORE AMR-WB Description: Adaptive Multi-Rate Wideband speech codec library Version: 0.1.6 Libs: -L${libdir} -lopencore-amrwb Cflags: -I${includedir} ================================================ FILE: thirdparty/32/lib/pkgconfig/speex.pc ================================================ # libspeex pkg-config source file prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: speex Description: Speex is an audio codec tuned for speech Version: 1.2.1 Requires: Conflicts: Libs: -L${libdir} -lspeex Libs.private: -lm Cflags: -I${includedir} ================================================ FILE: thirdparty/64/include/avisynth/avisynth.h ================================================ // Avisynth v2.5. Copyright 2002 Ben Rudiak-Gould et al. // Avisynth v2.6. Copyright 2006 Klaus Post. // Avisynth v2.6. Copyright 2009 Ian Brabham. // Avisynth+ project // 20160613: new 16 bit planar pixel_type constants go live! // 20160725: pixel_type constants 10-12-14 bit + planar RGB + BRG48/64 // 20161005: Fallback of VideoInfo functions to defaults if no function exists // 20170117: global variables for VfW output OPT_xxxx // 20170310: new MT mode: MT_SPECIAL_MT // 20171103: (test with SIZETMOD define: Videoframe offsets to size_t, may affect x64) // 20171207: C++ Standard Conformance (no change for plugin writers) // 20180525: AVS_UNUSED define to supress parameter not used warnings // 2020xxxx: AVS_WINDOWS and AVS_POSIX option see avs/config.h // 20200305: ScriptEnvironment::VSprintf parameter (void *) changed back to va_list // 20200330: removed __stdcall from variadic argument functions (Sprintf) // (remove test SIZETMOD define for clarity) // Integrate Avisynth Neo structures and interface, PFunction, PDevice // 20200501: frame property support (NewVideoFrameP and other helpers) to legacy IScriptEnvironment. // move some former IScriptEnvironment2 functions to IScriptEnvironment: // GetEnvProperty (system prop), Allocate, Free (buffer pool) // GetVarTry, GetVarBool/Int/String/Double/Long // Invoke2, Invoke3, InvokeTry, Invoke2Try, Invoke3Try // Interface Version to 8 (classic 2.6 = 6) // 20200527 Add IScriptEnvironment_Avs25, used internally // 20200607 AVS frame property enums to match existing Avisynth enum style // 202112xx V9-MakePropertyWritable, IsPropertyWritable // 2023 V10 // prop_src parameter made as const in NewVideoFrameP (non-breaking cosmetics) // Add all enums of public C++ API a name // Add DEFAULT_PLANE as 0 to AvsPlane enum // Made `VideoFrameBuffer` destructor public // Introduce pixel_type to VideoFrame struct // VideoFrame::GetPixelType,VideoFrame::AmendPixelType // AVSValue::GetType // Add enum AvsChannelMask::MASK_SPEAKER_xxx, AvsImageTypeFlags::IT_SPEAKER_xxx // Audio channel mask support for VideoInfo: // Use 20 bits in VideoInfo::image_type for channel mask mapping // IsChannelMaskKnown, SetChannelMask, GetChannelMask in VideoInfo // http://www.avisynth.org // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making // a combined work based on Avisynth. Thus, the terms and conditions of // the GNU General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate // with Avisynth solely through the interfaces defined in avisynth.h, // regardless of the license terms of these independent modules, and to // copy and distribute the resulting combined work under terms of your // choice, provided that every copy of the combined work is accompanied // by a complete copy of the source code of Avisynth (the version of // Avisynth used to produce the combined work), being distributed under // the terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based on // Avisynth, such as 3rd-party filters, import and export plugins, or // graphical user interfaces. #ifndef __AVISYNTH_10_H__ #define __AVISYNTH_10_H__ #include "avs/config.h" #include "avs/capi.h" #include "avs/types.h" #ifdef AVS_POSIX # include "avs/posix.h" #endif #if defined(AVS_POSIX) #if defined(AVS_HAIKU) #undef __stdcall #undef __cdecl #endif #define __stdcall #define __cdecl #endif // Important note on AVISYNTH_INTERFACE_VERSION V6->V8 change: // Note 1: Those few plugins which were using earlier IScriptEnvironment2 despite the big Warning will crash have to be rebuilt. // Note 2: How to support earlier avisynth interface with an up-to-date avisynth.h: // Use the new frame property features adaptively after querying that at least v8 is supported // AviSynth property support can be queried (cpp iface example): // has_at_least_v8 = true; // try { env->CheckVersion(8); } catch (const AvisynthError&) { has_at_least_v8 = false; } // and use it: // if (has_at_least_v8) dst = env->NewVideoFrameP(vi, &src); else dst = env->NewVideoFrame(vi); enum AvsVersion { AVISYNTH_CLASSIC_INTERFACE_VERSION_25 = 3, AVISYNTH_CLASSIC_INTERFACE_VERSION_26BETA = 5, AVISYNTH_CLASSIC_INTERFACE_VERSION = 6, AVISYNTH_INTERFACE_VERSION = 10, AVISYNTHPLUS_INTERFACE_BUGFIX_VERSION = 0 // reset to zero whenever the normal interface version bumps }; /* Compiler-specific crap */ // Tell MSVC to stop precompiling here #if defined(_MSC_VER) && !defined(__clang__) #pragma hdrstop #endif // Set up debugging macros for MS compilers; for others, step down to the // standard interface #ifdef _MSC_VER #include #else #undef _RPT0 #undef _RPT1 #undef _RPT2 #undef _RPT3 #undef _RPT4 #undef _RPT5 #define _RPT0(a,b) ((void)0) #define _RPT1(a,b,c) ((void)0) #define _RPT2(a,b,c,d) ((void)0) #define _RPT3(a,b,c,d,e) ((void)0) #define _RPT4(a,b,c,d,e,f) ((void)0) #define _RPT5(a,b,c,d,e,f,g) ((void)0) #include #undef _ASSERTE #undef _ASSERT #define _ASSERTE(x) assert(x) #define _ASSERT(x) assert(x) #endif // I had problems with Premiere wanting 1-byte alignment for its structures, // so I now set the Avisynth struct alignment explicitly here. #pragma pack(push,8) // The VideoInfo struct holds global information about a clip (i.e. // information that does not depend on the frame number). The GetVideoInfo // method in IClip returns this struct. enum AvsSampleType { SAMPLE_INT8 = 1 << 0, SAMPLE_INT16 = 1 << 1, SAMPLE_INT24 = 1 << 2, // Int24 is a very stupid thing to code, but it's supported by some hardware. SAMPLE_INT32 = 1 << 3, SAMPLE_FLOAT = 1 << 4 }; enum AvsPlane { DEFAULT_PLANE = 0, PLANAR_Y = 1 << 0, PLANAR_U = 1 << 1, PLANAR_V = 1 << 2, PLANAR_ALIGNED = 1 << 3, PLANAR_Y_ALIGNED = PLANAR_Y | PLANAR_ALIGNED, PLANAR_U_ALIGNED = PLANAR_U | PLANAR_ALIGNED, PLANAR_V_ALIGNED = PLANAR_V | PLANAR_ALIGNED, PLANAR_A = 1 << 4, PLANAR_R = 1 << 5, PLANAR_G = 1 << 6, PLANAR_B = 1 << 7, PLANAR_A_ALIGNED = PLANAR_A | PLANAR_ALIGNED, PLANAR_R_ALIGNED = PLANAR_R | PLANAR_ALIGNED, PLANAR_G_ALIGNED = PLANAR_G | PLANAR_ALIGNED, PLANAR_B_ALIGNED = PLANAR_B | PLANAR_ALIGNED, }; class AvisynthError /* exception */ { public: const char* const msg; AvisynthError(const char* _msg) : msg(_msg) {} // Ensure AvisynthError cannot be publicly assigned! private: AvisynthError& operator=(const AvisynthError&); }; // end class AvisynthError enum AvsDeviceType { DEV_TYPE_NONE = 0, DEV_TYPE_CPU = 1, DEV_TYPE_CUDA = 2, DEV_TYPE_ANY = 0xFFFF }; enum AvsValueType { VALUE_TYPE_UNDEFINED = 'v', VALUE_TYPE_BOOL = 'b', VALUE_TYPE_INT = 'i', VALUE_TYPE_LONG = 'l', VALUE_TYPE_FLOAT = 'f', VALUE_TYPE_DOUBLE = 'd', VALUE_TYPE_STRING = 's', VALUE_TYPE_CLIP = 'c', VALUE_TYPE_FUNCTION = 'n', VALUE_TYPE_ARRAY = 'a' }; /* Forward references */ #if defined(MSVC) #define SINGLE_INHERITANCE __single_inheritance #else #define SINGLE_INHERITANCE #endif struct SINGLE_INHERITANCE VideoInfo; class SINGLE_INHERITANCE VideoFrameBuffer; class SINGLE_INHERITANCE VideoFrame; class IClip; class SINGLE_INHERITANCE PClip; class SINGLE_INHERITANCE PVideoFrame; class IScriptEnvironment; class SINGLE_INHERITANCE AVSValue; class INeoEnv; class IFunction; class SINGLE_INHERITANCE PFunction; class Device; class SINGLE_INHERITANCE PDevice; class AVSMap; /* * Avisynth C++ plugin API code function pointers. * * In order to maintain binary compatibility with * future version do not change the order of the * existing function pointers. It will be baked * into all existing plugins. * * Add new function pointers to the end of the * structure. The linkage macros generate some * protection code to ensure newer plugin do not * call non-existing functions in an older host. */ struct AVS_Linkage { int Size; /**********************************************************************/ // struct VideoInfo bool (VideoInfo::*HasVideo)() const; bool (VideoInfo::*HasAudio)() const; bool (VideoInfo::*IsRGB)() const; bool (VideoInfo::*IsRGB24)() const; bool (VideoInfo::*IsRGB32)() const; bool (VideoInfo::*IsYUV)() const; bool (VideoInfo::*IsYUY2)() const; bool (VideoInfo::*IsYV24)() const; bool (VideoInfo::*IsYV16)() const; bool (VideoInfo::*IsYV12)() const; bool (VideoInfo::*IsYV411)() const; bool (VideoInfo::*IsY8)() const; bool (VideoInfo::*IsColorSpace)(int c_space) const; bool (VideoInfo::*Is)(int property) const; bool (VideoInfo::*IsPlanar)() const; bool (VideoInfo::*IsFieldBased)() const; bool (VideoInfo::*IsParityKnown)() const; bool (VideoInfo::*IsBFF)() const; bool (VideoInfo::*IsTFF)() const; bool (VideoInfo::*IsVPlaneFirst)() const; int (VideoInfo::*BytesFromPixels)(int pixels) const; int (VideoInfo::*RowSize)(int plane) const; int (VideoInfo::*BMPSize)() const; int64_t (VideoInfo::*AudioSamplesFromFrames)(int frames) const; int (VideoInfo::*FramesFromAudioSamples)(int64_t samples) const; int64_t (VideoInfo::*AudioSamplesFromBytes)(int64_t bytes) const; int64_t (VideoInfo::*BytesFromAudioSamples)(int64_t samples) const; int (VideoInfo::*AudioChannels)() const; int (VideoInfo::*SampleType)() const; bool (VideoInfo::*IsSampleType)(int testtype) const; int (VideoInfo::*SamplesPerSecond)() const; int (VideoInfo::*BytesPerAudioSample)() const; void (VideoInfo::*SetFieldBased)(bool isfieldbased); void (VideoInfo::*Set)(int property); void (VideoInfo::*Clear)(int property); int (VideoInfo::*GetPlaneWidthSubsampling)(int plane) const; int (VideoInfo::*GetPlaneHeightSubsampling)(int plane) const; int (VideoInfo::*BitsPerPixel)() const; int (VideoInfo::*BytesPerChannelSample)() const; void (VideoInfo::*SetFPS)(unsigned numerator, unsigned denominator); void (VideoInfo::*MulDivFPS)(unsigned multiplier, unsigned divisor); bool (VideoInfo::*IsSameColorspace)(const VideoInfo& vi) const; // end struct VideoInfo /**********************************************************************/ // class VideoFrameBuffer const BYTE* (VideoFrameBuffer::*VFBGetReadPtr)() const; BYTE* (VideoFrameBuffer::*VFBGetWritePtr)(); int (VideoFrameBuffer::*GetDataSize)() const; int (VideoFrameBuffer::*GetSequenceNumber)() const; int (VideoFrameBuffer::*GetRefcount)() const; // end class VideoFrameBuffer /**********************************************************************/ // class VideoFrame int (VideoFrame::*GetPitch)(int plane) const; int (VideoFrame::*GetRowSize)(int plane) const; int (VideoFrame::*GetHeight)(int plane) const; VideoFrameBuffer* (VideoFrame::*GetFrameBuffer)() const; int (VideoFrame::*GetOffset)(int plane) const; const BYTE* (VideoFrame::*VFGetReadPtr)(int plane) const; bool (VideoFrame::*IsWritable)() const; BYTE* (VideoFrame::*VFGetWritePtr)(int plane) const; void (VideoFrame::*VideoFrame_DESTRUCTOR)(); // end class VideoFrame /**********************************************************************/ // class IClip /* nothing */ // end class IClip /**********************************************************************/ // class PClip void (PClip::*PClip_CONSTRUCTOR0)(); void (PClip::*PClip_CONSTRUCTOR1)(const PClip& x); void (PClip::*PClip_CONSTRUCTOR2)(IClip* x); void (PClip::*PClip_OPERATOR_ASSIGN0)(IClip* x); void (PClip::*PClip_OPERATOR_ASSIGN1)(const PClip& x); void (PClip::*PClip_DESTRUCTOR)(); // end class PClip /**********************************************************************/ // class PVideoFrame void (PVideoFrame::*PVideoFrame_CONSTRUCTOR0)(); void (PVideoFrame::*PVideoFrame_CONSTRUCTOR1)(const PVideoFrame& x); void (PVideoFrame::*PVideoFrame_CONSTRUCTOR2)(VideoFrame* x); void (PVideoFrame::*PVideoFrame_OPERATOR_ASSIGN0)(VideoFrame* x); void (PVideoFrame::*PVideoFrame_OPERATOR_ASSIGN1)(const PVideoFrame& x); void (PVideoFrame::*PVideoFrame_DESTRUCTOR)(); // end class PVideoFrame /**********************************************************************/ // class AVSValue void (AVSValue::*AVSValue_CONSTRUCTOR0)(); void (AVSValue::*AVSValue_CONSTRUCTOR1)(IClip* c); void (AVSValue::*AVSValue_CONSTRUCTOR2)(const PClip& c); void (AVSValue::*AVSValue_CONSTRUCTOR3)(bool b); void (AVSValue::*AVSValue_CONSTRUCTOR4)(int i); void (AVSValue::*AVSValue_CONSTRUCTOR5)(float f); void (AVSValue::*AVSValue_CONSTRUCTOR6)(double f); void (AVSValue::*AVSValue_CONSTRUCTOR7)(const char* s); void (AVSValue::*AVSValue_CONSTRUCTOR8)(const AVSValue* a, int size); void (AVSValue::*AVSValue_CONSTRUCTOR9)(const AVSValue& v); void (AVSValue::*AVSValue_DESTRUCTOR)(); AVSValue& (AVSValue::*AVSValue_OPERATOR_ASSIGN)(const AVSValue& v); const AVSValue& (AVSValue::*AVSValue_OPERATOR_INDEX)(int index) const; bool (AVSValue::*Defined)() const; bool (AVSValue::*IsClip)() const; bool (AVSValue::*IsBool)() const; bool (AVSValue::*IsInt)() const; bool (AVSValue::*IsFloat)() const; bool (AVSValue::*IsString)() const; bool (AVSValue::*IsArray)() const; PClip (AVSValue::*AsClip)() const; bool (AVSValue::*AsBool1)() const; int (AVSValue::*AsInt1)() const; const char* (AVSValue::*AsString1)() const; double (AVSValue::*AsFloat1)() const; bool (AVSValue::*AsBool2)(bool def) const; int (AVSValue::*AsInt2)(int def) const; double (AVSValue::*AsDblDef)(double def) const; double (AVSValue::*AsFloat2)(float def) const; const char* (AVSValue::*AsString2)(const char* def) const; int (AVSValue::*ArraySize)() const; // end class AVSValue /**********************************************************************/ // Reserve pointer space so that we can keep compatibility with Avs "classic" even if it adds functions on its own void (VideoInfo::*reserved[32])(); /**********************************************************************/ // AviSynth+ additions int (VideoInfo::*NumComponents)() const; int (VideoInfo::*ComponentSize)() const; int (VideoInfo::*BitsPerComponent)() const; bool (VideoInfo::*Is444)() const; bool (VideoInfo::*Is422)() const; bool (VideoInfo::*Is420)() const; bool (VideoInfo::*IsY)() const; bool (VideoInfo::*IsRGB48)() const; bool (VideoInfo::*IsRGB64)() const; bool (VideoInfo::*IsYUVA)() const; bool (VideoInfo::*IsPlanarRGB)() const; bool (VideoInfo::*IsPlanarRGBA)() const; /**********************************************************************/ // frame property access AVSMap& (VideoFrame::* getProperties)(); const AVSMap& (VideoFrame::* getConstProperties)(); void (VideoFrame::* setProperties)(const AVSMap& properties); // PFunction void (AVSValue::* AVSValue_CONSTRUCTOR11)(const PFunction& o); bool (AVSValue::* IsFunction)() const; void (PFunction::* PFunction_CONSTRUCTOR0)(); void (PFunction::* PFunction_CONSTRUCTOR1)(IFunction* p); void (PFunction::* PFunction_CONSTRUCTOR2)(const PFunction& p); PFunction& (PFunction::* PFunction_OPERATOR_ASSIGN0)(IFunction* other); PFunction& (PFunction::* PFunction_OPERATOR_ASSIGN1)(const PFunction& other); void (PFunction::* PFunction_DESTRUCTOR)(); // end PFunction // extra VideoFrame functions int (VideoFrame::* VideoFrame_CheckMemory)() const; PDevice (VideoFrame::* VideoFrame_GetDevice)() const; // class PDevice, even if only CPU device void (PDevice::* PDevice_CONSTRUCTOR0)(); void (PDevice::* PDevice_CONSTRUCTOR1)(Device* p); void (PDevice::* PDevice_CONSTRUCTOR2)(const PDevice& p); PDevice& (PDevice::* PDevice_OPERATOR_ASSIGN0)(Device* other); PDevice& (PDevice::* PDevice_OPERATOR_ASSIGN1)(const PDevice& other); void (PDevice::* PDevice_DESTRUCTOR)(); AvsDeviceType (PDevice::* PDevice_GetType)() const; int (PDevice::* PDevice_GetId)() const; int (PDevice::* PDevice_GetIndex)() const; const char* (PDevice::* PDevice_GetName)() const; // end class PDevice // V9: VideoFrame helper bool (VideoFrame::*IsPropertyWritable)() const; // V10 int (VideoFrame::*VideoFrame_GetPixelType)() const; void (VideoFrame::*VideoFrame_AmendPixelType)(int new_pixel_type); void (VideoFrameBuffer::*VideoFrameBuffer_DESTRUCTOR)(); AvsValueType (AVSValue::*AVSValue_GetType)() const; // V10.1 bool (VideoInfo::* IsChannelMaskKnown)() const; void (VideoInfo::* SetChannelMask)(bool isChannelMaskKnown, unsigned int dwChannelMask); unsigned int (VideoInfo::* GetChannelMask)() const; /**********************************************************************/ // Reserve pointer space for Avisynth+ void (VideoInfo::* reserved2[64 - 31])(); /**********************************************************************/ // AviSynth Neo additions INeoEnv* (__stdcall *GetNeoEnv)(IScriptEnvironment* env); // As of V8 most PDevice, PFunction linkage entries are moved to standard avs+ place. /**********************************************************************/ // This part should be identical with AVS_Linkage entries in interface.cpp }; #if defined(BUILDING_AVSCORE) || defined(AVS_STATIC_LIB) /* Macro resolution for code inside Avisynth.dll */ # define AVS_BakedCode(arg) ; # define AVS_LinkCall(arg) # define AVS_LinkCallV(arg) # define AVS_LinkCallOpt(arg, argOpt) AVSLinkCall(arg) # define AVS_LinkCallOptDefault(arg, argDefaultValue) AVSLinkCall(arg()) # define CALL_MEMBER_FN(object,ptrToMember) #else /* Macro resolution for code inside user plugin */ # ifdef AVS_LINKAGE_DLLIMPORT extern __declspec(dllimport) const AVS_Linkage* const AVS_linkage; # else extern const AVS_Linkage* AVS_linkage; # endif # ifndef offsetof # include # endif # define AVS_BakedCode(arg) { arg ; } # define AVS_LinkCall(arg) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? 0 : (this->*(AVS_linkage->arg)) # define AVS_LinkCall_Void(arg) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? (void)0 : (this->*(AVS_linkage->arg)) # define AVS_LinkCallV(arg) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? *this : (this->*(AVS_linkage->arg)) // Helper macros for fallback option when a function does not exists #define CALL_MEMBER_FN(object,ptrToMember) ((object)->*(ptrToMember)) #define AVS_LinkCallOpt(arg, argOpt) !AVS_linkage ? 0 : \ ( offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? \ (offsetof(AVS_Linkage, argOpt) >= (size_t)AVS_linkage->Size ? 0 : CALL_MEMBER_FN(this, AVS_linkage->argOpt)() ) : \ CALL_MEMBER_FN(this, AVS_linkage->arg)() ) // AVS_LinkCallOptDefault puts automatically () only after arg # define AVS_LinkCallOptDefault(arg, argDefaultValue) !AVS_linkage || offsetof(AVS_Linkage, arg) >= (size_t)AVS_linkage->Size ? (argDefaultValue) : ((this->*(AVS_linkage->arg))()) #endif class PDevice { public: PDevice() AVS_BakedCode(AVS_LinkCall_Void(PDevice_CONSTRUCTOR0)()) PDevice(Device* p) AVS_BakedCode(AVS_LinkCall_Void(PDevice_CONSTRUCTOR1)(p)) PDevice(const PDevice& p) AVS_BakedCode(AVS_LinkCall_Void(PDevice_CONSTRUCTOR2)(p)) PDevice& operator=(Device* p) AVS_BakedCode(return AVS_LinkCallV(PDevice_OPERATOR_ASSIGN0)(p)) PDevice& operator=(const PDevice& p) AVS_BakedCode(return AVS_LinkCallV(PDevice_OPERATOR_ASSIGN1)(p)) ~PDevice() AVS_BakedCode(AVS_LinkCall_Void(PDevice_DESTRUCTOR)()) int operator!() const { return !e; } operator void*() const { return e; } Device* operator->() const { return e; } AvsDeviceType GetType() const AVS_BakedCode(return AVS_LinkCallOptDefault(PDevice_GetType, DEV_TYPE_NONE)) int GetId() const AVS_BakedCode(return AVS_LinkCall(PDevice_GetId)()) int GetIndex() const AVS_BakedCode(return AVS_LinkCall(PDevice_GetIndex)()) const char* GetName() const AVS_BakedCode(return AVS_LinkCall(PDevice_GetName)()) private: Device * e; #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(Device* p); void CONSTRUCTOR2(const PDevice& p); PDevice& OPERATOR_ASSIGN0(Device* p); PDevice& OPERATOR_ASSIGN1(const PDevice& p); void DESTRUCTOR(); #endif }; // Unshifted channel mask constants like in WAVEFORMATEXTENSIBLE // in AvsImageTypeFlags they are shifted by 4 bits enum AvsChannelMask { MASK_SPEAKER_FRONT_LEFT = 0x1, MASK_SPEAKER_FRONT_RIGHT = 0x2, MASK_SPEAKER_FRONT_CENTER = 0x4, MASK_SPEAKER_LOW_FREQUENCY = 0x8, MASK_SPEAKER_BACK_LEFT = 0x10, MASK_SPEAKER_BACK_RIGHT = 0x20, MASK_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40, MASK_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80, MASK_SPEAKER_BACK_CENTER = 0x100, MASK_SPEAKER_SIDE_LEFT = 0x200, MASK_SPEAKER_SIDE_RIGHT = 0x400, MASK_SPEAKER_TOP_CENTER = 0x800, MASK_SPEAKER_TOP_FRONT_LEFT = 0x1000, MASK_SPEAKER_TOP_FRONT_CENTER = 0x2000, MASK_SPEAKER_TOP_FRONT_RIGHT = 0x4000, MASK_SPEAKER_TOP_BACK_LEFT = 0x8000, MASK_SPEAKER_TOP_BACK_CENTER = 0x10000, MASK_SPEAKER_TOP_BACK_RIGHT = 0x20000, // Bit mask locations used up for the above positions MASK_SPEAKER_DEFINED = 0x0003FFFF, // Bit mask locations reserved for future use MASK_SPEAKER_RESERVED = 0x7FFC0000, // Used to specify that any possible permutation of speaker configurations // Due to lack of available bits this one is put differently into image_type MASK_SPEAKER_ALL = 0x80000000 }; struct VideoInfo { int width, height; // width 0 means no video unsigned fps_numerator, fps_denominator; int num_frames; // This is more extensible than previous versions. More properties can be added seamlessly. // Colorspace properties. /* Planar match mask 1111.1000.0000.0111.0000.0111.0000.0111 Planar signature 10xx.1000.0000.00xx.0000.00xx.00xx.00xx ? Planar signature 10xx.1000.0000.0xxx.0000.00xx.000x.x0xx ? *new Planar filter mask 1111.1111.1111.1111.1111.1111.1110.0111 (typo from old header fixed) pixel_type mapping ================== pixel_type bit-map PIYB.Z000.0???.0SSS.0000.0???.????.???? planar YUV CCC HHH.000u.vWWW planar RGB(A) CCC AR nonplanar CCC 000.00wx xyAR Legend ====== Planar YUV: Code Bits Remark W 0-2 Planar Width Subsampling bits Use (X+1) & 3 for GetPlaneWidthSubsampling 000 => 1 YV12, YV16, YUV420, YUV422 001 => 2 YV411, YUV9 010 => reserved 011 => 0 YV24, YUV444, RGBP 1xx => reserved v 3 VPlaneFirst YV12, YV16, YV24, YV411, YUV9 u 4 UPlaneFirst I420 H 7-9 Planar Height Subsampling bits Use ((X>>8)+1) & 3 for GetPlaneHeightSubsampling 000 => 1 YV12, YUV420 001 => 2 YUV9 010 => reserved 011 => 0 YV16, YV24, YV411, YUV422, YUV444, RGBP 1xx => reserved Planar RGB Code Bits Remark R 0 BGR, (with SSS bits for 8/16 bit/sample or float) A 1 BGRA, (with SSS bits for 8/16 bit/sample or float) Not Planar, Interleaved (I flag) Code Bits Remark R 0 BGR24, and BGRx in future (with SSS bits for 8/16 bit/sample or float) A 1 BGR32, and BGRAx in future (with SSS bits for 8/16 bit/sample or float) y 2 YUY2 x 3-4 reserved w 5 Raw32 General Code Bits Remark S 16-18 Sample resolution bits 000 => 8 001 => 16 010 => 32 (float) 011,100 => reserved 101 => 10 bits 110 => 12 bits 111 => 14 bits for packed RGB(A): only 8 and 16 bits are valid Other YV12 specific (will never be used) C 20-23 Chroma Placement values 0-4; see CS_xxx_CHROMA_PLACEMENT Color family and layout Packed Planar Planar Planar Code Bits Remark RGB/RGBA YUV YUY2 Y_Grey RGB/RGBA YUVA R 0 1/0 - 0 - 1/0 - A 1 0/1 - 0 - 0/1 - y 2 - - 1 - 0 - Z 27 YUVA 0 0 0 0 1 1 B 28 BGR 1 0 0 0 1* 0 Y 29 YUV 0 1 1 1 0 0 I 30 Interleaved 1 0 1 1 0 0 P 31 Planar 0 1 0 1 1 1 * Planar RGB plane order: G,B,R(,A) */ enum AvsColorFormat { CS_YUVA = 1 << 27, CS_BGR = 1 << 28, CS_YUV = 1 << 29, CS_INTERLEAVED = 1 << 30, CS_PLANAR = 1 << 31, CS_Shift_Sub_Width = 0, CS_Shift_Sub_Height = 8, CS_Shift_Sample_Bits = 16, CS_Sub_Width_Mask = 7 << CS_Shift_Sub_Width, CS_Sub_Width_1 = 3 << CS_Shift_Sub_Width, // YV24 CS_Sub_Width_2 = 0 << CS_Shift_Sub_Width, // YV12, I420, YV16 CS_Sub_Width_4 = 1 << CS_Shift_Sub_Width, // YUV9, YV411 CS_VPlaneFirst = 1 << 3, // YV12, YV16, YV24, YV411, YUV9 CS_UPlaneFirst = 1 << 4, // I420 CS_Sub_Height_Mask = 7 << CS_Shift_Sub_Height, CS_Sub_Height_1 = 3 << CS_Shift_Sub_Height, // YV16, YV24, YV411 CS_Sub_Height_2 = 0 << CS_Shift_Sub_Height, // YV12, I420 CS_Sub_Height_4 = 1 << CS_Shift_Sub_Height, // YUV9 CS_Sample_Bits_Mask = 7 << CS_Shift_Sample_Bits, CS_Sample_Bits_8 = 0 << CS_Shift_Sample_Bits, CS_Sample_Bits_10 = 5 << CS_Shift_Sample_Bits, CS_Sample_Bits_12 = 6 << CS_Shift_Sample_Bits, CS_Sample_Bits_14 = 7 << CS_Shift_Sample_Bits, CS_Sample_Bits_16 = 1 << CS_Shift_Sample_Bits, CS_Sample_Bits_32 = 2 << CS_Shift_Sample_Bits, CS_PLANAR_MASK = CS_PLANAR | CS_INTERLEAVED | CS_YUV | CS_BGR | CS_YUVA | CS_Sample_Bits_Mask | CS_Sub_Width_Mask | CS_Sub_Height_Mask, CS_PLANAR_FILTER = ~(CS_VPlaneFirst | CS_UPlaneFirst), CS_RGB_TYPE = 1 << 0, CS_RGBA_TYPE = 1 << 1, // Specific colorformats CS_UNKNOWN = 0, CS_BGR24 = CS_RGB_TYPE | CS_BGR | CS_INTERLEAVED, CS_BGR32 = CS_RGBA_TYPE | CS_BGR | CS_INTERLEAVED, CS_YUY2 = 1 << 2 | CS_YUV | CS_INTERLEAVED, // CS_YV12 = 1 << 3 Reserved // CS_I420 = 1 << 4 Reserved CS_RAW32 = 1 << 5 | CS_INTERLEAVED, // YV12 must be 0xA0000008. v2.5 Baked API will see all new planar as YV12. // I420 must be 0xA0000010. CS_GENERIC_YUV444 = CS_PLANAR | CS_YUV | CS_VPlaneFirst | CS_Sub_Width_1 | CS_Sub_Height_1, // 4:4:4 planar CS_GENERIC_YUV422 = CS_PLANAR | CS_YUV | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_1, // 4:2:2 planar CS_GENERIC_YUV420 = CS_PLANAR | CS_YUV | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_2, // 4:2:0 planar CS_GENERIC_Y = CS_PLANAR | CS_INTERLEAVED | CS_YUV, // Y only (4:0:0) CS_GENERIC_RGBP = CS_PLANAR | CS_BGR | CS_RGB_TYPE, // planar RGB. Though name is RGB but plane order G,B,R CS_GENERIC_RGBAP = CS_PLANAR | CS_BGR | CS_RGBA_TYPE, // planar RGBA CS_GENERIC_YUVA444 = CS_PLANAR | CS_YUVA | CS_VPlaneFirst | CS_Sub_Width_1 | CS_Sub_Height_1, // 4:4:4:A planar CS_GENERIC_YUVA422 = CS_PLANAR | CS_YUVA | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_1, // 4:2:2:A planar CS_GENERIC_YUVA420 = CS_PLANAR | CS_YUVA | CS_VPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_2, // 4:2:0:A planar CS_YV24 = CS_GENERIC_YUV444 | CS_Sample_Bits_8, // YVU 4:4:4 planar CS_YV16 = CS_GENERIC_YUV422 | CS_Sample_Bits_8, // YVU 4:2:2 planar CS_YV12 = CS_GENERIC_YUV420 | CS_Sample_Bits_8, // YVU 4:2:0 planar CS_I420 = CS_PLANAR | CS_YUV | CS_Sample_Bits_8 | CS_UPlaneFirst | CS_Sub_Width_2 | CS_Sub_Height_2, // YUV 4:2:0 planar CS_IYUV = CS_I420, CS_YUV9 = CS_PLANAR | CS_YUV | CS_Sample_Bits_8 | CS_VPlaneFirst | CS_Sub_Width_4 | CS_Sub_Height_4, // YUV 4:1:0 planar CS_YV411 = CS_PLANAR | CS_YUV | CS_Sample_Bits_8 | CS_VPlaneFirst | CS_Sub_Width_4 | CS_Sub_Height_1, // YUV 4:1:1 planar CS_Y8 = CS_GENERIC_Y | CS_Sample_Bits_8, // Y 4:0:0 planar //------------------------- // AVS16: new planar constants go live! Experimental PF 160613 // 10-12-14 bit + planar RGB + BRG48/64 160725 CS_YUV444P10 = CS_GENERIC_YUV444 | CS_Sample_Bits_10, // YUV 4:4:4 10bit samples CS_YUV422P10 = CS_GENERIC_YUV422 | CS_Sample_Bits_10, // YUV 4:2:2 10bit samples CS_YUV420P10 = CS_GENERIC_YUV420 | CS_Sample_Bits_10, // YUV 4:2:0 10bit samples CS_Y10 = CS_GENERIC_Y | CS_Sample_Bits_10, // Y 4:0:0 10bit samples CS_YUV444P12 = CS_GENERIC_YUV444 | CS_Sample_Bits_12, // YUV 4:4:4 12bit samples CS_YUV422P12 = CS_GENERIC_YUV422 | CS_Sample_Bits_12, // YUV 4:2:2 12bit samples CS_YUV420P12 = CS_GENERIC_YUV420 | CS_Sample_Bits_12, // YUV 4:2:0 12bit samples CS_Y12 = CS_GENERIC_Y | CS_Sample_Bits_12, // Y 4:0:0 12bit samples CS_YUV444P14 = CS_GENERIC_YUV444 | CS_Sample_Bits_14, // YUV 4:4:4 14bit samples CS_YUV422P14 = CS_GENERIC_YUV422 | CS_Sample_Bits_14, // YUV 4:2:2 14bit samples CS_YUV420P14 = CS_GENERIC_YUV420 | CS_Sample_Bits_14, // YUV 4:2:0 14bit samples CS_Y14 = CS_GENERIC_Y | CS_Sample_Bits_14, // Y 4:0:0 14bit samples CS_YUV444P16 = CS_GENERIC_YUV444 | CS_Sample_Bits_16, // YUV 4:4:4 16bit samples CS_YUV422P16 = CS_GENERIC_YUV422 | CS_Sample_Bits_16, // YUV 4:2:2 16bit samples CS_YUV420P16 = CS_GENERIC_YUV420 | CS_Sample_Bits_16, // YUV 4:2:0 16bit samples CS_Y16 = CS_GENERIC_Y | CS_Sample_Bits_16, // Y 4:0:0 16bit samples // 32 bit samples (float) CS_YUV444PS = CS_GENERIC_YUV444 | CS_Sample_Bits_32, // YUV 4:4:4 32bit samples CS_YUV422PS = CS_GENERIC_YUV422 | CS_Sample_Bits_32, // YUV 4:2:2 32bit samples CS_YUV420PS = CS_GENERIC_YUV420 | CS_Sample_Bits_32, // YUV 4:2:0 32bit samples CS_Y32 = CS_GENERIC_Y | CS_Sample_Bits_32, // Y 4:0:0 32bit samples // RGB packed CS_BGR48 = CS_RGB_TYPE | CS_BGR | CS_INTERLEAVED | CS_Sample_Bits_16, // BGR 3x16 bit CS_BGR64 = CS_RGBA_TYPE | CS_BGR | CS_INTERLEAVED | CS_Sample_Bits_16, // BGR 4x16 bit // no packed 32 bit (float) support for these legacy types // RGB planar CS_RGBP = CS_GENERIC_RGBP | CS_Sample_Bits_8, // Planar RGB 8 bit samples CS_RGBP8 = CS_GENERIC_RGBP | CS_Sample_Bits_8, // Planar RGB 8 bit samples CS_RGBP10 = CS_GENERIC_RGBP | CS_Sample_Bits_10, // Planar RGB 10bit samples CS_RGBP12 = CS_GENERIC_RGBP | CS_Sample_Bits_12, // Planar RGB 12bit samples CS_RGBP14 = CS_GENERIC_RGBP | CS_Sample_Bits_14, // Planar RGB 14bit samples CS_RGBP16 = CS_GENERIC_RGBP | CS_Sample_Bits_16, // Planar RGB 16bit samples CS_RGBPS = CS_GENERIC_RGBP | CS_Sample_Bits_32, // Planar RGB 32bit samples // RGBA planar CS_RGBAP = CS_GENERIC_RGBAP | CS_Sample_Bits_8, // Planar RGBA 8 bit samples CS_RGBAP8 = CS_GENERIC_RGBAP | CS_Sample_Bits_8, // Planar RGBA 8 bit samples CS_RGBAP10 = CS_GENERIC_RGBAP | CS_Sample_Bits_10, // Planar RGBA 10bit samples CS_RGBAP12 = CS_GENERIC_RGBAP | CS_Sample_Bits_12, // Planar RGBA 12bit samples CS_RGBAP14 = CS_GENERIC_RGBAP | CS_Sample_Bits_14, // Planar RGBA 14bit samples CS_RGBAP16 = CS_GENERIC_RGBAP | CS_Sample_Bits_16, // Planar RGBA 16bit samples CS_RGBAPS = CS_GENERIC_RGBAP | CS_Sample_Bits_32, // Planar RGBA 32bit samples // Planar YUVA CS_YUVA444 = CS_GENERIC_YUVA444 | CS_Sample_Bits_8, // YUVA 4:4:4 8bit samples CS_YUVA422 = CS_GENERIC_YUVA422 | CS_Sample_Bits_8, // YUVA 4:2:2 8bit samples CS_YUVA420 = CS_GENERIC_YUVA420 | CS_Sample_Bits_8, // YUVA 4:2:0 8bit samples CS_YUVA444P10 = CS_GENERIC_YUVA444 | CS_Sample_Bits_10, // YUVA 4:4:4 10bit samples CS_YUVA422P10 = CS_GENERIC_YUVA422 | CS_Sample_Bits_10, // YUVA 4:2:2 10bit samples CS_YUVA420P10 = CS_GENERIC_YUVA420 | CS_Sample_Bits_10, // YUVA 4:2:0 10bit samples CS_YUVA444P12 = CS_GENERIC_YUVA444 | CS_Sample_Bits_12, // YUVA 4:4:4 12bit samples CS_YUVA422P12 = CS_GENERIC_YUVA422 | CS_Sample_Bits_12, // YUVA 4:2:2 12bit samples CS_YUVA420P12 = CS_GENERIC_YUVA420 | CS_Sample_Bits_12, // YUVA 4:2:0 12bit samples CS_YUVA444P14 = CS_GENERIC_YUVA444 | CS_Sample_Bits_14, // YUVA 4:4:4 14bit samples CS_YUVA422P14 = CS_GENERIC_YUVA422 | CS_Sample_Bits_14, // YUVA 4:2:2 14bit samples CS_YUVA420P14 = CS_GENERIC_YUVA420 | CS_Sample_Bits_14, // YUVA 4:2:0 14bit samples CS_YUVA444P16 = CS_GENERIC_YUVA444 | CS_Sample_Bits_16, // YUVA 4:4:4 16bit samples CS_YUVA422P16 = CS_GENERIC_YUVA422 | CS_Sample_Bits_16, // YUVA 4:2:2 16bit samples CS_YUVA420P16 = CS_GENERIC_YUVA420 | CS_Sample_Bits_16, // YUVA 4:2:0 16bit samples CS_YUVA444PS = CS_GENERIC_YUVA444 | CS_Sample_Bits_32, // YUVA 4:4:4 32bit samples CS_YUVA422PS = CS_GENERIC_YUVA422 | CS_Sample_Bits_32, // YUVA 4:2:2 32bit samples CS_YUVA420PS = CS_GENERIC_YUVA420 | CS_Sample_Bits_32, // YUVA 4:2:0 32bit samples }; int pixel_type; // changed to int as of 2.5 int audio_samples_per_second; // 0 means no audio int sample_type; // as of 2.5 int64_t num_audio_samples; // changed as of 2.5 int nchannels; // as of 2.5 // BFF, TFF, FIELDBASED. Also used for storing Channel Mask int image_type; enum AvsImageTypeFlags { IT_BFF = 1 << 0, IT_TFF = 1 << 1, IT_FIELDBASED = 1 << 2, // Audio channel mask support IT_HAS_CHANNELMASK = 1 << 3, // shifted by 4 bits compared to WAVEFORMATEXTENSIBLE dwChannelMask // otherwise same as AvsChannelMask IT_SPEAKER_FRONT_LEFT = 0x1 << 4, IT_SPEAKER_FRONT_RIGHT = 0x2 << 4, IT_SPEAKER_FRONT_CENTER = 0x4 << 4, IT_SPEAKER_LOW_FREQUENCY = 0x8 << 4, IT_SPEAKER_BACK_LEFT = 0x10 << 4, IT_SPEAKER_BACK_RIGHT = 0x20 << 4, IT_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40 << 4, IT_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80 << 4, IT_SPEAKER_BACK_CENTER = 0x100 << 4, IT_SPEAKER_SIDE_LEFT = 0x200 << 4, IT_SPEAKER_SIDE_RIGHT = 0x400 << 4, IT_SPEAKER_TOP_CENTER = 0x800 << 4, IT_SPEAKER_TOP_FRONT_LEFT = 0x1000 << 4, IT_SPEAKER_TOP_FRONT_CENTER = 0x2000 << 4, IT_SPEAKER_TOP_FRONT_RIGHT = 0x4000 << 4, IT_SPEAKER_TOP_BACK_LEFT = 0x8000 << 4, IT_SPEAKER_TOP_BACK_CENTER = 0x10000 << 4, IT_SPEAKER_TOP_BACK_RIGHT = 0x20000 << 4, // End of officially defined speaker bits // The next one is special, since cannot shift SPEAKER_ALL 0x80000000 further. // Set mask and get mask handles it. IT_SPEAKER_ALL = 0x40000 << 4, // Mask for the defined 18 bits + SPEAKER_ALL IT_SPEAKER_BITS_MASK = (AvsChannelMask::MASK_SPEAKER_DEFINED << 4) | IT_SPEAKER_ALL, IT_NEXT_AVAILABLE = 1 << 23 }; // Chroma placement bits 20 -> 23 ::FIXME:: Really want a Class to support this enum AvsChromaPlacement { CS_UNKNOWN_CHROMA_PLACEMENT = 0 << 20, CS_MPEG1_CHROMA_PLACEMENT = 1 << 20, CS_MPEG2_CHROMA_PLACEMENT = 2 << 20, CS_YUY2_CHROMA_PLACEMENT = 3 << 20, CS_TOPLEFT_CHROMA_PLACEMENT = 4 << 20 }; // useful functions of the above bool HasVideo() const AVS_BakedCode(return AVS_LinkCall(HasVideo)()) bool HasAudio() const AVS_BakedCode(return AVS_LinkCall(HasAudio)()) bool IsRGB() const AVS_BakedCode(return AVS_LinkCall(IsRGB)()) bool IsRGB24() const AVS_BakedCode(return AVS_LinkCall(IsRGB24)()) bool IsRGB32() const AVS_BakedCode(return AVS_LinkCall(IsRGB32)()) bool IsYUV() const AVS_BakedCode(return AVS_LinkCall(IsYUV)()) bool IsYUY2() const AVS_BakedCode(return AVS_LinkCall(IsYUY2)()) bool IsYV24() const AVS_BakedCode(return AVS_LinkCall(IsYV24)()) bool IsYV16() const AVS_BakedCode(return AVS_LinkCall(IsYV16)()) bool IsYV12() const AVS_BakedCode(return AVS_LinkCall(IsYV12)()) bool IsYV411() const AVS_BakedCode(return AVS_LinkCall(IsYV411)()) //bool IsYUV9() const; bool IsY8() const AVS_BakedCode(return AVS_LinkCall(IsY8)()) bool IsColorSpace(int c_space) const AVS_BakedCode(return AVS_LinkCall(IsColorSpace)(c_space)) bool Is(int property) const AVS_BakedCode(return AVS_LinkCall(Is)(property)) bool IsPlanar() const AVS_BakedCode(return AVS_LinkCall(IsPlanar)()) bool IsFieldBased() const AVS_BakedCode(return AVS_LinkCall(IsFieldBased)()) bool IsParityKnown() const AVS_BakedCode(return AVS_LinkCall(IsParityKnown)()) bool IsBFF() const AVS_BakedCode(return AVS_LinkCall(IsBFF)()) bool IsTFF() const AVS_BakedCode(return AVS_LinkCall(IsTFF)()) bool IsVPlaneFirst() const AVS_BakedCode(return AVS_LinkCall(IsVPlaneFirst)()) // Don't use this // Will not work on planar images, but will return only luma planes int BytesFromPixels(int pixels) const AVS_BakedCode(return AVS_LinkCall(BytesFromPixels)(pixels)) int RowSize(int plane = DEFAULT_PLANE) const AVS_BakedCode(return AVS_LinkCall(RowSize)(plane)) int BMPSize() const AVS_BakedCode(return AVS_LinkCall(BMPSize)()) int64_t AudioSamplesFromFrames(int frames) const AVS_BakedCode(return AVS_LinkCall(AudioSamplesFromFrames)(frames)) int FramesFromAudioSamples(int64_t samples) const AVS_BakedCode(return AVS_LinkCall(FramesFromAudioSamples)(samples)) int64_t AudioSamplesFromBytes(int64_t bytes) const AVS_BakedCode(return AVS_LinkCall(AudioSamplesFromBytes)(bytes)) int64_t BytesFromAudioSamples(int64_t samples) const AVS_BakedCode(return AVS_LinkCall(BytesFromAudioSamples)(samples)) int AudioChannels() const AVS_BakedCode(return AVS_LinkCall(AudioChannels)()) int SampleType() const AVS_BakedCode(return AVS_LinkCall(SampleType)()) bool IsSampleType(int testtype) const AVS_BakedCode(return AVS_LinkCall(IsSampleType)(testtype)) int SamplesPerSecond() const AVS_BakedCode(return AVS_LinkCall(SamplesPerSecond)()) int BytesPerAudioSample() const AVS_BakedCode(return AVS_LinkCall(BytesPerAudioSample)()) void SetFieldBased(bool isfieldbased) AVS_BakedCode(AVS_LinkCall_Void(SetFieldBased)(isfieldbased)) void Set(int property) AVS_BakedCode(AVS_LinkCall_Void(Set)(property)) void Clear(int property) AVS_BakedCode(AVS_LinkCall_Void(Clear)(property)) // Subsampling in bitshifts! int GetPlaneWidthSubsampling(int plane) const AVS_BakedCode(return AVS_LinkCall(GetPlaneWidthSubsampling)(plane)) int GetPlaneHeightSubsampling(int plane) const AVS_BakedCode(return AVS_LinkCall(GetPlaneHeightSubsampling)(plane)) int BitsPerPixel() const AVS_BakedCode(return AVS_LinkCall(BitsPerPixel)()) int BytesPerChannelSample() const AVS_BakedCode(return AVS_LinkCall(BytesPerChannelSample)()) // useful mutator void SetFPS(unsigned numerator, unsigned denominator) AVS_BakedCode(AVS_LinkCall_Void(SetFPS)(numerator, denominator)) // Range protected multiply-divide of FPS void MulDivFPS(unsigned multiplier, unsigned divisor) AVS_BakedCode(AVS_LinkCall_Void(MulDivFPS)(multiplier, divisor)) // Test for same colorspace bool IsSameColorspace(const VideoInfo& vi) const AVS_BakedCode(return AVS_LinkCall(IsSameColorspace)(vi)) // AVS+ extensions // 20161005: // Mapping of AVS+ extensions to classic 2.6 functions. // In order to use these extended AVS+ functions for plugins that should work // either with AVS+ or with Classic (8 bit) Avs 2.6 ans earlier AVS+ versions, there is an // automatic fallback mechanism. // From AVS+'s point of view these are not "baked" codes, the primary functions should exist. // Examples: // Is444() is mapped to IsYV24() for classic AVS2.6 // ComponentSize() returns constant 1 (1 bytes per pixel component) // BitsPerComponent() returns constant 8 (Classic AVS2.6 is 8 bit only) // Returns the number of color channels or planes in a frame int NumComponents() const AVS_BakedCode(return AVS_LinkCallOptDefault(NumComponents, (((AVS_LinkCall(IsYUV)()) && !(AVS_LinkCall(IsY8)())) ? 3 : AVS_LinkCall(BytesFromPixels)(1)) ) ) // Returns the size in bytes of a single component of a pixel int ComponentSize() const AVS_BakedCode(return AVS_LinkCallOptDefault(ComponentSize, 1)) // Returns the bit depth of a single component of a pixel int BitsPerComponent() const AVS_BakedCode(return AVS_LinkCallOptDefault(BitsPerComponent, 8)) // like IsYV24, but bit-depth independent also for YUVA bool Is444() const AVS_BakedCode(return AVS_LinkCallOpt(Is444, IsYV24) ) // like IsYV16, but bit-depth independent also for YUVA bool Is422() const AVS_BakedCode(return AVS_LinkCallOpt(Is422, IsYV16) ) // like IsYV12, but bit-depth independent also for YUVA bool Is420() const AVS_BakedCode( return AVS_LinkCallOpt(Is420, IsYV12) ) // like IsY8, but bit-depth independent bool IsY() const AVS_BakedCode( return AVS_LinkCallOpt(IsY, IsY8) ) // like IsRGB24 for 16 bit samples bool IsRGB48() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsRGB48, false) ) // like IsRGB32 for 16 bit samples bool IsRGB64() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsRGB64, false) ) // YUVA? bool IsYUVA() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsYUVA, false) ) // Planar RGB? bool IsPlanarRGB() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsPlanarRGB, false) ) // Planar RGBA? bool IsPlanarRGBA() const AVS_BakedCode( return AVS_LinkCallOptDefault(IsPlanarRGBA, false) ) // v10.1 interface: audio channel masks bool IsChannelMaskKnown() const AVS_BakedCode(return AVS_LinkCallOptDefault(IsChannelMaskKnown, false) ) void SetChannelMask(bool isChannelMaskKnown, unsigned int dwChannelMask) AVS_BakedCode(AVS_LinkCall_Void(SetChannelMask)(isChannelMaskKnown, dwChannelMask)) unsigned int GetChannelMask() const AVS_BakedCode(return AVS_LinkCallOptDefault(GetChannelMask, 0) ) }; // end struct VideoInfo // VideoFrameBuffer holds information about a memory block which is used // for video data. For efficiency, instances of this class are not deleted // when the refcount reaches zero; instead they're stored in a linked list // to be reused. The instances are deleted when the corresponding AVS // file is closed. class VideoFrameBuffer { BYTE* data; int data_size; // sequence_number is incremented every time the buffer is changed, so // that stale views can tell they're no longer valid. volatile long sequence_number; friend class VideoFrame; friend class Cache; friend class ScriptEnvironment; volatile long refcount; // AVS+CUDA extension, does not break plugins if appended here Device* device; protected: VideoFrameBuffer(int size, int margin, Device* device); VideoFrameBuffer(); public: ~VideoFrameBuffer() AVS_BakedCode(AVS_LinkCall_Void(VideoFrameBuffer_DESTRUCTOR)()) const BYTE* GetReadPtr() const AVS_BakedCode( return AVS_LinkCall(VFBGetReadPtr)() ) BYTE* GetWritePtr() AVS_BakedCode( return AVS_LinkCall(VFBGetWritePtr)() ) int GetDataSize() const AVS_BakedCode( return AVS_LinkCall(GetDataSize)() ) int GetSequenceNumber() const AVS_BakedCode( return AVS_LinkCall(GetSequenceNumber)() ) int GetRefcount() const AVS_BakedCode( return AVS_LinkCall(GetRefcount)() ) // Ensure VideoFrameBuffer cannot be publicly assigned private: VideoFrameBuffer& operator=(const VideoFrameBuffer&); #ifdef BUILDING_AVSCORE public: void DESTRUCTOR(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ #endif }; // end class VideoFrameBuffer // smart pointer to VideoFrame class PVideoFrame { VideoFrame* p; void Init(VideoFrame* x); void Set(VideoFrame* x); public: PVideoFrame() AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_CONSTRUCTOR0)()) PVideoFrame(const PVideoFrame& x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_CONSTRUCTOR1)(x)) PVideoFrame(VideoFrame* x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_CONSTRUCTOR2)(x)) void operator=(VideoFrame* x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_OPERATOR_ASSIGN0)(x)) void operator=(const PVideoFrame& x) AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_OPERATOR_ASSIGN1)(x)) VideoFrame* operator->() const { return p; } // for conditional expressions operator void*() const { return p; } bool operator!() const { return !p; } ~PVideoFrame() AVS_BakedCode(AVS_LinkCall_Void(PVideoFrame_DESTRUCTOR)()) #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(const PVideoFrame& x); void CONSTRUCTOR2(VideoFrame* x); void OPERATOR_ASSIGN0(VideoFrame* x); void OPERATOR_ASSIGN1(const PVideoFrame& x); void DESTRUCTOR(); #endif }; // end class PVideoFrame // VideoFrame holds a "window" into a VideoFrameBuffer. Operator new // is overloaded to recycle class instances. class VideoFrame { volatile long refcount; VideoFrameBuffer* vfb; // Due to technical reasons these members are not const, but should be treated as such. // That means do not modify them once the class has been constructed. int offset; int pitch, row_size, height; int offsetU, offsetV; // U&V offsets are from top of picture. int pitchUV, row_sizeUV, heightUV; // for Planar RGB offsetU, offsetV is for the 2nd and 3rd Plane. // for Planar RGB pitchUV and row_sizeUV = 0, because when no VideoInfo (MakeWriteable) // the decision on existance of UV is checked by zero pitch // AVS+ extension, does not break plugins if appended here int offsetA; int pitchA, row_sizeA; // 4th alpha plane support, pitch and row_size is 0 is none AVSMap *properties; // this one is changable by AmendPixelType in rare cases int pixel_type; // V10 - Copy from VideoInfo friend class PVideoFrame; void AddRef(); void Release(); friend class ScriptEnvironment; friend class Cache; VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height, int _pixel_type); VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height, int _offsetU, int _offsetV, int _pitchUV, int _row_sizeUV, int _heightUV, int _pixel_type); // for Alpha VideoFrame(VideoFrameBuffer* _vfb, AVSMap* avsmap, int _offset, int _pitch, int _row_size, int _height, int _offsetU, int _offsetV, int _pitchUV, int _row_sizeUV, int _heightUV, int _offsetA, int _pixel_type); void* operator new(size_t size); // TESTME: OFFSET U/V may be switched to what could be expected from AVI standard! public: int GetPitch(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetPitch)(plane) ) int GetRowSize(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetRowSize)(plane) ) int GetHeight(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetHeight)(plane) ) // generally you shouldn't use these three VideoFrameBuffer* GetFrameBuffer() const AVS_BakedCode( return AVS_LinkCall(GetFrameBuffer)() ) int GetOffset(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(GetOffset)(plane) ) // in plugins use env->SubFrame() -- because implementation code is only available inside avisynth.dll. Doh! VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height) const; VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int pitchUV) const; // for Alpha VideoFrame* Subframe(int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int pitchUV, int rel_offsetA) const; const BYTE* GetReadPtr(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(VFGetReadPtr)(plane) ) bool IsWritable() const AVS_BakedCode( return AVS_LinkCall(IsWritable)() ) BYTE* GetWritePtr(int plane = DEFAULT_PLANE) const AVS_BakedCode( return AVS_LinkCall(VFGetWritePtr)(plane) ) AVSMap& getProperties() AVS_BakedCode(return AVS_LinkCallOptDefault(getProperties, (AVSMap&)*(AVSMap*)0)) const AVSMap& getConstProperties() AVS_BakedCode(return AVS_LinkCallOptDefault(getConstProperties, (const AVSMap&)*(const AVSMap*)0)) void setProperties(const AVSMap & _properties) AVS_BakedCode(AVS_LinkCall_Void(setProperties)(_properties)) PDevice GetDevice() const AVS_BakedCode(return AVS_LinkCall(VideoFrame_GetDevice)()) // 0: OK, 1: NG, -1: disabled or non CPU frame int CheckMemory() const AVS_BakedCode(return AVS_LinkCall(VideoFrame_CheckMemory)()) bool IsPropertyWritable() const AVS_BakedCode(return AVS_LinkCall(IsPropertyWritable)()) ~VideoFrame() AVS_BakedCode( AVS_LinkCall_Void(VideoFrame_DESTRUCTOR)() ) int GetPixelType() const AVS_BakedCode(return AVS_LinkCall(VideoFrame_GetPixelType)()) // Changes the color format metadata on this frame. Using it on a frame that isn't writable leads // to an inconsistent state, because other filters depend on it. So, use MakeWritable() before. // Only for rare cases where a plugin makes frame bytes pose as another color format. void AmendPixelType(int new_pixel_type) AVS_BakedCode(return AVS_LinkCall_Void(VideoFrame_AmendPixelType)(new_pixel_type)) #ifdef BUILDING_AVSCORE public: void DESTRUCTOR(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ #endif // Ensure VideoFrame cannot be publicly assigned private: VideoFrame& operator=(const VideoFrame&); }; // end class VideoFrame enum CachePolicyHint { // Values 0 to 5 are reserved for old 2.5 plugins // do not use them in new plugins // New 2.6 explicitly defined cache hints. CACHE_NOTHING = 10, // Do not cache video. CACHE_WINDOW = 11, // Hard protect upto X frames within a range of X from the current frame N. CACHE_GENERIC = 12, // LRU cache upto X frames. CACHE_FORCE_GENERIC = 13, // LRU cache upto X frames, override any previous CACHE_WINDOW. CACHE_GET_POLICY = 30, // Get the current policy. CACHE_GET_WINDOW = 31, // Get the current window h_span. CACHE_GET_RANGE = 32, // Get the current generic frame range. // Set Audio cache mode and answers to CACHE_GETCHILD_AUDIO_MODE CACHE_AUDIO = 50, // Explicitly cache audio, X byte cache. CACHE_AUDIO_NOTHING = 51, // Explicitly do not cache audio. CACHE_AUDIO_NONE = 52, // Audio cache off (auto mode), X byte initial cache. CACHE_AUDIO_AUTO_START_OFF = 52, // synonym CACHE_AUDIO_AUTO = 53, // Audio cache on (auto mode), X byte initial cache. CACHE_AUDIO_AUTO_START_ON = 53, // synonym // These just returns actual value if clip is cached CACHE_GET_AUDIO_POLICY = 70, // Get the current audio policy. CACHE_GET_AUDIO_SIZE = 71, // Get the current audio cache size. CACHE_PREFETCH_FRAME = 100, // n/a Queue request to prefetch frame N. CACHE_PREFETCH_GO = 101, // n/a Action video prefetches. CACHE_PREFETCH_AUDIO_BEGIN = 120, // n/a Begin queue request transaction to prefetch audio (take critical section). CACHE_PREFETCH_AUDIO_STARTLO = 121, // n/a Set low 32 bits of start. CACHE_PREFETCH_AUDIO_STARTHI = 122, // n/a Set high 32 bits of start. CACHE_PREFETCH_AUDIO_COUNT = 123, // n/a Set low 32 bits of length. CACHE_PREFETCH_AUDIO_COMMIT = 124, // n/a Enqueue request transaction to prefetch audio (release critical section). CACHE_PREFETCH_AUDIO_GO = 125, // n/a Action audio prefetches. CACHE_GETCHILD_CACHE_MODE = 200, // n/a Cache ask Child for desired video cache mode. CACHE_GETCHILD_CACHE_SIZE = 201, // n/a Cache ask Child for desired video cache size. // Filters are queried about their desired audio cache mode. // Child can answer them with CACHE_AUDIO_xxx CACHE_GETCHILD_AUDIO_MODE = 202, // Cache ask Child for desired audio cache mode. CACHE_GETCHILD_AUDIO_SIZE = 203, // Cache ask Child for desired audio cache size. CACHE_GETCHILD_COST = 220, // n/a Cache ask Child for estimated processing cost. CACHE_COST_ZERO = 221, // n/a Child response of zero cost (ptr arithmetic only). CACHE_COST_UNIT = 222, // n/a Child response of unit cost (less than or equal 1 full frame blit). CACHE_COST_LOW = 223, // n/a Child response of light cost. (Fast) CACHE_COST_MED = 224, // n/a Child response of medium cost. (Real time) CACHE_COST_HI = 225, // n/a Child response of heavy cost. (Slow) CACHE_GETCHILD_THREAD_MODE = 240, // n/a Cache ask Child for thread safetyness. CACHE_THREAD_UNSAFE = 241, // n/a Only 1 thread allowed for all instances. 2.5 filters default! CACHE_THREAD_CLASS = 242, // n/a Only 1 thread allowed for each instance. 2.6 filters default! CACHE_THREAD_SAFE = 243, // n/a Allow all threads in any instance. CACHE_THREAD_OWN = 244, // n/a Safe but limit to 1 thread, internally threaded. CACHE_GETCHILD_ACCESS_COST = 260, // n/a Cache ask Child for preferred access pattern. CACHE_ACCESS_RAND = 261, // n/a Filter is access order agnostic. CACHE_ACCESS_SEQ0 = 262, // n/a Filter prefers sequential access (low cost) CACHE_ACCESS_SEQ1 = 263, // n/a Filter needs sequential access (high cost) CACHE_AVSPLUS_CONSTANTS = 500, // Smaller values are reserved for classic Avisynth CACHE_DONT_CACHE_ME, // Filters that don't need caching (eg. trim, cache etc.) should return 1 to this request CACHE_SET_MIN_CAPACITY, CACHE_SET_MAX_CAPACITY, CACHE_GET_MIN_CAPACITY, CACHE_GET_MAX_CAPACITY, CACHE_GET_SIZE, CACHE_GET_REQUESTED_CAP, CACHE_GET_CAPACITY, CACHE_GET_MTMODE, // Filters specify their desired MT mode, see enum MtMode // By returning IS_CACHE_ANS to IS_CACHE_REQ, we tell the caller we are a cache CACHE_IS_CACHE_REQ, CACHE_IS_CACHE_ANS, // By returning IS_MTGUARD_ANS to IS_MTGUARD_REQ, we tell the caller we are an mt guard CACHE_IS_MTGUARD_REQ, CACHE_IS_MTGUARD_ANS, CACHE_AVSPLUS_CUDA_CONSTANTS = 600, CACHE_GET_DEV_TYPE, // Device types a filter can return CACHE_GET_CHILD_DEV_TYPE, // Device types a filter can receive CACHE_USER_CONSTANTS = 1000 // Smaller values are reserved for the core }; // Base class for all filters. class IClip { friend class PClip; friend class AVSValue; volatile long refcnt; void AddRef(); #if BUILDING_AVSCORE public: #endif void Release(); public: IClip() : refcnt(0) {} virtual int __stdcall GetVersion() { return AVISYNTH_INTERFACE_VERSION; } virtual PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env) = 0; virtual bool __stdcall GetParity(int n) = 0; // return field parity if field_based, else parity of first field in frame virtual void __stdcall GetAudio(void* buf, int64_t start, int64_t count, IScriptEnvironment* env) = 0; // start and count are in samples /* Need to check GetVersion first, pre v5 will return random crap from EAX reg. */ virtual int __stdcall SetCacheHints(int cachehints,int frame_range) = 0 ; // We do not pass cache requests upwards, only to the next filter. virtual const VideoInfo& __stdcall GetVideoInfo() = 0; virtual ~IClip() {} }; // end class IClip // smart pointer to IClip class PClip { IClip* p; IClip* GetPointerWithAddRef() const; friend class AVSValue; friend class VideoFrame; void Init(IClip* x); void Set(IClip* x); public: PClip() AVS_BakedCode( AVS_LinkCall_Void(PClip_CONSTRUCTOR0)() ) PClip(const PClip& x) AVS_BakedCode( AVS_LinkCall_Void(PClip_CONSTRUCTOR1)(x) ) PClip(IClip* x) AVS_BakedCode( AVS_LinkCall_Void(PClip_CONSTRUCTOR2)(x) ) void operator=(IClip* x) AVS_BakedCode( AVS_LinkCall_Void(PClip_OPERATOR_ASSIGN0)(x) ) void operator=(const PClip& x) AVS_BakedCode( AVS_LinkCall_Void(PClip_OPERATOR_ASSIGN1)(x) ) IClip* operator->() const { return p; } // useful in conditional expressions operator void*() const { return p; } bool operator!() const { return !p; } ~PClip() AVS_BakedCode( AVS_LinkCall_Void(PClip_DESTRUCTOR)() ) #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(const PClip& x); void CONSTRUCTOR2(IClip* x); void OPERATOR_ASSIGN0(IClip* x); void OPERATOR_ASSIGN1(const PClip& x); void DESTRUCTOR(); #endif }; // end class PClip // enums for frame property functions enum AVSPropTypes { PROPTYPE_UNSET = 'u', // ptUnset PROPTYPE_INT = 'i', // peType PROPTYPE_FLOAT = 'f', // ptFloat PROPTYPE_DATA = 's', // ptData PROPTYPE_CLIP = 'c', // ptClip PROPTYPE_FRAME = 'v' // ptFrame // ptFunction = 'm' }; enum AVSGetPropErrors { GETPROPERROR_UNSET = 1, // peUnset GETPROPERROR_TYPE = 2, // peType GETPROPERROR_INDEX = 4 // peIndex }; enum AVSPropAppendMode { PROPAPPENDMODE_REPLACE = 0, // paReplace PROPAPPENDMODE_APPEND = 1, // paAppend PROPAPPENDMODE_TOUCH = 2 // paTouch }; class AVSValue { public: AVSValue() AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR0)() ) AVSValue(IClip* c) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR1)(c) ) AVSValue(const PClip& c) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR2)(c) ) AVSValue(bool b) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR3)(b) ) AVSValue(int i) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR4)(i) ) // AVSValue(int64_t l); AVSValue(float f) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR5)(f) ) AVSValue(double f) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR6)(f) ) AVSValue(const char* s) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR7)(s) ) AVSValue(const AVSValue* a, int size) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR8)(a, size) ) AVSValue(const AVSValue& a, int size) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR8)(&a, size) ) AVSValue(const AVSValue& v) AVS_BakedCode( AVS_LinkCall_Void(AVSValue_CONSTRUCTOR9)(v) ) AVSValue(const PFunction& n) AVS_BakedCode(AVS_LinkCall_Void(AVSValue_CONSTRUCTOR11)(n)) ~AVSValue() AVS_BakedCode( AVS_LinkCall_Void(AVSValue_DESTRUCTOR)() ) AVSValue& operator=(const AVSValue& v) AVS_BakedCode( return AVS_LinkCallV(AVSValue_OPERATOR_ASSIGN)(v) ) // Note that we transparently allow 'int' to be treated as 'float'. // There are no int<->bool conversions, though. bool Defined() const AVS_BakedCode( return AVS_LinkCall(Defined)() ) bool IsClip() const AVS_BakedCode( return AVS_LinkCall(IsClip)() ) bool IsBool() const AVS_BakedCode( return AVS_LinkCall(IsBool)() ) bool IsInt() const AVS_BakedCode( return AVS_LinkCall(IsInt)() ) // bool IsLong() const; bool IsFloat() const AVS_BakedCode( return AVS_LinkCall(IsFloat)() ) bool IsString() const AVS_BakedCode( return AVS_LinkCall(IsString)() ) bool IsArray() const AVS_BakedCode( return AVS_LinkCall(IsArray)() ) bool IsFunction() const AVS_BakedCode( return AVS_LinkCall(IsFunction)() ) PClip AsClip() const AVS_BakedCode( return AVS_LinkCall(AsClip)() ) bool AsBool() const AVS_BakedCode( return AVS_LinkCall(AsBool1)() ) int AsInt() const AVS_BakedCode( return AVS_LinkCall(AsInt1)() ) // int AsLong() const; const char* AsString() const AVS_BakedCode( return AVS_LinkCall(AsString1)() ) double AsFloat() const AVS_BakedCode( return AVS_LinkCall(AsFloat1)() ) float AsFloatf() const AVS_BakedCode( return float( AVS_LinkCall(AsFloat1)() ) ) bool AsBool(bool def) const AVS_BakedCode( return AVS_LinkCall(AsBool2)(def) ) int AsInt(int def) const AVS_BakedCode( return AVS_LinkCall(AsInt2)(def) ) double AsDblDef(double def) const AVS_BakedCode( return AVS_LinkCall(AsDblDef)(def) ) // Value is still a float double AsFloat(float def) const AVS_BakedCode( return AVS_LinkCall(AsFloat2)(def) ) float AsFloatf(float def) const AVS_BakedCode( return float( AVS_LinkCall(AsFloat2)(def) ) ) const char* AsString(const char* def) const AVS_BakedCode( return AVS_LinkCall(AsString2)(def) ) PFunction AsFunction() const; // internal use only int ArraySize() const AVS_BakedCode( return AVS_LinkCall(ArraySize)() ) const AVSValue& operator[](int index) const AVS_BakedCode( return AVS_LinkCallV(AVSValue_OPERATOR_INDEX)(index) ) private: short type; // 'a'rray, 'c'lip, 'b'ool, 'i'nt, 'f'loat, 's'tring, 'v'oid, fu'n'ction, or RFU: 'l'ong ('d'ouble) short array_size; union { IClip* clip; bool boolean; int integer; float floating_pt; const char* string; const AVSValue* array; IFunction* function; #ifdef X86_64 // if ever, only x64 will support. It breaks struct size on 32 bit int64_t longlong; // 8 bytes double double_pt; // 8 bytes #endif }; void Assign(const AVSValue* src, bool init); public: AvsValueType GetType() const AVS_BakedCode( return AVS_LinkCallOptDefault(AVSValue_GetType, VALUE_TYPE_UNDEFINED) ) #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(IClip* c); void CONSTRUCTOR2(const PClip& c); void CONSTRUCTOR3(bool b); void CONSTRUCTOR4(int i); void CONSTRUCTOR5(float f); void CONSTRUCTOR6(double f); void CONSTRUCTOR7(const char* s); void CONSTRUCTOR8(const AVSValue* a, int size); void CONSTRUCTOR9(const AVSValue& v); void CONSTRUCTOR11(const PFunction& n); void DESTRUCTOR(); AVSValue& OPERATOR_ASSIGN(const AVSValue& v); const AVSValue& OPERATOR_INDEX(int index) const; bool AsBool1() const; int AsInt1() const; const char* AsString1() const; double AsFloat1() const; bool AsBool2(bool def) const; int AsInt2(int def) const; double AsFloat2(float def) const; const char* AsString2(const char* def) const; void MarkArrayAsC(); // for C interface, no deep-copy and deep-free void CONSTRUCTOR10(const AVSValue& v, bool c_arrays); AVSValue(const AVSValue& v, bool c_arrays); void Assign2(const AVSValue* src, bool init, bool c_arrays); #endif }; // end class AVSValue #define AVS_UNUSED(x) (void)(x) // instantiable null filter class GenericVideoFilter : public IClip { protected: PClip child; VideoInfo vi; public: GenericVideoFilter(PClip _child) : child(_child) { vi = child->GetVideoInfo(); } PVideoFrame __stdcall GetFrame(int n, IScriptEnvironment* env) { return child->GetFrame(n, env); } void __stdcall GetAudio(void* buf, int64_t start, int64_t count, IScriptEnvironment* env) { child->GetAudio(buf, start, count, env); } const VideoInfo& __stdcall GetVideoInfo() { return vi; } bool __stdcall GetParity(int n) { return child->GetParity(n); } int __stdcall SetCacheHints(int cachehints, int frame_range) { AVS_UNUSED(cachehints); AVS_UNUSED(frame_range); return 0; } // We do not pass cache requests upwards, only to the next filter. }; class PFunction { public: PFunction() AVS_BakedCode(AVS_LinkCall_Void(PFunction_CONSTRUCTOR0)()) PFunction(IFunction* p) AVS_BakedCode(AVS_LinkCall_Void(PFunction_CONSTRUCTOR1)(p)) PFunction(const PFunction& p) AVS_BakedCode(AVS_LinkCall_Void(PFunction_CONSTRUCTOR2)(p)) PFunction& operator=(IFunction* p) AVS_BakedCode(return AVS_LinkCallV(PFunction_OPERATOR_ASSIGN0)(p)) PFunction& operator=(const PFunction& p) AVS_BakedCode(return AVS_LinkCallV(PFunction_OPERATOR_ASSIGN1)(p)) ~PFunction() AVS_BakedCode(AVS_LinkCall_Void(PFunction_DESTRUCTOR)()) int operator!() const { return !e; } operator void*() const { return e; } IFunction* operator->() const { return e; } private: IFunction * e; friend class AVSValue; IFunction * GetPointerWithAddRef() const; void Init(IFunction* p); void Set(IFunction* p); #ifdef BUILDING_AVSCORE public: void CONSTRUCTOR0(); /* Damn compiler won't allow taking the address of reserved constructs, make a dummy interlude */ void CONSTRUCTOR1(IFunction* p); void CONSTRUCTOR2(const PFunction& p); PFunction& OPERATOR_ASSIGN0(IFunction* p); PFunction& OPERATOR_ASSIGN1(const PFunction& p); void DESTRUCTOR(); #endif }; #undef CALL_MEMBER_FN #undef AVS_LinkCallOptDefault #undef AVS_LinkCallOpt #undef AVS_LinkCallV #undef AVS_LinkCall #undef AVS_BakedCode #include "avs/cpuid.h" // IScriptEnvironment GetEnvProperty enum AvsEnvProperty { AEP_PHYSICAL_CPUS = 1, AEP_LOGICAL_CPUS = 2, AEP_THREADPOOL_THREADS = 3, AEP_FILTERCHAIN_THREADS = 4, AEP_THREAD_ID = 5, AEP_VERSION = 6, AEP_HOST_SYSTEM_ENDIANNESS = 7, AEP_INTERFACE_VERSION = 8, AEP_INTERFACE_BUGFIX = 9, // Neo additionals AEP_NUM_DEVICES = 901, AEP_FRAME_ALIGN = 902, AEP_PLANE_ALIGN = 903, AEP_SUPPRESS_THREAD = 921, AEP_GETFRAME_RECURSIVE = 922, }; // IScriptEnvironment::Allocate() enum AvsAllocType { AVS_NORMAL_ALLOC = 1, AVS_POOLED_ALLOC = 2 }; // Important note (Windows, MSVC): // When extending IScriptEnvironment, do not declare existing names again // with different parameters. Methods with the same name will be grouped // together in the vtable. This results in shifting all vtable method pointers // after such grouping and breaks all plugins who expect the old order. // E.g. ApplyMessage will be called instead of GetAVSLinkage. // As long as the declaration is compatible with COM interop, the order of // declaration is sequential. But if not, overloads in the same class are grouped // together in the vtable in the reverse order of declaration. class IScriptEnvironment { public: virtual ~IScriptEnvironment() {} virtual /*static*/ int __stdcall GetCPUFlags() = 0; virtual char* __stdcall SaveString(const char* s, int length = -1) = 0; virtual char* Sprintf(const char* fmt, ...) = 0; // note: val is really a va_list; I hope everyone typedefs va_list to a pointer // 20200305: (void *) changed back to va_list virtual char* __stdcall VSprintf(const char* fmt, va_list val) = 0; #ifdef AVS_WINDOWS __declspec(noreturn) virtual void ThrowError(const char* fmt, ...) = 0; #else virtual void ThrowError(const char* fmt, ...) = 0; #endif class NotFound /*exception*/ {}; // thrown by Invoke and GetVar typedef AVSValue (__cdecl *ApplyFunc)(AVSValue args, void* user_data, IScriptEnvironment* env); virtual void __stdcall AddFunction(const char* name, const char* params, ApplyFunc apply, void* user_data) = 0; virtual bool __stdcall FunctionExists(const char* name) = 0; virtual AVSValue __stdcall Invoke(const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall GetVar(const char* name) = 0; virtual bool __stdcall SetVar(const char* name, const AVSValue& val) = 0; virtual bool __stdcall SetGlobalVar(const char* name, const AVSValue& val) = 0; virtual void __stdcall PushContext(int level = 0) = 0; virtual void __stdcall PopContext() = 0; // note v8: use NewVideoFrameP is possible virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, int align = FRAME_ALIGN) = 0; virtual bool __stdcall MakeWritable(PVideoFrame* pvf) = 0; virtual void __stdcall BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height) = 0; typedef void (__cdecl *ShutdownFunc)(void* user_data, IScriptEnvironment* env); virtual void __stdcall AtExit(ShutdownFunc function, void* user_data) = 0; virtual void __stdcall CheckVersion(int version = AVISYNTH_INTERFACE_VERSION) = 0; virtual PVideoFrame __stdcall Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height) = 0; virtual int __stdcall SetMemoryMax(int mem) = 0; virtual int __stdcall SetWorkingDir(const char * newdir) = 0; virtual void* __stdcall ManageCache(int key, void* data) = 0; enum PlanarChromaAlignmentMode { PlanarChromaAlignmentOff, PlanarChromaAlignmentOn, PlanarChromaAlignmentTest }; virtual bool __stdcall PlanarChromaAlignment(PlanarChromaAlignmentMode key) = 0; virtual PVideoFrame __stdcall SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV) = 0; // **** AVISYNTH_INTERFACE_VERSION 5 **** defined since classic Avisynth 2.6 beta virtual void __stdcall DeleteScriptEnvironment() = 0; virtual void __stdcall ApplyMessage(PVideoFrame* frame, const VideoInfo& vi, const char* message, int size, int textcolor, int halocolor, int bgcolor) = 0; virtual const AVS_Linkage* __stdcall GetAVSLinkage() = 0; // **** AVISYNTH_INTERFACE_VERSION 6 **** defined since classic Avisynth 2.6 // noThrow version of GetVar virtual AVSValue __stdcall GetVarDef(const char* name, const AVSValue& def = AVSValue()) = 0; // **** AVISYNTH_INTERFACE_VERSION 8 **** AviSynth+ 3.6.0- virtual PVideoFrame __stdcall SubframePlanarA(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA) = 0; virtual void __stdcall copyFrameProps(const PVideoFrame& src, PVideoFrame& dst) = 0; virtual const AVSMap* __stdcall getFramePropsRO(const PVideoFrame& frame) = 0; virtual AVSMap* __stdcall getFramePropsRW(PVideoFrame& frame) = 0; virtual int __stdcall propNumKeys(const AVSMap* map) = 0; virtual const char* __stdcall propGetKey(const AVSMap* map, int index) = 0; virtual int __stdcall propNumElements(const AVSMap* map, const char* key) = 0; virtual char __stdcall propGetType(const AVSMap* map, const char* key) = 0; virtual int64_t __stdcall propGetInt(const AVSMap* map, const char* key, int index, int* error) = 0; virtual double __stdcall propGetFloat(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const char* __stdcall propGetData(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propGetDataSize(const AVSMap* map, const char* key, int index, int* error) = 0; virtual PClip __stdcall propGetClip(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const PVideoFrame __stdcall propGetFrame(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propDeleteKey(AVSMap* map, const char* key) = 0; virtual int __stdcall propSetInt(AVSMap* map, const char* key, int64_t i, int append) = 0; virtual int __stdcall propSetFloat(AVSMap* map, const char* key, double d, int append) = 0; virtual int __stdcall propSetData(AVSMap* map, const char* key, const char* d, int length, int append) = 0; virtual int __stdcall propSetClip(AVSMap* map, const char* key, PClip& clip, int append) = 0; virtual int __stdcall propSetFrame(AVSMap* map, const char* key, const PVideoFrame& frame, int append) = 0; virtual const int64_t* __stdcall propGetIntArray(const AVSMap* map, const char* key, int* error) = 0; virtual const double* __stdcall propGetFloatArray(const AVSMap* map, const char* key, int* error) = 0; virtual int __stdcall propSetIntArray(AVSMap* map, const char* key, const int64_t* i, int size) = 0; virtual int __stdcall propSetFloatArray(AVSMap* map, const char* key, const double* d, int size) = 0; virtual AVSMap* __stdcall createMap() = 0; virtual void __stdcall freeMap(AVSMap* map) = 0; virtual void __stdcall clearMap(AVSMap* map) = 0; // NewVideoFrame with frame property source. virtual PVideoFrame __stdcall NewVideoFrameP(const VideoInfo& vi, const PVideoFrame* prop_src, int align = FRAME_ALIGN) = 0; // Generic query to ask for various system properties virtual size_t __stdcall GetEnvProperty(AvsEnvProperty prop) = 0; // Support functions virtual void* __stdcall Allocate(size_t nBytes, size_t alignment, AvsAllocType type) = 0; virtual void __stdcall Free(void* ptr) = 0; // these GetVar versions (renamed differently) were moved from IScriptEnvironment2 // Returns TRUE and the requested variable. If the method fails, returns FALSE and does not touch 'val'. virtual bool __stdcall GetVarTry(const char* name, AVSValue* val) const = 0; // ex virtual bool __stdcall GetVar(const char* name, AVSValue* val) const = 0; // Return the value of the requested variable. // If the variable was not found or had the wrong type, // return the supplied default value. virtual bool __stdcall GetVarBool(const char* name, bool def) const = 0; virtual int __stdcall GetVarInt(const char* name, int def) const = 0; virtual double __stdcall GetVarDouble(const char* name, double def) const = 0; virtual const char* __stdcall GetVarString(const char* name, const char* def) const = 0; // brand new in v8 - though no real int64 support yet virtual int64_t __stdcall GetVarLong(const char* name, int64_t def) const = 0; // 'Invoke' functions moved here from internal ScriptEnvironments are renamed in order to keep vtable order // Invoke functions with 'Try' will return false instead of throwing NotFound(). // ex-IScriptEnvironment2 virtual bool __stdcall InvokeTry(AVSValue* result, const char* name, const AVSValue& args, const char* const* arg_names = 0) = 0; // Since V8 virtual AVSValue __stdcall Invoke2(const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; // Ex-INeo virtual bool __stdcall Invoke2Try(AVSValue* result, const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall Invoke3(const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; virtual bool __stdcall Invoke3Try(AVSValue* result, const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; // V9 virtual bool __stdcall MakePropertyWritable(PVideoFrame* pvf) = 0; }; // end class IScriptEnvironment. Order is important. Avoid overloads with the same name. // used internally class IScriptEnvironment_Avs25 { public: virtual ~IScriptEnvironment_Avs25() {} virtual /*static*/ int __stdcall GetCPUFlags() = 0; virtual char* __stdcall SaveString(const char* s, int length = -1) = 0; virtual char* Sprintf(const char* fmt, ...) = 0; virtual char* __stdcall VSprintf(const char* fmt, va_list val) = 0; #ifdef AVS_WINDOWS __declspec(noreturn) virtual void ThrowError(const char* fmt, ...) = 0; #else virtual void ThrowError(const char* fmt, ...) = 0; #endif class NotFound /*exception*/ {}; // thrown by Invoke and GetVar typedef AVSValue(__cdecl* ApplyFunc)(AVSValue args, void* user_data, IScriptEnvironment* env); virtual void __stdcall AddFunction25(const char* name, const char* params, ApplyFunc apply, void* user_data) = 0; virtual bool __stdcall FunctionExists(const char* name) = 0; virtual AVSValue __stdcall Invoke25(const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall GetVar(const char* name) = 0; virtual bool __stdcall SetVar(const char* name, const AVSValue& val) = 0; virtual bool __stdcall SetGlobalVar(const char* name, const AVSValue& val) = 0; virtual void __stdcall PushContext(int level = 0) = 0; virtual void __stdcall PopContext() = 0; virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, int align = FRAME_ALIGN) = 0; virtual bool __stdcall MakeWritable(PVideoFrame* pvf) = 0; virtual void __stdcall BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height) = 0; typedef void(__cdecl* ShutdownFunc)(void* user_data, IScriptEnvironment* env); virtual void __stdcall AtExit(ShutdownFunc function, void* user_data) = 0; virtual void __stdcall CheckVersion(int version = AVISYNTH_CLASSIC_INTERFACE_VERSION_25) = 0; virtual PVideoFrame __stdcall Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height) = 0; virtual int __stdcall SetMemoryMax(int mem) = 0; virtual int __stdcall SetWorkingDir(const char* newdir) = 0; // specially returns 1 for key MC_QueryAvs25 to check if called from AVS2.5 interface virtual void* __stdcall ManageCache25(int key, void* data) = 0; enum PlanarChromaAlignmentMode { PlanarChromaAlignmentOff, PlanarChromaAlignmentOn, PlanarChromaAlignmentTest }; virtual bool __stdcall PlanarChromaAlignment(IScriptEnvironment::PlanarChromaAlignmentMode key) = 0; virtual PVideoFrame __stdcall SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV) = 0; // Despite the name, we provide entries up to V6 in case someone requests // a V3 interface and still wants to use V5-V6 functions // **** AVISYNTH_INTERFACE_VERSION 5 **** defined since classic Avisynth 2.6 beta virtual void __stdcall DeleteScriptEnvironment() = 0; virtual void __stdcall ApplyMessage(PVideoFrame* frame, const VideoInfo& vi, const char* message, int size, int textcolor, int halocolor, int bgcolor) = 0; virtual const AVS_Linkage* __stdcall GetAVSLinkage() = 0; // **** AVISYNTH_INTERFACE_VERSION 6 **** defined since classic Avisynth 2.6 // noThrow version of GetVar virtual AVSValue __stdcall GetVarDef(const char* name, const AVSValue& def = AVSValue()) = 0; }; // end class IScriptEnvironment_Avs25. Order is important. enum MtMode { MT_INVALID = 0, MT_NICE_FILTER = 1, MT_MULTI_INSTANCE = 2, MT_SERIALIZED = 3, MT_SPECIAL_MT = 4, MT_MODE_COUNT = 5 }; class IJobCompletion { public: virtual ~IJobCompletion() {} virtual void __stdcall Wait() = 0; virtual AVSValue __stdcall Get(size_t i) = 0; virtual size_t __stdcall Size() const = 0; virtual size_t __stdcall Capacity() const = 0; virtual void __stdcall Reset() = 0; virtual void __stdcall Destroy() = 0; }; class IScriptEnvironment2; class Prefetcher; typedef AVSValue (*ThreadWorkerFuncPtr)(IScriptEnvironment2* env, void* data); /* ----------------------------------------------------------------------------- Note to plugin authors: The interface in IScriptEnvironment2 is preliminary / under construction / only for testing / non-final etc.! As long as you see this note here, IScriptEnvironment2 might still change, in which case your plugin WILL break. This also means that you are welcome to test it and give your feedback about any ideas, improvements, or issues you might have. ----------------------------------------------------------------------------- */ class IScriptEnvironment2 : public IScriptEnvironment{ public: virtual ~IScriptEnvironment2() {} // V8: SubframePlanarA, GetEnvProperty, GetVar versions, Allocate, Free, no-throw Invoke moved to IScriptEnvironment // Plugin functions virtual bool __stdcall LoadPlugin(const char* filePath, bool throwOnError, AVSValue *result) = 0; virtual void __stdcall AddAutoloadDir(const char* dirPath, bool toFront) = 0; virtual void __stdcall ClearAutoloadDirs() = 0; virtual void __stdcall AutoloadPlugins() = 0; virtual void __stdcall AddFunction(const char* name, const char* params, ApplyFunc apply, void* user_data, const char *exportVar) = 0; virtual bool __stdcall InternalFunctionExists(const char* name) = 0; // Threading virtual void __stdcall SetFilterMTMode(const char* filter, MtMode mode, bool force) = 0; // If filter is "DEFAULT_MT_MODE", sets the default MT mode virtual IJobCompletion* __stdcall NewCompletion(size_t capacity) = 0; virtual void __stdcall ParallelJob(ThreadWorkerFuncPtr jobFunc, void* jobData, IJobCompletion* completion) = 0; // These lines are needed so that we can overload the older functions from IScriptEnvironment. using IScriptEnvironment::Invoke; using IScriptEnvironment::AddFunction; }; // end class IScriptEnvironment2 // To allow Avisynth+ add functions to IScriptEnvironment2, // Neo defines another new interface, INeoEnv. // INeoEnv and the legacy interfaces (IScriptEnvironment/IScriptEnvironment2) // share the same ScriptEnvironment instance. The function with the same signature // is exactly identical and there is no limitation to switch interfaces. // You can use any interface you like. // Note to plugin authors : The interface is not stable, see comments in IScriptEnvironment2 class INeoEnv { public: virtual ~INeoEnv() {} typedef IScriptEnvironment::NotFound NotFound; typedef IScriptEnvironment::ApplyFunc ApplyFunc; typedef IScriptEnvironment::ShutdownFunc ShutdownFunc; virtual void __stdcall DeleteScriptEnvironment() = 0; virtual const AVS_Linkage* __stdcall GetAVSLinkage() = 0; // Get legacy interface (Avisynth+) virtual IScriptEnvironment2* __stdcall GetEnv2() = 0; // Get compatibility interface for AVS CPP 2.5 plugins virtual IScriptEnvironment_Avs25* __stdcall GetEnv25() = 0; // Generic system to ask for various properties virtual size_t __stdcall GetEnvProperty(AvsEnvProperty prop) = 0; virtual int __stdcall GetCPUFlags() = 0; // Plugin functions virtual bool __stdcall LoadPlugin(const char* filePath, bool throwOnError, AVSValue *result) = 0; virtual void __stdcall AddAutoloadDir(const char* dirPath, bool toFront) = 0; virtual void __stdcall ClearAutoloadDirs() = 0; virtual void __stdcall AutoloadPlugins() = 0; virtual void __stdcall AddFunction( const char* name, const char* params, ApplyFunc apply, void* user_data) = 0; virtual void __stdcall AddFunction( const char* name, const char* params, ApplyFunc apply, void* user_data, const char *exportVar) = 0; virtual bool __stdcall FunctionExists(const char* name) = 0; virtual bool __stdcall InternalFunctionExists(const char* name) = 0; // Invoke function. Throws NotFound exception when the specified function does not exist. virtual AVSValue __stdcall Invoke( const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall Invoke2( const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual AVSValue __stdcall Invoke3( const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; // These versions of Invoke will return false instead of throwing NotFound(). virtual bool __stdcall InvokeTry( AVSValue* result, const char* name, const AVSValue& args, const char* const* arg_names = 0) = 0; virtual bool __stdcall Invoke2Try( AVSValue* result, const AVSValue& implicit_last, const char* name, const AVSValue args, const char* const* arg_names = 0) = 0; virtual bool __stdcall Invoke3Try( AVSValue* result, const AVSValue& implicit_last, const PFunction& func, const AVSValue args, const char* const* arg_names = 0) = 0; // V9 virtual bool __stdcall MakePropertyWritable(PVideoFrame* pvf) = 0; // Throws exception when the requested variable is not found. virtual AVSValue __stdcall GetVar(const char* name) = 0; // noThrow version of GetVar virtual AVSValue __stdcall GetVarDef(const char* name, const AVSValue& def = AVSValue()) = 0; // Returns TRUE and the requested variable. If the method fails, returns FALSE and does not touch 'val'. virtual bool __stdcall GetVarTry(const char* name, AVSValue* val) const = 0; // Return the value of the requested variable. // If the variable was not found or had the wrong type, // return the supplied default value. virtual bool __stdcall GetVarBool(const char* name, bool def) const = 0; virtual int __stdcall GetVarInt(const char* name, int def) const = 0; virtual double __stdcall GetVarDouble(const char* name, double def) const = 0; virtual const char* __stdcall GetVarString(const char* name, const char* def) const = 0; virtual int64_t __stdcall GetVarLong(const char* name, int64_t def) const = 0; virtual bool __stdcall SetVar(const char* name, const AVSValue& val) = 0; virtual bool __stdcall SetGlobalVar(const char* name, const AVSValue& val) = 0; // Switch local variables virtual void __stdcall PushContext(int level = 0) = 0; virtual void __stdcall PopContext() = 0; // Global variable frame support virtual void __stdcall PushContextGlobal() = 0; virtual void __stdcall PopContextGlobal() = 0; // Allocate new video frame // in PNeoEnv: align parameter is no longer supported virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi) = 0; // current device is used virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, const PDevice& device) = 0; // as above but with property sources virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, const PVideoFrame *prop_src) = 0; // current device is used + frame property source virtual PVideoFrame __stdcall NewVideoFrame(const VideoInfo& vi, const PDevice& device, const PVideoFrame* prop_src) = 0; // current device is used + frame property source // Frame related operations virtual bool __stdcall MakeWritable(PVideoFrame* pvf) = 0; virtual void __stdcall BitBlt(BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height) = 0; virtual PVideoFrame __stdcall Subframe(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height) = 0; virtual PVideoFrame __stdcall SubframePlanar(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV) = 0; virtual PVideoFrame __stdcall SubframePlanarA(PVideoFrame src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA) = 0; // frame properties support virtual void __stdcall copyFrameProps(const PVideoFrame& src, PVideoFrame& dst) = 0; virtual const AVSMap* __stdcall getFramePropsRO(const PVideoFrame& frame) = 0; virtual AVSMap* __stdcall getFramePropsRW(PVideoFrame& frame) = 0; virtual int __stdcall propNumKeys(const AVSMap* map) = 0; virtual const char* __stdcall propGetKey(const AVSMap* map, int index) = 0; virtual int __stdcall propNumElements(const AVSMap* map, const char* key) = 0; virtual char __stdcall propGetType(const AVSMap* map, const char* key) = 0; virtual int64_t __stdcall propGetInt(const AVSMap* map, const char* key, int index, int* error) = 0; virtual double __stdcall propGetFloat(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const char* __stdcall propGetData(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propGetDataSize(const AVSMap* map, const char* key, int index, int* error) = 0; virtual PClip __stdcall propGetClip(const AVSMap* map, const char* key, int index, int* error) = 0; virtual const PVideoFrame __stdcall propGetFrame(const AVSMap* map, const char* key, int index, int* error) = 0; virtual int __stdcall propDeleteKey(AVSMap* map, const char* key) = 0; virtual int __stdcall propSetInt(AVSMap* map, const char* key, int64_t i, int append) = 0; virtual int __stdcall propSetFloat(AVSMap* map, const char* key, double d, int append) = 0; virtual int __stdcall propSetData(AVSMap* map, const char* key, const char* d, int length, int append) = 0; virtual int __stdcall propSetClip(AVSMap* map, const char* key, PClip& clip, int append) = 0; virtual int __stdcall propSetFrame(AVSMap* map, const char* key, const PVideoFrame& frame, int append) = 0; virtual const int64_t *__stdcall propGetIntArray(const AVSMap* map, const char* key, int* error) = 0; virtual const double *__stdcall propGetFloatArray(const AVSMap* map, const char* key, int* error) = 0; virtual int __stdcall propSetIntArray(AVSMap* map, const char* key, const int64_t* i, int size) = 0; virtual int __stdcall propSetFloatArray(AVSMap* map, const char* key, const double* d, int size) = 0; virtual AVSMap* __stdcall createMap() = 0; virtual void __stdcall freeMap(AVSMap* map) = 0; virtual void __stdcall clearMap(AVSMap* map) = 0; // Support functions virtual void* __stdcall Allocate(size_t nBytes, size_t alignment, AvsAllocType type) = 0; virtual void __stdcall Free(void* ptr) = 0; virtual char* __stdcall SaveString(const char* s, int length = -1) = 0; virtual char* __stdcall SaveString(const char* s, int length, bool escape) = 0; virtual char* Sprintf(const char* fmt, ...) = 0; virtual char* __stdcall VSprintf(const char* fmt, va_list val) = 0; __declspec(noreturn) virtual void ThrowError(const char* fmt, ...) = 0; virtual void __stdcall ApplyMessage(PVideoFrame* frame, const VideoInfo& vi, const char* message, int size, int textcolor, int halocolor, int bgcolor) = 0; // Setting virtual int __stdcall SetMemoryMax(int mem) = 0; virtual int __stdcall SetMemoryMax(AvsDeviceType type, int index, int mem) = 0; virtual bool __stdcall PlanarChromaAlignment(IScriptEnvironment::PlanarChromaAlignmentMode key) = 0; virtual int __stdcall SetWorkingDir(const char * newdir) = 0; virtual void* __stdcall ManageCache(int key, void* data) = 0; virtual void __stdcall AtExit(ShutdownFunc function, void* user_data) = 0; virtual void __stdcall CheckVersion(int version = AVISYNTH_INTERFACE_VERSION) = 0; // Threading virtual void __stdcall SetFilterMTMode(const char* filter, MtMode mode, bool force) = 0; virtual IJobCompletion* __stdcall NewCompletion(size_t capacity) = 0; virtual void __stdcall ParallelJob(ThreadWorkerFuncPtr jobFunc, void* jobData, IJobCompletion* completion) = 0; // CUDA Support virtual PDevice __stdcall GetDevice(AvsDeviceType dev_type, int dev_index) const = 0; virtual PDevice __stdcall GetDevice() const = 0; // get current device virtual AvsDeviceType __stdcall GetDeviceType() const = 0; virtual int __stdcall GetDeviceId() const = 0; virtual int __stdcall GetDeviceIndex() const = 0; virtual void* __stdcall GetDeviceStream() const = 0; virtual void __stdcall DeviceAddCallback(void(*cb)(void*), void* user_data) = 0; virtual PVideoFrame __stdcall GetFrame(PClip c, int n, const PDevice& device) = 0; }; // support interface conversion struct PNeoEnv { INeoEnv* p; PNeoEnv() : p() { } PNeoEnv(IScriptEnvironment* env) #if defined(BUILDING_AVSCORE) || defined(AVS_STATIC_LIB) ; #else : p(!AVS_linkage || offsetof(AVS_Linkage, GetNeoEnv) >= (size_t)AVS_linkage->Size ? 0 : AVS_linkage->GetNeoEnv(env)) { } #endif int operator!() const { return !p; } operator void*() const { return p; } INeoEnv* operator->() const { return p; } #ifdef BUILDING_AVSCORE inline operator IScriptEnvironment2*(); inline operator IScriptEnvironment_Avs25* (); #else operator IScriptEnvironment2*() { return p->GetEnv2(); } operator IScriptEnvironment_Avs25* () { return p->GetEnv25(); } #endif }; // avisynth.dll exports this; it's a way to use it as a library, without // writing an AVS script or without going through AVIFile. AVSC_API(IScriptEnvironment*, CreateScriptEnvironment)(int version = AVISYNTH_INTERFACE_VERSION); // These are some global variables you can set in your script to change AviSynth's behavior. #define VARNAME_AllowFloatAudio "OPT_AllowFloatAudio" // Allow WAVE_FORMAT_IEEE_FLOAT audio output #define VARNAME_VDubPlanarHack "OPT_VDubPlanarHack" // Hack YV16 and YV24 chroma plane order for old VDub's #define VARNAME_AVIPadScanlines "OPT_AVIPadScanlines" // Have scanlines mod4 padded in all pixel formats #define VARNAME_UseWaveExtensible "OPT_UseWaveExtensible" // Use WAVEFORMATEXTENSIBLE when describing audio to Windows #define VARNAME_dwChannelMask "OPT_dwChannelMask" // Integer audio channel mask. See description of WAVEFORMATEXTENSIBLE for more info. #define VARNAME_Enable_V210 "OPT_Enable_V210" // AVS+ use V210 instead of P210 (VfW) #define VARNAME_Enable_Y3_10_10 "OPT_Enable_Y3_10_10" // AVS+ use Y3[10][10] instead of P210 (VfW) #define VARNAME_Enable_Y3_10_16 "OPT_Enable_Y3_10_16" // AVS+ use Y3[10][16] instead of P216 (VfW) #define VARNAME_Enable_b64a "OPT_Enable_b64a" // AVS+ use b64a instead of BRA[64] (VfW) #define VARNAME_Enable_PlanarToPackedRGB "OPT_Enable_PlanarToPackedRGB" // AVS+ convert Planar RGB to packed RGB (VfW) // C exports #include "avs/capi.h" AVSC_API(IScriptEnvironment2*, CreateScriptEnvironment2)(int version = AVISYNTH_INTERFACE_VERSION); #ifndef BUILDING_AVSCORE #undef AVS_UNUSED #endif #pragma pack(pop) #endif //__AVISYNTH_10_H__ ================================================ FILE: thirdparty/64/include/avisynth/avisynth_c.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // Copyright 2020 AviSynth+ project // Actual C Interface version follows the global Avisynth+ IF version numbers. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, // MA 02110-1301 USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. // NOTE: this is a partial update of the Avisynth C interface to recognize // new color spaces and interface elements added in Avisynth 2.60 and AviSynth+. // This interface is not 100% Avisynth+ CPP interface equivalent. // 170103: added new CPU constants (FMA4, AVX512xx) // 171102: define SIZETMOD. do not use yet, experimental. Offsets are size_t instead of int. Affects x64. // 171106: avs_get_row_size calls into avs_get_row_size_p, instead of direct field access // 171106: avs_get_height calls into avs_get_row_size_p, instead of direct field access // 180524: AVSC_EXPORT to dllexport in capi.h for avisynth_c_plugin_init // 180524: avs_is_same_colorspace VideoInfo parameters to const // 181230: Readability: functions regrouped to mix less AVSC_API and AVSC_INLINE, put together Avisynth+ specific stuff // 181230: use #ifndef AVSC_NO_DECLSPEC for AVSC_INLINE functions which are calling API functions // 181230: comments on avs_load_library (helper for loading API entries dynamically into a struct using AVSC_NO_DECLSPEC define) // 181230: define alias AVS_FRAME_ALIGN as FRAME_ALIGN // 181230: remove unused form of avs_get_rowsize and avs_get_height (kept earlier for reference) // 190104: avs_load_library: smart fallback mechanism for Avisynth+ specific functions: // if they are not loadable, they will work in a classic Avisynth compatible mode // Example#1: e.g. avs_is_444 will call the existing avs_is_yv24 instead // Example#2: avs_bits_per_component will return 8 for all colorspaces (Classic Avisynth supports only 8 bits/pixel) // Thus the Avisynth+ specific API functions are safely callable even when connected to classic Avisynth DLL // 2002xx non-Windows friendly additions // 200305 avs_vsprintf parameter type change: (void *) to va_list // 200330: (remove test SIZETMOD define for clarity) // 200513: user must use explicite #define AVS26_FALLBACK_SIMULATION for having fallback helpers in dynamic loaded library section // 200513: Follow AviSynth+ V8 interface additions // AVS_VideoFrame struct extended with placeholder for frame property pointer // avs_subframe_planar_a // avs_copy_frame_props // avs_get_frame_props_ro, avs_get_frame_props_rw // avs_prop_num_keys, avs_prop_get_key, avs_prop_num_elements, avs_prop_get_type, avs_prop_get_data_size // avs_prop_get_int, avs_prop_get_float, avs_prop_get_data, avs_prop_get_clip, avs_prop_get_frame, avs_prop_get_int_array, avs_prop_get_float_array // avs_prop_set_int, avs_prop_set_float, avs_prop_set_data, avs_prop_set_clip, avs_prop_set_frame, avs_prop_set_int_array, avs_prop_set_float_array // avs_prop_delete_key, avs_clear_map // avs_new_video_frame_p, avs_new_video_frame_p_a // avs_get_env_property (internal system properties), AVS_AEP_xxx (AvsEnvProperty) enums // avs_get_var_try, avs_get_var_bool, avs_get_var_int, avs_get_var_double, avs_get_var_string, avs_get_var_long // avs_pool_allocate, avs_pool_free // 2021: Follow AviSynth+ V9 interface additions // avs_is_property_writable, avs_make_property_writable // Add enum AVISYNTHPLUS_INTERFACE_BUGFIX_VERSION (AVISYNTH_INTERFACE_VERSION still exists) // Add enum AVS_AEP_HOST_SYSTEM_ENDIANNESS to system property request types (avs_get_env_property) // Add enums AVS_AEP_INTERFACE_VERSION and AVS_AEP_INTERFACE_BUGFIX for direct interface version system property request types (avs_get_env_property) // Bugfix 9.1: fix avs_prop_get_data // 2023: Follow AviSynth+ V10 interface additions // Add enum AVS_DEFAULT_PLANE (as 0) to plane constants // prop_src argument now const in avs_new_video_frame_p and avs_new_video_frame_p_a (no change in use) // Add pixel_type to struct AVS_VideoFrame // Add avs_video_frame_get_pixel_type and avs_video_frame_amend_pixel_type for getting and setting AVS_VideoFrame pixel_type // Additional AviSynth+ V10 interface additions: // Add enum AVS_SPEAKER_xxx, AVS_IT_SPEAKER_xxx // audio channel mask support avs_is_channel_mask_known, avs_set_channel_mask, avs_get_channel_mask #ifndef __AVISYNTH_C__ #define __AVISYNTH_C__ #include "avs/config.h" #include "avs/capi.h" #include "avs/types.h" #define AVS_FRAME_ALIGN FRAME_ALIGN ///////////////////////////////////////////////////////////////////// // // Constants // #ifndef __AVISYNTH_10_H__ enum { AVISYNTH_INTERFACE_CLASSIC_VERSION = 6, AVISYNTH_INTERFACE_VERSION = 10, AVISYNTHPLUS_INTERFACE_BUGFIX_VERSION = 0 // reset to zero whenever the normal interface version bumps }; #endif enum { AVS_SAMPLE_INT8 = 1 << 0, AVS_SAMPLE_INT16 = 1 << 1, AVS_SAMPLE_INT24 = 1 << 2, AVS_SAMPLE_INT32 = 1 << 3, AVS_SAMPLE_FLOAT = 1 << 4 }; enum { AVS_DEFAULT_PLANE = 0, AVS_PLANAR_Y = 1 << 0, AVS_PLANAR_U = 1 << 1, AVS_PLANAR_V = 1 << 2, AVS_PLANAR_ALIGNED = 1 << 3, AVS_PLANAR_Y_ALIGNED = AVS_PLANAR_Y | AVS_PLANAR_ALIGNED, AVS_PLANAR_U_ALIGNED = AVS_PLANAR_U | AVS_PLANAR_ALIGNED, AVS_PLANAR_V_ALIGNED = AVS_PLANAR_V | AVS_PLANAR_ALIGNED, AVS_PLANAR_A = 1 << 4, AVS_PLANAR_R = 1 << 5, AVS_PLANAR_G = 1 << 6, AVS_PLANAR_B = 1 << 7, AVS_PLANAR_A_ALIGNED = AVS_PLANAR_A | AVS_PLANAR_ALIGNED, AVS_PLANAR_R_ALIGNED = AVS_PLANAR_R | AVS_PLANAR_ALIGNED, AVS_PLANAR_G_ALIGNED = AVS_PLANAR_G | AVS_PLANAR_ALIGNED, AVS_PLANAR_B_ALIGNED = AVS_PLANAR_B | AVS_PLANAR_ALIGNED }; // Colorspace properties. enum { AVS_CS_YUVA = 1 << 27, AVS_CS_BGR = 1 << 28, AVS_CS_YUV = 1 << 29, AVS_CS_INTERLEAVED = 1 << 30, AVS_CS_PLANAR = 1 << 31, AVS_CS_SHIFT_SUB_WIDTH = 0, AVS_CS_SHIFT_SUB_HEIGHT = 8, AVS_CS_SHIFT_SAMPLE_BITS = 16, AVS_CS_SUB_WIDTH_MASK = 7 << AVS_CS_SHIFT_SUB_WIDTH, AVS_CS_SUB_WIDTH_1 = 3 << AVS_CS_SHIFT_SUB_WIDTH, // YV24 AVS_CS_SUB_WIDTH_2 = 0 << AVS_CS_SHIFT_SUB_WIDTH, // YV12, I420, YV16 AVS_CS_SUB_WIDTH_4 = 1 << AVS_CS_SHIFT_SUB_WIDTH, // YUV9, YV411 AVS_CS_VPLANEFIRST = 1 << 3, // YV12, YV16, YV24, YV411, YUV9 AVS_CS_UPLANEFIRST = 1 << 4, // I420 AVS_CS_SUB_HEIGHT_MASK = 7 << AVS_CS_SHIFT_SUB_HEIGHT, AVS_CS_SUB_HEIGHT_1 = 3 << AVS_CS_SHIFT_SUB_HEIGHT, // YV16, YV24, YV411 AVS_CS_SUB_HEIGHT_2 = 0 << AVS_CS_SHIFT_SUB_HEIGHT, // YV12, I420 AVS_CS_SUB_HEIGHT_4 = 1 << AVS_CS_SHIFT_SUB_HEIGHT, // YUV9 AVS_CS_SAMPLE_BITS_MASK = 7 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_8 = 0 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_10 = 5 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_12 = 6 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_14 = 7 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_16 = 1 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_SAMPLE_BITS_32 = 2 << AVS_CS_SHIFT_SAMPLE_BITS, AVS_CS_PLANAR_MASK = AVS_CS_PLANAR | AVS_CS_INTERLEAVED | AVS_CS_YUV | AVS_CS_BGR | AVS_CS_YUVA | AVS_CS_SAMPLE_BITS_MASK | AVS_CS_SUB_WIDTH_MASK | AVS_CS_SUB_HEIGHT_MASK, AVS_CS_PLANAR_FILTER = ~(AVS_CS_VPLANEFIRST | AVS_CS_UPLANEFIRST), AVS_CS_RGB_TYPE = 1 << 0, AVS_CS_RGBA_TYPE = 1 << 1, AVS_CS_GENERIC_YUV444 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_1 | AVS_CS_SUB_HEIGHT_1, // 4:4:4 planar AVS_CS_GENERIC_YUV422 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_1, // 4:2:2 planar AVS_CS_GENERIC_YUV420 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_2, // 4:2:0 planar AVS_CS_GENERIC_Y = AVS_CS_PLANAR | AVS_CS_INTERLEAVED | AVS_CS_YUV, // Y only (4:0:0) AVS_CS_GENERIC_RGBP = AVS_CS_PLANAR | AVS_CS_BGR | AVS_CS_RGB_TYPE, // planar RGB AVS_CS_GENERIC_RGBAP = AVS_CS_PLANAR | AVS_CS_BGR | AVS_CS_RGBA_TYPE, // planar RGBA AVS_CS_GENERIC_YUVA444 = AVS_CS_PLANAR | AVS_CS_YUVA | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_1 | AVS_CS_SUB_HEIGHT_1, // 4:4:4:A planar AVS_CS_GENERIC_YUVA422 = AVS_CS_PLANAR | AVS_CS_YUVA | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_1, // 4:2:2:A planar AVS_CS_GENERIC_YUVA420 = AVS_CS_PLANAR | AVS_CS_YUVA | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_2 // 4:2:0:A planar }; // Specific color formats enum { AVS_CS_UNKNOWN = 0, AVS_CS_BGR24 = AVS_CS_RGB_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED, AVS_CS_BGR32 = AVS_CS_RGBA_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED, AVS_CS_YUY2 = 1 << 2 | AVS_CS_YUV | AVS_CS_INTERLEAVED, // AVS_CS_YV12 = 1 << 3 Reserved // AVS_CS_I420 = 1 << 4 Reserved AVS_CS_RAW32 = 1 << 5 | AVS_CS_INTERLEAVED, AVS_CS_YV24 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_8, // YUV 4:4:4 planar AVS_CS_YV16 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_8, // YUV 4:2:2 planar AVS_CS_YV12 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_8, // YUV 4:2:0 planar AVS_CS_I420 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_SAMPLE_BITS_8 | AVS_CS_UPLANEFIRST | AVS_CS_SUB_WIDTH_2 | AVS_CS_SUB_HEIGHT_2, // YUV 4:2:0 planar AVS_CS_IYUV = AVS_CS_I420, AVS_CS_YV411 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_SAMPLE_BITS_8 | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_4 | AVS_CS_SUB_HEIGHT_1, // YUV 4:1:1 planar AVS_CS_YUV9 = AVS_CS_PLANAR | AVS_CS_YUV | AVS_CS_SAMPLE_BITS_8 | AVS_CS_VPLANEFIRST | AVS_CS_SUB_WIDTH_4 | AVS_CS_SUB_HEIGHT_4, // YUV 4:1:0 planar AVS_CS_Y8 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_8, // Y 4:0:0 planar //------------------------- // AVS16: new planar constants go live! Experimental PF 160613 // 10-12-14-16 bit + planar RGB + BGR48/64 160725 AVS_CS_YUV444P10 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_10, // YUV 4:4:4 10bit samples AVS_CS_YUV422P10 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_10, // YUV 4:2:2 10bit samples AVS_CS_YUV420P10 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_10, // YUV 4:2:0 10bit samples AVS_CS_Y10 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_10, // Y 4:0:0 10bit samples AVS_CS_YUV444P12 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_12, // YUV 4:4:4 12bit samples AVS_CS_YUV422P12 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_12, // YUV 4:2:2 12bit samples AVS_CS_YUV420P12 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_12, // YUV 4:2:0 12bit samples AVS_CS_Y12 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_12, // Y 4:0:0 12bit samples AVS_CS_YUV444P14 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_14, // YUV 4:4:4 14bit samples AVS_CS_YUV422P14 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_14, // YUV 4:2:2 14bit samples AVS_CS_YUV420P14 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_14, // YUV 4:2:0 14bit samples AVS_CS_Y14 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_14, // Y 4:0:0 14bit samples AVS_CS_YUV444P16 = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_16, // YUV 4:4:4 16bit samples AVS_CS_YUV422P16 = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_16, // YUV 4:2:2 16bit samples AVS_CS_YUV420P16 = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_16, // YUV 4:2:0 16bit samples AVS_CS_Y16 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_16, // Y 4:0:0 16bit samples // 32 bit samples (float) AVS_CS_YUV444PS = AVS_CS_GENERIC_YUV444 | AVS_CS_SAMPLE_BITS_32, // YUV 4:4:4 32bit samples AVS_CS_YUV422PS = AVS_CS_GENERIC_YUV422 | AVS_CS_SAMPLE_BITS_32, // YUV 4:2:2 32bit samples AVS_CS_YUV420PS = AVS_CS_GENERIC_YUV420 | AVS_CS_SAMPLE_BITS_32, // YUV 4:2:0 32bit samples AVS_CS_Y32 = AVS_CS_GENERIC_Y | AVS_CS_SAMPLE_BITS_32, // Y 4:0:0 32bit samples // RGB packed AVS_CS_BGR48 = AVS_CS_RGB_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED | AVS_CS_SAMPLE_BITS_16, // BGR 3x16 bit AVS_CS_BGR64 = AVS_CS_RGBA_TYPE | AVS_CS_BGR | AVS_CS_INTERLEAVED | AVS_CS_SAMPLE_BITS_16, // BGR 4x16 bit // no packed 32 bit (float) support for these legacy types // RGB planar AVS_CS_RGBP = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_8, // Planar RGB 8 bit samples AVS_CS_RGBP10 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_10, // Planar RGB 10bit samples AVS_CS_RGBP12 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_12, // Planar RGB 12bit samples AVS_CS_RGBP14 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_14, // Planar RGB 14bit samples AVS_CS_RGBP16 = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_16, // Planar RGB 16bit samples AVS_CS_RGBPS = AVS_CS_GENERIC_RGBP | AVS_CS_SAMPLE_BITS_32, // Planar RGB 32bit samples // RGBA planar AVS_CS_RGBAP = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_8, // Planar RGBA 8 bit samples AVS_CS_RGBAP10 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_10, // Planar RGBA 10bit samples AVS_CS_RGBAP12 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_12, // Planar RGBA 12bit samples AVS_CS_RGBAP14 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_14, // Planar RGBA 14bit samples AVS_CS_RGBAP16 = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_16, // Planar RGBA 16bit samples AVS_CS_RGBAPS = AVS_CS_GENERIC_RGBAP | AVS_CS_SAMPLE_BITS_32, // Planar RGBA 32bit samples // Planar YUVA AVS_CS_YUVA444 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_8, // YUVA 4:4:4 8bit samples AVS_CS_YUVA422 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_8, // YUVA 4:2:2 8bit samples AVS_CS_YUVA420 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_8, // YUVA 4:2:0 8bit samples AVS_CS_YUVA444P10 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_10, // YUVA 4:4:4 10bit samples AVS_CS_YUVA422P10 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_10, // YUVA 4:2:2 10bit samples AVS_CS_YUVA420P10 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_10, // YUVA 4:2:0 10bit samples AVS_CS_YUVA444P12 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_12, // YUVA 4:4:4 12bit samples AVS_CS_YUVA422P12 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_12, // YUVA 4:2:2 12bit samples AVS_CS_YUVA420P12 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_12, // YUVA 4:2:0 12bit samples AVS_CS_YUVA444P14 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_14, // YUVA 4:4:4 14bit samples AVS_CS_YUVA422P14 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_14, // YUVA 4:2:2 14bit samples AVS_CS_YUVA420P14 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_14, // YUVA 4:2:0 14bit samples AVS_CS_YUVA444P16 = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_16, // YUVA 4:4:4 16bit samples AVS_CS_YUVA422P16 = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_16, // YUVA 4:2:2 16bit samples AVS_CS_YUVA420P16 = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_16, // YUVA 4:2:0 16bit samples AVS_CS_YUVA444PS = AVS_CS_GENERIC_YUVA444 | AVS_CS_SAMPLE_BITS_32, // YUVA 4:4:4 32bit samples AVS_CS_YUVA422PS = AVS_CS_GENERIC_YUVA422 | AVS_CS_SAMPLE_BITS_32, // YUVA 4:2:2 32bit samples AVS_CS_YUVA420PS = AVS_CS_GENERIC_YUVA420 | AVS_CS_SAMPLE_BITS_32, // YUVA 4:2:0 32bit samples }; // AvsChannelMask enum: Unshifted channel mask constants like in WAVEFORMATEXTENSIBLE // in AvsImageTypeFlags they are shifted by 4 bits enum { AVS_MASK_SPEAKER_FRONT_LEFT = 0x1, AVS_MASK_SPEAKER_FRONT_RIGHT = 0x2, AVS_MASK_SPEAKER_FRONT_CENTER = 0x4, AVS_MASK_SPEAKER_LOW_FREQUENCY = 0x8, AVS_MASK_SPEAKER_BACK_LEFT = 0x10, AVS_MASK_SPEAKER_BACK_RIGHT = 0x20, AVS_MASK_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40, AVS_MASK_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80, AVS_MASK_SPEAKER_BACK_CENTER = 0x100, AVS_MASK_SPEAKER_SIDE_LEFT = 0x200, AVS_MASK_SPEAKER_SIDE_RIGHT = 0x400, AVS_MASK_SPEAKER_TOP_CENTER = 0x800, AVS_MASK_SPEAKER_TOP_FRONT_LEFT = 0x1000, AVS_MASK_SPEAKER_TOP_FRONT_CENTER = 0x2000, AVS_MASK_SPEAKER_TOP_FRONT_RIGHT = 0x4000, AVS_MASK_SPEAKER_TOP_BACK_LEFT = 0x8000, AVS_MASK_SPEAKER_TOP_BACK_CENTER = 0x10000, AVS_MASK_SPEAKER_TOP_BACK_RIGHT = 0x20000, // Bit mask locations used up for the above positions AVS_MASK_SPEAKER_DEFINED = 0x0003FFFF, // Bit mask locations reserved for future use AVS_MASK_SPEAKER_RESERVED = 0x7FFC0000, // Used to specify that any possible permutation of speaker configurations // Due to lack of available bits this one is put differently into image_type AVS_MASK_SPEAKER_ALL = 0x80000000 }; // AvsImageTypeFlags enum { AVS_IT_BFF = 1 << 0, AVS_IT_TFF = 1 << 1, AVS_IT_FIELDBASED = 1 << 2, // Audio channel mask support AVS_IT_HAS_CHANNELMASK = 1 << 3, // shifted by 4 bits compared to WAVEFORMATEXTENSIBLE dwChannelMask // otherwise same as AvsChannelMask AVS_IT_SPEAKER_FRONT_LEFT = 0x1 << 4, AVS_IT_SPEAKER_FRONT_RIGHT = 0x2 << 4, AVS_IT_SPEAKER_FRONT_CENTER = 0x4 << 4, AVS_IT_SPEAKER_LOW_FREQUENCY = 0x8 << 4, AVS_IT_SPEAKER_BACK_LEFT = 0x10 << 4, AVS_IT_SPEAKER_BACK_RIGHT = 0x20 << 4, AVS_IT_SPEAKER_FRONT_LEFT_OF_CENTER = 0x40 << 4, AVS_IT_SPEAKER_FRONT_RIGHT_OF_CENTER = 0x80 << 4, AVS_IT_SPEAKER_BACK_CENTER = 0x100 << 4, AVS_IT_SPEAKER_SIDE_LEFT = 0x200 << 4, AVS_IT_SPEAKER_SIDE_RIGHT = 0x400 << 4, AVS_IT_SPEAKER_TOP_CENTER = 0x800 << 4, AVS_IT_SPEAKER_TOP_FRONT_LEFT = 0x1000 << 4, AVS_IT_SPEAKER_TOP_FRONT_CENTER = 0x2000 << 4, AVS_IT_SPEAKER_TOP_FRONT_RIGHT = 0x4000 << 4, AVS_IT_SPEAKER_TOP_BACK_LEFT = 0x8000 << 4, AVS_IT_SPEAKER_TOP_BACK_CENTER = 0x10000 << 4, AVS_IT_SPEAKER_TOP_BACK_RIGHT = 0x20000 << 4, // End of officially defined speaker bits // The next one is special, since cannot shift SPEAKER_ALL 0x80000000 further. // Set mask and get mask handles it. AVS_IT_SPEAKER_ALL = 0x40000 << 4, // Mask for the defined 18 bits + SPEAKER_ALL AVS_IT_SPEAKER_BITS_MASK = (AVS_MASK_SPEAKER_DEFINED << 4) | AVS_IT_SPEAKER_ALL, AVS_IT_NEXT_AVAILABLE = 1 << 23 }; enum { AVS_FILTER_TYPE = 1, AVS_FILTER_INPUT_COLORSPACE = 2, AVS_FILTER_OUTPUT_TYPE = 9, AVS_FILTER_NAME = 4, AVS_FILTER_AUTHOR = 5, AVS_FILTER_VERSION = 6, AVS_FILTER_ARGS = 7, AVS_FILTER_ARGS_INFO = 8, AVS_FILTER_ARGS_DESCRIPTION = 10, AVS_FILTER_DESCRIPTION = 11 }; enum { // SUBTYPES AVS_FILTER_TYPE_AUDIO = 1, AVS_FILTER_TYPE_VIDEO = 2, AVS_FILTER_OUTPUT_TYPE_SAME = 3, AVS_FILTER_OUTPUT_TYPE_DIFFERENT = 4 }; enum { // New 2.6 explicitly defined cache hints. AVS_CACHE_NOTHING = 10, // Do not cache video. AVS_CACHE_WINDOW = 11, // Hard protect up to X frames within a range of X from the current frame N. AVS_CACHE_GENERIC = 12, // LRU cache up to X frames. AVS_CACHE_FORCE_GENERIC = 13, // LRU cache up to X frames, override any previous CACHE_WINDOW. AVS_CACHE_GET_POLICY = 30, // Get the current policy. AVS_CACHE_GET_WINDOW = 31, // Get the current window h_span. AVS_CACHE_GET_RANGE = 32, // Get the current generic frame range. // Set Audio cache mode and answers to CACHE_GETCHILD_AUDIO_MODE AVS_CACHE_AUDIO = 50, // Explicitly do cache audio, X byte cache. AVS_CACHE_AUDIO_NOTHING = 51, // Explicitly do not cache audio. AVS_CACHE_AUDIO_NONE = 52, // Audio cache off (auto mode), X byte initial cache. AVS_CACHE_AUDIO_AUTO_START_OFF = 52, // synonym AVS_CACHE_AUDIO_AUTO = 53, // Audio cache on (auto mode), X byte initial cache. AVS_CACHE_AUDIO_AUTO_START_ON = 53, // synonym // These just returns actual value if clip is cached AVS_CACHE_GET_AUDIO_POLICY = 70, // Get the current audio policy. AVS_CACHE_GET_AUDIO_SIZE = 71, // Get the current audio cache size. AVS_CACHE_PREFETCH_FRAME = 100, // n/a Queue request to prefetch frame N. AVS_CACHE_PREFETCH_GO = 101, // n/a Action video prefetches. AVS_CACHE_PREFETCH_AUDIO_BEGIN = 120, // n/a Begin queue request transaction to prefetch audio (take critical section). AVS_CACHE_PREFETCH_AUDIO_STARTLO = 121, // n/a Set low 32 bits of start. AVS_CACHE_PREFETCH_AUDIO_STARTHI = 122, // n/a Set high 32 bits of start. AVS_CACHE_PREFETCH_AUDIO_COUNT = 123, // n/a Set low 32 bits of length. AVS_CACHE_PREFETCH_AUDIO_COMMIT = 124, // n/a Enqueue request transaction to prefetch audio (release critical section). AVS_CACHE_PREFETCH_AUDIO_GO = 125, // n/a Action audio prefetches. AVS_CACHE_GETCHILD_CACHE_MODE = 200, // n/a Cache ask Child for desired video cache mode. AVS_CACHE_GETCHILD_CACHE_SIZE = 201, // n/a Cache ask Child for desired video cache size. // Filters are queried about their desired audio cache mode. // Child can answer them with CACHE_AUDIO_xxx AVS_CACHE_GETCHILD_AUDIO_MODE = 202, // Cache ask Child for desired audio cache mode. AVS_CACHE_GETCHILD_AUDIO_SIZE = 203, // Cache ask Child for desired audio cache size. AVS_CACHE_GETCHILD_COST = 220, // n/a Cache ask Child for estimated processing cost. AVS_CACHE_COST_ZERO = 221, // n/a Child response of zero cost (ptr arithmetic only). AVS_CACHE_COST_UNIT = 222, // n/a Child response of unit cost (less than or equal 1 full frame blit). AVS_CACHE_COST_LOW = 223, // n/a Child response of light cost. (Fast) AVS_CACHE_COST_MED = 224, // n/a Child response of medium cost. (Real time) AVS_CACHE_COST_HI = 225, // n/a Child response of heavy cost. (Slow) AVS_CACHE_GETCHILD_THREAD_MODE = 240, // n/a Cache ask Child for thread safety. AVS_CACHE_THREAD_UNSAFE = 241, // n/a Only 1 thread allowed for all instances. 2.5 filters default! AVS_CACHE_THREAD_CLASS = 242, // n/a Only 1 thread allowed for each instance. 2.6 filters default! AVS_CACHE_THREAD_SAFE = 243, // n/a Allow all threads in any instance. AVS_CACHE_THREAD_OWN = 244, // n/a Safe but limit to 1 thread, internally threaded. AVS_CACHE_GETCHILD_ACCESS_COST = 260, // Cache ask Child for preferred access pattern. AVS_CACHE_ACCESS_RAND = 261, // Filter is access order agnostic. AVS_CACHE_ACCESS_SEQ0 = 262, // Filter prefers sequential access (low cost) AVS_CACHE_ACCESS_SEQ1 = 263, // Filter needs sequential access (high cost) AVS_CACHE_AVSPLUS_CONSTANTS = 500, // Smaller values are reserved for classic Avisynth AVS_CACHE_DONT_CACHE_ME = 501, // Filters that don't need caching (eg. trim, cache etc.) should return 1 to this request AVS_CACHE_SET_MIN_CAPACITY = 502, AVS_CACHE_SET_MAX_CAPACITY = 503, AVS_CACHE_GET_MIN_CAPACITY = 504, AVS_CACHE_GET_MAX_CAPACITY = 505, AVS_CACHE_GET_SIZE = 506, AVS_CACHE_GET_REQUESTED_CAP = 507, AVS_CACHE_GET_CAPACITY = 508, AVS_CACHE_GET_MTMODE = 509, // Filters specify their desired MT mode, see enum MtMode // By returning IS_CACHE_ANS to IS_CACHE_REQ, we tell the caller we are a cache AVS_CACHE_IS_CACHE_REQ = 510, AVS_CACHE_IS_CACHE_ANS = 511, // By returning IS_MTGUARD_ANS to IS_MTGUARD_REQ, we tell the caller we are an mt guard AVS_CACHE_IS_MTGUARD_REQ = 512, AVS_CACHE_IS_MTGUARD_ANS = 513, AVS_CACHE_AVSPLUS_CUDA_CONSTANTS = 600, AVS_CACHE_GET_DEV_TYPE = 601, // Device types a filter can return AVS_CACHE_GET_CHILD_DEV_TYPE = 602, // Device types a fitler can receive AVS_CACHE_USER_CONSTANTS = 1000 // Smaller values are reserved for the core }; // enums for frame property functions // AVSPropTypes enum { AVS_PROPTYPE_UNSET = 'u', AVS_PROPTYPE_INT = 'i', AVS_PROPTYPE_FLOAT = 'f', AVS_PROPTYPE_DATA = 's', AVS_PROPTYPE_CLIP = 'c', AVS_PROPTYPE_FRAME = 'v' }; // AVSGetPropErrors for avs_prop_get_... enum { AVS_GETPROPERROR_UNSET = 1, AVS_GETPROPERROR_TYPE = 2, AVS_GETPROPERROR_INDEX = 4 }; // AVSPropAppendMode for avs_prop_set_... enum { AVS_PROPAPPENDMODE_REPLACE = 0, AVS_PROPAPPENDMODE_APPEND = 1, AVS_PROPAPPENDMODE_TOUCH = 2 }; // AvsEnvProperty for avs_get_env_property enum { AVS_AEP_PHYSICAL_CPUS = 1, AVS_AEP_LOGICAL_CPUS = 2, AVS_AEP_THREADPOOL_THREADS = 3, AVS_AEP_FILTERCHAIN_THREADS = 4, AVS_AEP_THREAD_ID = 5, AVS_AEP_VERSION = 6, AVS_AEP_HOST_SYSTEM_ENDIANNESS = 7, AVS_AEP_INTERFACE_VERSION = 8, AVS_AEP_INTERFACE_BUGFIX = 9, // Neo additionals AVS_AEP_NUM_DEVICES = 901, AVS_AEP_FRAME_ALIGN = 902, AVS_AEP_PLANE_ALIGN = 903, AVS_AEP_SUPPRESS_THREAD = 921, AVS_AEP_GETFRAME_RECURSIVE = 922 }; // enum AvsAllocType for avs_allocate enum { AVS_ALLOCTYPE_NORMAL_ALLOC = 1, AVS_ALLOCTYPE_POOLED_ALLOC = 2 }; #ifdef BUILDING_AVSCORE AVSValue create_c_video_filter(AVSValue args, void * user_data, IScriptEnvironment * e0); struct AVS_ScriptEnvironment { IScriptEnvironment * env; const char * error; AVS_ScriptEnvironment(IScriptEnvironment * e = 0) : env(e), error(0) {} }; #endif typedef struct AVS_Clip AVS_Clip; typedef struct AVS_ScriptEnvironment AVS_ScriptEnvironment; ///////////////////////////////////////////////////////////////////// // // AVS_VideoInfo // // AVS_VideoInfo is laid out identically to VideoInfo typedef struct AVS_VideoInfo { int width, height; // width=0 means no video unsigned fps_numerator, fps_denominator; int num_frames; int pixel_type; int audio_samples_per_second; // 0 means no audio int sample_type; int64_t num_audio_samples; int nchannels; // Image type properties // BFF, TFF, FIELDBASED. Also used for storing Channel Mask // Manipulate it through the channelmask interface calls int image_type; } AVS_VideoInfo; // useful functions of the above AVSC_INLINE int avs_has_video(const AVS_VideoInfo * p) { return (p->width!=0); } AVSC_INLINE int avs_has_audio(const AVS_VideoInfo * p) { return (p->audio_samples_per_second!=0); } AVSC_INLINE int avs_is_rgb(const AVS_VideoInfo * p) { return !!(p->pixel_type&AVS_CS_BGR); } AVSC_INLINE int avs_is_rgb24(const AVS_VideoInfo * p) { return ((p->pixel_type&AVS_CS_BGR24)==AVS_CS_BGR24) && ((p->pixel_type & AVS_CS_SAMPLE_BITS_MASK) == AVS_CS_SAMPLE_BITS_8); } AVSC_INLINE int avs_is_rgb32(const AVS_VideoInfo * p) { return ((p->pixel_type&AVS_CS_BGR32)==AVS_CS_BGR32) && ((p->pixel_type & AVS_CS_SAMPLE_BITS_MASK) == AVS_CS_SAMPLE_BITS_8); } AVSC_INLINE int avs_is_yuv(const AVS_VideoInfo * p) { return !!(p->pixel_type&AVS_CS_YUV ); } AVSC_INLINE int avs_is_yuy2(const AVS_VideoInfo * p) { return (p->pixel_type & AVS_CS_YUY2) == AVS_CS_YUY2; } AVSC_API(int, avs_is_yv24)(const AVS_VideoInfo * p); // avs+: for generic 444 check, use avs_is_yuv444 AVSC_API(int, avs_is_yv16)(const AVS_VideoInfo * p); // avs+: for generic 422 check, use avs_is_yuv422 AVSC_API(int, avs_is_yv12)(const AVS_VideoInfo * p) ; // avs+: for generic 420 check, use avs_is_yuv420 AVSC_API(int, avs_is_yv411)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_y8)(const AVS_VideoInfo * p); // avs+: for generic grayscale, use avs_is_y AVSC_API(int, avs_get_plane_width_subsampling)(const AVS_VideoInfo * p, int plane); AVSC_API(int, avs_get_plane_height_subsampling)(const AVS_VideoInfo * p, int plane); AVSC_API(int, avs_bits_per_pixel)(const AVS_VideoInfo * p); AVSC_API(int, avs_bytes_from_pixels)(const AVS_VideoInfo * p, int pixels); AVSC_API(int, avs_row_size)(const AVS_VideoInfo * p, int plane); AVSC_API(int, avs_bmp_size)(const AVS_VideoInfo * vi); AVSC_API(int, avs_is_color_space)(const AVS_VideoInfo * p, int c_space); // no API for these, inline helper functions AVSC_INLINE int avs_is_property(const AVS_VideoInfo * p, int property) { return ((p->image_type & property) == property); } AVSC_INLINE int avs_is_planar(const AVS_VideoInfo * p) { return !!(p->pixel_type & AVS_CS_PLANAR); } AVSC_INLINE int avs_is_field_based(const AVS_VideoInfo * p) { return !!(p->image_type & AVS_IT_FIELDBASED); } AVSC_INLINE int avs_is_parity_known(const AVS_VideoInfo * p) { return ((p->image_type & AVS_IT_FIELDBASED) && (p->image_type & (AVS_IT_BFF | AVS_IT_TFF))); } AVSC_INLINE int avs_is_bff(const AVS_VideoInfo * p) { return !!(p->image_type & AVS_IT_BFF); } AVSC_INLINE int avs_is_tff(const AVS_VideoInfo * p) { return !!(p->image_type & AVS_IT_TFF); } AVSC_INLINE int avs_samples_per_second(const AVS_VideoInfo * p) { return p->audio_samples_per_second; } AVSC_INLINE int avs_bytes_per_channel_sample(const AVS_VideoInfo * p) { switch (p->sample_type) { case AVS_SAMPLE_INT8: return sizeof(signed char); case AVS_SAMPLE_INT16: return sizeof(signed short); case AVS_SAMPLE_INT24: return 3; case AVS_SAMPLE_INT32: return sizeof(signed int); case AVS_SAMPLE_FLOAT: return sizeof(float); default: return 0; } } AVSC_INLINE int avs_bytes_per_audio_sample(const AVS_VideoInfo * p) { return p->nchannels*avs_bytes_per_channel_sample(p);} AVSC_INLINE int64_t avs_audio_samples_from_frames(const AVS_VideoInfo * p, int64_t frames) { return ((int64_t)(frames) * p->audio_samples_per_second * p->fps_denominator / p->fps_numerator); } AVSC_INLINE int avs_frames_from_audio_samples(const AVS_VideoInfo * p, int64_t samples) { return (int)(samples * (int64_t)p->fps_numerator / (int64_t)p->fps_denominator / (int64_t)p->audio_samples_per_second); } AVSC_INLINE int64_t avs_audio_samples_from_bytes(const AVS_VideoInfo * p, int64_t bytes) { return bytes / avs_bytes_per_audio_sample(p); } AVSC_INLINE int64_t avs_bytes_from_audio_samples(const AVS_VideoInfo * p, int64_t samples) { return samples * avs_bytes_per_audio_sample(p); } AVSC_INLINE int avs_audio_channels(const AVS_VideoInfo * p) { return p->nchannels; } AVSC_INLINE int avs_sample_type(const AVS_VideoInfo * p) { return p->sample_type;} // useful mutator // Note: these are video format properties, neither frame properties, nor system properties AVSC_INLINE void avs_set_property(AVS_VideoInfo * p, int property) { p->image_type|=property; } AVSC_INLINE void avs_clear_property(AVS_VideoInfo * p, int property) { p->image_type&=~property; } AVSC_INLINE void avs_set_field_based(AVS_VideoInfo * p, int isfieldbased) { if (isfieldbased) p->image_type|=AVS_IT_FIELDBASED; else p->image_type&=~AVS_IT_FIELDBASED; } AVSC_INLINE void avs_set_fps(AVS_VideoInfo * p, unsigned numerator, unsigned denominator) { unsigned x=numerator, y=denominator; while (y) { // find gcd unsigned t = x%y; x = y; y = t; } p->fps_numerator = numerator/x; p->fps_denominator = denominator/x; } #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_is_same_colorspace(const AVS_VideoInfo * x, const AVS_VideoInfo * y) { return (x->pixel_type == y->pixel_type) || (avs_is_yv12(x) && avs_is_yv12(y)); } #endif // AviSynth+ extensions AVSC_API(int, avs_is_rgb48)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_rgb64)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_yuv444p16)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv444 AVSC_API(int, avs_is_yuv422p16)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv422 AVSC_API(int, avs_is_yuv420p16)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv420 AVSC_API(int, avs_is_y16)(const AVS_VideoInfo * p); // deprecated, use avs_is_y AVSC_API(int, avs_is_yuv444ps)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv444 AVSC_API(int, avs_is_yuv422ps)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv422 AVSC_API(int, avs_is_yuv420ps)(const AVS_VideoInfo * p); // deprecated, use avs_is_yuv420 AVSC_API(int, avs_is_y32)(const AVS_VideoInfo * p); // deprecated, use avs_is_y AVSC_API(int, avs_is_444)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_422)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_420)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_y)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_yuva)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_planar_rgb)(const AVS_VideoInfo * p); AVSC_API(int, avs_is_planar_rgba)(const AVS_VideoInfo * p); AVSC_API(int, avs_num_components)(const AVS_VideoInfo * p); AVSC_API(int, avs_component_size)(const AVS_VideoInfo * p); AVSC_API(int, avs_bits_per_component)(const AVS_VideoInfo * p); // V10 AVSC_API(bool, avs_is_channel_mask_known)(const AVS_VideoInfo* p); AVSC_API(void, avs_set_channel_mask)(const AVS_VideoInfo* p, bool isChannelMaskKnown, unsigned int dwChannelMask); AVSC_API(unsigned int, avs_get_channel_mask)(const AVS_VideoInfo* p); // end of Avisynth+ specific ///////////////////////////////////////////////////////////////////// // // AVS_VideoFrame // // VideoFrameBuffer holds information about a memory block which is used // for video data. For efficiency, instances of this class are not deleted // when the refcount reaches zero; instead they're stored in a linked list // to be reused. The instances are deleted when the corresponding AVS // file is closed. // AVS_VideoFrameBuffer is laid out identically to VideoFrameBuffer // DO NOT USE THIS STRUCTURE DIRECTLY typedef struct AVS_VideoFrameBuffer { BYTE * data; int data_size; // sequence_number is incremented every time the buffer is changed, so // that stale views can tell they're no longer valid. volatile long sequence_number; volatile long refcount; void* device; // avs+ } AVS_VideoFrameBuffer; // VideoFrame holds a "window" into a VideoFrameBuffer. // AVS_VideoFrame is laid out identically to VideoFrame // DO NOT USE THIS STRUCTURE DIRECTLY typedef struct AVS_VideoFrame { volatile long refcount; AVS_VideoFrameBuffer * vfb; int offset; // DO NOT USE THEM DIRECTLY // Use avs_get_pitch_p, avs_get_row_size_p, avs_get_height_p int pitch, row_size, height; int offsetU, offsetV; int pitchUV; // U&V offsets are from top of picture. int row_sizeUV, heightUV; // for Planar RGB offsetU, offsetV is for the 2nd and 3rd Plane. // for Planar RGB pitchUV and row_sizeUV = 0, because when no VideoInfo (MakeWriteable) // the decision on existence of UV is checked by zero pitch // AVS+ extension, avisynth.h: class does not break plugins if appended here int offsetA; int pitchA, row_sizeA; // 4th alpha plane support, pitch and row_size is 0 is none void* properties; // interface V8: frame properties // DO NOT USE DIRECTLY // Use avs_video_frame_get_pixel_type (and avs_video_frame_amend_pixel_type in special cases) int pixel_type; // Interface V10: an automatically maintained copy from AVS_VideoInfo } AVS_VideoFrame; // Access functions for AVS_VideoFrame AVSC_API(int, avs_get_pitch_p)(const AVS_VideoFrame * p, int plane); AVSC_API(int, avs_get_row_size_p)(const AVS_VideoFrame * p, int plane); AVSC_API(int, avs_get_height_p)(const AVS_VideoFrame * p, int plane); AVSC_API(const BYTE *, avs_get_read_ptr_p)(const AVS_VideoFrame * p, int plane); AVSC_API(int, avs_is_writable)(const AVS_VideoFrame * p); // V9 AVSC_API(int, avs_is_property_writable)(const AVS_VideoFrame* p); AVSC_API(BYTE *, avs_get_write_ptr_p)(const AVS_VideoFrame * p, int plane); AVSC_API(void, avs_release_video_frame)(AVS_VideoFrame *); // makes a shallow copy of a video frame AVSC_API(AVS_VideoFrame *, avs_copy_video_frame)(AVS_VideoFrame *); // V10 AVSC_API(int, avs_video_frame_get_pixel_type)(const AVS_VideoFrame* p); // V10 AVSC_API(void, avs_video_frame_amend_pixel_type)(AVS_VideoFrame* p, int new_pixel_type); // no API for these, inline helper functions #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_get_pitch(const AVS_VideoFrame * p) { return avs_get_pitch_p(p, 0); } #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_get_row_size(const AVS_VideoFrame * p) { return avs_get_row_size_p(p, 0); } #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE int avs_get_height(const AVS_VideoFrame * p) { return avs_get_height_p(p, 0); } #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE const BYTE* avs_get_read_ptr(const AVS_VideoFrame * p) { return avs_get_read_ptr_p(p, 0);} #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE BYTE* avs_get_write_ptr(const AVS_VideoFrame * p) { return avs_get_write_ptr_p(p, 0);} #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE void avs_release_frame(AVS_VideoFrame * f) {avs_release_video_frame(f);} #endif #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE AVS_VideoFrame * avs_copy_frame(AVS_VideoFrame * f) {return avs_copy_video_frame(f);} #endif // Interface V8: frame properties // AVS_Map is just a placeholder for AVSMap typedef struct AVS_Map { void* data; } AVS_Map; ///////////////////////////////////////////////////////////////////// // // AVS_Value // // Treat AVS_Value as a fat pointer. That is use avs_copy_value // and avs_release_value appropriately as you would if AVS_Value was // a pointer. // To maintain source code compatibility with future versions of the // avisynth_c API don't use the AVS_Value directly. Use the helper // functions below. // AVS_Value is laid out identically to AVSValue typedef struct AVS_Value AVS_Value; struct AVS_Value { short type; // 'a'rray, 'c'lip, 'b'ool, 'i'nt, 'f'loat, 's'tring, 'v'oid, or 'l'ong, or fu'n'ction // for some function e'rror short array_size; union { void * clip; // do not use directly, use avs_take_clip char boolean; int integer; float floating_pt; const char * string; const AVS_Value * array; void * function; // not supported on C interface #ifdef X86_64 // if ever, only x64 will support. It breaks struct size on 32 bit int64_t longlong; // 8 bytes double double_pt; // 8 bytes #endif } d; }; // AVS_Value should be initialized with avs_void. // Should also set to avs_void after the value is released // with avs_copy_value. Consider it the equivalent of setting // a pointer to NULL static const AVS_Value avs_void = {'v'}; AVSC_API(void, avs_copy_value)(AVS_Value * dest, AVS_Value src); AVSC_API(void, avs_release_value)(AVS_Value); AVSC_API(AVS_Clip *, avs_take_clip)(AVS_Value, AVS_ScriptEnvironment *); AVSC_API(void, avs_set_to_clip)(AVS_Value *, AVS_Clip *); // no API for these, inline helper functions AVSC_INLINE int avs_defined(AVS_Value v) { return v.type != 'v'; } AVSC_INLINE int avs_is_clip(AVS_Value v) { return v.type == 'c'; } AVSC_INLINE int avs_is_bool(AVS_Value v) { return v.type == 'b'; } AVSC_INLINE int avs_is_int(AVS_Value v) { return v.type == 'i'; } AVSC_INLINE int avs_is_float(AVS_Value v) { return v.type == 'f' || v.type == 'i'; } AVSC_INLINE int avs_is_string(AVS_Value v) { return v.type == 's'; } AVSC_INLINE int avs_is_array(AVS_Value v) { return v.type == 'a'; } AVSC_INLINE int avs_is_error(AVS_Value v) { return v.type == 'e'; } AVSC_INLINE int avs_as_bool(AVS_Value v) { return v.d.boolean; } AVSC_INLINE int avs_as_int(AVS_Value v) { return v.d.integer; } AVSC_INLINE const char * avs_as_string(AVS_Value v) { return avs_is_error(v) || avs_is_string(v) ? v.d.string : 0; } AVSC_INLINE double avs_as_float(AVS_Value v) { return avs_is_int(v) ? v.d.integer : v.d.floating_pt; } AVSC_INLINE const char * avs_as_error(AVS_Value v) { return avs_is_error(v) ? v.d.string : 0; } AVSC_INLINE const AVS_Value * avs_as_array(AVS_Value v) { return v.d.array; } AVSC_INLINE int avs_array_size(AVS_Value v) { return avs_is_array(v) ? v.array_size : 1; } AVSC_INLINE AVS_Value avs_array_elt(AVS_Value v, int index) { return avs_is_array(v) ? v.d.array[index] : v; } // only use these functions on an AVS_Value that does not already have // an active value. Remember, treat AVS_Value as a fat pointer. AVSC_INLINE AVS_Value avs_new_value_bool(int v0) { AVS_Value v; v.type = 'b'; v.d.boolean = v0 == 0 ? 0 : 1; return v; } AVSC_INLINE AVS_Value avs_new_value_int(int v0) { AVS_Value v; v.type = 'i'; v.d.integer = v0; return v; } AVSC_INLINE AVS_Value avs_new_value_string(const char * v0) { AVS_Value v; v.type = 's'; v.d.string = v0; return v; } AVSC_INLINE AVS_Value avs_new_value_float(float v0) { AVS_Value v; v.type = 'f'; v.d.floating_pt = v0; return v;} AVSC_INLINE AVS_Value avs_new_value_error(const char * v0) { AVS_Value v; v.type = 'e'; v.d.string = v0; return v; } #ifndef AVSC_NO_DECLSPEC // this inline function is calling an API function AVSC_INLINE AVS_Value avs_new_value_clip(AVS_Clip * v0) { AVS_Value v; avs_set_to_clip(&v, v0); return v; } #endif AVSC_INLINE AVS_Value avs_new_value_array(AVS_Value * v0, int size) { AVS_Value v; v.type = 'a'; v.d.array = v0; v.array_size = (short)size; return v; } // end of inline helper functions ///////////////////////////////////////////////////////////////////// // // AVS_Clip // AVSC_API(void, avs_release_clip)(AVS_Clip *); AVSC_API(AVS_Clip *, avs_copy_clip)(AVS_Clip *); AVSC_API(const char *, avs_clip_get_error)(AVS_Clip *); // return 0 if no error AVSC_API(const AVS_VideoInfo *, avs_get_video_info)(AVS_Clip *); AVSC_API(int, avs_get_version)(AVS_Clip *); AVSC_API(AVS_VideoFrame *, avs_get_frame)(AVS_Clip *, int n); // The returned video frame must be released with avs_release_video_frame AVSC_API(int, avs_get_parity)(AVS_Clip *, int n); // return field parity if field_based, else parity of first field in frame AVSC_API(int, avs_get_audio)(AVS_Clip *, void * buf, int64_t start, int64_t count); // start and count are in samples AVSC_API(int, avs_set_cache_hints)(AVS_Clip *, int cachehints, int frame_range); // This is the callback type used by avs_add_function typedef AVS_Value (AVSC_CC * AVS_ApplyFunc) (AVS_ScriptEnvironment *, AVS_Value args, void * user_data); typedef struct AVS_FilterInfo AVS_FilterInfo; struct AVS_FilterInfo { // these members should not be modified outside of the AVS_ApplyFunc callback AVS_Clip * child; AVS_VideoInfo vi; AVS_ScriptEnvironment * env; AVS_VideoFrame * (AVSC_CC * get_frame)(AVS_FilterInfo *, int n); int (AVSC_CC * get_parity)(AVS_FilterInfo *, int n); int (AVSC_CC * get_audio)(AVS_FilterInfo *, void * buf, int64_t start, int64_t count); int (AVSC_CC * set_cache_hints)(AVS_FilterInfo *, int cachehints, int frame_range); void (AVSC_CC * free_filter)(AVS_FilterInfo *); // Should be set when ever there is an error to report. // It is cleared before any of the above methods are called const char * error; // this is to store whatever and may be modified at will void * user_data; }; // Create a new filter // fi is set to point to the AVS_FilterInfo so that you can // modify it once it is initialized. // store_child should generally be set to true. If it is not // set than ALL methods (the function pointers) must be defined // If it is set than you do not need to worry about freeing the child // clip. AVSC_API(AVS_Clip *, avs_new_c_filter)(AVS_ScriptEnvironment * e, AVS_FilterInfo * * fi, AVS_Value child, int store_child); ///////////////////////////////////////////////////////////////////// // // AVS_ScriptEnvironment // // For GetCPUFlags. These are backwards-compatible with those in VirtualDub. enum { /* slowest CPU to support extension */ AVS_CPU_FORCE = 0x01, // N/A AVS_CPU_FPU = 0x02, // 386/486DX AVS_CPU_MMX = 0x04, // P55C, K6, PII AVS_CPU_INTEGER_SSE = 0x08, // PIII, Athlon AVS_CPU_SSE = 0x10, // PIII, Athlon XP/MP AVS_CPU_SSE2 = 0x20, // PIV, Hammer AVS_CPU_3DNOW = 0x40, // K6-2 AVS_CPU_3DNOW_EXT = 0x80, // Athlon AVS_CPU_X86_64 = 0xA0, // Hammer (note: equiv. to 3DNow + SSE2, // which only Hammer will have anyway) AVS_CPUF_SSE3 = 0x100, // PIV+, K8 Venice AVS_CPUF_SSSE3 = 0x200, // Core 2 AVS_CPUF_SSE4 = 0x400, // Penryn, Wolfdale, Yorkfield AVS_CPUF_SSE4_1 = 0x400, AVS_CPUF_AVX = 0x800, // Sandy Bridge, Bulldozer AVS_CPUF_SSE4_2 = 0x1000, // Nehalem // AVS+ AVS_CPUF_AVX2 = 0x2000, // Haswell AVS_CPUF_FMA3 = 0x4000, AVS_CPUF_F16C = 0x8000, AVS_CPUF_MOVBE = 0x10000, // Big Endian Move AVS_CPUF_POPCNT = 0x20000, AVS_CPUF_AES = 0x40000, AVS_CPUF_FMA4 = 0x80000, AVS_CPUF_AVX512F = 0x100000, // AVX-512 Foundation. AVS_CPUF_AVX512DQ = 0x200000, // AVX-512 DQ (Double/Quad granular) Instructions AVS_CPUF_AVX512PF = 0x400000, // AVX-512 Prefetch AVS_CPUF_AVX512ER = 0x800000, // AVX-512 Exponential and Reciprocal AVS_CPUF_AVX512CD = 0x1000000, // AVX-512 Conflict Detection AVS_CPUF_AVX512BW = 0x2000000, // AVX-512 BW (Byte/Word granular) Instructions AVS_CPUF_AVX512VL = 0x4000000, // AVX-512 VL (128/256 Vector Length) Extensions AVS_CPUF_AVX512IFMA = 0x8000000, // AVX-512 IFMA integer 52 bit AVS_CPUF_AVX512VBMI = 0x10000000 // AVX-512 VBMI }; AVSC_API(const char *, avs_get_error)(AVS_ScriptEnvironment *); // return 0 if no error AVSC_API(int, avs_get_cpu_flags)(AVS_ScriptEnvironment *); AVSC_API(int, avs_check_version)(AVS_ScriptEnvironment *, int version); AVSC_API(char *, avs_save_string)(AVS_ScriptEnvironment *, const char* s, int length); AVSC_API(char *, avs_sprintf)(AVS_ScriptEnvironment *, const char * fmt, ...); AVSC_API(char *, avs_vsprintf)(AVS_ScriptEnvironment *, const char * fmt, va_list val); AVSC_API(int, avs_add_function)(AVS_ScriptEnvironment *, const char * name, const char * params, AVS_ApplyFunc apply, void * user_data); AVSC_API(int, avs_function_exists)(AVS_ScriptEnvironment *, const char * name); AVSC_API(AVS_Value, avs_invoke)(AVS_ScriptEnvironment *, const char * name, AVS_Value args, const char** arg_names); // The returned value must be be released with avs_release_value AVSC_API(AVS_Value, avs_get_var)(AVS_ScriptEnvironment *, const char* name); // The returned value must be be released with avs_release_value AVSC_API(int, avs_set_var)(AVS_ScriptEnvironment *, const char* name, AVS_Value val); AVSC_API(int, avs_set_global_var)(AVS_ScriptEnvironment *, const char* name, const AVS_Value val); //void avs_push_context(AVS_ScriptEnvironment *, int level=0); //void avs_pop_context(AVS_ScriptEnvironment *); // partially deprecated, from V8 use avs_new_video_frame_p_a (frame property copy) AVSC_API(AVS_VideoFrame *, avs_new_video_frame_a)(AVS_ScriptEnvironment *, const AVS_VideoInfo * vi, int align); // align should be at least 16 for classic Avisynth // Avisynth+: any value, Avs+ ensures a minimum alignment if too small align is provided // no API for these, inline helper functions #ifndef AVSC_NO_DECLSPEC // partially deprecated, from V8 use avs_new_video_frame_p (frame property copy) // this inline function is calling an API function AVSC_INLINE AVS_VideoFrame * avs_new_video_frame(AVS_ScriptEnvironment * env, const AVS_VideoInfo * vi) {return avs_new_video_frame_a(env,vi,AVS_FRAME_ALIGN);} // an older compatibility alias // this inline function is calling an API function AVSC_INLINE AVS_VideoFrame * avs_new_frame(AVS_ScriptEnvironment * env, const AVS_VideoInfo * vi) {return avs_new_video_frame_a(env,vi,AVS_FRAME_ALIGN);} #endif // end of inline helper functions AVSC_API(int, avs_make_writable)(AVS_ScriptEnvironment *, AVS_VideoFrame * * pvf); // V9 AVSC_API(int, avs_make_property_writable)(AVS_ScriptEnvironment*, AVS_VideoFrame** pvf); AVSC_API(void, avs_bit_blt)(AVS_ScriptEnvironment *, BYTE* dstp, int dst_pitch, const BYTE* srcp, int src_pitch, int row_size, int height); typedef void (AVSC_CC *AVS_ShutdownFunc)(void* user_data, AVS_ScriptEnvironment * env); AVSC_API(void, avs_at_exit)(AVS_ScriptEnvironment *, AVS_ShutdownFunc function, void * user_data); AVSC_API(AVS_VideoFrame *, avs_subframe)(AVS_ScriptEnvironment *, AVS_VideoFrame * src, int rel_offset, int new_pitch, int new_row_size, int new_height); // The returned video frame must be be released AVSC_API(AVS_VideoFrame*, avs_subframe_planar)(AVS_ScriptEnvironment*, AVS_VideoFrame* src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV); // The returned video frame must be be released // see also avs_subframe_planar_a in interface V8 AVSC_API(int, avs_set_memory_max)(AVS_ScriptEnvironment *, int mem); AVSC_API(int, avs_set_working_dir)(AVS_ScriptEnvironment *, const char * newdir); // avisynth.dll exports this; it's a way to use it as a library, without // writing an AVS script or without going through AVIFile. AVSC_API(AVS_ScriptEnvironment *, avs_create_script_environment)(int version); // this symbol is the entry point for the plugin and must // be defined AVSC_EXPORT const char * AVSC_CC avisynth_c_plugin_init(AVS_ScriptEnvironment* env); AVSC_API(void, avs_delete_script_environment)(AVS_ScriptEnvironment *); /////////////////////////////////////////////////////////////////////////////// // // Avisynth+ V8 interface elements // AVSC_API(AVS_VideoFrame*, avs_subframe_planar_a)(AVS_ScriptEnvironment*, AVS_VideoFrame* src, int rel_offset, int new_pitch, int new_row_size, int new_height, int rel_offsetU, int rel_offsetV, int new_pitchUV, int rel_offsetA); // The returned video frame must be be released AVSC_API(void, avs_copy_frame_props)(AVS_ScriptEnvironment* p, const AVS_VideoFrame* src, AVS_VideoFrame* dst); AVSC_API(const AVS_Map*, avs_get_frame_props_ro)(AVS_ScriptEnvironment* p, const AVS_VideoFrame* frame); AVSC_API(AVS_Map*, avs_get_frame_props_rw)(AVS_ScriptEnvironment* p, AVS_VideoFrame* frame); AVSC_API(int, avs_prop_num_keys)(AVS_ScriptEnvironment* p, const AVS_Map* map); AVSC_API(const char*, avs_prop_get_key)(AVS_ScriptEnvironment* p, const AVS_Map* map, int index); AVSC_API(int, avs_prop_num_elements)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key); // see AVS_PROPTYPE_... enums AVSC_API(char, avs_prop_get_type)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key); // see AVS_GETPROPERROR_... enums AVSC_API(int64_t, avs_prop_get_int)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(double, avs_prop_get_float)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); // Note: avs_prop_get_data was fixed in interface V9.1 AVSC_API(const char*, avs_prop_get_data)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(int, avs_prop_get_data_size)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(AVS_Clip*, avs_prop_get_clip)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(const AVS_VideoFrame*, avs_prop_get_frame)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int index, int* error); AVSC_API(int, avs_prop_delete_key)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key); // see AVS_PROPAPPENDMODE_... enums AVSC_API(int, avs_prop_set_int)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, int64_t i, int append); AVSC_API(int, avs_prop_set_float)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, double d, int append); AVSC_API(int, avs_prop_set_data)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const char* d, int length, int append); AVSC_API(int, avs_prop_set_clip)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, AVS_Clip* clip, int append); AVSC_API(int, avs_prop_set_frame)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const AVS_VideoFrame* frame, int append); AVSC_API(const int64_t*, avs_prop_get_int_array)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int* error); AVSC_API(const double*, avs_prop_get_float_array)(AVS_ScriptEnvironment* p, const AVS_Map* map, const char* key, int* error); AVSC_API(int, avs_prop_set_int_array)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const int64_t* i, int size); AVSC_API(int, avs_prop_set_float_array)(AVS_ScriptEnvironment* p, AVS_Map* map, const char* key, const double* d, int size); AVSC_API(void, avs_clear_map)(AVS_ScriptEnvironment* p, AVS_Map* map); // with frame property source AVSC_API(AVS_VideoFrame*, avs_new_video_frame_p)(AVS_ScriptEnvironment*, const AVS_VideoInfo* vi, const AVS_VideoFrame* prop_src); // with frame property source AVSC_API(AVS_VideoFrame*, avs_new_video_frame_p_a)(AVS_ScriptEnvironment*, const AVS_VideoInfo* vi, const AVS_VideoFrame* prop_src, int align); // Generic query to ask for various system properties, see AVS_AEP_xxx enums AVSC_API(size_t, avs_get_env_property)(AVS_ScriptEnvironment*, int avs_aep_prop); // buffer pool, see AVS_ALLOCTYPE enums AVSC_API(void *, avs_pool_allocate)(AVS_ScriptEnvironment*, size_t nBytes, size_t alignment, int avs_alloc_type); AVSC_API(void, avs_pool_free)(AVS_ScriptEnvironment*, void *ptr); // Interface V8 // Returns TRUE (1) and the requested variable. If the method fails, returns 0 (FALSE) and does not touch 'val'. // The returned AVS_Value *val value must be be released with avs_release_value only on success // AVS_Value *val is not caller allocated AVSC_API(int, avs_get_var_try)(AVS_ScriptEnvironment*, const char* name, AVS_Value* val); // Interface V8 // Return the value of the requested variable. // If the variable was not found or had the wrong type, // return the supplied default value. AVSC_API(int, avs_get_var_bool)(AVS_ScriptEnvironment*, const char* name, int def); AVSC_API(int, avs_get_var_int)(AVS_ScriptEnvironment*, const char* name, int def); AVSC_API(double, avs_get_var_double)(AVS_ScriptEnvironment*, const char* name, double def); AVSC_API(const char*, avs_get_var_string)(AVS_ScriptEnvironment*, const char* name, const char* def); AVSC_API(int64_t, avs_get_var_long)(AVS_ScriptEnvironment*, const char* name, int64_t def); #if defined(AVS_WINDOWS) // The following stuff is only relevant for Windows DLL handling; Linux does it completely differently. #ifdef AVSC_NO_DECLSPEC // This part uses LoadLibrary and related functions to dynamically load Avisynth instead of declspec(dllimport) // When AVSC_NO_DECLSPEC is defined, you can use avs_load_library to populate API functions into a struct // AVSC_INLINE functions which call onto an API functions should be treated specially (todo) /* The following functions needs to have been declared, probably from windows.h void* malloc(size_t) void free(void*); HMODULE LoadLibraryA(const char*); void* GetProcAddress(HMODULE, const char*); FreeLibrary(HMODULE); */ typedef struct AVS_Library AVS_Library; #define AVSC_DECLARE_FUNC(name) name##_func name // AVSC_DECLARE_FUNC helps keeping naming convention: type is xxxxx_func, function name is xxxxx // e.g. "AVSC_DECLARE_FUNC(avs_add_function);" // is a shortcut for "avs_add_function_func avs_add_function;" // Note: AVSC_INLINE functions, which call into API, // are guarded by #ifndef AVSC_NO_DECLSPEC. // They should call the appropriate library-> API entry. struct AVS_Library { HMODULE handle; AVSC_DECLARE_FUNC(avs_add_function); AVSC_DECLARE_FUNC(avs_at_exit); AVSC_DECLARE_FUNC(avs_bit_blt); AVSC_DECLARE_FUNC(avs_check_version); AVSC_DECLARE_FUNC(avs_clip_get_error); AVSC_DECLARE_FUNC(avs_copy_clip); AVSC_DECLARE_FUNC(avs_copy_value); AVSC_DECLARE_FUNC(avs_copy_video_frame); AVSC_DECLARE_FUNC(avs_create_script_environment); AVSC_DECLARE_FUNC(avs_delete_script_environment); AVSC_DECLARE_FUNC(avs_function_exists); AVSC_DECLARE_FUNC(avs_get_audio); AVSC_DECLARE_FUNC(avs_get_cpu_flags); AVSC_DECLARE_FUNC(avs_get_frame); AVSC_DECLARE_FUNC(avs_get_parity); AVSC_DECLARE_FUNC(avs_get_var); AVSC_DECLARE_FUNC(avs_get_version); AVSC_DECLARE_FUNC(avs_get_video_info); AVSC_DECLARE_FUNC(avs_invoke); AVSC_DECLARE_FUNC(avs_make_writable); AVSC_DECLARE_FUNC(avs_new_c_filter); AVSC_DECLARE_FUNC(avs_new_video_frame_a); AVSC_DECLARE_FUNC(avs_release_clip); AVSC_DECLARE_FUNC(avs_release_value); AVSC_DECLARE_FUNC(avs_release_video_frame); AVSC_DECLARE_FUNC(avs_save_string); AVSC_DECLARE_FUNC(avs_set_cache_hints); AVSC_DECLARE_FUNC(avs_set_global_var); AVSC_DECLARE_FUNC(avs_set_memory_max); AVSC_DECLARE_FUNC(avs_set_to_clip); AVSC_DECLARE_FUNC(avs_set_var); AVSC_DECLARE_FUNC(avs_set_working_dir); AVSC_DECLARE_FUNC(avs_sprintf); AVSC_DECLARE_FUNC(avs_subframe); AVSC_DECLARE_FUNC(avs_subframe_planar); AVSC_DECLARE_FUNC(avs_take_clip); AVSC_DECLARE_FUNC(avs_vsprintf); AVSC_DECLARE_FUNC(avs_get_error); AVSC_DECLARE_FUNC(avs_is_yv24); AVSC_DECLARE_FUNC(avs_is_yv16); AVSC_DECLARE_FUNC(avs_is_yv12); AVSC_DECLARE_FUNC(avs_is_yv411); AVSC_DECLARE_FUNC(avs_is_y8); AVSC_DECLARE_FUNC(avs_is_color_space); AVSC_DECLARE_FUNC(avs_get_plane_width_subsampling); AVSC_DECLARE_FUNC(avs_get_plane_height_subsampling); AVSC_DECLARE_FUNC(avs_bits_per_pixel); AVSC_DECLARE_FUNC(avs_bytes_from_pixels); AVSC_DECLARE_FUNC(avs_row_size); AVSC_DECLARE_FUNC(avs_bmp_size); AVSC_DECLARE_FUNC(avs_get_pitch_p); AVSC_DECLARE_FUNC(avs_get_row_size_p); AVSC_DECLARE_FUNC(avs_get_height_p); AVSC_DECLARE_FUNC(avs_get_read_ptr_p); AVSC_DECLARE_FUNC(avs_is_writable); AVSC_DECLARE_FUNC(avs_get_write_ptr_p); // Avisynth+ specific // Note: these functions are simulated/use fallback to existing functions AVSC_DECLARE_FUNC(avs_is_rgb48); AVSC_DECLARE_FUNC(avs_is_rgb64); AVSC_DECLARE_FUNC(avs_is_yuv444p16); AVSC_DECLARE_FUNC(avs_is_yuv422p16); AVSC_DECLARE_FUNC(avs_is_yuv420p16); AVSC_DECLARE_FUNC(avs_is_y16); AVSC_DECLARE_FUNC(avs_is_yuv444ps); AVSC_DECLARE_FUNC(avs_is_yuv422ps); AVSC_DECLARE_FUNC(avs_is_yuv420ps); AVSC_DECLARE_FUNC(avs_is_y32); AVSC_DECLARE_FUNC(avs_is_444); AVSC_DECLARE_FUNC(avs_is_422); AVSC_DECLARE_FUNC(avs_is_420); AVSC_DECLARE_FUNC(avs_is_y); AVSC_DECLARE_FUNC(avs_is_yuva); AVSC_DECLARE_FUNC(avs_is_planar_rgb); AVSC_DECLARE_FUNC(avs_is_planar_rgba); AVSC_DECLARE_FUNC(avs_num_components); AVSC_DECLARE_FUNC(avs_component_size); AVSC_DECLARE_FUNC(avs_bits_per_component); /////////////////////////////////////////////////////////////////////////////// // Avisynth+ new interface elements from interface version 8 // avs_subframe_planar with alpha support AVSC_DECLARE_FUNC(avs_subframe_planar_a); // frame properties AVSC_DECLARE_FUNC(avs_copy_frame_props); AVSC_DECLARE_FUNC(avs_get_frame_props_ro); AVSC_DECLARE_FUNC(avs_get_frame_props_rw); AVSC_DECLARE_FUNC(avs_prop_num_keys); AVSC_DECLARE_FUNC(avs_prop_get_key); AVSC_DECLARE_FUNC(avs_prop_num_elements); AVSC_DECLARE_FUNC(avs_prop_get_type); AVSC_DECLARE_FUNC(avs_prop_get_int); AVSC_DECLARE_FUNC(avs_prop_get_float); AVSC_DECLARE_FUNC(avs_prop_get_data); AVSC_DECLARE_FUNC(avs_prop_get_data_size); AVSC_DECLARE_FUNC(avs_prop_get_clip); AVSC_DECLARE_FUNC(avs_prop_get_frame); AVSC_DECLARE_FUNC(avs_prop_delete_key); AVSC_DECLARE_FUNC(avs_prop_set_int); AVSC_DECLARE_FUNC(avs_prop_set_float); AVSC_DECLARE_FUNC(avs_prop_set_data); AVSC_DECLARE_FUNC(avs_prop_set_clip); AVSC_DECLARE_FUNC(avs_prop_set_frame); AVSC_DECLARE_FUNC(avs_prop_get_int_array); AVSC_DECLARE_FUNC(avs_prop_get_float_array); AVSC_DECLARE_FUNC(avs_prop_set_int_array); AVSC_DECLARE_FUNC(avs_prop_set_float_array); AVSC_DECLARE_FUNC(avs_clear_map); // NewVideoFrame with frame properties AVSC_DECLARE_FUNC(avs_new_video_frame_p); AVSC_DECLARE_FUNC(avs_new_video_frame_p_a); AVSC_DECLARE_FUNC(avs_get_env_property); AVSC_DECLARE_FUNC(avs_get_var_try); AVSC_DECLARE_FUNC(avs_get_var_bool); AVSC_DECLARE_FUNC(avs_get_var_int); AVSC_DECLARE_FUNC(avs_get_var_double); AVSC_DECLARE_FUNC(avs_get_var_string); AVSC_DECLARE_FUNC(avs_get_var_long); AVSC_DECLARE_FUNC(avs_pool_allocate); AVSC_DECLARE_FUNC(avs_pool_free); // V9 AVSC_DECLARE_FUNC(avs_is_property_writable); AVSC_DECLARE_FUNC(avs_make_property_writable); // V10 AVSC_DECLARE_FUNC(avs_video_frame_get_pixel_type); AVSC_DECLARE_FUNC(avs_video_frame_amend_pixel_type); // V10 AVSC_DECLARE_FUNC(avs_is_channel_mask_known); AVSC_DECLARE_FUNC(avs_set_channel_mask); AVSC_DECLARE_FUNC(avs_get_channel_mask); }; #undef AVSC_DECLARE_FUNC #ifdef AVS26_FALLBACK_SIMULATION // Helper functions for fallback simulation // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_is_xx_fallback_return_false(const AVS_VideoInfo * p) { return 0; } // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_num_components_fallback(const AVS_VideoInfo * p) { switch (p->pixel_type) { case AVS_CS_UNKNOWN: return 0; case AVS_CS_RAW32: case AVS_CS_Y8: return 1; case AVS_CS_BGR32: return 4; // not planar but return the count default: return 3; } } // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_component_size_fallback(const AVS_VideoInfo * p) { return 1; } // Avisynth+ extensions do not exist in classic Avisynth so they are simulated AVSC_INLINE int avs_bits_per_component_fallback(const AVS_VideoInfo * p) { return 8; } // End of helper functions for fallback simulation #endif // AVS26_FALLBACK_SIMULATION // avs_load_library() allocates an array for API procedure entries // reads and fills the entries with live procedure addresses. // AVSC_INLINE helpers which are calling into API procedures are not treated here (todo) AVSC_INLINE AVS_Library * avs_load_library() { AVS_Library *library = (AVS_Library *)malloc(sizeof(AVS_Library)); if (library == NULL) return NULL; library->handle = LoadLibraryA("avisynth"); if (library->handle == NULL) goto fail; #define __AVSC_STRINGIFY(x) #x #define AVSC_STRINGIFY(x) __AVSC_STRINGIFY(x) #define AVSC_LOAD_FUNC(name) {\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name));\ if (library->name == NULL)\ goto fail;\ } #ifdef AVS26_FALLBACK_SIMULATION // When an API function is not loadable, let's try a replacement // Missing Avisynth+ functions will be substituted with classic Avisynth compatible methods /* Avisynth+ When method is missing (classic Avisynth) avs_is_rgb48 constant false avs_is_rgb64 constant false avs_is_444 avs_is_yv24 avs_is_422 avs_is_yv16 avs_is_420 avs_is_yv12 avs_is_y avs_is_y8 avs_is_yuva constant false avs_is_planar_rgb constant false avs_is_planar_rgba constant false avs_num_components special: avs_num_components_fake Y8:1 RGB32:4 else 3 avs_component_size constant 1 (1 bytes/component) avs_bits_per_component constant 8 (8 bits/component) */ // try to load an alternative function #define AVSC_LOAD_FUNC_FALLBACK(name,name2) {\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name));\ if (library->name == NULL)\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name2));\ if (library->name == NULL)\ goto fail;\ } // try to assign a replacement function #define AVSC_LOAD_FUNC_FALLBACK_SIMULATED(name,name2) {\ library->name = (name##_func) GetProcAddress(library->handle, AVSC_STRINGIFY(name));\ if (library->name == NULL)\ library->name = name2;\ if (library->name == NULL)\ goto fail;\ } #endif // AVS26_FALLBACK_SIMULATION AVSC_LOAD_FUNC(avs_add_function); AVSC_LOAD_FUNC(avs_at_exit); AVSC_LOAD_FUNC(avs_bit_blt); AVSC_LOAD_FUNC(avs_check_version); AVSC_LOAD_FUNC(avs_clip_get_error); AVSC_LOAD_FUNC(avs_copy_clip); AVSC_LOAD_FUNC(avs_copy_value); AVSC_LOAD_FUNC(avs_copy_video_frame); AVSC_LOAD_FUNC(avs_create_script_environment); AVSC_LOAD_FUNC(avs_delete_script_environment); AVSC_LOAD_FUNC(avs_function_exists); AVSC_LOAD_FUNC(avs_get_audio); AVSC_LOAD_FUNC(avs_get_cpu_flags); AVSC_LOAD_FUNC(avs_get_frame); AVSC_LOAD_FUNC(avs_get_parity); AVSC_LOAD_FUNC(avs_get_var); AVSC_LOAD_FUNC(avs_get_version); AVSC_LOAD_FUNC(avs_get_video_info); AVSC_LOAD_FUNC(avs_invoke); AVSC_LOAD_FUNC(avs_make_writable); AVSC_LOAD_FUNC(avs_new_c_filter); AVSC_LOAD_FUNC(avs_new_video_frame_a); AVSC_LOAD_FUNC(avs_release_clip); AVSC_LOAD_FUNC(avs_release_value); AVSC_LOAD_FUNC(avs_release_video_frame); AVSC_LOAD_FUNC(avs_save_string); AVSC_LOAD_FUNC(avs_set_cache_hints); AVSC_LOAD_FUNC(avs_set_global_var); AVSC_LOAD_FUNC(avs_set_memory_max); AVSC_LOAD_FUNC(avs_set_to_clip); AVSC_LOAD_FUNC(avs_set_var); AVSC_LOAD_FUNC(avs_set_working_dir); AVSC_LOAD_FUNC(avs_sprintf); AVSC_LOAD_FUNC(avs_subframe); AVSC_LOAD_FUNC(avs_subframe_planar); AVSC_LOAD_FUNC(avs_take_clip); AVSC_LOAD_FUNC(avs_vsprintf); AVSC_LOAD_FUNC(avs_get_error); AVSC_LOAD_FUNC(avs_is_yv24); AVSC_LOAD_FUNC(avs_is_yv16); AVSC_LOAD_FUNC(avs_is_yv12); AVSC_LOAD_FUNC(avs_is_yv411); AVSC_LOAD_FUNC(avs_is_y8); AVSC_LOAD_FUNC(avs_is_color_space); AVSC_LOAD_FUNC(avs_get_plane_width_subsampling); AVSC_LOAD_FUNC(avs_get_plane_height_subsampling); AVSC_LOAD_FUNC(avs_bits_per_pixel); AVSC_LOAD_FUNC(avs_bytes_from_pixels); AVSC_LOAD_FUNC(avs_row_size); AVSC_LOAD_FUNC(avs_bmp_size); AVSC_LOAD_FUNC(avs_get_pitch_p); AVSC_LOAD_FUNC(avs_get_row_size_p); AVSC_LOAD_FUNC(avs_get_height_p); AVSC_LOAD_FUNC(avs_get_read_ptr_p); AVSC_LOAD_FUNC(avs_is_writable); AVSC_LOAD_FUNC(avs_get_write_ptr_p); // Avisynth+ specific #ifdef AVS26_FALLBACK_SIMULATION // replace with fallback fn when does not exist AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_rgb48, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_rgb64, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK(avs_is_444, avs_is_yv24); AVSC_LOAD_FUNC_FALLBACK(avs_is_422, avs_is_yv16); AVSC_LOAD_FUNC_FALLBACK(avs_is_420, avs_is_yv12); AVSC_LOAD_FUNC_FALLBACK(avs_is_y, avs_is_y8); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_yuva, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_planar_rgb, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_is_planar_rgba, avs_is_xx_fallback_return_false); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_num_components, avs_num_components_fallback); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_component_size, avs_component_size_fallback); AVSC_LOAD_FUNC_FALLBACK_SIMULATED(avs_bits_per_component, avs_bits_per_component_fallback); #else // Avisynth+ specific AVSC_LOAD_FUNC(avs_is_rgb48); AVSC_LOAD_FUNC(avs_is_rgb64); AVSC_LOAD_FUNC(avs_is_444); AVSC_LOAD_FUNC(avs_is_422); AVSC_LOAD_FUNC(avs_is_420); AVSC_LOAD_FUNC(avs_is_y); AVSC_LOAD_FUNC(avs_is_yuva); AVSC_LOAD_FUNC(avs_is_planar_rgb); AVSC_LOAD_FUNC(avs_is_planar_rgba); AVSC_LOAD_FUNC(avs_num_components); AVSC_LOAD_FUNC(avs_component_size); AVSC_LOAD_FUNC(avs_bits_per_component); #endif // Avisynth+ interface V8, no backward compatible simulation AVSC_LOAD_FUNC(avs_subframe_planar_a); // frame properties AVSC_LOAD_FUNC(avs_copy_frame_props); AVSC_LOAD_FUNC(avs_get_frame_props_ro); AVSC_LOAD_FUNC(avs_get_frame_props_rw); AVSC_LOAD_FUNC(avs_prop_num_keys); AVSC_LOAD_FUNC(avs_prop_get_key); AVSC_LOAD_FUNC(avs_prop_num_elements); AVSC_LOAD_FUNC(avs_prop_get_type); AVSC_LOAD_FUNC(avs_prop_get_int); AVSC_LOAD_FUNC(avs_prop_get_float); AVSC_LOAD_FUNC(avs_prop_get_data); AVSC_LOAD_FUNC(avs_prop_get_data_size); AVSC_LOAD_FUNC(avs_prop_get_clip); AVSC_LOAD_FUNC(avs_prop_get_frame); AVSC_LOAD_FUNC(avs_prop_delete_key); AVSC_LOAD_FUNC(avs_prop_set_int); AVSC_LOAD_FUNC(avs_prop_set_float); AVSC_LOAD_FUNC(avs_prop_set_data); AVSC_LOAD_FUNC(avs_prop_set_clip); AVSC_LOAD_FUNC(avs_prop_set_frame); AVSC_LOAD_FUNC(avs_prop_get_int_array); AVSC_LOAD_FUNC(avs_prop_get_float_array); AVSC_LOAD_FUNC(avs_prop_set_int_array); AVSC_LOAD_FUNC(avs_prop_set_float_array); AVSC_LOAD_FUNC(avs_clear_map); // NewVideoFrame with frame properties AVSC_LOAD_FUNC(avs_new_video_frame_p); AVSC_LOAD_FUNC(avs_new_video_frame_p_a); AVSC_LOAD_FUNC(avs_get_env_property); AVSC_LOAD_FUNC(avs_get_var_try); AVSC_LOAD_FUNC(avs_get_var_bool); AVSC_LOAD_FUNC(avs_get_var_int); AVSC_LOAD_FUNC(avs_get_var_double); AVSC_LOAD_FUNC(avs_get_var_string); AVSC_LOAD_FUNC(avs_get_var_long); AVSC_LOAD_FUNC(avs_pool_allocate); AVSC_LOAD_FUNC(avs_pool_free); // V9 AVSC_LOAD_FUNC(avs_make_property_writable); AVSC_LOAD_FUNC(avs_is_property_writable); // V10 AVSC_LOAD_FUNC(avs_video_frame_get_pixel_type); AVSC_LOAD_FUNC(avs_video_frame_amend_pixel_type); // V10 AVSC_LOAD_FUNC(avs_is_channel_mask_known); AVSC_LOAD_FUNC(avs_set_channel_mask); AVSC_LOAD_FUNC(avs_get_channel_mask); #undef __AVSC_STRINGIFY #undef AVSC_STRINGIFY #undef AVSC_LOAD_FUNC #undef AVSC_LOAD_FUNC_FALLBACK #undef AVSC_LOAD_FUNC_FALLBACK_SIMULATED return library; fail: free(library); return NULL; } AVSC_INLINE void avs_free_library(AVS_Library *library) { if (library == NULL) return; FreeLibrary(library->handle); free(library); } #endif #endif // AVS_WINDOWS #endif ================================================ FILE: thirdparty/64/include/avisynth/avs/alignment.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_ALIGNMENT_H #define AVS_ALIGNMENT_H // Functions and macros to help work with alignment requirements. // Tells if a number is a power of two. #define IS_POWER2(n) ((n) && !((n) & ((n) - 1))) // Tells if the pointer "ptr" is aligned to "align" bytes. #define IS_PTR_ALIGNED(ptr, align) (((uintptr_t)ptr & ((uintptr_t)(align-1))) == 0) // Rounds up the number "n" to the next greater multiple of "align" #define ALIGN_NUMBER(n, align) (((n) + (align)-1) & (~((align)-1))) // Rounds up the pointer address "ptr" to the next greater multiple of "align" #define ALIGN_POINTER(ptr, align) (((uintptr_t)(ptr) + (align)-1) & (~(uintptr_t)((align)-1))) #ifdef __cplusplus #include #include #include #include "config.h" #if defined(MSVC) && _MSC_VER<1400 // needed for VS2013, otherwise C++11 'alignas' works #define avs_alignas(x) __declspec(align(x)) #else // assumes C++11 support #define avs_alignas(x) alignas(x) #endif template static bool IsPtrAligned(T* ptr, size_t align) { assert(IS_POWER2(align)); return (bool)IS_PTR_ALIGNED(ptr, align); } template static T AlignNumber(T n, T align) { assert(IS_POWER2(align)); return ALIGN_NUMBER(n, align); } template static T* AlignPointer(T* ptr, size_t align) { assert(IS_POWER2(align)); return (T*)ALIGN_POINTER(ptr, align); } extern "C" { #else #include #endif // __cplusplus // Returns a new buffer that is at least the size "nbytes". // The buffer will be aligned to "align" bytes. // Returns NULL on error. On successful allocation, // the returned buffer must be freed using "avs_free". inline void* avs_malloc(size_t nbytes, size_t align) { if (!IS_POWER2(align)) return NULL; size_t offset = sizeof(void*) + align - 1; void *orig = malloc(nbytes + offset); if (orig == NULL) return NULL; void **aligned = (void**)(((uintptr_t)orig + (uintptr_t)offset) & (~(uintptr_t)(align-1))); aligned[-1] = orig; return aligned; } // Buffers allocated using "avs_malloc" must be freed // using "avs_free" instead of "free". inline void avs_free(void *ptr) { // Mirroring free()'s semantic requires us to accept NULLs if (ptr == NULL) return; free(((void**)ptr)[-1]); } #ifdef __cplusplus } // extern "C" // The point of these undef's is to force using the template functions // if we are in C++ mode. For C, the user can rely only on the macros. #undef IS_PTR_ALIGNED #undef ALIGN_NUMBER #undef ALIGN_POINTER #endif // __cplusplus #endif //AVS_ALIGNMENT_H ================================================ FILE: thirdparty/64/include/avisynth/avs/arch.h ================================================ #ifndef _AVS_ARCH_H_ #define _AVS_ARCH_H_ #define AVS_ARCH x86_64 // e.g. i386 #endif // _AVS_ARCH_H_ ================================================ FILE: thirdparty/64/include/avisynth/avs/capi.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_CAPI_H #define AVS_CAPI_H #include "config.h" #ifdef AVS_POSIX // this is also defined in avs/posix.h #ifndef AVS_HAIKU #define __declspec(x) #endif #endif #ifdef __cplusplus # define EXTERN_C extern "C" #else # define EXTERN_C #endif #ifdef AVS_WINDOWS #ifdef BUILDING_AVSCORE # if defined(GCC) && defined(X86_32) # define AVSC_CC # else // MSVC builds and 64-bit GCC # ifndef AVSC_USE_STDCALL # define AVSC_CC __cdecl # else # define AVSC_CC __stdcall # endif # endif #else // needed for programs that talk to AviSynth+ # ifndef AVSC_WIN32_GCC32 // see comment below # ifndef AVSC_USE_STDCALL # define AVSC_CC __cdecl # else # define AVSC_CC __stdcall # endif # else # define AVSC_CC # endif #endif # else # define AVSC_CC #endif // On 64-bit Windows, there's only one calling convention, // so there is no difference between MSVC and GCC. On 32-bit, // this isn't true. The convention that GCC needs to use to // even build AviSynth+ as 32-bit makes anything that uses // it incompatible with 32-bit MSVC builds of AviSynth+. // The AVSC_WIN32_GCC32 define is meant to provide a user // switchable way to make builds of FFmpeg to test 32-bit // GCC builds of AviSynth+ without having to screw around // with alternate headers, while still default to the usual // situation of using 32-bit MSVC builds of AviSynth+. // Hopefully, this situation will eventually be resolved // and a broadly compatible solution will arise so the // same 32-bit FFmpeg build can handle either MSVC or GCC // builds of AviSynth+. #define AVSC_INLINE static __inline #ifdef BUILDING_AVSCORE #ifdef AVS_WINDOWS # ifndef AVS_STATIC_LIB # define AVSC_EXPORT __declspec(dllexport) # else # define AVSC_EXPORT # endif # define AVSC_API(ret, name) EXTERN_C AVSC_EXPORT ret AVSC_CC name #else # define AVSC_EXPORT EXTERN_C # define AVSC_API(ret, name) EXTERN_C ret AVSC_CC name #endif #else # define AVSC_EXPORT EXTERN_C __declspec(dllexport) # ifndef AVS_STATIC_LIB # define AVSC_IMPORT __declspec(dllimport) # else # define AVSC_IMPORT # endif # ifndef AVSC_NO_DECLSPEC # define AVSC_API(ret, name) EXTERN_C AVSC_IMPORT ret AVSC_CC name # else # define AVSC_API(ret, name) typedef ret (AVSC_CC *name##_func) # endif #endif #endif //AVS_CAPI_H ================================================ FILE: thirdparty/64/include/avisynth/avs/config.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_CONFIG_H #define AVS_CONFIG_H // Undefine this to get cdecl calling convention #define AVSC_USE_STDCALL 1 // NOTE TO PLUGIN AUTHORS: // Because FRAME_ALIGN can be substantially higher than the alignment // a plugin actually needs, plugins should not use FRAME_ALIGN to check for // alignment. They should always request the exact alignment value they need. // This is to make sure that plugins work over the widest range of AviSynth // builds possible. #define FRAME_ALIGN 64 #if defined(_M_AMD64) || defined(__x86_64) # define X86_64 #elif defined(_M_IX86) || defined(__i386__) # define X86_32 // VS2017 introduced _M_ARM64 #elif defined(_M_ARM64) || defined(__aarch64__) # define ARM64 #elif defined(_M_ARM) || defined(__arm__) # define ARM32 #elif defined(__PPC64__) # define PPC64 #elif defined(_M_PPC) || defined(__PPC__) || defined(__POWERPC__) # define PPC32 #elif defined(__riscv) # define RISCV #elif defined(__sparc_v9__) # define SPARC #elif defined(__mips__) # define MIPS #else # error Unsupported CPU architecture. #endif // VC++ LLVM-Clang-cl MinGW-Gnu // MSVC x x // MSVC_PURE x // CLANG x // GCC x #if defined(__clang__) // Check clang first. clang-cl also defines __MSC_VER // We set MSVC because they are mostly compatible # define CLANG #if defined(_MSC_VER) # define MSVC # define AVS_FORCEINLINE __attribute__((always_inline)) #else # define AVS_FORCEINLINE __attribute__((always_inline)) inline #endif #elif defined(_MSC_VER) # define MSVC # define MSVC_PURE # define AVS_FORCEINLINE __forceinline #elif defined(__GNUC__) # define GCC # define AVS_FORCEINLINE __attribute__((always_inline)) inline #elif defined(__INTEL_COMPILER) || defined(__INTEL_LLVM_COMPILER) // Intel C++ Compilers with MSVC command line interface will not appear here rather at _MSC_VER # define AVS_FORCEINLINE inline # undef __forceinline # define __forceinline inline #else # error Unsupported compiler. # define AVS_FORCEINLINE inline # undef __forceinline # define __forceinline inline #endif #if defined(_WIN32) # define AVS_WINDOWS #elif defined(__linux__) # define AVS_LINUX # define AVS_POSIX #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) # define AVS_BSD # define AVS_POSIX #elif defined(__APPLE__) # define AVS_MACOS # define AVS_POSIX #elif defined(__HAIKU__) # define AVS_HAIKU # define AVS_POSIX #else # error Operating system unsupported. #endif // useful warnings disabler macros for supported compilers #if defined(_MSC_VER) #define DISABLE_WARNING_PUSH __pragma(warning( push )) #define DISABLE_WARNING_POP __pragma(warning( pop )) #define DISABLE_WARNING(warningNumber) __pragma(warning( disable : warningNumber )) #define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE DISABLE_WARNING(4101) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(4505) // other warnings you want to deactivate... #elif defined(__GNUC__) || defined(__clang__) #define DO_PRAGMA(X) _Pragma(#X) #define DISABLE_WARNING_PUSH DO_PRAGMA(GCC diagnostic push) #define DISABLE_WARNING_POP DO_PRAGMA(GCC diagnostic pop) #define DISABLE_WARNING(warningName) DO_PRAGMA(GCC diagnostic ignored #warningName) #define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE DISABLE_WARNING(-Wunused-variable) #define DISABLE_WARNING_UNREFERENCED_FUNCTION DISABLE_WARNING(-Wunused-function) // other warnings you want to deactivate... #else #define DISABLE_WARNING_PUSH #define DISABLE_WARNING_POP #define DISABLE_WARNING_UNREFERENCED_LOCAL_VARIABLE #define DISABLE_WARNING_UNREFERENCED_FUNCTION // other warnings you want to deactivate... #endif #if defined(AVS_WINDOWS) && defined(_USING_V110_SDK71_) // Windows XP does not have proper initialization for // thread local variables. // Use workaround instead __declspec(thread) #define XP_TLS #endif #ifndef MSVC // GCC and Clang can be used on big endian systems, MSVC can't. # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define AVS_ENDIANNESS "little" # elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ # define AVS_ENDIANNESS "big" # else # define AVS_ENDIANNESS "middle" # endif #else #define AVS_ENDIANNESS "little" #endif #endif //AVS_CONFIG_H ================================================ FILE: thirdparty/64/include/avisynth/avs/cpuid.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifndef AVSCORE_CPUID_H #define AVSCORE_CPUID_H // For GetCPUFlags. These are backwards-compatible with those in VirtualDub. // ending with SSE4_2 // For emulation see https://software.intel.com/en-us/articles/intel-software-development-emulator enum { /* oldest CPU to support extension */ CPUF_FORCE = 0x01, // N/A CPUF_FPU = 0x02, // 386/486DX CPUF_MMX = 0x04, // P55C, K6, PII CPUF_INTEGER_SSE = 0x08, // PIII, Athlon CPUF_SSE = 0x10, // PIII, Athlon XP/MP CPUF_SSE2 = 0x20, // PIV, K8 CPUF_3DNOW = 0x40, // K6-2 CPUF_3DNOW_EXT = 0x80, // Athlon CPUF_X86_64 = 0xA0, // Hammer (note: equiv. to 3DNow + SSE2, which // only Hammer will have anyway) CPUF_SSE3 = 0x100, // PIV+, K8 Venice CPUF_SSSE3 = 0x200, // Core 2 CPUF_SSE4 = 0x400, CPUF_SSE4_1 = 0x400, // Penryn, Wolfdale, Yorkfield CPUF_AVX = 0x800, // Sandy Bridge, Bulldozer CPUF_SSE4_2 = 0x1000, // Nehalem // AVS+ CPUF_AVX2 = 0x2000, // Haswell CPUF_FMA3 = 0x4000, CPUF_F16C = 0x8000, CPUF_MOVBE = 0x10000, // Big Endian move CPUF_POPCNT = 0x20000, CPUF_AES = 0x40000, CPUF_FMA4 = 0x80000, CPUF_AVX512F = 0x100000, // AVX-512 Foundation. CPUF_AVX512DQ = 0x200000, // AVX-512 DQ (Double/Quad granular) Instructions CPUF_AVX512PF = 0x400000, // AVX-512 Prefetch CPUF_AVX512ER = 0x800000, // AVX-512 Exponential and Reciprocal CPUF_AVX512CD = 0x1000000, // AVX-512 Conflict Detection CPUF_AVX512BW = 0x2000000, // AVX-512 BW (Byte/Word granular) Instructions CPUF_AVX512VL = 0x4000000, // AVX-512 VL (128/256 Vector Length) Extensions CPUF_AVX512IFMA = 0x8000000, // AVX-512 IFMA integer 52 bit CPUF_AVX512VBMI = 0x10000000,// AVX-512 VBMI }; #ifdef BUILDING_AVSCORE int GetCPUFlags(); void SetMaxCPU(int new_flags); #endif #endif // AVSCORE_CPUID_H ================================================ FILE: thirdparty/64/include/avisynth/avs/filesystem.h ================================================ #pragma once // Snippet copied from filesystem/README.md #if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include) #if __has_include() #define GHC_USE_STD_FS #include namespace fs = std::filesystem; #endif #endif #ifndef GHC_USE_STD_FS #include namespace fs = ghc::filesystem; #endif ================================================ FILE: thirdparty/64/include/avisynth/avs/minmax.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifndef AVSCORE_MINMAX_H #define AVSCORE_MINMAX_H template T min(T v1, T v2) { return v1 < v2 ? v1 : v2; } template T max(T v1, T v2) { return v1 > v2 ? v1 : v2; } template T clamp(T n, T min, T max) { n = n > max ? max : n; return n < min ? min : n; } #endif // AVSCORE_MINMAX_H ================================================ FILE: thirdparty/64/include/avisynth/avs/posix.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifdef AVS_POSIX #ifndef AVSCORE_POSIX_H #define AVSCORE_POSIX_H #ifdef __cplusplus #include #endif #include #include // Define these MSVC-extension used in Avisynth #define __single_inheritance // These things don't exist in Linux #if defined(AVS_HAIKU) #undef __declspec #endif #define __declspec(x) #define lstrlen strlen #define lstrcmp strcmp #define lstrcmpi strcasecmp #define _stricmp strcasecmp #define _strnicmp strncasecmp #define _strdup strdup #define SetCurrentDirectory(x) chdir(x) #define SetCurrentDirectoryW(x) chdir(x) #define GetCurrentDirectoryW(x) getcwd(x) #define _putenv putenv #define _alloca alloca // Borrowing some compatibility macros from AvxSynth, slightly modified #define UInt32x32To64(a, b) ((uint64_t)(((uint64_t)((uint32_t)(a))) * ((uint32_t)(b)))) #define Int64ShrlMod32(a, b) ((uint64_t)((uint64_t)(a) >> (b))) #define Int32x32To64(a, b) ((int64_t)(((int64_t)((long)(a))) * ((long)(b)))) #define InterlockedIncrement(x) __sync_add_and_fetch((x), 1) #define InterlockedDecrement(x) __sync_sub_and_fetch((x), 1) #define InterlockedExchangeAdd(x, v) __sync_add_and_fetch((x), (v)) #define MulDiv(nNumber, nNumerator, nDenominator) (int32_t) (((int64_t) (nNumber) * (int64_t) (nNumerator) + (int64_t) ((nDenominator)/2)) / (int64_t) (nDenominator)) #ifndef TRUE #define TRUE true #endif #ifndef FALSE #define FALSE false #endif #define S_FALSE (0x00000001) #define E_FAIL (0x80004005) #define FAILED(hr) ((hr) & 0x80000000) #define SUCCEEDED(hr) (!FAILED(hr)) // Statuses copied from comments in exception.cpp #define STATUS_GUARD_PAGE_VIOLATION 0x80000001 #define STATUS_DATATYPE_MISALIGNMENT 0x80000002 #define STATUS_BREAKPOINT 0x80000003 #define STATUS_SINGLE_STEP 0x80000004 #define STATUS_ACCESS_VIOLATION 0xc0000005 #define STATUS_IN_PAGE_ERROR 0xc0000006 #define STATUS_INVALID_HANDLE 0xc0000008 #define STATUS_NO_MEMORY 0xc0000017 #define STATUS_ILLEGAL_INSTRUCTION 0xc000001d #define STATUS_NONCONTINUABLE_EXCEPTION 0xc0000025 #define STATUS_INVALID_DISPOSITION 0xc0000026 #define STATUS_ARRAY_BOUNDS_EXCEEDED 0xc000008c #define STATUS_FLOAT_DENORMAL_OPERAND 0xc000008d #define STATUS_FLOAT_DIVIDE_BY_ZERO 0xc000008e #define STATUS_FLOAT_INEXACT_RESULT 0xc000008f #define STATUS_FLOAT_INVALID_OPERATION 0xc0000090 #define STATUS_FLOAT_OVERFLOW 0xc0000091 #define STATUS_FLOAT_STACK_CHECK 0xc0000092 #define STATUS_FLOAT_UNDERFLOW 0xc0000093 #define STATUS_INTEGER_DIVIDE_BY_ZERO 0xc0000094 #define STATUS_INTEGER_OVERFLOW 0xc0000095 #define STATUS_PRIVILEGED_INSTRUCTION 0xc0000096 #define STATUS_STACK_OVERFLOW 0xc00000fd // Calling convension #ifndef AVS_HAIKU #define __stdcall #define __cdecl #endif // PowerPC OS X is really niche these days, but this painless equivocation // of the function/macro names used in posix_get_available_memory() // is all it takes to let it work. The G5 was 64-bit, and if 10.5 Leopard // can run in native 64-bit, it probably uses the names in that block as-is. #ifdef AVS_MACOS #ifdef PPC32 #define vm_statistics64_data_t vm_statistics_data_t #define HOST_VM_INFO64_COUNT HOST_VM_INFO_COUNT #define HOST_VM_INFO64 HOST_VM_INFO #define host_statistics64 host_statistics #endif // PPC32 #endif // AVS_MACOS #endif // AVSCORE_POSIX_H #endif // AVS_POSIX ================================================ FILE: thirdparty/64/include/avisynth/avs/types.h ================================================ // Avisynth C Interface Version 0.20 // Copyright 2003 Kevin Atkinson // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // As a special exception, I give you permission to link to the // Avisynth C interface with independent modules that communicate with // the Avisynth C interface solely through the interfaces defined in // avisynth_c.h, regardless of the license terms of these independent // modules, and to copy and distribute the resulting combined work // under terms of your choice, provided that every copy of the // combined work is accompanied by a complete copy of the source code // of the Avisynth C interface and Avisynth itself (with the version // used to produce the combined work), being distributed under the // terms of the GNU General Public License plus this exception. An // independent module is a module which is not derived from or based // on Avisynth C Interface, such as 3rd-party filters, import and // export plugins, or graphical user interfaces. #ifndef AVS_TYPES_H #define AVS_TYPES_H // Define all types necessary for interfacing with avisynth.dll #include #include #ifdef __cplusplus #include #include #else #include #include #endif // Raster types used by VirtualDub & Avisynth typedef uint32_t Pixel32; typedef uint8_t BYTE; // Audio Sample information typedef float SFLOAT; #endif //AVS_TYPES_H ================================================ FILE: thirdparty/64/include/avisynth/avs/version.h ================================================ #ifndef _AVS_VERSION_H_ #define _AVS_VERSION_H_ #include "arch.h" #define AVS_PPSTR_(x) #x #define AVS_PPSTR(x) AVS_PPSTR_(x) #define AVS_PROJECT AviSynth+ #define AVS_MAJOR_VER 3 #define AVS_MINOR_VER 7 #define AVS_BUGFIX_VER 3 #ifdef RELEASE_TARBALL #define AVS_FULLVERSION AVS_PPSTR(AVS_PROJECT) " " AVS_PPSTR(AVS_MAJOR_VER) "." AVS_PPSTR(AVS_MINOR_VER) "." AVS_PPSTR(AVS_BUGFIX_VER) " (" AVS_PPSTR(AVS_ARCH) ")" #else #define AVS_DEVNEXT_REV #define AVS_DEV_REVDATE #define AVS_DEV_GITHASH #define AVS_SEQREV // e.g. 1576 #define AVS_BRANCH // e.g. master #define AVS_FULLVERSION AVS_PPSTR(AVS_PROJECT) " " AVS_PPSTR(AVS_MAJOR_VER) "." AVS_PPSTR(AVS_MINOR_VER) "." AVS_PPSTR(AVS_BUGFIX_VER) " (r" AVS_PPSTR(AVS_SEQREV) ", " AVS_PPSTR(AVS_BRANCH) ", " AVS_PPSTR(AVS_ARCH) ")" #endif #endif // _AVS_VERSION_H_ ================================================ FILE: thirdparty/64/include/avisynth/avs/win.h ================================================ // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA, or visit // http://www.gnu.org/copyleft/gpl.html . // // Linking Avisynth statically or dynamically with other modules is making a // combined work based on Avisynth. Thus, the terms and conditions of the GNU // General Public License cover the whole combination. // // As a special exception, the copyright holders of Avisynth give you // permission to link Avisynth with independent modules that communicate with // Avisynth solely through the interfaces defined in avisynth.h, regardless of the license // terms of these independent modules, and to copy and distribute the // resulting combined work under terms of your choice, provided that // every copy of the combined work is accompanied by a complete copy of // the source code of Avisynth (the version of Avisynth used to produce the // combined work), being distributed under the terms of the GNU General // Public License plus this exception. An independent module is a module // which is not derived from or based on Avisynth, such as 3rd-party filters, // import and export plugins, or graphical user interfaces. #ifndef AVSCORE_WIN_H #define AVSCORE_WIN_H // Whenever you need windows headers, start by including this file, then the rest. // WWUUT? We require XP now? #if !defined(NTDDI_VERSION) && !defined(_WIN32_WINNT) #define NTDDI_VERSION 0x05020000 #define _WIN32_WINNT 0x0502 #endif #define WIN32_LEAN_AND_MEAN #define STRICT #if !defined(NOMINMAX) #define NOMINMAX #endif #include // Provision for UTF-8 max 4 bytes per code point #define AVS_MAX_PATH MAX_PATH*4 #endif // AVSCORE_WIN_H ================================================ FILE: thirdparty/64/include/dav1d/common.h ================================================ /* * Copyright © 2018, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_COMMON_H #define DAV1D_COMMON_H #include #include #include #ifdef __cplusplus extern "C" { #endif #ifndef DAV1D_API #if defined _WIN32 #if defined DAV1D_BUILDING_DLL #define DAV1D_API __declspec(dllexport) #else #define DAV1D_API #endif #else #if __GNUC__ >= 4 #define DAV1D_API __attribute__ ((visibility ("default"))) #else #define DAV1D_API #endif #endif #endif #if EPERM > 0 #define DAV1D_ERR(e) (-(e)) ///< Negate POSIX error code. #else #define DAV1D_ERR(e) (e) #endif /** * A reference-counted object wrapper for a user-configurable pointer. */ typedef struct Dav1dUserData { const uint8_t *data; ///< data pointer struct Dav1dRef *ref; ///< allocation origin } Dav1dUserData; /** * Input packet metadata which are copied from the input data used to * decode each image into the matching structure of the output image * returned back to the user. Since these are metadata fields, they * can be used for other purposes than the documented ones, they will * still be passed from input data to output picture without being * used internally. */ typedef struct Dav1dDataProps { int64_t timestamp; ///< container timestamp of input data, INT64_MIN if unknown (default) int64_t duration; ///< container duration of input data, 0 if unknown (default) int64_t offset; ///< stream offset of input data, -1 if unknown (default) size_t size; ///< packet size, default Dav1dData.sz struct Dav1dUserData user_data; ///< user-configurable data, default NULL members } Dav1dDataProps; /** * Release reference to a Dav1dDataProps. */ DAV1D_API void dav1d_data_props_unref(Dav1dDataProps *props); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_COMMON_H */ ================================================ FILE: thirdparty/64/include/dav1d/data.h ================================================ /* * Copyright © 2018, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_DATA_H #define DAV1D_DATA_H #include #include #include "common.h" #ifdef __cplusplus extern "C" { #endif typedef struct Dav1dData { const uint8_t *data; ///< data pointer size_t sz; ///< data size struct Dav1dRef *ref; ///< allocation origin Dav1dDataProps m; ///< user provided metadata passed to the output picture } Dav1dData; /** * Allocate data. * * @param data Input context. * @param sz Size of the data that should be allocated. * * @return Pointer to the allocated buffer on success. NULL on error. */ DAV1D_API uint8_t * dav1d_data_create(Dav1dData *data, size_t sz); /** * Wrap an existing data array. * * @param data Input context. * @param buf The data to be wrapped. * @param sz Size of the data. * @param free_callback Function to be called when we release our last * reference to this data. In this callback, $buf will be * the $buf argument to this function, and $cookie will * be the $cookie input argument to this function. * @param cookie Opaque parameter passed to free_callback(). * * @return 0 on success. A negative DAV1D_ERR value on error. */ DAV1D_API int dav1d_data_wrap(Dav1dData *data, const uint8_t *buf, size_t sz, void (*free_callback)(const uint8_t *buf, void *cookie), void *cookie); /** * Wrap a user-provided data pointer into a reference counted object. * * data->m.user_data field will initialized to wrap the provided $user_data * pointer. * * $free_callback will be called on the same thread that released the last * reference. If frame threading is used, make sure $free_callback is * thread-safe. * * @param data Input context. * @param user_data The user data to be wrapped. * @param free_callback Function to be called when we release our last * reference to this data. In this callback, $user_data * will be the $user_data argument to this function, and * $cookie will be the $cookie input argument to this * function. * @param cookie Opaque parameter passed to $free_callback. * * @return 0 on success. A negative DAV1D_ERR value on error. */ DAV1D_API int dav1d_data_wrap_user_data(Dav1dData *data, const uint8_t *user_data, void (*free_callback)(const uint8_t *user_data, void *cookie), void *cookie); /** * Free the data reference. * * The reference count for data->m.user_data will be decremented (if it has been * initialized with dav1d_data_wrap_user_data). The $data object will be memset * to 0. * * @param data Input context. */ DAV1D_API void dav1d_data_unref(Dav1dData *data); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_DATA_H */ ================================================ FILE: thirdparty/64/include/dav1d/dav1d.h ================================================ /* * Copyright © 2018-2021, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_H #define DAV1D_H #include #include #include "common.h" #include "picture.h" #include "data.h" #include "version.h" #ifdef __cplusplus extern "C" { #endif typedef struct Dav1dContext Dav1dContext; typedef struct Dav1dRef Dav1dRef; #define DAV1D_MAX_THREADS 256 #define DAV1D_MAX_FRAME_DELAY 256 typedef struct Dav1dLogger { void *cookie; ///< Custom data to pass to the callback. /** * Logger callback. May be NULL to disable logging. * * @param cookie Custom pointer passed to all calls. * @param format The vprintf compatible format string. * @param ap List of arguments referenced by the format string. */ void (*callback)(void *cookie, const char *format, va_list ap); } Dav1dLogger; enum Dav1dInloopFilterType { DAV1D_INLOOPFILTER_NONE = 0, DAV1D_INLOOPFILTER_DEBLOCK = 1 << 0, DAV1D_INLOOPFILTER_CDEF = 1 << 1, DAV1D_INLOOPFILTER_RESTORATION = 1 << 2, DAV1D_INLOOPFILTER_ALL = DAV1D_INLOOPFILTER_DEBLOCK | DAV1D_INLOOPFILTER_CDEF | DAV1D_INLOOPFILTER_RESTORATION, }; enum Dav1dDecodeFrameType { DAV1D_DECODEFRAMETYPE_ALL = 0, ///< decode and return all frames DAV1D_DECODEFRAMETYPE_REFERENCE = 1,///< decode and return frames referenced by other frames only DAV1D_DECODEFRAMETYPE_INTRA = 2, ///< decode and return intra frames only (includes keyframes) DAV1D_DECODEFRAMETYPE_KEY = 3, ///< decode and return keyframes only }; typedef struct Dav1dSettings { int n_threads; ///< number of threads (0 = number of logical cores in host system, default 0) int max_frame_delay; ///< Set to 1 for low-latency decoding (0 = ceil(sqrt(n_threads)), default 0) int apply_grain; ///< whether to apply film grain on output frames (default 1) int operating_point; ///< select an operating point for scalable AV1 bitstreams (0 - 31, default 0) int all_layers; ///< output all spatial layers of a scalable AV1 biststream (default 1) unsigned frame_size_limit; ///< maximum frame size, in pixels (0 = unlimited, default 0) Dav1dPicAllocator allocator; ///< Picture allocator callback. Dav1dLogger logger; ///< Logger callback. int strict_std_compliance; ///< whether to abort decoding on standard compliance violations ///< that don't affect actual bitstream decoding (e.g. inconsistent ///< or invalid metadata, default 0) int output_invisible_frames; ///< output invisibly coded frames (in coding order) in addition ///< to all visible frames. Because of show-existing-frame, this ///< means some frames may appear twice (once when coded, ///< once when shown, default 0) enum Dav1dInloopFilterType inloop_filters; ///< postfilters to enable during decoding (default ///< DAV1D_INLOOPFILTER_ALL) enum Dav1dDecodeFrameType decode_frame_type; ///< frame types to decode (default ///< DAV1D_DECODEFRAMETYPE_ALL) uint8_t reserved[16]; ///< reserved for future use } Dav1dSettings; /** * Get library version. */ DAV1D_API const char *dav1d_version(void); /** * Get library API version. * * @return A value in the format 0x00XXYYZZ, where XX is the major version, * YY the minor version, and ZZ the patch version. * @see DAV1D_API_MAJOR, DAV1D_API_MINOR, DAV1D_API_PATCH */ DAV1D_API unsigned dav1d_version_api(void); /** * Initialize settings to default values. * * @param s Input settings context. */ DAV1D_API void dav1d_default_settings(Dav1dSettings *s); /** * Allocate and open a decoder instance. * * @param c_out The decoder instance to open. *c_out will be set to the * allocated context. * @param s Input settings context. * * @note The context must be freed using dav1d_close() when decoding is * finished. * * @return 0 on success, or < 0 (a negative DAV1D_ERR code) on error. */ DAV1D_API int dav1d_open(Dav1dContext **c_out, const Dav1dSettings *s); /** * Parse a Sequence Header OBU from bitstream data. * * @param out Output Sequence Header. * @param buf The data to be parser. * @param sz Size of the data. * * @return * 0: Success, and out is filled with the parsed Sequence Header * OBU parameters. * DAV1D_ERR(ENOENT): No Sequence Header OBUs were found in the buffer. * Other negative DAV1D_ERR codes: Invalid data in the buffer, invalid passed-in * arguments, and other errors during parsing. * * @note It is safe to feed this function data containing other OBUs than a * Sequence Header, as they will simply be ignored. If there is more than * one Sequence Header OBU present, only the last will be returned. */ DAV1D_API int dav1d_parse_sequence_header(Dav1dSequenceHeader *out, const uint8_t *buf, const size_t sz); /** * Feed bitstream data to the decoder, in the form of one or multiple AV1 * Open Bitstream Units (OBUs). * * @param c Input decoder instance. * @param in Input bitstream data. On success, ownership of the reference is * passed to the library. * * @return * 0: Success, and the data was consumed. * DAV1D_ERR(EAGAIN): The data can't be consumed. dav1d_get_picture() should * be called to get one or more frames before the function * can consume new data. * Other negative DAV1D_ERR codes: Error during decoding or because of invalid * passed-in arguments. The reference remains * owned by the caller. */ DAV1D_API int dav1d_send_data(Dav1dContext *c, Dav1dData *in); /** * Return a decoded picture. * * @param c Input decoder instance. * @param out Output frame. The caller assumes ownership of the returned * reference. * * @return * 0: Success, and a frame is returned. * DAV1D_ERR(EAGAIN): Not enough data to output a frame. dav1d_send_data() * should be called with new input. * Other negative DAV1D_ERR codes: Error during decoding or because of invalid * passed-in arguments. * * @note To drain buffered frames from the decoder (i.e. on end of stream), * call this function until it returns DAV1D_ERR(EAGAIN). * * @code{.c} * Dav1dData data = { 0 }; * Dav1dPicture p = { 0 }; * int res; * * read_data(&data); * do { * res = dav1d_send_data(c, &data); * // Keep going even if the function can't consume the current data * packet. It eventually will after one or more frames have been * returned in this loop. * if (res < 0 && res != DAV1D_ERR(EAGAIN)) * free_and_abort(); * res = dav1d_get_picture(c, &p); * if (res < 0) { * if (res != DAV1D_ERR(EAGAIN)) * free_and_abort(); * } else * output_and_unref_picture(&p); * // Stay in the loop as long as there's data to consume. * } while (data.sz || read_data(&data) == SUCCESS); * * // Handle EOS by draining all buffered frames. * do { * res = dav1d_get_picture(c, &p); * if (res < 0) { * if (res != DAV1D_ERR(EAGAIN)) * free_and_abort(); * } else * output_and_unref_picture(&p); * } while (res == 0); * @endcode */ DAV1D_API int dav1d_get_picture(Dav1dContext *c, Dav1dPicture *out); /** * Apply film grain to a previously decoded picture. If the picture contains no * film grain metadata, then this function merely returns a new reference. * * @param c Input decoder instance. * @param out Output frame. The caller assumes ownership of the returned * reference. * @param in Input frame. No ownership is transferred. * * @return * 0: Success, and a frame is returned. * Other negative DAV1D_ERR codes: Error due to lack of memory or because of * invalid passed-in arguments. * * @note If `Dav1dSettings.apply_grain` is true, film grain was already applied * by `dav1d_get_picture`, and so calling this function leads to double * application of film grain. Users should only call this when needed. */ DAV1D_API int dav1d_apply_grain(Dav1dContext *c, Dav1dPicture *out, const Dav1dPicture *in); /** * Close a decoder instance and free all associated memory. * * @param c_out The decoder instance to close. *c_out will be set to NULL. */ DAV1D_API void dav1d_close(Dav1dContext **c_out); /** * Flush all delayed frames in decoder and clear internal decoder state, * to be used when seeking. * * @param c Input decoder instance. * * @note Decoding will start only after a valid sequence header OBU is * delivered to dav1d_send_data(). * */ DAV1D_API void dav1d_flush(Dav1dContext *c); enum Dav1dEventFlags { /** * The last returned picture contains a reference to a new Sequence Header, * either because it's the start of a new coded sequence, or the decoder was * flushed before it was generated. */ DAV1D_EVENT_FLAG_NEW_SEQUENCE = 1 << 0, /** * The last returned picture contains a reference to a Sequence Header with * new operating parameters information for the current coded sequence. */ DAV1D_EVENT_FLAG_NEW_OP_PARAMS_INFO = 1 << 1, }; /** * Fetch a combination of DAV1D_EVENT_FLAG_* event flags generated by the decoding * process. * * @param c Input decoder instance. * @param flags Where to write the flags. * * @return 0 on success, or < 0 (a negative DAV1D_ERR code) on error. * * @note Calling this function will clear all the event flags currently stored in * the decoder. * */ DAV1D_API int dav1d_get_event_flags(Dav1dContext *c, enum Dav1dEventFlags *flags); /** * Retrieve the user-provided metadata associated with the input data packet * for the last decoding error reported to the user, i.e. a negative return * value (not EAGAIN) from dav1d_send_data() or dav1d_get_picture(). * * @param c Input decoder instance. * @param out Output Dav1dDataProps. On success, the caller assumes ownership of * the returned reference. * * @return 0 on success, or < 0 (a negative DAV1D_ERR code) on error. */ DAV1D_API int dav1d_get_decode_error_data_props(Dav1dContext *c, Dav1dDataProps *out); /** * Get the decoder delay, which is the number of internally buffered frames, not * including reference frames. * This value is guaranteed to be >= 1 and <= max_frame_delay. * * @param s Input settings context. * * @return Decoder frame delay on success, or < 0 (a negative DAV1D_ERR code) on * error. * * @note The returned delay is valid only for a Dav1dContext initialized with the * provided Dav1dSettings. */ DAV1D_API int dav1d_get_frame_delay(const Dav1dSettings *s); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_H */ ================================================ FILE: thirdparty/64/include/dav1d/headers.h ================================================ /* * Copyright © 2018-2020, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_HEADERS_H #define DAV1D_HEADERS_H #include #include #ifdef __cplusplus extern "C" { #endif // Constants from Section 3. "Symbols and abbreviated terms" #define DAV1D_MAX_CDEF_STRENGTHS 8 #define DAV1D_MAX_OPERATING_POINTS 32 #define DAV1D_MAX_TILE_COLS 64 #define DAV1D_MAX_TILE_ROWS 64 #define DAV1D_MAX_SEGMENTS 8 #define DAV1D_NUM_REF_FRAMES 8 #define DAV1D_PRIMARY_REF_NONE 7 #define DAV1D_REFS_PER_FRAME 7 #define DAV1D_TOTAL_REFS_PER_FRAME (DAV1D_REFS_PER_FRAME + 1) enum Dav1dObuType { DAV1D_OBU_SEQ_HDR = 1, DAV1D_OBU_TD = 2, DAV1D_OBU_FRAME_HDR = 3, DAV1D_OBU_TILE_GRP = 4, DAV1D_OBU_METADATA = 5, DAV1D_OBU_FRAME = 6, DAV1D_OBU_REDUNDANT_FRAME_HDR = 7, DAV1D_OBU_PADDING = 15, }; enum Dav1dTxfmMode { DAV1D_TX_4X4_ONLY, DAV1D_TX_LARGEST, DAV1D_TX_SWITCHABLE, DAV1D_N_TX_MODES, }; enum Dav1dFilterMode { DAV1D_FILTER_8TAP_REGULAR, DAV1D_FILTER_8TAP_SMOOTH, DAV1D_FILTER_8TAP_SHARP, DAV1D_N_SWITCHABLE_FILTERS, DAV1D_FILTER_BILINEAR = DAV1D_N_SWITCHABLE_FILTERS, DAV1D_N_FILTERS, DAV1D_FILTER_SWITCHABLE = DAV1D_N_FILTERS, }; enum Dav1dAdaptiveBoolean { DAV1D_OFF = 0, DAV1D_ON = 1, DAV1D_ADAPTIVE = 2, }; enum Dav1dRestorationType { DAV1D_RESTORATION_NONE, DAV1D_RESTORATION_SWITCHABLE, DAV1D_RESTORATION_WIENER, DAV1D_RESTORATION_SGRPROJ, }; enum Dav1dWarpedMotionType { DAV1D_WM_TYPE_IDENTITY, DAV1D_WM_TYPE_TRANSLATION, DAV1D_WM_TYPE_ROT_ZOOM, DAV1D_WM_TYPE_AFFINE, }; typedef struct Dav1dWarpedMotionParams { enum Dav1dWarpedMotionType type; int32_t matrix[6]; union { struct { int16_t alpha, beta, gamma, delta; } p; int16_t abcd[4]; } u; } Dav1dWarpedMotionParams; enum Dav1dPixelLayout { DAV1D_PIXEL_LAYOUT_I400, ///< monochrome DAV1D_PIXEL_LAYOUT_I420, ///< 4:2:0 planar DAV1D_PIXEL_LAYOUT_I422, ///< 4:2:2 planar DAV1D_PIXEL_LAYOUT_I444, ///< 4:4:4 planar }; enum Dav1dFrameType { DAV1D_FRAME_TYPE_KEY = 0, ///< Key Intra frame DAV1D_FRAME_TYPE_INTER = 1, ///< Inter frame DAV1D_FRAME_TYPE_INTRA = 2, ///< Non key Intra frame DAV1D_FRAME_TYPE_SWITCH = 3, ///< Switch Inter frame }; enum Dav1dColorPrimaries { DAV1D_COLOR_PRI_BT709 = 1, DAV1D_COLOR_PRI_UNKNOWN = 2, DAV1D_COLOR_PRI_BT470M = 4, DAV1D_COLOR_PRI_BT470BG = 5, DAV1D_COLOR_PRI_BT601 = 6, DAV1D_COLOR_PRI_SMPTE240 = 7, DAV1D_COLOR_PRI_FILM = 8, DAV1D_COLOR_PRI_BT2020 = 9, DAV1D_COLOR_PRI_XYZ = 10, DAV1D_COLOR_PRI_SMPTE431 = 11, DAV1D_COLOR_PRI_SMPTE432 = 12, DAV1D_COLOR_PRI_EBU3213 = 22, DAV1D_COLOR_PRI_RESERVED = 255, }; enum Dav1dTransferCharacteristics { DAV1D_TRC_BT709 = 1, DAV1D_TRC_UNKNOWN = 2, DAV1D_TRC_BT470M = 4, DAV1D_TRC_BT470BG = 5, DAV1D_TRC_BT601 = 6, DAV1D_TRC_SMPTE240 = 7, DAV1D_TRC_LINEAR = 8, DAV1D_TRC_LOG100 = 9, ///< logarithmic (100:1 range) DAV1D_TRC_LOG100_SQRT10 = 10, ///< lograithmic (100*sqrt(10):1 range) DAV1D_TRC_IEC61966 = 11, DAV1D_TRC_BT1361 = 12, DAV1D_TRC_SRGB = 13, DAV1D_TRC_BT2020_10BIT = 14, DAV1D_TRC_BT2020_12BIT = 15, DAV1D_TRC_SMPTE2084 = 16, ///< PQ DAV1D_TRC_SMPTE428 = 17, DAV1D_TRC_HLG = 18, ///< hybrid log/gamma (BT.2100 / ARIB STD-B67) DAV1D_TRC_RESERVED = 255, }; enum Dav1dMatrixCoefficients { DAV1D_MC_IDENTITY = 0, DAV1D_MC_BT709 = 1, DAV1D_MC_UNKNOWN = 2, DAV1D_MC_FCC = 4, DAV1D_MC_BT470BG = 5, DAV1D_MC_BT601 = 6, DAV1D_MC_SMPTE240 = 7, DAV1D_MC_SMPTE_YCGCO = 8, DAV1D_MC_BT2020_NCL = 9, DAV1D_MC_BT2020_CL = 10, DAV1D_MC_SMPTE2085 = 11, DAV1D_MC_CHROMAT_NCL = 12, ///< Chromaticity-derived DAV1D_MC_CHROMAT_CL = 13, DAV1D_MC_ICTCP = 14, DAV1D_MC_RESERVED = 255, }; enum Dav1dChromaSamplePosition { DAV1D_CHR_UNKNOWN = 0, DAV1D_CHR_VERTICAL = 1, ///< Horizontally co-located with luma(0, 0) ///< sample, between two vertical samples DAV1D_CHR_COLOCATED = 2, ///< Co-located with luma(0, 0) sample }; typedef struct Dav1dContentLightLevel { uint16_t max_content_light_level; uint16_t max_frame_average_light_level; } Dav1dContentLightLevel; typedef struct Dav1dMasteringDisplay { uint16_t primaries[3][2]; ///< 0.16 fixed point uint16_t white_point[2]; ///< 0.16 fixed point uint32_t max_luminance; ///< 24.8 fixed point uint32_t min_luminance; ///< 18.14 fixed point } Dav1dMasteringDisplay; typedef struct Dav1dITUTT35 { uint8_t country_code; uint8_t country_code_extension_byte; size_t payload_size; uint8_t *payload; } Dav1dITUTT35; typedef struct Dav1dSequenceHeader { /** * Stream profile, 0 for 8-10 bits/component 4:2:0 or monochrome; * 1 for 8-10 bits/component 4:4:4; 2 for 4:2:2 at any bits/component, * or 12 bits/component at any chroma subsampling. */ uint8_t profile; /** * Maximum dimensions for this stream. In non-scalable streams, these * are often the actual dimensions of the stream, although that is not * a normative requirement. */ int max_width, max_height; enum Dav1dPixelLayout layout; ///< format of the picture enum Dav1dColorPrimaries pri; ///< color primaries (av1) enum Dav1dTransferCharacteristics trc; ///< transfer characteristics (av1) enum Dav1dMatrixCoefficients mtrx; ///< matrix coefficients (av1) enum Dav1dChromaSamplePosition chr; ///< chroma sample position (av1) /** * 0, 1 and 2 mean 8, 10 or 12 bits/component, respectively. This is not * exactly the same as 'hbd' from the spec; the spec's hbd distinguishes * between 8 (0) and 10-12 (1) bits/component, and another element * (twelve_bit) to distinguish between 10 and 12 bits/component. To get * the spec's hbd, use !!our_hbd, and to get twelve_bit, use hbd == 2. */ uint8_t hbd; /** * Pixel data uses JPEG pixel range ([0,255] for 8bits) instead of * MPEG pixel range ([16,235] for 8bits luma, [16,240] for 8bits chroma). */ uint8_t color_range; uint8_t num_operating_points; struct Dav1dSequenceHeaderOperatingPoint { uint8_t major_level, minor_level; uint8_t initial_display_delay; uint16_t idc; uint8_t tier; uint8_t decoder_model_param_present; uint8_t display_model_param_present; } operating_points[DAV1D_MAX_OPERATING_POINTS]; uint8_t still_picture; uint8_t reduced_still_picture_header; uint8_t timing_info_present; uint32_t num_units_in_tick; uint32_t time_scale; uint8_t equal_picture_interval; uint32_t num_ticks_per_picture; uint8_t decoder_model_info_present; uint8_t encoder_decoder_buffer_delay_length; uint32_t num_units_in_decoding_tick; uint8_t buffer_removal_delay_length; uint8_t frame_presentation_delay_length; uint8_t display_model_info_present; uint8_t width_n_bits, height_n_bits; uint8_t frame_id_numbers_present; uint8_t delta_frame_id_n_bits; uint8_t frame_id_n_bits; uint8_t sb128; uint8_t filter_intra; uint8_t intra_edge_filter; uint8_t inter_intra; uint8_t masked_compound; uint8_t warped_motion; uint8_t dual_filter; uint8_t order_hint; uint8_t jnt_comp; uint8_t ref_frame_mvs; enum Dav1dAdaptiveBoolean screen_content_tools; enum Dav1dAdaptiveBoolean force_integer_mv; uint8_t order_hint_n_bits; uint8_t super_res; uint8_t cdef; uint8_t restoration; uint8_t ss_hor, ss_ver, monochrome; uint8_t color_description_present; uint8_t separate_uv_delta_q; uint8_t film_grain_present; // Dav1dSequenceHeaders of the same sequence are required to be // bit-identical until this offset. See 7.5 "Ordering of OBUs": // Within a particular coded video sequence, the contents of // sequence_header_obu must be bit-identical each time the // sequence header appears except for the contents of // operating_parameters_info. struct Dav1dSequenceHeaderOperatingParameterInfo { uint32_t decoder_buffer_delay; uint32_t encoder_buffer_delay; uint8_t low_delay_mode; } operating_parameter_info[DAV1D_MAX_OPERATING_POINTS]; } Dav1dSequenceHeader; typedef struct Dav1dSegmentationData { int16_t delta_q; int8_t delta_lf_y_v, delta_lf_y_h, delta_lf_u, delta_lf_v; int8_t ref; uint8_t skip; uint8_t globalmv; } Dav1dSegmentationData; typedef struct Dav1dSegmentationDataSet { Dav1dSegmentationData d[DAV1D_MAX_SEGMENTS]; uint8_t preskip; int8_t last_active_segid; } Dav1dSegmentationDataSet; typedef struct Dav1dLoopfilterModeRefDeltas { int8_t mode_delta[2 /* is_zeromv */]; int8_t ref_delta[DAV1D_TOTAL_REFS_PER_FRAME]; } Dav1dLoopfilterModeRefDeltas; typedef struct Dav1dFilmGrainData { unsigned seed; int num_y_points; uint8_t y_points[14][2 /* value, scaling */]; int chroma_scaling_from_luma; int num_uv_points[2]; uint8_t uv_points[2][10][2 /* value, scaling */]; int scaling_shift; int ar_coeff_lag; int8_t ar_coeffs_y[24]; int8_t ar_coeffs_uv[2][25 + 3 /* padding for alignment purposes */]; uint64_t ar_coeff_shift; int grain_scale_shift; int uv_mult[2]; int uv_luma_mult[2]; int uv_offset[2]; int overlap_flag; int clip_to_restricted_range; } Dav1dFilmGrainData; typedef struct Dav1dFrameHeader { struct { Dav1dFilmGrainData data; uint8_t present, update; } film_grain; ///< film grain parameters enum Dav1dFrameType frame_type; ///< type of the picture int width[2 /* { coded_width, superresolution_upscaled_width } */], height; uint8_t frame_offset; ///< frame number uint8_t temporal_id; ///< temporal id of the frame for SVC uint8_t spatial_id; ///< spatial id of the frame for SVC uint8_t show_existing_frame; uint8_t existing_frame_idx; uint32_t frame_id; uint32_t frame_presentation_delay; uint8_t show_frame; uint8_t showable_frame; uint8_t error_resilient_mode; uint8_t disable_cdf_update; uint8_t allow_screen_content_tools; uint8_t force_integer_mv; uint8_t frame_size_override; uint8_t primary_ref_frame; uint8_t buffer_removal_time_present; struct Dav1dFrameHeaderOperatingPoint { uint32_t buffer_removal_time; } operating_points[DAV1D_MAX_OPERATING_POINTS]; uint8_t refresh_frame_flags; int render_width, render_height; struct { uint8_t width_scale_denominator; uint8_t enabled; } super_res; uint8_t have_render_size; uint8_t allow_intrabc; uint8_t frame_ref_short_signaling; int8_t refidx[DAV1D_REFS_PER_FRAME]; uint8_t hp; enum Dav1dFilterMode subpel_filter_mode; uint8_t switchable_motion_mode; uint8_t use_ref_frame_mvs; uint8_t refresh_context; struct { uint8_t uniform; uint8_t n_bytes; uint8_t min_log2_cols, max_log2_cols, log2_cols, cols; uint8_t min_log2_rows, max_log2_rows, log2_rows, rows; uint16_t col_start_sb[DAV1D_MAX_TILE_COLS + 1]; uint16_t row_start_sb[DAV1D_MAX_TILE_ROWS + 1]; uint16_t update; } tiling; struct { uint8_t yac; int8_t ydc_delta; int8_t udc_delta, uac_delta, vdc_delta, vac_delta; uint8_t qm, qm_y, qm_u, qm_v; } quant; struct { uint8_t enabled, update_map, temporal, update_data; Dav1dSegmentationDataSet seg_data; uint8_t lossless[DAV1D_MAX_SEGMENTS], qidx[DAV1D_MAX_SEGMENTS]; } segmentation; struct { struct { uint8_t present; uint8_t res_log2; } q; struct { uint8_t present; uint8_t res_log2; uint8_t multi; } lf; } delta; uint8_t all_lossless; struct { uint8_t level_y[2 /* dir */]; uint8_t level_u, level_v; uint8_t mode_ref_delta_enabled; uint8_t mode_ref_delta_update; Dav1dLoopfilterModeRefDeltas mode_ref_deltas; uint8_t sharpness; } loopfilter; struct { uint8_t damping; uint8_t n_bits; uint8_t y_strength[DAV1D_MAX_CDEF_STRENGTHS]; uint8_t uv_strength[DAV1D_MAX_CDEF_STRENGTHS]; } cdef; struct { enum Dav1dRestorationType type[3 /* plane */]; uint8_t unit_size[2 /* y, uv */]; } restoration; enum Dav1dTxfmMode txfm_mode; uint8_t switchable_comp_refs; uint8_t skip_mode_allowed, skip_mode_enabled; int8_t skip_mode_refs[2]; uint8_t warp_motion; uint8_t reduced_txtp_set; Dav1dWarpedMotionParams gmv[DAV1D_REFS_PER_FRAME]; } Dav1dFrameHeader; #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_HEADERS_H */ ================================================ FILE: thirdparty/64/include/dav1d/picture.h ================================================ /* * Copyright © 2018-2020, VideoLAN and dav1d authors * Copyright © 2018, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_PICTURE_H #define DAV1D_PICTURE_H #include #include #include "common.h" #include "headers.h" #ifdef __cplusplus extern "C" { #endif /* Number of bytes to align AND pad picture memory buffers by, so that SIMD * implementations can over-read by a few bytes, and use aligned read/write * instructions. */ #define DAV1D_PICTURE_ALIGNMENT 64 typedef struct Dav1dPictureParameters { int w; ///< width (in pixels) int h; ///< height (in pixels) enum Dav1dPixelLayout layout; ///< format of the picture int bpc; ///< bits per pixel component (8 or 10) } Dav1dPictureParameters; typedef struct Dav1dPicture { Dav1dSequenceHeader *seq_hdr; Dav1dFrameHeader *frame_hdr; /** * Pointers to planar image data (Y is [0], U is [1], V is [2]). The data * should be bytes (for 8 bpc) or words (for 10 bpc). In case of words * containing 10 bpc image data, the pixels should be located in the LSB * bits, so that values range between [0, 1023]; the upper bits should be * zero'ed out. */ void *data[3]; /** * Number of bytes between 2 lines in data[] for luma [0] or chroma [1]. */ ptrdiff_t stride[2]; Dav1dPictureParameters p; Dav1dDataProps m; /** * High Dynamic Range Content Light Level metadata applying to this picture, * as defined in section 5.8.3 and 6.7.3 */ Dav1dContentLightLevel *content_light; /** * High Dynamic Range Mastering Display Color Volume metadata applying to * this picture, as defined in section 5.8.4 and 6.7.4 */ Dav1dMasteringDisplay *mastering_display; /** * Array of ITU-T T.35 metadata as defined in section 5.8.2 and 6.7.2 */ Dav1dITUTT35 *itut_t35; /** * Number of ITU-T T35 metadata entries in the array */ size_t n_itut_t35; uintptr_t reserved[4]; ///< reserved for future use struct Dav1dRef *frame_hdr_ref; ///< Dav1dFrameHeader allocation origin struct Dav1dRef *seq_hdr_ref; ///< Dav1dSequenceHeader allocation origin struct Dav1dRef *content_light_ref; ///< Dav1dContentLightLevel allocation origin struct Dav1dRef *mastering_display_ref; ///< Dav1dMasteringDisplay allocation origin struct Dav1dRef *itut_t35_ref; ///< Dav1dITUTT35 allocation origin uintptr_t reserved_ref[4]; ///< reserved for future use struct Dav1dRef *ref; ///< Frame data allocation origin void *allocator_data; ///< pointer managed by the allocator } Dav1dPicture; typedef struct Dav1dPicAllocator { void *cookie; ///< custom data to pass to the allocator callbacks. /** * Allocate the picture buffer based on the Dav1dPictureParameters. * * The data[0], data[1] and data[2] must be DAV1D_PICTURE_ALIGNMENT byte * aligned and with a pixel width/height multiple of 128 pixels. Any * allocated memory area should also be padded by DAV1D_PICTURE_ALIGNMENT * bytes. * data[1] and data[2] must share the same stride[1]. * * This function will be called on the main thread (the thread which calls * dav1d_get_picture()). * * @param pic The picture to allocate the buffer for. The callback needs to * fill the picture data[0], data[1], data[2], stride[0] and * stride[1]. * The allocator can fill the pic allocator_data pointer with * a custom pointer that will be passed to * release_picture_callback(). * @param cookie Custom pointer passed to all calls. * * @note No fields other than data, stride and allocator_data must be filled * by this callback. * @return 0 on success. A negative DAV1D_ERR value on error. */ int (*alloc_picture_callback)(Dav1dPicture *pic, void *cookie); /** * Release the picture buffer. * * If frame threading is used, this function may be called by the main * thread (the thread which calls dav1d_get_picture()) or any of the frame * threads and thus must be thread-safe. If frame threading is not used, * this function will only be called on the main thread. * * @param pic The picture that was filled by alloc_picture_callback(). * @param cookie Custom pointer passed to all calls. */ void (*release_picture_callback)(Dav1dPicture *pic, void *cookie); } Dav1dPicAllocator; /** * Release reference to a picture. */ DAV1D_API void dav1d_picture_unref(Dav1dPicture *p); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_PICTURE_H */ ================================================ FILE: thirdparty/64/include/dav1d/version.h ================================================ /* * Copyright © 2019-2024, VideoLAN and dav1d authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DAV1D_VERSION_H #define DAV1D_VERSION_H #ifdef __cplusplus extern "C" { #endif #define DAV1D_API_VERSION_MAJOR 7 #define DAV1D_API_VERSION_MINOR 0 #define DAV1D_API_VERSION_PATCH 0 /** * Extract version components from the value returned by * dav1d_version_int() */ #define DAV1D_API_MAJOR(v) (((v) >> 16) & 0xFF) #define DAV1D_API_MINOR(v) (((v) >> 8) & 0xFF) #define DAV1D_API_PATCH(v) (((v) >> 0) & 0xFF) #ifdef __cplusplus } /* extern "C" */ #endif #endif /* DAV1D_VERSION_H */ ================================================ FILE: thirdparty/64/include/gmp.h ================================================ /* Definitions for GNU multiple precision functions. -*- mode: c -*- Copyright 1991, 1993-1997, 1999-2016, 2020, 2021 Free Software Foundation, Inc. This file is part of the GNU MP Library. The GNU MP Library is free software; you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. The GNU MP Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with the GNU MP Library. If not, see https://www.gnu.org/licenses/. */ #ifndef __GMP_H__ #if defined (__cplusplus) #include /* for std::istream, std::ostream, std::string */ #include #endif /* Instantiated by configure. */ #if ! defined (__GMP_WITHIN_CONFIGURE) #define __GMP_HAVE_HOST_CPU_FAMILY_power 0 #define __GMP_HAVE_HOST_CPU_FAMILY_powerpc 0 #define GMP_LIMB_BITS 64 #define GMP_NAIL_BITS 0 #endif #define GMP_NUMB_BITS (GMP_LIMB_BITS - GMP_NAIL_BITS) #define GMP_NUMB_MASK ((~ __GMP_CAST (mp_limb_t, 0)) >> GMP_NAIL_BITS) #define GMP_NUMB_MAX GMP_NUMB_MASK #define GMP_NAIL_MASK (~ GMP_NUMB_MASK) #ifndef __GNU_MP__ #define __GNU_MP__ 6 #include /* for size_t */ #include /* Instantiated by configure. */ #if ! defined (__GMP_WITHIN_CONFIGURE) #define _LONG_LONG_LIMB 1 #define __GMP_LIBGMP_DLL 0 #endif /* __GMP_DECLSPEC supports Windows DLL versions of libgmp, and is empty in all other circumstances. When compiling objects for libgmp, __GMP_DECLSPEC is an export directive, or when compiling for an application it's an import directive. The two cases are differentiated by __GMP_WITHIN_GMP defined by the GMP Makefiles (and not defined from an application). __GMP_DECLSPEC_XX is similarly used for libgmpxx. __GMP_WITHIN_GMPXX indicates when building libgmpxx, and in that case libgmpxx functions are exports, but libgmp functions which might get called are imports. Libtool DLL_EXPORT define is not used. There's no attempt to support GMP built both static and DLL. Doing so would mean applications would have to tell us which of the two is going to be used when linking, and that seems very tedious and error prone if using GMP by hand, and equally tedious from a package since autoconf and automake don't give much help. __GMP_DECLSPEC is required on all documented global functions and variables, the various internals in gmp-impl.h etc can be left unadorned. But internals used by the test programs or speed measuring programs should have __GMP_DECLSPEC, and certainly constants or variables must have it or the wrong address will be resolved. In gcc __declspec can go at either the start or end of a prototype. In Microsoft C __declspec must go at the start, or after the type like void __declspec(...) *foo()". There's no __dllexport or anything to guard against someone foolish #defining dllexport. _export used to be available, but no longer. In Borland C _export still exists, but needs to go after the type, like "void _export foo();". Would have to change the __GMP_DECLSPEC syntax to make use of that. Probably more trouble than it's worth. */ #if defined (__GNUC__) #define __GMP_DECLSPEC_EXPORT __declspec(__dllexport__) #define __GMP_DECLSPEC_IMPORT __declspec(__dllimport__) #endif #if defined (_MSC_VER) || defined (__BORLANDC__) #define __GMP_DECLSPEC_EXPORT __declspec(dllexport) #define __GMP_DECLSPEC_IMPORT __declspec(dllimport) #endif #ifdef __WATCOMC__ #define __GMP_DECLSPEC_EXPORT __export #define __GMP_DECLSPEC_IMPORT __import #endif #ifdef __IBMC__ #define __GMP_DECLSPEC_EXPORT _Export #define __GMP_DECLSPEC_IMPORT _Import #endif #if __GMP_LIBGMP_DLL #ifdef __GMP_WITHIN_GMP /* compiling to go into a DLL libgmp */ #define __GMP_DECLSPEC __GMP_DECLSPEC_EXPORT #else /* compiling to go into an application which will link to a DLL libgmp */ #define __GMP_DECLSPEC __GMP_DECLSPEC_IMPORT #endif #else /* all other cases */ #define __GMP_DECLSPEC #endif #ifdef __GMP_SHORT_LIMB typedef unsigned int mp_limb_t; typedef int mp_limb_signed_t; #else #ifdef _LONG_LONG_LIMB typedef unsigned long long int mp_limb_t; typedef long long int mp_limb_signed_t; #else typedef unsigned long int mp_limb_t; typedef long int mp_limb_signed_t; #endif #endif typedef unsigned long int mp_bitcnt_t; /* For reference, note that the name __mpz_struct gets into C++ mangled function names, which means although the "__" suggests an internal, we must leave this name for binary compatibility. */ typedef struct { int _mp_alloc; /* Number of *limbs* allocated and pointed to by the _mp_d field. */ int _mp_size; /* abs(_mp_size) is the number of limbs the last field points to. If _mp_size is negative this is a negative number. */ mp_limb_t *_mp_d; /* Pointer to the limbs. */ } __mpz_struct; #endif /* __GNU_MP__ */ typedef __mpz_struct MP_INT; /* gmp 1 source compatibility */ typedef __mpz_struct mpz_t[1]; typedef mp_limb_t * mp_ptr; typedef const mp_limb_t * mp_srcptr; #if defined (_CRAY) && ! defined (_CRAYMPP) /* plain `int' is much faster (48 bits) */ #define __GMP_MP_SIZE_T_INT 1 typedef int mp_size_t; typedef int mp_exp_t; #else #define __GMP_MP_SIZE_T_INT 0 typedef long int mp_size_t; typedef long int mp_exp_t; #endif typedef struct { __mpz_struct _mp_num; __mpz_struct _mp_den; } __mpq_struct; typedef __mpq_struct MP_RAT; /* gmp 1 source compatibility */ typedef __mpq_struct mpq_t[1]; typedef struct { int _mp_prec; /* Max precision, in number of `mp_limb_t's. Set by mpf_init and modified by mpf_set_prec. The area pointed to by the _mp_d field contains `prec' + 1 limbs. */ int _mp_size; /* abs(_mp_size) is the number of limbs the last field points to. If _mp_size is negative this is a negative number. */ mp_exp_t _mp_exp; /* Exponent, in the base of `mp_limb_t'. */ mp_limb_t *_mp_d; /* Pointer to the limbs. */ } __mpf_struct; /* typedef __mpf_struct MP_FLOAT; */ typedef __mpf_struct mpf_t[1]; /* Available random number generation algorithms. */ typedef enum { GMP_RAND_ALG_DEFAULT = 0, GMP_RAND_ALG_LC = GMP_RAND_ALG_DEFAULT /* Linear congruential. */ } gmp_randalg_t; /* Random state struct. */ typedef struct { mpz_t _mp_seed; /* _mp_d member points to state of the generator. */ gmp_randalg_t _mp_alg; /* Currently unused. */ union { void *_mp_lc; /* Pointer to function pointers structure. */ } _mp_algdata; } __gmp_randstate_struct; typedef __gmp_randstate_struct gmp_randstate_t[1]; /* Types for function declarations in gmp files. */ /* ??? Should not pollute user name space with these ??? */ typedef const __mpz_struct *mpz_srcptr; typedef __mpz_struct *mpz_ptr; typedef const __mpf_struct *mpf_srcptr; typedef __mpf_struct *mpf_ptr; typedef const __mpq_struct *mpq_srcptr; typedef __mpq_struct *mpq_ptr; typedef __gmp_randstate_struct *gmp_randstate_ptr; typedef const __gmp_randstate_struct *gmp_randstate_srcptr; #if __GMP_LIBGMP_DLL #ifdef __GMP_WITHIN_GMPXX /* compiling to go into a DLL libgmpxx */ #define __GMP_DECLSPEC_XX __GMP_DECLSPEC_EXPORT #else /* compiling to go into a application which will link to a DLL libgmpxx */ #define __GMP_DECLSPEC_XX __GMP_DECLSPEC_IMPORT #endif #else /* all other cases */ #define __GMP_DECLSPEC_XX #endif #ifndef __MPN #define __MPN(x) __gmpn_##x #endif /* For reference, "defined(EOF)" cannot be used here. In g++ 2.95.4, defines EOF but not FILE. */ #if defined (FILE) \ || defined (H_STDIO) \ || defined (_H_STDIO) /* AIX */ \ || defined (_STDIO_H) /* glibc, Sun, SCO */ \ || defined (_STDIO_H_) /* BSD, OSF */ \ || defined (__STDIO_H) /* Borland */ \ || defined (__STDIO_H__) /* IRIX */ \ || defined (_STDIO_INCLUDED) /* HPUX */ \ || defined (__dj_include_stdio_h_) /* DJGPP */ \ || defined (_FILE_DEFINED) /* Microsoft */ \ || defined (__STDIO__) /* Apple MPW MrC */ \ || defined (_MSL_STDIO_H) /* Metrowerks */ \ || defined (_STDIO_H_INCLUDED) /* QNX4 */ \ || defined (_ISO_STDIO_ISO_H) /* Sun C++ */ \ || defined (__STDIO_LOADED) /* VMS */ \ || defined (_STDIO) /* HPE NonStop */ \ || defined (__DEFINED_FILE) /* musl */ #define _GMP_H_HAVE_FILE 1 #endif /* In ISO C, if a prototype involving "struct obstack *" is given without that structure defined, then the struct is scoped down to just the prototype, causing a conflict if it's subsequently defined for real. So only give prototypes if we've got obstack.h. */ #if defined (_OBSTACK_H) /* glibc */ #define _GMP_H_HAVE_OBSTACK 1 #endif /* The prototypes for gmp_vprintf etc are provided only if va_list is defined, via an application having included . Usually va_list is a typedef so can't be tested directly, but C99 specifies that va_start is a macro. will define some sort of va_list for vprintf and vfprintf, but let's not bother trying to use that since it's not standard and since application uses for gmp_vprintf etc will almost certainly require the whole anyway. */ #ifdef va_start #define _GMP_H_HAVE_VA_LIST 1 #endif /* Test for gcc >= maj.min, as per __GNUC_PREREQ in glibc */ #if defined (__GNUC__) && defined (__GNUC_MINOR__) #define __GMP_GNUC_PREREQ(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) #else #define __GMP_GNUC_PREREQ(maj, min) 0 #endif /* "pure" is in gcc 2.96 and up, see "(gcc)Function Attributes". Basically it means a function does nothing but examine its arguments and memory (global or via arguments) to generate a return value, but changes nothing and has no side-effects. __GMP_NO_ATTRIBUTE_CONST_PURE lets tune/common.c etc turn this off when trying to write timing loops. */ #if __GMP_GNUC_PREREQ (2,96) && ! defined (__GMP_NO_ATTRIBUTE_CONST_PURE) #define __GMP_ATTRIBUTE_PURE __attribute__ ((__pure__)) #else #define __GMP_ATTRIBUTE_PURE #endif /* __GMP_CAST allows us to use static_cast in C++, so our macros are clean to "g++ -Wold-style-cast". Casts in "extern inline" code within an extern "C" block don't induce these warnings, so __GMP_CAST only needs to be used on documented macros. */ #ifdef __cplusplus #define __GMP_CAST(type, expr) (static_cast (expr)) #else #define __GMP_CAST(type, expr) ((type) (expr)) #endif /* An empty "throw ()" means the function doesn't throw any C++ exceptions, this can save some stack frame info in applications. Currently it's given only on functions which never divide-by-zero etc, don't allocate memory, and are expected to never need to allocate memory. This leaves open the possibility of a C++ throw from a future GMP exceptions scheme. mpz_set_ui etc are omitted to leave open the lazy allocation scheme described in doc/tasks.html. mpz_get_d etc are omitted to leave open exceptions for float overflows. Note that __GMP_NOTHROW must be given on any inlines the same as on their prototypes (for g++ at least, where they're used together). Note also that g++ 3.0 demands that __GMP_NOTHROW is before other attributes like __GMP_ATTRIBUTE_PURE. */ #if defined (__cplusplus) #if __cplusplus >= 201103L #define __GMP_NOTHROW noexcept #else #define __GMP_NOTHROW throw () #endif #else #define __GMP_NOTHROW #endif /* PORTME: What other compilers have a useful "extern inline"? "static inline" would be an acceptable substitute if the compiler (or linker) discards unused statics. */ /* gcc has __inline__ in all modes, including strict ansi. Give a prototype for an inline too, so as to correctly specify "dllimport" on windows, in case the function is called rather than inlined. GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99 inline semantics, unless -fgnu89-inline is used. */ #ifdef __GNUC__ #if (defined __GNUC_STDC_INLINE__) || (__GNUC__ == 4 && __GNUC_MINOR__ == 2) \ || (defined __GNUC_GNU_INLINE__ && defined __cplusplus) #define __GMP_EXTERN_INLINE extern __inline__ __attribute__ ((__gnu_inline__)) #else #define __GMP_EXTERN_INLINE extern __inline__ #endif #define __GMP_INLINE_PROTOTYPES 1 #endif /* DEC C (eg. version 5.9) supports "static __inline foo()", even in -std1 strict ANSI mode. Inlining is done even when not optimizing (ie. -O0 mode, which is the default), but an unnecessary local copy of foo is emitted unless -O is used. "extern __inline" is accepted, but the "extern" appears to be ignored, ie. it becomes a plain global function but which is inlined within its file. Don't know if all old versions of DEC C supported __inline, but as a start let's do the right thing for current versions. */ #ifdef __DECC #define __GMP_EXTERN_INLINE static __inline #endif /* SCO OpenUNIX 8 cc supports "static inline foo()" but not in -Xc strict ANSI mode (__STDC__ is 1 in that mode). Inlining only actually takes place under -O. Without -O "foo" seems to be emitted whether it's used or not, which is wasteful. "extern inline foo()" isn't useful, the "extern" is apparently ignored, so foo is inlined if possible but also emitted as a global, which causes multiple definition errors when building a shared libgmp. */ #ifdef __SCO_VERSION__ #if __SCO_VERSION__ > 400000000 && __STDC__ != 1 \ && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE static inline #endif #endif /* Microsoft's C compiler accepts __inline */ #ifdef _MSC_VER #define __GMP_EXTERN_INLINE __inline #endif /* Recent enough Sun C compilers want "inline" */ #if defined (__SUNPRO_C) && __SUNPRO_C >= 0x560 \ && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE inline #endif /* Somewhat older Sun C compilers want "static inline" */ #if defined (__SUNPRO_C) && __SUNPRO_C >= 0x540 \ && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE static inline #endif /* C++ always has "inline" and since it's a normal feature the linker should discard duplicate non-inlined copies, or if it doesn't then that's a problem for everyone, not just GMP. */ #if defined (__cplusplus) && ! defined (__GMP_EXTERN_INLINE) #define __GMP_EXTERN_INLINE inline #endif /* Don't do any inlining within a configure run, since if the compiler ends up emitting copies of the code into the object file it can end up demanding the various support routines (like mpn_popcount) for linking, making the "alloca" test and perhaps others fail. And on hppa ia64 a pre-release gcc 3.2 was seen not respecting the "extern" in "extern __inline__", triggering this problem too. */ #if defined (__GMP_WITHIN_CONFIGURE) && ! __GMP_WITHIN_CONFIGURE_INLINE #undef __GMP_EXTERN_INLINE #endif /* By default, don't give a prototype when there's going to be an inline version. Note in particular that Cray C++ objects to the combination of prototype and inline. */ #ifdef __GMP_EXTERN_INLINE #ifndef __GMP_INLINE_PROTOTYPES #define __GMP_INLINE_PROTOTYPES 0 #endif #else #define __GMP_INLINE_PROTOTYPES 1 #endif #define __GMP_ABS(x) ((x) >= 0 ? (x) : -(x)) #define __GMP_MAX(h,i) ((h) > (i) ? (h) : (i)) /* __builtin_expect is in gcc 3.0, and not in 2.95. */ #if __GMP_GNUC_PREREQ (3,0) #define __GMP_LIKELY(cond) __builtin_expect ((cond) != 0, 1) #define __GMP_UNLIKELY(cond) __builtin_expect ((cond) != 0, 0) #else #define __GMP_LIKELY(cond) (cond) #define __GMP_UNLIKELY(cond) (cond) #endif #ifdef _CRAY #define __GMP_CRAY_Pragma(str) _Pragma (str) #else #define __GMP_CRAY_Pragma(str) #endif /* Allow direct user access to numerator and denominator of an mpq_t object. */ #define mpq_numref(Q) (&((Q)->_mp_num)) #define mpq_denref(Q) (&((Q)->_mp_den)) #if defined (__cplusplus) extern "C" { using std::FILE; #endif #define mp_set_memory_functions __gmp_set_memory_functions __GMP_DECLSPEC void mp_set_memory_functions (void *(*) (size_t), void *(*) (void *, size_t, size_t), void (*) (void *, size_t)) __GMP_NOTHROW; #define mp_get_memory_functions __gmp_get_memory_functions __GMP_DECLSPEC void mp_get_memory_functions (void *(**) (size_t), void *(**) (void *, size_t, size_t), void (**) (void *, size_t)) __GMP_NOTHROW; #define mp_bits_per_limb __gmp_bits_per_limb __GMP_DECLSPEC extern const int mp_bits_per_limb; #define gmp_errno __gmp_errno __GMP_DECLSPEC extern int gmp_errno; #define gmp_version __gmp_version __GMP_DECLSPEC extern const char * const gmp_version; /**************** Random number routines. ****************/ /* obsolete */ #define gmp_randinit __gmp_randinit __GMP_DECLSPEC void gmp_randinit (gmp_randstate_ptr, gmp_randalg_t, ...); #define gmp_randinit_default __gmp_randinit_default __GMP_DECLSPEC void gmp_randinit_default (gmp_randstate_ptr); #define gmp_randinit_lc_2exp __gmp_randinit_lc_2exp __GMP_DECLSPEC void gmp_randinit_lc_2exp (gmp_randstate_ptr, mpz_srcptr, unsigned long int, mp_bitcnt_t); #define gmp_randinit_lc_2exp_size __gmp_randinit_lc_2exp_size __GMP_DECLSPEC int gmp_randinit_lc_2exp_size (gmp_randstate_ptr, mp_bitcnt_t); #define gmp_randinit_mt __gmp_randinit_mt __GMP_DECLSPEC void gmp_randinit_mt (gmp_randstate_ptr); #define gmp_randinit_set __gmp_randinit_set __GMP_DECLSPEC void gmp_randinit_set (gmp_randstate_ptr, gmp_randstate_srcptr); #define gmp_randseed __gmp_randseed __GMP_DECLSPEC void gmp_randseed (gmp_randstate_ptr, mpz_srcptr); #define gmp_randseed_ui __gmp_randseed_ui __GMP_DECLSPEC void gmp_randseed_ui (gmp_randstate_ptr, unsigned long int); #define gmp_randclear __gmp_randclear __GMP_DECLSPEC void gmp_randclear (gmp_randstate_ptr); #define gmp_urandomb_ui __gmp_urandomb_ui __GMP_DECLSPEC unsigned long gmp_urandomb_ui (gmp_randstate_ptr, unsigned long); #define gmp_urandomm_ui __gmp_urandomm_ui __GMP_DECLSPEC unsigned long gmp_urandomm_ui (gmp_randstate_ptr, unsigned long); /**************** Formatted output routines. ****************/ #define gmp_asprintf __gmp_asprintf __GMP_DECLSPEC int gmp_asprintf (char **, const char *, ...); #define gmp_fprintf __gmp_fprintf #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC int gmp_fprintf (FILE *, const char *, ...); #endif #define gmp_obstack_printf __gmp_obstack_printf #if defined (_GMP_H_HAVE_OBSTACK) __GMP_DECLSPEC int gmp_obstack_printf (struct obstack *, const char *, ...); #endif #define gmp_obstack_vprintf __gmp_obstack_vprintf #if defined (_GMP_H_HAVE_OBSTACK) && defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_obstack_vprintf (struct obstack *, const char *, va_list); #endif #define gmp_printf __gmp_printf __GMP_DECLSPEC int gmp_printf (const char *, ...); #define gmp_snprintf __gmp_snprintf __GMP_DECLSPEC int gmp_snprintf (char *, size_t, const char *, ...); #define gmp_sprintf __gmp_sprintf __GMP_DECLSPEC int gmp_sprintf (char *, const char *, ...); #define gmp_vasprintf __gmp_vasprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vasprintf (char **, const char *, va_list); #endif #define gmp_vfprintf __gmp_vfprintf #if defined (_GMP_H_HAVE_FILE) && defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vfprintf (FILE *, const char *, va_list); #endif #define gmp_vprintf __gmp_vprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vprintf (const char *, va_list); #endif #define gmp_vsnprintf __gmp_vsnprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vsnprintf (char *, size_t, const char *, va_list); #endif #define gmp_vsprintf __gmp_vsprintf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vsprintf (char *, const char *, va_list); #endif /**************** Formatted input routines. ****************/ #define gmp_fscanf __gmp_fscanf #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC int gmp_fscanf (FILE *, const char *, ...); #endif #define gmp_scanf __gmp_scanf __GMP_DECLSPEC int gmp_scanf (const char *, ...); #define gmp_sscanf __gmp_sscanf __GMP_DECLSPEC int gmp_sscanf (const char *, const char *, ...); #define gmp_vfscanf __gmp_vfscanf #if defined (_GMP_H_HAVE_FILE) && defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vfscanf (FILE *, const char *, va_list); #endif #define gmp_vscanf __gmp_vscanf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vscanf (const char *, va_list); #endif #define gmp_vsscanf __gmp_vsscanf #if defined (_GMP_H_HAVE_VA_LIST) __GMP_DECLSPEC int gmp_vsscanf (const char *, const char *, va_list); #endif /**************** Integer (i.e. Z) routines. ****************/ #define _mpz_realloc __gmpz_realloc #define mpz_realloc __gmpz_realloc __GMP_DECLSPEC void *_mpz_realloc (mpz_ptr, mp_size_t); #define mpz_abs __gmpz_abs #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_abs) __GMP_DECLSPEC void mpz_abs (mpz_ptr, mpz_srcptr); #endif #define mpz_add __gmpz_add __GMP_DECLSPEC void mpz_add (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_add_ui __gmpz_add_ui __GMP_DECLSPEC void mpz_add_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_addmul __gmpz_addmul __GMP_DECLSPEC void mpz_addmul (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_addmul_ui __gmpz_addmul_ui __GMP_DECLSPEC void mpz_addmul_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_and __gmpz_and __GMP_DECLSPEC void mpz_and (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_array_init __gmpz_array_init __GMP_DECLSPEC void mpz_array_init (mpz_ptr, mp_size_t, mp_size_t); #define mpz_bin_ui __gmpz_bin_ui __GMP_DECLSPEC void mpz_bin_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_bin_uiui __gmpz_bin_uiui __GMP_DECLSPEC void mpz_bin_uiui (mpz_ptr, unsigned long int, unsigned long int); #define mpz_cdiv_q __gmpz_cdiv_q __GMP_DECLSPEC void mpz_cdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_cdiv_q_2exp __gmpz_cdiv_q_2exp __GMP_DECLSPEC void mpz_cdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_cdiv_q_ui __gmpz_cdiv_q_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_cdiv_qr __gmpz_cdiv_qr __GMP_DECLSPEC void mpz_cdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_cdiv_qr_ui __gmpz_cdiv_qr_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_cdiv_r __gmpz_cdiv_r __GMP_DECLSPEC void mpz_cdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_cdiv_r_2exp __gmpz_cdiv_r_2exp __GMP_DECLSPEC void mpz_cdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_cdiv_r_ui __gmpz_cdiv_r_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_cdiv_ui __gmpz_cdiv_ui __GMP_DECLSPEC unsigned long int mpz_cdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpz_clear __gmpz_clear __GMP_DECLSPEC void mpz_clear (mpz_ptr); #define mpz_clears __gmpz_clears __GMP_DECLSPEC void mpz_clears (mpz_ptr, ...); #define mpz_clrbit __gmpz_clrbit __GMP_DECLSPEC void mpz_clrbit (mpz_ptr, mp_bitcnt_t); #define mpz_cmp __gmpz_cmp __GMP_DECLSPEC int mpz_cmp (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_cmp_d __gmpz_cmp_d __GMP_DECLSPEC int mpz_cmp_d (mpz_srcptr, double) __GMP_ATTRIBUTE_PURE; #define _mpz_cmp_si __gmpz_cmp_si __GMP_DECLSPEC int _mpz_cmp_si (mpz_srcptr, signed long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define _mpz_cmp_ui __gmpz_cmp_ui __GMP_DECLSPEC int _mpz_cmp_ui (mpz_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_cmpabs __gmpz_cmpabs __GMP_DECLSPEC int mpz_cmpabs (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_cmpabs_d __gmpz_cmpabs_d __GMP_DECLSPEC int mpz_cmpabs_d (mpz_srcptr, double) __GMP_ATTRIBUTE_PURE; #define mpz_cmpabs_ui __gmpz_cmpabs_ui __GMP_DECLSPEC int mpz_cmpabs_ui (mpz_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_com __gmpz_com __GMP_DECLSPEC void mpz_com (mpz_ptr, mpz_srcptr); #define mpz_combit __gmpz_combit __GMP_DECLSPEC void mpz_combit (mpz_ptr, mp_bitcnt_t); #define mpz_congruent_p __gmpz_congruent_p __GMP_DECLSPEC int mpz_congruent_p (mpz_srcptr, mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_congruent_2exp_p __gmpz_congruent_2exp_p __GMP_DECLSPEC int mpz_congruent_2exp_p (mpz_srcptr, mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_congruent_ui_p __gmpz_congruent_ui_p __GMP_DECLSPEC int mpz_congruent_ui_p (mpz_srcptr, unsigned long, unsigned long) __GMP_ATTRIBUTE_PURE; #define mpz_divexact __gmpz_divexact __GMP_DECLSPEC void mpz_divexact (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_divexact_ui __gmpz_divexact_ui __GMP_DECLSPEC void mpz_divexact_ui (mpz_ptr, mpz_srcptr, unsigned long); #define mpz_divisible_p __gmpz_divisible_p __GMP_DECLSPEC int mpz_divisible_p (mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_divisible_ui_p __gmpz_divisible_ui_p __GMP_DECLSPEC int mpz_divisible_ui_p (mpz_srcptr, unsigned long) __GMP_ATTRIBUTE_PURE; #define mpz_divisible_2exp_p __gmpz_divisible_2exp_p __GMP_DECLSPEC int mpz_divisible_2exp_p (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_dump __gmpz_dump __GMP_DECLSPEC void mpz_dump (mpz_srcptr); #define mpz_export __gmpz_export __GMP_DECLSPEC void *mpz_export (void *, size_t *, int, size_t, int, size_t, mpz_srcptr); #define mpz_fac_ui __gmpz_fac_ui __GMP_DECLSPEC void mpz_fac_ui (mpz_ptr, unsigned long int); #define mpz_2fac_ui __gmpz_2fac_ui __GMP_DECLSPEC void mpz_2fac_ui (mpz_ptr, unsigned long int); #define mpz_mfac_uiui __gmpz_mfac_uiui __GMP_DECLSPEC void mpz_mfac_uiui (mpz_ptr, unsigned long int, unsigned long int); #define mpz_primorial_ui __gmpz_primorial_ui __GMP_DECLSPEC void mpz_primorial_ui (mpz_ptr, unsigned long int); #define mpz_fdiv_q __gmpz_fdiv_q __GMP_DECLSPEC void mpz_fdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_fdiv_q_2exp __gmpz_fdiv_q_2exp __GMP_DECLSPEC void mpz_fdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_fdiv_q_ui __gmpz_fdiv_q_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_fdiv_qr __gmpz_fdiv_qr __GMP_DECLSPEC void mpz_fdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_fdiv_qr_ui __gmpz_fdiv_qr_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_fdiv_r __gmpz_fdiv_r __GMP_DECLSPEC void mpz_fdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_fdiv_r_2exp __gmpz_fdiv_r_2exp __GMP_DECLSPEC void mpz_fdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_fdiv_r_ui __gmpz_fdiv_r_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_fdiv_ui __gmpz_fdiv_ui __GMP_DECLSPEC unsigned long int mpz_fdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpz_fib_ui __gmpz_fib_ui __GMP_DECLSPEC void mpz_fib_ui (mpz_ptr, unsigned long int); #define mpz_fib2_ui __gmpz_fib2_ui __GMP_DECLSPEC void mpz_fib2_ui (mpz_ptr, mpz_ptr, unsigned long int); #define mpz_fits_sint_p __gmpz_fits_sint_p __GMP_DECLSPEC int mpz_fits_sint_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_fits_slong_p __gmpz_fits_slong_p __GMP_DECLSPEC int mpz_fits_slong_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_fits_sshort_p __gmpz_fits_sshort_p __GMP_DECLSPEC int mpz_fits_sshort_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_fits_uint_p __gmpz_fits_uint_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_uint_p) __GMP_DECLSPEC int mpz_fits_uint_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_fits_ulong_p __gmpz_fits_ulong_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_ulong_p) __GMP_DECLSPEC int mpz_fits_ulong_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_fits_ushort_p __gmpz_fits_ushort_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_fits_ushort_p) __GMP_DECLSPEC int mpz_fits_ushort_p (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_gcd __gmpz_gcd __GMP_DECLSPEC void mpz_gcd (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_gcd_ui __gmpz_gcd_ui __GMP_DECLSPEC unsigned long int mpz_gcd_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_gcdext __gmpz_gcdext __GMP_DECLSPEC void mpz_gcdext (mpz_ptr, mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_get_d __gmpz_get_d __GMP_DECLSPEC double mpz_get_d (mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_get_d_2exp __gmpz_get_d_2exp __GMP_DECLSPEC double mpz_get_d_2exp (signed long int *, mpz_srcptr); #define mpz_get_si __gmpz_get_si __GMP_DECLSPEC /* signed */ long int mpz_get_si (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_get_str __gmpz_get_str __GMP_DECLSPEC char *mpz_get_str (char *, int, mpz_srcptr); #define mpz_get_ui __gmpz_get_ui #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_get_ui) __GMP_DECLSPEC unsigned long int mpz_get_ui (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_getlimbn __gmpz_getlimbn #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_getlimbn) __GMP_DECLSPEC mp_limb_t mpz_getlimbn (mpz_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_hamdist __gmpz_hamdist __GMP_DECLSPEC mp_bitcnt_t mpz_hamdist (mpz_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_import __gmpz_import __GMP_DECLSPEC void mpz_import (mpz_ptr, size_t, int, size_t, int, size_t, const void *); #define mpz_init __gmpz_init __GMP_DECLSPEC void mpz_init (mpz_ptr) __GMP_NOTHROW; #define mpz_init2 __gmpz_init2 __GMP_DECLSPEC void mpz_init2 (mpz_ptr, mp_bitcnt_t); #define mpz_inits __gmpz_inits __GMP_DECLSPEC void mpz_inits (mpz_ptr, ...) __GMP_NOTHROW; #define mpz_init_set __gmpz_init_set __GMP_DECLSPEC void mpz_init_set (mpz_ptr, mpz_srcptr); #define mpz_init_set_d __gmpz_init_set_d __GMP_DECLSPEC void mpz_init_set_d (mpz_ptr, double); #define mpz_init_set_si __gmpz_init_set_si __GMP_DECLSPEC void mpz_init_set_si (mpz_ptr, signed long int); #define mpz_init_set_str __gmpz_init_set_str __GMP_DECLSPEC int mpz_init_set_str (mpz_ptr, const char *, int); #define mpz_init_set_ui __gmpz_init_set_ui __GMP_DECLSPEC void mpz_init_set_ui (mpz_ptr, unsigned long int); #define mpz_inp_raw __gmpz_inp_raw #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_inp_raw (mpz_ptr, FILE *); #endif #define mpz_inp_str __gmpz_inp_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_inp_str (mpz_ptr, FILE *, int); #endif #define mpz_invert __gmpz_invert __GMP_DECLSPEC int mpz_invert (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_ior __gmpz_ior __GMP_DECLSPEC void mpz_ior (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_jacobi __gmpz_jacobi __GMP_DECLSPEC int mpz_jacobi (mpz_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_kronecker mpz_jacobi /* alias */ #define mpz_kronecker_si __gmpz_kronecker_si __GMP_DECLSPEC int mpz_kronecker_si (mpz_srcptr, long) __GMP_ATTRIBUTE_PURE; #define mpz_kronecker_ui __gmpz_kronecker_ui __GMP_DECLSPEC int mpz_kronecker_ui (mpz_srcptr, unsigned long) __GMP_ATTRIBUTE_PURE; #define mpz_si_kronecker __gmpz_si_kronecker __GMP_DECLSPEC int mpz_si_kronecker (long, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_ui_kronecker __gmpz_ui_kronecker __GMP_DECLSPEC int mpz_ui_kronecker (unsigned long, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_lcm __gmpz_lcm __GMP_DECLSPEC void mpz_lcm (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_lcm_ui __gmpz_lcm_ui __GMP_DECLSPEC void mpz_lcm_ui (mpz_ptr, mpz_srcptr, unsigned long); #define mpz_legendre mpz_jacobi /* alias */ #define mpz_lucnum_ui __gmpz_lucnum_ui __GMP_DECLSPEC void mpz_lucnum_ui (mpz_ptr, unsigned long int); #define mpz_lucnum2_ui __gmpz_lucnum2_ui __GMP_DECLSPEC void mpz_lucnum2_ui (mpz_ptr, mpz_ptr, unsigned long int); #define mpz_millerrabin __gmpz_millerrabin __GMP_DECLSPEC int mpz_millerrabin (mpz_srcptr, int) __GMP_ATTRIBUTE_PURE; #define mpz_mod __gmpz_mod __GMP_DECLSPEC void mpz_mod (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_mod_ui mpz_fdiv_r_ui /* same as fdiv_r because divisor unsigned */ #define mpz_mul __gmpz_mul __GMP_DECLSPEC void mpz_mul (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_mul_2exp __gmpz_mul_2exp __GMP_DECLSPEC void mpz_mul_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_mul_si __gmpz_mul_si __GMP_DECLSPEC void mpz_mul_si (mpz_ptr, mpz_srcptr, long int); #define mpz_mul_ui __gmpz_mul_ui __GMP_DECLSPEC void mpz_mul_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_neg __gmpz_neg #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_neg) __GMP_DECLSPEC void mpz_neg (mpz_ptr, mpz_srcptr); #endif #define mpz_nextprime __gmpz_nextprime __GMP_DECLSPEC void mpz_nextprime (mpz_ptr, mpz_srcptr); #define mpz_prevprime __gmpz_prevprime __GMP_DECLSPEC int mpz_prevprime (mpz_ptr, mpz_srcptr); #define mpz_out_raw __gmpz_out_raw #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_out_raw (FILE *, mpz_srcptr); #endif #define mpz_out_str __gmpz_out_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpz_out_str (FILE *, int, mpz_srcptr); #endif #define mpz_perfect_power_p __gmpz_perfect_power_p __GMP_DECLSPEC int mpz_perfect_power_p (mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpz_perfect_square_p __gmpz_perfect_square_p #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_perfect_square_p) __GMP_DECLSPEC int mpz_perfect_square_p (mpz_srcptr) __GMP_ATTRIBUTE_PURE; #endif #define mpz_popcount __gmpz_popcount #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_popcount) __GMP_DECLSPEC mp_bitcnt_t mpz_popcount (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_pow_ui __gmpz_pow_ui __GMP_DECLSPEC void mpz_pow_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_powm __gmpz_powm __GMP_DECLSPEC void mpz_powm (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr); #define mpz_powm_sec __gmpz_powm_sec __GMP_DECLSPEC void mpz_powm_sec (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr); #define mpz_powm_ui __gmpz_powm_ui __GMP_DECLSPEC void mpz_powm_ui (mpz_ptr, mpz_srcptr, unsigned long int, mpz_srcptr); #define mpz_probab_prime_p __gmpz_probab_prime_p __GMP_DECLSPEC int mpz_probab_prime_p (mpz_srcptr, int) __GMP_ATTRIBUTE_PURE; #define mpz_random __gmpz_random __GMP_DECLSPEC void mpz_random (mpz_ptr, mp_size_t); #define mpz_random2 __gmpz_random2 __GMP_DECLSPEC void mpz_random2 (mpz_ptr, mp_size_t); #define mpz_realloc2 __gmpz_realloc2 __GMP_DECLSPEC void mpz_realloc2 (mpz_ptr, mp_bitcnt_t); #define mpz_remove __gmpz_remove __GMP_DECLSPEC mp_bitcnt_t mpz_remove (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_root __gmpz_root __GMP_DECLSPEC int mpz_root (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_rootrem __gmpz_rootrem __GMP_DECLSPEC void mpz_rootrem (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_rrandomb __gmpz_rrandomb __GMP_DECLSPEC void mpz_rrandomb (mpz_ptr, gmp_randstate_ptr, mp_bitcnt_t); #define mpz_scan0 __gmpz_scan0 __GMP_DECLSPEC mp_bitcnt_t mpz_scan0 (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_scan1 __gmpz_scan1 __GMP_DECLSPEC mp_bitcnt_t mpz_scan1 (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_set __gmpz_set __GMP_DECLSPEC void mpz_set (mpz_ptr, mpz_srcptr); #define mpz_set_d __gmpz_set_d __GMP_DECLSPEC void mpz_set_d (mpz_ptr, double); #define mpz_set_f __gmpz_set_f __GMP_DECLSPEC void mpz_set_f (mpz_ptr, mpf_srcptr); #define mpz_set_q __gmpz_set_q #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_set_q) __GMP_DECLSPEC void mpz_set_q (mpz_ptr, mpq_srcptr); #endif #define mpz_set_si __gmpz_set_si __GMP_DECLSPEC void mpz_set_si (mpz_ptr, signed long int); #define mpz_set_str __gmpz_set_str __GMP_DECLSPEC int mpz_set_str (mpz_ptr, const char *, int); #define mpz_set_ui __gmpz_set_ui __GMP_DECLSPEC void mpz_set_ui (mpz_ptr, unsigned long int); #define mpz_setbit __gmpz_setbit __GMP_DECLSPEC void mpz_setbit (mpz_ptr, mp_bitcnt_t); #define mpz_size __gmpz_size #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpz_size) __GMP_DECLSPEC size_t mpz_size (mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpz_sizeinbase __gmpz_sizeinbase __GMP_DECLSPEC size_t mpz_sizeinbase (mpz_srcptr, int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_sqrt __gmpz_sqrt __GMP_DECLSPEC void mpz_sqrt (mpz_ptr, mpz_srcptr); #define mpz_sqrtrem __gmpz_sqrtrem __GMP_DECLSPEC void mpz_sqrtrem (mpz_ptr, mpz_ptr, mpz_srcptr); #define mpz_sub __gmpz_sub __GMP_DECLSPEC void mpz_sub (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_sub_ui __gmpz_sub_ui __GMP_DECLSPEC void mpz_sub_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_ui_sub __gmpz_ui_sub __GMP_DECLSPEC void mpz_ui_sub (mpz_ptr, unsigned long int, mpz_srcptr); #define mpz_submul __gmpz_submul __GMP_DECLSPEC void mpz_submul (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_submul_ui __gmpz_submul_ui __GMP_DECLSPEC void mpz_submul_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_swap __gmpz_swap __GMP_DECLSPEC void mpz_swap (mpz_ptr, mpz_ptr) __GMP_NOTHROW; #define mpz_tdiv_ui __gmpz_tdiv_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_ui (mpz_srcptr, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpz_tdiv_q __gmpz_tdiv_q __GMP_DECLSPEC void mpz_tdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_tdiv_q_2exp __gmpz_tdiv_q_2exp __GMP_DECLSPEC void mpz_tdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_tdiv_q_ui __gmpz_tdiv_q_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_tdiv_qr __gmpz_tdiv_qr __GMP_DECLSPEC void mpz_tdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_tdiv_qr_ui __gmpz_tdiv_qr_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_tdiv_r __gmpz_tdiv_r __GMP_DECLSPEC void mpz_tdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_tdiv_r_2exp __gmpz_tdiv_r_2exp __GMP_DECLSPEC void mpz_tdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t); #define mpz_tdiv_r_ui __gmpz_tdiv_r_ui __GMP_DECLSPEC unsigned long int mpz_tdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int); #define mpz_tstbit __gmpz_tstbit __GMP_DECLSPEC int mpz_tstbit (mpz_srcptr, mp_bitcnt_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpz_ui_pow_ui __gmpz_ui_pow_ui __GMP_DECLSPEC void mpz_ui_pow_ui (mpz_ptr, unsigned long int, unsigned long int); #define mpz_urandomb __gmpz_urandomb __GMP_DECLSPEC void mpz_urandomb (mpz_ptr, gmp_randstate_ptr, mp_bitcnt_t); #define mpz_urandomm __gmpz_urandomm __GMP_DECLSPEC void mpz_urandomm (mpz_ptr, gmp_randstate_ptr, mpz_srcptr); #define mpz_xor __gmpz_xor #define mpz_eor __gmpz_xor __GMP_DECLSPEC void mpz_xor (mpz_ptr, mpz_srcptr, mpz_srcptr); #define mpz_limbs_read __gmpz_limbs_read __GMP_DECLSPEC mp_srcptr mpz_limbs_read (mpz_srcptr); #define mpz_limbs_write __gmpz_limbs_write __GMP_DECLSPEC mp_ptr mpz_limbs_write (mpz_ptr, mp_size_t); #define mpz_limbs_modify __gmpz_limbs_modify __GMP_DECLSPEC mp_ptr mpz_limbs_modify (mpz_ptr, mp_size_t); #define mpz_limbs_finish __gmpz_limbs_finish __GMP_DECLSPEC void mpz_limbs_finish (mpz_ptr, mp_size_t); #define mpz_roinit_n __gmpz_roinit_n __GMP_DECLSPEC mpz_srcptr mpz_roinit_n (mpz_ptr, mp_srcptr, mp_size_t); #define MPZ_ROINIT_N(xp, xs) {{0, (xs),(xp) }} /**************** Rational (i.e. Q) routines. ****************/ #define mpq_abs __gmpq_abs #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpq_abs) __GMP_DECLSPEC void mpq_abs (mpq_ptr, mpq_srcptr); #endif #define mpq_add __gmpq_add __GMP_DECLSPEC void mpq_add (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_canonicalize __gmpq_canonicalize __GMP_DECLSPEC void mpq_canonicalize (mpq_ptr); #define mpq_clear __gmpq_clear __GMP_DECLSPEC void mpq_clear (mpq_ptr); #define mpq_clears __gmpq_clears __GMP_DECLSPEC void mpq_clears (mpq_ptr, ...); #define mpq_cmp __gmpq_cmp __GMP_DECLSPEC int mpq_cmp (mpq_srcptr, mpq_srcptr) __GMP_ATTRIBUTE_PURE; #define _mpq_cmp_si __gmpq_cmp_si __GMP_DECLSPEC int _mpq_cmp_si (mpq_srcptr, long, unsigned long) __GMP_ATTRIBUTE_PURE; #define _mpq_cmp_ui __gmpq_cmp_ui __GMP_DECLSPEC int _mpq_cmp_ui (mpq_srcptr, unsigned long int, unsigned long int) __GMP_ATTRIBUTE_PURE; #define mpq_cmp_z __gmpq_cmp_z __GMP_DECLSPEC int mpq_cmp_z (mpq_srcptr, mpz_srcptr) __GMP_ATTRIBUTE_PURE; #define mpq_div __gmpq_div __GMP_DECLSPEC void mpq_div (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_div_2exp __gmpq_div_2exp __GMP_DECLSPEC void mpq_div_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t); #define mpq_equal __gmpq_equal __GMP_DECLSPEC int mpq_equal (mpq_srcptr, mpq_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpq_get_num __gmpq_get_num __GMP_DECLSPEC void mpq_get_num (mpz_ptr, mpq_srcptr); #define mpq_get_den __gmpq_get_den __GMP_DECLSPEC void mpq_get_den (mpz_ptr, mpq_srcptr); #define mpq_get_d __gmpq_get_d __GMP_DECLSPEC double mpq_get_d (mpq_srcptr) __GMP_ATTRIBUTE_PURE; #define mpq_get_str __gmpq_get_str __GMP_DECLSPEC char *mpq_get_str (char *, int, mpq_srcptr); #define mpq_init __gmpq_init __GMP_DECLSPEC void mpq_init (mpq_ptr); #define mpq_inits __gmpq_inits __GMP_DECLSPEC void mpq_inits (mpq_ptr, ...); #define mpq_inp_str __gmpq_inp_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpq_inp_str (mpq_ptr, FILE *, int); #endif #define mpq_inv __gmpq_inv __GMP_DECLSPEC void mpq_inv (mpq_ptr, mpq_srcptr); #define mpq_mul __gmpq_mul __GMP_DECLSPEC void mpq_mul (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_mul_2exp __gmpq_mul_2exp __GMP_DECLSPEC void mpq_mul_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t); #define mpq_neg __gmpq_neg #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpq_neg) __GMP_DECLSPEC void mpq_neg (mpq_ptr, mpq_srcptr); #endif #define mpq_out_str __gmpq_out_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpq_out_str (FILE *, int, mpq_srcptr); #endif #define mpq_set __gmpq_set __GMP_DECLSPEC void mpq_set (mpq_ptr, mpq_srcptr); #define mpq_set_d __gmpq_set_d __GMP_DECLSPEC void mpq_set_d (mpq_ptr, double); #define mpq_set_den __gmpq_set_den __GMP_DECLSPEC void mpq_set_den (mpq_ptr, mpz_srcptr); #define mpq_set_f __gmpq_set_f __GMP_DECLSPEC void mpq_set_f (mpq_ptr, mpf_srcptr); #define mpq_set_num __gmpq_set_num __GMP_DECLSPEC void mpq_set_num (mpq_ptr, mpz_srcptr); #define mpq_set_si __gmpq_set_si __GMP_DECLSPEC void mpq_set_si (mpq_ptr, signed long int, unsigned long int); #define mpq_set_str __gmpq_set_str __GMP_DECLSPEC int mpq_set_str (mpq_ptr, const char *, int); #define mpq_set_ui __gmpq_set_ui __GMP_DECLSPEC void mpq_set_ui (mpq_ptr, unsigned long int, unsigned long int); #define mpq_set_z __gmpq_set_z __GMP_DECLSPEC void mpq_set_z (mpq_ptr, mpz_srcptr); #define mpq_sub __gmpq_sub __GMP_DECLSPEC void mpq_sub (mpq_ptr, mpq_srcptr, mpq_srcptr); #define mpq_swap __gmpq_swap __GMP_DECLSPEC void mpq_swap (mpq_ptr, mpq_ptr) __GMP_NOTHROW; /**************** Float (i.e. F) routines. ****************/ #define mpf_abs __gmpf_abs __GMP_DECLSPEC void mpf_abs (mpf_ptr, mpf_srcptr); #define mpf_add __gmpf_add __GMP_DECLSPEC void mpf_add (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_add_ui __gmpf_add_ui __GMP_DECLSPEC void mpf_add_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_ceil __gmpf_ceil __GMP_DECLSPEC void mpf_ceil (mpf_ptr, mpf_srcptr); #define mpf_clear __gmpf_clear __GMP_DECLSPEC void mpf_clear (mpf_ptr); #define mpf_clears __gmpf_clears __GMP_DECLSPEC void mpf_clears (mpf_ptr, ...); #define mpf_cmp __gmpf_cmp __GMP_DECLSPEC int mpf_cmp (mpf_srcptr, mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_cmp_z __gmpf_cmp_z __GMP_DECLSPEC int mpf_cmp_z (mpf_srcptr, mpz_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_cmp_d __gmpf_cmp_d __GMP_DECLSPEC int mpf_cmp_d (mpf_srcptr, double) __GMP_ATTRIBUTE_PURE; #define mpf_cmp_si __gmpf_cmp_si __GMP_DECLSPEC int mpf_cmp_si (mpf_srcptr, signed long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_cmp_ui __gmpf_cmp_ui __GMP_DECLSPEC int mpf_cmp_ui (mpf_srcptr, unsigned long int) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_div __gmpf_div __GMP_DECLSPEC void mpf_div (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_div_2exp __gmpf_div_2exp __GMP_DECLSPEC void mpf_div_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t); #define mpf_div_ui __gmpf_div_ui __GMP_DECLSPEC void mpf_div_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_dump __gmpf_dump __GMP_DECLSPEC void mpf_dump (mpf_srcptr); #define mpf_eq __gmpf_eq __GMP_DECLSPEC int mpf_eq (mpf_srcptr, mpf_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE; #define mpf_fits_sint_p __gmpf_fits_sint_p __GMP_DECLSPEC int mpf_fits_sint_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_slong_p __gmpf_fits_slong_p __GMP_DECLSPEC int mpf_fits_slong_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_sshort_p __gmpf_fits_sshort_p __GMP_DECLSPEC int mpf_fits_sshort_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_uint_p __gmpf_fits_uint_p __GMP_DECLSPEC int mpf_fits_uint_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_ulong_p __gmpf_fits_ulong_p __GMP_DECLSPEC int mpf_fits_ulong_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_fits_ushort_p __gmpf_fits_ushort_p __GMP_DECLSPEC int mpf_fits_ushort_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_floor __gmpf_floor __GMP_DECLSPEC void mpf_floor (mpf_ptr, mpf_srcptr); #define mpf_get_d __gmpf_get_d __GMP_DECLSPEC double mpf_get_d (mpf_srcptr) __GMP_ATTRIBUTE_PURE; #define mpf_get_d_2exp __gmpf_get_d_2exp __GMP_DECLSPEC double mpf_get_d_2exp (signed long int *, mpf_srcptr); #define mpf_get_default_prec __gmpf_get_default_prec __GMP_DECLSPEC mp_bitcnt_t mpf_get_default_prec (void) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_get_prec __gmpf_get_prec __GMP_DECLSPEC mp_bitcnt_t mpf_get_prec (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_get_si __gmpf_get_si __GMP_DECLSPEC long mpf_get_si (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_get_str __gmpf_get_str __GMP_DECLSPEC char *mpf_get_str (char *, mp_exp_t *, int, size_t, mpf_srcptr); #define mpf_get_ui __gmpf_get_ui __GMP_DECLSPEC unsigned long mpf_get_ui (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_init __gmpf_init __GMP_DECLSPEC void mpf_init (mpf_ptr); #define mpf_init2 __gmpf_init2 __GMP_DECLSPEC void mpf_init2 (mpf_ptr, mp_bitcnt_t); #define mpf_inits __gmpf_inits __GMP_DECLSPEC void mpf_inits (mpf_ptr, ...); #define mpf_init_set __gmpf_init_set __GMP_DECLSPEC void mpf_init_set (mpf_ptr, mpf_srcptr); #define mpf_init_set_d __gmpf_init_set_d __GMP_DECLSPEC void mpf_init_set_d (mpf_ptr, double); #define mpf_init_set_si __gmpf_init_set_si __GMP_DECLSPEC void mpf_init_set_si (mpf_ptr, signed long int); #define mpf_init_set_str __gmpf_init_set_str __GMP_DECLSPEC int mpf_init_set_str (mpf_ptr, const char *, int); #define mpf_init_set_ui __gmpf_init_set_ui __GMP_DECLSPEC void mpf_init_set_ui (mpf_ptr, unsigned long int); #define mpf_inp_str __gmpf_inp_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpf_inp_str (mpf_ptr, FILE *, int); #endif #define mpf_integer_p __gmpf_integer_p __GMP_DECLSPEC int mpf_integer_p (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_mul __gmpf_mul __GMP_DECLSPEC void mpf_mul (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_mul_2exp __gmpf_mul_2exp __GMP_DECLSPEC void mpf_mul_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t); #define mpf_mul_ui __gmpf_mul_ui __GMP_DECLSPEC void mpf_mul_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_neg __gmpf_neg __GMP_DECLSPEC void mpf_neg (mpf_ptr, mpf_srcptr); #define mpf_out_str __gmpf_out_str #ifdef _GMP_H_HAVE_FILE __GMP_DECLSPEC size_t mpf_out_str (FILE *, int, size_t, mpf_srcptr); #endif #define mpf_pow_ui __gmpf_pow_ui __GMP_DECLSPEC void mpf_pow_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_random2 __gmpf_random2 __GMP_DECLSPEC void mpf_random2 (mpf_ptr, mp_size_t, mp_exp_t); #define mpf_reldiff __gmpf_reldiff __GMP_DECLSPEC void mpf_reldiff (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_set __gmpf_set __GMP_DECLSPEC void mpf_set (mpf_ptr, mpf_srcptr); #define mpf_set_d __gmpf_set_d __GMP_DECLSPEC void mpf_set_d (mpf_ptr, double); #define mpf_set_default_prec __gmpf_set_default_prec __GMP_DECLSPEC void mpf_set_default_prec (mp_bitcnt_t) __GMP_NOTHROW; #define mpf_set_prec __gmpf_set_prec __GMP_DECLSPEC void mpf_set_prec (mpf_ptr, mp_bitcnt_t); #define mpf_set_prec_raw __gmpf_set_prec_raw __GMP_DECLSPEC void mpf_set_prec_raw (mpf_ptr, mp_bitcnt_t) __GMP_NOTHROW; #define mpf_set_q __gmpf_set_q __GMP_DECLSPEC void mpf_set_q (mpf_ptr, mpq_srcptr); #define mpf_set_si __gmpf_set_si __GMP_DECLSPEC void mpf_set_si (mpf_ptr, signed long int); #define mpf_set_str __gmpf_set_str __GMP_DECLSPEC int mpf_set_str (mpf_ptr, const char *, int); #define mpf_set_ui __gmpf_set_ui __GMP_DECLSPEC void mpf_set_ui (mpf_ptr, unsigned long int); #define mpf_set_z __gmpf_set_z __GMP_DECLSPEC void mpf_set_z (mpf_ptr, mpz_srcptr); #define mpf_size __gmpf_size __GMP_DECLSPEC size_t mpf_size (mpf_srcptr) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpf_sqrt __gmpf_sqrt __GMP_DECLSPEC void mpf_sqrt (mpf_ptr, mpf_srcptr); #define mpf_sqrt_ui __gmpf_sqrt_ui __GMP_DECLSPEC void mpf_sqrt_ui (mpf_ptr, unsigned long int); #define mpf_sub __gmpf_sub __GMP_DECLSPEC void mpf_sub (mpf_ptr, mpf_srcptr, mpf_srcptr); #define mpf_sub_ui __gmpf_sub_ui __GMP_DECLSPEC void mpf_sub_ui (mpf_ptr, mpf_srcptr, unsigned long int); #define mpf_swap __gmpf_swap __GMP_DECLSPEC void mpf_swap (mpf_ptr, mpf_ptr) __GMP_NOTHROW; #define mpf_trunc __gmpf_trunc __GMP_DECLSPEC void mpf_trunc (mpf_ptr, mpf_srcptr); #define mpf_ui_div __gmpf_ui_div __GMP_DECLSPEC void mpf_ui_div (mpf_ptr, unsigned long int, mpf_srcptr); #define mpf_ui_sub __gmpf_ui_sub __GMP_DECLSPEC void mpf_ui_sub (mpf_ptr, unsigned long int, mpf_srcptr); #define mpf_urandomb __gmpf_urandomb __GMP_DECLSPEC void mpf_urandomb (mpf_ptr, gmp_randstate_ptr, mp_bitcnt_t); /************ Low level positive-integer (i.e. N) routines. ************/ /* This is ugly, but we need to make user calls reach the prefixed function. */ #define mpn_add __MPN(add) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_add) __GMP_DECLSPEC mp_limb_t mpn_add (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #endif #define mpn_add_1 __MPN(add_1) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_add_1) __GMP_DECLSPEC mp_limb_t mpn_add_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t) __GMP_NOTHROW; #endif #define mpn_add_n __MPN(add_n) __GMP_DECLSPEC mp_limb_t mpn_add_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_addmul_1 __MPN(addmul_1) __GMP_DECLSPEC mp_limb_t mpn_addmul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_cmp __MPN(cmp) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_cmp) __GMP_DECLSPEC int mpn_cmp (mp_srcptr, mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpn_zero_p __MPN(zero_p) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_zero_p) __GMP_DECLSPEC int mpn_zero_p (mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #endif #define mpn_divexact_1 __MPN(divexact_1) __GMP_DECLSPEC void mpn_divexact_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_divexact_by3(dst,src,size) \ mpn_divexact_by3c (dst, src, size, __GMP_CAST (mp_limb_t, 0)) #define mpn_divexact_by3c __MPN(divexact_by3c) __GMP_DECLSPEC mp_limb_t mpn_divexact_by3c (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_divmod_1(qp,np,nsize,dlimb) \ mpn_divrem_1 (qp, __GMP_CAST (mp_size_t, 0), np, nsize, dlimb) #define mpn_divrem __MPN(divrem) __GMP_DECLSPEC mp_limb_t mpn_divrem (mp_ptr, mp_size_t, mp_ptr, mp_size_t, mp_srcptr, mp_size_t); #define mpn_divrem_1 __MPN(divrem_1) __GMP_DECLSPEC mp_limb_t mpn_divrem_1 (mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_divrem_2 __MPN(divrem_2) __GMP_DECLSPEC mp_limb_t mpn_divrem_2 (mp_ptr, mp_size_t, mp_ptr, mp_size_t, mp_srcptr); #define mpn_div_qr_1 __MPN(div_qr_1) __GMP_DECLSPEC mp_limb_t mpn_div_qr_1 (mp_ptr, mp_limb_t *, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_div_qr_2 __MPN(div_qr_2) __GMP_DECLSPEC mp_limb_t mpn_div_qr_2 (mp_ptr, mp_ptr, mp_srcptr, mp_size_t, mp_srcptr); #define mpn_gcd __MPN(gcd) __GMP_DECLSPEC mp_size_t mpn_gcd (mp_ptr, mp_ptr, mp_size_t, mp_ptr, mp_size_t); #define mpn_gcd_11 __MPN(gcd_11) __GMP_DECLSPEC mp_limb_t mpn_gcd_11 (mp_limb_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_gcd_1 __MPN(gcd_1) __GMP_DECLSPEC mp_limb_t mpn_gcd_1 (mp_srcptr, mp_size_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_gcdext_1 __MPN(gcdext_1) __GMP_DECLSPEC mp_limb_t mpn_gcdext_1 (mp_limb_signed_t *, mp_limb_signed_t *, mp_limb_t, mp_limb_t); #define mpn_gcdext __MPN(gcdext) __GMP_DECLSPEC mp_size_t mpn_gcdext (mp_ptr, mp_ptr, mp_size_t *, mp_ptr, mp_size_t, mp_ptr, mp_size_t); #define mpn_get_str __MPN(get_str) __GMP_DECLSPEC size_t mpn_get_str (unsigned char *, int, mp_ptr, mp_size_t); #define mpn_hamdist __MPN(hamdist) __GMP_DECLSPEC mp_bitcnt_t mpn_hamdist (mp_srcptr, mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpn_lshift __MPN(lshift) __GMP_DECLSPEC mp_limb_t mpn_lshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int); #define mpn_mod_1 __MPN(mod_1) __GMP_DECLSPEC mp_limb_t mpn_mod_1 (mp_srcptr, mp_size_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_mul __MPN(mul) __GMP_DECLSPEC mp_limb_t mpn_mul (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #define mpn_mul_1 __MPN(mul_1) __GMP_DECLSPEC mp_limb_t mpn_mul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_mul_n __MPN(mul_n) __GMP_DECLSPEC void mpn_mul_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_sqr __MPN(sqr) __GMP_DECLSPEC void mpn_sqr (mp_ptr, mp_srcptr, mp_size_t); #define mpn_neg __MPN(neg) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_neg) __GMP_DECLSPEC mp_limb_t mpn_neg (mp_ptr, mp_srcptr, mp_size_t); #endif #define mpn_com __MPN(com) __GMP_DECLSPEC void mpn_com (mp_ptr, mp_srcptr, mp_size_t); #define mpn_perfect_square_p __MPN(perfect_square_p) __GMP_DECLSPEC int mpn_perfect_square_p (mp_srcptr, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_perfect_power_p __MPN(perfect_power_p) __GMP_DECLSPEC int mpn_perfect_power_p (mp_srcptr, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_popcount __MPN(popcount) __GMP_DECLSPEC mp_bitcnt_t mpn_popcount (mp_srcptr, mp_size_t) __GMP_NOTHROW __GMP_ATTRIBUTE_PURE; #define mpn_pow_1 __MPN(pow_1) __GMP_DECLSPEC mp_size_t mpn_pow_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr); /* undocumented now, but retained here for upward compatibility */ #define mpn_preinv_mod_1 __MPN(preinv_mod_1) __GMP_DECLSPEC mp_limb_t mpn_preinv_mod_1 (mp_srcptr, mp_size_t, mp_limb_t, mp_limb_t) __GMP_ATTRIBUTE_PURE; #define mpn_random __MPN(random) __GMP_DECLSPEC void mpn_random (mp_ptr, mp_size_t); #define mpn_random2 __MPN(random2) __GMP_DECLSPEC void mpn_random2 (mp_ptr, mp_size_t); #define mpn_rshift __MPN(rshift) __GMP_DECLSPEC mp_limb_t mpn_rshift (mp_ptr, mp_srcptr, mp_size_t, unsigned int); #define mpn_scan0 __MPN(scan0) __GMP_DECLSPEC mp_bitcnt_t mpn_scan0 (mp_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE; #define mpn_scan1 __MPN(scan1) __GMP_DECLSPEC mp_bitcnt_t mpn_scan1 (mp_srcptr, mp_bitcnt_t) __GMP_ATTRIBUTE_PURE; #define mpn_set_str __MPN(set_str) __GMP_DECLSPEC mp_size_t mpn_set_str (mp_ptr, const unsigned char *, size_t, int); #define mpn_sizeinbase __MPN(sizeinbase) __GMP_DECLSPEC size_t mpn_sizeinbase (mp_srcptr, mp_size_t, int); #define mpn_sqrtrem __MPN(sqrtrem) __GMP_DECLSPEC mp_size_t mpn_sqrtrem (mp_ptr, mp_ptr, mp_srcptr, mp_size_t); #define mpn_sub __MPN(sub) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_sub) __GMP_DECLSPEC mp_limb_t mpn_sub (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #endif #define mpn_sub_1 __MPN(sub_1) #if __GMP_INLINE_PROTOTYPES || defined (__GMP_FORCE_mpn_sub_1) __GMP_DECLSPEC mp_limb_t mpn_sub_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t) __GMP_NOTHROW; #endif #define mpn_sub_n __MPN(sub_n) __GMP_DECLSPEC mp_limb_t mpn_sub_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_submul_1 __MPN(submul_1) __GMP_DECLSPEC mp_limb_t mpn_submul_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t); #define mpn_tdiv_qr __MPN(tdiv_qr) __GMP_DECLSPEC void mpn_tdiv_qr (mp_ptr, mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t); #define mpn_and_n __MPN(and_n) __GMP_DECLSPEC void mpn_and_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_andn_n __MPN(andn_n) __GMP_DECLSPEC void mpn_andn_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_nand_n __MPN(nand_n) __GMP_DECLSPEC void mpn_nand_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_ior_n __MPN(ior_n) __GMP_DECLSPEC void mpn_ior_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_iorn_n __MPN(iorn_n) __GMP_DECLSPEC void mpn_iorn_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_nior_n __MPN(nior_n) __GMP_DECLSPEC void mpn_nior_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_xor_n __MPN(xor_n) __GMP_DECLSPEC void mpn_xor_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_xnor_n __MPN(xnor_n) __GMP_DECLSPEC void mpn_xnor_n (mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_copyi __MPN(copyi) __GMP_DECLSPEC void mpn_copyi (mp_ptr, mp_srcptr, mp_size_t); #define mpn_copyd __MPN(copyd) __GMP_DECLSPEC void mpn_copyd (mp_ptr, mp_srcptr, mp_size_t); #define mpn_zero __MPN(zero) __GMP_DECLSPEC void mpn_zero (mp_ptr, mp_size_t); #define mpn_cnd_add_n __MPN(cnd_add_n) __GMP_DECLSPEC mp_limb_t mpn_cnd_add_n (mp_limb_t, mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_cnd_sub_n __MPN(cnd_sub_n) __GMP_DECLSPEC mp_limb_t mpn_cnd_sub_n (mp_limb_t, mp_ptr, mp_srcptr, mp_srcptr, mp_size_t); #define mpn_sec_add_1 __MPN(sec_add_1) __GMP_DECLSPEC mp_limb_t mpn_sec_add_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr); #define mpn_sec_add_1_itch __MPN(sec_add_1_itch) __GMP_DECLSPEC mp_size_t mpn_sec_add_1_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_sub_1 __MPN(sec_sub_1) __GMP_DECLSPEC mp_limb_t mpn_sec_sub_1 (mp_ptr, mp_srcptr, mp_size_t, mp_limb_t, mp_ptr); #define mpn_sec_sub_1_itch __MPN(sec_sub_1_itch) __GMP_DECLSPEC mp_size_t mpn_sec_sub_1_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_cnd_swap __MPN(cnd_swap) __GMP_DECLSPEC void mpn_cnd_swap (mp_limb_t, volatile mp_limb_t *, volatile mp_limb_t *, mp_size_t); #define mpn_sec_mul __MPN(sec_mul) __GMP_DECLSPEC void mpn_sec_mul (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_mul_itch __MPN(sec_mul_itch) __GMP_DECLSPEC mp_size_t mpn_sec_mul_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_sqr __MPN(sec_sqr) __GMP_DECLSPEC void mpn_sec_sqr (mp_ptr, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_sqr_itch __MPN(sec_sqr_itch) __GMP_DECLSPEC mp_size_t mpn_sec_sqr_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_powm __MPN(sec_powm) __GMP_DECLSPEC void mpn_sec_powm (mp_ptr, mp_srcptr, mp_size_t, mp_srcptr, mp_bitcnt_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_powm_itch __MPN(sec_powm_itch) __GMP_DECLSPEC mp_size_t mpn_sec_powm_itch (mp_size_t, mp_bitcnt_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_tabselect __MPN(sec_tabselect) __GMP_DECLSPEC void mpn_sec_tabselect (volatile mp_limb_t *, volatile const mp_limb_t *, mp_size_t, mp_size_t, mp_size_t); #define mpn_sec_div_qr __MPN(sec_div_qr) __GMP_DECLSPEC mp_limb_t mpn_sec_div_qr (mp_ptr, mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_div_qr_itch __MPN(sec_div_qr_itch) __GMP_DECLSPEC mp_size_t mpn_sec_div_qr_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_div_r __MPN(sec_div_r) __GMP_DECLSPEC void mpn_sec_div_r (mp_ptr, mp_size_t, mp_srcptr, mp_size_t, mp_ptr); #define mpn_sec_div_r_itch __MPN(sec_div_r_itch) __GMP_DECLSPEC mp_size_t mpn_sec_div_r_itch (mp_size_t, mp_size_t) __GMP_ATTRIBUTE_PURE; #define mpn_sec_invert __MPN(sec_invert) __GMP_DECLSPEC int mpn_sec_invert (mp_ptr, mp_ptr, mp_srcptr, mp_size_t, mp_bitcnt_t, mp_ptr); #define mpn_sec_invert_itch __MPN(sec_invert_itch) __GMP_DECLSPEC mp_size_t mpn_sec_invert_itch (mp_size_t) __GMP_ATTRIBUTE_PURE; /**************** mpz inlines ****************/ /* The following are provided as inlines where possible, but always exist as library functions too, for binary compatibility. Within gmp itself this inlining generally isn't relied on, since it doesn't get done for all compilers, whereas if something is worth inlining then it's worth arranging always. There are two styles of inlining here. When the same bit of code is wanted for the inline as for the library version, then __GMP_FORCE_foo arranges for that code to be emitted and the __GMP_EXTERN_INLINE directive suppressed, eg. mpz_fits_uint_p. When a different bit of code is wanted for the inline than for the library version, then __GMP_FORCE_foo arranges the inline to be suppressed, eg. mpz_abs. */ #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpz_abs) __GMP_EXTERN_INLINE void mpz_abs (mpz_ptr __gmp_w, mpz_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpz_set (__gmp_w, __gmp_u); __gmp_w->_mp_size = __GMP_ABS (__gmp_w->_mp_size); } #endif #if GMP_NAIL_BITS == 0 #define __GMPZ_FITS_UTYPE_P(z,maxval) \ mp_size_t __gmp_n = z->_mp_size; \ mp_ptr __gmp_p = z->_mp_d; \ return (__gmp_n == 0 || (__gmp_n == 1 && __gmp_p[0] <= maxval)); #else #define __GMPZ_FITS_UTYPE_P(z,maxval) \ mp_size_t __gmp_n = z->_mp_size; \ mp_ptr __gmp_p = z->_mp_d; \ return (__gmp_n == 0 || (__gmp_n == 1 && __gmp_p[0] <= maxval) \ || (__gmp_n == 2 && __gmp_p[1] <= ((mp_limb_t) maxval >> GMP_NUMB_BITS))); #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_uint_p) #if ! defined (__GMP_FORCE_mpz_fits_uint_p) __GMP_EXTERN_INLINE #endif int mpz_fits_uint_p (mpz_srcptr __gmp_z) __GMP_NOTHROW { __GMPZ_FITS_UTYPE_P (__gmp_z, UINT_MAX); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_ulong_p) #if ! defined (__GMP_FORCE_mpz_fits_ulong_p) __GMP_EXTERN_INLINE #endif int mpz_fits_ulong_p (mpz_srcptr __gmp_z) __GMP_NOTHROW { __GMPZ_FITS_UTYPE_P (__gmp_z, ULONG_MAX); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_fits_ushort_p) #if ! defined (__GMP_FORCE_mpz_fits_ushort_p) __GMP_EXTERN_INLINE #endif int mpz_fits_ushort_p (mpz_srcptr __gmp_z) __GMP_NOTHROW { __GMPZ_FITS_UTYPE_P (__gmp_z, USHRT_MAX); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_get_ui) #if ! defined (__GMP_FORCE_mpz_get_ui) __GMP_EXTERN_INLINE #endif unsigned long mpz_get_ui (mpz_srcptr __gmp_z) __GMP_NOTHROW { mp_ptr __gmp_p = __gmp_z->_mp_d; mp_size_t __gmp_n = __gmp_z->_mp_size; mp_limb_t __gmp_l = __gmp_p[0]; /* This is a "#if" rather than a plain "if" so as to avoid gcc warnings about "<< GMP_NUMB_BITS" exceeding the type size, and to avoid Borland C++ 6.0 warnings about condition always true for something like "ULONG_MAX < GMP_NUMB_MASK". */ #if GMP_NAIL_BITS == 0 || defined (_LONG_LONG_LIMB) /* limb==long and no nails, or limb==longlong, one limb is enough */ return (__gmp_n != 0 ? __gmp_l : 0); #else /* limb==long and nails, need two limbs when available */ __gmp_n = __GMP_ABS (__gmp_n); if (__gmp_n <= 1) return (__gmp_n != 0 ? __gmp_l : 0); else return __gmp_l + (__gmp_p[1] << GMP_NUMB_BITS); #endif } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_getlimbn) #if ! defined (__GMP_FORCE_mpz_getlimbn) __GMP_EXTERN_INLINE #endif mp_limb_t mpz_getlimbn (mpz_srcptr __gmp_z, mp_size_t __gmp_n) __GMP_NOTHROW { mp_limb_t __gmp_result = 0; if (__GMP_LIKELY (__gmp_n >= 0 && __gmp_n < __GMP_ABS (__gmp_z->_mp_size))) __gmp_result = __gmp_z->_mp_d[__gmp_n]; return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpz_neg) __GMP_EXTERN_INLINE void mpz_neg (mpz_ptr __gmp_w, mpz_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpz_set (__gmp_w, __gmp_u); __gmp_w->_mp_size = - __gmp_w->_mp_size; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_perfect_square_p) #if ! defined (__GMP_FORCE_mpz_perfect_square_p) __GMP_EXTERN_INLINE #endif int mpz_perfect_square_p (mpz_srcptr __gmp_a) { mp_size_t __gmp_asize; int __gmp_result; __gmp_asize = __gmp_a->_mp_size; __gmp_result = (__gmp_asize >= 0); /* zero is a square, negatives are not */ if (__GMP_LIKELY (__gmp_asize > 0)) __gmp_result = mpn_perfect_square_p (__gmp_a->_mp_d, __gmp_asize); return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_popcount) #if ! defined (__GMP_FORCE_mpz_popcount) __GMP_EXTERN_INLINE #endif mp_bitcnt_t mpz_popcount (mpz_srcptr __gmp_u) __GMP_NOTHROW { mp_size_t __gmp_usize; mp_bitcnt_t __gmp_result; __gmp_usize = __gmp_u->_mp_size; __gmp_result = (__gmp_usize < 0 ? ~ __GMP_CAST (mp_bitcnt_t, 0) : __GMP_CAST (mp_bitcnt_t, 0)); if (__GMP_LIKELY (__gmp_usize > 0)) __gmp_result = mpn_popcount (__gmp_u->_mp_d, __gmp_usize); return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_set_q) #if ! defined (__GMP_FORCE_mpz_set_q) __GMP_EXTERN_INLINE #endif void mpz_set_q (mpz_ptr __gmp_w, mpq_srcptr __gmp_u) { mpz_tdiv_q (__gmp_w, mpq_numref (__gmp_u), mpq_denref (__gmp_u)); } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpz_size) #if ! defined (__GMP_FORCE_mpz_size) __GMP_EXTERN_INLINE #endif size_t mpz_size (mpz_srcptr __gmp_z) __GMP_NOTHROW { return __GMP_ABS (__gmp_z->_mp_size); } #endif /**************** mpq inlines ****************/ #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpq_abs) __GMP_EXTERN_INLINE void mpq_abs (mpq_ptr __gmp_w, mpq_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpq_set (__gmp_w, __gmp_u); __gmp_w->_mp_num._mp_size = __GMP_ABS (__gmp_w->_mp_num._mp_size); } #endif #if defined (__GMP_EXTERN_INLINE) && ! defined (__GMP_FORCE_mpq_neg) __GMP_EXTERN_INLINE void mpq_neg (mpq_ptr __gmp_w, mpq_srcptr __gmp_u) { if (__gmp_w != __gmp_u) mpq_set (__gmp_w, __gmp_u); __gmp_w->_mp_num._mp_size = - __gmp_w->_mp_num._mp_size; } #endif /**************** mpn inlines ****************/ /* The comments with __GMPN_ADD_1 below apply here too. The test for FUNCTION returning 0 should predict well. If it's assumed {yp,ysize} will usually have a random number of bits then the high limb won't be full and a carry out will occur a good deal less than 50% of the time. ysize==0 isn't a documented feature, but is used internally in a few places. Producing cout last stops it using up a register during the main part of the calculation, though gcc (as of 3.0) on an "if (mpn_add (...))" doesn't seem able to move the true and false legs of the conditional up to the two places cout is generated. */ #define __GMPN_AORS(cout, wp, xp, xsize, yp, ysize, FUNCTION, TEST) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x; \ \ /* ASSERT ((ysize) >= 0); */ \ /* ASSERT ((xsize) >= (ysize)); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE2_P (wp, xsize, xp, xsize)); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE2_P (wp, xsize, yp, ysize)); */ \ \ __gmp_i = (ysize); \ if (__gmp_i != 0) \ { \ if (FUNCTION (wp, xp, yp, __gmp_i)) \ { \ do \ { \ if (__gmp_i >= (xsize)) \ { \ (cout) = 1; \ goto __gmp_done; \ } \ __gmp_x = (xp)[__gmp_i]; \ } \ while (TEST); \ } \ } \ if ((wp) != (xp)) \ __GMPN_COPY_REST (wp, xp, xsize, __gmp_i); \ (cout) = 0; \ __gmp_done: \ ; \ } while (0) #define __GMPN_ADD(cout, wp, xp, xsize, yp, ysize) \ __GMPN_AORS (cout, wp, xp, xsize, yp, ysize, mpn_add_n, \ (((wp)[__gmp_i++] = (__gmp_x + 1) & GMP_NUMB_MASK) == 0)) #define __GMPN_SUB(cout, wp, xp, xsize, yp, ysize) \ __GMPN_AORS (cout, wp, xp, xsize, yp, ysize, mpn_sub_n, \ (((wp)[__gmp_i++] = (__gmp_x - 1) & GMP_NUMB_MASK), __gmp_x == 0)) /* The use of __gmp_i indexing is designed to ensure a compile time src==dst remains nice and clear to the compiler, so that __GMPN_COPY_REST can disappear, and the load/add/store gets a chance to become a read-modify-write on CISC CPUs. Alternatives: Using a pair of pointers instead of indexing would be possible, but gcc isn't able to recognise compile-time src==dst in that case, even when the pointers are incremented more or less together. Other compilers would very likely have similar difficulty. gcc could use "if (__builtin_constant_p(src==dst) && src==dst)" or similar to detect a compile-time src==dst. This works nicely on gcc 2.95.x, it's not good on gcc 3.0 where __builtin_constant_p(p==p) seems to be always false, for a pointer p. But the current code form seems good enough for src==dst anyway. gcc on x86 as usual doesn't give particularly good flags handling for the carry/borrow detection. It's tempting to want some multi instruction asm blocks to help it, and this was tried, but in truth there's only a few instructions to save and any gain is all too easily lost by register juggling setting up for the asm. */ #if GMP_NAIL_BITS == 0 #define __GMPN_AORS_1(cout, dst, src, n, v, OP, CB) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x, __gmp_r; \ \ /* ASSERT ((n) >= 1); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, n)); */ \ \ __gmp_x = (src)[0]; \ __gmp_r = __gmp_x OP (v); \ (dst)[0] = __gmp_r; \ if (CB (__gmp_r, __gmp_x, (v))) \ { \ (cout) = 1; \ for (__gmp_i = 1; __gmp_i < (n);) \ { \ __gmp_x = (src)[__gmp_i]; \ __gmp_r = __gmp_x OP 1; \ (dst)[__gmp_i] = __gmp_r; \ ++__gmp_i; \ if (!CB (__gmp_r, __gmp_x, 1)) \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, __gmp_i); \ (cout) = 0; \ break; \ } \ } \ } \ else \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, 1); \ (cout) = 0; \ } \ } while (0) #endif #if GMP_NAIL_BITS >= 1 #define __GMPN_AORS_1(cout, dst, src, n, v, OP, CB) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x, __gmp_r; \ \ /* ASSERT ((n) >= 1); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, n)); */ \ \ __gmp_x = (src)[0]; \ __gmp_r = __gmp_x OP (v); \ (dst)[0] = __gmp_r & GMP_NUMB_MASK; \ if (__gmp_r >> GMP_NUMB_BITS != 0) \ { \ (cout) = 1; \ for (__gmp_i = 1; __gmp_i < (n);) \ { \ __gmp_x = (src)[__gmp_i]; \ __gmp_r = __gmp_x OP 1; \ (dst)[__gmp_i] = __gmp_r & GMP_NUMB_MASK; \ ++__gmp_i; \ if (__gmp_r >> GMP_NUMB_BITS == 0) \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, __gmp_i); \ (cout) = 0; \ break; \ } \ } \ } \ else \ { \ if ((src) != (dst)) \ __GMPN_COPY_REST (dst, src, n, 1); \ (cout) = 0; \ } \ } while (0) #endif #define __GMPN_ADDCB(r,x,y) ((r) < (y)) #define __GMPN_SUBCB(r,x,y) ((x) < (y)) #define __GMPN_ADD_1(cout, dst, src, n, v) \ __GMPN_AORS_1(cout, dst, src, n, v, +, __GMPN_ADDCB) #define __GMPN_SUB_1(cout, dst, src, n, v) \ __GMPN_AORS_1(cout, dst, src, n, v, -, __GMPN_SUBCB) /* Compare {xp,size} and {yp,size}, setting "result" to positive, zero or negative. size==0 is allowed. On random data usually only one limb will need to be examined to get a result, so it's worth having it inline. */ #define __GMPN_CMP(result, xp, yp, size) \ do { \ mp_size_t __gmp_i; \ mp_limb_t __gmp_x, __gmp_y; \ \ /* ASSERT ((size) >= 0); */ \ \ (result) = 0; \ __gmp_i = (size); \ while (--__gmp_i >= 0) \ { \ __gmp_x = (xp)[__gmp_i]; \ __gmp_y = (yp)[__gmp_i]; \ if (__gmp_x != __gmp_y) \ { \ /* Cannot use __gmp_x - __gmp_y, may overflow an "int" */ \ (result) = (__gmp_x > __gmp_y ? 1 : -1); \ break; \ } \ } \ } while (0) #if defined (__GMPN_COPY) && ! defined (__GMPN_COPY_REST) #define __GMPN_COPY_REST(dst, src, size, start) \ do { \ /* ASSERT ((start) >= 0); */ \ /* ASSERT ((start) <= (size)); */ \ __GMPN_COPY ((dst)+(start), (src)+(start), (size)-(start)); \ } while (0) #endif /* Copy {src,size} to {dst,size}, starting at "start". This is designed to keep the indexing dst[j] and src[j] nice and simple for __GMPN_ADD_1, __GMPN_ADD, etc. */ #if ! defined (__GMPN_COPY_REST) #define __GMPN_COPY_REST(dst, src, size, start) \ do { \ mp_size_t __gmp_j; \ /* ASSERT ((size) >= 0); */ \ /* ASSERT ((start) >= 0); */ \ /* ASSERT ((start) <= (size)); */ \ /* ASSERT (MPN_SAME_OR_SEPARATE_P (dst, src, size)); */ \ __GMP_CRAY_Pragma ("_CRI ivdep"); \ for (__gmp_j = (start); __gmp_j < (size); __gmp_j++) \ (dst)[__gmp_j] = (src)[__gmp_j]; \ } while (0) #endif /* Enhancement: Use some of the smarter code from gmp-impl.h. Maybe use mpn_copyi if there's a native version, and if we don't mind demanding binary compatibility for it (on targets which use it). */ #if ! defined (__GMPN_COPY) #define __GMPN_COPY(dst, src, size) __GMPN_COPY_REST (dst, src, size, 0) #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_add) #if ! defined (__GMP_FORCE_mpn_add) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_add (mp_ptr __gmp_wp, mp_srcptr __gmp_xp, mp_size_t __gmp_xsize, mp_srcptr __gmp_yp, mp_size_t __gmp_ysize) { mp_limb_t __gmp_c; __GMPN_ADD (__gmp_c, __gmp_wp, __gmp_xp, __gmp_xsize, __gmp_yp, __gmp_ysize); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_add_1) #if ! defined (__GMP_FORCE_mpn_add_1) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_add_1 (mp_ptr __gmp_dst, mp_srcptr __gmp_src, mp_size_t __gmp_size, mp_limb_t __gmp_n) __GMP_NOTHROW { mp_limb_t __gmp_c; __GMPN_ADD_1 (__gmp_c, __gmp_dst, __gmp_src, __gmp_size, __gmp_n); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_cmp) #if ! defined (__GMP_FORCE_mpn_cmp) __GMP_EXTERN_INLINE #endif int mpn_cmp (mp_srcptr __gmp_xp, mp_srcptr __gmp_yp, mp_size_t __gmp_size) __GMP_NOTHROW { int __gmp_result; __GMPN_CMP (__gmp_result, __gmp_xp, __gmp_yp, __gmp_size); return __gmp_result; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_zero_p) #if ! defined (__GMP_FORCE_mpn_zero_p) __GMP_EXTERN_INLINE #endif int mpn_zero_p (mp_srcptr __gmp_p, mp_size_t __gmp_n) __GMP_NOTHROW { /* if (__GMP_LIKELY (__gmp_n > 0)) */ do { if (__gmp_p[--__gmp_n] != 0) return 0; } while (__gmp_n != 0); return 1; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_sub) #if ! defined (__GMP_FORCE_mpn_sub) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_sub (mp_ptr __gmp_wp, mp_srcptr __gmp_xp, mp_size_t __gmp_xsize, mp_srcptr __gmp_yp, mp_size_t __gmp_ysize) { mp_limb_t __gmp_c; __GMPN_SUB (__gmp_c, __gmp_wp, __gmp_xp, __gmp_xsize, __gmp_yp, __gmp_ysize); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_sub_1) #if ! defined (__GMP_FORCE_mpn_sub_1) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_sub_1 (mp_ptr __gmp_dst, mp_srcptr __gmp_src, mp_size_t __gmp_size, mp_limb_t __gmp_n) __GMP_NOTHROW { mp_limb_t __gmp_c; __GMPN_SUB_1 (__gmp_c, __gmp_dst, __gmp_src, __gmp_size, __gmp_n); return __gmp_c; } #endif #if defined (__GMP_EXTERN_INLINE) || defined (__GMP_FORCE_mpn_neg) #if ! defined (__GMP_FORCE_mpn_neg) __GMP_EXTERN_INLINE #endif mp_limb_t mpn_neg (mp_ptr __gmp_rp, mp_srcptr __gmp_up, mp_size_t __gmp_n) { while (*__gmp_up == 0) /* Low zero limbs are unchanged by negation. */ { *__gmp_rp = 0; if (!--__gmp_n) /* All zero */ return 0; ++__gmp_up; ++__gmp_rp; } *__gmp_rp = (- *__gmp_up) & GMP_NUMB_MASK; if (--__gmp_n) /* Higher limbs get complemented. */ mpn_com (++__gmp_rp, ++__gmp_up, __gmp_n); return 1; } #endif #if defined (__cplusplus) } #endif /* Allow faster testing for negative, zero, and positive. */ #define mpz_sgn(Z) ((Z)->_mp_size < 0 ? -1 : (Z)->_mp_size > 0) #define mpf_sgn(F) ((F)->_mp_size < 0 ? -1 : (F)->_mp_size > 0) #define mpq_sgn(Q) ((Q)->_mp_num._mp_size < 0 ? -1 : (Q)->_mp_num._mp_size > 0) /* When using GCC, optimize certain common comparisons. */ #if defined (__GNUC__) && __GNUC__ >= 2 #define mpz_cmp_ui(Z,UI) \ (__builtin_constant_p (UI) && (UI) == 0 \ ? mpz_sgn (Z) : _mpz_cmp_ui (Z,UI)) #define mpz_cmp_si(Z,SI) \ (__builtin_constant_p ((SI) >= 0) && (SI) >= 0 \ ? mpz_cmp_ui (Z, __GMP_CAST (unsigned long, SI)) \ : _mpz_cmp_si (Z,SI)) #define mpq_cmp_ui(Q,NUI,DUI) \ (__builtin_constant_p (NUI) && (NUI) == 0 ? mpq_sgn (Q) \ : __builtin_constant_p ((NUI) == (DUI)) && (NUI) == (DUI) \ ? mpz_cmp (mpq_numref (Q), mpq_denref (Q)) \ : _mpq_cmp_ui (Q,NUI,DUI)) #define mpq_cmp_si(q,n,d) \ (__builtin_constant_p ((n) >= 0) && (n) >= 0 \ ? mpq_cmp_ui (q, __GMP_CAST (unsigned long, n), d) \ : _mpq_cmp_si (q, n, d)) #else #define mpz_cmp_ui(Z,UI) _mpz_cmp_ui (Z,UI) #define mpz_cmp_si(Z,UI) _mpz_cmp_si (Z,UI) #define mpq_cmp_ui(Q,NUI,DUI) _mpq_cmp_ui (Q,NUI,DUI) #define mpq_cmp_si(q,n,d) _mpq_cmp_si(q,n,d) #endif /* Using "&" rather than "&&" means these can come out branch-free. Every mpz_t has at least one limb allocated, so fetching the low limb is always allowed. */ #define mpz_odd_p(z) (((z)->_mp_size != 0) & __GMP_CAST (int, (z)->_mp_d[0])) #define mpz_even_p(z) (! mpz_odd_p (z)) /**************** C++ routines ****************/ #ifdef __cplusplus __GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpz_srcptr); __GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpq_srcptr); __GMP_DECLSPEC_XX std::ostream& operator<< (std::ostream &, mpf_srcptr); __GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpz_ptr); __GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpq_ptr); __GMP_DECLSPEC_XX std::istream& operator>> (std::istream &, mpf_ptr); #endif /* Source-level compatibility with GMP 2 and earlier. */ #define mpn_divmod(qp,np,nsize,dp,dsize) \ mpn_divrem (qp, __GMP_CAST (mp_size_t, 0), np, nsize, dp, dsize) /* Source-level compatibility with GMP 1. */ #define mpz_mdiv mpz_fdiv_q #define mpz_mdivmod mpz_fdiv_qr #define mpz_mmod mpz_fdiv_r #define mpz_mdiv_ui mpz_fdiv_q_ui #define mpz_mdivmod_ui(q,r,n,d) \ (((r) == 0) ? mpz_fdiv_q_ui (q,n,d) : mpz_fdiv_qr_ui (q,r,n,d)) #define mpz_mmod_ui(r,n,d) \ (((r) == 0) ? mpz_fdiv_ui (n,d) : mpz_fdiv_r_ui (r,n,d)) /* Useful synonyms, but not quite compatible with GMP 1. */ #define mpz_div mpz_fdiv_q #define mpz_divmod mpz_fdiv_qr #define mpz_div_ui mpz_fdiv_q_ui #define mpz_divmod_ui mpz_fdiv_qr_ui #define mpz_div_2exp mpz_fdiv_q_2exp #define mpz_mod_2exp mpz_fdiv_r_2exp enum { GMP_ERROR_NONE = 0, GMP_ERROR_UNSUPPORTED_ARGUMENT = 1, GMP_ERROR_DIVISION_BY_ZERO = 2, GMP_ERROR_SQRT_OF_NEGATIVE = 4, GMP_ERROR_INVALID_ARGUMENT = 8, GMP_ERROR_MPZ_OVERFLOW = 16 }; /* Define CC and CFLAGS which were used to build this version of GMP */ #define __GMP_CC "x86_64-w64-mingw32-gcc" #define __GMP_CFLAGS "-O2 -pedantic -fomit-frame-pointer -m64 -mtune=k8 -march=k8" /* Major version number is the value of __GNU_MP__ too, above. */ #define __GNU_MP_VERSION 6 #define __GNU_MP_VERSION_MINOR 3 #define __GNU_MP_VERSION_PATCHLEVEL 0 #define __GNU_MP_RELEASE (__GNU_MP_VERSION * 10000 + __GNU_MP_VERSION_MINOR * 100 + __GNU_MP_VERSION_PATCHLEVEL) #define __GMP_H__ #endif /* __GMP_H__ */ ================================================ FILE: thirdparty/64/include/gnutls/abstract.h ================================================ /* * Copyright (C) 2010-2012 Free Software Foundation, Inc. * Copyright (C) 2015-2017 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_ABSTRACT_H #define GNUTLS_ABSTRACT_H #include #include #include #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* Public key operations */ #define GNUTLS_PUBKEY_VERIFY_FLAG_TLS_RSA GNUTLS_PUBKEY_VERIFY_FLAG_TLS1_RSA /** * gnutls_pubkey_flags: * @GNUTLS_PUBKEY_DISABLE_CALLBACKS: The following flag disables call to PIN callbacks. Only * relevant to TPM keys. * @GNUTLS_PUBKEY_GET_OPENPGP_FINGERPRINT: request an OPENPGP fingerprint instead of the default. * * Enumeration of different certificate import flags. */ typedef enum gnutls_pubkey_flags { GNUTLS_PUBKEY_DISABLE_CALLBACKS = 1 << 2, GNUTLS_PUBKEY_GET_OPENPGP_FINGERPRINT = 1 << 3 } gnutls_pubkey_flags_t; /** * gnutls_abstract_export_flags: * @GNUTLS_EXPORT_FLAG_NO_LZ: do not prepend a leading zero to exported values * * Enumeration of different certificate import flags. */ typedef enum gnutls_abstract_export_flags { GNUTLS_EXPORT_FLAG_NO_LZ = 1 } gnutls_abstract_export_flags_t; #define GNUTLS_PUBKEY_VERIFY_FLAG_TLS1_RSA GNUTLS_VERIFY_USE_TLS1_RSA typedef int (*gnutls_privkey_sign_func) (gnutls_privkey_t key, void *userdata, const gnutls_datum_t *raw_data, gnutls_datum_t * signature); typedef int (*gnutls_privkey_decrypt_func) (gnutls_privkey_t key, void *userdata, const gnutls_datum_t *ciphertext, gnutls_datum_t * plaintext); typedef int (*gnutls_privkey_decrypt_func2) (gnutls_privkey_t key, void *userdata, const gnutls_datum_t *ciphertext, unsigned char * plaintext, size_t plaintext_size); /* to be called to sign pre-hashed data. The input will be * the output of the hash (such as SHA256) corresponding to * the signature algorithm. The algorithm GNUTLS_SIGN_RSA_RAW * will be provided when RSA PKCS#1 DigestInfo structure is provided * as data (when this is called from a TLS 1.0 or 1.1 session). */ typedef int (*gnutls_privkey_sign_hash_func) (gnutls_privkey_t key, gnutls_sign_algorithm_t algo, void *userdata, unsigned int flags, const gnutls_datum_t *hash, gnutls_datum_t * signature); /* to be called to sign data. The input data will be * the data to be signed (and hashed), with the provided * signature algorithm. This function is used for algorithms * like ed25519 which cannot take pre-hashed data as input. */ typedef int (*gnutls_privkey_sign_data_func) (gnutls_privkey_t key, gnutls_sign_algorithm_t algo, void *userdata, unsigned int flags, const gnutls_datum_t *data, gnutls_datum_t * signature); typedef void (*gnutls_privkey_deinit_func) (gnutls_privkey_t key, void *userdata); #define GNUTLS_SIGN_ALGO_TO_FLAGS(sig) (unsigned int)((sig)<<20) #define GNUTLS_FLAGS_TO_SIGN_ALGO(flags) (unsigned int)((flags)>>20) /* Should return the public key algorithm (gnutls_pk_algorithm_t) */ #define GNUTLS_PRIVKEY_INFO_PK_ALGO 1 /* Should return the preferred signature algorithm (gnutls_sign_algorithm_t) or 0. */ #define GNUTLS_PRIVKEY_INFO_SIGN_ALGO (1<<1) /* Should return true (1) or false (0) if the provided sign algorithm * (obtained with GNUTLS_FLAGS_TO_SIGN_ALGO) is supported. */ #define GNUTLS_PRIVKEY_INFO_HAVE_SIGN_ALGO (1<<2) /* Should return the number of bits of the public key algorithm (required for RSA-PSS) * It is the value that should be returned by gnutls_pubkey_get_pk_algorithm() */ #define GNUTLS_PRIVKEY_INFO_PK_ALGO_BITS (1<<3) /* returns information on the public key associated with userdata */ typedef int (*gnutls_privkey_info_func) (gnutls_privkey_t key, unsigned int flags, void *userdata); int gnutls_pubkey_init(gnutls_pubkey_t * key); void gnutls_pubkey_deinit(gnutls_pubkey_t key); int gnutls_pubkey_verify_params(gnutls_pubkey_t key); void gnutls_pubkey_set_pin_function(gnutls_pubkey_t key, gnutls_pin_callback_t fn, void *userdata); int gnutls_pubkey_get_pk_algorithm(gnutls_pubkey_t key, unsigned int *bits); int gnutls_pubkey_set_spki(gnutls_pubkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_pubkey_get_spki(gnutls_pubkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_pubkey_import_x509(gnutls_pubkey_t key, gnutls_x509_crt_t crt, unsigned int flags); int gnutls_pubkey_import_x509_crq(gnutls_pubkey_t key, gnutls_x509_crq_t crq, unsigned int flags); int gnutls_pubkey_import_pkcs11(gnutls_pubkey_t key, gnutls_pkcs11_obj_t obj, unsigned int flags); int gnutls_pubkey_import_openpgp(gnutls_pubkey_t key, gnutls_openpgp_crt_t crt, unsigned int flags); int gnutls_pubkey_import_openpgp_raw(gnutls_pubkey_t pkey, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format, const gnutls_openpgp_keyid_t keyid, unsigned int flags); int gnutls_pubkey_import_x509_raw(gnutls_pubkey_t pkey, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pubkey_import_privkey(gnutls_pubkey_t key, gnutls_privkey_t pkey, unsigned int usage, unsigned int flags); int gnutls_pubkey_import_tpm_url(gnutls_pubkey_t pkey, const char *url, const char *srk_password, unsigned int flags); int gnutls_pubkey_import_url(gnutls_pubkey_t key, const char *url, unsigned int flags); int gnutls_pubkey_import_tpm_raw(gnutls_pubkey_t pkey, const gnutls_datum_t * fdata, gnutls_tpmkey_fmt_t format, const char *srk_password, unsigned int flags); int gnutls_pubkey_get_preferred_hash_algorithm(gnutls_pubkey_t key, gnutls_digest_algorithm_t * hash, unsigned int *mand); #define gnutls_pubkey_get_pk_rsa_raw gnutls_pubkey_export_rsa_raw int gnutls_pubkey_export_rsa_raw(gnutls_pubkey_t key, gnutls_datum_t * m, gnutls_datum_t * e); int gnutls_pubkey_export_rsa_raw2(gnutls_pubkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, unsigned flags); #define gnutls_pubkey_get_pk_dsa_raw gnutls_pubkey_export_dsa_raw int gnutls_pubkey_export_dsa_raw(gnutls_pubkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y); int gnutls_pubkey_export_dsa_raw2(gnutls_pubkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, unsigned flags); int gnutls_pubkey_export_ecc_raw2(gnutls_pubkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, unsigned flags); int gnutls_pubkey_export_gost_raw2(gnutls_pubkey_t key, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t * paramset, gnutls_datum_t * x, gnutls_datum_t * y, unsigned int flags); #define gnutls_pubkey_get_pk_ecc_raw gnutls_pubkey_export_ecc_raw int gnutls_pubkey_export_ecc_raw(gnutls_pubkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y); #define gnutls_pubkey_get_pk_ecc_x962 gnutls_pubkey_export_ecc_x962 int gnutls_pubkey_export_ecc_x962(gnutls_pubkey_t key, gnutls_datum_t * parameters, gnutls_datum_t * ecpoint); int gnutls_pubkey_export(gnutls_pubkey_t key, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_pubkey_export2(gnutls_pubkey_t key, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_pubkey_get_key_id(gnutls_pubkey_t key, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_pubkey_get_openpgp_key_id(gnutls_pubkey_t key, unsigned int flags, unsigned char *output_data, size_t * output_data_size, unsigned int *subkey); int gnutls_pubkey_get_key_usage(gnutls_pubkey_t key, unsigned int *usage); int gnutls_pubkey_set_key_usage(gnutls_pubkey_t key, unsigned int usage); int gnutls_pubkey_import(gnutls_pubkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); #define gnutls_pubkey_import_pkcs11_url(key, url, flags) gnutls_pubkey_import_url(key, url, flags) int gnutls_pubkey_import_dsa_raw(gnutls_pubkey_t key, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * g, const gnutls_datum_t * y); int gnutls_pubkey_import_rsa_raw(gnutls_pubkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e); int gnutls_pubkey_import_ecc_x962(gnutls_pubkey_t key, const gnutls_datum_t * parameters, const gnutls_datum_t * ecpoint); int gnutls_pubkey_import_ecc_raw(gnutls_pubkey_t key, gnutls_ecc_curve_t curve, const gnutls_datum_t * x, const gnutls_datum_t * y); int gnutls_pubkey_import_gost_raw(gnutls_pubkey_t key, gnutls_ecc_curve_t curve, gnutls_digest_algorithm_t digest, gnutls_gost_paramset_t paramset, const gnutls_datum_t * x, const gnutls_datum_t * y); int gnutls_pubkey_encrypt_data(gnutls_pubkey_t key, unsigned int flags, const gnutls_datum_t * plaintext, gnutls_datum_t * ciphertext); int gnutls_x509_crt_set_pubkey(gnutls_x509_crt_t crt, gnutls_pubkey_t key); int gnutls_x509_crq_set_pubkey(gnutls_x509_crq_t crq, gnutls_pubkey_t key); int gnutls_pubkey_verify_hash2(gnutls_pubkey_t key, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * hash, const gnutls_datum_t * signature); int gnutls_pubkey_verify_data2(gnutls_pubkey_t pubkey, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * data, const gnutls_datum_t * signature); /* Private key operations */ int gnutls_privkey_init(gnutls_privkey_t * key); void gnutls_privkey_deinit(gnutls_privkey_t key); /* macros to allow specifying a subgroup and group size in gnutls_privkey_generate() * and gnutls_x509_privkey_generate() */ #define GNUTLS_SUBGROUP_TO_BITS(group, subgroup) (unsigned int)((subgroup<<16)|(group)) #define GNUTLS_BITS_TO_SUBGROUP(bits) ((bits >> 16) & 0xFFFF) #define GNUTLS_BITS_TO_GROUP(bits) (bits & 0xFFFF) #define GNUTLS_BITS_HAVE_SUBGROUP(bits) ((bits) & 0xFFFF0000) int gnutls_privkey_generate (gnutls_privkey_t key, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags); int gnutls_privkey_generate2(gnutls_privkey_t pkey, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags, const gnutls_keygen_data_st *data, unsigned data_size); int gnutls_privkey_set_spki(gnutls_privkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_privkey_get_spki(gnutls_privkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_privkey_verify_seed(gnutls_privkey_t key, gnutls_digest_algorithm_t, const void *seed, size_t seed_size); int gnutls_privkey_get_seed(gnutls_privkey_t key, gnutls_digest_algorithm_t*, void *seed, size_t *seed_size); int gnutls_privkey_verify_params(gnutls_privkey_t key); void gnutls_privkey_set_flags(gnutls_privkey_t key, unsigned int flags); void gnutls_privkey_set_pin_function (gnutls_privkey_t key, gnutls_pin_callback_t fn, void *userdata); int gnutls_privkey_get_pk_algorithm(gnutls_privkey_t key, unsigned int *bits); gnutls_privkey_type_t gnutls_privkey_get_type(gnutls_privkey_t key); int gnutls_privkey_status(gnutls_privkey_t key); /** * gnutls_privkey_flags: * @GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA: Make an RSA signature on the hashed data as in the TLS protocol. * @GNUTLS_PRIVKEY_SIGN_FLAG_RSA_PSS: Make an RSA signature on the hashed data with the PSS padding. * @GNUTLS_PRIVKEY_FLAG_REPRODUCIBLE: Make a signature on the hashed data with reproducible parameters. * For RSA-PSS, that means to use empty salt instead of random value. To * verify a signature created using this flag, the corresponding SPKI needs * to be set on the public key. Use gnutls_pubkey_set_spki() for that. * For ECDSA/DSA, it uses the deterministic construction of random parameter * according to RFC 6979. Note that this only supports the NIST curves and DSA * subgroup bits up to 512. * @GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE: When importing a private key, automatically * release it when the structure it was imported is released. * @GNUTLS_PRIVKEY_IMPORT_COPY: Copy required values during import. * @GNUTLS_PRIVKEY_DISABLE_CALLBACKS: The following flag disables call to PIN callbacks etc. * Only relevant to TPM keys. * @GNUTLS_PRIVKEY_FLAG_PROVABLE: When generating a key involving prime numbers, use provable primes; a seed may be required. * @GNUTLS_PRIVKEY_FLAG_CA: The generated private key is going to be used as a CA (relevant for RSA-PSS keys). * @GNUTLS_PRIVKEY_FLAG_EXPORT_COMPAT: Keys generated or imported as provable require an extended format which cannot be read by previous versions * of gnutls or other applications. By setting this flag the key will be exported in a backwards compatible way, * even if the information about the seed used will be lost. * @GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH: When making an RSA-PSS * signature, use the salt whose length is equal to the digest length, as * mandated in RFC 8446 4.2.3. * * Enumeration of different certificate import flags. */ typedef enum gnutls_privkey_flags { GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE = 1, GNUTLS_PRIVKEY_IMPORT_COPY = 1 << 1, GNUTLS_PRIVKEY_DISABLE_CALLBACKS = 1 << 2, GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA = 1 << 4, GNUTLS_PRIVKEY_FLAG_PROVABLE = 1 << 5, GNUTLS_PRIVKEY_FLAG_EXPORT_COMPAT = 1 << 6, GNUTLS_PRIVKEY_SIGN_FLAG_RSA_PSS = 1 << 7, GNUTLS_PRIVKEY_FLAG_REPRODUCIBLE = 1 << 8, GNUTLS_PRIVKEY_FLAG_CA = 1 << 9, GNUTLS_PRIVKEY_FLAG_RSA_PSS_FIXED_SALT_LENGTH = 1 << 10 } gnutls_privkey_flags_t; int gnutls_privkey_import_pkcs11(gnutls_privkey_t pkey, gnutls_pkcs11_privkey_t key, unsigned int flags); int gnutls_privkey_import_x509(gnutls_privkey_t pkey, gnutls_x509_privkey_t key, unsigned int flags); int gnutls_privkey_import_openpgp(gnutls_privkey_t pkey, gnutls_openpgp_privkey_t key, unsigned int flags); int gnutls_privkey_export_x509(gnutls_privkey_t pkey, gnutls_x509_privkey_t * key); int gnutls_privkey_export_openpgp(gnutls_privkey_t pkey, gnutls_openpgp_privkey_t * key); int gnutls_privkey_export_pkcs11(gnutls_privkey_t pkey, gnutls_pkcs11_privkey_t *key); int gnutls_privkey_import_openpgp_raw(gnutls_privkey_t pkey, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format, const gnutls_openpgp_keyid_t keyid, const char *password); int gnutls_privkey_import_x509_raw(gnutls_privkey_t pkey, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags); int gnutls_privkey_import_tpm_raw(gnutls_privkey_t pkey, const gnutls_datum_t * fdata, gnutls_tpmkey_fmt_t format, const char *srk_password, const char *key_password, unsigned int flags); int gnutls_privkey_import_tpm_url(gnutls_privkey_t pkey, const char *url, const char *srk_password, const char *key_password, unsigned int flags); int gnutls_privkey_import_url(gnutls_privkey_t key, const char *url, unsigned int flags); #if 0 /* for documentation purposes */ int gnutls_privkey_import_pkcs11_url(gnutls_privkey_t key, const char *url); #endif #define gnutls_privkey_import_pkcs11_url(key, url) gnutls_privkey_import_url(key, url, 0) int gnutls_privkey_import_ext(gnutls_privkey_t pkey, gnutls_pk_algorithm_t pk, void *userdata, gnutls_privkey_sign_func sign_func, gnutls_privkey_decrypt_func decrypt_func, unsigned int flags); int gnutls_privkey_import_ext2(gnutls_privkey_t pkey, gnutls_pk_algorithm_t pk, void *userdata, gnutls_privkey_sign_func sign_func, gnutls_privkey_decrypt_func decrypt_func, gnutls_privkey_deinit_func deinit_func, unsigned int flags); int gnutls_privkey_import_ext3(gnutls_privkey_t pkey, void *userdata, gnutls_privkey_sign_func sign_func, gnutls_privkey_decrypt_func decrypt_func, gnutls_privkey_deinit_func deinit_func, gnutls_privkey_info_func info_func, unsigned int flags); int gnutls_privkey_import_ext4(gnutls_privkey_t pkey, void *userdata, gnutls_privkey_sign_data_func sign_data_func, gnutls_privkey_sign_hash_func sign_hash_func, gnutls_privkey_decrypt_func decrypt_func, gnutls_privkey_deinit_func deinit_func, gnutls_privkey_info_func info_func, unsigned int flags); int gnutls_privkey_import_dsa_raw(gnutls_privkey_t key, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * g, const gnutls_datum_t * y, const gnutls_datum_t * x); int gnutls_privkey_import_rsa_raw(gnutls_privkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e, const gnutls_datum_t * d, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * u, const gnutls_datum_t * e1, const gnutls_datum_t * e2); int gnutls_privkey_import_ecc_raw(gnutls_privkey_t key, gnutls_ecc_curve_t curve, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_privkey_import_gost_raw(gnutls_privkey_t key, gnutls_ecc_curve_t curve, gnutls_digest_algorithm_t digest, gnutls_gost_paramset_t paramset, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_privkey_sign_data(gnutls_privkey_t signer, gnutls_digest_algorithm_t hash, unsigned int flags, const gnutls_datum_t * data, gnutls_datum_t * signature); int gnutls_privkey_sign_data2(gnutls_privkey_t signer, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * data, gnutls_datum_t * signature); #define gnutls_privkey_sign_raw_data(key, flags, data, sig) \ gnutls_privkey_sign_hash ( key, 0, GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA, data, sig) int gnutls_privkey_sign_hash(gnutls_privkey_t signer, gnutls_digest_algorithm_t hash_algo, unsigned int flags, const gnutls_datum_t * hash_data, gnutls_datum_t * signature); int gnutls_privkey_sign_hash2(gnutls_privkey_t signer, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * hash_data, gnutls_datum_t * signature); int gnutls_privkey_decrypt_data(gnutls_privkey_t key, unsigned int flags, const gnutls_datum_t * ciphertext, gnutls_datum_t * plaintext); int gnutls_privkey_decrypt_data2(gnutls_privkey_t key, unsigned int flags, const gnutls_datum_t * ciphertext, unsigned char * plaintext, size_t plaintext_size); int gnutls_privkey_export_rsa_raw(gnutls_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u, gnutls_datum_t * e1, gnutls_datum_t * e2); int gnutls_privkey_export_rsa_raw2(gnutls_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u, gnutls_datum_t * e1, gnutls_datum_t * e2, unsigned flags); int gnutls_privkey_export_dsa_raw(gnutls_privkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x); int gnutls_privkey_export_dsa_raw2(gnutls_privkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x, unsigned flags); int gnutls_privkey_export_ecc_raw(gnutls_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k); int gnutls_privkey_export_ecc_raw2(gnutls_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k, unsigned flags); int gnutls_privkey_export_gost_raw2(gnutls_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t * paramset, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k, unsigned flags); int gnutls_x509_crt_privkey_sign(gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crl_privkey_sign(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer, gnutls_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crq_privkey_sign(gnutls_x509_crq_t crq, gnutls_privkey_t key, gnutls_digest_algorithm_t dig, unsigned int flags); /** * gnutls_pcert_st: * @pubkey: public key of parsed certificate. * @cert: certificate itself of parsed certificate * @type: type of certificate, a #gnutls_certificate_type_t type. * * A parsed certificate. */ typedef struct gnutls_pcert_st { gnutls_pubkey_t pubkey; gnutls_datum_t cert; gnutls_certificate_type_t type; } gnutls_pcert_st; /* This flag is unused/ignored */ #define GNUTLS_PCERT_NO_CERT 1 int gnutls_pcert_import_x509(gnutls_pcert_st * pcert, gnutls_x509_crt_t crt, unsigned int flags); int gnutls_pcert_import_x509_list(gnutls_pcert_st * pcert, gnutls_x509_crt_t *crt, unsigned *ncrt, unsigned int flags); int gnutls_pcert_export_x509(gnutls_pcert_st * pcert, gnutls_x509_crt_t * crt); int gnutls_pcert_list_import_x509_raw(gnutls_pcert_st * pcerts, unsigned int *pcert_max, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pcert_list_import_x509_file(gnutls_pcert_st *pcert_list, unsigned *pcert_list_size, const char *file, gnutls_x509_crt_fmt_t format, gnutls_pin_callback_t pin_fn, void *pin_fn_userdata, unsigned int flags); int gnutls_pcert_import_x509_raw(gnutls_pcert_st * pcert, const gnutls_datum_t * cert, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pcert_import_openpgp_raw(gnutls_pcert_st * pcert, const gnutls_datum_t * cert, gnutls_openpgp_crt_fmt_t format, gnutls_openpgp_keyid_t keyid, unsigned int flags); int gnutls_pcert_import_openpgp(gnutls_pcert_st * pcert, gnutls_openpgp_crt_t crt, unsigned int flags); int gnutls_pcert_export_openpgp(gnutls_pcert_st * pcert, gnutls_openpgp_crt_t * crt); void gnutls_pcert_deinit(gnutls_pcert_st * pcert); int gnutls_pcert_import_rawpk(gnutls_pcert_st* pcert, gnutls_pubkey_t key, unsigned int flags); int gnutls_pcert_import_rawpk_raw(gnutls_pcert_st* pcert, const gnutls_datum_t* rawpubkey, gnutls_x509_crt_fmt_t format, unsigned int key_usage, unsigned int flags); /* For certificate credentials */ /* This is the same as gnutls_certificate_retrieve_function() * but retrieves a gnutls_pcert_st which requires much less processing * within the library. */ typedef int gnutls_certificate_retrieve_function2(gnutls_session_t, const gnutls_datum_t *req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t *pk_algos, int pk_algos_length, gnutls_pcert_st**, unsigned int *pcert_length, gnutls_privkey_t *privkey); void gnutls_certificate_set_retrieve_function2 (gnutls_certificate_credentials_t cred, gnutls_certificate_retrieve_function2 *func); struct gnutls_cert_retr_st { unsigned version; /* set to 1 */ gnutls_certificate_credentials_t cred; const gnutls_datum_t *req_ca_rdn; unsigned nreqs; const gnutls_pk_algorithm_t *pk_algos; unsigned pk_algos_length; /* other fields may be added if version is > 1 */ unsigned char padding[64]; }; /* When the callback sets this value, gnutls will deinitialize the given * values after use */ #define GNUTLS_CERT_RETR_DEINIT_ALL 1 typedef int gnutls_certificate_retrieve_function3( gnutls_session_t, const struct gnutls_cert_retr_st *info, gnutls_pcert_st **certs, unsigned int *certs_length, gnutls_ocsp_data_st **ocsp, unsigned int *ocsp_length, gnutls_privkey_t *privkey, unsigned int *flags); void gnutls_certificate_set_retrieve_function3 (gnutls_certificate_credentials_t cred, gnutls_certificate_retrieve_function3 *func); int gnutls_certificate_set_key(gnutls_certificate_credentials_t res, const char **names, int names_size, gnutls_pcert_st * pcert_list, int pcert_list_size, gnutls_privkey_t key); int gnutls_pubkey_print(gnutls_pubkey_t pubkey, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_ABSTRACT_H */ ================================================ FILE: thirdparty/64/include/gnutls/compat.h ================================================ /* * Copyright (C) 2008-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* Typedefs for more compatibility with older GnuTLS. */ #ifndef GNUTLS_COMPAT_H #define GNUTLS_COMPAT_H /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #ifdef __GNUC__ #define _GNUTLS_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #if !defined GNUTLS_INTERNAL_BUILD #if _GNUTLS_GCC_VERSION >= 30100 #define _GNUTLS_GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__)) #endif #endif #endif /* __GNUC__ */ #ifndef _GNUTLS_GCC_ATTR_DEPRECATED #define _GNUTLS_GCC_ATTR_DEPRECATED #endif /* gnutls_connection_end_t was made redundant in 2.99.0 */ typedef unsigned int gnutls_connection_end_t _GNUTLS_GCC_ATTR_DEPRECATED; /* Stuff deprecated in 2.x */ typedef gnutls_cipher_algorithm_t gnutls_cipher_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_kx_algorithm_t gnutls_kx_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_mac_algorithm_t gnutls_mac_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_digest_algorithm_t gnutls_digest_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_compression_method_t gnutls_compression_method _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_connection_end_t gnutls_connection_end _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crt_fmt_t gnutls_x509_crt_fmt _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_pk_algorithm_t gnutls_pk_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_sign_algorithm_t gnutls_sign_algorithm _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_close_request_t gnutls_close_request _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_request_t gnutls_certificate_request _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_status_t gnutls_certificate_status _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_session_t gnutls_session _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_alert_level_t gnutls_alert_level _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_alert_description_t gnutls_alert_description _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_subject_alt_name_t gnutls_x509_subject_alt_name _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_openpgp_privkey_t gnutls_openpgp_privkey _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_openpgp_keyring_t gnutls_openpgp_keyring _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crt_t gnutls_x509_crt _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_privkey_t gnutls_x509_privkey _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crl_t gnutls_x509_crl _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_x509_crq_t gnutls_x509_crq _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_credentials_t gnutls_certificate_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_anon_server_credentials_t gnutls_anon_server_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_anon_client_credentials_t gnutls_anon_client_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_srp_client_credentials_t gnutls_srp_client_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_srp_server_credentials_t gnutls_srp_server_credentials _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_dh_params_t gnutls_dh_params _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_rsa_params_t gnutls_rsa_params _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_params_type_t gnutls_params_type _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_credentials_type_t gnutls_credentials_type _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_certificate_type_t gnutls_certificate_type _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_datum_t gnutls_datum _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_transport_ptr_t gnutls_transport_ptr _GNUTLS_GCC_ATTR_DEPRECATED; /* Old verification flags */ #define GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT (0) /* Old SRP alerts removed in 2.1.x because the TLS-SRP RFC was modified to use the PSK alert. */ #define GNUTLS_A_MISSING_SRP_USERNAME GNUTLS_A_UNKNOWN_PSK_IDENTITY #define GNUTLS_A_UNKNOWN_SRP_USERNAME GNUTLS_A_UNKNOWN_PSK_IDENTITY /* OpenPGP stuff renamed in 2.1.x. */ #define GNUTLS_OPENPGP_KEY GNUTLS_OPENPGP_CERT #define GNUTLS_OPENPGP_KEY_FINGERPRINT GNUTLS_OPENPGP_CERT_FINGERPRINT #define gnutls_openpgp_send_key gnutls_openpgp_send_cert typedef gnutls_openpgp_crt_status_t gnutls_openpgp_key_status_t _GNUTLS_GCC_ATTR_DEPRECATED; typedef gnutls_openpgp_crt_t gnutls_openpgp_key_t _GNUTLS_GCC_ATTR_DEPRECATED; #define gnutls_openpgp_key_init gnutls_openpgp_crt_init #define gnutls_openpgp_key_deinit gnutls_openpgp_crt_deinit #define gnutls_openpgp_key_import gnutls_openpgp_crt_import #define gnutls_openpgp_key_export gnutls_openpgp_crt_export #define gnutls_openpgp_key_get_key_usage gnutls_openpgp_crt_get_key_usage #define gnutls_openpgp_key_get_fingerprint gnutls_openpgp_crt_get_fingerprint #define gnutls_openpgp_key_get_pk_algorithm gnutls_openpgp_crt_get_pk_algorithm #define gnutls_openpgp_key_get_name gnutls_openpgp_crt_get_name #define gnutls_openpgp_key_get_version gnutls_openpgp_crt_get_version #define gnutls_openpgp_key_get_creation_time gnutls_openpgp_crt_get_creation_time #define gnutls_openpgp_key_get_expiration_time gnutls_openpgp_crt_get_expiration_time #define gnutls_openpgp_key_get_id gnutls_openpgp_crt_get_id #define gnutls_openpgp_key_check_hostname gnutls_openpgp_crt_check_hostname /* OpenPGP stuff renamed in 2.3.x. */ #define gnutls_openpgp_crt_get_id gnutls_openpgp_crt_get_key_id /* New better names renamed in 2.3.x, add these for backwards compatibility with old poor names.*/ #define GNUTLS_X509_CRT_FULL GNUTLS_CRT_PRINT_FULL #define GNUTLS_X509_CRT_ONELINE GNUTLS_CRT_PRINT_ONELINE #define GNUTLS_X509_CRT_UNSIGNED_FULL GNUTLS_CRT_PRINT_UNSIGNED_FULL /* Namespace problems. */ #define LIBGNUTLS_VERSION GNUTLS_VERSION #define LIBGNUTLS_VERSION_MAJOR GNUTLS_VERSION_MAJOR #define LIBGNUTLS_VERSION_MINOR GNUTLS_VERSION_MINOR #define LIBGNUTLS_VERSION_PATCH GNUTLS_VERSION_PATCH #define LIBGNUTLS_VERSION_NUMBER GNUTLS_VERSION_NUMBER #define LIBGNUTLS_EXTRA_VERSION GNUTLS_VERSION /* This is a very dangerous and error-prone function. * Use gnutls_privkey_sign_hash() instead. */ int gnutls_x509_privkey_sign_hash(gnutls_x509_privkey_t key, const gnutls_datum_t * hash, gnutls_datum_t * signature) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_sign_hash(gnutls_openpgp_privkey_t key, const gnutls_datum_t * hash, gnutls_datum_t * signature) _GNUTLS_GCC_ATTR_DEPRECATED; /* gnutls_pubkey_get_preferred_hash_algorithm() */ int gnutls_x509_crt_get_preferred_hash_algorithm(gnutls_x509_crt_t crt, gnutls_digest_algorithm_t * hash, unsigned int *mand) _GNUTLS_GCC_ATTR_DEPRECATED; /* use gnutls_privkey_sign_hash() with the GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA flag */ #ifdef _ISOC99_SOURCE /* we provide older functions for compatibility as inline functions that * depend on gnutls_session_get_random. */ static inline const void *gnutls_session_get_server_random(gnutls_session_t session) _GNUTLS_GCC_ATTR_DEPRECATED; static inline const void *gnutls_session_get_server_random(gnutls_session_t session) { gnutls_datum_t rnd; gnutls_session_get_random(session, NULL, &rnd); /*doc-skip */ return rnd.data; } static inline const void *gnutls_session_get_client_random(gnutls_session_t session) _GNUTLS_GCC_ATTR_DEPRECATED; static inline const void *gnutls_session_get_client_random(gnutls_session_t session) { gnutls_datum_t rnd; gnutls_session_get_random(session, &rnd, NULL); /*doc-skip */ return rnd.data; } #endif void gnutls_global_set_mem_functions(gnutls_alloc_function alloc_func, gnutls_alloc_function secure_alloc_func, gnutls_is_secure_function is_secure_func, gnutls_realloc_function realloc_func, gnutls_free_function free_func) _GNUTLS_GCC_ATTR_DEPRECATED; /* defined in old headers - unused nevertheless */ #define GNUTLS_SUPPLEMENTAL_USER_MAPPING_DATA 0 /* old compression related functions */ gnutls_compression_method_t gnutls_compression_get(gnutls_session_t session) _GNUTLS_GCC_ATTR_DEPRECATED; const char * gnutls_compression_get_name(gnutls_compression_method_t algorithm) __GNUTLS_CONST__ _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_compression_method_t gnutls_compression_get_id(const char *name) __GNUTLS_CONST__ _GNUTLS_GCC_ATTR_DEPRECATED; const gnutls_compression_method_t * gnutls_compression_list(void) __GNUTLS_PURE__ _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_priority_compression_list(gnutls_priority_t pcache, const unsigned int **list) _GNUTLS_GCC_ATTR_DEPRECATED; /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_COMPAT_H */ ================================================ FILE: thirdparty/64/include/gnutls/crypto.h ================================================ /* * Copyright (C) 2008-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_CRYPTO_H #define GNUTLS_CRYPTO_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ typedef struct api_cipher_hd_st *gnutls_cipher_hd_t; int gnutls_cipher_init(gnutls_cipher_hd_t * handle, gnutls_cipher_algorithm_t cipher, const gnutls_datum_t * key, const gnutls_datum_t * iv); int gnutls_cipher_encrypt(const gnutls_cipher_hd_t handle, void *text, size_t textlen); int gnutls_cipher_decrypt(const gnutls_cipher_hd_t handle, void *ciphertext, size_t ciphertextlen); int gnutls_cipher_decrypt2(gnutls_cipher_hd_t handle, const void *ciphertext, size_t ciphertextlen, void *text, size_t textlen); int gnutls_cipher_encrypt2(gnutls_cipher_hd_t handle, const void *text, size_t textlen, void *ciphertext, size_t ciphertextlen); /** * gnutls_cipher_flags_t: * @GNUTLS_CIPHER_PADDING_PKCS7: Flag to indicate PKCS#7 padding * * Enumeration of flags to control block cipher padding, used by * gnutls_cipher_encrypt3() and gnutls_cipher_decrypt3(). * * Since: 3.7.7 */ typedef enum gnutls_cipher_flags_t { GNUTLS_CIPHER_PADDING_PKCS7 = 1 } gnutls_cipher_flags_t; int gnutls_cipher_encrypt3(gnutls_cipher_hd_t handle, const void *ptext, size_t ptext_len, void *ctext, size_t *ctext_len, unsigned flags); int gnutls_cipher_decrypt3(gnutls_cipher_hd_t handle, const void *ctext, size_t ctext_len, void *ptext, size_t *ptext_len, unsigned flags); void gnutls_cipher_set_iv(gnutls_cipher_hd_t handle, void *iv, size_t ivlen); int gnutls_cipher_tag(gnutls_cipher_hd_t handle, void *tag, size_t tag_size); int gnutls_cipher_add_auth(gnutls_cipher_hd_t handle, const void *text, size_t text_size); void gnutls_cipher_deinit(gnutls_cipher_hd_t handle); unsigned gnutls_cipher_get_block_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_cipher_get_iv_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_cipher_get_tag_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; /* AEAD API */ typedef struct api_aead_cipher_hd_st *gnutls_aead_cipher_hd_t; int gnutls_aead_cipher_init(gnutls_aead_cipher_hd_t * handle, gnutls_cipher_algorithm_t cipher, const gnutls_datum_t * key); int gnutls_aead_cipher_set_key(gnutls_aead_cipher_hd_t handle, const gnutls_datum_t *key); int gnutls_aead_cipher_decrypt(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const void *auth, size_t auth_len, size_t tag_size, const void *ctext, size_t ctext_len, void *ptext, size_t *ptext_len); int gnutls_aead_cipher_encrypt(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const void *auth, size_t auth_len, size_t tag_size, const void *ptext, size_t ptext_len, void *ctext, size_t *ctext_len); int gnutls_aead_cipher_encryptv(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const giovec_t *auth_iov, int auth_iovcnt, size_t tag_size, const giovec_t *iov, int iovcnt, void *ctext, size_t *ctext_len); int gnutls_aead_cipher_encryptv2(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const giovec_t *auth_iov, int auth_iovcnt, const giovec_t *iov, int iovcnt, void *tag, size_t *tag_size); int gnutls_aead_cipher_decryptv2(gnutls_aead_cipher_hd_t handle, const void *nonce, size_t nonce_len, const giovec_t *auth_iov, int auth_iovcnt, const giovec_t *iov, int iovcnt, void *tag, size_t tag_size); void gnutls_aead_cipher_deinit(gnutls_aead_cipher_hd_t handle); /* Hash - MAC API */ typedef struct hash_hd_st *gnutls_hash_hd_t; typedef struct hmac_hd_st *gnutls_hmac_hd_t; size_t gnutls_mac_get_nonce_size(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; int gnutls_hmac_init(gnutls_hmac_hd_t * dig, gnutls_mac_algorithm_t algorithm, const void *key, size_t keylen); void gnutls_hmac_set_nonce(gnutls_hmac_hd_t handle, const void *nonce, size_t nonce_len); int gnutls_hmac(gnutls_hmac_hd_t handle, const void *text, size_t textlen); void gnutls_hmac_output(gnutls_hmac_hd_t handle, void *digest); void gnutls_hmac_deinit(gnutls_hmac_hd_t handle, void *digest); unsigned gnutls_hmac_get_len(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_hmac_get_key_size(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; int gnutls_hmac_fast(gnutls_mac_algorithm_t algorithm, const void *key, size_t keylen, const void *text, size_t textlen, void *digest); gnutls_hmac_hd_t gnutls_hmac_copy(gnutls_hmac_hd_t handle); int gnutls_hash_init(gnutls_hash_hd_t * dig, gnutls_digest_algorithm_t algorithm); int gnutls_hash(gnutls_hash_hd_t handle, const void *text, size_t textlen); void gnutls_hash_output(gnutls_hash_hd_t handle, void *digest); void gnutls_hash_deinit(gnutls_hash_hd_t handle, void *digest); unsigned gnutls_hash_get_len(gnutls_digest_algorithm_t algorithm) __GNUTLS_CONST__; int gnutls_hash_fast(gnutls_digest_algorithm_t algorithm, const void *text, size_t textlen, void *digest); gnutls_hash_hd_t gnutls_hash_copy(gnutls_hash_hd_t handle); /* KDF API */ int gnutls_hkdf_extract(gnutls_mac_algorithm_t mac, const gnutls_datum_t *key, const gnutls_datum_t *salt, void *output); int gnutls_hkdf_expand(gnutls_mac_algorithm_t mac, const gnutls_datum_t *key, const gnutls_datum_t *info, void *output, size_t length); int gnutls_pbkdf2(gnutls_mac_algorithm_t mac, const gnutls_datum_t *key, const gnutls_datum_t *salt, unsigned iter_count, void *output, size_t length); /* register ciphers */ /** * gnutls_rnd_level_t: * @GNUTLS_RND_NONCE: Non-predictable random number. Fatal in parts * of session if broken, i.e., vulnerable to statistical analysis. * @GNUTLS_RND_RANDOM: Pseudo-random cryptographic random number. * Fatal in session if broken. Example use: temporal keys. * @GNUTLS_RND_KEY: Fatal in many sessions if broken. Example use: * Long-term keys. * * Enumeration of random quality levels. */ typedef enum gnutls_rnd_level { GNUTLS_RND_NONCE = 0, GNUTLS_RND_RANDOM = 1, GNUTLS_RND_KEY = 2 } gnutls_rnd_level_t; int gnutls_rnd(gnutls_rnd_level_t level, void *data, size_t len); void gnutls_rnd_refresh(void); /* API to override ciphers and MAC algorithms */ typedef int (*gnutls_cipher_init_func) (gnutls_cipher_algorithm_t, void **ctx, int enc); typedef int (*gnutls_cipher_setkey_func) (void *ctx, const void *key, size_t keysize); /* old style ciphers */ typedef int (*gnutls_cipher_setiv_func) (void *ctx, const void *iv, size_t ivsize); typedef int (*gnutls_cipher_getiv_func) (void *ctx, void *iv, size_t ivsize); typedef int (*gnutls_cipher_encrypt_func) (void *ctx, const void *plain, size_t plainsize, void *encr, size_t encrsize); typedef int (*gnutls_cipher_decrypt_func) (void *ctx, const void *encr, size_t encrsize, void *plain, size_t plainsize); /* aead ciphers */ typedef int (*gnutls_cipher_auth_func) (void *ctx, const void *data, size_t datasize); typedef void (*gnutls_cipher_tag_func) (void *ctx, void *tag, size_t tagsize); typedef int (*gnutls_cipher_aead_encrypt_func) (void *ctx, const void *nonce, size_t noncesize, const void *auth, size_t authsize, size_t tag_size, const void *plain, size_t plainsize, void *encr, size_t encrsize); typedef int (*gnutls_cipher_aead_decrypt_func) (void *ctx, const void *nonce, size_t noncesize, const void *auth, size_t authsize, size_t tag_size, const void *encr, size_t encrsize, void *plain, size_t plainsize); typedef void (*gnutls_cipher_deinit_func) (void *ctx); int gnutls_crypto_register_cipher(gnutls_cipher_algorithm_t algorithm, int priority, gnutls_cipher_init_func init, gnutls_cipher_setkey_func setkey, gnutls_cipher_setiv_func setiv, gnutls_cipher_encrypt_func encrypt, gnutls_cipher_decrypt_func decrypt, gnutls_cipher_deinit_func deinit) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_crypto_register_aead_cipher(gnutls_cipher_algorithm_t algorithm, int priority, gnutls_cipher_init_func init, gnutls_cipher_setkey_func setkey, gnutls_cipher_aead_encrypt_func aead_encrypt, gnutls_cipher_aead_decrypt_func aead_decrypt, gnutls_cipher_deinit_func deinit) _GNUTLS_GCC_ATTR_DEPRECATED; typedef int (*gnutls_mac_init_func) (gnutls_mac_algorithm_t, void **ctx); typedef int (*gnutls_mac_setkey_func) (void *ctx, const void *key, size_t keysize); typedef int (*gnutls_mac_setnonce_func) (void *ctx, const void *nonce, size_t noncesize); typedef int (*gnutls_mac_hash_func) (void *ctx, const void *text, size_t textsize); typedef int (*gnutls_mac_output_func) (void *src_ctx, void *digest, size_t digestsize); typedef void (*gnutls_mac_deinit_func) (void *ctx); typedef int (*gnutls_mac_fast_func) (gnutls_mac_algorithm_t, const void *nonce, size_t nonce_size, const void *key, size_t keysize, const void *text, size_t textsize, void *digest); typedef void *(*gnutls_mac_copy_func) (const void *ctx); int gnutls_crypto_register_mac(gnutls_mac_algorithm_t mac, int priority, gnutls_mac_init_func init, gnutls_mac_setkey_func setkey, gnutls_mac_setnonce_func setnonce, gnutls_mac_hash_func hash, gnutls_mac_output_func output, gnutls_mac_deinit_func deinit, gnutls_mac_fast_func hash_fast) _GNUTLS_GCC_ATTR_DEPRECATED; typedef int (*gnutls_digest_init_func) (gnutls_digest_algorithm_t, void **ctx); typedef int (*gnutls_digest_hash_func) (void *ctx, const void *text, size_t textsize); typedef int (*gnutls_digest_output_func) (void *src_ctx, void *digest, size_t digestsize); typedef void (*gnutls_digest_deinit_func) (void *ctx); typedef int (*gnutls_digest_fast_func) (gnutls_digest_algorithm_t, const void *text, size_t textsize, void *digest); typedef void *(*gnutls_digest_copy_func) (const void *ctx); int gnutls_crypto_register_digest(gnutls_digest_algorithm_t digest, int priority, gnutls_digest_init_func init, gnutls_digest_hash_func hash, gnutls_digest_output_func output, gnutls_digest_deinit_func deinit, gnutls_digest_fast_func hash_fast) _GNUTLS_GCC_ATTR_DEPRECATED; /* RSA-PKCS#1 1.5 helper functions */ int gnutls_encode_ber_digest_info(gnutls_digest_algorithm_t hash, const gnutls_datum_t * digest, gnutls_datum_t * output); int gnutls_decode_ber_digest_info(const gnutls_datum_t * info, gnutls_digest_algorithm_t *hash, unsigned char *digest, unsigned int *digest_size); int gnutls_decode_rs_value(const gnutls_datum_t * sig_value, gnutls_datum_t *r, gnutls_datum_t *s); int gnutls_encode_rs_value(gnutls_datum_t * sig_value, const gnutls_datum_t * r, const gnutls_datum_t * s); int gnutls_encode_gost_rs_value(gnutls_datum_t * sig_value, const gnutls_datum_t * r, const gnutls_datum_t *s); int gnutls_decode_gost_rs_value(const gnutls_datum_t * sig_value, gnutls_datum_t * r, gnutls_datum_t * s); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_CRYPTO_H */ ================================================ FILE: thirdparty/64/include/gnutls/dtls.h ================================================ /* * Copyright (C) 2011-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the X.509 * certificate and CRL handling functions. */ #ifndef GNUTLS_DTLS_H #define GNUTLS_DTLS_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_COOKIE_KEY_SIZE 16 void gnutls_dtls_set_timeouts(gnutls_session_t session, unsigned int retrans_timeout, unsigned int total_timeout); unsigned int gnutls_dtls_get_mtu(gnutls_session_t session); unsigned int gnutls_dtls_get_data_mtu(gnutls_session_t session); void gnutls_dtls_set_mtu(gnutls_session_t session, unsigned int mtu); int gnutls_dtls_set_data_mtu(gnutls_session_t session, unsigned int mtu); unsigned int gnutls_dtls_get_timeout(gnutls_session_t session); /** * gnutls_dtls_prestate_st: * @record_seq: record sequence number * @hsk_read_seq: handshake read sequence number * @hsk_write_seq: handshake write sequence number * * DTLS cookie prestate struct. This is usually never modified by * the application, it is used to carry the cookie data between * gnutls_dtls_cookie_send(), gnutls_dtls_cookie_verify() and * gnutls_dtls_prestate_set(). */ typedef struct { unsigned int record_seq; unsigned int hsk_read_seq; unsigned int hsk_write_seq; } gnutls_dtls_prestate_st; int gnutls_dtls_cookie_send(gnutls_datum_t * key, void *client_data, size_t client_data_size, gnutls_dtls_prestate_st * prestate, gnutls_transport_ptr_t ptr, gnutls_push_func push_func); int gnutls_dtls_cookie_verify(gnutls_datum_t * key, void *client_data, size_t client_data_size, void *_msg, size_t msg_size, gnutls_dtls_prestate_st * prestate); void gnutls_dtls_prestate_set(gnutls_session_t session, gnutls_dtls_prestate_st * prestate); unsigned int gnutls_record_get_discarded(gnutls_session_t session); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_DTLS_H */ ================================================ FILE: thirdparty/64/include/gnutls/gnutls.h ================================================ /* -*- c -*- * Copyright (C) 2000-2016 Free Software Foundation, Inc. * Copyright (C) 2015-2017 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for all the * high level functionality of the gnutls main library. * * If the optional C++ binding was built, it is available in * gnutls/gnutlsxx.h. * * The openssl compatibility layer (which is under the GNU GPL * license) is in gnutls/openssl.h. * * The low level cipher functionality is in gnutls/crypto.h. */ #ifndef GNUTLS_GNUTLS_H #define GNUTLS_GNUTLS_H /* Get ssize_t. */ #include /* Get size_t. */ #include /* Get time_t. */ #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_VERSION "3.7.10" #define GNUTLS_VERSION_MAJOR 3 #define GNUTLS_VERSION_MINOR 7 #define GNUTLS_VERSION_PATCH 10 #define GNUTLS_VERSION_NUMBER 0x03070a #define GNUTLS_CIPHER_RIJNDAEL_128_CBC GNUTLS_CIPHER_AES_128_CBC #define GNUTLS_CIPHER_RIJNDAEL_256_CBC GNUTLS_CIPHER_AES_256_CBC #define GNUTLS_CIPHER_RIJNDAEL_CBC GNUTLS_CIPHER_AES_128_CBC #define GNUTLS_CIPHER_ARCFOUR GNUTLS_CIPHER_ARCFOUR_128 #if !defined(GNUTLS_INTERNAL_BUILD) && defined(_WIN32) # define _SYM_EXPORT __declspec(dllimport) #else # define _SYM_EXPORT #endif #ifdef __GNUC__ # define __GNUTLS_CONST__ __attribute__((const)) # define __GNUTLS_PURE__ __attribute__((pure)) #else # define __GNUTLS_CONST__ # define __GNUTLS_PURE__ #endif /* Use the following definition globally in your program to disable * implicit initialization of gnutls. */ #define GNUTLS_SKIP_GLOBAL_INIT int _gnutls_global_init_skip(void); \ int _gnutls_global_init_skip(void) {return 1;} /** * gnutls_cipher_algorithm_t: * @GNUTLS_CIPHER_UNKNOWN: Value to identify an unknown/unsupported algorithm. * @GNUTLS_CIPHER_NULL: The NULL (identity) encryption algorithm. * @GNUTLS_CIPHER_ARCFOUR_128: ARCFOUR stream cipher with 128-bit keys. * @GNUTLS_CIPHER_3DES_CBC: 3DES in CBC mode. * @GNUTLS_CIPHER_AES_128_CBC: AES in CBC mode with 128-bit keys. * @GNUTLS_CIPHER_AES_192_CBC: AES in CBC mode with 192-bit keys. * @GNUTLS_CIPHER_AES_256_CBC: AES in CBC mode with 256-bit keys. * @GNUTLS_CIPHER_AES_128_CFB8: AES in CFB8 mode with 128-bit keys. * @GNUTLS_CIPHER_AES_192_CFB8: AES in CFB8 mode with 192-bit keys. * @GNUTLS_CIPHER_AES_256_CFB8: AES in CFB8 mode with 256-bit keys. * @GNUTLS_CIPHER_ARCFOUR_40: ARCFOUR stream cipher with 40-bit keys. * @GNUTLS_CIPHER_CAMELLIA_128_CBC: Camellia in CBC mode with 128-bit keys. * @GNUTLS_CIPHER_CAMELLIA_192_CBC: Camellia in CBC mode with 192-bit keys. * @GNUTLS_CIPHER_CAMELLIA_256_CBC: Camellia in CBC mode with 256-bit keys. * @GNUTLS_CIPHER_RC2_40_CBC: RC2 in CBC mode with 40-bit keys. * @GNUTLS_CIPHER_DES_CBC: DES in CBC mode (56-bit keys). * @GNUTLS_CIPHER_AES_128_GCM: AES in GCM mode with 128-bit keys (AEAD). * @GNUTLS_CIPHER_AES_256_GCM: AES in GCM mode with 256-bit keys (AEAD). * @GNUTLS_CIPHER_AES_128_CCM: AES in CCM mode with 128-bit keys (AEAD). * @GNUTLS_CIPHER_AES_256_CCM: AES in CCM mode with 256-bit keys (AEAD). * @GNUTLS_CIPHER_AES_128_CCM_8: AES in CCM mode with 64-bit tag and 128-bit keys (AEAD). * @GNUTLS_CIPHER_AES_256_CCM_8: AES in CCM mode with 64-bit tag and 256-bit keys (AEAD). * @GNUTLS_CIPHER_CAMELLIA_128_GCM: CAMELLIA in GCM mode with 128-bit keys (AEAD). * @GNUTLS_CIPHER_CAMELLIA_256_GCM: CAMELLIA in GCM mode with 256-bit keys (AEAD). * @GNUTLS_CIPHER_SALSA20_256: Salsa20 with 256-bit keys. * @GNUTLS_CIPHER_ESTREAM_SALSA20_256: Estream's Salsa20 variant with 256-bit keys. * @GNUTLS_CIPHER_CHACHA20_32: Chacha20 cipher with 96-bit nonces and 32-bit block counters. * @GNUTLS_CIPHER_CHACHA20_64: Chacha20 cipher with 64-bit nonces and 64-bit block counters. * @GNUTLS_CIPHER_CHACHA20_POLY1305: The Chacha20 cipher with the Poly1305 authenticator (AEAD). * @GNUTLS_CIPHER_GOST28147_TC26Z_CFB: GOST 28147-89 (Magma) cipher in CFB mode with TC26 Z S-box. * @GNUTLS_CIPHER_GOST28147_CPA_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro A S-box. * @GNUTLS_CIPHER_GOST28147_CPB_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro B S-box. * @GNUTLS_CIPHER_GOST28147_CPC_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro C S-box. * @GNUTLS_CIPHER_GOST28147_CPD_CFB: GOST 28147-89 (Magma) cipher in CFB mode with CryptoPro D S-box. * @GNUTLS_CIPHER_AES_128_XTS: AES in XTS mode with 128-bit key + 128bit tweak key. * @GNUTLS_CIPHER_AES_256_XTS: AES in XTS mode with 256-bit key + 256bit tweak key. * Note that the XTS ciphers are message oriented. * The whole message needs to be provided with a single call, because * cipher-stealing requires to know where the message actually terminates * in order to be able to compute where the stealing occurs. * @GNUTLS_CIPHER_GOST28147_TC26Z_CNT: GOST 28147-89 (Magma) cipher in CNT mode with TC26 Z S-box. * @GNUTLS_CIPHER_MAGMA_CTR_ACPKM: GOST R 34.12-2015 (Magma) cipher in CTR-ACPKM mode. * @GNUTLS_CIPHER_KUZNYECHIK_CTR_ACPKM: GOST R 34.12-2015 (Kuznyechik) cipher in CTR-ACPKM mode. * @GNUTLS_CIPHER_IDEA_PGP_CFB: IDEA in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_3DES_PGP_CFB: 3DES in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_CAST5_PGP_CFB: CAST5 in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_BLOWFISH_PGP_CFB: Blowfish in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_SAFER_SK128_PGP_CFB: Safer-SK in CFB mode with 128-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_AES128_PGP_CFB: AES in CFB mode with 128-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_AES192_PGP_CFB: AES in CFB mode with 192-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_AES256_PGP_CFB: AES in CFB mode with 256-bit keys (placeholder - unsupported). * @GNUTLS_CIPHER_TWOFISH_PGP_CFB: Twofish in CFB mode (placeholder - unsupported). * @GNUTLS_CIPHER_AES_128_SIV: AES in SIV mode with 128-bit key. * @GNUTLS_CIPHER_AES_256_SIV: AES in SIV mode with 256-bit key. * Note that the SIV ciphers can only be used with * the AEAD interface, and the IV plays a role as * the authentication tag while it is prepended to * the cipher text. * @GNUTLS_CIPHER_AES_192_GCM: AES in GCM mode with 192-bit keys (AEAD). * * Enumeration of different symmetric encryption algorithms. */ typedef enum gnutls_cipher_algorithm { GNUTLS_CIPHER_UNKNOWN = 0, GNUTLS_CIPHER_NULL = 1, GNUTLS_CIPHER_ARCFOUR_128 = 2, GNUTLS_CIPHER_3DES_CBC = 3, GNUTLS_CIPHER_AES_128_CBC = 4, GNUTLS_CIPHER_AES_256_CBC = 5, GNUTLS_CIPHER_ARCFOUR_40 = 6, GNUTLS_CIPHER_CAMELLIA_128_CBC = 7, GNUTLS_CIPHER_CAMELLIA_256_CBC = 8, GNUTLS_CIPHER_AES_192_CBC = 9, GNUTLS_CIPHER_AES_128_GCM = 10, GNUTLS_CIPHER_AES_256_GCM = 11, GNUTLS_CIPHER_CAMELLIA_192_CBC = 12, GNUTLS_CIPHER_SALSA20_256 = 13, GNUTLS_CIPHER_ESTREAM_SALSA20_256 = 14, GNUTLS_CIPHER_CAMELLIA_128_GCM = 15, GNUTLS_CIPHER_CAMELLIA_256_GCM = 16, GNUTLS_CIPHER_RC2_40_CBC = 17, GNUTLS_CIPHER_DES_CBC = 18, GNUTLS_CIPHER_AES_128_CCM = 19, GNUTLS_CIPHER_AES_256_CCM = 20, GNUTLS_CIPHER_AES_128_CCM_8 = 21, GNUTLS_CIPHER_AES_256_CCM_8 = 22, GNUTLS_CIPHER_CHACHA20_POLY1305 = 23, GNUTLS_CIPHER_GOST28147_TC26Z_CFB = 24, GNUTLS_CIPHER_GOST28147_CPA_CFB = 25, GNUTLS_CIPHER_GOST28147_CPB_CFB = 26, GNUTLS_CIPHER_GOST28147_CPC_CFB = 27, GNUTLS_CIPHER_GOST28147_CPD_CFB = 28, GNUTLS_CIPHER_AES_128_CFB8 = 29, GNUTLS_CIPHER_AES_192_CFB8 = 30, GNUTLS_CIPHER_AES_256_CFB8 = 31, GNUTLS_CIPHER_AES_128_XTS = 32, GNUTLS_CIPHER_AES_256_XTS = 33, GNUTLS_CIPHER_GOST28147_TC26Z_CNT = 34, GNUTLS_CIPHER_CHACHA20_64 = 35, GNUTLS_CIPHER_CHACHA20_32 = 36, GNUTLS_CIPHER_AES_128_SIV = 37, GNUTLS_CIPHER_AES_256_SIV = 38, GNUTLS_CIPHER_AES_192_GCM = 39, GNUTLS_CIPHER_MAGMA_CTR_ACPKM = 40, GNUTLS_CIPHER_KUZNYECHIK_CTR_ACPKM = 41, /* used only for PGP internals. Ignored in TLS/SSL */ GNUTLS_CIPHER_IDEA_PGP_CFB = 200, GNUTLS_CIPHER_3DES_PGP_CFB = 201, GNUTLS_CIPHER_CAST5_PGP_CFB = 202, GNUTLS_CIPHER_BLOWFISH_PGP_CFB = 203, GNUTLS_CIPHER_SAFER_SK128_PGP_CFB = 204, GNUTLS_CIPHER_AES128_PGP_CFB = 205, GNUTLS_CIPHER_AES192_PGP_CFB = 206, GNUTLS_CIPHER_AES256_PGP_CFB = 207, GNUTLS_CIPHER_TWOFISH_PGP_CFB = 208 } gnutls_cipher_algorithm_t; /** * gnutls_kx_algorithm_t: * @GNUTLS_KX_UNKNOWN: Unknown key-exchange algorithm. * @GNUTLS_KX_RSA: RSA key-exchange algorithm. * @GNUTLS_KX_DHE_DSS: DHE-DSS key-exchange algorithm. * @GNUTLS_KX_DHE_RSA: DHE-RSA key-exchange algorithm. * @GNUTLS_KX_ECDHE_RSA: ECDHE-RSA key-exchange algorithm. * @GNUTLS_KX_ECDHE_ECDSA: ECDHE-ECDSA key-exchange algorithm. * @GNUTLS_KX_ANON_DH: Anon-DH key-exchange algorithm. * @GNUTLS_KX_ANON_ECDH: Anon-ECDH key-exchange algorithm. * @GNUTLS_KX_SRP: SRP key-exchange algorithm. * @GNUTLS_KX_RSA_EXPORT: RSA-EXPORT key-exchange algorithm (defunc). * @GNUTLS_KX_SRP_RSA: SRP-RSA key-exchange algorithm. * @GNUTLS_KX_SRP_DSS: SRP-DSS key-exchange algorithm. * @GNUTLS_KX_PSK: PSK key-exchange algorithm. * @GNUTLS_KX_DHE_PSK: DHE-PSK key-exchange algorithm. * @GNUTLS_KX_ECDHE_PSK: ECDHE-PSK key-exchange algorithm. * @GNUTLS_KX_RSA_PSK: RSA-PSK key-exchange algorithm. * @GNUTLS_KX_VKO_GOST_12: VKO GOST R 34.10-2012 key-exchange algorithm. * * Enumeration of different key exchange algorithms. */ typedef enum { GNUTLS_KX_UNKNOWN = 0, GNUTLS_KX_RSA = 1, GNUTLS_KX_DHE_DSS = 2, GNUTLS_KX_DHE_RSA = 3, GNUTLS_KX_ANON_DH = 4, GNUTLS_KX_SRP = 5, GNUTLS_KX_RSA_EXPORT = 6, GNUTLS_KX_SRP_RSA = 7, GNUTLS_KX_SRP_DSS = 8, GNUTLS_KX_PSK = 9, GNUTLS_KX_DHE_PSK = 10, GNUTLS_KX_ANON_ECDH = 11, GNUTLS_KX_ECDHE_RSA = 12, GNUTLS_KX_ECDHE_ECDSA = 13, GNUTLS_KX_ECDHE_PSK = 14, GNUTLS_KX_RSA_PSK = 15, GNUTLS_KX_VKO_GOST_12 = 16 } gnutls_kx_algorithm_t; /** * gnutls_params_type_t: * @GNUTLS_PARAMS_RSA_EXPORT: Session RSA-EXPORT parameters (defunc). * @GNUTLS_PARAMS_DH: Session Diffie-Hellman parameters. * @GNUTLS_PARAMS_ECDH: Session Elliptic-Curve Diffie-Hellman parameters. * * Enumeration of different TLS session parameter types. */ typedef enum { GNUTLS_PARAMS_RSA_EXPORT = 1, GNUTLS_PARAMS_DH = 2, GNUTLS_PARAMS_ECDH = 3 } gnutls_params_type_t; /** * gnutls_credentials_type_t: * @GNUTLS_CRD_CERTIFICATE: Certificate credential. * @GNUTLS_CRD_ANON: Anonymous credential. * @GNUTLS_CRD_SRP: SRP credential. * @GNUTLS_CRD_PSK: PSK credential. * @GNUTLS_CRD_IA: IA credential. * * Enumeration of different credential types. */ typedef enum { GNUTLS_CRD_CERTIFICATE = 1, GNUTLS_CRD_ANON, GNUTLS_CRD_SRP, GNUTLS_CRD_PSK, GNUTLS_CRD_IA } gnutls_credentials_type_t; #define GNUTLS_MAC_SHA GNUTLS_MAC_SHA1 #define GNUTLS_DIG_SHA GNUTLS_DIG_SHA1 /** * gnutls_mac_algorithm_t: * @GNUTLS_MAC_UNKNOWN: Unknown MAC algorithm. * @GNUTLS_MAC_NULL: NULL MAC algorithm (empty output). * @GNUTLS_MAC_MD5: HMAC-MD5 algorithm. * @GNUTLS_MAC_SHA1: HMAC-SHA-1 algorithm. * @GNUTLS_MAC_RMD160: HMAC-RMD160 algorithm. * @GNUTLS_MAC_MD2: HMAC-MD2 algorithm. * @GNUTLS_MAC_SHA256: HMAC-SHA-256 algorithm. * @GNUTLS_MAC_SHA384: HMAC-SHA-384 algorithm. * @GNUTLS_MAC_SHA512: HMAC-SHA-512 algorithm. * @GNUTLS_MAC_SHA224: HMAC-SHA-224 algorithm. * @GNUTLS_MAC_MD5_SHA1: Combined MD5+SHA1 MAC placeholder. * @GNUTLS_MAC_GOSTR_94: HMAC GOST R 34.11-94 algorithm. * @GNUTLS_MAC_STREEBOG_256: HMAC GOST R 34.11-2001 (Streebog) algorithm, 256 bit. * @GNUTLS_MAC_STREEBOG_512: HMAC GOST R 34.11-2001 (Streebog) algorithm, 512 bit. * @GNUTLS_MAC_AEAD: MAC implicit through AEAD cipher. * @GNUTLS_MAC_UMAC_96: The UMAC-96 MAC algorithm (requires nonce). * @GNUTLS_MAC_UMAC_128: The UMAC-128 MAC algorithm (requires nonce). * @GNUTLS_MAC_AES_CMAC_128: The AES-CMAC-128 MAC algorithm. * @GNUTLS_MAC_AES_CMAC_256: The AES-CMAC-256 MAC algorithm. * @GNUTLS_MAC_AES_GMAC_128: The AES-GMAC-128 MAC algorithm (requires nonce). * @GNUTLS_MAC_AES_GMAC_192: The AES-GMAC-192 MAC algorithm (requires nonce). * @GNUTLS_MAC_AES_GMAC_256: The AES-GMAC-256 MAC algorithm (requires nonce). * @GNUTLS_MAC_SHA3_224: Reserved; unimplemented. * @GNUTLS_MAC_SHA3_256: Reserved; unimplemented. * @GNUTLS_MAC_SHA3_384: Reserved; unimplemented. * @GNUTLS_MAC_SHA3_512: Reserved; unimplemented. * @GNUTLS_MAC_GOST28147_TC26Z_IMIT: The GOST 28147-89 working in IMIT mode with TC26 Z S-box. * @GNUTLS_MAC_SHAKE_128: Reserved; unimplemented. * @GNUTLS_MAC_SHAKE_256: Reserved; unimplemented. * @GNUTLS_MAC_MAGMA_OMAC: GOST R 34.12-2015 (Magma) in OMAC (CMAC) mode. * @GNUTLS_MAC_KUZNYECHIK_OMAC: GOST R 34.12-2015 (Kuznyechik) in OMAC (CMAC) mode. * * Enumeration of different Message Authentication Code (MAC) * algorithms. */ typedef enum { GNUTLS_MAC_UNKNOWN = 0, GNUTLS_MAC_NULL = 1, GNUTLS_MAC_MD5 = 2, GNUTLS_MAC_SHA1 = 3, GNUTLS_MAC_RMD160 = 4, GNUTLS_MAC_MD2 = 5, GNUTLS_MAC_SHA256 = 6, GNUTLS_MAC_SHA384 = 7, GNUTLS_MAC_SHA512 = 8, GNUTLS_MAC_SHA224 = 9, GNUTLS_MAC_SHA3_224 = 10, /* reserved: no implementation */ GNUTLS_MAC_SHA3_256 = 11, /* reserved: no implementation */ GNUTLS_MAC_SHA3_384 = 12, /* reserved: no implementation */ GNUTLS_MAC_SHA3_512 = 13, /* reserved: no implementation */ GNUTLS_MAC_MD5_SHA1 = 14, /* reserved: no implementation */ GNUTLS_MAC_GOSTR_94 = 15, GNUTLS_MAC_STREEBOG_256 = 16, GNUTLS_MAC_STREEBOG_512 = 17, /* If you add anything here, make sure you align with gnutls_digest_algorithm_t. */ GNUTLS_MAC_AEAD = 200, /* indicates that MAC is on the cipher */ GNUTLS_MAC_UMAC_96 = 201, GNUTLS_MAC_UMAC_128 = 202, GNUTLS_MAC_AES_CMAC_128 = 203, GNUTLS_MAC_AES_CMAC_256 = 204, GNUTLS_MAC_AES_GMAC_128 = 205, GNUTLS_MAC_AES_GMAC_192 = 206, GNUTLS_MAC_AES_GMAC_256 = 207, GNUTLS_MAC_GOST28147_TC26Z_IMIT = 208, GNUTLS_MAC_SHAKE_128 = 209, GNUTLS_MAC_SHAKE_256 = 210, GNUTLS_MAC_MAGMA_OMAC = 211, GNUTLS_MAC_KUZNYECHIK_OMAC = 212 } gnutls_mac_algorithm_t; /** * gnutls_digest_algorithm_t: * @GNUTLS_DIG_UNKNOWN: Unknown hash algorithm. * @GNUTLS_DIG_NULL: NULL hash algorithm (empty output). * @GNUTLS_DIG_MD5: MD5 algorithm. * @GNUTLS_DIG_SHA1: SHA-1 algorithm. * @GNUTLS_DIG_RMD160: RMD160 algorithm. * @GNUTLS_DIG_MD2: MD2 algorithm. * @GNUTLS_DIG_SHA256: SHA-256 algorithm. * @GNUTLS_DIG_SHA384: SHA-384 algorithm. * @GNUTLS_DIG_SHA512: SHA-512 algorithm. * @GNUTLS_DIG_SHA224: SHA-224 algorithm. * @GNUTLS_DIG_SHA3_224: SHA3-224 algorithm. * @GNUTLS_DIG_SHA3_256: SHA3-256 algorithm. * @GNUTLS_DIG_SHA3_384: SHA3-384 algorithm. * @GNUTLS_DIG_SHA3_512: SHA3-512 algorithm. * @GNUTLS_DIG_MD5_SHA1: Combined MD5+SHA1 algorithm. * @GNUTLS_DIG_GOSTR_94: GOST R 34.11-94 algorithm. * @GNUTLS_DIG_STREEBOG_256: GOST R 34.11-2001 (Streebog) algorithm, 256 bit. * @GNUTLS_DIG_STREEBOG_512: GOST R 34.11-2001 (Streebog) algorithm, 512 bit. * @GNUTLS_DIG_SHAKE_128: Reserved; unimplemented. * @GNUTLS_DIG_SHAKE_256: Reserved; unimplemented. * * Enumeration of different digest (hash) algorithms. */ typedef enum { GNUTLS_DIG_UNKNOWN = GNUTLS_MAC_UNKNOWN, GNUTLS_DIG_NULL = GNUTLS_MAC_NULL, GNUTLS_DIG_MD5 = GNUTLS_MAC_MD5, GNUTLS_DIG_SHA1 = GNUTLS_MAC_SHA1, GNUTLS_DIG_RMD160 = GNUTLS_MAC_RMD160, GNUTLS_DIG_MD2 = GNUTLS_MAC_MD2, GNUTLS_DIG_SHA256 = GNUTLS_MAC_SHA256, GNUTLS_DIG_SHA384 = GNUTLS_MAC_SHA384, GNUTLS_DIG_SHA512 = GNUTLS_MAC_SHA512, GNUTLS_DIG_SHA224 = GNUTLS_MAC_SHA224, GNUTLS_DIG_SHA3_224 = GNUTLS_MAC_SHA3_224, GNUTLS_DIG_SHA3_256 = GNUTLS_MAC_SHA3_256, GNUTLS_DIG_SHA3_384 = GNUTLS_MAC_SHA3_384, GNUTLS_DIG_SHA3_512 = GNUTLS_MAC_SHA3_512, GNUTLS_DIG_MD5_SHA1 = GNUTLS_MAC_MD5_SHA1, GNUTLS_DIG_GOSTR_94 = GNUTLS_MAC_GOSTR_94, GNUTLS_DIG_STREEBOG_256 = GNUTLS_MAC_STREEBOG_256, GNUTLS_DIG_STREEBOG_512 = GNUTLS_MAC_STREEBOG_512, GNUTLS_DIG_SHAKE_128 = GNUTLS_MAC_SHAKE_128, GNUTLS_DIG_SHAKE_256 = GNUTLS_MAC_SHAKE_256 /* If you add anything here, make sure you align with gnutls_mac_algorithm_t. */ } gnutls_digest_algorithm_t; /* exported for other gnutls headers. This is the maximum number of * algorithms (ciphers, kx or macs). */ #define GNUTLS_MAX_ALGORITHM_NUM 128 #define GNUTLS_MAX_SESSION_ID_SIZE 32 /** * gnutls_compression_method_t: * @GNUTLS_COMP_UNKNOWN: Unknown compression method. * @GNUTLS_COMP_NULL: The NULL compression method (no compression). * @GNUTLS_COMP_DEFLATE: The DEFLATE compression method from zlib. * @GNUTLS_COMP_ZLIB: Same as %GNUTLS_COMP_DEFLATE. * @GNUTLS_COMP_BROTLI: Brotli compression method. * @GNUTLS_COMP_ZSTD: Zstandard compression method. * * Enumeration of different TLS compression methods. */ typedef enum { GNUTLS_COMP_UNKNOWN = 0, GNUTLS_COMP_NULL = 1, GNUTLS_COMP_DEFLATE = 2, GNUTLS_COMP_ZLIB = GNUTLS_COMP_DEFLATE, GNUTLS_COMP_BROTLI = 3, GNUTLS_COMP_ZSTD = 4 } gnutls_compression_method_t; /** * gnutls_init_flags_t: * * @GNUTLS_SERVER: Connection end is a server. * @GNUTLS_CLIENT: Connection end is a client. * @GNUTLS_DATAGRAM: Connection is datagram oriented (DTLS). Since 3.0.0. * @GNUTLS_NONBLOCK: Connection should not block. Since 3.0.0. * @GNUTLS_NO_SIGNAL: In systems where SIGPIPE is delivered on send, it will be disabled. That flag has effect in systems which support the MSG_NOSIGNAL sockets flag (since 3.4.2). * @GNUTLS_NO_EXTENSIONS: Do not enable any TLS extensions by default (since 3.1.2). As TLS 1.2 and later require extensions this option is considered obsolete and should not be used. * @GNUTLS_NO_REPLAY_PROTECTION: Disable any replay protection in DTLS. This must only be used if replay protection is achieved using other means. Since 3.2.2. * @GNUTLS_ALLOW_ID_CHANGE: Allow the peer to replace its certificate, or change its ID during a rehandshake. This change is often used in attacks and thus prohibited by default. Since 3.5.0. * @GNUTLS_ENABLE_FALSE_START: Enable the TLS false start on client side if the negotiated ciphersuites allow it. This will enable sending data prior to the handshake being complete, and may introduce a risk of crypto failure when combined with certain key exchanged; for that GnuTLS may not enable that option in ciphersuites that are known to be not safe for false start. Since 3.5.0. * @GNUTLS_ENABLE_EARLY_START: Under TLS1.3 allow the server to return earlier than the full handshake * finish; similarly to false start the handshake will be completed once data are received by the * client, while the server is able to transmit sooner. This is not enabled by default as it could * break certain existing server assumptions and use-cases. Since 3.6.4. * @GNUTLS_ENABLE_EARLY_DATA: Under TLS1.3 allow the server to receive early data sent as part of the initial ClientHello (0-RTT). * This can also be used to explicitly indicate that the client will send early data. * This is not enabled by default as early data has weaker security properties than other data. Since 3.6.5. * @GNUTLS_FORCE_CLIENT_CERT: When in client side and only a single cert is specified, send that certificate irrespective of the issuers expected by the server. Since 3.5.0. * @GNUTLS_NO_TICKETS: Flag to indicate that the session should not use resumption with session tickets. * @GNUTLS_NO_TICKETS_TLS12: Flag to indicate that the session should not use resumption with session tickets. This flag only has effect if TLS 1.2 is used. * @GNUTLS_KEY_SHARE_TOP3: Generate key shares for the top-3 different groups which are enabled. * That is, as each group is associated with a key type (EC, finite field, x25519), generate * three keys using %GNUTLS_PK_DH, %GNUTLS_PK_EC, %GNUTLS_PK_ECDH_X25519 if all of them are enabled. * @GNUTLS_KEY_SHARE_TOP2: Generate key shares for the top-2 different groups which are enabled. * For example (ECDH + x25519). This is the default. * @GNUTLS_KEY_SHARE_TOP: Generate key share for the first group which is enabled. * For example x25519. This option is the most performant for client (less CPU spent * generating keys), but if the server doesn't support the advertized option it may * result to more roundtrips needed to discover the server's choice. * @GNUTLS_NO_AUTO_REKEY: Disable auto-rekeying under TLS1.3. If this option is not specified * gnutls will force a rekey after 2^24 records have been sent. * @GNUTLS_POST_HANDSHAKE_AUTH: Enable post handshake authentication for server and client. When set and * a server requests authentication after handshake %GNUTLS_E_REAUTH_REQUEST will be returned * by gnutls_record_recv(). A client should then call gnutls_reauth() to re-authenticate. * @GNUTLS_SAFE_PADDING_CHECK: Flag to indicate that the TLS 1.3 padding check will be done in a * safe way which doesn't leak the pad size based on GnuTLS processing time. This is of use to * applications which hide the length of transferred data via the TLS1.3 padding mechanism and * are already taking steps to hide the data processing time. This comes at a performance * penalty. * @GNUTLS_AUTO_REAUTH: Enable transparent re-authentication in client side when the server * requests to. That is, reauthentication is handled within gnutls_record_recv(), and * the %GNUTLS_E_REHANDSHAKE or %GNUTLS_E_REAUTH_REQUEST are not returned. This must be * enabled with %GNUTLS_POST_HANDSHAKE_AUTH for TLS1.3. Enabling this flag requires to restore * interrupted calls to gnutls_record_recv() based on the output of gnutls_record_get_direction(), * since gnutls_record_recv() could be interrupted when sending when this flag is enabled. * Note this flag may not be used if you are using the same session for sending and receiving * in different threads. * @GNUTLS_ENABLE_RAWPK: Allows raw public-keys to be negotiated during the handshake. Since 3.6.6. * @GNUTLS_NO_AUTO_SEND_TICKET: Under TLS1.3 disable auto-sending of * session tickets during the handshake. * @GNUTLS_NO_END_OF_EARLY_DATA: Under TLS1.3 suppress sending EndOfEarlyData message. Since 3.7.2. * * Enumeration of different flags for gnutls_init() function. All the flags * can be combined except @GNUTLS_SERVER and @GNUTLS_CLIENT which are mutually * exclusive. * * The key share options relate to the TLS 1.3 key share extension * which is a speculative key generation expecting that the server * would support the generated key. */ typedef enum { GNUTLS_SERVER = 1, GNUTLS_CLIENT = (1<<1), GNUTLS_DATAGRAM = (1<<2), GNUTLS_NONBLOCK = (1<<3), GNUTLS_NO_EXTENSIONS = (1<<4), GNUTLS_NO_REPLAY_PROTECTION = (1<<5), GNUTLS_NO_SIGNAL = (1<<6), GNUTLS_ALLOW_ID_CHANGE = (1<<7), GNUTLS_ENABLE_FALSE_START = (1<<8), GNUTLS_FORCE_CLIENT_CERT = (1<<9), GNUTLS_NO_TICKETS = (1<<10), GNUTLS_KEY_SHARE_TOP = (1<<11), GNUTLS_KEY_SHARE_TOP2 = (1<<12), GNUTLS_KEY_SHARE_TOP3 = (1<<13), GNUTLS_POST_HANDSHAKE_AUTH = (1<<14), GNUTLS_NO_AUTO_REKEY = (1<<15), GNUTLS_SAFE_PADDING_CHECK = (1<<16), GNUTLS_ENABLE_EARLY_START = (1<<17), GNUTLS_ENABLE_RAWPK = (1<<18), GNUTLS_AUTO_REAUTH = (1<<19), GNUTLS_ENABLE_EARLY_DATA = (1<<20), GNUTLS_NO_AUTO_SEND_TICKET = (1<<21), GNUTLS_NO_END_OF_EARLY_DATA = (1<<22), GNUTLS_NO_TICKETS_TLS12 = (1<<23) } gnutls_init_flags_t; /* compatibility defines (previous versions of gnutls * used defines instead of enumerated values). */ #define GNUTLS_SERVER (1) #define GNUTLS_CLIENT (1<<1) #define GNUTLS_DATAGRAM (1<<2) #define GNUTLS_NONBLOCK (1<<3) #define GNUTLS_NO_EXTENSIONS (1<<4) #define GNUTLS_NO_REPLAY_PROTECTION (1<<5) #define GNUTLS_NO_SIGNAL (1<<6) #define GNUTLS_ALLOW_ID_CHANGE (1<<7) #define GNUTLS_ENABLE_FALSE_START (1<<8) #define GNUTLS_FORCE_CLIENT_CERT (1<<9) #define GNUTLS_NO_TICKETS (1<<10) #define GNUTLS_ENABLE_CERT_TYPE_NEG 0 // Here for compatibility reasons /** * gnutls_alert_level_t: * @GNUTLS_AL_WARNING: Alert of warning severity. * @GNUTLS_AL_FATAL: Alert of fatal severity. * * Enumeration of different TLS alert severities. */ typedef enum { GNUTLS_AL_WARNING = 1, GNUTLS_AL_FATAL } gnutls_alert_level_t; /** * gnutls_alert_description_t: * @GNUTLS_A_CLOSE_NOTIFY: Close notify. * @GNUTLS_A_UNEXPECTED_MESSAGE: Unexpected message. * @GNUTLS_A_BAD_RECORD_MAC: Bad record MAC. * @GNUTLS_A_DECRYPTION_FAILED: Decryption failed. * @GNUTLS_A_RECORD_OVERFLOW: Record overflow. * @GNUTLS_A_DECOMPRESSION_FAILURE: Decompression failed. * @GNUTLS_A_HANDSHAKE_FAILURE: Handshake failed. * @GNUTLS_A_SSL3_NO_CERTIFICATE: No certificate. * @GNUTLS_A_BAD_CERTIFICATE: Certificate is bad. * @GNUTLS_A_UNSUPPORTED_CERTIFICATE: Certificate is not supported. * @GNUTLS_A_CERTIFICATE_REVOKED: Certificate was revoked. * @GNUTLS_A_CERTIFICATE_EXPIRED: Certificate is expired. * @GNUTLS_A_CERTIFICATE_UNKNOWN: Unknown certificate. * @GNUTLS_A_ILLEGAL_PARAMETER: Illegal parameter. * @GNUTLS_A_UNKNOWN_CA: CA is unknown. * @GNUTLS_A_ACCESS_DENIED: Access was denied. * @GNUTLS_A_DECODE_ERROR: Decode error. * @GNUTLS_A_DECRYPT_ERROR: Decrypt error. * @GNUTLS_A_EXPORT_RESTRICTION: Export restriction. * @GNUTLS_A_PROTOCOL_VERSION: Error in protocol version. * @GNUTLS_A_INSUFFICIENT_SECURITY: Insufficient security. * @GNUTLS_A_INTERNAL_ERROR: Internal error. * @GNUTLS_A_INAPPROPRIATE_FALLBACK: Inappropriate fallback, * @GNUTLS_A_USER_CANCELED: User canceled. * @GNUTLS_A_NO_RENEGOTIATION: No renegotiation is allowed. * @GNUTLS_A_MISSING_EXTENSION: An extension was expected but was not seen * @GNUTLS_A_UNSUPPORTED_EXTENSION: An unsupported extension was * sent. * @GNUTLS_A_CERTIFICATE_UNOBTAINABLE: Could not retrieve the * specified certificate. * @GNUTLS_A_UNRECOGNIZED_NAME: The server name sent was not * recognized. * @GNUTLS_A_UNKNOWN_PSK_IDENTITY: The SRP/PSK username is missing * or not known. * @GNUTLS_A_CERTIFICATE_REQUIRED: Certificate is required. * @GNUTLS_A_NO_APPLICATION_PROTOCOL: The ALPN protocol requested is * not supported by the peer. * * Enumeration of different TLS alerts. */ typedef enum { GNUTLS_A_CLOSE_NOTIFY, GNUTLS_A_UNEXPECTED_MESSAGE = 10, GNUTLS_A_BAD_RECORD_MAC = 20, GNUTLS_A_DECRYPTION_FAILED, GNUTLS_A_RECORD_OVERFLOW, GNUTLS_A_DECOMPRESSION_FAILURE = 30, GNUTLS_A_HANDSHAKE_FAILURE = 40, GNUTLS_A_SSL3_NO_CERTIFICATE = 41, GNUTLS_A_BAD_CERTIFICATE = 42, GNUTLS_A_UNSUPPORTED_CERTIFICATE, GNUTLS_A_CERTIFICATE_REVOKED, GNUTLS_A_CERTIFICATE_EXPIRED, GNUTLS_A_CERTIFICATE_UNKNOWN, GNUTLS_A_ILLEGAL_PARAMETER, GNUTLS_A_UNKNOWN_CA, GNUTLS_A_ACCESS_DENIED, GNUTLS_A_DECODE_ERROR = 50, GNUTLS_A_DECRYPT_ERROR, GNUTLS_A_EXPORT_RESTRICTION = 60, GNUTLS_A_PROTOCOL_VERSION = 70, GNUTLS_A_INSUFFICIENT_SECURITY, GNUTLS_A_INTERNAL_ERROR = 80, GNUTLS_A_INAPPROPRIATE_FALLBACK = 86, GNUTLS_A_USER_CANCELED = 90, GNUTLS_A_NO_RENEGOTIATION = 100, GNUTLS_A_MISSING_EXTENSION = 109, GNUTLS_A_UNSUPPORTED_EXTENSION = 110, GNUTLS_A_CERTIFICATE_UNOBTAINABLE = 111, GNUTLS_A_UNRECOGNIZED_NAME = 112, GNUTLS_A_UNKNOWN_PSK_IDENTITY = 115, GNUTLS_A_CERTIFICATE_REQUIRED = 116, GNUTLS_A_NO_APPLICATION_PROTOCOL = 120, GNUTLS_A_MAX = GNUTLS_A_NO_APPLICATION_PROTOCOL } gnutls_alert_description_t; /** * gnutls_handshake_description_t: * @GNUTLS_HANDSHAKE_HELLO_REQUEST: Hello request. * @GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST: DTLS Hello verify request. * @GNUTLS_HANDSHAKE_CLIENT_HELLO: Client hello. * @GNUTLS_HANDSHAKE_SERVER_HELLO: Server hello. * @GNUTLS_HANDSHAKE_END_OF_EARLY_DATA: End of early data. * @GNUTLS_HANDSHAKE_HELLO_RETRY_REQUEST: Hello retry request. * @GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: New session ticket. * @GNUTLS_HANDSHAKE_CERTIFICATE_PKT: Certificate packet. * @GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE: Server key exchange. * @GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST: Certificate request. * @GNUTLS_HANDSHAKE_SERVER_HELLO_DONE: Server hello done. * @GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY: Certificate verify. * @GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE: Client key exchange. * @GNUTLS_HANDSHAKE_FINISHED: Finished. * @GNUTLS_HANDSHAKE_CERTIFICATE_STATUS: Certificate status (OCSP). * @GNUTLS_HANDSHAKE_KEY_UPDATE: TLS1.3 key update message. * @GNUTLS_HANDSHAKE_COMPRESSED_CERTIFICATE_PKT: Compressed certificate packet. * @GNUTLS_HANDSHAKE_SUPPLEMENTAL: Supplemental. * @GNUTLS_HANDSHAKE_CHANGE_CIPHER_SPEC: Change Cipher Spec. * @GNUTLS_HANDSHAKE_CLIENT_HELLO_V2: SSLv2 Client Hello. * @GNUTLS_HANDSHAKE_ENCRYPTED_EXTENSIONS: Encrypted extensions message. * * Enumeration of different TLS handshake packets. */ typedef enum { GNUTLS_HANDSHAKE_HELLO_REQUEST = 0, GNUTLS_HANDSHAKE_CLIENT_HELLO = 1, GNUTLS_HANDSHAKE_SERVER_HELLO = 2, GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST = 3, GNUTLS_HANDSHAKE_NEW_SESSION_TICKET = 4, GNUTLS_HANDSHAKE_END_OF_EARLY_DATA = 5, GNUTLS_HANDSHAKE_ENCRYPTED_EXTENSIONS = 8, GNUTLS_HANDSHAKE_CERTIFICATE_PKT = 11, GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE = 12, GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST = 13, GNUTLS_HANDSHAKE_SERVER_HELLO_DONE = 14, GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY = 15, GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE = 16, GNUTLS_HANDSHAKE_FINISHED = 20, GNUTLS_HANDSHAKE_CERTIFICATE_STATUS = 22, GNUTLS_HANDSHAKE_SUPPLEMENTAL = 23, GNUTLS_HANDSHAKE_KEY_UPDATE = 24, GNUTLS_HANDSHAKE_COMPRESSED_CERTIFICATE_PKT = 25, GNUTLS_HANDSHAKE_CHANGE_CIPHER_SPEC = 254, GNUTLS_HANDSHAKE_CLIENT_HELLO_V2 = 1024, GNUTLS_HANDSHAKE_HELLO_RETRY_REQUEST = 1025, } gnutls_handshake_description_t; #define GNUTLS_HANDSHAKE_ANY ((unsigned int)-1) const char *gnutls_handshake_description_get_name(gnutls_handshake_description_t type); /** * gnutls_certificate_status_t: * @GNUTLS_CERT_INVALID: The certificate is not signed by one of the * known authorities or the signature is invalid (deprecated by the flags * %GNUTLS_CERT_SIGNATURE_FAILURE and %GNUTLS_CERT_SIGNER_NOT_FOUND). * @GNUTLS_CERT_SIGNATURE_FAILURE: The signature verification failed. * @GNUTLS_CERT_REVOKED: Certificate is revoked by its authority. In X.509 this will be * set only if CRLs are checked. * @GNUTLS_CERT_SIGNER_NOT_FOUND: The certificate's issuer is not known. * This is the case if the issuer is not included in the trusted certificate list. * @GNUTLS_CERT_SIGNER_NOT_CA: The certificate's signer was not a CA. This * may happen if this was a version 1 certificate, which is common with * some CAs, or a version 3 certificate without the basic constrains extension. * @GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE: The certificate's signer constraints were * violated. * @GNUTLS_CERT_INSECURE_ALGORITHM: The certificate was signed using an insecure * algorithm such as MD2 or MD5. These algorithms have been broken and * should not be trusted. * @GNUTLS_CERT_NOT_ACTIVATED: The certificate is not yet activated. * @GNUTLS_CERT_EXPIRED: The certificate has expired. * @GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED: The revocation data are old and have been superseded. * @GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE: The revocation data have a future issue date. * @GNUTLS_CERT_UNEXPECTED_OWNER: The owner is not the expected one. * @GNUTLS_CERT_MISMATCH: The certificate presented isn't the expected one (TOFU) * @GNUTLS_CERT_PURPOSE_MISMATCH: The certificate or an intermediate does not match the intended purpose (extended key usage). * @GNUTLS_CERT_MISSING_OCSP_STATUS: The certificate requires the server to send the certificate status, but no status was received. * @GNUTLS_CERT_INVALID_OCSP_STATUS: The received OCSP status response is invalid. * @GNUTLS_CERT_UNKNOWN_CRIT_EXTENSIONS: The certificate has extensions marked as critical which are not supported. * * Enumeration of certificate status codes. Note that the status * bits may have different meanings in OpenPGP keys and X.509 * certificate verification. */ typedef enum { GNUTLS_CERT_INVALID = 1 << 1, GNUTLS_CERT_REVOKED = 1 << 5, GNUTLS_CERT_SIGNER_NOT_FOUND = 1 << 6, GNUTLS_CERT_SIGNER_NOT_CA = 1 << 7, GNUTLS_CERT_INSECURE_ALGORITHM = 1 << 8, GNUTLS_CERT_NOT_ACTIVATED = 1 << 9, GNUTLS_CERT_EXPIRED = 1 << 10, GNUTLS_CERT_SIGNATURE_FAILURE = 1 << 11, GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED = 1 << 12, GNUTLS_CERT_UNEXPECTED_OWNER = 1 << 14, GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE = 1 << 15, GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE = 1 << 16, GNUTLS_CERT_MISMATCH = 1 << 17, GNUTLS_CERT_PURPOSE_MISMATCH = 1 << 18, GNUTLS_CERT_MISSING_OCSP_STATUS = 1 << 19, GNUTLS_CERT_INVALID_OCSP_STATUS = 1 << 20, GNUTLS_CERT_UNKNOWN_CRIT_EXTENSIONS = 1 << 21 } gnutls_certificate_status_t; /** * gnutls_certificate_request_t: * @GNUTLS_CERT_IGNORE: Ignore certificate. * @GNUTLS_CERT_REQUEST: Request certificate. * @GNUTLS_CERT_REQUIRE: Require certificate. * * Enumeration of certificate request types. */ typedef enum { GNUTLS_CERT_IGNORE = 0, GNUTLS_CERT_REQUEST = 1, GNUTLS_CERT_REQUIRE = 2 } gnutls_certificate_request_t; /** * gnutls_openpgp_crt_status_t: * @GNUTLS_OPENPGP_CERT: Send entire certificate. * @GNUTLS_OPENPGP_CERT_FINGERPRINT: Send only certificate fingerprint. * * Enumeration of ways to send OpenPGP certificate. */ typedef enum { GNUTLS_OPENPGP_CERT = 0, GNUTLS_OPENPGP_CERT_FINGERPRINT = 1 } gnutls_openpgp_crt_status_t; /** * gnutls_close_request_t: * @GNUTLS_SHUT_RDWR: Disallow further receives/sends. * @GNUTLS_SHUT_WR: Disallow further sends. * * Enumeration of how TLS session should be terminated. See gnutls_bye(). */ typedef enum { GNUTLS_SHUT_RDWR = 0, GNUTLS_SHUT_WR = 1 } gnutls_close_request_t; /** * gnutls_protocol_t: * @GNUTLS_SSL3: SSL version 3.0. * @GNUTLS_TLS1_0: TLS version 1.0. * @GNUTLS_TLS1: Same as %GNUTLS_TLS1_0. * @GNUTLS_TLS1_1: TLS version 1.1. * @GNUTLS_TLS1_2: TLS version 1.2. * @GNUTLS_TLS1_3: TLS version 1.3. * @GNUTLS_DTLS1_0: DTLS version 1.0. * @GNUTLS_DTLS1_2: DTLS version 1.2. * @GNUTLS_DTLS0_9: DTLS version 0.9 (Cisco AnyConnect / OpenSSL 0.9.8e). * @GNUTLS_TLS_VERSION_MAX: Maps to the highest supported TLS version. * @GNUTLS_DTLS_VERSION_MAX: Maps to the highest supported DTLS version. * @GNUTLS_VERSION_UNKNOWN: Unknown SSL/TLS version. * * Enumeration of different SSL/TLS protocol versions. */ typedef enum { GNUTLS_SSL3 = 1, GNUTLS_TLS1_0 = 2, GNUTLS_TLS1 = GNUTLS_TLS1_0, GNUTLS_TLS1_1 = 3, GNUTLS_TLS1_2 = 4, GNUTLS_TLS1_3 = 5, GNUTLS_DTLS0_9 = 200, GNUTLS_DTLS1_0 = 201, /* 201 */ GNUTLS_DTLS1_2 = 202, GNUTLS_DTLS_VERSION_MIN = GNUTLS_DTLS0_9, GNUTLS_DTLS_VERSION_MAX = GNUTLS_DTLS1_2, GNUTLS_TLS_VERSION_MAX = GNUTLS_TLS1_3, GNUTLS_VERSION_UNKNOWN = 0xff /* change it to 0xffff */ } gnutls_protocol_t; #define GNUTLS_CRT_RAW GNUTLS_CRT_RAWPK /** * gnutls_certificate_type_t: * @GNUTLS_CRT_UNKNOWN: Unknown certificate type. * @GNUTLS_CRT_X509: X.509 Certificate. * @GNUTLS_CRT_OPENPGP: OpenPGP certificate. * @GNUTLS_CRT_RAWPK: Raw public-key (SubjectPublicKeyInfo) * * Enumeration of different certificate types. */ typedef enum { GNUTLS_CRT_UNKNOWN = 0, GNUTLS_CRT_X509 = 1, GNUTLS_CRT_OPENPGP = 2, GNUTLS_CRT_RAWPK = 3, GNUTLS_CRT_MAX = GNUTLS_CRT_RAWPK } gnutls_certificate_type_t; /** * gnutls_x509_crt_fmt_t: * @GNUTLS_X509_FMT_DER: X.509 certificate in DER format (binary). * @GNUTLS_X509_FMT_PEM: X.509 certificate in PEM format (text). * * Enumeration of different certificate encoding formats. */ typedef enum { GNUTLS_X509_FMT_DER = 0, GNUTLS_X509_FMT_PEM = 1 } gnutls_x509_crt_fmt_t; /** * gnutls_certificate_print_formats_t: * @GNUTLS_CRT_PRINT_FULL: Full information about certificate. * @GNUTLS_CRT_PRINT_FULL_NUMBERS: Full information about certificate and include easy to parse public key parameters. * @GNUTLS_CRT_PRINT_COMPACT: Information about certificate name in one line, plus identification of the public key. * @GNUTLS_CRT_PRINT_ONELINE: Information about certificate in one line. * @GNUTLS_CRT_PRINT_UNSIGNED_FULL: All info for an unsigned certificate. * * Enumeration of different certificate printing variants. */ typedef enum gnutls_certificate_print_formats { GNUTLS_CRT_PRINT_FULL = 0, GNUTLS_CRT_PRINT_ONELINE = 1, GNUTLS_CRT_PRINT_UNSIGNED_FULL = 2, GNUTLS_CRT_PRINT_COMPACT = 3, GNUTLS_CRT_PRINT_FULL_NUMBERS = 4 } gnutls_certificate_print_formats_t; #define GNUTLS_PK_ECC GNUTLS_PK_ECDSA #define GNUTLS_PK_EC GNUTLS_PK_ECDSA #define GNUTLS_PK_ECDHX GNUTLS_PK_ECDH_X25519 /** * gnutls_pk_algorithm_t: * @GNUTLS_PK_UNKNOWN: Unknown public-key algorithm. * @GNUTLS_PK_RSA: RSA public-key algorithm. * @GNUTLS_PK_RSA_PSS: RSA public-key algorithm, with PSS padding. * @GNUTLS_PK_DSA: DSA public-key algorithm. * @GNUTLS_PK_DH: Diffie-Hellman algorithm. Used to generate parameters. * @GNUTLS_PK_ECDSA: Elliptic curve algorithm. These parameters are compatible with the ECDSA and ECDH algorithm. * @GNUTLS_PK_ECDH_X25519: Elliptic curve algorithm, restricted to ECDH as per rfc7748. * @GNUTLS_PK_EDDSA_ED25519: Edwards curve Digital signature algorithm. Used with SHA512 on signatures. * @GNUTLS_PK_GOST_01: GOST R 34.10-2001 algorithm per rfc5832. * @GNUTLS_PK_GOST_12_256: GOST R 34.10-2012 algorithm, 256-bit key per rfc7091. * @GNUTLS_PK_GOST_12_512: GOST R 34.10-2012 algorithm, 512-bit key per rfc7091. * @GNUTLS_PK_ECDH_X448: Elliptic curve algorithm, restricted to ECDH as per rfc7748. * @GNUTLS_PK_EDDSA_ED448: Edwards curve Digital signature algorithm. Used with SHAKE256 on signatures. * * Enumeration of different public-key algorithms. */ typedef enum { GNUTLS_PK_UNKNOWN = 0, GNUTLS_PK_RSA = 1, GNUTLS_PK_DSA = 2, GNUTLS_PK_DH = 3, GNUTLS_PK_ECDSA = 4, GNUTLS_PK_ECDH_X25519 = 5, GNUTLS_PK_RSA_PSS = 6, GNUTLS_PK_EDDSA_ED25519 = 7, GNUTLS_PK_GOST_01 = 8, GNUTLS_PK_GOST_12_256 = 9, GNUTLS_PK_GOST_12_512 = 10, GNUTLS_PK_ECDH_X448 = 11, GNUTLS_PK_EDDSA_ED448 = 12, GNUTLS_PK_MAX = GNUTLS_PK_EDDSA_ED448 } gnutls_pk_algorithm_t; const char *gnutls_pk_algorithm_get_name(gnutls_pk_algorithm_t algorithm); /** * gnutls_sign_algorithm_t: * @GNUTLS_SIGN_UNKNOWN: Unknown signature algorithm. * @GNUTLS_SIGN_RSA_RAW: Digital signature algorithm RSA with DigestInfo formatted data * @GNUTLS_SIGN_RSA_SHA1: Digital signature algorithm RSA with SHA-1 * @GNUTLS_SIGN_RSA_SHA: Same as %GNUTLS_SIGN_RSA_SHA1. * @GNUTLS_SIGN_DSA_SHA1: Digital signature algorithm DSA with SHA-1 * @GNUTLS_SIGN_DSA_SHA224: Digital signature algorithm DSA with SHA-224 * @GNUTLS_SIGN_DSA_SHA256: Digital signature algorithm DSA with SHA-256 * @GNUTLS_SIGN_DSA_SHA384: Digital signature algorithm DSA with SHA-384 * @GNUTLS_SIGN_DSA_SHA512: Digital signature algorithm DSA with SHA-512 * @GNUTLS_SIGN_DSA_SHA: Same as %GNUTLS_SIGN_DSA_SHA1. * @GNUTLS_SIGN_RSA_MD5: Digital signature algorithm RSA with MD5. * @GNUTLS_SIGN_RSA_MD2: Digital signature algorithm RSA with MD2. * @GNUTLS_SIGN_RSA_RMD160: Digital signature algorithm RSA with RMD-160. * @GNUTLS_SIGN_RSA_SHA256: Digital signature algorithm RSA with SHA-256. * @GNUTLS_SIGN_RSA_SHA384: Digital signature algorithm RSA with SHA-384. * @GNUTLS_SIGN_RSA_SHA512: Digital signature algorithm RSA with SHA-512. * @GNUTLS_SIGN_RSA_SHA224: Digital signature algorithm RSA with SHA-224. * @GNUTLS_SIGN_ECDSA_SHA1: ECDSA with SHA1. * @GNUTLS_SIGN_ECDSA_SHA224: Digital signature algorithm ECDSA with SHA-224. * @GNUTLS_SIGN_ECDSA_SHA256: Digital signature algorithm ECDSA with SHA-256. * @GNUTLS_SIGN_ECDSA_SHA384: Digital signature algorithm ECDSA with SHA-384. * @GNUTLS_SIGN_ECDSA_SHA512: Digital signature algorithm ECDSA with SHA-512. * @GNUTLS_SIGN_ECDSA_SECP256R1_SHA256: Digital signature algorithm ECDSA-SECP256R1 with SHA-256 (used in TLS 1.3 but not PKIX). * @GNUTLS_SIGN_ECDSA_SECP384R1_SHA384: Digital signature algorithm ECDSA-SECP384R1 with SHA-384 (used in TLS 1.3 but not PKIX). * @GNUTLS_SIGN_ECDSA_SECP521R1_SHA512: Digital signature algorithm ECDSA-SECP521R1 with SHA-512 (used in TLS 1.3 but not PKIX). * @GNUTLS_SIGN_ECDSA_SHA3_224: Digital signature algorithm ECDSA with SHA3-224. * @GNUTLS_SIGN_ECDSA_SHA3_256: Digital signature algorithm ECDSA with SHA3-256. * @GNUTLS_SIGN_ECDSA_SHA3_384: Digital signature algorithm ECDSA with SHA3-384. * @GNUTLS_SIGN_ECDSA_SHA3_512: Digital signature algorithm ECDSA with SHA3-512. * @GNUTLS_SIGN_DSA_SHA3_224: Digital signature algorithm DSA with SHA3-224. * @GNUTLS_SIGN_DSA_SHA3_256: Digital signature algorithm DSA with SHA3-256. * @GNUTLS_SIGN_DSA_SHA3_384: Digital signature algorithm DSA with SHA3-384. * @GNUTLS_SIGN_DSA_SHA3_512: Digital signature algorithm DSA with SHA3-512. * @GNUTLS_SIGN_RSA_SHA3_224: Digital signature algorithm RSA with SHA3-224. * @GNUTLS_SIGN_RSA_SHA3_256: Digital signature algorithm RSA with SHA3-256. * @GNUTLS_SIGN_RSA_SHA3_384: Digital signature algorithm RSA with SHA3-384. * @GNUTLS_SIGN_RSA_SHA3_512: Digital signature algorithm RSA with SHA3-512. * @GNUTLS_SIGN_RSA_PSS_RSAE_SHA256: Digital signature algorithm RSA with SHA-256, * with PSS padding (RSA PKCS#1 1.5 certificate). This signature is identical * to #GNUTLS_SIGN_RSA_PSS_SHA256, but they are distinct as the TLS1.3 protocol * treats them differently. * @GNUTLS_SIGN_RSA_PSS_RSAE_SHA384: Digital signature algorithm RSA with SHA-384, * with PSS padding (RSA PKCS#1 1.5 certificate). This signature is identical * to #GNUTLS_SIGN_RSA_PSS_SHA384, but they are distinct as the TLS1.3 protocol * treats them differently. * @GNUTLS_SIGN_RSA_PSS_RSAE_SHA512: Digital signature algorithm RSA with SHA-512, * with PSS padding (RSA PKCS#1 1.5 certificate). This signature is identical * to #GNUTLS_SIGN_RSA_PSS_SHA512, but they are distinct as the TLS1.3 protocol * treats them differently. * @GNUTLS_SIGN_RSA_PSS_SHA256: Digital signature algorithm RSA with SHA-256, with PSS padding (RSA-PSS certificate). * @GNUTLS_SIGN_RSA_PSS_SHA384: Digital signature algorithm RSA with SHA-384, with PSS padding (RSA-PSS certificate). * @GNUTLS_SIGN_RSA_PSS_SHA512: Digital signature algorithm RSA with SHA-512, with PSS padding (RSA-PSS certificate). * @GNUTLS_SIGN_EDDSA_ED25519: Digital signature algorithm EdDSA with Ed25519 curve. * @GNUTLS_SIGN_GOST_94: Digital signature algorithm GOST R 34.10-2001 with GOST R 34.11-94 * @GNUTLS_SIGN_GOST_256: Digital signature algorithm GOST R 34.10-2012 with GOST R 34.11-2012 256 bit * @GNUTLS_SIGN_GOST_512: Digital signature algorithm GOST R 34.10-2012 with GOST R 34.11-2012 512 bit * @GNUTLS_SIGN_EDDSA_ED448: Digital signature algorithm EdDSA with Ed448 curve. * * Enumeration of different digital signature algorithms. */ typedef enum { GNUTLS_SIGN_UNKNOWN = 0, GNUTLS_SIGN_RSA_SHA1 = 1, GNUTLS_SIGN_RSA_SHA = GNUTLS_SIGN_RSA_SHA1, GNUTLS_SIGN_DSA_SHA1 = 2, GNUTLS_SIGN_DSA_SHA = GNUTLS_SIGN_DSA_SHA1, GNUTLS_SIGN_RSA_MD5 = 3, GNUTLS_SIGN_RSA_MD2 = 4, GNUTLS_SIGN_RSA_RMD160 = 5, GNUTLS_SIGN_RSA_SHA256 = 6, GNUTLS_SIGN_RSA_SHA384 = 7, GNUTLS_SIGN_RSA_SHA512 = 8, GNUTLS_SIGN_RSA_SHA224 = 9, GNUTLS_SIGN_DSA_SHA224 = 10, GNUTLS_SIGN_DSA_SHA256 = 11, GNUTLS_SIGN_ECDSA_SHA1 = 12, GNUTLS_SIGN_ECDSA_SHA224 = 13, GNUTLS_SIGN_ECDSA_SHA256 = 14, GNUTLS_SIGN_ECDSA_SHA384 = 15, GNUTLS_SIGN_ECDSA_SHA512 = 16, GNUTLS_SIGN_DSA_SHA384 = 17, GNUTLS_SIGN_DSA_SHA512 = 18, GNUTLS_SIGN_ECDSA_SHA3_224 = 20, GNUTLS_SIGN_ECDSA_SHA3_256 = 21, GNUTLS_SIGN_ECDSA_SHA3_384 = 22, GNUTLS_SIGN_ECDSA_SHA3_512 = 23, GNUTLS_SIGN_DSA_SHA3_224 = 24, GNUTLS_SIGN_DSA_SHA3_256 = 25, GNUTLS_SIGN_DSA_SHA3_384 = 26, GNUTLS_SIGN_DSA_SHA3_512 = 27, GNUTLS_SIGN_RSA_SHA3_224 = 28, GNUTLS_SIGN_RSA_SHA3_256 = 29, GNUTLS_SIGN_RSA_SHA3_384 = 30, GNUTLS_SIGN_RSA_SHA3_512 = 31, GNUTLS_SIGN_RSA_PSS_SHA256 = 32, GNUTLS_SIGN_RSA_PSS_SHA384 = 33, GNUTLS_SIGN_RSA_PSS_SHA512 = 34, GNUTLS_SIGN_EDDSA_ED25519 = 35, GNUTLS_SIGN_RSA_RAW = 36, GNUTLS_SIGN_ECDSA_SECP256R1_SHA256 = 37, GNUTLS_SIGN_ECDSA_SECP384R1_SHA384 = 38, GNUTLS_SIGN_ECDSA_SECP521R1_SHA512 = 39, GNUTLS_SIGN_RSA_PSS_RSAE_SHA256 = 40, GNUTLS_SIGN_RSA_PSS_RSAE_SHA384 = 41, GNUTLS_SIGN_RSA_PSS_RSAE_SHA512 = 42, GNUTLS_SIGN_GOST_94 = 43, GNUTLS_SIGN_GOST_256 = 44, GNUTLS_SIGN_GOST_512 = 45, GNUTLS_SIGN_EDDSA_ED448 = 46, GNUTLS_SIGN_MAX = GNUTLS_SIGN_EDDSA_ED448 } gnutls_sign_algorithm_t; /** * gnutls_ecc_curve_t: * @GNUTLS_ECC_CURVE_INVALID: Cannot be known * @GNUTLS_ECC_CURVE_SECP192R1: the SECP192R1 curve * @GNUTLS_ECC_CURVE_SECP224R1: the SECP224R1 curve * @GNUTLS_ECC_CURVE_SECP256R1: the SECP256R1 curve * @GNUTLS_ECC_CURVE_SECP384R1: the SECP384R1 curve * @GNUTLS_ECC_CURVE_SECP521R1: the SECP521R1 curve * @GNUTLS_ECC_CURVE_X25519: the X25519 curve (ECDH only) * @GNUTLS_ECC_CURVE_ED25519: the Ed25519 curve * @GNUTLS_ECC_CURVE_GOST256CPA: GOST R 34.10 CryptoPro 256 A curve * @GNUTLS_ECC_CURVE_GOST256CPB: GOST R 34.10 CryptoPro 256 B curve * @GNUTLS_ECC_CURVE_GOST256CPC: GOST R 34.10 CryptoPro 256 C curve * @GNUTLS_ECC_CURVE_GOST256CPXA: GOST R 34.10 CryptoPro 256 XchA curve * @GNUTLS_ECC_CURVE_GOST256CPXB: GOST R 34.10 CryptoPro 256 XchB curve * @GNUTLS_ECC_CURVE_GOST512A: GOST R 34.10 TC26 512 A curve * @GNUTLS_ECC_CURVE_GOST512B: GOST R 34.10 TC26 512 B curve * @GNUTLS_ECC_CURVE_GOST512C: GOST R 34.10 TC26 512 C curve * @GNUTLS_ECC_CURVE_GOST256A: GOST R 34.10 TC26 256 A curve * @GNUTLS_ECC_CURVE_GOST256B: GOST R 34.10 TC26 256 B curve * @GNUTLS_ECC_CURVE_GOST256C: GOST R 34.10 TC26 256 C curve * @GNUTLS_ECC_CURVE_GOST256D: GOST R 34.10 TC26 256 D curve * @GNUTLS_ECC_CURVE_X448: the X448 curve (ECDH only) * @GNUTLS_ECC_CURVE_ED448: the Ed448 curve * * Enumeration of ECC curves. */ typedef enum { GNUTLS_ECC_CURVE_INVALID = 0, GNUTLS_ECC_CURVE_SECP224R1, GNUTLS_ECC_CURVE_SECP256R1, GNUTLS_ECC_CURVE_SECP384R1, GNUTLS_ECC_CURVE_SECP521R1, GNUTLS_ECC_CURVE_SECP192R1, GNUTLS_ECC_CURVE_X25519, GNUTLS_ECC_CURVE_ED25519, GNUTLS_ECC_CURVE_GOST256CPA, GNUTLS_ECC_CURVE_GOST256CPB, GNUTLS_ECC_CURVE_GOST256CPC, GNUTLS_ECC_CURVE_GOST256CPXA, GNUTLS_ECC_CURVE_GOST256CPXB, GNUTLS_ECC_CURVE_GOST512A, GNUTLS_ECC_CURVE_GOST512B, GNUTLS_ECC_CURVE_GOST512C, GNUTLS_ECC_CURVE_GOST256A, GNUTLS_ECC_CURVE_GOST256B, GNUTLS_ECC_CURVE_GOST256C, GNUTLS_ECC_CURVE_GOST256D, GNUTLS_ECC_CURVE_X448, GNUTLS_ECC_CURVE_ED448, GNUTLS_ECC_CURVE_MAX = GNUTLS_ECC_CURVE_ED448 } gnutls_ecc_curve_t; /** * gnutls_group_t: * @GNUTLS_GROUP_INVALID: Indicates unknown/invalid group * @GNUTLS_GROUP_SECP192R1: the SECP192R1 curve group (legacy, only for TLS 1.2 compatibility) * @GNUTLS_GROUP_SECP224R1: the SECP224R1 curve group (legacy, only for TLS 1.2 compatibility) * @GNUTLS_GROUP_SECP256R1: the SECP256R1 curve group * @GNUTLS_GROUP_SECP384R1: the SECP384R1 curve group * @GNUTLS_GROUP_SECP521R1: the SECP521R1 curve group * @GNUTLS_GROUP_X25519: the X25519 curve group * @GNUTLS_GROUP_GC256A: the GOST R 34.10 TC26 256 A curve group * @GNUTLS_GROUP_GC256B: the GOST R 34.10 TC26 256 B curve group * @GNUTLS_GROUP_GC256C: the GOST R 34.10 TC26 256 C curve group * @GNUTLS_GROUP_GC256D: the GOST R 34.10 TC26 256 D curve group * @GNUTLS_GROUP_GC512A: the GOST R 34.10 TC26 512 A curve group * @GNUTLS_GROUP_GC512B: the GOST R 34.10 TC26 512 B curve group * @GNUTLS_GROUP_GC512C: the GOST R 34.10 TC26 512 C curve group * @GNUTLS_GROUP_FFDHE2048: the FFDHE2048 group * @GNUTLS_GROUP_FFDHE3072: the FFDHE3072 group * @GNUTLS_GROUP_FFDHE4096: the FFDHE4096 group * @GNUTLS_GROUP_FFDHE6144: the FFDHE6144 group * @GNUTLS_GROUP_FFDHE8192: the FFDHE8192 group * @GNUTLS_GROUP_X448: the X448 curve group * * Enumeration of supported groups. It is intended to be backwards * compatible with the enumerations in %gnutls_ecc_curve_t for the groups * which are valid elliptic curves. */ typedef enum { GNUTLS_GROUP_INVALID = 0, GNUTLS_GROUP_SECP192R1 = GNUTLS_ECC_CURVE_SECP192R1, GNUTLS_GROUP_SECP224R1 = GNUTLS_ECC_CURVE_SECP224R1, GNUTLS_GROUP_SECP256R1 = GNUTLS_ECC_CURVE_SECP256R1, GNUTLS_GROUP_SECP384R1 = GNUTLS_ECC_CURVE_SECP384R1, GNUTLS_GROUP_SECP521R1 = GNUTLS_ECC_CURVE_SECP521R1, GNUTLS_GROUP_X25519 = GNUTLS_ECC_CURVE_X25519, GNUTLS_GROUP_X448 = GNUTLS_ECC_CURVE_X448, GNUTLS_GROUP_GC256A = GNUTLS_ECC_CURVE_GOST256A, GNUTLS_GROUP_GC256B = GNUTLS_ECC_CURVE_GOST256B, GNUTLS_GROUP_GC256C = GNUTLS_ECC_CURVE_GOST256C, GNUTLS_GROUP_GC256D = GNUTLS_ECC_CURVE_GOST256D, GNUTLS_GROUP_GC512A = GNUTLS_ECC_CURVE_GOST512A, GNUTLS_GROUP_GC512B = GNUTLS_ECC_CURVE_GOST512B, GNUTLS_GROUP_GC512C = GNUTLS_ECC_CURVE_GOST512C, GNUTLS_GROUP_FFDHE2048 = 256, GNUTLS_GROUP_FFDHE3072, GNUTLS_GROUP_FFDHE4096, GNUTLS_GROUP_FFDHE8192, GNUTLS_GROUP_FFDHE6144, GNUTLS_GROUP_MAX = GNUTLS_GROUP_FFDHE6144, } gnutls_group_t; /* macros to allow specifying a specific curve in gnutls_privkey_generate() * and gnutls_x509_privkey_generate() */ #define GNUTLS_CURVE_TO_BITS(curve) (unsigned int)(((unsigned int)1<<31)|((unsigned int)(curve))) #define GNUTLS_BITS_TO_CURVE(bits) (((unsigned int)(bits)) & 0x7FFFFFFF) #define GNUTLS_BITS_ARE_CURVE(bits) (((unsigned int)(bits)) & 0x80000000) /** * gnutls_sec_param_t: * @GNUTLS_SEC_PARAM_UNKNOWN: Cannot be known * @GNUTLS_SEC_PARAM_INSECURE: Less than 42 bits of security * @GNUTLS_SEC_PARAM_EXPORT: 42 bits of security * @GNUTLS_SEC_PARAM_VERY_WEAK: 64 bits of security * @GNUTLS_SEC_PARAM_WEAK: 72 bits of security * @GNUTLS_SEC_PARAM_LOW: 80 bits of security * @GNUTLS_SEC_PARAM_LEGACY: 96 bits of security * @GNUTLS_SEC_PARAM_MEDIUM: 112 bits of security (used to be %GNUTLS_SEC_PARAM_NORMAL) * @GNUTLS_SEC_PARAM_HIGH: 128 bits of security * @GNUTLS_SEC_PARAM_ULTRA: 192 bits of security * @GNUTLS_SEC_PARAM_FUTURE: 256 bits of security * * Enumeration of security parameters for passive attacks. */ typedef enum { GNUTLS_SEC_PARAM_UNKNOWN = 0, GNUTLS_SEC_PARAM_INSECURE = 5, GNUTLS_SEC_PARAM_EXPORT = 10, GNUTLS_SEC_PARAM_VERY_WEAK = 15, GNUTLS_SEC_PARAM_WEAK = 20, GNUTLS_SEC_PARAM_LOW = 25, GNUTLS_SEC_PARAM_LEGACY = 30, GNUTLS_SEC_PARAM_MEDIUM = 35, GNUTLS_SEC_PARAM_HIGH = 40, GNUTLS_SEC_PARAM_ULTRA = 45, GNUTLS_SEC_PARAM_FUTURE = 50, GNUTLS_SEC_PARAM_MAX = GNUTLS_SEC_PARAM_FUTURE } gnutls_sec_param_t; /* old name */ #define GNUTLS_SEC_PARAM_NORMAL GNUTLS_SEC_PARAM_MEDIUM /** * gnutls_channel_binding_t: * @GNUTLS_CB_TLS_UNIQUE: "tls-unique" (RFC 5929) channel binding * @GNUTLS_CB_TLS_SERVER_END_POINT: "tls-server-end-point" (RFC 5929) channel binding * @GNUTLS_CB_TLS_EXPORTER: "tls-exporter" (RFC 9266) channel binding * * Enumeration of supported channel binding types. */ typedef enum { GNUTLS_CB_TLS_UNIQUE, GNUTLS_CB_TLS_SERVER_END_POINT, GNUTLS_CB_TLS_EXPORTER } gnutls_channel_binding_t; /** * gnutls_gost_paramset_t: * @GNUTLS_GOST_PARAMSET_UNKNOWN: Unknown/default parameter set * @GNUTLS_GOST_PARAMSET_TC26_Z: Specified by TC26, see rfc7836 * @GNUTLS_GOST_PARAMSET_CP_A: CryptoPro-A, see rfc4357 * @GNUTLS_GOST_PARAMSET_CP_B: CryptoPro-B, see rfc4357 * @GNUTLS_GOST_PARAMSET_CP_C: CryptoPro-C, see rfc4357 * @GNUTLS_GOST_PARAMSET_CP_D: CryptoPro-D, see rfc4357 * * Enumeration of different GOST 28147 parameter sets. */ typedef enum { GNUTLS_GOST_PARAMSET_UNKNOWN = 0, GNUTLS_GOST_PARAMSET_TC26_Z, GNUTLS_GOST_PARAMSET_CP_A, GNUTLS_GOST_PARAMSET_CP_B, GNUTLS_GOST_PARAMSET_CP_C, GNUTLS_GOST_PARAMSET_CP_D } gnutls_gost_paramset_t; /** * gnutls_ctype_target_t: * @GNUTLS_CTYPE_CLIENT: for requesting client certificate type values. * @GNUTLS_CTYPE_SERVER: for requesting server certificate type values. * @GNUTLS_CTYPE_OURS: for requesting our certificate type values. * @GNUTLS_CTYPE_PEERS: for requesting the peers' certificate type values. * * Enumeration of certificate type targets with respect to asymmetric * certificate types as specified in RFC7250 and P2P connection set up * as specified in draft-vanrein-tls-symmetry-02. */ typedef enum { GNUTLS_CTYPE_CLIENT, GNUTLS_CTYPE_SERVER, GNUTLS_CTYPE_OURS, GNUTLS_CTYPE_PEERS } gnutls_ctype_target_t; /* If you want to change this, then also change the define in * gnutls_int.h, and recompile. */ typedef void *gnutls_transport_ptr_t; struct gnutls_session_int; typedef struct gnutls_session_int *gnutls_session_t; struct gnutls_dh_params_int; typedef struct gnutls_dh_params_int *gnutls_dh_params_t; /* XXX ugly. */ struct gnutls_x509_privkey_int; typedef struct gnutls_x509_privkey_int *gnutls_rsa_params_t; struct gnutls_priority_st; typedef struct gnutls_priority_st *gnutls_priority_t; typedef struct { unsigned char *data; unsigned int size; } gnutls_datum_t; typedef struct gnutls_library_config_st { const char *name; const char *value; } gnutls_library_config_st; typedef struct gnutls_params_st { gnutls_params_type_t type; union params { gnutls_dh_params_t dh; gnutls_rsa_params_t rsa_export; } params; int deinit; } gnutls_params_st; typedef int gnutls_params_function(gnutls_session_t, gnutls_params_type_t, gnutls_params_st *); /* internal functions */ int gnutls_init(gnutls_session_t * session, unsigned int flags); void gnutls_deinit(gnutls_session_t session); #define _gnutls_deinit(x) gnutls_deinit(x) int gnutls_bye(gnutls_session_t session, gnutls_close_request_t how); int gnutls_handshake(gnutls_session_t session); int gnutls_reauth(gnutls_session_t session, unsigned int flags); #define GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT ((unsigned int)-1) #define GNUTLS_INDEFINITE_TIMEOUT ((unsigned int)-2) void gnutls_handshake_set_timeout(gnutls_session_t session, unsigned int ms); int gnutls_rehandshake(gnutls_session_t session); #define GNUTLS_KU_PEER 1 int gnutls_session_key_update(gnutls_session_t session, unsigned flags); gnutls_alert_description_t gnutls_alert_get(gnutls_session_t session); int gnutls_alert_send(gnutls_session_t session, gnutls_alert_level_t level, gnutls_alert_description_t desc); int gnutls_alert_send_appropriate(gnutls_session_t session, int err); const char *gnutls_alert_get_name(gnutls_alert_description_t alert); const char *gnutls_alert_get_strname(gnutls_alert_description_t alert); gnutls_sec_param_t gnutls_pk_bits_to_sec_param(gnutls_pk_algorithm_t algo, unsigned int bits); const char *gnutls_sec_param_get_name(gnutls_sec_param_t param); unsigned int gnutls_sec_param_to_pk_bits(gnutls_pk_algorithm_t algo, gnutls_sec_param_t param); unsigned int gnutls_sec_param_to_symmetric_bits(gnutls_sec_param_t param) __GNUTLS_CONST__; /* Elliptic curves */ const char * gnutls_ecc_curve_get_name(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; const char * gnutls_ecc_curve_get_oid(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; const char * gnutls_group_get_name(gnutls_group_t group) __GNUTLS_CONST__; int gnutls_ecc_curve_get_size(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; gnutls_ecc_curve_t gnutls_ecc_curve_get(gnutls_session_t session); gnutls_group_t gnutls_group_get(gnutls_session_t session); /* get information on the current session */ gnutls_cipher_algorithm_t gnutls_cipher_get(gnutls_session_t session); gnutls_cipher_algorithm_t gnutls_early_cipher_get(gnutls_session_t session); gnutls_kx_algorithm_t gnutls_kx_get(gnutls_session_t session); gnutls_mac_algorithm_t gnutls_mac_get(gnutls_session_t session); gnutls_digest_algorithm_t gnutls_prf_hash_get(const gnutls_session_t session); gnutls_digest_algorithm_t gnutls_early_prf_hash_get(const gnutls_session_t session); gnutls_certificate_type_t gnutls_certificate_type_get(gnutls_session_t session); gnutls_certificate_type_t gnutls_certificate_type_get2(gnutls_session_t session, gnutls_ctype_target_t target); int gnutls_sign_algorithm_get(gnutls_session_t session); int gnutls_sign_algorithm_get_client(gnutls_session_t session); int gnutls_sign_algorithm_get_requested(gnutls_session_t session, size_t indx, gnutls_sign_algorithm_t * algo); /* the name of the specified algorithms */ const char * gnutls_cipher_get_name(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_mac_get_name(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_digest_get_name(gnutls_digest_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_digest_get_oid(gnutls_digest_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_kx_get_name(gnutls_kx_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_certificate_type_get_name(gnutls_certificate_type_t type) __GNUTLS_CONST__; const char * gnutls_pk_get_name(gnutls_pk_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_pk_get_oid(gnutls_pk_algorithm_t algorithm) __GNUTLS_CONST__; const char * gnutls_sign_get_name(gnutls_sign_algorithm_t algorithm) __GNUTLS_CONST__; const char *gnutls_sign_get_oid(gnutls_sign_algorithm_t sign) __GNUTLS_CONST__; const char * gnutls_gost_paramset_get_name(gnutls_gost_paramset_t param) __GNUTLS_CONST__; const char * gnutls_gost_paramset_get_oid(gnutls_gost_paramset_t param) __GNUTLS_CONST__; size_t gnutls_cipher_get_key_size(gnutls_cipher_algorithm_t algorithm) __GNUTLS_CONST__; size_t gnutls_mac_get_key_size(gnutls_mac_algorithm_t algorithm) __GNUTLS_CONST__; unsigned gnutls_sign_is_secure(gnutls_sign_algorithm_t algorithm) __GNUTLS_CONST__; /* It is possible that a signature algorithm is ok to use for short-lived * data (e.g., to sign a TLS session), but not for data that are long-lived * like certificates. This flag is about checking the security of the algorithm * for long-lived data. */ #define GNUTLS_SIGN_FLAG_SECURE_FOR_CERTS 1 unsigned gnutls_sign_is_secure2(gnutls_sign_algorithm_t algorithm, unsigned int flags) __GNUTLS_CONST__; gnutls_digest_algorithm_t gnutls_sign_get_hash_algorithm(gnutls_sign_algorithm_t sign) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_sign_get_pk_algorithm(gnutls_sign_algorithm_t sign) __GNUTLS_CONST__; gnutls_sign_algorithm_t gnutls_pk_to_sign(gnutls_pk_algorithm_t pk, gnutls_digest_algorithm_t hash) __GNUTLS_CONST__; unsigned gnutls_sign_supports_pk_algorithm(gnutls_sign_algorithm_t sign, gnutls_pk_algorithm_t pk) __GNUTLS_CONST__; #define gnutls_sign_algorithm_get_name gnutls_sign_get_name gnutls_mac_algorithm_t gnutls_mac_get_id(const char *name) __GNUTLS_CONST__; gnutls_digest_algorithm_t gnutls_digest_get_id(const char *name) __GNUTLS_CONST__; gnutls_cipher_algorithm_t gnutls_cipher_get_id(const char *name) __GNUTLS_CONST__; gnutls_kx_algorithm_t gnutls_kx_get_id(const char *name) __GNUTLS_CONST__; gnutls_protocol_t gnutls_protocol_get_id(const char *name) __GNUTLS_CONST__; gnutls_certificate_type_t gnutls_certificate_type_get_id(const char *name) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_pk_get_id(const char *name) __GNUTLS_CONST__; gnutls_sign_algorithm_t gnutls_sign_get_id(const char *name) __GNUTLS_CONST__; gnutls_ecc_curve_t gnutls_ecc_curve_get_id(const char *name) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_ecc_curve_get_pk(gnutls_ecc_curve_t curve) __GNUTLS_CONST__; gnutls_group_t gnutls_group_get_id(const char *name); gnutls_digest_algorithm_t gnutls_oid_to_digest(const char *oid) __GNUTLS_CONST__; gnutls_mac_algorithm_t gnutls_oid_to_mac(const char *oid) __GNUTLS_CONST__; gnutls_pk_algorithm_t gnutls_oid_to_pk(const char *oid) __GNUTLS_CONST__; gnutls_sign_algorithm_t gnutls_oid_to_sign(const char *oid) __GNUTLS_CONST__; gnutls_ecc_curve_t gnutls_oid_to_ecc_curve(const char *oid) __GNUTLS_CONST__; gnutls_gost_paramset_t gnutls_oid_to_gost_paramset(const char *oid) __GNUTLS_CONST__; /* list supported algorithms */ const gnutls_ecc_curve_t * gnutls_ecc_curve_list(void) __GNUTLS_PURE__; const gnutls_group_t * gnutls_group_list(void) __GNUTLS_PURE__; const gnutls_cipher_algorithm_t * gnutls_cipher_list(void) __GNUTLS_PURE__; const gnutls_mac_algorithm_t * gnutls_mac_list(void) __GNUTLS_PURE__; const gnutls_digest_algorithm_t * gnutls_digest_list(void) __GNUTLS_PURE__; const gnutls_protocol_t * gnutls_protocol_list(void) __GNUTLS_PURE__; const gnutls_certificate_type_t * gnutls_certificate_type_list(void) __GNUTLS_PURE__; const gnutls_kx_algorithm_t * gnutls_kx_list(void) __GNUTLS_PURE__; const gnutls_pk_algorithm_t * gnutls_pk_list(void) __GNUTLS_PURE__; const gnutls_sign_algorithm_t * gnutls_sign_list(void) __GNUTLS_PURE__; const char * gnutls_cipher_suite_info(size_t idx, unsigned char *cs_id, gnutls_kx_algorithm_t * kx, gnutls_cipher_algorithm_t * cipher, gnutls_mac_algorithm_t * mac, gnutls_protocol_t * min_version); /* functions for run-time enablement of algorithms */ int gnutls_ecc_curve_set_enabled(gnutls_ecc_curve_t curve, unsigned int enabled); int gnutls_sign_set_secure(gnutls_sign_algorithm_t sign, unsigned int secure); int gnutls_sign_set_secure_for_certs(gnutls_sign_algorithm_t sign, unsigned int secure); int gnutls_digest_set_secure(gnutls_digest_algorithm_t dig, unsigned int secure); int gnutls_protocol_set_enabled(gnutls_protocol_t version, unsigned int enabled); /* error functions */ int gnutls_error_is_fatal(int error) __GNUTLS_CONST__; int gnutls_error_to_alert(int err, int *level); void gnutls_perror(int error); const char * gnutls_strerror(int error) __GNUTLS_CONST__; const char * gnutls_strerror_name(int error) __GNUTLS_CONST__; /* Semi-internal functions. */ void gnutls_handshake_set_private_extensions(gnutls_session_t session, int allow); int gnutls_handshake_set_random(gnutls_session_t session, const gnutls_datum_t * random); gnutls_handshake_description_t gnutls_handshake_get_last_out(gnutls_session_t session); gnutls_handshake_description_t gnutls_handshake_get_last_in(gnutls_session_t session); /* Record layer functions. */ #define GNUTLS_HEARTBEAT_WAIT 1 int gnutls_heartbeat_ping(gnutls_session_t session, size_t data_size, unsigned int max_tries, unsigned int flags); int gnutls_heartbeat_pong(gnutls_session_t session, unsigned int flags); void gnutls_record_set_timeout(gnutls_session_t session, unsigned int ms); void gnutls_record_disable_padding(gnutls_session_t session); void gnutls_record_cork(gnutls_session_t session); #define GNUTLS_RECORD_WAIT 1 int gnutls_record_uncork(gnutls_session_t session, unsigned int flags); size_t gnutls_record_discard_queued(gnutls_session_t session); int gnutls_record_get_state(gnutls_session_t session, unsigned read, gnutls_datum_t *mac_key, gnutls_datum_t *IV, gnutls_datum_t *cipher_key, unsigned char seq_number[8]); int gnutls_record_set_state(gnutls_session_t session, unsigned read, const unsigned char seq_number[8]); typedef struct { size_t low; size_t high; } gnutls_range_st; int gnutls_range_split(gnutls_session_t session, const gnutls_range_st * orig, gnutls_range_st * small_range, gnutls_range_st * rem_range); ssize_t gnutls_record_send(gnutls_session_t session, const void *data, size_t data_size); ssize_t gnutls_record_send2(gnutls_session_t session, const void *data, size_t data_size, size_t pad, unsigned flags); ssize_t gnutls_record_send_range(gnutls_session_t session, const void *data, size_t data_size, const gnutls_range_st * range); ssize_t gnutls_record_send_file(gnutls_session_t session, int fd, off_t *offset, size_t count); ssize_t gnutls_record_recv(gnutls_session_t session, void *data, size_t data_size); typedef struct mbuffer_st *gnutls_packet_t; ssize_t gnutls_record_recv_packet(gnutls_session_t session, gnutls_packet_t *packet); void gnutls_packet_get(gnutls_packet_t packet, gnutls_datum_t *data, unsigned char *sequence); void gnutls_packet_deinit(gnutls_packet_t packet); #define gnutls_read gnutls_record_recv #define gnutls_write gnutls_record_send ssize_t gnutls_record_recv_seq(gnutls_session_t session, void *data, size_t data_size, unsigned char *seq); size_t gnutls_record_overhead_size(gnutls_session_t session); size_t gnutls_est_record_overhead_size(gnutls_protocol_t version, gnutls_cipher_algorithm_t cipher, gnutls_mac_algorithm_t mac, gnutls_compression_method_t comp, unsigned int flags) __GNUTLS_CONST__; void gnutls_session_enable_compatibility_mode(gnutls_session_t session); #define gnutls_record_set_max_empty_records(session, x) unsigned gnutls_record_can_use_length_hiding(gnutls_session_t session); int gnutls_record_get_direction(gnutls_session_t session); size_t gnutls_record_get_max_size(gnutls_session_t session); ssize_t gnutls_record_set_max_size(gnutls_session_t session, size_t size); ssize_t gnutls_record_set_max_recv_size(gnutls_session_t session, size_t size); size_t gnutls_record_check_pending(gnutls_session_t session); size_t gnutls_record_check_corked(gnutls_session_t session); size_t gnutls_record_get_max_early_data_size(gnutls_session_t session); int gnutls_record_set_max_early_data_size(gnutls_session_t session, size_t size); ssize_t gnutls_record_send_early_data(gnutls_session_t session, const void *data, size_t length); ssize_t gnutls_record_recv_early_data(gnutls_session_t session, void *data, size_t data_size); void gnutls_session_force_valid(gnutls_session_t session); int gnutls_prf(gnutls_session_t session, size_t label_size, const char *label, int server_random_first, size_t extra_size, const char *extra, size_t outsize, char *out); int gnutls_prf_rfc5705(gnutls_session_t session, size_t label_size, const char *label, size_t context_size, const char *context, size_t outsize, char *out); int gnutls_prf_early(gnutls_session_t session, size_t label_size, const char *label, size_t context_size, const char *context, size_t outsize, char *out); int gnutls_prf_raw(gnutls_session_t session, size_t label_size, const char *label, size_t seed_size, const char *seed, size_t outsize, char *out); /** * gnutls_server_name_type_t: * @GNUTLS_NAME_DNS: Domain Name System name type. * * Enumeration of different server name types. */ typedef enum { GNUTLS_NAME_DNS = 1 } gnutls_server_name_type_t; int gnutls_server_name_set(gnutls_session_t session, gnutls_server_name_type_t type, const void *name, size_t name_length); int gnutls_server_name_get(gnutls_session_t session, void *data, size_t * data_length, unsigned int *type, unsigned int indx); unsigned int gnutls_heartbeat_get_timeout(gnutls_session_t session); void gnutls_heartbeat_set_timeouts(gnutls_session_t session, unsigned int retrans_timeout, unsigned int total_timeout); #define GNUTLS_HB_PEER_ALLOWED_TO_SEND (1) #define GNUTLS_HB_PEER_NOT_ALLOWED_TO_SEND (1<<1) /* Heartbeat */ void gnutls_heartbeat_enable(gnutls_session_t session, unsigned int type); #define GNUTLS_HB_LOCAL_ALLOWED_TO_SEND (1<<2) unsigned gnutls_heartbeat_allowed(gnutls_session_t session, unsigned int type); /* Safe renegotiation */ unsigned gnutls_safe_renegotiation_status(gnutls_session_t session); unsigned gnutls_session_ext_master_secret_status(gnutls_session_t session); unsigned gnutls_session_etm_status(gnutls_session_t session); /** * gnutls_session_flags_t: * @GNUTLS_SFLAGS_SAFE_RENEGOTIATION: Safe renegotiation (RFC5746) was used * @GNUTLS_SFLAGS_EXT_MASTER_SECRET: The extended master secret (RFC7627) extension was used * @GNUTLS_SFLAGS_ETM: The encrypt then MAC (RFC7366) extension was used * @GNUTLS_SFLAGS_RFC7919: The RFC7919 Diffie-Hellman parameters were negotiated * @GNUTLS_SFLAGS_HB_LOCAL_SEND: The heartbeat negotiation allows the local side to send heartbeat messages * @GNUTLS_SFLAGS_HB_PEER_SEND: The heartbeat negotiation allows the peer to send heartbeat messages * @GNUTLS_SFLAGS_FALSE_START: False start was used in this client session. * @GNUTLS_SFLAGS_SESSION_TICKET: A session ticket has been received by the server. * @GNUTLS_SFLAGS_POST_HANDSHAKE_AUTH: Indicates client capability for post-handshake auth; set only on server side. * @GNUTLS_SFLAGS_EARLY_START: The TLS1.3 server session returned early. * @GNUTLS_SFLAGS_EARLY_DATA: The TLS1.3 early data has been received by the server. * @GNUTLS_SFLAGS_CLI_REQUESTED_OCSP: Set when the client has requested OCSP staple during handshake. * @GNUTLS_SFLAGS_SERV_REQUESTED_OCSP: Set when the server has requested OCSP staple during handshake. * * Enumeration of different session parameters. */ typedef enum { GNUTLS_SFLAGS_SAFE_RENEGOTIATION = 1, GNUTLS_SFLAGS_EXT_MASTER_SECRET = 1<<1, GNUTLS_SFLAGS_ETM = 1<<2, GNUTLS_SFLAGS_HB_LOCAL_SEND = 1<<3, GNUTLS_SFLAGS_HB_PEER_SEND = 1<<4, GNUTLS_SFLAGS_FALSE_START = 1<<5, GNUTLS_SFLAGS_RFC7919 = 1<<6, GNUTLS_SFLAGS_SESSION_TICKET = 1<<7, GNUTLS_SFLAGS_POST_HANDSHAKE_AUTH = 1<<8, GNUTLS_SFLAGS_EARLY_START = 1<<9, GNUTLS_SFLAGS_EARLY_DATA = 1<<10, GNUTLS_SFLAGS_CLI_REQUESTED_OCSP = 1<<11, GNUTLS_SFLAGS_SERV_REQUESTED_OCSP = 1<<12 } gnutls_session_flags_t; unsigned gnutls_session_get_flags(gnutls_session_t session); /** * gnutls_supplemental_data_format_type_t: * @GNUTLS_SUPPLEMENTAL_UNKNOWN: Unknown data format * * Enumeration of different supplemental data types (RFC 4680). */ typedef enum { GNUTLS_SUPPLEMENTAL_UNKNOWN = 0, } gnutls_supplemental_data_format_type_t; const char *gnutls_supplemental_get_name(gnutls_supplemental_data_format_type_t type); /* SessionTicket, RFC 5077. */ int gnutls_session_ticket_key_generate(gnutls_datum_t * key); int gnutls_session_ticket_enable_client(gnutls_session_t session); int gnutls_session_ticket_enable_server(gnutls_session_t session, const gnutls_datum_t * key); int gnutls_session_ticket_send(gnutls_session_t session, unsigned nr, unsigned flags); /* SRTP, RFC 5764 */ /** * gnutls_srtp_profile_t: * @GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80: 128 bit AES with a 80 bit HMAC-SHA1 * @GNUTLS_SRTP_AES128_CM_HMAC_SHA1_32: 128 bit AES with a 32 bit HMAC-SHA1 * @GNUTLS_SRTP_NULL_HMAC_SHA1_80: NULL cipher with a 80 bit HMAC-SHA1 * @GNUTLS_SRTP_NULL_HMAC_SHA1_32: NULL cipher with a 32 bit HMAC-SHA1 * * Enumeration of different SRTP protection profiles. */ typedef enum { GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80 = 0x0001, GNUTLS_SRTP_AES128_CM_HMAC_SHA1_32 = 0x0002, GNUTLS_SRTP_NULL_HMAC_SHA1_80 = 0x0005, GNUTLS_SRTP_NULL_HMAC_SHA1_32 = 0x0006 } gnutls_srtp_profile_t; int gnutls_srtp_set_profile(gnutls_session_t session, gnutls_srtp_profile_t profile); int gnutls_srtp_set_profile_direct(gnutls_session_t session, const char *profiles, const char **err_pos); int gnutls_srtp_get_selected_profile(gnutls_session_t session, gnutls_srtp_profile_t * profile); const char *gnutls_srtp_get_profile_name(gnutls_srtp_profile_t profile); int gnutls_srtp_get_profile_id(const char *name, gnutls_srtp_profile_t * profile); int gnutls_srtp_get_keys(gnutls_session_t session, void *key_material, unsigned int key_material_size, gnutls_datum_t * client_key, gnutls_datum_t * client_salt, gnutls_datum_t * server_key, gnutls_datum_t * server_salt); int gnutls_srtp_set_mki(gnutls_session_t session, const gnutls_datum_t * mki); int gnutls_srtp_get_mki(gnutls_session_t session, gnutls_datum_t * mki); /* COMPRESS_CERTIFICATE extension, RFC8879 */ gnutls_compression_method_t gnutls_compress_certificate_get_selected_method(gnutls_session_t session); int gnutls_compress_certificate_set_methods(gnutls_session_t session, const gnutls_compression_method_t * methods, size_t methods_len); /* ALPN TLS extension */ /** * gnutls_alpn_flags_t: * @GNUTLS_ALPN_MANDATORY: Require ALPN negotiation. The connection will be * aborted if no matching ALPN protocol is found. * @GNUTLS_ALPN_SERVER_PRECEDENCE: The choices set by the server * will take precedence over the client's. * * Enumeration of different ALPN flags. These are used by gnutls_alpn_set_protocols(). */ typedef enum { GNUTLS_ALPN_MANDATORY = 1, GNUTLS_ALPN_SERVER_PRECEDENCE = (1<<1) } gnutls_alpn_flags_t; #define GNUTLS_ALPN_MAND GNUTLS_ALPN_MANDATORY int gnutls_alpn_get_selected_protocol(gnutls_session_t session, gnutls_datum_t * protocol); int gnutls_alpn_set_protocols(gnutls_session_t session, const gnutls_datum_t * protocols, unsigned protocols_size, unsigned flags); int gnutls_key_generate(gnutls_datum_t * key, unsigned int key_size); #define GNUTLS_PRIORITY_INIT_DEF_APPEND 1 int gnutls_priority_init(gnutls_priority_t * priority_cache, const char *priorities, const char **err_pos); int gnutls_priority_init2(gnutls_priority_t * priority_cache, const char *priorities, const char **err_pos, unsigned flags); void gnutls_priority_deinit(gnutls_priority_t priority_cache); int gnutls_priority_get_cipher_suite_index(gnutls_priority_t pcache, unsigned int idx, unsigned int *sidx); #define GNUTLS_PRIORITY_LIST_INIT_KEYWORDS 1 #define GNUTLS_PRIORITY_LIST_SPECIAL 2 const char * gnutls_priority_string_list(unsigned iter, unsigned int flags); int gnutls_priority_set(gnutls_session_t session, gnutls_priority_t priority); int gnutls_priority_set_direct(gnutls_session_t session, const char *priorities, const char **err_pos); int gnutls_priority_certificate_type_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_certificate_type_list2(gnutls_priority_t pcache, const unsigned int **list, gnutls_ctype_target_t target); int gnutls_priority_sign_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_protocol_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_ecc_curve_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_group_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_kx_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_cipher_list(gnutls_priority_t pcache, const unsigned int **list); int gnutls_priority_mac_list(gnutls_priority_t pcache, const unsigned int **list); const char *gnutls_get_system_config_file(void); int gnutls_set_default_priority(gnutls_session_t session); int gnutls_set_default_priority_append(gnutls_session_t session, const char *add_prio, const char **err_pos, unsigned flags); /* Returns the name of a cipher suite */ const char * gnutls_cipher_suite_get_name(gnutls_kx_algorithm_t kx_algorithm, gnutls_cipher_algorithm_t cipher_algorithm, gnutls_mac_algorithm_t mac_algorithm) __GNUTLS_CONST__; const char * gnutls_ciphersuite_get(gnutls_session_t session) __GNUTLS_CONST__; /* get the currently used protocol version */ gnutls_protocol_t gnutls_protocol_get_version(gnutls_session_t session); const char * gnutls_protocol_get_name(gnutls_protocol_t version) __GNUTLS_CONST__; /* get/set session */ int gnutls_session_set_data(gnutls_session_t session, const void *session_data, size_t session_data_size); int gnutls_session_get_data(gnutls_session_t session, void *session_data, size_t * session_data_size); int gnutls_session_get_data2(gnutls_session_t session, gnutls_datum_t * data); void gnutls_session_get_random(gnutls_session_t session, gnutls_datum_t * client, gnutls_datum_t * server); void gnutls_session_get_master_secret(gnutls_session_t session, gnutls_datum_t * secret); char *gnutls_session_get_desc(gnutls_session_t session); typedef int gnutls_certificate_verify_function(gnutls_session_t); void gnutls_session_set_verify_function(gnutls_session_t session, gnutls_certificate_verify_function * func); /** * gnutls_vdata_types_t: * @GNUTLS_DT_UNKNOWN: Unknown data type. * @GNUTLS_DT_DNS_HOSTNAME: The data contain a null-terminated DNS hostname; the hostname will be * matched using the RFC6125 rules. If the data contain a textual IP (v4 or v6) address it will * be marched against the IPAddress Alternative name, unless the verification flag %GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES * is specified. * @GNUTLS_DT_IP_ADDRESS: The data contain a raw IP address (4 or 16 bytes). If will be matched * against the IPAddress Alternative name; option available since 3.6.0. * @GNUTLS_DT_RFC822NAME: The data contain a null-terminated email address; the email will be * matched against the RFC822Name Alternative name of the certificate, or the EMAIL DN component if the * former isn't available. Prior to matching the email address will be converted to ACE * (ASCII-compatible-encoding). * @GNUTLS_DT_KEY_PURPOSE_OID: The data contain a null-terminated key purpose OID. It will be matched * against the certificate's Extended Key Usage extension. * * Enumeration of different typed-data options. They are used as input to certificate * verification functions to provide information about the name and purpose of the * certificate. Only a single option of a type can be provided to the relevant functions * (i.e., options %GNUTLS_DT_DNS_HOSTNAME, %GNUTLS_DT_IP_ADDRESS and * %GNUTLS_DT_RFC822NAME cannot be combined). */ typedef enum { GNUTLS_DT_UNKNOWN = 0, GNUTLS_DT_DNS_HOSTNAME = 1, GNUTLS_DT_KEY_PURPOSE_OID = 2, GNUTLS_DT_RFC822NAME = 3, GNUTLS_DT_IP_ADDRESS = 4 } gnutls_vdata_types_t; typedef struct { gnutls_vdata_types_t type; unsigned char *data; unsigned int size; } gnutls_typed_vdata_st; void gnutls_session_set_verify_cert(gnutls_session_t session, const char *hostname, unsigned flags); void gnutls_session_set_verify_cert2(gnutls_session_t session, gnutls_typed_vdata_st * data, unsigned elements, unsigned flags); unsigned int gnutls_session_get_verify_cert_status(gnutls_session_t); int gnutls_session_set_premaster(gnutls_session_t session, unsigned int entity, gnutls_protocol_t version, gnutls_kx_algorithm_t kx, gnutls_cipher_algorithm_t cipher, gnutls_mac_algorithm_t mac, gnutls_compression_method_t comp, const gnutls_datum_t * master, const gnutls_datum_t * session_id); /* returns the session ID */ #define GNUTLS_MAX_SESSION_ID 32 int gnutls_session_get_id(gnutls_session_t session, void *session_id, size_t * session_id_size); int gnutls_session_get_id2(gnutls_session_t session, gnutls_datum_t * session_id); int gnutls_session_set_id(gnutls_session_t session, const gnutls_datum_t * sid); int gnutls_session_channel_binding(gnutls_session_t session, gnutls_channel_binding_t cbtype, gnutls_datum_t * cb); /* checks if this session is a resumed one */ int gnutls_session_is_resumed(gnutls_session_t session); int gnutls_session_resumption_requested(gnutls_session_t session); typedef int (*gnutls_db_store_func) (void *, gnutls_datum_t key, gnutls_datum_t data); typedef int (*gnutls_db_remove_func) (void *, gnutls_datum_t key); typedef gnutls_datum_t(*gnutls_db_retr_func) (void *, gnutls_datum_t key); void gnutls_db_set_cache_expiration(gnutls_session_t session, int seconds); unsigned gnutls_db_get_default_cache_expiration(void); void gnutls_db_remove_session(gnutls_session_t session); void gnutls_db_set_retrieve_function(gnutls_session_t session, gnutls_db_retr_func retr_func); void gnutls_db_set_remove_function(gnutls_session_t session, gnutls_db_remove_func rem_func); void gnutls_db_set_store_function(gnutls_session_t session, gnutls_db_store_func store_func); void gnutls_db_set_ptr(gnutls_session_t session, void *ptr); void *gnutls_db_get_ptr(gnutls_session_t session); int gnutls_db_check_entry(gnutls_session_t session, gnutls_datum_t session_entry); time_t gnutls_db_check_entry_time(gnutls_datum_t * entry); time_t gnutls_db_check_entry_expire_time(gnutls_datum_t * entry); /** * gnutls_handshake_hook_func: * @session: the current session * @htype: the type of the handshake message (%gnutls_handshake_description_t) * @when: non zero if this is a post-process/generation call and zero otherwise * @incoming: non zero if this is an incoming message and zero if this is an outgoing message * @msg: the (const) data of the handshake message without the handshake headers. * * Function prototype for handshake hooks. It is set using * gnutls_handshake_set_hook_function(). * * Returns: Non zero on error. */ #define GNUTLS_HOOK_POST (1) #define GNUTLS_HOOK_PRE (0) #define GNUTLS_HOOK_BOTH (-1) typedef int (*gnutls_handshake_hook_func) (gnutls_session_t, unsigned int htype, unsigned when, unsigned int incoming, const gnutls_datum_t *msg); void gnutls_handshake_set_hook_function(gnutls_session_t session, unsigned int htype, int when, gnutls_handshake_hook_func func); #define gnutls_handshake_post_client_hello_func gnutls_handshake_simple_hook_func typedef int (*gnutls_handshake_simple_hook_func) (gnutls_session_t); void gnutls_handshake_set_post_client_hello_function(gnutls_session_t session, gnutls_handshake_simple_hook_func func); void gnutls_handshake_set_max_packet_length(gnutls_session_t session, size_t max); /* returns libgnutls version (call it with a NULL argument) */ const char * gnutls_check_version(const char *req_version) __GNUTLS_CONST__; /* A macro which will allow optimizing out calls to gnutls_check_version() * when the version being compiled with is sufficient. * Used as: * if (gnutls_check_version_numerc(3,3,16)) { */ #define gnutls_check_version_numeric(a,b,c) \ ((GNUTLS_VERSION_MAJOR >= (a)) && \ ((GNUTLS_VERSION_NUMBER >= ( ((a) << 16) + ((b) << 8) + (c) )) || \ gnutls_check_version(#a "." #b "." #c))) /* Functions for setting/clearing credentials */ void gnutls_credentials_clear(gnutls_session_t session); /* cred is a structure defined by the kx algorithm */ int gnutls_credentials_set(gnutls_session_t session, gnutls_credentials_type_t type, void *cred); int gnutls_credentials_get(gnutls_session_t session, gnutls_credentials_type_t type, void **cred); #define gnutls_cred_set gnutls_credentials_set /* x.509 types */ struct gnutls_pubkey_st; typedef struct gnutls_pubkey_st *gnutls_pubkey_t; struct gnutls_privkey_st; typedef struct gnutls_privkey_st *gnutls_privkey_t; struct gnutls_x509_privkey_int; typedef struct gnutls_x509_privkey_int *gnutls_x509_privkey_t; struct gnutls_x509_crl_int; typedef struct gnutls_x509_crl_int *gnutls_x509_crl_t; struct gnutls_x509_crt_int; typedef struct gnutls_x509_crt_int *gnutls_x509_crt_t; struct gnutls_x509_crq_int; typedef struct gnutls_x509_crq_int *gnutls_x509_crq_t; struct gnutls_openpgp_keyring_int; typedef struct gnutls_openpgp_keyring_int *gnutls_openpgp_keyring_t; /* Credential structures - used in gnutls_credentials_set(); */ struct gnutls_certificate_credentials_st; typedef struct gnutls_certificate_credentials_st *gnutls_certificate_credentials_t; typedef gnutls_certificate_credentials_t gnutls_certificate_server_credentials; typedef gnutls_certificate_credentials_t gnutls_certificate_client_credentials; typedef struct gnutls_anon_server_credentials_st *gnutls_anon_server_credentials_t; typedef struct gnutls_anon_client_credentials_st *gnutls_anon_client_credentials_t; void gnutls_anon_free_server_credentials(gnutls_anon_server_credentials_t sc); int gnutls_anon_allocate_server_credentials(gnutls_anon_server_credentials_t * sc); void gnutls_anon_set_server_dh_params(gnutls_anon_server_credentials_t res, gnutls_dh_params_t dh_params); int gnutls_anon_set_server_known_dh_params(gnutls_anon_server_credentials_t res, gnutls_sec_param_t sec_param); void gnutls_anon_set_server_params_function(gnutls_anon_server_credentials_t res, gnutls_params_function * func); void gnutls_anon_free_client_credentials(gnutls_anon_client_credentials_t sc); int gnutls_anon_allocate_client_credentials(gnutls_anon_client_credentials_t * sc); /* CERTFILE is an x509 certificate in PEM form. * KEYFILE is a pkcs-1 private key in PEM form (for RSA keys). */ void gnutls_certificate_free_credentials(gnutls_certificate_credentials_t sc); int gnutls_certificate_allocate_credentials(gnutls_certificate_credentials_t * res); int gnutls_certificate_get_issuer(gnutls_certificate_credentials_t sc, gnutls_x509_crt_t cert, gnutls_x509_crt_t * issuer, unsigned int flags); int gnutls_certificate_get_crt_raw(gnutls_certificate_credentials_t sc, unsigned idx1, unsigned idx2, gnutls_datum_t * cert); void gnutls_certificate_free_keys(gnutls_certificate_credentials_t sc); void gnutls_certificate_free_cas(gnutls_certificate_credentials_t sc); void gnutls_certificate_free_ca_names(gnutls_certificate_credentials_t sc); void gnutls_certificate_free_crls(gnutls_certificate_credentials_t sc); void gnutls_certificate_set_dh_params(gnutls_certificate_credentials_t res, gnutls_dh_params_t dh_params); int gnutls_certificate_set_known_dh_params(gnutls_certificate_credentials_t res, gnutls_sec_param_t sec_param); void gnutls_certificate_set_verify_flags(gnutls_certificate_credentials_t res, unsigned int flags); unsigned int gnutls_certificate_get_verify_flags(gnutls_certificate_credentials_t res); /** * gnutls_certificate_flags: * @GNUTLS_CERTIFICATE_SKIP_KEY_CERT_MATCH: Skip the key and certificate matching check. * @GNUTLS_CERTIFICATE_API_V2: If set the gnutls_certificate_set_*key* functions will return an index of the added key pair instead of zero. * @GNUTLS_CERTIFICATE_SKIP_OCSP_RESPONSE_CHECK: If set, the gnutls_certificate_set_ocsp_status_request_file * function, will not check whether the response set matches any of the certificates. * @GNUTLS_CERTIFICATE_VERIFY_CRLS: This will enable CRL verification when added in the certificate structure. * When used, it requires CAs to be added before CRLs. * * Enumeration of different certificate credentials flags. */ typedef enum gnutls_certificate_flags { GNUTLS_CERTIFICATE_SKIP_KEY_CERT_MATCH = 1, GNUTLS_CERTIFICATE_API_V2 = (1<<1), GNUTLS_CERTIFICATE_SKIP_OCSP_RESPONSE_CHECK = (1<<2), GNUTLS_CERTIFICATE_VERIFY_CRLS = (1<<3) } gnutls_certificate_flags; void gnutls_certificate_set_flags(gnutls_certificate_credentials_t, unsigned flags); void gnutls_certificate_set_verify_limits(gnutls_certificate_credentials_t res, unsigned int max_bits, unsigned int max_depth); int gnutls_certificate_set_x509_system_trust(gnutls_certificate_credentials_t cred); int gnutls_certificate_set_x509_trust_file(gnutls_certificate_credentials_t cred, const char *cafile, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_trust_dir(gnutls_certificate_credentials_t cred, const char *ca_dir, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_trust_mem(gnutls_certificate_credentials_t res, const gnutls_datum_t * ca, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_crl_file(gnutls_certificate_credentials_t res, const char *crlfile, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_crl_mem(gnutls_certificate_credentials_t res, const gnutls_datum_t * CRL, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_key_file(gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_key_file2(gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, gnutls_x509_crt_fmt_t type, const char *pass, unsigned int flags); int gnutls_certificate_set_x509_key_mem(gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, gnutls_x509_crt_fmt_t type); int gnutls_certificate_set_x509_key_mem2(gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, gnutls_x509_crt_fmt_t type, const char *pass, unsigned int flags); void gnutls_certificate_send_x509_rdn_sequence(gnutls_session_t session, int status); int gnutls_certificate_set_x509_simple_pkcs12_file (gnutls_certificate_credentials_t res, const char *pkcs12file, gnutls_x509_crt_fmt_t type, const char *password); int gnutls_certificate_set_x509_simple_pkcs12_mem (gnutls_certificate_credentials_t res, const gnutls_datum_t * p12blob, gnutls_x509_crt_fmt_t type, const char *password); /* New functions to allow setting already parsed X.509 stuff. */ int gnutls_certificate_set_x509_key(gnutls_certificate_credentials_t res, gnutls_x509_crt_t * cert_list, int cert_list_size, gnutls_x509_privkey_t key); int gnutls_certificate_set_x509_trust(gnutls_certificate_credentials_t res, gnutls_x509_crt_t * ca_list, int ca_list_size); int gnutls_certificate_set_x509_crl(gnutls_certificate_credentials_t res, gnutls_x509_crl_t * crl_list, int crl_list_size); int gnutls_certificate_get_x509_key(gnutls_certificate_credentials_t res, unsigned index, gnutls_x509_privkey_t *key); int gnutls_certificate_get_x509_crt(gnutls_certificate_credentials_t res, unsigned index, gnutls_x509_crt_t **crt_list, unsigned *crt_list_size); /* OCSP status request extension, RFC 6066 */ typedef int (*gnutls_status_request_ocsp_func) (gnutls_session_t session, void *ptr, gnutls_datum_t *ocsp_response); void gnutls_certificate_set_ocsp_status_request_function (gnutls_certificate_credentials_t res, gnutls_status_request_ocsp_func ocsp_func, void *ptr); int gnutls_certificate_set_ocsp_status_request_function2 (gnutls_certificate_credentials_t res, unsigned idx, gnutls_status_request_ocsp_func ocsp_func, void *ptr); int gnutls_certificate_set_ocsp_status_request_file (gnutls_certificate_credentials_t res, const char *response_file, unsigned idx); int gnutls_certificate_set_ocsp_status_request_file2 (gnutls_certificate_credentials_t res, const char *response_file, unsigned idx, gnutls_x509_crt_fmt_t fmt); int gnutls_certificate_set_ocsp_status_request_mem (gnutls_certificate_credentials_t res, const gnutls_datum_t *resp, unsigned idx, gnutls_x509_crt_fmt_t fmt); typedef struct gnutls_ocsp_data_st { unsigned int version; /* must be zero */ gnutls_datum_t response; time_t exptime; unsigned char padding[32]; } gnutls_ocsp_data_st; time_t gnutls_certificate_get_ocsp_expiration(gnutls_certificate_credentials_t sc, unsigned idx, int oidx, unsigned flags); int gnutls_ocsp_status_request_enable_client(gnutls_session_t session, gnutls_datum_t * responder_id, size_t responder_id_size, gnutls_datum_t * request_extensions); int gnutls_ocsp_status_request_get(gnutls_session_t session, gnutls_datum_t * response); #define GNUTLS_OCSP_SR_IS_AVAIL 1 unsigned gnutls_ocsp_status_request_is_checked(gnutls_session_t session, unsigned int flags); int gnutls_ocsp_status_request_get2(gnutls_session_t session, unsigned idx, gnutls_datum_t * response); /* RAW public key functions (RFC7250) */ int gnutls_certificate_set_rawpk_key_mem(gnutls_certificate_credentials_t cred, const gnutls_datum_t* spki, const gnutls_datum_t* pkey, gnutls_x509_crt_fmt_t format, const char* pass, unsigned int key_usage, const char **names, unsigned int names_length, unsigned int flags); int gnutls_certificate_set_rawpk_key_file(gnutls_certificate_credentials_t cred, const char* rawpkfile, const char* privkeyfile, gnutls_x509_crt_fmt_t format, const char *pass, unsigned int key_usage, const char **names, unsigned int names_length, unsigned int privkey_flags, unsigned int pkcs11_flags); /* global state functions */ int gnutls_global_init(void); void gnutls_global_deinit(void); const gnutls_library_config_st *gnutls_get_library_config(void); /** * gnutls_time_func: * @t: where to store time. * * Function prototype for time()-like function. Set with * gnutls_global_set_time_function(). * * Returns: Number of seconds since the epoch, or (time_t)-1 on errors. */ typedef time_t(*gnutls_time_func) (time_t * t); typedef int (*mutex_init_func) (void **mutex); typedef int (*mutex_lock_func) (void **mutex); typedef int (*mutex_unlock_func) (void **mutex); typedef int (*mutex_deinit_func) (void **mutex); void gnutls_global_set_mutex(mutex_init_func init, mutex_deinit_func deinit, mutex_lock_func lock, mutex_unlock_func unlock); typedef void *(*gnutls_alloc_function) (size_t); typedef void *(*gnutls_calloc_function) (size_t, size_t); typedef int (*gnutls_is_secure_function) (const void *); typedef void (*gnutls_free_function) (void *); typedef void *(*gnutls_realloc_function) (void *, size_t); void gnutls_global_set_time_function(gnutls_time_func time_func); /* For use in callbacks */ extern _SYM_EXPORT gnutls_alloc_function gnutls_malloc; extern _SYM_EXPORT gnutls_realloc_function gnutls_realloc; extern _SYM_EXPORT gnutls_calloc_function gnutls_calloc; extern _SYM_EXPORT gnutls_free_function gnutls_free; #ifdef GNUTLS_INTERNAL_BUILD #define gnutls_free(a) gnutls_free((void *) (a)), a=NULL #endif extern _SYM_EXPORT char *(*gnutls_strdup) (const char *); /* a variant of memset that doesn't get optimized out */ void gnutls_memset(void *data, int c, size_t size); /* constant time memcmp */ int gnutls_memcmp(const void *s1, const void *s2, size_t n); typedef void (*gnutls_log_func) (int, const char *); typedef void (*gnutls_audit_log_func) (gnutls_session_t, const char *); void gnutls_global_set_log_function(gnutls_log_func log_func); void gnutls_global_set_audit_log_function(gnutls_audit_log_func log_func); void gnutls_global_set_log_level(int level); /** * gnutls_keylog_func: * @session: the current session * @label: the keylog label * @secret: the (const) data of the derived secret. * * Function prototype for keylog hooks. It is set using * gnutls_session_set_keylog_function(). * * Returns: Non zero on error. * Since: 3.6.13 */ typedef int (*gnutls_keylog_func) (gnutls_session_t session, const char *label, const gnutls_datum_t *secret); gnutls_keylog_func gnutls_session_get_keylog_function(const gnutls_session_t session); void gnutls_session_set_keylog_function(gnutls_session_t session, gnutls_keylog_func func); /* Diffie-Hellman parameter handling. */ int gnutls_dh_params_init(gnutls_dh_params_t * dh_params); void gnutls_dh_params_deinit(gnutls_dh_params_t dh_params); int gnutls_dh_params_import_raw(gnutls_dh_params_t dh_params, const gnutls_datum_t * prime, const gnutls_datum_t * generator); int gnutls_dh_params_import_dsa(gnutls_dh_params_t dh_params, gnutls_x509_privkey_t key); int gnutls_dh_params_import_raw2(gnutls_dh_params_t dh_params, const gnutls_datum_t * prime, const gnutls_datum_t * generator, unsigned key_bits); int gnutls_dh_params_import_raw3(gnutls_dh_params_t dh_params, const gnutls_datum_t * prime, const gnutls_datum_t * q, const gnutls_datum_t * generator); int gnutls_dh_params_import_pkcs3(gnutls_dh_params_t params, const gnutls_datum_t * pkcs3_params, gnutls_x509_crt_fmt_t format); int gnutls_dh_params_generate2(gnutls_dh_params_t params, unsigned int bits); int gnutls_dh_params_export_pkcs3(gnutls_dh_params_t params, gnutls_x509_crt_fmt_t format, unsigned char *params_data, size_t * params_data_size); int gnutls_dh_params_export2_pkcs3(gnutls_dh_params_t params, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_dh_params_export_raw(gnutls_dh_params_t params, gnutls_datum_t * prime, gnutls_datum_t * generator, unsigned int *bits); int gnutls_dh_params_cpy(gnutls_dh_params_t dst, gnutls_dh_params_t src); /* Session stuff */ typedef struct { void *iov_base; size_t iov_len; } giovec_t; typedef ssize_t(*gnutls_pull_func) (gnutls_transport_ptr_t, void *, size_t); typedef ssize_t(*gnutls_push_func) (gnutls_transport_ptr_t, const void *, size_t); int gnutls_system_recv_timeout(gnutls_transport_ptr_t ptr, unsigned int ms); typedef int (*gnutls_pull_timeout_func) (gnutls_transport_ptr_t, unsigned int ms); typedef ssize_t(*gnutls_vec_push_func) (gnutls_transport_ptr_t, const giovec_t * iov, int iovcnt); typedef int (*gnutls_errno_func) (gnutls_transport_ptr_t); #if 0 /* This will be defined as macro. */ void gnutls_transport_set_int (gnutls_session_t session, int r); #endif void gnutls_transport_set_int2(gnutls_session_t session, int r, int s); #define gnutls_transport_set_int(s, i) gnutls_transport_set_int2(s, i, i) void gnutls_transport_get_int2(gnutls_session_t session, int *r, int *s); int gnutls_transport_get_int(gnutls_session_t session); void gnutls_transport_set_ptr(gnutls_session_t session, gnutls_transport_ptr_t ptr); void gnutls_transport_set_ptr2(gnutls_session_t session, gnutls_transport_ptr_t recv_ptr, gnutls_transport_ptr_t send_ptr); gnutls_transport_ptr_t gnutls_transport_get_ptr(gnutls_session_t session); void gnutls_transport_get_ptr2(gnutls_session_t session, gnutls_transport_ptr_t * recv_ptr, gnutls_transport_ptr_t * send_ptr); void gnutls_transport_set_vec_push_function(gnutls_session_t session, gnutls_vec_push_func vec_func); void gnutls_transport_set_push_function(gnutls_session_t session, gnutls_push_func push_func); void gnutls_transport_set_pull_function(gnutls_session_t session, gnutls_pull_func pull_func); void gnutls_transport_set_pull_timeout_function(gnutls_session_t session, gnutls_pull_timeout_func func); void gnutls_transport_set_errno_function(gnutls_session_t session, gnutls_errno_func errno_func); void gnutls_transport_set_errno(gnutls_session_t session, int err); /* session specific */ void gnutls_session_set_ptr(gnutls_session_t session, void *ptr); void *gnutls_session_get_ptr(gnutls_session_t session); void gnutls_openpgp_send_cert(gnutls_session_t session, gnutls_openpgp_crt_status_t status); /* This function returns the hash of the given data. */ int gnutls_fingerprint(gnutls_digest_algorithm_t algo, const gnutls_datum_t * data, void *result, size_t * result_size); /** * gnutls_random_art_t: * @GNUTLS_RANDOM_ART_OPENSSH: OpenSSH-style random art. * * Enumeration of different random art types. */ typedef enum gnutls_random_art { GNUTLS_RANDOM_ART_OPENSSH = 1 } gnutls_random_art_t; int gnutls_random_art(gnutls_random_art_t type, const char *key_type, unsigned int key_size, void *fpr, size_t fpr_size, gnutls_datum_t * art); /* IDNA */ #define GNUTLS_IDNA_FORCE_2008 (1<<1) int gnutls_idna_map(const char * input, unsigned ilen, gnutls_datum_t *out, unsigned flags); int gnutls_idna_reverse_map(const char *input, unsigned ilen, gnutls_datum_t *out, unsigned flags); /* SRP */ typedef struct gnutls_srp_server_credentials_st *gnutls_srp_server_credentials_t; typedef struct gnutls_srp_client_credentials_st *gnutls_srp_client_credentials_t; void gnutls_srp_free_client_credentials(gnutls_srp_client_credentials_t sc); int gnutls_srp_allocate_client_credentials(gnutls_srp_client_credentials_t * sc); int gnutls_srp_set_client_credentials(gnutls_srp_client_credentials_t res, const char *username, const char *password); void gnutls_srp_free_server_credentials(gnutls_srp_server_credentials_t sc); int gnutls_srp_allocate_server_credentials(gnutls_srp_server_credentials_t * sc); int gnutls_srp_set_server_credentials_file(gnutls_srp_server_credentials_t res, const char *password_file, const char *password_conf_file); const char *gnutls_srp_server_get_username(gnutls_session_t session); void gnutls_srp_set_prime_bits(gnutls_session_t session, unsigned int bits); int gnutls_srp_verifier(const char *username, const char *password, const gnutls_datum_t * salt, const gnutls_datum_t * generator, const gnutls_datum_t * prime, gnutls_datum_t * res); /* The static parameters defined in draft-ietf-tls-srp-05 * Those should be used as input to gnutls_srp_verifier(). */ extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_8192_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_8192_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_4096_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_4096_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_3072_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_3072_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_2048_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_2048_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1536_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1536_group_generator; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1024_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_srp_1024_group_generator; /* The static parameters defined in rfc7919 */ extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_8192_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_8192_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_8192_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_8192_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_6144_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_6144_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_6144_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_6144_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_4096_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_4096_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_4096_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_4096_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_3072_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_3072_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_3072_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_3072_key_bits; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_2048_group_prime; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_2048_group_q; extern _SYM_EXPORT const gnutls_datum_t gnutls_ffdhe_2048_group_generator; extern _SYM_EXPORT const unsigned int gnutls_ffdhe_2048_key_bits; typedef int gnutls_srp_server_credentials_function(gnutls_session_t, const char *username, gnutls_datum_t * salt, gnutls_datum_t * verifier, gnutls_datum_t * generator, gnutls_datum_t * prime); void gnutls_srp_set_server_credentials_function(gnutls_srp_server_credentials_t cred, gnutls_srp_server_credentials_function * func); typedef int gnutls_srp_client_credentials_function(gnutls_session_t, char **, char **); void gnutls_srp_set_client_credentials_function(gnutls_srp_client_credentials_t cred, gnutls_srp_client_credentials_function * func); int gnutls_srp_base64_encode(const gnutls_datum_t * data, char *result, size_t * result_size); int gnutls_srp_base64_encode2(const gnutls_datum_t * data, gnutls_datum_t * result); int gnutls_srp_base64_decode(const gnutls_datum_t * b64_data, char *result, size_t * result_size); int gnutls_srp_base64_decode2(const gnutls_datum_t * b64_data, gnutls_datum_t * result); #define gnutls_srp_base64_encode_alloc gnutls_srp_base64_encode2 #define gnutls_srp_base64_decode_alloc gnutls_srp_base64_decode2 void gnutls_srp_set_server_fake_salt_seed(gnutls_srp_server_credentials_t sc, const gnutls_datum_t * seed, unsigned int salt_length); /* PSK stuff */ typedef struct gnutls_psk_server_credentials_st *gnutls_psk_server_credentials_t; typedef struct gnutls_psk_client_credentials_st *gnutls_psk_client_credentials_t; /** * gnutls_psk_key_flags: * @GNUTLS_PSK_KEY_RAW: PSK-key in raw format. * @GNUTLS_PSK_KEY_HEX: PSK-key in hex format. * * Enumeration of different PSK key flags. */ typedef enum gnutls_psk_key_flags { GNUTLS_PSK_KEY_RAW = 0, GNUTLS_PSK_KEY_HEX } gnutls_psk_key_flags; void gnutls_psk_free_client_credentials(gnutls_psk_client_credentials_t sc); int gnutls_psk_allocate_client_credentials(gnutls_psk_client_credentials_t * sc); int gnutls_psk_set_client_credentials(gnutls_psk_client_credentials_t res, const char *username, const gnutls_datum_t * key, gnutls_psk_key_flags flags); int gnutls_psk_set_client_credentials2(gnutls_psk_client_credentials_t res, const gnutls_datum_t *username, const gnutls_datum_t *key, gnutls_psk_key_flags flags); void gnutls_psk_free_server_credentials(gnutls_psk_server_credentials_t sc); int gnutls_psk_allocate_server_credentials(gnutls_psk_server_credentials_t * sc); int gnutls_psk_set_server_credentials_file(gnutls_psk_server_credentials_t res, const char *password_file); int gnutls_psk_set_server_credentials_hint(gnutls_psk_server_credentials_t res, const char *hint); const char *gnutls_psk_server_get_username(gnutls_session_t session); int gnutls_psk_server_get_username2(gnutls_session_t session, gnutls_datum_t *out); const char *gnutls_psk_client_get_hint(gnutls_session_t session); typedef int gnutls_psk_server_credentials_function(gnutls_session_t, const char *username, gnutls_datum_t * key); typedef int gnutls_psk_server_credentials_function2(gnutls_session_t, const gnutls_datum_t *username, gnutls_datum_t *key); void gnutls_psk_set_server_credentials_function(gnutls_psk_server_credentials_t cred, gnutls_psk_server_credentials_function * func); void gnutls_psk_set_server_credentials_function2(gnutls_psk_server_credentials_t cred, gnutls_psk_server_credentials_function2 *func); typedef int gnutls_psk_client_credentials_function(gnutls_session_t, char **username, gnutls_datum_t * key); typedef int gnutls_psk_client_credentials_function2(gnutls_session_t, gnutls_datum_t *username, gnutls_datum_t *key); void gnutls_psk_set_client_credentials_function(gnutls_psk_client_credentials_t cred, gnutls_psk_client_credentials_function * func); void gnutls_psk_set_client_credentials_function2(gnutls_psk_client_credentials_t cred, gnutls_psk_client_credentials_function2 *func); int gnutls_hex_encode(const gnutls_datum_t * data, char *result, size_t * result_size); int gnutls_hex_decode(const gnutls_datum_t * hex_data, void *result, size_t * result_size); int gnutls_hex_encode2(const gnutls_datum_t * data, gnutls_datum_t *result); int gnutls_hex_decode2(const gnutls_datum_t * data, gnutls_datum_t *result); void gnutls_psk_set_server_dh_params(gnutls_psk_server_credentials_t res, gnutls_dh_params_t dh_params); int gnutls_psk_set_server_known_dh_params(gnutls_psk_server_credentials_t res, gnutls_sec_param_t sec_param); void gnutls_psk_set_server_params_function(gnutls_psk_server_credentials_t res, gnutls_params_function * func); /** * gnutls_x509_subject_alt_name_t: * @GNUTLS_SAN_DNSNAME: DNS-name SAN. * @GNUTLS_SAN_RFC822NAME: E-mail address SAN. * @GNUTLS_SAN_URI: URI SAN. * @GNUTLS_SAN_IPADDRESS: IP address SAN. * @GNUTLS_SAN_OTHERNAME: OtherName SAN. * @GNUTLS_SAN_DN: DN SAN. * @GNUTLS_SAN_REGISTERED_ID: RegisteredID. * @GNUTLS_SAN_OTHERNAME_XMPP: Virtual SAN, used by certain functions for convenience. * @GNUTLS_SAN_OTHERNAME_KRB5PRINCIPAL: Virtual SAN, used by certain functions for convenience. * @GNUTLS_SAN_OTHERNAME_MSUSERPRINCIPAL: Virtual SAN, used by certain functions for convenience. * * Enumeration of different subject alternative names types. */ typedef enum gnutls_x509_subject_alt_name_t { GNUTLS_SAN_DNSNAME = 1, GNUTLS_SAN_RFC822NAME = 2, GNUTLS_SAN_URI = 3, GNUTLS_SAN_IPADDRESS = 4, GNUTLS_SAN_OTHERNAME = 5, GNUTLS_SAN_DN = 6, GNUTLS_SAN_REGISTERED_ID = 7, GNUTLS_SAN_MAX = GNUTLS_SAN_REGISTERED_ID, /* The following are "virtual" subject alternative name types, in that they are represented by an otherName value and an OID. Used by gnutls_x509_crt_get_subject_alt_othername_oid. */ GNUTLS_SAN_OTHERNAME_XMPP = 1000, GNUTLS_SAN_OTHERNAME_KRB5PRINCIPAL, GNUTLS_SAN_OTHERNAME_MSUSERPRINCIPAL } gnutls_x509_subject_alt_name_t; struct gnutls_openpgp_crt_int; typedef struct gnutls_openpgp_crt_int *gnutls_openpgp_crt_t; struct gnutls_openpgp_privkey_int; typedef struct gnutls_openpgp_privkey_int *gnutls_openpgp_privkey_t; struct gnutls_pkcs11_privkey_st; typedef struct gnutls_pkcs11_privkey_st *gnutls_pkcs11_privkey_t; /** * gnutls_privkey_type_t: * @GNUTLS_PRIVKEY_X509: X.509 private key, #gnutls_x509_privkey_t. * @GNUTLS_PRIVKEY_OPENPGP: OpenPGP private key, #gnutls_openpgp_privkey_t. * @GNUTLS_PRIVKEY_PKCS11: PKCS11 private key, #gnutls_pkcs11_privkey_t. * @GNUTLS_PRIVKEY_EXT: External private key, operating using callbacks. * * Enumeration of different private key types. */ typedef enum { GNUTLS_PRIVKEY_X509, GNUTLS_PRIVKEY_OPENPGP, GNUTLS_PRIVKEY_PKCS11, GNUTLS_PRIVKEY_EXT } gnutls_privkey_type_t; typedef struct gnutls_retr2_st { gnutls_certificate_type_t cert_type; gnutls_privkey_type_t key_type; union { gnutls_x509_crt_t *x509; gnutls_openpgp_crt_t pgp; } cert; unsigned int ncerts; /* one for pgp keys */ union { gnutls_x509_privkey_t x509; gnutls_openpgp_privkey_t pgp; gnutls_pkcs11_privkey_t pkcs11; } key; unsigned int deinit_all; /* if non zero all keys will be deinited */ } gnutls_retr2_st; /* Functions that allow auth_info_t structures handling */ gnutls_credentials_type_t gnutls_auth_get_type(gnutls_session_t session); gnutls_credentials_type_t gnutls_auth_server_get_type(gnutls_session_t session); gnutls_credentials_type_t gnutls_auth_client_get_type(gnutls_session_t session); /* DH */ void gnutls_dh_set_prime_bits(gnutls_session_t session, unsigned int bits); int gnutls_dh_get_secret_bits(gnutls_session_t session); int gnutls_dh_get_peers_public_bits(gnutls_session_t session); int gnutls_dh_get_prime_bits(gnutls_session_t session); int gnutls_dh_get_group(gnutls_session_t session, gnutls_datum_t * raw_gen, gnutls_datum_t * raw_prime); int gnutls_dh_get_pubkey(gnutls_session_t session, gnutls_datum_t * raw_key); /* X509PKI */ /* These are set on the credentials structure. */ /* use gnutls_certificate_set_retrieve_function2() in abstract.h * instead. It's much more efficient. */ typedef int gnutls_certificate_retrieve_function(gnutls_session_t, const gnutls_datum_t * req_ca_rdn, int nreqs, const gnutls_pk_algorithm_t * pk_algos, int pk_algos_length, gnutls_retr2_st *); void gnutls_certificate_set_retrieve_function(gnutls_certificate_credentials_t cred, gnutls_certificate_retrieve_function * func); void gnutls_certificate_set_verify_function(gnutls_certificate_credentials_t cred, gnutls_certificate_verify_function * func); void gnutls_certificate_server_set_request(gnutls_session_t session, gnutls_certificate_request_t req); /* get data from the session */ const gnutls_datum_t *gnutls_certificate_get_peers(gnutls_session_t session, unsigned int *list_size); const gnutls_datum_t *gnutls_certificate_get_ours(gnutls_session_t session); int gnutls_certificate_get_peers_subkey_id(gnutls_session_t session, gnutls_datum_t * id); time_t gnutls_certificate_activation_time_peers(gnutls_session_t session); time_t gnutls_certificate_expiration_time_peers(gnutls_session_t session); unsigned gnutls_certificate_client_get_request_status(gnutls_session_t session); int gnutls_certificate_verify_peers2(gnutls_session_t session, unsigned int *status); int gnutls_certificate_verify_peers3(gnutls_session_t session, const char *hostname, unsigned int *status); int gnutls_certificate_verify_peers(gnutls_session_t session, gnutls_typed_vdata_st * data, unsigned int elements, unsigned int *status); int gnutls_certificate_verification_status_print(unsigned int status, gnutls_certificate_type_t type, gnutls_datum_t * out, unsigned int flags); int gnutls_pem_base64_encode(const char *msg, const gnutls_datum_t * data, char *result, size_t * result_size); int gnutls_pem_base64_decode(const char *header, const gnutls_datum_t * b64_data, unsigned char *result, size_t * result_size); int gnutls_pem_base64_encode2(const char *msg, const gnutls_datum_t * data, gnutls_datum_t * result); int gnutls_pem_base64_decode2(const char *header, const gnutls_datum_t * b64_data, gnutls_datum_t * result); int gnutls_base64_encode2(const gnutls_datum_t * data, gnutls_datum_t * result); int gnutls_base64_decode2(const gnutls_datum_t * b64_data, gnutls_datum_t * result); #define gnutls_pem_base64_encode_alloc gnutls_pem_base64_encode2 #define gnutls_pem_base64_decode_alloc gnutls_pem_base64_decode2 /* key_usage will be an OR of the following values: */ /* when the key is to be used for signing: */ #define GNUTLS_KEY_DIGITAL_SIGNATURE 128 #define GNUTLS_KEY_NON_REPUDIATION 64 /* when the key is to be used for encryption: */ #define GNUTLS_KEY_KEY_ENCIPHERMENT 32 #define GNUTLS_KEY_DATA_ENCIPHERMENT 16 #define GNUTLS_KEY_KEY_AGREEMENT 8 #define GNUTLS_KEY_KEY_CERT_SIGN 4 #define GNUTLS_KEY_CRL_SIGN 2 #define GNUTLS_KEY_ENCIPHER_ONLY 1 #define GNUTLS_KEY_DECIPHER_ONLY 32768 void gnutls_certificate_set_params_function(gnutls_certificate_credentials_t res, gnutls_params_function * func); void gnutls_anon_set_params_function(gnutls_anon_server_credentials_t res, gnutls_params_function * func); void gnutls_psk_set_params_function(gnutls_psk_server_credentials_t res, gnutls_params_function * func); int gnutls_hex2bin(const char *hex_data, size_t hex_size, void *bin_data, size_t * bin_size); /* Trust on first use (or ssh like) functions */ /* stores the provided information to a database */ typedef int (*gnutls_tdb_store_func) (const char *db_name, const char *host, const char *service, time_t expiration, const gnutls_datum_t * pubkey); typedef int (*gnutls_tdb_store_commitment_func) (const char *db_name, const char *host, const char *service, time_t expiration, gnutls_digest_algorithm_t hash_algo, const gnutls_datum_t * hash); /* searches for the provided host/service pair that match the * provided public key in the database. */ typedef int (*gnutls_tdb_verify_func) (const char *db_name, const char *host, const char *service, const gnutls_datum_t * pubkey); struct gnutls_tdb_int; typedef struct gnutls_tdb_int *gnutls_tdb_t; int gnutls_tdb_init(gnutls_tdb_t * tdb); void gnutls_tdb_set_store_func(gnutls_tdb_t tdb, gnutls_tdb_store_func store); void gnutls_tdb_set_store_commitment_func(gnutls_tdb_t tdb, gnutls_tdb_store_commitment_func cstore); void gnutls_tdb_set_verify_func(gnutls_tdb_t tdb, gnutls_tdb_verify_func verify); void gnutls_tdb_deinit(gnutls_tdb_t tdb); int gnutls_verify_stored_pubkey(const char *db_name, gnutls_tdb_t tdb, const char *host, const char *service, gnutls_certificate_type_t cert_type, const gnutls_datum_t * cert, unsigned int flags); #define GNUTLS_SCOMMIT_FLAG_ALLOW_BROKEN 1 int gnutls_store_commitment(const char *db_name, gnutls_tdb_t tdb, const char *host, const char *service, gnutls_digest_algorithm_t hash_algo, const gnutls_datum_t * hash, time_t expiration, unsigned int flags); int gnutls_store_pubkey(const char *db_name, gnutls_tdb_t tdb, const char *host, const char *service, gnutls_certificate_type_t cert_type, const gnutls_datum_t * cert, time_t expiration, unsigned int flags); /* Other helper functions */ int gnutls_load_file(const char *filename, gnutls_datum_t * data); unsigned gnutls_url_is_supported(const char *url); /* PIN callback */ /** * gnutls_pin_flag_t: * @GNUTLS_PIN_USER: The PIN for the user. * @GNUTLS_PIN_SO: The PIN for the security officer (admin). * @GNUTLS_PIN_CONTEXT_SPECIFIC: The PIN is for a specific action and key like signing. * @GNUTLS_PIN_FINAL_TRY: This is the final try before blocking. * @GNUTLS_PIN_COUNT_LOW: Few tries remain before token blocks. * @GNUTLS_PIN_WRONG: Last given PIN was not correct. * * Enumeration of different flags that are input to the PIN function. */ typedef enum { GNUTLS_PIN_USER = (1 << 0), GNUTLS_PIN_SO = (1 << 1), GNUTLS_PIN_FINAL_TRY = (1 << 2), GNUTLS_PIN_COUNT_LOW = (1 << 3), GNUTLS_PIN_CONTEXT_SPECIFIC = (1 << 4), GNUTLS_PIN_WRONG = (1 << 5) } gnutls_pin_flag_t; #define GNUTLS_PKCS11_PIN_USER GNUTLS_PIN_USER #define GNUTLS_PKCS11_PIN_SO GNUTLS_PIN_SO #define GNUTLS_PKCS11_PIN_FINAL_TRY GNUTLS_PIN_FINAL_TRY #define GNUTLS_PKCS11_PIN_COUNT_LOW GNUTLS_PIN_COUNT_LOW #define GNUTLS_PKCS11_PIN_CONTEXT_SPECIFIC GNUTLS_PIN_CONTEXT_SPECIFIC #define GNUTLS_PKCS11_PIN_WRONG GNUTLS_PIN_WRONG /** * gnutls_pin_callback_t: * @userdata: user-controlled data from gnutls_pkcs11_set_pin_function(). * @attempt: pin-attempt counter, initially 0. * @token_url: URL of token. * @token_label: label of token. * @flags: a #gnutls_pin_flag_t flag. * @pin: buffer to hold PIN, of size @pin_max. * @pin_max: size of @pin buffer. * * Callback function type for PKCS#11 or TPM PIN entry. It is set by * functions like gnutls_pkcs11_set_pin_function(). * * The callback should provides the PIN code to unlock the token with * label @token_label, specified by the URL @token_url. * * The PIN code, as a NUL-terminated ASCII string, should be copied * into the @pin buffer (of maximum size @pin_max), and return 0 to * indicate success. Alternatively, the callback may return a * negative gnutls error code to indicate failure and cancel PIN entry * (in which case, the contents of the @pin parameter are ignored). * * When a PIN is required, the callback will be invoked repeatedly * (and indefinitely) until either the returned PIN code is correct, * the callback returns failure, or the token refuses login (e.g. when * the token is locked due to too many incorrect PINs!). For the * first such invocation, the @attempt counter will have value zero; * it will increase by one for each subsequent attempt. * * Returns: %GNUTLS_E_SUCCESS (0) on success or a negative error code on error. * * Since: 2.12.0 **/ typedef int (*gnutls_pin_callback_t) (void *userdata, int attempt, const char *token_url, const char *token_label, unsigned int flags, char *pin, size_t pin_max); void gnutls_certificate_set_pin_function(gnutls_certificate_credentials_t, gnutls_pin_callback_t fn, void *userdata); /* Public string related functions */ typedef struct gnutls_buffer_st *gnutls_buffer_t; int gnutls_buffer_append_data(gnutls_buffer_t, const void *data, size_t data_size); #define GNUTLS_UTF8_IGNORE_ERRS 1 int gnutls_utf8_password_normalize(const unsigned char *password, unsigned password_len, gnutls_datum_t *out, unsigned flags); /* Public extensions related functions */ typedef void *gnutls_ext_priv_data_t; void gnutls_ext_set_data(gnutls_session_t session, unsigned type, gnutls_ext_priv_data_t); int gnutls_ext_get_data(gnutls_session_t session, unsigned type, gnutls_ext_priv_data_t *); unsigned gnutls_ext_get_current_msg(gnutls_session_t session); typedef int (*gnutls_ext_recv_func) (gnutls_session_t session, const unsigned char *data, size_t len); typedef int (*gnutls_ext_send_func) (gnutls_session_t session, gnutls_buffer_t extdata); typedef void (*gnutls_ext_deinit_data_func) (gnutls_ext_priv_data_t data); typedef int (*gnutls_ext_pack_func) (gnutls_ext_priv_data_t data, gnutls_buffer_t packed_data); typedef int (*gnutls_ext_unpack_func) (gnutls_buffer_t packed_data, gnutls_ext_priv_data_t *data); #define GNUTLS_EXT_RAW_FLAG_TLS_CLIENT_HELLO 1 #define GNUTLS_EXT_RAW_FLAG_DTLS_CLIENT_HELLO (1<<1) typedef int (*gnutls_ext_raw_process_func)(void *ctx, unsigned tls_id, const unsigned char *data, unsigned data_size); int gnutls_ext_raw_parse(void *ctx, gnutls_ext_raw_process_func cb, const gnutls_datum_t *data, unsigned int flags); /** * gnutls_ext_parse_type_t: * @GNUTLS_EXT_NONE: Never to be parsed * @GNUTLS_EXT_ANY: Any extension type (should not be used as it is used only internally). * @GNUTLS_EXT_VERSION_NEG: Extensions to be parsed first for TLS version negotiation. * @GNUTLS_EXT_MANDATORY: Parsed after @GNUTLS_EXT_VERSION_NEG and even when resuming. * @GNUTLS_EXT_APPLICATION: Parsed after @GNUTLS_EXT_MANDATORY * @GNUTLS_EXT_TLS: TLS-internal extensions, parsed after @GNUTLS_EXT_APPLICATION. * * Enumeration of different TLS extension parsing phases. The @gnutls_ext_parse_type_t * indicates the time/phase an extension is parsed during Client or Server hello parsing. * */ typedef enum { GNUTLS_EXT_ANY = 0, GNUTLS_EXT_APPLICATION = 1, GNUTLS_EXT_TLS = 2, GNUTLS_EXT_MANDATORY = 3, GNUTLS_EXT_NONE = 4, GNUTLS_EXT_VERSION_NEG = 5 } gnutls_ext_parse_type_t; /** * gnutls_ext_flags_t: * @GNUTLS_EXT_FLAG_OVERRIDE_INTERNAL: If specified the extension registered will override the internal; this does not work with extensions existing prior to 3.6.0. * @GNUTLS_EXT_FLAG_CLIENT_HELLO: This extension can be present in a client hello * @GNUTLS_EXT_FLAG_TLS12_SERVER_HELLO: This extension can be present in a TLS1.2 or earlier server hello * @GNUTLS_EXT_FLAG_TLS13_SERVER_HELLO: This extension can be present in a TLS1.3 server hello * @GNUTLS_EXT_FLAG_EE: This extension can be present in encrypted extensions message * @GNUTLS_EXT_FLAG_HRR: This extension can be present in hello retry request message * @GNUTLS_EXT_FLAG_IGNORE_CLIENT_REQUEST: When flag is present, this extension will be send even if the client didn't advertise it. An extension of this type is the Cookie TLS1.3 extension. * @GNUTLS_EXT_FLAG_DTLS: This extension can be present under DTLS; otherwise ignored. * @GNUTLS_EXT_FLAG_TLS: This extension can be present under TLS; otherwise ignored. * * Enumeration of different TLS extension registration flags. */ typedef enum { GNUTLS_EXT_FLAG_OVERRIDE_INTERNAL = 1, GNUTLS_EXT_FLAG_CLIENT_HELLO = (1<<1), GNUTLS_EXT_FLAG_TLS12_SERVER_HELLO = (1<<2), GNUTLS_EXT_FLAG_TLS13_SERVER_HELLO = (1<<3), GNUTLS_EXT_FLAG_EE = (1<<4), /* ENCRYPTED */ GNUTLS_EXT_FLAG_HRR = (1<<5), GNUTLS_EXT_FLAG_IGNORE_CLIENT_REQUEST = (1<<6), GNUTLS_EXT_FLAG_TLS = (1<<7), GNUTLS_EXT_FLAG_DTLS = (1<<8) } gnutls_ext_flags_t; /* Register a custom tls extension */ int gnutls_ext_register(const char *name, int type, gnutls_ext_parse_type_t parse_point, gnutls_ext_recv_func recv_func, gnutls_ext_send_func send_func, gnutls_ext_deinit_data_func deinit_func, gnutls_ext_pack_func pack_func, gnutls_ext_unpack_func unpack_func); int gnutls_session_ext_register(gnutls_session_t, const char *name, int type, gnutls_ext_parse_type_t parse_point, gnutls_ext_recv_func recv_func, gnutls_ext_send_func send_func, gnutls_ext_deinit_data_func deinit_func, gnutls_ext_pack_func pack_func, gnutls_ext_unpack_func unpack_func, unsigned flags); const char *gnutls_ext_get_name(unsigned int ext); const char *gnutls_ext_get_name2(gnutls_session_t session, unsigned int tls_id, gnutls_ext_parse_type_t parse_point); /* Public supplemental data related functions */ typedef int (*gnutls_supp_recv_func) (gnutls_session_t session, const unsigned char * data, size_t data_size); typedef int (*gnutls_supp_send_func) (gnutls_session_t session, gnutls_buffer_t buf); int gnutls_supplemental_register(const char *name, gnutls_supplemental_data_format_type_t type, gnutls_supp_recv_func supp_recv_func, gnutls_supp_send_func supp_send_func); int gnutls_session_supplemental_register(gnutls_session_t session, const char *name, gnutls_supplemental_data_format_type_t type, gnutls_supp_recv_func supp_recv_func, gnutls_supp_send_func supp_send_func, unsigned int flags); void gnutls_supplemental_recv(gnutls_session_t session, unsigned do_recv_supplemental); void gnutls_supplemental_send(gnutls_session_t session, unsigned do_send_supplemental); /* Anti-replay related functions */ typedef struct gnutls_anti_replay_st *gnutls_anti_replay_t; int gnutls_anti_replay_init(gnutls_anti_replay_t *anti_replay); void gnutls_anti_replay_deinit(gnutls_anti_replay_t anti_replay); void gnutls_anti_replay_set_window(gnutls_anti_replay_t anti_replay, unsigned int window); void gnutls_anti_replay_enable(gnutls_session_t session, gnutls_anti_replay_t anti_replay); typedef int (*gnutls_db_add_func) (void *, time_t exp_time, const gnutls_datum_t *key, const gnutls_datum_t *data); void gnutls_anti_replay_set_add_function(gnutls_anti_replay_t, gnutls_db_add_func add_func); void gnutls_anti_replay_set_ptr(gnutls_anti_replay_t, void *ptr); /** * gnutls_record_encryption_level_t: * @GNUTLS_ENCRYPTION_LEVEL_INITIAL: initial level that doesn't involve any * encryption * @GNUTLS_ENCRYPTION_LEVEL_EARLY: early traffic secret is installed * @GNUTLS_ENCRYPTION_LEVEL_HANDSHAKE: handshake traffic secret is installed * @GNUTLS_ENCRYPTION_LEVEL_APPLICATION: application traffic secret is installed * * Enumeration of different levels of record encryption currently in place. * This is used by gnutls_handshake_set_read_function() and * gnutls_handshake_write(). * * Since: 3.7.0 */ typedef enum { GNUTLS_ENCRYPTION_LEVEL_INITIAL, GNUTLS_ENCRYPTION_LEVEL_EARLY, GNUTLS_ENCRYPTION_LEVEL_HANDSHAKE, GNUTLS_ENCRYPTION_LEVEL_APPLICATION } gnutls_record_encryption_level_t; /** * gnutls_handshake_read_func: * @session: the current session * @htype: the type of the handshake message (#gnutls_handshake_description_t) * @level: #gnutls_record_encryption_level_t * @data: the (const) data that was being sent * @data_size: the size of data * * Function prototype for handshake intercepting hooks. It is set using * gnutls_handshake_set_read_function(). * * Returns: Non zero on error. * Since: 3.7.0 */ typedef int (*gnutls_handshake_read_func) (gnutls_session_t session, gnutls_record_encryption_level_t level, gnutls_handshake_description_t htype, const void *data, size_t data_size); void gnutls_handshake_set_read_function(gnutls_session_t session, gnutls_handshake_read_func func); int gnutls_handshake_write(gnutls_session_t session, gnutls_record_encryption_level_t level, const void *data, size_t data_size); /** * gnutls_handshake_secret_func: * @session: the current session * @level: the encryption level * @secret_read: the secret used for reading, can be %NULL if not set * @secret_write: the secret used for writing, can be %NULL if not set * @secret_size: the size of the secrets * * Function prototype for secret hooks. It is set using * gnutls_handshake_set_secret_function(). * * Returns: Non zero on error. * Since: 3.7.0 */ typedef int (*gnutls_handshake_secret_func) (gnutls_session_t session, gnutls_record_encryption_level_t level, const void *secret_read, const void *secret_write, size_t secret_size); void gnutls_handshake_set_secret_function(gnutls_session_t session, gnutls_handshake_secret_func func); /** * gnutls_alert_read_func: * @session: the current session * @level: #gnutls_record_encryption_level_t * @alert_level: the level of the alert * @alert_desc: the alert description * * Function prototype for alert intercepting hooks. It is set using * gnutls_alert_set_read_function(). * * Returns: Non zero on error. * Since: 3.7.0 */ typedef int (*gnutls_alert_read_func) (gnutls_session_t session, gnutls_record_encryption_level_t level, gnutls_alert_level_t alert_level, gnutls_alert_description_t alert_desc); void gnutls_alert_set_read_function(gnutls_session_t session, gnutls_alert_read_func func); /* FIPS140-2 related functions */ unsigned gnutls_fips140_mode_enabled(void); /** * gnutls_fips_mode_t: * @GNUTLS_FIPS140_DISABLED: The FIPS140-2 mode is disabled. * @GNUTLS_FIPS140_STRICT: The default mode; all forbidden operations will cause an * operation failure via error code. * @GNUTLS_FIPS140_LAX: The library still uses the FIPS140-2 relevant algorithms but all * forbidden by FIPS140-2 operations are allowed; this is useful when the * application is aware of the followed security policy, and needs * to utilize disallowed operations for other reasons (e.g., compatibility). * @GNUTLS_FIPS140_LOG: Similarly to %GNUTLS_FIPS140_LAX, it allows forbidden operations; any use of them results * to a message to the audit callback functions. * @GNUTLS_FIPS140_SELFTESTS: A transient state during library initialization. That state * cannot be set or seen by applications. * * Enumeration of different operational modes under FIPS140-2. */ typedef enum gnutls_fips_mode_t { GNUTLS_FIPS140_DISABLED = 0, GNUTLS_FIPS140_STRICT = 1, GNUTLS_FIPS140_SELFTESTS = 2, GNUTLS_FIPS140_LAX = 3, GNUTLS_FIPS140_LOG = 4 } gnutls_fips_mode_t; #define GNUTLS_FIPS140_SET_MODE_THREAD 1 void gnutls_fips140_set_mode(gnutls_fips_mode_t mode, unsigned flags); #define GNUTLS_FIPS140_SET_LAX_MODE() do { \ if (gnutls_fips140_mode_enabled()) \ gnutls_fips140_set_mode(GNUTLS_FIPS140_LAX, GNUTLS_FIPS140_SET_MODE_THREAD); \ } while(0) #define GNUTLS_FIPS140_SET_STRICT_MODE() do { \ if (gnutls_fips140_mode_enabled()) \ gnutls_fips140_set_mode(GNUTLS_FIPS140_STRICT, GNUTLS_FIPS140_SET_MODE_THREAD); \ } while(0) typedef struct gnutls_fips140_context_st *gnutls_fips140_context_t; int gnutls_fips140_context_init(gnutls_fips140_context_t *context); void gnutls_fips140_context_deinit(gnutls_fips140_context_t context); /** * gnutls_fips140_operation_state_t: * @GNUTLS_FIPS140_OP_INITIAL: no previous operation has done * @GNUTLS_FIPS140_OP_APPROVED: the previous operation was FIPS approved * @GNUTLS_FIPS140_OP_NOT_APPROVED: the previous operation was not FIPS approved * @GNUTLS_FIPS140_OP_ERROR: the previous operation caused an error regardless of FIPS * * The FIPS operation state set by the preceding operation. * * There are state transition rules among the enum values: * - When the context is attached to a thread, it will be set to reset * to the %GNUTLS_FIPS140_OP_INITIAL state * - From the %GNUTLS_FIPS140_OP_INITIAL state, the context can * transition to either %GNUTLS_FIPS140_OP_APPROVED, * %GNUTLS_FIPS140_OP_NOT_APPROVED, or %GNUTLS_FIPS140_OP_ERROR * - From the %GNUTLS_FIPS140_OP_APPROVED state, the context can * transition to %GNUTLS_FIPS140_OP_NOT_APPROVED * - All other transitions are prohibited. * * Since: 3.7.3 */ typedef enum { GNUTLS_FIPS140_OP_INITIAL, GNUTLS_FIPS140_OP_APPROVED, GNUTLS_FIPS140_OP_NOT_APPROVED, GNUTLS_FIPS140_OP_ERROR } gnutls_fips140_operation_state_t; gnutls_fips140_operation_state_t gnutls_fips140_get_operation_state(gnutls_fips140_context_t context); int gnutls_fips140_push_context(gnutls_fips140_context_t context); int gnutls_fips140_pop_context(void); int gnutls_fips140_run_self_tests(void); /* Gnutls error codes. The mapping to a TLS alert is also shown in * comments. */ #define GNUTLS_E_SUCCESS 0 #define GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM -3 #define GNUTLS_E_UNKNOWN_CIPHER_TYPE -6 #define GNUTLS_E_LARGE_PACKET -7 #define GNUTLS_E_UNSUPPORTED_VERSION_PACKET -8 /* GNUTLS_A_PROTOCOL_VERSION */ #define GNUTLS_E_TLS_PACKET_DECODING_ERROR GNUTLS_E_UNEXPECTED_PACKET_LENGTH #define GNUTLS_E_UNEXPECTED_PACKET_LENGTH -9 /* GNUTLS_A_DECODE_ERROR */ #define GNUTLS_E_INVALID_SESSION -10 #define GNUTLS_E_FATAL_ALERT_RECEIVED -12 #define GNUTLS_E_UNEXPECTED_PACKET -15 /* GNUTLS_A_UNEXPECTED_MESSAGE */ #define GNUTLS_E_WARNING_ALERT_RECEIVED -16 #define GNUTLS_E_ERROR_IN_FINISHED_PACKET -18 #define GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET -19 #define GNUTLS_E_UNKNOWN_CIPHER_SUITE -21 /* GNUTLS_A_HANDSHAKE_FAILURE */ #define GNUTLS_E_UNWANTED_ALGORITHM -22 #define GNUTLS_E_MPI_SCAN_FAILED -23 #define GNUTLS_E_DECRYPTION_FAILED -24 /* GNUTLS_A_DECRYPTION_FAILED, GNUTLS_A_BAD_RECORD_MAC */ #define GNUTLS_E_MEMORY_ERROR -25 #define GNUTLS_E_DECOMPRESSION_FAILED -26 /* GNUTLS_A_DECOMPRESSION_FAILURE */ #define GNUTLS_E_COMPRESSION_FAILED -27 #define GNUTLS_E_AGAIN -28 #define GNUTLS_E_EXPIRED -29 #define GNUTLS_E_DB_ERROR -30 #define GNUTLS_E_SRP_PWD_ERROR GNUTLS_E_KEYFILE_ERROR #define GNUTLS_E_KEYFILE_ERROR -31 #define GNUTLS_E_INSUFFICIENT_CREDENTIALS -32 #define GNUTLS_E_INSUFICIENT_CREDENTIALS GNUTLS_E_INSUFFICIENT_CREDENTIALS /* for backwards compatibility only */ #define GNUTLS_E_INSUFFICIENT_CRED GNUTLS_E_INSUFFICIENT_CREDENTIALS #define GNUTLS_E_INSUFICIENT_CRED GNUTLS_E_INSUFFICIENT_CREDENTIALS /* for backwards compatibility only */ #define GNUTLS_E_HASH_FAILED -33 #define GNUTLS_E_BASE64_DECODING_ERROR -34 #define GNUTLS_E_MPI_PRINT_FAILED -35 #define GNUTLS_E_REHANDSHAKE -37 /* GNUTLS_A_NO_RENEGOTIATION */ #define GNUTLS_E_GOT_APPLICATION_DATA -38 #define GNUTLS_E_RECORD_LIMIT_REACHED -39 #define GNUTLS_E_ENCRYPTION_FAILED -40 #define GNUTLS_E_PK_ENCRYPTION_FAILED -44 #define GNUTLS_E_PK_DECRYPTION_FAILED -45 #define GNUTLS_E_PK_SIGN_FAILED -46 #define GNUTLS_E_X509_UNSUPPORTED_CRITICAL_EXTENSION -47 #define GNUTLS_E_KEY_USAGE_VIOLATION -48 #define GNUTLS_E_NO_CERTIFICATE_FOUND -49 /* GNUTLS_A_BAD_CERTIFICATE */ #define GNUTLS_E_INVALID_REQUEST -50 #define GNUTLS_E_SHORT_MEMORY_BUFFER -51 #define GNUTLS_E_INTERRUPTED -52 #define GNUTLS_E_PUSH_ERROR -53 #define GNUTLS_E_PULL_ERROR -54 #define GNUTLS_E_RECEIVED_ILLEGAL_PARAMETER -55 /* GNUTLS_A_ILLEGAL_PARAMETER */ #define GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE -56 #define GNUTLS_E_PKCS1_WRONG_PAD -57 #define GNUTLS_E_RECEIVED_ILLEGAL_EXTENSION -58 #define GNUTLS_E_INTERNAL_ERROR -59 #define GNUTLS_E_DH_PRIME_UNACCEPTABLE -63 #define GNUTLS_E_FILE_ERROR -64 #define GNUTLS_E_TOO_MANY_EMPTY_PACKETS -78 #define GNUTLS_E_UNKNOWN_PK_ALGORITHM -80 #define GNUTLS_E_TOO_MANY_HANDSHAKE_PACKETS -81 #define GNUTLS_E_RECEIVED_DISALLOWED_NAME -82 /* GNUTLS_A_ILLEGAL_PARAMETER */ #define GNUTLS_E_CERTIFICATE_REQUIRED -112 /* GNUTLS_A_CERTIFICATE_REQUIRED */ /* returned if you need to generate temporary RSA * parameters. These are needed for export cipher suites. */ #define GNUTLS_E_NO_TEMPORARY_RSA_PARAMS -84 #define GNUTLS_E_NO_COMPRESSION_ALGORITHMS -86 #define GNUTLS_E_NO_CIPHER_SUITES -87 #define GNUTLS_E_OPENPGP_GETKEY_FAILED -88 #define GNUTLS_E_PK_SIG_VERIFY_FAILED -89 #define GNUTLS_E_ILLEGAL_SRP_USERNAME -90 #define GNUTLS_E_SRP_PWD_PARSING_ERROR GNUTLS_E_KEYFILE_PARSING_ERROR #define GNUTLS_E_KEYFILE_PARSING_ERROR -91 #define GNUTLS_E_NO_TEMPORARY_DH_PARAMS -93 /* For certificate and key stuff */ #define GNUTLS_E_ASN1_ELEMENT_NOT_FOUND -67 #define GNUTLS_E_ASN1_IDENTIFIER_NOT_FOUND -68 #define GNUTLS_E_ASN1_DER_ERROR -69 #define GNUTLS_E_ASN1_VALUE_NOT_FOUND -70 #define GNUTLS_E_ASN1_GENERIC_ERROR -71 #define GNUTLS_E_ASN1_VALUE_NOT_VALID -72 #define GNUTLS_E_ASN1_TAG_ERROR -73 #define GNUTLS_E_ASN1_TAG_IMPLICIT -74 #define GNUTLS_E_ASN1_TYPE_ANY_ERROR -75 #define GNUTLS_E_ASN1_SYNTAX_ERROR -76 #define GNUTLS_E_ASN1_DER_OVERFLOW -77 #define GNUTLS_E_OPENPGP_UID_REVOKED -79 #define GNUTLS_E_CERTIFICATE_ERROR -43 #define GNUTLS_E_X509_CERTIFICATE_ERROR GNUTLS_E_CERTIFICATE_ERROR #define GNUTLS_E_CERTIFICATE_KEY_MISMATCH -60 #define GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE -61 /* GNUTLS_A_UNSUPPORTED_CERTIFICATE */ #define GNUTLS_E_X509_UNKNOWN_SAN -62 #define GNUTLS_E_OPENPGP_FINGERPRINT_UNSUPPORTED -94 #define GNUTLS_E_X509_UNSUPPORTED_ATTRIBUTE -95 #define GNUTLS_E_UNKNOWN_HASH_ALGORITHM -96 #define GNUTLS_E_UNKNOWN_PKCS_CONTENT_TYPE -97 #define GNUTLS_E_UNKNOWN_PKCS_BAG_TYPE -98 #define GNUTLS_E_INVALID_PASSWORD -99 #define GNUTLS_E_MAC_VERIFY_FAILED -100 /* for PKCS #12 MAC */ #define GNUTLS_E_CONSTRAINT_ERROR -101 #define GNUTLS_E_WARNING_IA_IPHF_RECEIVED -102 #define GNUTLS_E_WARNING_IA_FPHF_RECEIVED -103 #define GNUTLS_E_IA_VERIFY_FAILED -104 #define GNUTLS_E_UNKNOWN_ALGORITHM -105 #define GNUTLS_E_UNSUPPORTED_SIGNATURE_ALGORITHM -106 #define GNUTLS_E_SAFE_RENEGOTIATION_FAILED -107 #define GNUTLS_E_UNSAFE_RENEGOTIATION_DENIED -108 #define GNUTLS_E_UNKNOWN_SRP_USERNAME -109 #define GNUTLS_E_PREMATURE_TERMINATION -110 #define GNUTLS_E_MALFORMED_CIDR -111 #define GNUTLS_E_BASE64_ENCODING_ERROR -201 #define GNUTLS_E_INCOMPATIBLE_GCRYPT_LIBRARY -202 /* obsolete */ #define GNUTLS_E_INCOMPATIBLE_CRYPTO_LIBRARY -202 #define GNUTLS_E_INCOMPATIBLE_LIBTASN1_LIBRARY -203 #define GNUTLS_E_OPENPGP_KEYRING_ERROR -204 #define GNUTLS_E_X509_UNSUPPORTED_OID -205 #define GNUTLS_E_RANDOM_FAILED -206 #define GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR -207 #define GNUTLS_E_OPENPGP_SUBKEY_ERROR -208 #define GNUTLS_E_CRYPTO_ALREADY_REGISTERED GNUTLS_E_ALREADY_REGISTERED #define GNUTLS_E_ALREADY_REGISTERED -209 #define GNUTLS_E_HANDSHAKE_TOO_LARGE -210 #define GNUTLS_E_CRYPTODEV_IOCTL_ERROR -211 #define GNUTLS_E_CRYPTODEV_DEVICE_ERROR -212 #define GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE -213 #define GNUTLS_E_BAD_COOKIE -214 #define GNUTLS_E_OPENPGP_PREFERRED_KEY_ERROR -215 #define GNUTLS_E_INCOMPAT_DSA_KEY_WITH_TLS_PROTOCOL -216 #define GNUTLS_E_INSUFFICIENT_SECURITY -217 #define GNUTLS_E_HEARTBEAT_PONG_RECEIVED -292 #define GNUTLS_E_HEARTBEAT_PING_RECEIVED -293 #define GNUTLS_E_UNRECOGNIZED_NAME -294 /* PKCS11 related */ #define GNUTLS_E_PKCS11_ERROR -300 #define GNUTLS_E_PKCS11_LOAD_ERROR -301 #define GNUTLS_E_PARSING_ERROR -302 #define GNUTLS_E_PKCS11_PIN_ERROR -303 #define GNUTLS_E_PKCS11_SLOT_ERROR -305 #define GNUTLS_E_LOCKING_ERROR -306 #define GNUTLS_E_PKCS11_ATTRIBUTE_ERROR -307 #define GNUTLS_E_PKCS11_DEVICE_ERROR -308 #define GNUTLS_E_PKCS11_DATA_ERROR -309 #define GNUTLS_E_PKCS11_UNSUPPORTED_FEATURE_ERROR -310 #define GNUTLS_E_PKCS11_KEY_ERROR -311 #define GNUTLS_E_PKCS11_PIN_EXPIRED -312 #define GNUTLS_E_PKCS11_PIN_LOCKED -313 #define GNUTLS_E_PKCS11_SESSION_ERROR -314 #define GNUTLS_E_PKCS11_SIGNATURE_ERROR -315 #define GNUTLS_E_PKCS11_TOKEN_ERROR -316 #define GNUTLS_E_PKCS11_USER_ERROR -317 #define GNUTLS_E_CRYPTO_INIT_FAILED -318 #define GNUTLS_E_TIMEDOUT -319 #define GNUTLS_E_USER_ERROR -320 #define GNUTLS_E_ECC_NO_SUPPORTED_CURVES -321 #define GNUTLS_E_ECC_UNSUPPORTED_CURVE -322 #define GNUTLS_E_PKCS11_REQUESTED_OBJECT_NOT_AVAILBLE -323 #define GNUTLS_E_CERTIFICATE_LIST_UNSORTED -324 #define GNUTLS_E_ILLEGAL_PARAMETER -325 /* GNUTLS_A_ILLEGAL_PARAMETER */ #define GNUTLS_E_NO_PRIORITIES_WERE_SET -326 #define GNUTLS_E_X509_UNSUPPORTED_EXTENSION -327 #define GNUTLS_E_SESSION_EOF -328 #define GNUTLS_E_TPM_ERROR -329 #define GNUTLS_E_TPM_KEY_PASSWORD_ERROR -330 #define GNUTLS_E_TPM_SRK_PASSWORD_ERROR -331 #define GNUTLS_E_TPM_SESSION_ERROR -332 #define GNUTLS_E_TPM_KEY_NOT_FOUND -333 #define GNUTLS_E_TPM_UNINITIALIZED -334 #define GNUTLS_E_TPM_NO_LIB -335 #define GNUTLS_E_NO_CERTIFICATE_STATUS -340 #define GNUTLS_E_OCSP_RESPONSE_ERROR -341 #define GNUTLS_E_RANDOM_DEVICE_ERROR -342 #define GNUTLS_E_AUTH_ERROR -343 #define GNUTLS_E_NO_APPLICATION_PROTOCOL -344 #define GNUTLS_E_SOCKETS_INIT_ERROR -345 #define GNUTLS_E_KEY_IMPORT_FAILED -346 #define GNUTLS_E_INAPPROPRIATE_FALLBACK -347 /*GNUTLS_A_INAPPROPRIATE_FALLBACK*/ #define GNUTLS_E_CERTIFICATE_VERIFICATION_ERROR -348 #define GNUTLS_E_PRIVKEY_VERIFICATION_ERROR -349 #define GNUTLS_E_UNEXPECTED_EXTENSIONS_LENGTH -350 /*GNUTLS_A_DECODE_ERROR*/ #define GNUTLS_E_ASN1_EMBEDDED_NULL_IN_STRING -351 #define GNUTLS_E_SELF_TEST_ERROR -400 #define GNUTLS_E_NO_SELF_TEST -401 #define GNUTLS_E_LIB_IN_ERROR_STATE -402 #define GNUTLS_E_PK_GENERATION_ERROR -403 #define GNUTLS_E_IDNA_ERROR -404 #define GNUTLS_E_NEED_FALLBACK -405 #define GNUTLS_E_SESSION_USER_ID_CHANGED -406 #define GNUTLS_E_HANDSHAKE_DURING_FALSE_START -407 #define GNUTLS_E_UNAVAILABLE_DURING_HANDSHAKE -408 #define GNUTLS_E_PK_INVALID_PUBKEY -409 #define GNUTLS_E_PK_INVALID_PRIVKEY -410 #define GNUTLS_E_NOT_YET_ACTIVATED -411 #define GNUTLS_E_INVALID_UTF8_STRING -412 #define GNUTLS_E_NO_EMBEDDED_DATA -413 #define GNUTLS_E_INVALID_UTF8_EMAIL -414 #define GNUTLS_E_INVALID_PASSWORD_STRING -415 #define GNUTLS_E_CERTIFICATE_TIME_ERROR -416 #define GNUTLS_E_RECORD_OVERFLOW -417 /* GNUTLS_A_RECORD_OVERFLOW */ #define GNUTLS_E_ASN1_TIME_ERROR -418 #define GNUTLS_E_INCOMPATIBLE_SIG_WITH_KEY -419 #define GNUTLS_E_PK_INVALID_PUBKEY_PARAMS -420 #define GNUTLS_E_PK_NO_VALIDATION_PARAMS -421 #define GNUTLS_E_OCSP_MISMATCH_WITH_CERTS -422 #define GNUTLS_E_NO_COMMON_KEY_SHARE -423 #define GNUTLS_E_REAUTH_REQUEST -424 #define GNUTLS_E_TOO_MANY_MATCHES -425 #define GNUTLS_E_CRL_VERIFICATION_ERROR -426 #define GNUTLS_E_MISSING_EXTENSION -427 #define GNUTLS_E_DB_ENTRY_EXISTS -428 #define GNUTLS_E_EARLY_DATA_REJECTED -429 #define GNUTLS_E_X509_DUPLICATE_EXTENSION -430 #define GNUTLS_E_UNIMPLEMENTED_FEATURE -1250 /* Internal errors of the library; will never be returned * to a calling application */ #define GNUTLS_E_INT_RET_0 -1251 #define GNUTLS_E_INT_CHECK_AGAIN -1252 #define GNUTLS_E_APPLICATION_ERROR_MAX -65000 #define GNUTLS_E_APPLICATION_ERROR_MIN -65500 /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #include #endif /* GNUTLS_GNUTLS_H */ ================================================ FILE: thirdparty/64/include/gnutls/ocsp.h ================================================ /* * Copyright (C) 2011-2012 Free Software Foundation, Inc. * * Author: Simon Josefsson * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* Online Certificate Status Protocol - RFC 2560 */ #ifndef GNUTLS_OCSP_H #define GNUTLS_OCSP_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_OCSP_NONCE "1.3.6.1.5.5.7.48.1.2" /** * gnutls_ocsp_print_formats_t: * @GNUTLS_OCSP_PRINT_FULL: Full information about OCSP request/response. * @GNUTLS_OCSP_PRINT_COMPACT: More compact information about OCSP request/response. * * Enumeration of different OCSP printing variants. */ typedef enum gnutls_ocsp_print_formats_t { GNUTLS_OCSP_PRINT_FULL = 0, GNUTLS_OCSP_PRINT_COMPACT = 1 } gnutls_ocsp_print_formats_t; /** * gnutls_ocsp_resp_status_t: * @GNUTLS_OCSP_RESP_SUCCESSFUL: Response has valid confirmations. * @GNUTLS_OCSP_RESP_MALFORMEDREQUEST: Illegal confirmation request * @GNUTLS_OCSP_RESP_INTERNALERROR: Internal error in issuer * @GNUTLS_OCSP_RESP_TRYLATER: Try again later * @GNUTLS_OCSP_RESP_SIGREQUIRED: Must sign the request * @GNUTLS_OCSP_RESP_UNAUTHORIZED: Request unauthorized * * Enumeration of different OCSP response status codes. */ typedef enum gnutls_ocsp_resp_status_t { GNUTLS_OCSP_RESP_SUCCESSFUL = 0, GNUTLS_OCSP_RESP_MALFORMEDREQUEST = 1, GNUTLS_OCSP_RESP_INTERNALERROR = 2, GNUTLS_OCSP_RESP_TRYLATER = 3, GNUTLS_OCSP_RESP_SIGREQUIRED = 5, GNUTLS_OCSP_RESP_UNAUTHORIZED = 6 } gnutls_ocsp_resp_status_t; /** * gnutls_ocsp_cert_status_t: * @GNUTLS_OCSP_CERT_GOOD: Positive response to status inquiry. * @GNUTLS_OCSP_CERT_REVOKED: Certificate has been revoked. * @GNUTLS_OCSP_CERT_UNKNOWN: The responder doesn't know about the * certificate. * * Enumeration of different OCSP response certificate status codes. */ typedef enum gnutls_ocsp_cert_status_t { GNUTLS_OCSP_CERT_GOOD = 0, GNUTLS_OCSP_CERT_REVOKED = 1, GNUTLS_OCSP_CERT_UNKNOWN = 2 } gnutls_ocsp_cert_status_t; /** * gnutls_x509_crl_reason_t: * @GNUTLS_X509_CRLREASON_UNSPECIFIED: Unspecified reason. * @GNUTLS_X509_CRLREASON_KEYCOMPROMISE: Private key compromised. * @GNUTLS_X509_CRLREASON_CACOMPROMISE: CA compromised. * @GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED: Affiliation has changed. * @GNUTLS_X509_CRLREASON_SUPERSEDED: Certificate superseded. * @GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION: Operation has ceased. * @GNUTLS_X509_CRLREASON_CERTIFICATEHOLD: Certificate is on hold. * @GNUTLS_X509_CRLREASON_REMOVEFROMCRL: Will be removed from delta CRL. * @GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN: Privilege withdrawn. * @GNUTLS_X509_CRLREASON_AACOMPROMISE: AA compromised. * * Enumeration of different reason codes. Note that this * corresponds to the CRLReason ASN.1 enumeration type, and not the * ReasonFlags ASN.1 bit string. */ typedef enum gnutls_x509_crl_reason_t { GNUTLS_X509_CRLREASON_UNSPECIFIED = 0, GNUTLS_X509_CRLREASON_KEYCOMPROMISE = 1, GNUTLS_X509_CRLREASON_CACOMPROMISE = 2, GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED = 3, GNUTLS_X509_CRLREASON_SUPERSEDED = 4, GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION = 5, GNUTLS_X509_CRLREASON_CERTIFICATEHOLD = 6, GNUTLS_X509_CRLREASON_REMOVEFROMCRL = 8, GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN = 9, GNUTLS_X509_CRLREASON_AACOMPROMISE = 10 } gnutls_x509_crl_reason_t; /* When adding a verify failure reason update: * _gnutls_ocsp_verify_status_to_str() */ /** * gnutls_ocsp_verify_reason_t: * @GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND: Signer cert not found. * @GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR: Signer keyusage bits incorrect. * @GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER: Signer is not trusted. * @GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM: Signature using insecure algorithm. * @GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE: Signature mismatch. * @GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED: Signer cert is not yet activated. * @GNUTLS_OCSP_VERIFY_CERT_EXPIRED: Signer cert has expired. * * Enumeration of OCSP verify status codes, used by * gnutls_ocsp_resp_verify() and gnutls_ocsp_resp_verify_direct(). */ typedef enum gnutls_ocsp_verify_reason_t { GNUTLS_OCSP_VERIFY_SIGNER_NOT_FOUND = 1, GNUTLS_OCSP_VERIFY_SIGNER_KEYUSAGE_ERROR = 2, GNUTLS_OCSP_VERIFY_UNTRUSTED_SIGNER = 4, GNUTLS_OCSP_VERIFY_INSECURE_ALGORITHM = 8, GNUTLS_OCSP_VERIFY_SIGNATURE_FAILURE = 16, GNUTLS_OCSP_VERIFY_CERT_NOT_ACTIVATED = 32, GNUTLS_OCSP_VERIFY_CERT_EXPIRED = 64 } gnutls_ocsp_verify_reason_t; struct gnutls_ocsp_req_int; typedef struct gnutls_ocsp_req_int *gnutls_ocsp_req_t; typedef const struct gnutls_ocsp_req_int *gnutls_ocsp_req_const_t; int gnutls_ocsp_req_init(gnutls_ocsp_req_t * req); void gnutls_ocsp_req_deinit(gnutls_ocsp_req_t req); int gnutls_ocsp_req_import(gnutls_ocsp_req_t req, const gnutls_datum_t * data); int gnutls_ocsp_req_export(gnutls_ocsp_req_const_t req, gnutls_datum_t * data); int gnutls_ocsp_req_print(gnutls_ocsp_req_const_t req, gnutls_ocsp_print_formats_t format, gnutls_datum_t * out); int gnutls_ocsp_req_get_version(gnutls_ocsp_req_const_t req); int gnutls_ocsp_req_get_cert_id(gnutls_ocsp_req_const_t req, unsigned indx, gnutls_digest_algorithm_t * digest, gnutls_datum_t * issuer_name_hash, gnutls_datum_t * issuer_key_hash, gnutls_datum_t * serial_number); int gnutls_ocsp_req_add_cert_id(gnutls_ocsp_req_t req, gnutls_digest_algorithm_t digest, const gnutls_datum_t * issuer_name_hash, const gnutls_datum_t * issuer_key_hash, const gnutls_datum_t * serial_number); int gnutls_ocsp_req_add_cert(gnutls_ocsp_req_t req, gnutls_digest_algorithm_t digest, gnutls_x509_crt_t issuer, gnutls_x509_crt_t cert); int gnutls_ocsp_req_get_extension(gnutls_ocsp_req_const_t req, unsigned indx, gnutls_datum_t * oid, unsigned int *critical, gnutls_datum_t * data); int gnutls_ocsp_req_set_extension(gnutls_ocsp_req_t req, const char *oid, unsigned int critical, const gnutls_datum_t * data); int gnutls_ocsp_req_get_nonce(gnutls_ocsp_req_const_t req, unsigned int *critical, gnutls_datum_t * nonce); int gnutls_ocsp_req_set_nonce(gnutls_ocsp_req_t req, unsigned int critical, const gnutls_datum_t * nonce); int gnutls_ocsp_req_randomize_nonce(gnutls_ocsp_req_t req); struct gnutls_ocsp_resp_int; typedef struct gnutls_ocsp_resp_int *gnutls_ocsp_resp_t; typedef const struct gnutls_ocsp_resp_int *gnutls_ocsp_resp_const_t; int gnutls_ocsp_resp_init(gnutls_ocsp_resp_t * resp); void gnutls_ocsp_resp_deinit(gnutls_ocsp_resp_t resp); int gnutls_ocsp_resp_import(gnutls_ocsp_resp_t resp, const gnutls_datum_t * data); int gnutls_ocsp_resp_import2(gnutls_ocsp_resp_t resp, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t fmt); int gnutls_ocsp_resp_export(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * data); int gnutls_ocsp_resp_export2(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * data, gnutls_x509_crt_fmt_t fmt); int gnutls_ocsp_resp_print(gnutls_ocsp_resp_const_t resp, gnutls_ocsp_print_formats_t format, gnutls_datum_t * out); int gnutls_ocsp_resp_get_status(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_response(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * response_type_oid, gnutls_datum_t * response); int gnutls_ocsp_resp_get_version(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_responder(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * dn); int gnutls_ocsp_resp_get_responder2(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * dn, unsigned flags); /* the raw key ID of the responder */ #define GNUTLS_OCSP_RESP_ID_KEY 1 /* the raw DN of the responder */ #define GNUTLS_OCSP_RESP_ID_DN 2 int gnutls_ocsp_resp_get_responder_raw_id(gnutls_ocsp_resp_const_t resp, unsigned type, gnutls_datum_t * raw); time_t gnutls_ocsp_resp_get_produced(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_single(gnutls_ocsp_resp_const_t resp, unsigned indx, gnutls_digest_algorithm_t * digest, gnutls_datum_t * issuer_name_hash, gnutls_datum_t * issuer_key_hash, gnutls_datum_t * serial_number, unsigned int *cert_status, time_t * this_update, time_t * next_update, time_t * revocation_time, unsigned int *revocation_reason); int gnutls_ocsp_resp_get_extension(gnutls_ocsp_resp_const_t resp, unsigned indx, gnutls_datum_t * oid, unsigned int *critical, gnutls_datum_t * data); int gnutls_ocsp_resp_get_nonce(gnutls_ocsp_resp_const_t resp, unsigned int *critical, gnutls_datum_t * nonce); int gnutls_ocsp_resp_get_signature_algorithm(gnutls_ocsp_resp_const_t resp); int gnutls_ocsp_resp_get_signature(gnutls_ocsp_resp_const_t resp, gnutls_datum_t * sig); int gnutls_ocsp_resp_get_certs(gnutls_ocsp_resp_const_t resp, gnutls_x509_crt_t ** certs, size_t * ncerts); int gnutls_ocsp_resp_verify_direct(gnutls_ocsp_resp_const_t resp, gnutls_x509_crt_t issuer, unsigned int *verify, unsigned int flags); int gnutls_ocsp_resp_verify(gnutls_ocsp_resp_const_t resp, gnutls_x509_trust_list_t trustlist, unsigned int *verify, unsigned int flags); int gnutls_ocsp_resp_check_crt(gnutls_ocsp_resp_const_t resp, unsigned int indx, gnutls_x509_crt_t crt); int gnutls_ocsp_resp_list_import2(gnutls_ocsp_resp_t **ocsps, unsigned int *size, const gnutls_datum_t *resp_data, gnutls_x509_crt_fmt_t format, unsigned int flags); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_OCSP_H */ ================================================ FILE: thirdparty/64/include/gnutls/openpgp.h ================================================ /* * Copyright (C) 2003-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the OpenPGP * key and private key parsing functions. */ #ifndef GNUTLS_OPENPGP_H #define GNUTLS_OPENPGP_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* Openpgp certificate stuff */ /** * gnutls_openpgp_crt_fmt_t: * @GNUTLS_OPENPGP_FMT_RAW: OpenPGP certificate in raw format. * @GNUTLS_OPENPGP_FMT_BASE64: OpenPGP certificate in base64 format. * * Enumeration of different OpenPGP key formats. */ typedef enum gnutls_openpgp_crt_fmt { GNUTLS_OPENPGP_FMT_RAW, GNUTLS_OPENPGP_FMT_BASE64 } gnutls_openpgp_crt_fmt_t; #define GNUTLS_OPENPGP_KEYID_SIZE 8 #define GNUTLS_OPENPGP_V4_FINGERPRINT_SIZE 20 typedef unsigned char gnutls_openpgp_keyid_t[GNUTLS_OPENPGP_KEYID_SIZE]; /* gnutls_openpgp_cert_t should be defined in gnutls.h */ /* initializes the memory for gnutls_openpgp_crt_t struct */ int gnutls_openpgp_crt_init(gnutls_openpgp_crt_t * key) _GNUTLS_GCC_ATTR_DEPRECATED; /* frees all memory */ void gnutls_openpgp_crt_deinit(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_import(gnutls_openpgp_crt_t key, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_export(gnutls_openpgp_crt_t key, gnutls_openpgp_crt_fmt_t format, void *output_data, size_t * output_data_size) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_export2(gnutls_openpgp_crt_t key, gnutls_openpgp_crt_fmt_t format, gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_print(gnutls_openpgp_crt_t cert, gnutls_certificate_print_formats_t format, gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED; /* The key_usage flags are defined in gnutls.h. They are * the GNUTLS_KEY_* definitions. */ #define GNUTLS_OPENPGP_MASTER_KEYID_IDX INT_MAX int gnutls_openpgp_crt_get_key_usage(gnutls_openpgp_crt_t key, unsigned int *key_usage) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_fingerprint(gnutls_openpgp_crt_t key, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_fingerprint(gnutls_openpgp_crt_t key, unsigned int idx, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_name(gnutls_openpgp_crt_t key, int idx, char *buf, size_t * sizeof_buf) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_crt_get_pk_algorithm(gnutls_openpgp_crt_t key, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_version(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_creation_time(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_expiration_time(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_key_id(gnutls_openpgp_crt_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_check_hostname(gnutls_openpgp_crt_t key, const char *hostname) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_check_hostname2(gnutls_openpgp_crt_t key, const char *hostname, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_check_email(gnutls_openpgp_crt_t key, const char *email, unsigned flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_revoked_status(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_count(gnutls_openpgp_crt_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_idx(gnutls_openpgp_crt_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_revoked_status (gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_crt_get_subkey_pk_algorithm(gnutls_openpgp_crt_t key, unsigned int idx, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_subkey_creation_time (gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_crt_get_subkey_expiration_time (gnutls_openpgp_crt_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_id(gnutls_openpgp_crt_t key, unsigned int idx, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_usage(gnutls_openpgp_crt_t key, unsigned int idx, unsigned int *key_usage) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_pk_dsa_raw(gnutls_openpgp_crt_t crt, unsigned int idx, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_subkey_pk_rsa_raw(gnutls_openpgp_crt_t crt, unsigned int idx, gnutls_datum_t * m, gnutls_datum_t * e) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_pk_dsa_raw(gnutls_openpgp_crt_t crt, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_pk_rsa_raw(gnutls_openpgp_crt_t crt, gnutls_datum_t * m, gnutls_datum_t * e) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_preferred_key_id(gnutls_openpgp_crt_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_set_preferred_key_id(gnutls_openpgp_crt_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; /* privkey stuff. */ int gnutls_openpgp_privkey_init(gnutls_openpgp_privkey_t * key) _GNUTLS_GCC_ATTR_DEPRECATED; void gnutls_openpgp_privkey_deinit(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_privkey_get_pk_algorithm (gnutls_openpgp_privkey_t key, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_sec_param_t gnutls_openpgp_privkey_sec_param(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_import(gnutls_openpgp_privkey_t key, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format, const char *password, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_fingerprint(gnutls_openpgp_privkey_t key, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_fingerprint (gnutls_openpgp_privkey_t key, unsigned int idx, void *fpr, size_t * fprlen) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_key_id(gnutls_openpgp_privkey_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_count(gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_idx(gnutls_openpgp_privkey_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_revoked_status (gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_revoked_status (gnutls_openpgp_privkey_t key) _GNUTLS_GCC_ATTR_DEPRECATED; gnutls_pk_algorithm_t gnutls_openpgp_privkey_get_subkey_pk_algorithm (gnutls_openpgp_privkey_t key, unsigned int idx, unsigned int *bits) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_privkey_get_subkey_expiration_time (gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_subkey_id(gnutls_openpgp_privkey_t key, unsigned int idx, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; time_t gnutls_openpgp_privkey_get_subkey_creation_time (gnutls_openpgp_privkey_t key, unsigned int idx) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_subkey_dsa_raw (gnutls_openpgp_privkey_t pkey, unsigned int idx, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_subkey_rsa_raw (gnutls_openpgp_privkey_t pkey, unsigned int idx, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_dsa_raw(gnutls_openpgp_privkey_t pkey, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export_rsa_raw(gnutls_openpgp_privkey_t pkey, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export(gnutls_openpgp_privkey_t key, gnutls_openpgp_crt_fmt_t format, const char *password, unsigned int flags, void *output_data, size_t * output_data_size) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_export2(gnutls_openpgp_privkey_t key, gnutls_openpgp_crt_fmt_t format, const char *password, unsigned int flags, gnutls_datum_t * out) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_set_preferred_key_id (gnutls_openpgp_privkey_t key, const gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_privkey_get_preferred_key_id (gnutls_openpgp_privkey_t key, gnutls_openpgp_keyid_t keyid) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_get_auth_subkey(gnutls_openpgp_crt_t crt, gnutls_openpgp_keyid_t keyid, unsigned int flag) _GNUTLS_GCC_ATTR_DEPRECATED; /* Keyring stuff. */ int gnutls_openpgp_keyring_init(gnutls_openpgp_keyring_t * keyring) _GNUTLS_GCC_ATTR_DEPRECATED; void gnutls_openpgp_keyring_deinit(gnutls_openpgp_keyring_t keyring) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_import(gnutls_openpgp_keyring_t keyring, const gnutls_datum_t * data, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_check_id(gnutls_openpgp_keyring_t ring, const gnutls_openpgp_keyid_t keyid, unsigned int flags) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_verify_ring(gnutls_openpgp_crt_t key, gnutls_openpgp_keyring_t keyring, unsigned int flags, unsigned int *verify /* the output of the verification */ ) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_crt_verify_self(gnutls_openpgp_crt_t key, unsigned int flags, unsigned int *verify) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_get_crt(gnutls_openpgp_keyring_t ring, unsigned int idx, gnutls_openpgp_crt_t * cert) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_openpgp_keyring_get_crt_count(gnutls_openpgp_keyring_t ring) _GNUTLS_GCC_ATTR_DEPRECATED; /** * gnutls_openpgp_recv_key_func: * @session: a TLS session * @keyfpr: key fingerprint * @keyfpr_length: length of key fingerprint * @key: output key. * * A callback of this type is used to retrieve OpenPGP keys. Only * useful on the server, and will only be used if the peer send a key * fingerprint instead of a full key. See also * gnutls_openpgp_set_recv_key_function(). * * The variable @key must be allocated using gnutls_malloc(). * * Returns: On success, %GNUTLS_E_SUCCESS (zero) is returned, * otherwise an error code is returned. */ typedef int (*gnutls_openpgp_recv_key_func) (gnutls_session_t session, const unsigned char *keyfpr, unsigned int keyfpr_length, gnutls_datum_t * key); void gnutls_openpgp_set_recv_key_function(gnutls_session_t session, gnutls_openpgp_recv_key_func func) _GNUTLS_GCC_ATTR_DEPRECATED; /* certificate authentication stuff. */ int gnutls_certificate_set_openpgp_key (gnutls_certificate_credentials_t res, gnutls_openpgp_crt_t crt, gnutls_openpgp_privkey_t pkey) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_get_openpgp_key(gnutls_certificate_credentials_t res, unsigned index, gnutls_openpgp_privkey_t *key) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_get_openpgp_crt(gnutls_certificate_credentials_t res, unsigned index, gnutls_openpgp_crt_t **crt_list, unsigned *crt_list_size) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_file (gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_mem (gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_file2 (gnutls_certificate_credentials_t res, const char *certfile, const char *keyfile, const char *subkey_id, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_key_mem2 (gnutls_certificate_credentials_t res, const gnutls_datum_t * cert, const gnutls_datum_t * key, const char *subkey_id, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_keyring_mem (gnutls_certificate_credentials_t c, const unsigned char *data, size_t dlen, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; int gnutls_certificate_set_openpgp_keyring_file (gnutls_certificate_credentials_t c, const char *file, gnutls_openpgp_crt_fmt_t format) _GNUTLS_GCC_ATTR_DEPRECATED; /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_OPENPGP_H */ ================================================ FILE: thirdparty/64/include/gnutls/pkcs11.h ================================================ /* * Copyright (C) 2010-2012 Free Software Foundation, Inc. * Copyright (C) 2016-2018 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_PKCS11_H #define GNUTLS_PKCS11_H #include #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ #define GNUTLS_PKCS11_MAX_PIN_LEN 256 /** * gnutls_pkcs11_token_callback_t: * @userdata: user-controlled data from gnutls_pkcs11_set_token_function(). * @label: token label. * @retry: retry counter, initially 0. * * Token callback function. The callback will be used to ask the user * to re-insert the token with given (null terminated) label. The * callback should return zero if token has been inserted by user and * a negative error code otherwise. It might be called multiple times * if the token is not detected and the retry counter will be * increased. * * Returns: %GNUTLS_E_SUCCESS (0) on success or a negative error code * on error. * * Since: 2.12.0 **/ typedef int (*gnutls_pkcs11_token_callback_t) (void *const userdata, const char *const label, unsigned retry); struct gnutls_pkcs11_obj_st; typedef struct gnutls_pkcs11_obj_st *gnutls_pkcs11_obj_t; #define GNUTLS_PKCS11_FLAG_MANUAL 0 /* Manual loading of libraries */ #define GNUTLS_PKCS11_FLAG_AUTO 1 /* Automatically load libraries by reading /etc/gnutls/pkcs11.conf */ #define GNUTLS_PKCS11_FLAG_AUTO_TRUSTED (1<<1) /* Automatically load trusted libraries by reading /etc/gnutls/pkcs11.conf */ /* pkcs11.conf format: * load = /lib/xxx-pkcs11.so * load = /lib/yyy-pkcs11.so */ int gnutls_pkcs11_init(unsigned int flags, const char *deprecated_config_file); int gnutls_pkcs11_reinit(void); void gnutls_pkcs11_deinit(void); void gnutls_pkcs11_set_token_function (gnutls_pkcs11_token_callback_t fn, void *userdata); void gnutls_pkcs11_set_pin_function(gnutls_pin_callback_t fn, void *userdata); gnutls_pin_callback_t gnutls_pkcs11_get_pin_function(void **userdata); int gnutls_pkcs11_add_provider(const char *name, const char *params); int gnutls_pkcs11_obj_init(gnutls_pkcs11_obj_t * obj); void gnutls_pkcs11_obj_set_pin_function(gnutls_pkcs11_obj_t obj, gnutls_pin_callback_t fn, void *userdata); /** * gnutls_pkcs11_obj_flags: * @GNUTLS_PKCS11_OBJ_FLAG_LOGIN: Force login in the token for the operation (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED: object marked as trusted (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE: object is explicitly marked as sensitive -unexportable (store). * @GNUTLS_PKCS11_OBJ_FLAG_LOGIN_SO: force login as a security officer in the token for the operation (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE: marked as private -requires PIN to access (store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_PRIVATE: marked as not private (store). * @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_ANY: When retrieving an object, do not set any requirements (store). * @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_TRUSTED: When retrieving an object, only retrieve the marked as trusted (alias to %GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED). * In gnutls_pkcs11_crt_is_known() it implies %GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_COMPARE if %GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY is not given. * @GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED: When writing an object, mark it as distrusted (store). * @GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_DISTRUSTED: When retrieving an object, only retrieve the marked as distrusted (seek). * @GNUTLS_PKCS11_OBJ_FLAG_COMPARE: When checking an object's presence, fully compare it before returning any result (seek). * @GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY: When checking an object's presence, compare the key before returning any result (seek). * @GNUTLS_PKCS11_OBJ_FLAG_PRESENT_IN_TRUSTED_MODULE: The object must be present in a marked as trusted module (seek). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_CA: Mark the object as a CA (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_KEY_WRAP: Mark the generated key pair as wrapping and unwrapping keys (store). * @GNUTLS_PKCS11_OBJ_FLAG_OVERWRITE_TRUSTMOD_EXT: When an issuer is requested, override its extensions with the ones present in the trust module (seek). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH: Mark the key pair as requiring authentication (pin entry) before every operation (seek+store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_EXTRACTABLE: Mark the key pair as being extractable (store). * @GNUTLS_PKCS11_OBJ_FLAG_NEVER_EXTRACTABLE: If set, the object was never marked as extractable (store). * @GNUTLS_PKCS11_OBJ_FLAG_CRT: When searching, restrict to certificates only (seek). * @GNUTLS_PKCS11_OBJ_FLAG_PUBKEY: When searching, restrict to public key objects only (seek). * @GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY: When searching, restrict to private key objects only (seek). * @GNUTLS_PKCS11_OBJ_FLAG_NO_STORE_PUBKEY: When generating a keypair don't store the public key (store). * @GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE: object marked as not sensitive -exportable (store). * * Enumeration of different PKCS #11 object flags. Some flags are used * to mark objects when storing, while others are also used while seeking * or retrieving objects. */ typedef enum gnutls_pkcs11_obj_flags { GNUTLS_PKCS11_OBJ_FLAG_LOGIN = (1<<0), GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED = (1<<1), GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE = (1<<2), GNUTLS_PKCS11_OBJ_FLAG_LOGIN_SO = (1<<3), GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE = (1<<4), GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_PRIVATE = (1<<5), GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_ANY = (1<<6), GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_TRUSTED = GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED, GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED = (1<<8), GNUTLS_PKCS11_OBJ_FLAG_RETRIEVE_DISTRUSTED = GNUTLS_PKCS11_OBJ_FLAG_MARK_DISTRUSTED, GNUTLS_PKCS11_OBJ_FLAG_COMPARE = (1<<9), GNUTLS_PKCS11_OBJ_FLAG_PRESENT_IN_TRUSTED_MODULE = (1<<10), GNUTLS_PKCS11_OBJ_FLAG_MARK_CA = (1<<11), GNUTLS_PKCS11_OBJ_FLAG_MARK_KEY_WRAP = (1<<12), GNUTLS_PKCS11_OBJ_FLAG_COMPARE_KEY = (1<<13), GNUTLS_PKCS11_OBJ_FLAG_OVERWRITE_TRUSTMOD_EXT = (1<<14), GNUTLS_PKCS11_OBJ_FLAG_MARK_ALWAYS_AUTH = (1<<15), GNUTLS_PKCS11_OBJ_FLAG_MARK_EXTRACTABLE = (1<<16), GNUTLS_PKCS11_OBJ_FLAG_NEVER_EXTRACTABLE = (1<<17), GNUTLS_PKCS11_OBJ_FLAG_CRT = (1<<18), GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY = (1<<19), GNUTLS_PKCS11_OBJ_FLAG_PUBKEY = (1<<20), GNUTLS_PKCS11_OBJ_FLAG_NO_STORE_PUBKEY = GNUTLS_PKCS11_OBJ_FLAG_PUBKEY, GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY = (1<<21), GNUTLS_PKCS11_OBJ_FLAG_MARK_NOT_SENSITIVE = (1<<22), /* flags 1<<29 and later are reserved - see pkcs11_int.h */ } gnutls_pkcs11_obj_flags; #define gnutls_pkcs11_obj_attr_t gnutls_pkcs11_obj_flags /** * gnutls_pkcs11_url_type_t: * @GNUTLS_PKCS11_URL_GENERIC: A generic-purpose URL. * @GNUTLS_PKCS11_URL_LIB: A URL that specifies the library used as well. * @GNUTLS_PKCS11_URL_LIB_VERSION: A URL that specifies the library and its version. * * Enumeration of different URL extraction flags. */ typedef enum { GNUTLS_PKCS11_URL_GENERIC, /* URL specifies the object on token level */ GNUTLS_PKCS11_URL_LIB, /* URL specifies the object on module level */ GNUTLS_PKCS11_URL_LIB_VERSION /* URL specifies the object on module and version level */ } gnutls_pkcs11_url_type_t; int gnutls_pkcs11_obj_import_url(gnutls_pkcs11_obj_t obj, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_obj_export_url(gnutls_pkcs11_obj_t obj, gnutls_pkcs11_url_type_t detailed, char **url); void gnutls_pkcs11_obj_deinit(gnutls_pkcs11_obj_t obj); int gnutls_pkcs11_obj_export(gnutls_pkcs11_obj_t obj, void *output_data, size_t * output_data_size); int gnutls_pkcs11_obj_export2(gnutls_pkcs11_obj_t obj, gnutls_datum_t * out); int gnutls_pkcs11_obj_export3(gnutls_pkcs11_obj_t obj, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * out); int gnutls_pkcs11_get_raw_issuer(const char *url, gnutls_x509_crt_t cert, gnutls_datum_t * issuer, gnutls_x509_crt_fmt_t fmt, unsigned int flags); int gnutls_pkcs11_get_raw_issuer_by_dn (const char *url, const gnutls_datum_t *dn, gnutls_datum_t *issuer, gnutls_x509_crt_fmt_t fmt, unsigned int flags); int gnutls_pkcs11_get_raw_issuer_by_subject_key_id (const char *url, const gnutls_datum_t *dn, const gnutls_datum_t *spki, gnutls_datum_t *issuer, gnutls_x509_crt_fmt_t fmt, unsigned int flags); unsigned gnutls_pkcs11_crt_is_known(const char *url, gnutls_x509_crt_t cert, unsigned int flags); #if 0 /* for documentation */ int gnutls_pkcs11_copy_x509_crt(const char *token_url, gnutls_x509_crt_t crt, const char *label, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_copy_x509_privkey(const char *token_url, gnutls_x509_privkey_t key, const char *label, unsigned int key_usage, unsigned int flags); int gnutls_pkcs11_privkey_generate2(const char *url, gnutls_pk_algorithm_t pk, unsigned int bits, const char *label, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * pubkey, unsigned int flags); int gnutls_pkcs11_privkey_generate(const char *url, gnutls_pk_algorithm_t pk, unsigned int bits, const char *label, unsigned int flags); #endif int gnutls_pkcs11_copy_pubkey(const char *token_url, gnutls_pubkey_t crt, const char *label, const gnutls_datum_t *cid, unsigned int key_usage, unsigned int flags); #define gnutls_pkcs11_copy_x509_crt(url, crt, label, flags) \ gnutls_pkcs11_copy_x509_crt2(url, crt, label, NULL, flags) int gnutls_pkcs11_copy_x509_crt2(const char *token_url, gnutls_x509_crt_t crt, const char *label, const gnutls_datum_t *id, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */); #define gnutls_pkcs11_copy_x509_privkey(url, key, label, usage, flags) \ gnutls_pkcs11_copy_x509_privkey2(url, key, label, NULL, usage, flags) int gnutls_pkcs11_copy_x509_privkey2(const char *token_url, gnutls_x509_privkey_t key, const char *label, const gnutls_datum_t *cid, unsigned int key_usage /*GNUTLS_KEY_* */ , unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_delete_url(const char *object_url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_copy_secret_key(const char *token_url, gnutls_datum_t * key, const char *label, unsigned int key_usage /* GNUTLS_KEY_* */ , unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); /** * gnutls_pkcs11_obj_info_t: * @GNUTLS_PKCS11_OBJ_ID_HEX: The object ID in hex. Null-terminated text. * @GNUTLS_PKCS11_OBJ_LABEL: The object label. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_LABEL: The token's label. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_SERIAL: The token's serial number. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_MANUFACTURER: The token's manufacturer. Null-terminated text. * @GNUTLS_PKCS11_OBJ_TOKEN_MODEL: The token's model. Null-terminated text. * @GNUTLS_PKCS11_OBJ_ID: The object ID. Raw bytes. * @GNUTLS_PKCS11_OBJ_LIBRARY_VERSION: The library's version. Null-terminated text. * @GNUTLS_PKCS11_OBJ_LIBRARY_DESCRIPTION: The library's description. Null-terminated text. * @GNUTLS_PKCS11_OBJ_LIBRARY_MANUFACTURER: The library's manufacturer name. Null-terminated text. * * Enumeration of several object information types. */ typedef enum { GNUTLS_PKCS11_OBJ_ID_HEX = 1, GNUTLS_PKCS11_OBJ_LABEL, GNUTLS_PKCS11_OBJ_TOKEN_LABEL, GNUTLS_PKCS11_OBJ_TOKEN_SERIAL, GNUTLS_PKCS11_OBJ_TOKEN_MANUFACTURER, GNUTLS_PKCS11_OBJ_TOKEN_MODEL, GNUTLS_PKCS11_OBJ_ID, /* the pkcs11 provider library info */ GNUTLS_PKCS11_OBJ_LIBRARY_VERSION, GNUTLS_PKCS11_OBJ_LIBRARY_DESCRIPTION, GNUTLS_PKCS11_OBJ_LIBRARY_MANUFACTURER } gnutls_pkcs11_obj_info_t; int gnutls_pkcs11_obj_get_ptr(gnutls_pkcs11_obj_t obj, void **ptr, void **session, void **ohandle, unsigned long *slot_id, unsigned int flags); int gnutls_pkcs11_obj_get_info(gnutls_pkcs11_obj_t obj, gnutls_pkcs11_obj_info_t itype, void *output, size_t * output_size); int gnutls_pkcs11_obj_set_info(gnutls_pkcs11_obj_t obj, gnutls_pkcs11_obj_info_t itype, const void *data, size_t data_size, unsigned flags); #define GNUTLS_PKCS11_OBJ_ATTR_CRT_ALL GNUTLS_PKCS11_OBJ_FLAG_CRT #define GNUTLS_PKCS11_OBJ_ATTR_MATCH 0 /* always match the given URL */ #define GNUTLS_PKCS11_OBJ_ATTR_ALL 0 /* match everything! */ #define GNUTLS_PKCS11_OBJ_ATTR_CRT_TRUSTED (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED) #define GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_WITH_PRIVKEY) #define GNUTLS_PKCS11_OBJ_ATTR_CRT_TRUSTED_CA (GNUTLS_PKCS11_OBJ_FLAG_CRT|GNUTLS_PKCS11_OBJ_FLAG_MARK_CA|GNUTLS_PKCS11_OBJ_FLAG_MARK_TRUSTED) #define GNUTLS_PKCS11_OBJ_ATTR_PUBKEY GNUTLS_PKCS11_OBJ_FLAG_PUBKEY #define GNUTLS_PKCS11_OBJ_ATTR_PRIVKEY GNUTLS_PKCS11_OBJ_FLAG_PRIVKEY /** * gnutls_pkcs11_token_info_t: * @GNUTLS_PKCS11_TOKEN_LABEL: The token's label (string) * @GNUTLS_PKCS11_TOKEN_SERIAL: The token's serial number (string) * @GNUTLS_PKCS11_TOKEN_MANUFACTURER: The token's manufacturer (string) * @GNUTLS_PKCS11_TOKEN_MODEL: The token's model (string) * @GNUTLS_PKCS11_TOKEN_MODNAME: The token's module name (string - since 3.4.3). This value is * unavailable for providers which were manually loaded. * * Enumeration of types for retrieving token information. */ typedef enum { GNUTLS_PKCS11_TOKEN_LABEL, GNUTLS_PKCS11_TOKEN_SERIAL, GNUTLS_PKCS11_TOKEN_MANUFACTURER, GNUTLS_PKCS11_TOKEN_MODEL, GNUTLS_PKCS11_TOKEN_MODNAME } gnutls_pkcs11_token_info_t; /** * gnutls_pkcs11_obj_type_t: * @GNUTLS_PKCS11_OBJ_UNKNOWN: Unknown PKCS11 object. * @GNUTLS_PKCS11_OBJ_X509_CRT: X.509 certificate. * @GNUTLS_PKCS11_OBJ_PUBKEY: Public key. * @GNUTLS_PKCS11_OBJ_PRIVKEY: Private key. * @GNUTLS_PKCS11_OBJ_SECRET_KEY: Secret key. * @GNUTLS_PKCS11_OBJ_DATA: Data object. * @GNUTLS_PKCS11_OBJ_X509_CRT_EXTENSION: X.509 certificate extension (supported by p11-kit trust module only). * * Enumeration of object types. */ typedef enum { GNUTLS_PKCS11_OBJ_UNKNOWN, GNUTLS_PKCS11_OBJ_X509_CRT, GNUTLS_PKCS11_OBJ_PUBKEY, GNUTLS_PKCS11_OBJ_PRIVKEY, GNUTLS_PKCS11_OBJ_SECRET_KEY, GNUTLS_PKCS11_OBJ_DATA, GNUTLS_PKCS11_OBJ_X509_CRT_EXTENSION } gnutls_pkcs11_obj_type_t; int gnutls_pkcs11_token_init(const char *token_url, const char *so_pin, const char *label); int gnutls_pkcs11_token_get_ptr(const char *url, void **ptr, unsigned long *slot_id, unsigned int flags); int gnutls_pkcs11_token_get_mechanism(const char *url, unsigned int idx, unsigned long *mechanism); unsigned gnutls_pkcs11_token_check_mechanism(const char *url, unsigned long mechanism, void *ptr, unsigned psize, unsigned flags); int gnutls_pkcs11_token_set_pin(const char *token_url, const char *oldpin, const char *newpin, unsigned int flags /*gnutls_pin_flag_t */); int gnutls_pkcs11_token_get_url(unsigned int seq, gnutls_pkcs11_url_type_t detailed, char **url); int gnutls_pkcs11_token_get_info(const char *url, gnutls_pkcs11_token_info_t ttype, void *output, size_t * output_size); #define GNUTLS_PKCS11_TOKEN_HW 1 #define GNUTLS_PKCS11_TOKEN_TRUSTED (1<<1) /* p11-kit trusted */ #define GNUTLS_PKCS11_TOKEN_RNG (1<<2) /* CKF_RNG */ #define GNUTLS_PKCS11_TOKEN_LOGIN_REQUIRED (1<<3) /* CKF_LOGIN_REQUIRED */ #define GNUTLS_PKCS11_TOKEN_PROTECTED_AUTHENTICATION_PATH (1<<4) /* CKF_PROTECTED_AUTHENTICATION_PATH */ #define GNUTLS_PKCS11_TOKEN_INITIALIZED (1<<5) /* CKF_TOKEN_INITIALIZED */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_COUNT_LOW (1<<6) /* CKF_USER_PIN_COUNT_LOW */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_FINAL_TRY (1<<7) /* CKF_USER_PIN_FINAL_TRY */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_LOCKED (1<<8) /* CKF_USER_PIN_LOCKED */ #define GNUTLS_PKCS11_TOKEN_SO_PIN_COUNT_LOW (1<<9) /* CKF_SO_PIN_COUNT_LOW */ #define GNUTLS_PKCS11_TOKEN_SO_PIN_FINAL_TRY (1<<10) /* CKF_SO_PIN_FINAL_TRY */ #define GNUTLS_PKCS11_TOKEN_SO_PIN_LOCKED (1<<11) /* CKF_SO_PIN_LOCKED */ #define GNUTLS_PKCS11_TOKEN_USER_PIN_INITIALIZED (1<<12) /* CKF_USER_PIN_INITIALIZED */ #define GNUTLS_PKCS11_TOKEN_ERROR_STATE (1<<13) /* CKF_ERROR_STATE */ int gnutls_pkcs11_token_get_flags(const char *url, unsigned int *flags); #define gnutls_pkcs11_obj_list_import_url(p_list, n_list, url, attrs, flags) gnutls_pkcs11_obj_list_import_url3(p_list, n_list, url, attrs|flags) #define gnutls_pkcs11_obj_list_import_url2(p_list, n_list, url, attrs, flags) gnutls_pkcs11_obj_list_import_url4(p_list, n_list, url, attrs|flags) int gnutls_pkcs11_obj_list_import_url3(gnutls_pkcs11_obj_t * p_list, unsigned int *const n_list, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_pkcs11_obj_list_import_url4(gnutls_pkcs11_obj_t ** p_list, unsigned int *n_list, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_x509_crt_import_pkcs11(gnutls_x509_crt_t crt, gnutls_pkcs11_obj_t pkcs11_crt); gnutls_pkcs11_obj_type_t gnutls_pkcs11_obj_get_type(gnutls_pkcs11_obj_t obj); const char *gnutls_pkcs11_type_get_name(gnutls_pkcs11_obj_type_t type); int gnutls_pkcs11_obj_get_exts(gnutls_pkcs11_obj_t obj, struct gnutls_x509_ext_st **exts, unsigned int *exts_size, unsigned int flags); int gnutls_pkcs11_obj_get_flags(gnutls_pkcs11_obj_t obj, unsigned int *oflags); char *gnutls_pkcs11_obj_flags_get_str(unsigned int flags); int gnutls_x509_crt_list_import_pkcs11(gnutls_x509_crt_t * certs, unsigned int cert_max, gnutls_pkcs11_obj_t * const objs, unsigned int flags /* must be zero */ ); /* private key functions...*/ int gnutls_pkcs11_privkey_init(gnutls_pkcs11_privkey_t * key); int gnutls_pkcs11_privkey_cpy(gnutls_pkcs11_privkey_t dst, gnutls_pkcs11_privkey_t src); void gnutls_pkcs11_privkey_set_pin_function(gnutls_pkcs11_privkey_t key, gnutls_pin_callback_t fn, void *userdata); void gnutls_pkcs11_privkey_deinit(gnutls_pkcs11_privkey_t key); int gnutls_pkcs11_privkey_get_pk_algorithm(gnutls_pkcs11_privkey_t key, unsigned int *bits); int gnutls_pkcs11_privkey_get_info(gnutls_pkcs11_privkey_t pkey, gnutls_pkcs11_obj_info_t itype, void *output, size_t * output_size); int gnutls_pkcs11_privkey_import_url(gnutls_pkcs11_privkey_t pkey, const char *url, unsigned int flags); int gnutls_pkcs11_privkey_export_url(gnutls_pkcs11_privkey_t key, gnutls_pkcs11_url_type_t detailed, char **url); unsigned gnutls_pkcs11_privkey_status(gnutls_pkcs11_privkey_t key); #define gnutls_pkcs11_privkey_generate(url, pk, bits, label, flags) \ gnutls_pkcs11_privkey_generate3(url, pk, bits, label, NULL, 0, NULL, 0, flags) #define gnutls_pkcs11_privkey_generate2(url, pk, bits, label, fmt, pubkey, flags) \ gnutls_pkcs11_privkey_generate3(url, pk, bits, label, NULL, fmt, pubkey, 0, flags) int gnutls_pkcs11_privkey_generate3(const char *url, gnutls_pk_algorithm_t pk, unsigned int bits, const char *label, const gnutls_datum_t *cid, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * pubkey, unsigned int key_usage, unsigned int flags); int gnutls_pkcs11_privkey_export_pubkey(gnutls_pkcs11_privkey_t pkey, gnutls_x509_crt_fmt_t fmt, gnutls_datum_t * pubkey, unsigned int flags); int gnutls_pkcs11_token_get_random(const char *token_url, void *data, size_t len); int gnutls_pkcs11_copy_attached_extension(const char *token_url, gnutls_x509_crt_t crt, gnutls_datum_t *data, const char *label, unsigned int flags); #define gnutls_x509_crt_import_pkcs11_url gnutls_x509_crt_import_url /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_PKCS11_H */ ================================================ FILE: thirdparty/64/include/gnutls/pkcs12.h ================================================ /* * Copyright (C) 2003-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_PKCS12_H #define GNUTLS_PKCS12_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* PKCS12 structures handling */ struct gnutls_pkcs12_int; typedef struct gnutls_pkcs12_int *gnutls_pkcs12_t; struct gnutls_pkcs12_bag_int; typedef struct gnutls_pkcs12_bag_int *gnutls_pkcs12_bag_t; int gnutls_pkcs12_init(gnutls_pkcs12_t * pkcs12); void gnutls_pkcs12_deinit(gnutls_pkcs12_t pkcs12); int gnutls_pkcs12_import(gnutls_pkcs12_t pkcs12, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_pkcs12_export(gnutls_pkcs12_t pkcs12, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_pkcs12_export2(gnutls_pkcs12_t pkcs12, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_pkcs12_get_bag(gnutls_pkcs12_t pkcs12, int indx, gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_set_bag(gnutls_pkcs12_t pkcs12, gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_generate_mac(gnutls_pkcs12_t pkcs12, const char *pass); int gnutls_pkcs12_generate_mac2(gnutls_pkcs12_t pkcs12, gnutls_mac_algorithm_t mac, const char *pass); int gnutls_pkcs12_verify_mac(gnutls_pkcs12_t pkcs12, const char *pass); int gnutls_pkcs12_bag_decrypt(gnutls_pkcs12_bag_t bag, const char *pass); int gnutls_pkcs12_bag_encrypt(gnutls_pkcs12_bag_t bag, const char *pass, unsigned int flags); int gnutls_pkcs12_bag_enc_info(gnutls_pkcs12_bag_t bag, unsigned int *schema, unsigned int *cipher, void *salt, unsigned int *salt_size, unsigned int *iter_count, char **oid); int gnutls_pkcs12_mac_info(gnutls_pkcs12_t pkcs12, unsigned int *mac, void *salt, unsigned int *salt_size, unsigned int *iter_count, char **oid); #define GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED 1 int gnutls_pkcs12_simple_parse(gnutls_pkcs12_t p12, const char *password, gnutls_x509_privkey_t * key, gnutls_x509_crt_t ** chain, unsigned int *chain_len, gnutls_x509_crt_t ** extra_certs, unsigned int *extra_certs_len, gnutls_x509_crl_t * crl, unsigned int flags); /** * gnutls_pkcs12_bag_type_t: * @GNUTLS_BAG_EMPTY: Empty PKCS-12 bag. * @GNUTLS_BAG_PKCS8_ENCRYPTED_KEY: PKCS-12 bag with PKCS-8 encrypted key. * @GNUTLS_BAG_PKCS8_KEY: PKCS-12 bag with PKCS-8 key. * @GNUTLS_BAG_CERTIFICATE: PKCS-12 bag with certificate. * @GNUTLS_BAG_CRL: PKCS-12 bag with CRL. * @GNUTLS_BAG_SECRET: PKCS-12 bag with secret PKCS-9 keys. * @GNUTLS_BAG_ENCRYPTED: Encrypted PKCS-12 bag. * @GNUTLS_BAG_UNKNOWN: Unknown PKCS-12 bag. * * Enumeration of different PKCS 12 bag types. */ typedef enum gnutls_pkcs12_bag_type_t { GNUTLS_BAG_EMPTY = 0, GNUTLS_BAG_PKCS8_ENCRYPTED_KEY = 1, GNUTLS_BAG_PKCS8_KEY = 2, GNUTLS_BAG_CERTIFICATE = 3, GNUTLS_BAG_CRL = 4, GNUTLS_BAG_SECRET = 5, /* Secret data. Underspecified in pkcs-12, * gnutls extension. We use the PKCS-9 * random nonce ID 1.2.840.113549.1.9.25.3 * to store randomly generated keys. */ GNUTLS_BAG_ENCRYPTED = 10, GNUTLS_BAG_UNKNOWN = 20 } gnutls_pkcs12_bag_type_t; int gnutls_pkcs12_bag_get_type(gnutls_pkcs12_bag_t bag, unsigned indx); int gnutls_pkcs12_bag_get_data(gnutls_pkcs12_bag_t bag, unsigned indx, gnutls_datum_t * data); int gnutls_pkcs12_bag_set_data(gnutls_pkcs12_bag_t bag, gnutls_pkcs12_bag_type_t type, const gnutls_datum_t * data); int gnutls_pkcs12_bag_set_crl(gnutls_pkcs12_bag_t bag, gnutls_x509_crl_t crl); int gnutls_pkcs12_bag_set_crt(gnutls_pkcs12_bag_t bag, gnutls_x509_crt_t crt); int gnutls_pkcs12_bag_set_privkey(gnutls_pkcs12_bag_t bag, gnutls_x509_privkey_t privkey, const char *password, unsigned flags); int gnutls_pkcs12_bag_init(gnutls_pkcs12_bag_t * bag); void gnutls_pkcs12_bag_deinit(gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_bag_get_count(gnutls_pkcs12_bag_t bag); int gnutls_pkcs12_bag_get_key_id(gnutls_pkcs12_bag_t bag, unsigned indx, gnutls_datum_t * id); int gnutls_pkcs12_bag_set_key_id(gnutls_pkcs12_bag_t bag, unsigned indx, const gnutls_datum_t * id); int gnutls_pkcs12_bag_get_friendly_name(gnutls_pkcs12_bag_t bag, unsigned indx, char **name); int gnutls_pkcs12_bag_set_friendly_name(gnutls_pkcs12_bag_t bag, unsigned indx, const char *name); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_PKCS12_H */ ================================================ FILE: thirdparty/64/include/gnutls/pkcs7.h ================================================ /* * Copyright (C) 2003-2012 Free Software Foundation, Inc. * Copyright (C) 2015 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the X.509 * certificate and CRL handling functions. */ #ifndef GNUTLS_PKCS7_H #define GNUTLS_PKCS7_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* PKCS7 structures handling */ struct gnutls_pkcs7_int; typedef struct gnutls_pkcs7_int *gnutls_pkcs7_t; int gnutls_pkcs7_init(gnutls_pkcs7_t * pkcs7); void gnutls_pkcs7_deinit(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_import(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_pkcs7_export(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_pkcs7_export2(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_pkcs7_get_signature_count(gnutls_pkcs7_t pkcs7); #define GNUTLS_PKCS7_EDATA_GET_RAW (1<<24) int gnutls_pkcs7_get_embedded_data(gnutls_pkcs7_t pkcs7, unsigned flags, gnutls_datum_t *data); const char * gnutls_pkcs7_get_embedded_data_oid(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_get_crt_count(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_get_crt_raw(gnutls_pkcs7_t pkcs7, unsigned indx, void *certificate, size_t * certificate_size); int gnutls_pkcs7_set_crt_raw(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * crt); int gnutls_pkcs7_set_crt(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_t crt); int gnutls_pkcs7_delete_crt(gnutls_pkcs7_t pkcs7, int indx); int gnutls_pkcs7_get_crl_raw(gnutls_pkcs7_t pkcs7, unsigned indx, void *crl, size_t * crl_size); int gnutls_pkcs7_get_crl_count(gnutls_pkcs7_t pkcs7); int gnutls_pkcs7_set_crl_raw(gnutls_pkcs7_t pkcs7, const gnutls_datum_t * crl); int gnutls_pkcs7_set_crl(gnutls_pkcs7_t pkcs7, gnutls_x509_crl_t crl); int gnutls_pkcs7_delete_crl(gnutls_pkcs7_t pkcs7, int indx); typedef struct gnutls_pkcs7_attrs_st *gnutls_pkcs7_attrs_t; typedef struct gnutls_pkcs7_signature_info_st { gnutls_sign_algorithm_t algo; gnutls_datum_t sig; gnutls_datum_t issuer_dn; gnutls_datum_t signer_serial; gnutls_datum_t issuer_keyid; time_t signing_time; gnutls_pkcs7_attrs_t signed_attrs; gnutls_pkcs7_attrs_t unsigned_attrs; char pad[64]; } gnutls_pkcs7_signature_info_st; void gnutls_pkcs7_signature_info_deinit(gnutls_pkcs7_signature_info_st *info); int gnutls_pkcs7_get_signature_info(gnutls_pkcs7_t pkcs7, unsigned idx, gnutls_pkcs7_signature_info_st *info); int gnutls_pkcs7_verify_direct(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_t signer, unsigned idx, const gnutls_datum_t *data, unsigned flags); int gnutls_pkcs7_verify(gnutls_pkcs7_t pkcs7, gnutls_x509_trust_list_t tl, gnutls_typed_vdata_st * vdata, unsigned int vdata_size, unsigned idx, const gnutls_datum_t *data, unsigned flags); #define GNUTLS_PKCS7_ATTR_ENCODE_OCTET_STRING 1 int gnutls_pkcs7_add_attr(gnutls_pkcs7_attrs_t *list, const char *oid, gnutls_datum_t *data, unsigned flags); void gnutls_pkcs7_attrs_deinit(gnutls_pkcs7_attrs_t list); int gnutls_pkcs7_get_attr(gnutls_pkcs7_attrs_t list, unsigned idx, char **oid, gnutls_datum_t *data, unsigned flags); /** * gnutls_pkcs7_sign_flags: * @GNUTLS_PKCS7_EMBED_DATA: The signed data will be embedded in the structure. * @GNUTLS_PKCS7_INCLUDE_TIME: The signing time will be included in the structure. * @GNUTLS_PKCS7_INCLUDE_CERT: The signer's certificate will be included in the cert list. * @GNUTLS_PKCS7_WRITE_SPKI: Use the signer's key identifier instead of name. * * Enumeration of the different PKCS #7 signature flags. */ typedef enum gnutls_pkcs7_sign_flags { GNUTLS_PKCS7_EMBED_DATA = 1, GNUTLS_PKCS7_INCLUDE_TIME = (1<<1), GNUTLS_PKCS7_INCLUDE_CERT = (1<<2), GNUTLS_PKCS7_WRITE_SPKI = (1<<3) } gnutls_pkcs7_sign_flags; int gnutls_pkcs7_sign(gnutls_pkcs7_t pkcs7, gnutls_x509_crt_t signer, gnutls_privkey_t signer_key, const gnutls_datum_t *data, gnutls_pkcs7_attrs_t signed_attrs, gnutls_pkcs7_attrs_t unsigned_attrs, gnutls_digest_algorithm_t dig, unsigned flags); int gnutls_pkcs7_get_crt_raw2(gnutls_pkcs7_t pkcs7, unsigned indx, gnutls_datum_t *cert); int gnutls_pkcs7_get_crl_raw2(gnutls_pkcs7_t pkcs7, unsigned indx, gnutls_datum_t *crl); int gnutls_pkcs7_print(gnutls_pkcs7_t pkcs7, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); int gnutls_pkcs7_print_signature_info(gnutls_pkcs7_signature_info_st * info, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_PKCS7_H */ ================================================ FILE: thirdparty/64/include/gnutls/self-test.h ================================================ /* * Copyright (C) 2014 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_SELF_TEST_H #define GNUTLS_SELF_TEST_H #include /* Self checking functions */ #define GNUTLS_SELF_TEST_FLAG_ALL 1 #define GNUTLS_SELF_TEST_FLAG_NO_COMPAT (1<<1) int gnutls_cipher_self_test(unsigned flags, gnutls_cipher_algorithm_t cipher); int gnutls_mac_self_test(unsigned flags, gnutls_mac_algorithm_t mac); int gnutls_digest_self_test(unsigned flags, gnutls_digest_algorithm_t digest); int gnutls_pk_self_test(unsigned flags, gnutls_pk_algorithm_t pk); int gnutls_hkdf_self_test(unsigned flags, gnutls_mac_algorithm_t mac); int gnutls_pbkdf2_self_test(unsigned flags, gnutls_mac_algorithm_t mac); int gnutls_tlsprf_self_test(unsigned flags, gnutls_mac_algorithm_t mac); #endif /* GNUTLS_SELF_TEST_H */ ================================================ FILE: thirdparty/64/include/gnutls/socket.h ================================================ /* * Copyright (C) 2016 Free Software Foundation, Inc. * * Author: Tim Ruehsen * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains socket related types, prototypes and includes. */ #ifndef GNUTLS_SOCKET_H #define GNUTLS_SOCKET_H #include /* Get socklen_t */ #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /** * gnutls_transport_ktls_enable_flags_t: * @GNUTLS_KTLS_RECV: ktls enabled for recv function. * @GNUTLS_KTLS_SEND: ktls enabled for send function. * @GNUTLS_KTLS_DUPLEX: ktls enabled for both recv and send functions. * * Flag enumeration of ktls enable status for recv and send functions. * This is used by gnutls_transport_is_ktls_enabled(). * * Since: 3.7.3 */ typedef enum { GNUTLS_KTLS_RECV = 1 << 0, GNUTLS_KTLS_SEND = 1 << 1, GNUTLS_KTLS_DUPLEX = GNUTLS_KTLS_RECV | GNUTLS_KTLS_SEND, } gnutls_transport_ktls_enable_flags_t; gnutls_transport_ktls_enable_flags_t gnutls_transport_is_ktls_enabled(gnutls_session_t session); void gnutls_transport_set_fastopen(gnutls_session_t session, int fd, struct sockaddr *connect_addr, socklen_t connect_addrlen, unsigned int flags); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_SOCKET_H */ ================================================ FILE: thirdparty/64/include/gnutls/system-keys.h ================================================ /* * Copyright (C) 2014 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_SYSTEM_KEYS_H #define GNUTLS_SYSTEM_KEYS_H #include #include /* This API allows to access user key and certificate pairs that are * available in the current system. If any passwords are required, * they will be requested through the pin callbacks. */ /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ struct system_key_iter_st; typedef struct system_key_iter_st *gnutls_system_key_iter_t; void gnutls_system_key_iter_deinit(gnutls_system_key_iter_t iter); int gnutls_system_key_iter_get_info(gnutls_system_key_iter_t *iter, unsigned cert_type /* gnutls_certificate_type_t */, char **cert_url, char **key_url, char **label, gnutls_datum_t *der, unsigned int flags); int gnutls_system_key_delete(const char *cert_url, const char *key_url); int gnutls_system_key_add_x509(gnutls_x509_crt_t crt, gnutls_x509_privkey_t privkey, const char *label, char **cert_url, char **key_url); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_SYSTEM_KEYS_H */ ================================================ FILE: thirdparty/64/include/gnutls/tpm.h ================================================ /* * Copyright (C) 2010-2012 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_TPM_H #define GNUTLS_TPM_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ struct tpm_key_list_st; typedef struct tpm_key_list_st *gnutls_tpm_key_list_t; #define GNUTLS_TPM_KEY_SIGNING (1<<1) #define GNUTLS_TPM_REGISTER_KEY (1<<2) #define GNUTLS_TPM_KEY_USER (1<<3) /** * gnutls_tpmkey_fmt_t: * @GNUTLS_TPMKEY_FMT_RAW: The portable data format. * @GNUTLS_TPMKEY_FMT_DER: An alias for the raw format. * @GNUTLS_TPMKEY_FMT_CTK_PEM: A custom data format used by some TPM tools. * * Enumeration of different certificate encoding formats. */ typedef enum { GNUTLS_TPMKEY_FMT_RAW = 0, GNUTLS_TPMKEY_FMT_DER = GNUTLS_TPMKEY_FMT_RAW, GNUTLS_TPMKEY_FMT_CTK_PEM = 1 } gnutls_tpmkey_fmt_t; int gnutls_tpm_privkey_generate(gnutls_pk_algorithm_t pk, unsigned int bits, const char *srk_password, const char *key_password, gnutls_tpmkey_fmt_t format, gnutls_x509_crt_fmt_t pub_format, gnutls_datum_t * privkey, gnutls_datum_t * pubkey, unsigned int flags); void gnutls_tpm_key_list_deinit(gnutls_tpm_key_list_t list); int gnutls_tpm_key_list_get_url(gnutls_tpm_key_list_t list, unsigned int idx, char **url, unsigned int flags); int gnutls_tpm_get_registered(gnutls_tpm_key_list_t * list); int gnutls_tpm_privkey_delete(const char *url, const char *srk_password); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_TPM_H */ ================================================ FILE: thirdparty/64/include/gnutls/urls.h ================================================ /* * Copyright (C) 2014 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ #ifndef GNUTLS_URLS_H #define GNUTLS_URLS_H #include #include #include /* This API allows to register application specific URLs for * keys and certificates. */ /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ typedef int (*gnutls_privkey_import_url_func)(gnutls_privkey_t pkey, const char *url, unsigned flags); typedef int (*gnutls_x509_crt_import_url_func)(gnutls_x509_crt_t pkey, const char *url, unsigned flags); /* The following callbacks are optional */ /* This is to enable gnutls_pubkey_import_url() */ typedef int (*gnutls_pubkey_import_url_func)(gnutls_pubkey_t pkey, const char *url, unsigned flags); /* This is to allow constructing a certificate chain. It will be provided * the initial certificate URL and the certificate to find its issuer, and must * return zero and the DER encoding of the issuer's certificate. If not available, * it should return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE. */ typedef int (*gnutls_get_raw_issuer_func)(const char *url, gnutls_x509_crt_t crt, gnutls_datum_t *issuer_der, unsigned flags); typedef struct gnutls_custom_url_st { const char *name; unsigned name_size; gnutls_privkey_import_url_func import_key; gnutls_x509_crt_import_url_func import_crt; gnutls_pubkey_import_url_func import_pubkey; gnutls_get_raw_issuer_func get_issuer; void *future1; /* replace in a future extension */ void *future2; /* replace in a future extension */ } gnutls_custom_url_st; int gnutls_register_custom_url(const gnutls_custom_url_st *st); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_URLS_H */ ================================================ FILE: thirdparty/64/include/gnutls/x509-ext.h ================================================ /* * Copyright (C) 2014 Free Software Foundation, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* Prototypes for direct handling of extension data */ #ifndef GNUTLS_X509_EXT_H #define GNUTLS_X509_EXT_H #include #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ typedef struct gnutls_subject_alt_names_st *gnutls_subject_alt_names_t; int gnutls_subject_alt_names_init(gnutls_subject_alt_names_t *); void gnutls_subject_alt_names_deinit(gnutls_subject_alt_names_t sans); int gnutls_subject_alt_names_get(gnutls_subject_alt_names_t sans, unsigned int seq, unsigned int *san_type, gnutls_datum_t * san, gnutls_datum_t * othername_oid); int gnutls_subject_alt_names_set(gnutls_subject_alt_names_t sans, unsigned int san_type, const gnutls_datum_t * san, const char* othername_oid); int gnutls_x509_ext_import_subject_alt_names(const gnutls_datum_t * ext, gnutls_subject_alt_names_t, unsigned int flags); int gnutls_x509_ext_export_subject_alt_names(gnutls_subject_alt_names_t, gnutls_datum_t * ext); /* They are exactly the same */ #define gnutls_x509_ext_import_issuer_alt_name gnutls_x509_ext_import_subject_alt_name #define gnutls_x509_ext_export_issuer_alt_name gnutls_x509_ext_export_subject_alt_name typedef struct gnutls_x509_crl_dist_points_st *gnutls_x509_crl_dist_points_t; int gnutls_x509_crl_dist_points_init(gnutls_x509_crl_dist_points_t *); void gnutls_x509_crl_dist_points_deinit(gnutls_x509_crl_dist_points_t); int gnutls_x509_crl_dist_points_get(gnutls_x509_crl_dist_points_t, unsigned int seq, unsigned int *type, gnutls_datum_t *dist, unsigned int *reason_flags); int gnutls_x509_crl_dist_points_set(gnutls_x509_crl_dist_points_t, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t *dist, unsigned int reason_flags); int gnutls_x509_ext_import_crl_dist_points(const gnutls_datum_t * ext, gnutls_x509_crl_dist_points_t dp, unsigned int flags); int gnutls_x509_ext_export_crl_dist_points(gnutls_x509_crl_dist_points_t dp, gnutls_datum_t * ext); int gnutls_x509_ext_import_name_constraints(const gnutls_datum_t * ext, gnutls_x509_name_constraints_t nc, unsigned int flags); int gnutls_x509_ext_export_name_constraints(gnutls_x509_name_constraints_t nc, gnutls_datum_t * ext); typedef struct gnutls_x509_aia_st *gnutls_x509_aia_t; int gnutls_x509_aia_init(gnutls_x509_aia_t *); void gnutls_x509_aia_deinit(gnutls_x509_aia_t); int gnutls_x509_aia_get(gnutls_x509_aia_t aia, unsigned int seq, gnutls_datum_t *oid, unsigned *san_type, gnutls_datum_t *san); int gnutls_x509_aia_set(gnutls_x509_aia_t aia, const char *oid, unsigned san_type, const gnutls_datum_t * san); int gnutls_x509_ext_import_aia(const gnutls_datum_t * ext, gnutls_x509_aia_t, unsigned int flags); int gnutls_x509_ext_export_aia(gnutls_x509_aia_t aia, gnutls_datum_t * ext); int gnutls_x509_ext_import_subject_key_id(const gnutls_datum_t * ext, gnutls_datum_t * id); int gnutls_x509_ext_export_subject_key_id(const gnutls_datum_t * id, gnutls_datum_t * ext); typedef struct gnutls_x509_aki_st *gnutls_x509_aki_t; int gnutls_x509_ext_export_authority_key_id(gnutls_x509_aki_t, gnutls_datum_t * ext); int gnutls_x509_ext_import_authority_key_id(const gnutls_datum_t * ext, gnutls_x509_aki_t, unsigned int flags); int gnutls_x509_othername_to_virtual(const char *oid, const gnutls_datum_t *othername, unsigned int *virt_type, gnutls_datum_t *virt); int gnutls_x509_aki_init(gnutls_x509_aki_t *); int gnutls_x509_aki_get_id(gnutls_x509_aki_t, gnutls_datum_t *id); int gnutls_x509_aki_get_cert_issuer(gnutls_x509_aki_t aki, unsigned int seq, unsigned int *san_type, gnutls_datum_t * san, gnutls_datum_t *othername_oid, gnutls_datum_t *serial); int gnutls_x509_aki_set_id(gnutls_x509_aki_t aki, const gnutls_datum_t *id); int gnutls_x509_aki_set_cert_issuer(gnutls_x509_aki_t aki, unsigned int san_type, const gnutls_datum_t * san, const char *othername_oid, const gnutls_datum_t * serial); void gnutls_x509_aki_deinit(gnutls_x509_aki_t); int gnutls_x509_ext_import_private_key_usage_period(const gnutls_datum_t * ext, time_t * activation, time_t * expiration); int gnutls_x509_ext_export_private_key_usage_period(time_t activation, time_t expiration, gnutls_datum_t * ext); int gnutls_x509_ext_import_basic_constraints(const gnutls_datum_t * ext, unsigned int *ca, int *pathlen); int gnutls_x509_ext_export_basic_constraints(unsigned int ca, int pathlen, gnutls_datum_t * ext); typedef struct gnutls_x509_key_purposes_st *gnutls_x509_key_purposes_t; int gnutls_x509_key_purpose_init(gnutls_x509_key_purposes_t *p); void gnutls_x509_key_purpose_deinit(gnutls_x509_key_purposes_t p); int gnutls_x509_key_purpose_set(gnutls_x509_key_purposes_t p, const char *oid); int gnutls_x509_key_purpose_get(gnutls_x509_key_purposes_t p, unsigned idx, gnutls_datum_t *oid); int gnutls_x509_ext_import_key_purposes(const gnutls_datum_t * ext, gnutls_x509_key_purposes_t, unsigned int flags); int gnutls_x509_ext_export_key_purposes(gnutls_x509_key_purposes_t, gnutls_datum_t * ext); int gnutls_x509_ext_import_key_usage(const gnutls_datum_t * ext, unsigned int *key_usage); int gnutls_x509_ext_export_key_usage(unsigned int key_usage, gnutls_datum_t * ext); int gnutls_x509_ext_import_inhibit_anypolicy(const gnutls_datum_t * ext, unsigned int *skipcerts); int gnutls_x509_ext_export_inhibit_anypolicy(unsigned int skipcerts, gnutls_datum_t * ext); int gnutls_x509_ext_import_proxy(const gnutls_datum_t * ext, int *pathlen, char **policyLanguage, char **policy, size_t * sizeof_policy); int gnutls_x509_ext_export_proxy(int pathLenConstraint, const char *policyLanguage, const char *policy, size_t sizeof_policy, gnutls_datum_t * ext); typedef struct gnutls_x509_policies_st *gnutls_x509_policies_t; int gnutls_x509_policies_init(gnutls_x509_policies_t *); void gnutls_x509_policies_deinit(gnutls_x509_policies_t); int gnutls_x509_policies_get(gnutls_x509_policies_t policies, unsigned int seq, struct gnutls_x509_policy_st *policy); int gnutls_x509_policies_set(gnutls_x509_policies_t policies, const struct gnutls_x509_policy_st *policy); int gnutls_x509_ext_import_policies(const gnutls_datum_t * ext, gnutls_x509_policies_t policies, unsigned int flags); int gnutls_x509_ext_export_policies(gnutls_x509_policies_t policies, gnutls_datum_t * ext); int gnutls_x509_ext_import_tlsfeatures(const gnutls_datum_t * ext, gnutls_x509_tlsfeatures_t, unsigned int flags); int gnutls_x509_ext_export_tlsfeatures(gnutls_x509_tlsfeatures_t f, gnutls_datum_t * ext); int gnutls_x509_tlsfeatures_add(gnutls_x509_tlsfeatures_t f, unsigned int feature); typedef struct gnutls_x509_ct_scts_st *gnutls_x509_ct_scts_t; int gnutls_x509_ext_ct_scts_init(gnutls_x509_ct_scts_t * scts); void gnutls_x509_ext_ct_scts_deinit(gnutls_x509_ct_scts_t scts); int gnutls_x509_ext_ct_import_scts(const gnutls_datum_t * ext, gnutls_x509_ct_scts_t scts, unsigned int flags); int gnutls_x509_ext_ct_export_scts(const gnutls_x509_ct_scts_t scts, gnutls_datum_t * ext); int gnutls_x509_ct_sct_get_version(const gnutls_x509_ct_scts_t scts, unsigned idx, unsigned int *version_out); int gnutls_x509_ct_sct_get(const gnutls_x509_ct_scts_t scts, unsigned idx, time_t *timestamp, gnutls_datum_t *logid, gnutls_sign_algorithm_t *sigalg, gnutls_datum_t *signature); /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_X509_EXT_H */ ================================================ FILE: thirdparty/64/include/gnutls/x509.h ================================================ /* * Copyright (C) 2003-2016 Free Software Foundation, Inc. * Copyright (C) 2015-2016 Red Hat, Inc. * * Author: Nikos Mavrogiannopoulos * * This file is part of GnuTLS. * * The GnuTLS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see * */ /* This file contains the types and prototypes for the X.509 * certificate and CRL handling functions. */ #ifndef GNUTLS_X509_H #define GNUTLS_X509_H #include /* *INDENT-OFF* */ #ifdef __cplusplus extern "C" { #endif /* *INDENT-ON* */ /* Some OIDs usually found in Distinguished names, or * in Subject Directory Attribute extensions. */ #define GNUTLS_OID_X520_COUNTRY_NAME "2.5.4.6" #define GNUTLS_OID_X520_ORGANIZATION_NAME "2.5.4.10" #define GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME "2.5.4.11" #define GNUTLS_OID_X520_COMMON_NAME "2.5.4.3" #define GNUTLS_OID_X520_LOCALITY_NAME "2.5.4.7" #define GNUTLS_OID_X520_STATE_OR_PROVINCE_NAME "2.5.4.8" #define GNUTLS_OID_X520_INITIALS "2.5.4.43" #define GNUTLS_OID_X520_GENERATION_QUALIFIER "2.5.4.44" #define GNUTLS_OID_X520_SURNAME "2.5.4.4" #define GNUTLS_OID_X520_GIVEN_NAME "2.5.4.42" #define GNUTLS_OID_X520_TITLE "2.5.4.12" #define GNUTLS_OID_X520_DN_QUALIFIER "2.5.4.46" #define GNUTLS_OID_X520_PSEUDONYM "2.5.4.65" #define GNUTLS_OID_X520_POSTALCODE "2.5.4.17" #define GNUTLS_OID_X520_NAME "2.5.4.41" #define GNUTLS_OID_LDAP_DC "0.9.2342.19200300.100.1.25" #define GNUTLS_OID_LDAP_UID "0.9.2342.19200300.100.1.1" /* The following should not be included in DN. */ #define GNUTLS_OID_PKCS9_EMAIL "1.2.840.113549.1.9.1" #define GNUTLS_OID_PKIX_DATE_OF_BIRTH "1.3.6.1.5.5.7.9.1" #define GNUTLS_OID_PKIX_PLACE_OF_BIRTH "1.3.6.1.5.5.7.9.2" #define GNUTLS_OID_PKIX_GENDER "1.3.6.1.5.5.7.9.3" #define GNUTLS_OID_PKIX_COUNTRY_OF_CITIZENSHIP "1.3.6.1.5.5.7.9.4" #define GNUTLS_OID_PKIX_COUNTRY_OF_RESIDENCE "1.3.6.1.5.5.7.9.5" /* Key purpose Object Identifiers. */ #define GNUTLS_KP_TLS_WWW_SERVER "1.3.6.1.5.5.7.3.1" #define GNUTLS_KP_TLS_WWW_CLIENT "1.3.6.1.5.5.7.3.2" #define GNUTLS_KP_CODE_SIGNING "1.3.6.1.5.5.7.3.3" #define GNUTLS_KP_MS_SMART_CARD_LOGON "1.3.6.1.4.1.311.20.2.2" #define GNUTLS_KP_EMAIL_PROTECTION "1.3.6.1.5.5.7.3.4" #define GNUTLS_KP_TIME_STAMPING "1.3.6.1.5.5.7.3.8" #define GNUTLS_KP_OCSP_SIGNING "1.3.6.1.5.5.7.3.9" #define GNUTLS_KP_IPSEC_IKE "1.3.6.1.5.5.7.3.17" #define GNUTLS_KP_ANY "2.5.29.37.0" #define GNUTLS_KP_FLAG_DISALLOW_ANY 1 #define GNUTLS_OID_AIA "1.3.6.1.5.5.7.1.1" #define GNUTLS_OID_AD_OCSP "1.3.6.1.5.5.7.48.1" #define GNUTLS_OID_AD_CAISSUERS "1.3.6.1.5.5.7.48.2" #define GNUTLS_FSAN_SET 0 #define GNUTLS_FSAN_APPEND 1 #define GNUTLS_FSAN_ENCODE_OCTET_STRING (1<<1) #define GNUTLS_FSAN_ENCODE_UTF8_STRING (1<<2) #define GNUTLS_X509EXT_OID_SUBJECT_KEY_ID "2.5.29.14" #define GNUTLS_X509EXT_OID_KEY_USAGE "2.5.29.15" #define GNUTLS_X509EXT_OID_PRIVATE_KEY_USAGE_PERIOD "2.5.29.16" #define GNUTLS_X509EXT_OID_SAN "2.5.29.17" #define GNUTLS_X509EXT_OID_IAN "2.5.29.18" #define GNUTLS_X509EXT_OID_BASIC_CONSTRAINTS "2.5.29.19" #define GNUTLS_X509EXT_OID_NAME_CONSTRAINTS "2.5.29.30" #define GNUTLS_X509EXT_OID_CRL_DIST_POINTS "2.5.29.31" #define GNUTLS_X509EXT_OID_CRT_POLICY "2.5.29.32" #define GNUTLS_X509EXT_OID_AUTHORITY_KEY_ID "2.5.29.35" #define GNUTLS_X509EXT_OID_EXTENDED_KEY_USAGE "2.5.29.37" #define GNUTLS_X509EXT_OID_INHIBIT_ANYPOLICY "2.5.29.52" #define GNUTLS_X509EXT_OID_AUTHORITY_INFO_ACCESS "1.3.6.1.5.5.7.1.1" #define GNUTLS_X509EXT_OID_PROXY_CRT_INFO "1.3.6.1.5.5.7.1.14" #define GNUTLS_X509EXT_OID_TLSFEATURES "1.3.6.1.5.5.7.1.24" #define GNUTLS_X509EXT_OID_CT_SCT_V1 "1.3.6.1.4.1.11129.2.4.2" #define GNUTLS_X509_OID_POLICY_ANY "2.5.29.54" /* Certificate handling functions. */ /** * gnutls_certificate_import_flags: * @GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED: Fail if the * certificates in the buffer are more than the space allocated for * certificates. The error code will be %GNUTLS_E_SHORT_MEMORY_BUFFER. * @GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED: Fail if the certificates * in the buffer are not ordered starting from subject to issuer. * The error code will be %GNUTLS_E_CERTIFICATE_LIST_UNSORTED. * @GNUTLS_X509_CRT_LIST_SORT: Sort the certificate chain if unsorted. * * Enumeration of different certificate import flags. */ typedef enum gnutls_certificate_import_flags { GNUTLS_X509_CRT_LIST_IMPORT_FAIL_IF_EXCEED = 1, GNUTLS_X509_CRT_LIST_FAIL_IF_UNSORTED = 1<<1, GNUTLS_X509_CRT_LIST_SORT = 1<<2 } gnutls_certificate_import_flags; int gnutls_x509_crt_init(gnutls_x509_crt_t * cert); void gnutls_x509_crt_deinit(gnutls_x509_crt_t cert); /** * gnutls_certificate_import_flags: * @GNUTLS_X509_CRT_FLAG_IGNORE_SANITY: Ignore any sanity checks at the * import of the certificate; i.e., ignore checks such as version/field * matching and strict time field checks. Intended to be used for debugging. * * Enumeration of different certificate flags. */ typedef enum gnutls_x509_crt_flags { GNUTLS_X509_CRT_FLAG_IGNORE_SANITY = 1 } gnutls_x509_crt_flags; void gnutls_x509_crt_set_flags(gnutls_x509_crt_t cert, unsigned flags); unsigned gnutls_x509_crt_equals(gnutls_x509_crt_t cert1, gnutls_x509_crt_t cert2); unsigned gnutls_x509_crt_equals2(gnutls_x509_crt_t cert1, const gnutls_datum_t * der); int gnutls_x509_crt_import(gnutls_x509_crt_t cert, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_crt_list_import2(gnutls_x509_crt_t ** certs, unsigned int *size, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_x509_crt_list_import(gnutls_x509_crt_t * certs, unsigned int *cert_max, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_x509_crt_import_url(gnutls_x509_crt_t crt, const char *url, unsigned int flags /* GNUTLS_PKCS11_OBJ_FLAG_* */ ); int gnutls_x509_crt_list_import_url(gnutls_x509_crt_t **certs, unsigned int *size, const char *url, gnutls_pin_callback_t pin_fn, void *pin_fn_userdata, unsigned int flags); int gnutls_x509_crt_export(gnutls_x509_crt_t cert, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_crt_export2(gnutls_x509_crt_t cert, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_crt_get_private_key_usage_period(gnutls_x509_crt_t cert, time_t * activation, time_t * expiration, unsigned int *critical); int gnutls_x509_crt_get_issuer_dn(gnutls_x509_crt_t cert, char *buf, size_t * buf_size); int gnutls_x509_crt_get_issuer_dn2(gnutls_x509_crt_t cert, gnutls_datum_t * dn); int gnutls_x509_crt_get_issuer_dn3(gnutls_x509_crt_t cert, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crt_get_issuer_dn_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size); int gnutls_x509_crt_get_issuer_dn_by_oid(gnutls_x509_crt_t cert, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * buf_size); int gnutls_x509_crt_get_dn(gnutls_x509_crt_t cert, char *buf, size_t * buf_size); int gnutls_x509_crt_get_dn2(gnutls_x509_crt_t cert, gnutls_datum_t * dn); int gnutls_x509_crt_get_dn3(gnutls_x509_crt_t cert, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crt_get_dn_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size); int gnutls_x509_crt_get_dn_by_oid(gnutls_x509_crt_t cert, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * buf_size); unsigned gnutls_x509_crt_check_hostname(gnutls_x509_crt_t cert, const char *hostname); unsigned gnutls_x509_crt_check_hostname2(gnutls_x509_crt_t cert, const char *hostname, unsigned int flags); unsigned gnutls_x509_crt_check_email(gnutls_x509_crt_t cert, const char *email, unsigned int flags); unsigned gnutls_x509_crt_check_ip(gnutls_x509_crt_t cert, const unsigned char *ip, unsigned int ip_size, unsigned int flags); int gnutls_x509_crt_get_signature_algorithm(gnutls_x509_crt_t cert); int gnutls_x509_crt_get_signature(gnutls_x509_crt_t cert, char *sig, size_t * sizeof_sig); int gnutls_x509_crt_get_version(gnutls_x509_crt_t cert); int gnutls_x509_crt_get_pk_oid(gnutls_x509_crt_t cert, char *oid, size_t *oid_size); int gnutls_x509_crt_get_signature_oid(gnutls_x509_crt_t cert, char *oid, size_t *oid_size); /** * gnutls_keyid_flags_t: * @GNUTLS_KEYID_USE_SHA1: Use SHA1 as the key ID algorithm (default). * @GNUTLS_KEYID_USE_SHA256: Use SHA256 as the key ID algorithm. * @GNUTLS_KEYID_USE_SHA512: Use SHA512 as the key ID algorithm. * @GNUTLS_KEYID_USE_BEST_KNOWN: Use the best known algorithm to calculate key ID. Using that option will make your program behavior depend on the version of gnutls linked with. That option has a cap of 64-bytes key IDs. * * Enumeration of different flags for the key ID functions. */ typedef enum { GNUTLS_KEYID_USE_SHA1 = 0, GNUTLS_KEYID_USE_SHA256 = (1<<0), GNUTLS_KEYID_USE_SHA512 = (1<<1), GNUTLS_KEYID_USE_BEST_KNOWN = (1<<30) } gnutls_keyid_flags_t; int gnutls_x509_crt_get_key_id(gnutls_x509_crt_t crt, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_x509_crt_set_private_key_usage_period(gnutls_x509_crt_t crt, time_t activation, time_t expiration); int gnutls_x509_crt_set_authority_key_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_get_authority_key_id(gnutls_x509_crt_t cert, void *id, size_t * id_size, unsigned int *critical); int gnutls_x509_crt_get_authority_key_gn_serial(gnutls_x509_crt_t cert, unsigned int seq, void *alt, size_t * alt_size, unsigned int *alt_type, void *serial, size_t * serial_size, unsigned int *critical); int gnutls_x509_crt_get_subject_key_id(gnutls_x509_crt_t cert, void *ret, size_t * ret_size, unsigned int *critical); int gnutls_x509_crt_get_subject_unique_id(gnutls_x509_crt_t crt, char *buf, size_t * buf_size); int gnutls_x509_crt_get_issuer_unique_id(gnutls_x509_crt_t crt, char *buf, size_t * buf_size); void gnutls_x509_crt_set_pin_function(gnutls_x509_crt_t crt, gnutls_pin_callback_t fn, void *userdata); /** * gnutls_info_access_what_t: * @GNUTLS_IA_ACCESSMETHOD_OID: Get accessMethod OID. * @GNUTLS_IA_ACCESSLOCATION_GENERALNAME_TYPE: Get accessLocation name type. * @GNUTLS_IA_URI: Get accessLocation URI value. * @GNUTLS_IA_OCSP_URI: get accessLocation URI value for OCSP. * @GNUTLS_IA_CAISSUERS_URI: get accessLocation URI value for caIssuers. * * Enumeration of types for the @what parameter of * gnutls_x509_crt_get_authority_info_access(). */ typedef enum gnutls_info_access_what_t { GNUTLS_IA_ACCESSMETHOD_OID = 1, GNUTLS_IA_ACCESSLOCATION_GENERALNAME_TYPE = 2, /* use 100-108 for the generalName types, populate as needed */ GNUTLS_IA_URI = 106, /* quick-access variants that match both OID and name type. */ GNUTLS_IA_UNKNOWN = 10000, GNUTLS_IA_OCSP_URI = 10006, GNUTLS_IA_CAISSUERS_URI = 10106 } gnutls_info_access_what_t; int gnutls_x509_crt_get_authority_info_access(gnutls_x509_crt_t crt, unsigned int seq, int what, gnutls_datum_t * data, unsigned int *critical); typedef struct gnutls_name_constraints_st *gnutls_x509_name_constraints_t; unsigned gnutls_x509_name_constraints_check(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t * name); unsigned gnutls_x509_name_constraints_check_crt(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, gnutls_x509_crt_t crt); int gnutls_x509_name_constraints_init(gnutls_x509_name_constraints_t *nc); void gnutls_x509_name_constraints_deinit(gnutls_x509_name_constraints_t nc); #define GNUTLS_EXT_FLAG_APPEND 1 #define GNUTLS_NAME_CONSTRAINTS_FLAG_APPEND GNUTLS_EXT_FLAG_APPEND int gnutls_x509_crt_get_name_constraints(gnutls_x509_crt_t crt, gnutls_x509_name_constraints_t nc, unsigned int flags, unsigned int *critical); int gnutls_x509_name_constraints_add_permitted(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t * name); int gnutls_x509_name_constraints_add_excluded(gnutls_x509_name_constraints_t nc, gnutls_x509_subject_alt_name_t type, const gnutls_datum_t * name); int gnutls_x509_crt_set_name_constraints(gnutls_x509_crt_t crt, gnutls_x509_name_constraints_t nc, unsigned int critical); int gnutls_x509_name_constraints_get_permitted(gnutls_x509_name_constraints_t nc, unsigned idx, unsigned *type, gnutls_datum_t * name); int gnutls_x509_name_constraints_get_excluded(gnutls_x509_name_constraints_t nc, unsigned idx, unsigned *type, gnutls_datum_t * name); int gnutls_x509_cidr_to_rfc5280(const char *cidr, gnutls_datum_t *cidr_rfc5280); #define GNUTLS_CRL_REASON_SUPERSEEDED GNUTLS_CRL_REASON_SUPERSEDED, /** * gnutls_x509_crl_reason_flags_t: * @GNUTLS_CRL_REASON_PRIVILEGE_WITHDRAWN: The privileges were withdrawn from the owner. * @GNUTLS_CRL_REASON_CERTIFICATE_HOLD: The certificate is on hold. * @GNUTLS_CRL_REASON_CESSATION_OF_OPERATION: The end-entity is no longer operating. * @GNUTLS_CRL_REASON_SUPERSEDED: There is a newer certificate of the owner. * @GNUTLS_CRL_REASON_AFFILIATION_CHANGED: The end-entity affiliation has changed. * @GNUTLS_CRL_REASON_CA_COMPROMISE: The CA was compromised. * @GNUTLS_CRL_REASON_KEY_COMPROMISE: The certificate's key was compromised. * @GNUTLS_CRL_REASON_UNUSED: The key was never used. * @GNUTLS_CRL_REASON_AA_COMPROMISE: AA compromised. * * Enumeration of types for the CRL revocation reasons. */ typedef enum gnutls_x509_crl_reason_flags_t { GNUTLS_CRL_REASON_UNSPECIFIED = 0, GNUTLS_CRL_REASON_PRIVILEGE_WITHDRAWN = 1, GNUTLS_CRL_REASON_CERTIFICATE_HOLD = 2, GNUTLS_CRL_REASON_CESSATION_OF_OPERATION = 4, GNUTLS_CRL_REASON_SUPERSEDED = 8, GNUTLS_CRL_REASON_AFFILIATION_CHANGED = 16, GNUTLS_CRL_REASON_CA_COMPROMISE = 32, GNUTLS_CRL_REASON_KEY_COMPROMISE = 64, GNUTLS_CRL_REASON_UNUSED = 128, GNUTLS_CRL_REASON_AA_COMPROMISE = 32768 } gnutls_x509_crl_reason_flags_t; int gnutls_x509_crt_get_crl_dist_points(gnutls_x509_crt_t cert, unsigned int seq, void *ret, size_t * ret_size, unsigned int *reason_flags, unsigned int *critical); int gnutls_x509_crt_set_crl_dist_points2(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data, unsigned int data_size, unsigned int reason_flags); int gnutls_x509_crt_set_crl_dist_points(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data_string, unsigned int reason_flags); int gnutls_x509_crt_cpy_crl_dist_points(gnutls_x509_crt_t dst, gnutls_x509_crt_t src); int gnutls_x509_crl_sign(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key); int gnutls_x509_crl_sign2(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); time_t gnutls_x509_crt_get_activation_time(gnutls_x509_crt_t cert); /* This macro is deprecated and defunc; do not use */ #define GNUTLS_X509_NO_WELL_DEFINED_EXPIRATION ((time_t)4294197631) time_t gnutls_x509_crt_get_expiration_time(gnutls_x509_crt_t cert); int gnutls_x509_crt_get_serial(gnutls_x509_crt_t cert, void *result, size_t * result_size); typedef struct gnutls_x509_spki_st *gnutls_x509_spki_t; int gnutls_x509_spki_init(gnutls_x509_spki_t *spki); void gnutls_x509_spki_deinit(gnutls_x509_spki_t spki); int gnutls_x509_spki_get_rsa_pss_params(gnutls_x509_spki_t spki, gnutls_digest_algorithm_t *dig, unsigned int *salt_size); void gnutls_x509_spki_set_rsa_pss_params(gnutls_x509_spki_t spki, gnutls_digest_algorithm_t dig, unsigned int salt_size); int gnutls_x509_crt_get_pk_algorithm(gnutls_x509_crt_t cert, unsigned int *bits); int gnutls_x509_crt_set_spki(gnutls_x509_crt_t crt, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crt_get_spki(gnutls_x509_crt_t cert, gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crt_get_pk_rsa_raw(gnutls_x509_crt_t crt, gnutls_datum_t * m, gnutls_datum_t * e); int gnutls_x509_crt_get_pk_dsa_raw(gnutls_x509_crt_t crt, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y); int gnutls_x509_crt_get_pk_ecc_raw(gnutls_x509_crt_t crt, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y); int gnutls_x509_crt_get_pk_gost_raw(gnutls_x509_crt_t crt, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t *paramset, gnutls_datum_t * x, gnutls_datum_t * y); int gnutls_x509_crt_get_subject_alt_name(gnutls_x509_crt_t cert, unsigned int seq, void *san, size_t * san_size, unsigned int *critical); int gnutls_x509_crt_get_subject_alt_name2(gnutls_x509_crt_t cert, unsigned int seq, void *san, size_t * san_size, unsigned int *san_type, unsigned int *critical); int gnutls_x509_crt_get_subject_alt_othername_oid(gnutls_x509_crt_t cert, unsigned int seq, void *oid, size_t * oid_size); int gnutls_x509_crt_get_issuer_alt_name(gnutls_x509_crt_t cert, unsigned int seq, void *ian, size_t * ian_size, unsigned int *critical); int gnutls_x509_crt_get_issuer_alt_name2(gnutls_x509_crt_t cert, unsigned int seq, void *ian, size_t * ian_size, unsigned int *ian_type, unsigned int *critical); int gnutls_x509_crt_get_issuer_alt_othername_oid(gnutls_x509_crt_t cert, unsigned int seq, void *ret, size_t * ret_size); int gnutls_x509_crt_get_ca_status(gnutls_x509_crt_t cert, unsigned int *critical); int gnutls_x509_crt_get_basic_constraints(gnutls_x509_crt_t cert, unsigned int *critical, unsigned int *ca, int *pathlen); /* The key_usage flags are defined in gnutls.h. They are the * GNUTLS_KEY_* definitions. */ int gnutls_x509_crt_get_key_usage(gnutls_x509_crt_t cert, unsigned int *key_usage, unsigned int *critical); int gnutls_x509_crt_set_key_usage(gnutls_x509_crt_t crt, unsigned int usage); int gnutls_x509_crt_set_authority_info_access(gnutls_x509_crt_t crt, int what, gnutls_datum_t * data); int gnutls_x509_crt_get_inhibit_anypolicy(gnutls_x509_crt_t cert, unsigned int *skipcerts, unsigned int *critical); int gnutls_x509_crt_set_inhibit_anypolicy(gnutls_x509_crt_t crt, unsigned int skipcerts); int gnutls_x509_crt_get_proxy(gnutls_x509_crt_t cert, unsigned int *critical, int *pathlen, char **policyLanguage, char **policy, size_t * sizeof_policy); typedef struct gnutls_x509_tlsfeatures_st *gnutls_x509_tlsfeatures_t; int gnutls_x509_tlsfeatures_init(gnutls_x509_tlsfeatures_t *features); void gnutls_x509_tlsfeatures_deinit(gnutls_x509_tlsfeatures_t); int gnutls_x509_tlsfeatures_get(gnutls_x509_tlsfeatures_t f, unsigned idx, unsigned int *feature); int gnutls_x509_crt_set_tlsfeatures(gnutls_x509_crt_t crt, gnutls_x509_tlsfeatures_t features); int gnutls_x509_crt_get_tlsfeatures(gnutls_x509_crt_t cert, gnutls_x509_tlsfeatures_t features, unsigned int flags, unsigned int *critical); unsigned gnutls_x509_tlsfeatures_check_crt(gnutls_x509_tlsfeatures_t feat, gnutls_x509_crt_t crt); #define GNUTLS_MAX_QUALIFIERS 8 /** * gnutls_x509_qualifier_t: * @GNUTLS_X509_QUALIFIER_UNKNOWN: Unknown qualifier. * @GNUTLS_X509_QUALIFIER_URI: A URL * @GNUTLS_X509_QUALIFIER_NOICE: A text notice. * * Enumeration of types for the X.509 qualifiers, of the certificate policy extension. */ typedef enum gnutls_x509_qualifier_t { GNUTLS_X509_QUALIFIER_UNKNOWN = 0, GNUTLS_X509_QUALIFIER_URI, GNUTLS_X509_QUALIFIER_NOTICE } gnutls_x509_qualifier_t; typedef struct gnutls_x509_policy_st { char *oid; unsigned int qualifiers; struct { gnutls_x509_qualifier_t type; char *data; unsigned int size; } qualifier[GNUTLS_MAX_QUALIFIERS]; } gnutls_x509_policy_st; void gnutls_x509_policy_release(struct gnutls_x509_policy_st *policy); int gnutls_x509_crt_get_policy(gnutls_x509_crt_t crt, unsigned indx, struct gnutls_x509_policy_st *policy, unsigned int *critical); int gnutls_x509_crt_set_policy(gnutls_x509_crt_t crt, const struct gnutls_x509_policy_st *policy, unsigned int critical); int gnutls_x509_dn_oid_known(const char *oid); #define GNUTLS_X509_DN_OID_RETURN_OID 1 const char *gnutls_x509_dn_oid_name(const char *oid, unsigned int flags); /* Read extensions by OID. */ int gnutls_x509_crt_get_extension_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size); int gnutls_x509_crt_get_extension_by_oid(gnutls_x509_crt_t cert, const char *oid, unsigned indx, void *buf, size_t * buf_size, unsigned int *critical); int gnutls_x509_crq_get_signature_algorithm(gnutls_x509_crq_t crq); int gnutls_x509_crq_get_extension_by_oid2(gnutls_x509_crq_t crq, const char *oid, unsigned indx, gnutls_datum_t *output, unsigned int *critical); /* Read extensions by sequence number. */ int gnutls_x509_crt_get_extension_info(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size, unsigned int *critical); int gnutls_x509_crt_get_extension_data(gnutls_x509_crt_t cert, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crt_get_extension_data2(gnutls_x509_crt_t cert, unsigned indx, gnutls_datum_t * data); int gnutls_x509_crt_set_extension_by_oid(gnutls_x509_crt_t crt, const char *oid, const void *buf, size_t sizeof_buf, unsigned int critical); /* X.509 Certificate writing. */ int gnutls_x509_crt_set_dn(gnutls_x509_crt_t crt, const char *dn, const char **err); int gnutls_x509_crt_set_dn_by_oid(gnutls_x509_crt_t crt, const char *oid, unsigned int raw_flag, const void *name, unsigned int sizeof_name); int gnutls_x509_crt_set_issuer_dn_by_oid(gnutls_x509_crt_t crt, const char *oid, unsigned int raw_flag, const void *name, unsigned int sizeof_name); int gnutls_x509_crt_set_issuer_dn(gnutls_x509_crt_t crt, const char *dn, const char **err); int gnutls_x509_crt_set_version(gnutls_x509_crt_t crt, unsigned int version); int gnutls_x509_crt_set_key(gnutls_x509_crt_t crt, gnutls_x509_privkey_t key); int gnutls_x509_crt_set_ca_status(gnutls_x509_crt_t crt, unsigned int ca); int gnutls_x509_crt_set_basic_constraints(gnutls_x509_crt_t crt, unsigned int ca, int pathLenConstraint); int gnutls_x509_crt_set_subject_unique_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_set_issuer_unique_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_set_subject_alternative_name(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const char *data_string); int gnutls_x509_crt_set_subject_alt_name(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_set_subject_alt_othername(gnutls_x509_crt_t crt, const char *oid, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_set_issuer_alt_name(gnutls_x509_crt_t crt, gnutls_x509_subject_alt_name_t type, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_set_issuer_alt_othername(gnutls_x509_crt_t crt, const char *oid, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crt_sign(gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key); int gnutls_x509_crt_sign2(gnutls_x509_crt_t crt, gnutls_x509_crt_t issuer, gnutls_x509_privkey_t issuer_key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crt_set_activation_time(gnutls_x509_crt_t cert, time_t act_time); int gnutls_x509_crt_set_expiration_time(gnutls_x509_crt_t cert, time_t exp_time); int gnutls_x509_crt_set_serial(gnutls_x509_crt_t cert, const void *serial, size_t serial_size); int gnutls_x509_crt_set_subject_key_id(gnutls_x509_crt_t cert, const void *id, size_t id_size); int gnutls_x509_crt_set_proxy_dn(gnutls_x509_crt_t crt, gnutls_x509_crt_t eecrt, unsigned int raw_flag, const void *name, unsigned int sizeof_name); int gnutls_x509_crt_set_proxy(gnutls_x509_crt_t crt, int pathLenConstraint, const char *policyLanguage, const char *policy, size_t sizeof_policy); int gnutls_x509_crt_print(gnutls_x509_crt_t cert, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); int gnutls_x509_crl_print(gnutls_x509_crl_t crl, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); /* Access to internal Certificate fields. */ int gnutls_x509_crt_get_raw_issuer_dn(gnutls_x509_crt_t cert, gnutls_datum_t * start); int gnutls_x509_crt_get_raw_dn(gnutls_x509_crt_t cert, gnutls_datum_t * start); /* RDN handling. */ int gnutls_x509_rdn_get(const gnutls_datum_t * idn, char *buf, size_t * sizeof_buf); int gnutls_x509_rdn_get2(const gnutls_datum_t * idn, gnutls_datum_t *str, unsigned flags); int gnutls_x509_rdn_get_oid(const gnutls_datum_t * idn, unsigned indx, void *buf, size_t * sizeof_buf); int gnutls_x509_rdn_get_by_oid(const gnutls_datum_t * idn, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * sizeof_buf); typedef struct gnutls_x509_dn_st *gnutls_x509_dn_t; typedef struct gnutls_x509_ava_st { gnutls_datum_t oid; gnutls_datum_t value; unsigned long value_tag; } gnutls_x509_ava_st; int gnutls_x509_crt_get_subject(gnutls_x509_crt_t cert, gnutls_x509_dn_t * dn); int gnutls_x509_crt_get_issuer(gnutls_x509_crt_t cert, gnutls_x509_dn_t * dn); int gnutls_x509_dn_get_rdn_ava(gnutls_x509_dn_t dn, int irdn, int iava, gnutls_x509_ava_st * ava); int gnutls_x509_dn_get_str(gnutls_x509_dn_t dn, gnutls_datum_t *str); #define GNUTLS_X509_DN_FLAG_COMPAT 1 int gnutls_x509_dn_get_str2(gnutls_x509_dn_t dn, gnutls_datum_t *str, unsigned flags); int gnutls_x509_dn_set_str(gnutls_x509_dn_t dn, const char *str, const char **err); int gnutls_x509_dn_init(gnutls_x509_dn_t * dn); int gnutls_x509_dn_import(gnutls_x509_dn_t dn, const gnutls_datum_t * data); int gnutls_x509_dn_export(gnutls_x509_dn_t dn, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_dn_export2(gnutls_x509_dn_t dn, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); void gnutls_x509_dn_deinit(gnutls_x509_dn_t dn); /* CRL handling functions. */ int gnutls_x509_crl_init(gnutls_x509_crl_t * crl); void gnutls_x509_crl_deinit(gnutls_x509_crl_t crl); int gnutls_x509_crl_import(gnutls_x509_crl_t crl, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_crl_export(gnutls_x509_crl_t crl, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_crl_export2(gnutls_x509_crl_t crl, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_crl_get_raw_issuer_dn(gnutls_x509_crl_t crl, gnutls_datum_t * dn); int gnutls_x509_crl_get_issuer_dn(gnutls_x509_crl_t crl, char *buf, size_t * sizeof_buf); int gnutls_x509_crl_get_issuer_dn2(gnutls_x509_crl_t crl, gnutls_datum_t * dn); int gnutls_x509_crl_get_issuer_dn3(gnutls_x509_crl_t crl, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crl_get_issuer_dn_by_oid(gnutls_x509_crl_t crl, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * sizeof_buf); int gnutls_x509_crl_get_dn_oid(gnutls_x509_crl_t crl, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crl_get_signature_algorithm(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_signature(gnutls_x509_crl_t crl, char *sig, size_t * sizeof_sig); int gnutls_x509_crl_get_version(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_signature_oid(gnutls_x509_crl_t crl, char *oid, size_t *oid_size); time_t gnutls_x509_crl_get_this_update(gnutls_x509_crl_t crl); time_t gnutls_x509_crl_get_next_update(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_crt_count(gnutls_x509_crl_t crl); int gnutls_x509_crl_get_crt_serial(gnutls_x509_crl_t crl, unsigned indx, unsigned char *serial, size_t * serial_size, time_t * t); typedef struct gnutls_x509_crl_iter * gnutls_x509_crl_iter_t; int gnutls_x509_crl_iter_crt_serial(gnutls_x509_crl_t crl, gnutls_x509_crl_iter_t *, unsigned char *serial, size_t * serial_size, time_t * t); void gnutls_x509_crl_iter_deinit(gnutls_x509_crl_iter_t); #define gnutls_x509_crl_get_certificate_count gnutls_x509_crl_get_crt_count #define gnutls_x509_crl_get_certificate gnutls_x509_crl_get_crt_serial unsigned gnutls_x509_crl_check_issuer(gnutls_x509_crl_t crl, gnutls_x509_crt_t issuer); int gnutls_x509_crl_list_import2(gnutls_x509_crl_t ** crls, unsigned int *size, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); int gnutls_x509_crl_list_import(gnutls_x509_crl_t * crls, unsigned int *crl_max, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int flags); /* CRL writing. */ int gnutls_x509_crl_set_version(gnutls_x509_crl_t crl, unsigned int version); int gnutls_x509_crl_set_this_update(gnutls_x509_crl_t crl, time_t act_time); int gnutls_x509_crl_set_next_update(gnutls_x509_crl_t crl, time_t exp_time); int gnutls_x509_crl_set_crt_serial(gnutls_x509_crl_t crl, const void *serial, size_t serial_size, time_t revocation_time); int gnutls_x509_crl_set_crt(gnutls_x509_crl_t crl, gnutls_x509_crt_t crt, time_t revocation_time); int gnutls_x509_crl_get_authority_key_id(gnutls_x509_crl_t crl, void *id, size_t * id_size, unsigned int *critical); int gnutls_x509_crl_get_authority_key_gn_serial(gnutls_x509_crl_t crl, unsigned int seq, void *alt, size_t * alt_size, unsigned int *alt_type, void *serial, size_t * serial_size, unsigned int *critical); int gnutls_x509_crl_get_number(gnutls_x509_crl_t crl, void *ret, size_t * ret_size, unsigned int *critical); int gnutls_x509_crl_get_extension_oid(gnutls_x509_crl_t crl, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crl_get_extension_info(gnutls_x509_crl_t crl, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical); int gnutls_x509_crl_get_extension_data(gnutls_x509_crl_t crl, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crl_get_extension_data2(gnutls_x509_crl_t crl, unsigned indx, gnutls_datum_t * data); int gnutls_x509_crl_set_authority_key_id(gnutls_x509_crl_t crl, const void *id, size_t id_size); int gnutls_x509_crl_set_number(gnutls_x509_crl_t crl, const void *nr, size_t nr_size); /* X.509 Certificate verification functions. */ /** * gnutls_certificate_verify_flags: * @GNUTLS_VERIFY_DISABLE_CA_SIGN: If set a signer does not have to be * a certificate authority. This flag should normally be disabled, * unless you know what this means. * @GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS: If set a signer in the trusted * list is never checked for expiration or activation. * @GNUTLS_VERIFY_DO_NOT_ALLOW_X509_V1_CA_CRT: Do not allow trusted CA * certificates that have version 1. This option is to be used * to deprecate all certificates of version 1. * @GNUTLS_VERIFY_DO_NOT_ALLOW_SAME: If a certificate is not signed by * anyone trusted but exists in the trusted CA list do not treat it * as trusted. * @GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN: A certificate chain is tolerated * if unsorted (the case with many TLS servers out there). This is the * default since GnuTLS 3.1.4. * @GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN: Do not tolerate an unsorted * certificate chain. * @GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT: Allow CA certificates that * have version 1 (both root and intermediate). This might be * dangerous since those haven't the basicConstraints * extension. * @GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2: Allow certificates to be signed * using the broken MD2 algorithm. * @GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5: Allow certificates to be signed * using the broken MD5 algorithm. * @GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1: Allow certificates to be signed * using the broken SHA1 hash algorithm. * @GNUTLS_VERIFY_ALLOW_BROKEN: Allow certificates to be signed * using any broken algorithm. * @GNUTLS_VERIFY_DISABLE_TIME_CHECKS: Disable checking of activation * and expiration validity periods of certificate chains. Don't set * this unless you understand the security implications. * @GNUTLS_VERIFY_DISABLE_CRL_CHECKS: Disable checking for validity * using certificate revocation lists or the available OCSP data. * @GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS: When including a hostname * check in the verification, do not consider any wildcards. * @GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES: When verifying a hostname * prevent textual IP addresses from matching IP addresses in the * certificate. Treat the input only as a DNS name. * @GNUTLS_VERIFY_USE_TLS1_RSA: This indicates that a (raw) RSA signature is provided * as in the TLS 1.0 protocol. Not all functions accept this flag. * @GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS: This signals the verification * process, not to fail on unknown critical extensions. * @GNUTLS_VERIFY_RSA_PSS_FIXED_SALT_LENGTH: Disallow RSA-PSS signatures made * with mismatching salt length with digest length, as mandated in RFC 8446 * 4.2.3. * * Enumeration of different certificate verify flags. Additional * verification profiles can be set using GNUTLS_PROFILE_TO_VFLAGS() * and %gnutls_certificate_verification_profiles_t. */ typedef enum gnutls_certificate_verify_flags { GNUTLS_VERIFY_DISABLE_CA_SIGN = 1 << 0, GNUTLS_VERIFY_DO_NOT_ALLOW_IP_MATCHES = 1<<1, GNUTLS_VERIFY_DO_NOT_ALLOW_SAME = 1 << 2, GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT = 1 << 3, GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2 = 1 << 4, GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5 = 1 << 5, GNUTLS_VERIFY_DISABLE_TIME_CHECKS = 1 << 6, GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS = 1 << 7, GNUTLS_VERIFY_DO_NOT_ALLOW_X509_V1_CA_CRT = 1 << 8, GNUTLS_VERIFY_DISABLE_CRL_CHECKS = 1 << 9, GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN = 1 << 10, GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN = 1 << 11, GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS = 1 << 12, GNUTLS_VERIFY_USE_TLS1_RSA = 1 << 13, GNUTLS_VERIFY_IGNORE_UNKNOWN_CRIT_EXTENSIONS = 1 << 14, GNUTLS_VERIFY_ALLOW_SIGN_WITH_SHA1 = 1 << 15, GNUTLS_VERIFY_RSA_PSS_FIXED_SALT_LENGTH = 1 << 16 /* cannot exceed 2^24 due to GNUTLS_PROFILE_TO_VFLAGS() */ } gnutls_certificate_verify_flags; #define GNUTLS_VERIFY_ALLOW_BROKEN (GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2|GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5) /** * gnutls_certificate_verification_profiles_t: * @GNUTLS_PROFILE_UNKNOWN: An invalid/unknown profile. * @GNUTLS_PROFILE_VERY_WEAK: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_VERY_WEAK (64 bits) * @GNUTLS_PROFILE_LOW: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_LOW (80 bits) * @GNUTLS_PROFILE_LEGACY: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_LEGACY (96 bits) * @GNUTLS_PROFILE_MEDIUM: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_MEDIUM (112 bits) * @GNUTLS_PROFILE_HIGH: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_HIGH (128 bits) * @GNUTLS_PROFILE_ULTRA: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_ULTRA (192 bits) * @GNUTLS_PROFILE_FUTURE: A verification profile that * corresponds to @GNUTLS_SEC_PARAM_FUTURE (256 bits) * @GNUTLS_PROFILE_SUITEB128: A verification profile that * applies the SUITEB128 rules * @GNUTLS_PROFILE_SUITEB192: A verification profile that * applies the SUITEB192 rules * * Enumeration of different certificate verification profiles. */ typedef enum gnutls_certificate_verification_profiles_t { GNUTLS_PROFILE_UNKNOWN = 0, GNUTLS_PROFILE_VERY_WEAK = 1, GNUTLS_PROFILE_LOW = 2, GNUTLS_PROFILE_LEGACY = 4, GNUTLS_PROFILE_MEDIUM = 5, GNUTLS_PROFILE_HIGH = 6, GNUTLS_PROFILE_ULTRA = 7, GNUTLS_PROFILE_FUTURE = 8, GNUTLS_PROFILE_SUITEB128=32, GNUTLS_PROFILE_SUITEB192=33 /*GNUTLS_PROFILE_MAX=255*/ } gnutls_certificate_verification_profiles_t; #define GNUTLS_PROFILE_TO_VFLAGS(x) \ (((unsigned)x)<<24) #define GNUTLS_VFLAGS_PROFILE_MASK (0xff000000) #define GNUTLS_VFLAGS_TO_PROFILE(x) \ ((((unsigned)x)>>24)&0xff) const char * gnutls_certificate_verification_profile_get_name(gnutls_certificate_verification_profiles_t id) __GNUTLS_CONST__; gnutls_certificate_verification_profiles_t gnutls_certificate_verification_profile_get_id(const char *name) __GNUTLS_CONST__; unsigned gnutls_x509_crt_check_issuer(gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer); int gnutls_x509_crt_list_verify(const gnutls_x509_crt_t * cert_list, unsigned cert_list_length, const gnutls_x509_crt_t * CA_list, unsigned CA_list_length, const gnutls_x509_crl_t * CRL_list, unsigned CRL_list_length, unsigned int flags, unsigned int *verify); int gnutls_x509_crt_verify(gnutls_x509_crt_t cert, const gnutls_x509_crt_t * CA_list, unsigned CA_list_length, unsigned int flags, unsigned int *verify); int gnutls_x509_crl_verify(gnutls_x509_crl_t crl, const gnutls_x509_crt_t * CA_list, unsigned CA_list_length, unsigned int flags, unsigned int *verify); int gnutls_x509_crt_verify_data2(gnutls_x509_crt_t crt, gnutls_sign_algorithm_t algo, unsigned int flags, const gnutls_datum_t * data, const gnutls_datum_t * signature); int gnutls_x509_crt_check_revocation(gnutls_x509_crt_t cert, const gnutls_x509_crl_t * crl_list, unsigned crl_list_length); int gnutls_x509_crt_get_fingerprint(gnutls_x509_crt_t cert, gnutls_digest_algorithm_t algo, void *buf, size_t * buf_size); int gnutls_x509_crt_get_key_purpose_oid(gnutls_x509_crt_t cert, unsigned indx, void *oid, size_t * oid_size, unsigned int *critical); int gnutls_x509_crt_set_key_purpose_oid(gnutls_x509_crt_t cert, const void *oid, unsigned int critical); unsigned gnutls_x509_crt_check_key_purpose(gnutls_x509_crt_t cert, const char *purpose, unsigned flags); /* Private key handling. */ /* Flags for the gnutls_x509_privkey_export_pkcs8() function. */ #define GNUTLS_PKCS8_PLAIN GNUTLS_PKCS_PLAIN #define GNUTLS_PKCS8_USE_PKCS12_3DES GNUTLS_PKCS_PKCS12_3DES #define GNUTLS_PKCS8_USE_PKCS12_ARCFOUR GNUTLS_PKCS_PKCS12_ARCFOUR #define GNUTLS_PKCS8_USE_PKCS12_RC2_40 GNUTLS_PKCS_PKCS12_RC2_40 /** * gnutls_pkcs_encrypt_flags_t: * @GNUTLS_PKCS_PLAIN: Unencrypted private key. * @GNUTLS_PKCS_NULL_PASSWORD: Some schemas distinguish between an empty and a NULL password. * @GNUTLS_PKCS_PKCS12_3DES: PKCS-12 3DES. * @GNUTLS_PKCS_PKCS12_ARCFOUR: PKCS-12 ARCFOUR. * @GNUTLS_PKCS_PKCS12_RC2_40: PKCS-12 RC2-40. * @GNUTLS_PKCS_PBES2_3DES: PBES2 3DES. * @GNUTLS_PKCS_PBES2_AES_128: PBES2 AES-128. * @GNUTLS_PKCS_PBES2_AES_192: PBES2 AES-192. * @GNUTLS_PKCS_PBES2_AES_256: PBES2 AES-256. * @GNUTLS_PKCS_PBES2_DES: PBES2 single DES. * @GNUTLS_PKCS_PBES1_DES_MD5: PBES1 with single DES; for compatibility with openssl only. * @GNUTLS_PKCS_PBES2_GOST_TC26Z: PBES2 GOST 28147-89 CFB with TC26-Z S-box. * @GNUTLS_PKCS_PBES2_GOST_CPA: PBES2 GOST 28147-89 CFB with CryptoPro-A S-box. * @GNUTLS_PKCS_PBES2_GOST_CPB: PBES2 GOST 28147-89 CFB with CryptoPro-B S-box. * @GNUTLS_PKCS_PBES2_GOST_CPC: PBES2 GOST 28147-89 CFB with CryptoPro-C S-box. * @GNUTLS_PKCS_PBES2_GOST_CPD: PBES2 GOST 28147-89 CFB with CryptoPro-D S-box. * * Enumeration of different PKCS encryption flags. */ typedef enum gnutls_pkcs_encrypt_flags_t { GNUTLS_PKCS_PLAIN = 1, GNUTLS_PKCS_PKCS12_3DES = 1<<1, GNUTLS_PKCS_PKCS12_ARCFOUR = 1<<2, GNUTLS_PKCS_PKCS12_RC2_40 = 1<<3, GNUTLS_PKCS_PBES2_3DES = 1<<4, GNUTLS_PKCS_PBES2_AES_128 = 1<<5, GNUTLS_PKCS_PBES2_AES_192 = 1<<6, GNUTLS_PKCS_PBES2_AES_256 = 1<<7, GNUTLS_PKCS_NULL_PASSWORD = 1<<8, GNUTLS_PKCS_PBES2_DES = 1<<9, GNUTLS_PKCS_PBES1_DES_MD5 = 1<<10, GNUTLS_PKCS_PBES2_GOST_TC26Z = 1<<11, GNUTLS_PKCS_PBES2_GOST_CPA = 1<<12, GNUTLS_PKCS_PBES2_GOST_CPB = 1<<13, GNUTLS_PKCS_PBES2_GOST_CPC = 1<<14, GNUTLS_PKCS_PBES2_GOST_CPD = 1<<15 } gnutls_pkcs_encrypt_flags_t; #define GNUTLS_PKCS_CIPHER_MASK(x) ((x)&(~(GNUTLS_PKCS_NULL_PASSWORD))) #define GNUTLS_PKCS_USE_PKCS12_3DES GNUTLS_PKCS_PKCS12_3DES #define GNUTLS_PKCS_USE_PKCS12_ARCFOUR GNUTLS_PKCS_PKCS12_ARCFOUR #define GNUTLS_PKCS_USE_PKCS12_RC2_40 GNUTLS_PKCS_PKCS12_RC2_40 #define GNUTLS_PKCS_USE_PBES2_3DES GNUTLS_PKCS_PBES2_3DES #define GNUTLS_PKCS_USE_PBES2_AES_128 GNUTLS_PKCS_PBES2_AES_128 #define GNUTLS_PKCS_USE_PBES2_AES_192 GNUTLS_PKCS_PBES2_AES_192 #define GNUTLS_PKCS_USE_PBES2_AES_256 GNUTLS_PKCS_PBES2_AES_256 #define GNUTLS_PKCS_USE_PBES2_GOST_TC26Z GNUTLS_PKCS_PBES2_GOST_TC26Z #define GNUTLS_PKCS_USE_PBES2_GOST_CPA GNUTLS_PKCS_PBES2_GOST_CPA #define GNUTLS_PKCS_USE_PBES2_GOST_CPB GNUTLS_PKCS_PBES2_GOST_CPB #define GNUTLS_PKCS_USE_PBES2_GOST_CPC GNUTLS_PKCS_PBES2_GOST_CPC #define GNUTLS_PKCS_USE_PBES2_GOST_CPD GNUTLS_PKCS_PBES2_GOST_CPD const char *gnutls_pkcs_schema_get_name(unsigned int schema); const char *gnutls_pkcs_schema_get_oid(unsigned int schema); int gnutls_x509_privkey_init(gnutls_x509_privkey_t * key); void gnutls_x509_privkey_deinit(gnutls_x509_privkey_t key); gnutls_sec_param_t gnutls_x509_privkey_sec_param(gnutls_x509_privkey_t key); void gnutls_x509_privkey_set_pin_function(gnutls_x509_privkey_t key, gnutls_pin_callback_t fn, void *userdata); int gnutls_x509_privkey_cpy(gnutls_x509_privkey_t dst, gnutls_x509_privkey_t src); int gnutls_x509_privkey_import(gnutls_x509_privkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_privkey_import_pkcs8(gnutls_x509_privkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags); int gnutls_x509_privkey_import_openssl(gnutls_x509_privkey_t key, const gnutls_datum_t * data, const char *password); int gnutls_pkcs8_info(const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, unsigned int *schema, unsigned int *cipher, void *salt, unsigned int *salt_size, unsigned int *iter_count, char **oid); int gnutls_x509_privkey_import2(gnutls_x509_privkey_t key, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags); int gnutls_x509_privkey_import_rsa_raw(gnutls_x509_privkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e, const gnutls_datum_t * d, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * u); int gnutls_x509_privkey_import_rsa_raw2(gnutls_x509_privkey_t key, const gnutls_datum_t * m, const gnutls_datum_t * e, const gnutls_datum_t * d, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * u, const gnutls_datum_t * e1, const gnutls_datum_t * e2); int gnutls_x509_privkey_import_ecc_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t curve, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_x509_privkey_import_gost_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t curve, gnutls_digest_algorithm_t digest, gnutls_gost_paramset_t paramset, const gnutls_datum_t * x, const gnutls_datum_t * y, const gnutls_datum_t * k); int gnutls_x509_privkey_fix(gnutls_x509_privkey_t key); int gnutls_x509_privkey_export_dsa_raw(gnutls_x509_privkey_t key, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g, gnutls_datum_t * y, gnutls_datum_t * x); int gnutls_x509_privkey_import_dsa_raw(gnutls_x509_privkey_t key, const gnutls_datum_t * p, const gnutls_datum_t * q, const gnutls_datum_t * g, const gnutls_datum_t * y, const gnutls_datum_t * x); int gnutls_x509_privkey_get_pk_algorithm(gnutls_x509_privkey_t key); int gnutls_x509_privkey_get_pk_algorithm2(gnutls_x509_privkey_t key, unsigned int *bits); int gnutls_x509_privkey_get_spki(gnutls_x509_privkey_t key, gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_privkey_set_spki(gnutls_x509_privkey_t key, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_privkey_get_key_id(gnutls_x509_privkey_t key, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_x509_privkey_generate(gnutls_x509_privkey_t key, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags); void gnutls_x509_privkey_set_flags(gnutls_x509_privkey_t key, unsigned int flags); /** * gnutls_keygen_types_t: * @GNUTLS_KEYGEN_SEED: Specifies the seed to be used in key generation. * @GNUTLS_KEYGEN_DIGEST: The size field specifies the hash algorithm to be used in key generation. * @GNUTLS_KEYGEN_SPKI: data points to a %gnutls_x509_spki_t structure; it is not used after the key generation call. * * Enumeration of different key generation data options. */ typedef enum { GNUTLS_KEYGEN_SEED = 1, GNUTLS_KEYGEN_DIGEST = 2, GNUTLS_KEYGEN_SPKI = 3 } gnutls_keygen_types_t; typedef struct { gnutls_keygen_types_t type; unsigned char *data; unsigned int size; } gnutls_keygen_data_st; int gnutls_x509_privkey_generate2(gnutls_x509_privkey_t key, gnutls_pk_algorithm_t algo, unsigned int bits, unsigned int flags, const gnutls_keygen_data_st *data, unsigned data_size); int gnutls_x509_privkey_verify_seed(gnutls_x509_privkey_t key, gnutls_digest_algorithm_t, const void *seed, size_t seed_size); int gnutls_x509_privkey_get_seed(gnutls_x509_privkey_t key, gnutls_digest_algorithm_t*, void *seed, size_t *seed_size); int gnutls_x509_privkey_verify_params(gnutls_x509_privkey_t key); int gnutls_x509_privkey_export(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_privkey_export2(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_privkey_export_pkcs8(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags, void *output_data, size_t * output_data_size); int gnutls_x509_privkey_export2_pkcs8(gnutls_x509_privkey_t key, gnutls_x509_crt_fmt_t format, const char *password, unsigned int flags, gnutls_datum_t * out); int gnutls_x509_privkey_export_rsa_raw2(gnutls_x509_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u, gnutls_datum_t * e1, gnutls_datum_t * e2); int gnutls_x509_privkey_export_rsa_raw(gnutls_x509_privkey_t key, gnutls_datum_t * m, gnutls_datum_t * e, gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * u); int gnutls_x509_privkey_export_ecc_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k); int gnutls_x509_privkey_export_gost_raw(gnutls_x509_privkey_t key, gnutls_ecc_curve_t * curve, gnutls_digest_algorithm_t * digest, gnutls_gost_paramset_t * paramset, gnutls_datum_t * x, gnutls_datum_t * y, gnutls_datum_t * k); int gnutls_x509_privkey_sign_data(gnutls_x509_privkey_t key, gnutls_digest_algorithm_t digest, unsigned int flags, const gnutls_datum_t * data, void *signature, size_t * signature_size); /* Certificate request stuff. */ int gnutls_x509_crq_sign(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key); int gnutls_x509_crq_sign2(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key, gnutls_digest_algorithm_t dig, unsigned int flags); int gnutls_x509_crq_print(gnutls_x509_crq_t crq, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); int gnutls_x509_crq_verify(gnutls_x509_crq_t crq, unsigned int flags); int gnutls_x509_crq_init(gnutls_x509_crq_t * crq); void gnutls_x509_crq_deinit(gnutls_x509_crq_t crq); int gnutls_x509_crq_import(gnutls_x509_crq_t crq, const gnutls_datum_t * data, gnutls_x509_crt_fmt_t format); int gnutls_x509_crq_get_private_key_usage_period(gnutls_x509_crq_t cert, time_t * activation, time_t * expiration, unsigned int *critical); int gnutls_x509_crq_get_dn(gnutls_x509_crq_t crq, char *buf, size_t * sizeof_buf); int gnutls_x509_crq_get_dn2(gnutls_x509_crq_t crq, gnutls_datum_t * dn); int gnutls_x509_crq_get_dn3(gnutls_x509_crq_t crq, gnutls_datum_t * dn, unsigned flags); int gnutls_x509_crq_get_dn_oid(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crq_get_dn_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, unsigned int raw_flag, void *buf, size_t * sizeof_buf); int gnutls_x509_crq_set_dn(gnutls_x509_crq_t crq, const char *dn, const char **err); int gnutls_x509_crq_set_dn_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned int raw_flag, const void *data, unsigned int sizeof_data); int gnutls_x509_crq_set_version(gnutls_x509_crq_t crq, unsigned int version); int gnutls_x509_crq_get_version(gnutls_x509_crq_t crq); int gnutls_x509_crq_set_key(gnutls_x509_crq_t crq, gnutls_x509_privkey_t key); int gnutls_x509_crq_set_extension_by_oid(gnutls_x509_crq_t crq, const char *oid, const void *buf, size_t sizeof_buf, unsigned int critical); int gnutls_x509_crq_set_challenge_password(gnutls_x509_crq_t crq, const char *pass); int gnutls_x509_crq_get_challenge_password(gnutls_x509_crq_t crq, char *pass, size_t * sizeof_pass); int gnutls_x509_crq_set_attribute_by_oid(gnutls_x509_crq_t crq, const char *oid, void *buf, size_t sizeof_buf); int gnutls_x509_crq_get_attribute_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, void *buf, size_t * sizeof_buf); int gnutls_x509_crq_export(gnutls_x509_crq_t crq, gnutls_x509_crt_fmt_t format, void *output_data, size_t * output_data_size); int gnutls_x509_crq_export2(gnutls_x509_crq_t crq, gnutls_x509_crt_fmt_t format, gnutls_datum_t * out); int gnutls_x509_crt_set_crq(gnutls_x509_crt_t crt, gnutls_x509_crq_t crq); int gnutls_x509_crt_set_crq_extensions(gnutls_x509_crt_t crt, gnutls_x509_crq_t crq); int gnutls_x509_crt_set_crq_extension_by_oid(gnutls_x509_crt_t crt, gnutls_x509_crq_t crq, const char *oid, unsigned flags); int gnutls_x509_crq_set_private_key_usage_period(gnutls_x509_crq_t crq, time_t activation, time_t expiration); int gnutls_x509_crq_set_key_rsa_raw(gnutls_x509_crq_t crq, const gnutls_datum_t * m, const gnutls_datum_t * e); int gnutls_x509_crq_set_subject_alt_name(gnutls_x509_crq_t crq, gnutls_x509_subject_alt_name_t nt, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crq_set_subject_alt_othername(gnutls_x509_crq_t crq, const char *oid, const void *data, unsigned int data_size, unsigned int flags); int gnutls_x509_crq_set_key_usage(gnutls_x509_crq_t crq, unsigned int usage); int gnutls_x509_crq_set_basic_constraints(gnutls_x509_crq_t crq, unsigned int ca, int pathLenConstraint); int gnutls_x509_crq_set_key_purpose_oid(gnutls_x509_crq_t crq, const void *oid, unsigned int critical); int gnutls_x509_crq_get_key_purpose_oid(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical); int gnutls_x509_crq_get_extension_data(gnutls_x509_crq_t crq, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crq_get_extension_data2(gnutls_x509_crq_t crq, unsigned indx, gnutls_datum_t * data); int gnutls_x509_crq_get_extension_info(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid, unsigned int *critical); int gnutls_x509_crq_get_attribute_data(gnutls_x509_crq_t crq, unsigned indx, void *data, size_t * sizeof_data); int gnutls_x509_crq_get_attribute_info(gnutls_x509_crq_t crq, unsigned indx, void *oid, size_t * sizeof_oid); int gnutls_x509_crq_get_pk_algorithm(gnutls_x509_crq_t crq, unsigned int *bits); int gnutls_x509_crq_get_spki(gnutls_x509_crq_t crq, gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crq_set_spki(gnutls_x509_crq_t crq, const gnutls_x509_spki_t spki, unsigned int flags); int gnutls_x509_crq_get_signature_oid(gnutls_x509_crq_t crq, char *oid, size_t *oid_size); int gnutls_x509_crq_get_pk_oid(gnutls_x509_crq_t crq, char *oid, size_t *oid_size); int gnutls_x509_crq_get_key_id(gnutls_x509_crq_t crq, unsigned int flags, unsigned char *output_data, size_t * output_data_size); int gnutls_x509_crq_get_key_rsa_raw(gnutls_x509_crq_t crq, gnutls_datum_t * m, gnutls_datum_t * e); int gnutls_x509_crq_get_key_usage(gnutls_x509_crq_t crq, unsigned int *key_usage, unsigned int *critical); int gnutls_x509_crq_get_basic_constraints(gnutls_x509_crq_t crq, unsigned int *critical, unsigned int *ca, int *pathlen); int gnutls_x509_crq_get_subject_alt_name(gnutls_x509_crq_t crq, unsigned int seq, void *ret, size_t * ret_size, unsigned int *ret_type, unsigned int *critical); int gnutls_x509_crq_get_subject_alt_othername_oid(gnutls_x509_crq_t crq, unsigned int seq, void *ret, size_t * ret_size); int gnutls_x509_crq_get_extension_by_oid(gnutls_x509_crq_t crq, const char *oid, unsigned indx, void *buf, size_t * sizeof_buf, unsigned int *critical); int gnutls_x509_crq_get_tlsfeatures(gnutls_x509_crq_t crq, gnutls_x509_tlsfeatures_t features, unsigned flags, unsigned int *critical); int gnutls_x509_crq_set_tlsfeatures(gnutls_x509_crq_t crq, gnutls_x509_tlsfeatures_t features); int gnutls_x509_crt_get_extension_by_oid2(gnutls_x509_crt_t cert, const char *oid, unsigned indx, gnutls_datum_t *output, unsigned int *critical); typedef struct gnutls_x509_trust_list_st *gnutls_x509_trust_list_t; typedef struct gnutls_x509_trust_list_iter *gnutls_x509_trust_list_iter_t; int gnutls_x509_trust_list_init(gnutls_x509_trust_list_t * list, unsigned int size); void gnutls_x509_trust_list_deinit(gnutls_x509_trust_list_t list, unsigned int all); int gnutls_x509_trust_list_get_issuer(gnutls_x509_trust_list_t list, gnutls_x509_crt_t cert, gnutls_x509_crt_t * issuer, unsigned int flags); int gnutls_x509_trust_list_get_issuer_by_dn(gnutls_x509_trust_list_t list, const gnutls_datum_t *dn, gnutls_x509_crt_t *issuer, unsigned int flags); int gnutls_x509_trust_list_get_issuer_by_subject_key_id(gnutls_x509_trust_list_t list, const gnutls_datum_t *dn, const gnutls_datum_t *spki, gnutls_x509_crt_t *issuer, unsigned int flags); /** * gnutls_trust_list_flags_t: * @GNUTLS_TL_VERIFY_CRL: If any CRLs are provided they will be verified for validity * prior to be added. The CA certificates that will be used for verification are the * ones already added in the trusted list. * @GNUTLS_TL_USE_IN_TLS: Internal flag used by GnuTLS. If provided the trust list * structure will cache a copy of CA DNs to be used in the certificate request * TLS message. * @GNUTLS_TL_NO_DUPLICATES: If this flag is specified, a function adding certificates * will check and eliminate any duplicates. * @GNUTLS_TL_NO_DUPLICATE_KEY: If this flag is specified, a certificate sharing the * same key as a previously added on will not be added. * @GNUTLS_TL_GET_COPY: The semantics of this flag are documented to the functions which * are applicable. In general, on returned value, the function will provide a copy * if this flag is provided, rather than a pointer to internal data. * @GNUTLS_TL_FAIL_ON_INVALID_CRL: If an CRL is added which cannot be validated return * an error instead of ignoring (must be used with %GNUTLS_TL_VERIFY_CRL). * * Enumeration of different certificate trust list flags. */ typedef enum gnutls_trust_list_flags_t { GNUTLS_TL_VERIFY_CRL = 1, #define GNUTLS_TL_VERIFY_CRL 1 GNUTLS_TL_USE_IN_TLS = (1<<1), #define GNUTLS_TL_USE_IN_TLS (1<<1) GNUTLS_TL_NO_DUPLICATES = (1<<2), #define GNUTLS_TL_NO_DUPLICATES (1<<2) GNUTLS_TL_NO_DUPLICATE_KEY = (1<<3), #define GNUTLS_TL_NO_DUPLICATE_KEY (1<<3) GNUTLS_TL_GET_COPY = (1<<4), #define GNUTLS_TL_GET_COPY (1<<4) GNUTLS_TL_FAIL_ON_INVALID_CRL = (1<<5) #define GNUTLS_TL_FAIL_ON_INVALID_CRL (1<<5) } gnutls_trust_list_flags_t; int gnutls_x509_trust_list_add_cas(gnutls_x509_trust_list_t list, const gnutls_x509_crt_t * clist, unsigned clist_size, unsigned int flags); int gnutls_x509_trust_list_remove_cas(gnutls_x509_trust_list_t list, const gnutls_x509_crt_t * clist, unsigned clist_size); int gnutls_x509_trust_list_add_named_crt(gnutls_x509_trust_list_t list, gnutls_x509_crt_t cert, const void *name, size_t name_size, unsigned int flags); int gnutls_x509_trust_list_add_crls(gnutls_x509_trust_list_t list, const gnutls_x509_crl_t * crl_list, unsigned crl_size, unsigned int flags, unsigned int verification_flags); int gnutls_x509_trust_list_iter_get_ca(gnutls_x509_trust_list_t list, gnutls_x509_trust_list_iter_t *iter, gnutls_x509_crt_t *crt); void gnutls_x509_trust_list_iter_deinit(gnutls_x509_trust_list_iter_t iter); typedef int gnutls_verify_output_function(gnutls_x509_crt_t cert, gnutls_x509_crt_t issuer, /* The issuer if verification failed * because of him. might be null. */ gnutls_x509_crl_t crl, /* The CRL that caused verification failure * if any. Might be null. */ unsigned int verification_output); void gnutls_session_set_verify_output_function(gnutls_session_t session, gnutls_verify_output_function * func); int gnutls_x509_trust_list_verify_named_crt (gnutls_x509_trust_list_t list, gnutls_x509_crt_t cert, const void *name, size_t name_size, unsigned int flags, unsigned int *verify, gnutls_verify_output_function func); int gnutls_x509_trust_list_verify_crt2(gnutls_x509_trust_list_t list, gnutls_x509_crt_t * cert_list, unsigned int cert_list_size, gnutls_typed_vdata_st * data, unsigned int elements, unsigned int flags, unsigned int *voutput, gnutls_verify_output_function func); int gnutls_x509_trust_list_verify_crt(gnutls_x509_trust_list_t list, gnutls_x509_crt_t * cert_list, unsigned int cert_list_size, unsigned int flags, unsigned int *verify, gnutls_verify_output_function func); /* trust list convenience functions */ int gnutls_x509_trust_list_add_trust_mem(gnutls_x509_trust_list_t list, const gnutls_datum_t * cas, const gnutls_datum_t * crls, gnutls_x509_crt_fmt_t type, unsigned int tl_flags, unsigned int tl_vflags); int gnutls_x509_trust_list_add_trust_file(gnutls_x509_trust_list_t list, const char *ca_file, const char *crl_file, gnutls_x509_crt_fmt_t type, unsigned int tl_flags, unsigned int tl_vflags); int gnutls_x509_trust_list_add_trust_dir(gnutls_x509_trust_list_t list, const char *ca_dir, const char *crl_dir, gnutls_x509_crt_fmt_t type, unsigned int tl_flags, unsigned int tl_vflags); int gnutls_x509_trust_list_remove_trust_file(gnutls_x509_trust_list_t list, const char *ca_file, gnutls_x509_crt_fmt_t type); int gnutls_x509_trust_list_remove_trust_mem(gnutls_x509_trust_list_t list, const gnutls_datum_t * cas, gnutls_x509_crt_fmt_t type); int gnutls_x509_trust_list_add_system_trust(gnutls_x509_trust_list_t list, unsigned int tl_flags, unsigned int tl_vflags); typedef int gnutls_x509_trust_list_getissuer_function(gnutls_x509_trust_list_t list, const gnutls_x509_crt_t cert, gnutls_x509_crt_t **issuers, unsigned int *issuers_size); void gnutls_x509_trust_list_set_getissuer_function(gnutls_x509_trust_list_t tlist, gnutls_x509_trust_list_getissuer_function *func); void gnutls_x509_trust_list_set_ptr(gnutls_x509_trust_list_t tlist, void *ptr); void *gnutls_x509_trust_list_get_ptr(gnutls_x509_trust_list_t tlist); void gnutls_certificate_set_trust_list (gnutls_certificate_credentials_t res, gnutls_x509_trust_list_t tlist, unsigned flags); void gnutls_certificate_get_trust_list (gnutls_certificate_credentials_t res, gnutls_x509_trust_list_t *tlist); typedef struct gnutls_x509_ext_st { char *oid; unsigned int critical; gnutls_datum_t data; } gnutls_x509_ext_st; void gnutls_x509_ext_deinit(gnutls_x509_ext_st *ext); int gnutls_x509_ext_print(gnutls_x509_ext_st *exts, unsigned int exts_size, gnutls_certificate_print_formats_t format, gnutls_datum_t * out); #include /* *INDENT-OFF* */ #ifdef __cplusplus } #endif /* *INDENT-ON* */ #endif /* GNUTLS_X509_H */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/HTMLparser.h ================================================ /* * Summary: interface for an HTML 4.0 non-verifying parser * Description: this module implements an HTML 4.0 non-verifying parser * with API compatible with the XML parser ones. It should * be able to parse "real world" HTML, even if severely * broken from a specification point of view. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __HTML_PARSER_H__ #define __HTML_PARSER_H__ #include #include #ifdef LIBXML_HTML_ENABLED #ifdef __cplusplus extern "C" { #endif /* * Most of the back-end structures from XML and HTML are shared. */ typedef xmlParserCtxt htmlParserCtxt; typedef xmlParserCtxtPtr htmlParserCtxtPtr; typedef xmlParserNodeInfo htmlParserNodeInfo; typedef xmlSAXHandler htmlSAXHandler; typedef xmlSAXHandlerPtr htmlSAXHandlerPtr; typedef xmlParserInput htmlParserInput; typedef xmlParserInputPtr htmlParserInputPtr; typedef xmlDocPtr htmlDocPtr; typedef xmlNodePtr htmlNodePtr; /* * Internal description of an HTML element, representing HTML 4.01 * and XHTML 1.0 (which share the same structure). */ typedef struct _htmlElemDesc htmlElemDesc; typedef htmlElemDesc *htmlElemDescPtr; struct _htmlElemDesc { const char *name; /* The tag name */ char startTag; /* Whether the start tag can be implied */ char endTag; /* Whether the end tag can be implied */ char saveEndTag; /* Whether the end tag should be saved */ char empty; /* Is this an empty element ? */ char depr; /* Is this a deprecated element ? */ char dtd; /* 1: only in Loose DTD, 2: only Frameset one */ char isinline; /* is this a block 0 or inline 1 element */ const char *desc; /* the description */ /* NRK Jan.2003 * New fields encapsulating HTML structure * * Bugs: * This is a very limited representation. It fails to tell us when * an element *requires* subelements (we only have whether they're * allowed or not), and it doesn't tell us where CDATA and PCDATA * are allowed. Some element relationships are not fully represented: * these are flagged with the word MODIFIER */ const char** subelts; /* allowed sub-elements of this element */ const char* defaultsubelt; /* subelement for suggested auto-repair if necessary or NULL */ const char** attrs_opt; /* Optional Attributes */ const char** attrs_depr; /* Additional deprecated attributes */ const char** attrs_req; /* Required attributes */ }; /* * Internal description of an HTML entity. */ typedef struct _htmlEntityDesc htmlEntityDesc; typedef htmlEntityDesc *htmlEntityDescPtr; struct _htmlEntityDesc { unsigned int value; /* the UNICODE value for the character */ const char *name; /* The entity name */ const char *desc; /* the description */ }; /* * There is only few public functions. */ XML_DEPRECATED XMLPUBFUN void htmlInitAutoClose (void); XMLPUBFUN const htmlElemDesc * htmlTagLookup (const xmlChar *tag); XMLPUBFUN const htmlEntityDesc * htmlEntityLookup(const xmlChar *name); XMLPUBFUN const htmlEntityDesc * htmlEntityValueLookup(unsigned int value); XMLPUBFUN int htmlIsAutoClosed(htmlDocPtr doc, htmlNodePtr elem); XMLPUBFUN int htmlAutoCloseTag(htmlDocPtr doc, const xmlChar *name, htmlNodePtr elem); XML_DEPRECATED XMLPUBFUN const htmlEntityDesc * htmlParseEntityRef(htmlParserCtxtPtr ctxt, const xmlChar **str); XML_DEPRECATED XMLPUBFUN int htmlParseCharRef(htmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void htmlParseElement(htmlParserCtxtPtr ctxt); XMLPUBFUN htmlParserCtxtPtr htmlNewParserCtxt(void); XMLPUBFUN htmlParserCtxtPtr htmlNewSAXParserCtxt(const htmlSAXHandler *sax, void *userData); XMLPUBFUN htmlParserCtxtPtr htmlCreateMemoryParserCtxt(const char *buffer, int size); XMLPUBFUN int htmlParseDocument(htmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN htmlDocPtr htmlSAXParseDoc (const xmlChar *cur, const char *encoding, htmlSAXHandlerPtr sax, void *userData); XMLPUBFUN htmlDocPtr htmlParseDoc (const xmlChar *cur, const char *encoding); XMLPUBFUN htmlParserCtxtPtr htmlCreateFileParserCtxt(const char *filename, const char *encoding); XML_DEPRECATED XMLPUBFUN htmlDocPtr htmlSAXParseFile(const char *filename, const char *encoding, htmlSAXHandlerPtr sax, void *userData); XMLPUBFUN htmlDocPtr htmlParseFile (const char *filename, const char *encoding); XMLPUBFUN int UTF8ToHtml (unsigned char *out, int *outlen, const unsigned char *in, int *inlen); XMLPUBFUN int htmlEncodeEntities(unsigned char *out, int *outlen, const unsigned char *in, int *inlen, int quoteChar); XMLPUBFUN int htmlIsScriptAttribute(const xmlChar *name); XMLPUBFUN int htmlHandleOmittedElem(int val); #ifdef LIBXML_PUSH_ENABLED /** * Interfaces for the Push mode. */ XMLPUBFUN htmlParserCtxtPtr htmlCreatePushParserCtxt(htmlSAXHandlerPtr sax, void *user_data, const char *chunk, int size, const char *filename, xmlCharEncoding enc); XMLPUBFUN int htmlParseChunk (htmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate); #endif /* LIBXML_PUSH_ENABLED */ XMLPUBFUN void htmlFreeParserCtxt (htmlParserCtxtPtr ctxt); /* * New set of simpler/more flexible APIs */ /** * xmlParserOption: * * This is the set of XML parser options that can be passed down * to the xmlReadDoc() and similar calls. */ typedef enum { HTML_PARSE_RECOVER = 1<<0, /* Relaxed parsing */ HTML_PARSE_NODEFDTD = 1<<2, /* do not default a doctype if not found */ HTML_PARSE_NOERROR = 1<<5, /* suppress error reports */ HTML_PARSE_NOWARNING= 1<<6, /* suppress warning reports */ HTML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */ HTML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */ HTML_PARSE_NONET = 1<<11,/* Forbid network access */ HTML_PARSE_NOIMPLIED= 1<<13,/* Do not add implied html/body... elements */ HTML_PARSE_COMPACT = 1<<16,/* compact small text nodes */ HTML_PARSE_IGNORE_ENC=1<<21 /* ignore internal document encoding hint */ } htmlParserOption; XMLPUBFUN void htmlCtxtReset (htmlParserCtxtPtr ctxt); XMLPUBFUN int htmlCtxtUseOptions (htmlParserCtxtPtr ctxt, int options); XMLPUBFUN htmlDocPtr htmlReadDoc (const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadFile (const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadMemory (const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadFd (int fd, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlReadIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadDoc (xmlParserCtxtPtr ctxt, const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadFile (xmlParserCtxtPtr ctxt, const char *filename, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadMemory (xmlParserCtxtPtr ctxt, const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadFd (xmlParserCtxtPtr ctxt, int fd, const char *URL, const char *encoding, int options); XMLPUBFUN htmlDocPtr htmlCtxtReadIO (xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); /* NRK/Jan2003: further knowledge of HTML structure */ typedef enum { HTML_NA = 0 , /* something we don't check at all */ HTML_INVALID = 0x1 , HTML_DEPRECATED = 0x2 , HTML_VALID = 0x4 , HTML_REQUIRED = 0xc /* VALID bit set so ( & HTML_VALID ) is TRUE */ } htmlStatus ; /* Using htmlElemDesc rather than name here, to emphasise the fact that otherwise there's a lookup overhead */ XMLPUBFUN htmlStatus htmlAttrAllowed(const htmlElemDesc*, const xmlChar*, int) ; XMLPUBFUN int htmlElementAllowedHere(const htmlElemDesc*, const xmlChar*) ; XMLPUBFUN htmlStatus htmlElementStatusHere(const htmlElemDesc*, const htmlElemDesc*) ; XMLPUBFUN htmlStatus htmlNodeStatus(const htmlNodePtr, int) ; /** * htmlDefaultSubelement: * @elt: HTML element * * Returns the default subelement for this element */ #define htmlDefaultSubelement(elt) elt->defaultsubelt /** * htmlElementAllowedHereDesc: * @parent: HTML parent element * @elt: HTML element * * Checks whether an HTML element description may be a * direct child of the specified element. * * Returns 1 if allowed; 0 otherwise. */ #define htmlElementAllowedHereDesc(parent,elt) \ htmlElementAllowedHere((parent), (elt)->name) /** * htmlRequiredAttrs: * @elt: HTML element * * Returns the attributes required for the specified element. */ #define htmlRequiredAttrs(elt) (elt)->attrs_req #ifdef __cplusplus } #endif #endif /* LIBXML_HTML_ENABLED */ #endif /* __HTML_PARSER_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/HTMLtree.h ================================================ /* * Summary: specific APIs to process HTML tree, especially serialization * Description: this module implements a few function needed to process * tree in an HTML specific way. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __HTML_TREE_H__ #define __HTML_TREE_H__ #include #include #include #include #ifdef LIBXML_HTML_ENABLED #ifdef __cplusplus extern "C" { #endif /** * HTML_TEXT_NODE: * * Macro. A text node in a HTML document is really implemented * the same way as a text node in an XML document. */ #define HTML_TEXT_NODE XML_TEXT_NODE /** * HTML_ENTITY_REF_NODE: * * Macro. An entity reference in a HTML document is really implemented * the same way as an entity reference in an XML document. */ #define HTML_ENTITY_REF_NODE XML_ENTITY_REF_NODE /** * HTML_COMMENT_NODE: * * Macro. A comment in a HTML document is really implemented * the same way as a comment in an XML document. */ #define HTML_COMMENT_NODE XML_COMMENT_NODE /** * HTML_PRESERVE_NODE: * * Macro. A preserved node in a HTML document is really implemented * the same way as a CDATA section in an XML document. */ #define HTML_PRESERVE_NODE XML_CDATA_SECTION_NODE /** * HTML_PI_NODE: * * Macro. A processing instruction in a HTML document is really implemented * the same way as a processing instruction in an XML document. */ #define HTML_PI_NODE XML_PI_NODE XMLPUBFUN htmlDocPtr htmlNewDoc (const xmlChar *URI, const xmlChar *ExternalID); XMLPUBFUN htmlDocPtr htmlNewDocNoDtD (const xmlChar *URI, const xmlChar *ExternalID); XMLPUBFUN const xmlChar * htmlGetMetaEncoding (htmlDocPtr doc); XMLPUBFUN int htmlSetMetaEncoding (htmlDocPtr doc, const xmlChar *encoding); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void htmlDocDumpMemory (xmlDocPtr cur, xmlChar **mem, int *size); XMLPUBFUN void htmlDocDumpMemoryFormat (xmlDocPtr cur, xmlChar **mem, int *size, int format); XMLPUBFUN int htmlDocDump (FILE *f, xmlDocPtr cur); XMLPUBFUN int htmlSaveFile (const char *filename, xmlDocPtr cur); XMLPUBFUN int htmlNodeDump (xmlBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur); XMLPUBFUN void htmlNodeDumpFile (FILE *out, xmlDocPtr doc, xmlNodePtr cur); XMLPUBFUN int htmlNodeDumpFileFormat (FILE *out, xmlDocPtr doc, xmlNodePtr cur, const char *encoding, int format); XMLPUBFUN int htmlSaveFileEnc (const char *filename, xmlDocPtr cur, const char *encoding); XMLPUBFUN int htmlSaveFileFormat (const char *filename, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN void htmlNodeDumpFormatOutput(xmlOutputBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, const char *encoding, int format); XMLPUBFUN void htmlDocContentDumpOutput(xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding); XMLPUBFUN void htmlDocContentDumpFormatOutput(xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN void htmlNodeDumpOutput (xmlOutputBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, const char *encoding); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN int htmlIsBooleanAttr (const xmlChar *name); #ifdef __cplusplus } #endif #endif /* LIBXML_HTML_ENABLED */ #endif /* __HTML_TREE_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/SAX.h ================================================ /* * Summary: Old SAX version 1 handler, deprecated * Description: DEPRECATED set of SAX version 1 interfaces used to * build the DOM tree. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SAX_H__ #define __XML_SAX_H__ #include #include #include #include #ifdef LIBXML_LEGACY_ENABLED #ifdef __cplusplus extern "C" { #endif XML_DEPRECATED XMLPUBFUN const xmlChar * getPublicId (void *ctx); XML_DEPRECATED XMLPUBFUN const xmlChar * getSystemId (void *ctx); XML_DEPRECATED XMLPUBFUN void setDocumentLocator (void *ctx, xmlSAXLocatorPtr loc); XML_DEPRECATED XMLPUBFUN int getLineNumber (void *ctx); XML_DEPRECATED XMLPUBFUN int getColumnNumber (void *ctx); XML_DEPRECATED XMLPUBFUN int isStandalone (void *ctx); XML_DEPRECATED XMLPUBFUN int hasInternalSubset (void *ctx); XML_DEPRECATED XMLPUBFUN int hasExternalSubset (void *ctx); XML_DEPRECATED XMLPUBFUN void internalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XML_DEPRECATED XMLPUBFUN void externalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XML_DEPRECATED XMLPUBFUN xmlEntityPtr getEntity (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN xmlEntityPtr getParameterEntity (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN xmlParserInputPtr resolveEntity (void *ctx, const xmlChar *publicId, const xmlChar *systemId); XML_DEPRECATED XMLPUBFUN void entityDecl (void *ctx, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content); XML_DEPRECATED XMLPUBFUN void attributeDecl (void *ctx, const xmlChar *elem, const xmlChar *fullname, int type, int def, const xmlChar *defaultValue, xmlEnumerationPtr tree); XML_DEPRECATED XMLPUBFUN void elementDecl (void *ctx, const xmlChar *name, int type, xmlElementContentPtr content); XML_DEPRECATED XMLPUBFUN void notationDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId); XML_DEPRECATED XMLPUBFUN void unparsedEntityDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName); XML_DEPRECATED XMLPUBFUN void startDocument (void *ctx); XML_DEPRECATED XMLPUBFUN void endDocument (void *ctx); XML_DEPRECATED XMLPUBFUN void attribute (void *ctx, const xmlChar *fullname, const xmlChar *value); XML_DEPRECATED XMLPUBFUN void startElement (void *ctx, const xmlChar *fullname, const xmlChar **atts); XML_DEPRECATED XMLPUBFUN void endElement (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN void reference (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN void characters (void *ctx, const xmlChar *ch, int len); XML_DEPRECATED XMLPUBFUN void ignorableWhitespace (void *ctx, const xmlChar *ch, int len); XML_DEPRECATED XMLPUBFUN void processingInstruction (void *ctx, const xmlChar *target, const xmlChar *data); XML_DEPRECATED XMLPUBFUN void globalNamespace (void *ctx, const xmlChar *href, const xmlChar *prefix); XML_DEPRECATED XMLPUBFUN void setNamespace (void *ctx, const xmlChar *name); XML_DEPRECATED XMLPUBFUN xmlNsPtr getNamespace (void *ctx); XML_DEPRECATED XMLPUBFUN int checkNamespace (void *ctx, xmlChar *nameSpace); XML_DEPRECATED XMLPUBFUN void namespaceDecl (void *ctx, const xmlChar *href, const xmlChar *prefix); XML_DEPRECATED XMLPUBFUN void comment (void *ctx, const xmlChar *value); XML_DEPRECATED XMLPUBFUN void cdataBlock (void *ctx, const xmlChar *value, int len); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN void initxmlDefaultSAXHandler (xmlSAXHandlerV1 *hdlr, int warning); #ifdef LIBXML_HTML_ENABLED XML_DEPRECATED XMLPUBFUN void inithtmlDefaultSAXHandler (xmlSAXHandlerV1 *hdlr); #endif #endif /* LIBXML_SAX1_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_LEGACY_ENABLED */ #endif /* __XML_SAX_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/SAX2.h ================================================ /* * Summary: SAX2 parser interface used to build the DOM tree * Description: those are the default SAX2 interfaces used by * the library when building DOM tree. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SAX2_H__ #define __XML_SAX2_H__ #include #include #include #include #ifdef __cplusplus extern "C" { #endif XMLPUBFUN const xmlChar * xmlSAX2GetPublicId (void *ctx); XMLPUBFUN const xmlChar * xmlSAX2GetSystemId (void *ctx); XMLPUBFUN void xmlSAX2SetDocumentLocator (void *ctx, xmlSAXLocatorPtr loc); XMLPUBFUN int xmlSAX2GetLineNumber (void *ctx); XMLPUBFUN int xmlSAX2GetColumnNumber (void *ctx); XMLPUBFUN int xmlSAX2IsStandalone (void *ctx); XMLPUBFUN int xmlSAX2HasInternalSubset (void *ctx); XMLPUBFUN int xmlSAX2HasExternalSubset (void *ctx); XMLPUBFUN void xmlSAX2InternalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN void xmlSAX2ExternalSubset (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlEntityPtr xmlSAX2GetEntity (void *ctx, const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlSAX2GetParameterEntity (void *ctx, const xmlChar *name); XMLPUBFUN xmlParserInputPtr xmlSAX2ResolveEntity (void *ctx, const xmlChar *publicId, const xmlChar *systemId); XMLPUBFUN void xmlSAX2EntityDecl (void *ctx, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content); XMLPUBFUN void xmlSAX2AttributeDecl (void *ctx, const xmlChar *elem, const xmlChar *fullname, int type, int def, const xmlChar *defaultValue, xmlEnumerationPtr tree); XMLPUBFUN void xmlSAX2ElementDecl (void *ctx, const xmlChar *name, int type, xmlElementContentPtr content); XMLPUBFUN void xmlSAX2NotationDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId); XMLPUBFUN void xmlSAX2UnparsedEntityDecl (void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName); XMLPUBFUN void xmlSAX2StartDocument (void *ctx); XMLPUBFUN void xmlSAX2EndDocument (void *ctx); #if defined(LIBXML_SAX1_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ defined(LIBXML_WRITER_ENABLED) || defined(LIBXML_LEGACY_ENABLED) XMLPUBFUN void xmlSAX2StartElement (void *ctx, const xmlChar *fullname, const xmlChar **atts); XMLPUBFUN void xmlSAX2EndElement (void *ctx, const xmlChar *name); #endif /* LIBXML_SAX1_ENABLED or LIBXML_HTML_ENABLED or LIBXML_LEGACY_ENABLED */ XMLPUBFUN void xmlSAX2StartElementNs (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes); XMLPUBFUN void xmlSAX2EndElementNs (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI); XMLPUBFUN void xmlSAX2Reference (void *ctx, const xmlChar *name); XMLPUBFUN void xmlSAX2Characters (void *ctx, const xmlChar *ch, int len); XMLPUBFUN void xmlSAX2IgnorableWhitespace (void *ctx, const xmlChar *ch, int len); XMLPUBFUN void xmlSAX2ProcessingInstruction (void *ctx, const xmlChar *target, const xmlChar *data); XMLPUBFUN void xmlSAX2Comment (void *ctx, const xmlChar *value); XMLPUBFUN void xmlSAX2CDataBlock (void *ctx, const xmlChar *value, int len); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN int xmlSAXDefaultVersion (int version); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN int xmlSAXVersion (xmlSAXHandler *hdlr, int version); XMLPUBFUN void xmlSAX2InitDefaultSAXHandler (xmlSAXHandler *hdlr, int warning); #ifdef LIBXML_HTML_ENABLED XMLPUBFUN void xmlSAX2InitHtmlDefaultSAXHandler(xmlSAXHandler *hdlr); XML_DEPRECATED XMLPUBFUN void htmlDefaultSAXHandlerInit (void); #endif XML_DEPRECATED XMLPUBFUN void xmlDefaultSAXHandlerInit (void); #ifdef __cplusplus } #endif #endif /* __XML_SAX2_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/c14n.h ================================================ /* * Summary: Provide Canonical XML and Exclusive XML Canonicalization * Description: the c14n modules provides a * * "Canonical XML" implementation * http://www.w3.org/TR/xml-c14n * * and an * * "Exclusive XML Canonicalization" implementation * http://www.w3.org/TR/xml-exc-c14n * Copy: See Copyright for the status of this software. * * Author: Aleksey Sanin */ #ifndef __XML_C14N_H__ #define __XML_C14N_H__ #include #ifdef LIBXML_C14N_ENABLED #ifdef LIBXML_OUTPUT_ENABLED #include #include #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* * XML Canonicalization * http://www.w3.org/TR/xml-c14n * * Exclusive XML Canonicalization * http://www.w3.org/TR/xml-exc-c14n * * Canonical form of an XML document could be created if and only if * a) default attributes (if any) are added to all nodes * b) all character and parsed entity references are resolved * In order to achieve this in libxml2 the document MUST be loaded with * following global settings: * * xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS; * xmlSubstituteEntitiesDefault(1); * * or corresponding parser context setting: * xmlParserCtxtPtr ctxt; * * ... * ctxt->loadsubset = XML_DETECT_IDS | XML_COMPLETE_ATTRS; * ctxt->replaceEntities = 1; * ... */ /* * xmlC14NMode: * * Predefined values for C14N modes * */ typedef enum { XML_C14N_1_0 = 0, /* Original C14N 1.0 spec */ XML_C14N_EXCLUSIVE_1_0 = 1, /* Exclusive C14N 1.0 spec */ XML_C14N_1_1 = 2 /* C14N 1.1 spec */ } xmlC14NMode; XMLPUBFUN int xmlC14NDocSaveTo (xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf); XMLPUBFUN int xmlC14NDocDumpMemory (xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, xmlChar **doc_txt_ptr); XMLPUBFUN int xmlC14NDocSave (xmlDocPtr doc, xmlNodeSetPtr nodes, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, const char* filename, int compression); /** * This is the core C14N function */ /** * xmlC14NIsVisibleCallback: * @user_data: user data * @node: the current node * @parent: the parent node * * Signature for a C14N callback on visible nodes * * Returns 1 if the node should be included */ typedef int (*xmlC14NIsVisibleCallback) (void* user_data, xmlNodePtr node, xmlNodePtr parent); XMLPUBFUN int xmlC14NExecute (xmlDocPtr doc, xmlC14NIsVisibleCallback is_visible_callback, void* user_data, int mode, /* a xmlC14NMode */ xmlChar **inclusive_ns_prefixes, int with_comments, xmlOutputBufferPtr buf); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* LIBXML_OUTPUT_ENABLED */ #endif /* LIBXML_C14N_ENABLED */ #endif /* __XML_C14N_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/catalog.h ================================================ /** * Summary: interfaces to the Catalog handling system * Description: the catalog module implements the support for * XML Catalogs and SGML catalogs * * SGML Open Technical Resolution TR9401:1997. * http://www.jclark.com/sp/catalog.htm * * XML Catalogs Working Draft 06 August 2001 * http://www.oasis-open.org/committees/entity/spec-2001-08-06.html * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_CATALOG_H__ #define __XML_CATALOG_H__ #include #include #include #include #ifdef LIBXML_CATALOG_ENABLED #ifdef __cplusplus extern "C" { #endif /** * XML_CATALOGS_NAMESPACE: * * The namespace for the XML Catalogs elements. */ #define XML_CATALOGS_NAMESPACE \ (const xmlChar *) "urn:oasis:names:tc:entity:xmlns:xml:catalog" /** * XML_CATALOG_PI: * * The specific XML Catalog Processing Instruction name. */ #define XML_CATALOG_PI \ (const xmlChar *) "oasis-xml-catalog" /* * The API is voluntarily limited to general cataloging. */ typedef enum { XML_CATA_PREFER_NONE = 0, XML_CATA_PREFER_PUBLIC = 1, XML_CATA_PREFER_SYSTEM } xmlCatalogPrefer; typedef enum { XML_CATA_ALLOW_NONE = 0, XML_CATA_ALLOW_GLOBAL = 1, XML_CATA_ALLOW_DOCUMENT = 2, XML_CATA_ALLOW_ALL = 3 } xmlCatalogAllow; typedef struct _xmlCatalog xmlCatalog; typedef xmlCatalog *xmlCatalogPtr; /* * Operations on a given catalog. */ XMLPUBFUN xmlCatalogPtr xmlNewCatalog (int sgml); XMLPUBFUN xmlCatalogPtr xmlLoadACatalog (const char *filename); XMLPUBFUN xmlCatalogPtr xmlLoadSGMLSuperCatalog (const char *filename); XMLPUBFUN int xmlConvertSGMLCatalog (xmlCatalogPtr catal); XMLPUBFUN int xmlACatalogAdd (xmlCatalogPtr catal, const xmlChar *type, const xmlChar *orig, const xmlChar *replace); XMLPUBFUN int xmlACatalogRemove (xmlCatalogPtr catal, const xmlChar *value); XMLPUBFUN xmlChar * xmlACatalogResolve (xmlCatalogPtr catal, const xmlChar *pubID, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlACatalogResolveSystem(xmlCatalogPtr catal, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlACatalogResolvePublic(xmlCatalogPtr catal, const xmlChar *pubID); XMLPUBFUN xmlChar * xmlACatalogResolveURI (xmlCatalogPtr catal, const xmlChar *URI); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlACatalogDump (xmlCatalogPtr catal, FILE *out); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN void xmlFreeCatalog (xmlCatalogPtr catal); XMLPUBFUN int xmlCatalogIsEmpty (xmlCatalogPtr catal); /* * Global operations. */ XMLPUBFUN void xmlInitializeCatalog (void); XMLPUBFUN int xmlLoadCatalog (const char *filename); XMLPUBFUN void xmlLoadCatalogs (const char *paths); XMLPUBFUN void xmlCatalogCleanup (void); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlCatalogDump (FILE *out); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN xmlChar * xmlCatalogResolve (const xmlChar *pubID, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlCatalogResolveSystem (const xmlChar *sysID); XMLPUBFUN xmlChar * xmlCatalogResolvePublic (const xmlChar *pubID); XMLPUBFUN xmlChar * xmlCatalogResolveURI (const xmlChar *URI); XMLPUBFUN int xmlCatalogAdd (const xmlChar *type, const xmlChar *orig, const xmlChar *replace); XMLPUBFUN int xmlCatalogRemove (const xmlChar *value); XMLPUBFUN xmlDocPtr xmlParseCatalogFile (const char *filename); XMLPUBFUN int xmlCatalogConvert (void); /* * Strictly minimal interfaces for per-document catalogs used * by the parser. */ XMLPUBFUN void xmlCatalogFreeLocal (void *catalogs); XMLPUBFUN void * xmlCatalogAddLocal (void *catalogs, const xmlChar *URL); XMLPUBFUN xmlChar * xmlCatalogLocalResolve (void *catalogs, const xmlChar *pubID, const xmlChar *sysID); XMLPUBFUN xmlChar * xmlCatalogLocalResolveURI(void *catalogs, const xmlChar *URI); /* * Preference settings. */ XMLPUBFUN int xmlCatalogSetDebug (int level); XMLPUBFUN xmlCatalogPrefer xmlCatalogSetDefaultPrefer(xmlCatalogPrefer prefer); XMLPUBFUN void xmlCatalogSetDefaults (xmlCatalogAllow allow); XMLPUBFUN xmlCatalogAllow xmlCatalogGetDefaults (void); /* DEPRECATED interfaces */ XMLPUBFUN const xmlChar * xmlCatalogGetSystem (const xmlChar *sysID); XMLPUBFUN const xmlChar * xmlCatalogGetPublic (const xmlChar *pubID); #ifdef __cplusplus } #endif #endif /* LIBXML_CATALOG_ENABLED */ #endif /* __XML_CATALOG_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/chvalid.h ================================================ /* * Summary: Unicode character range checking * Description: this module exports interfaces for the character * range validation APIs * * This file is automatically generated from the cvs source * definition files using the genChRanges.py Python script * * Generation date: Mon Mar 27 11:09:48 2006 * Sources: chvalid.def * Author: William Brack */ #ifndef __XML_CHVALID_H__ #define __XML_CHVALID_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * Define our typedefs and structures * */ typedef struct _xmlChSRange xmlChSRange; typedef xmlChSRange *xmlChSRangePtr; struct _xmlChSRange { unsigned short low; unsigned short high; }; typedef struct _xmlChLRange xmlChLRange; typedef xmlChLRange *xmlChLRangePtr; struct _xmlChLRange { unsigned int low; unsigned int high; }; typedef struct _xmlChRangeGroup xmlChRangeGroup; typedef xmlChRangeGroup *xmlChRangeGroupPtr; struct _xmlChRangeGroup { int nbShortRange; int nbLongRange; const xmlChSRange *shortRange; /* points to an array of ranges */ const xmlChLRange *longRange; }; /** * Range checking routine */ XMLPUBFUN int xmlCharInRange(unsigned int val, const xmlChRangeGroup *group); /** * xmlIsBaseChar_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBaseChar_ch(c) (((0x41 <= (c)) && ((c) <= 0x5a)) || \ ((0x61 <= (c)) && ((c) <= 0x7a)) || \ ((0xc0 <= (c)) && ((c) <= 0xd6)) || \ ((0xd8 <= (c)) && ((c) <= 0xf6)) || \ (0xf8 <= (c))) /** * xmlIsBaseCharQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBaseCharQ(c) (((c) < 0x100) ? \ xmlIsBaseChar_ch((c)) : \ xmlCharInRange((c), &xmlIsBaseCharGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsBaseCharGroup; /** * xmlIsBlank_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBlank_ch(c) (((c) == 0x20) || \ ((0x9 <= (c)) && ((c) <= 0xa)) || \ ((c) == 0xd)) /** * xmlIsBlankQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsBlankQ(c) (((c) < 0x100) ? \ xmlIsBlank_ch((c)) : 0) /** * xmlIsChar_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsChar_ch(c) (((0x9 <= (c)) && ((c) <= 0xa)) || \ ((c) == 0xd) || \ (0x20 <= (c))) /** * xmlIsCharQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsCharQ(c) (((c) < 0x100) ? \ xmlIsChar_ch((c)) :\ (((0x100 <= (c)) && ((c) <= 0xd7ff)) || \ ((0xe000 <= (c)) && ((c) <= 0xfffd)) || \ ((0x10000 <= (c)) && ((c) <= 0x10ffff)))) XMLPUBVAR const xmlChRangeGroup xmlIsCharGroup; /** * xmlIsCombiningQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsCombiningQ(c) (((c) < 0x100) ? \ 0 : \ xmlCharInRange((c), &xmlIsCombiningGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsCombiningGroup; /** * xmlIsDigit_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsDigit_ch(c) (((0x30 <= (c)) && ((c) <= 0x39))) /** * xmlIsDigitQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsDigitQ(c) (((c) < 0x100) ? \ xmlIsDigit_ch((c)) : \ xmlCharInRange((c), &xmlIsDigitGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsDigitGroup; /** * xmlIsExtender_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsExtender_ch(c) (((c) == 0xb7)) /** * xmlIsExtenderQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsExtenderQ(c) (((c) < 0x100) ? \ xmlIsExtender_ch((c)) : \ xmlCharInRange((c), &xmlIsExtenderGroup)) XMLPUBVAR const xmlChRangeGroup xmlIsExtenderGroup; /** * xmlIsIdeographicQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsIdeographicQ(c) (((c) < 0x100) ? \ 0 :\ (((0x4e00 <= (c)) && ((c) <= 0x9fa5)) || \ ((c) == 0x3007) || \ ((0x3021 <= (c)) && ((c) <= 0x3029)))) XMLPUBVAR const xmlChRangeGroup xmlIsIdeographicGroup; XMLPUBVAR const unsigned char xmlIsPubidChar_tab[256]; /** * xmlIsPubidChar_ch: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsPubidChar_ch(c) (xmlIsPubidChar_tab[(c)]) /** * xmlIsPubidCharQ: * @c: char to validate * * Automatically generated by genChRanges.py */ #define xmlIsPubidCharQ(c) (((c) < 0x100) ? \ xmlIsPubidChar_ch((c)) : 0) XMLPUBFUN int xmlIsBaseChar(unsigned int ch); XMLPUBFUN int xmlIsBlank(unsigned int ch); XMLPUBFUN int xmlIsChar(unsigned int ch); XMLPUBFUN int xmlIsCombining(unsigned int ch); XMLPUBFUN int xmlIsDigit(unsigned int ch); XMLPUBFUN int xmlIsExtender(unsigned int ch); XMLPUBFUN int xmlIsIdeographic(unsigned int ch); XMLPUBFUN int xmlIsPubidChar(unsigned int ch); #ifdef __cplusplus } #endif #endif /* __XML_CHVALID_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/debugXML.h ================================================ /* * Summary: Tree debugging APIs * Description: Interfaces to a set of routines used for debugging the tree * produced by the XML parser. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __DEBUG_XML__ #define __DEBUG_XML__ #include #include #include #ifdef LIBXML_DEBUG_ENABLED #include #ifdef __cplusplus extern "C" { #endif /* * The standard Dump routines. */ XMLPUBFUN void xmlDebugDumpString (FILE *output, const xmlChar *str); XMLPUBFUN void xmlDebugDumpAttr (FILE *output, xmlAttrPtr attr, int depth); XMLPUBFUN void xmlDebugDumpAttrList (FILE *output, xmlAttrPtr attr, int depth); XMLPUBFUN void xmlDebugDumpOneNode (FILE *output, xmlNodePtr node, int depth); XMLPUBFUN void xmlDebugDumpNode (FILE *output, xmlNodePtr node, int depth); XMLPUBFUN void xmlDebugDumpNodeList (FILE *output, xmlNodePtr node, int depth); XMLPUBFUN void xmlDebugDumpDocumentHead(FILE *output, xmlDocPtr doc); XMLPUBFUN void xmlDebugDumpDocument (FILE *output, xmlDocPtr doc); XMLPUBFUN void xmlDebugDumpDTD (FILE *output, xmlDtdPtr dtd); XMLPUBFUN void xmlDebugDumpEntities (FILE *output, xmlDocPtr doc); /**************************************************************** * * * Checking routines * * * ****************************************************************/ XMLPUBFUN int xmlDebugCheckDocument (FILE * output, xmlDocPtr doc); /**************************************************************** * * * XML shell helpers * * * ****************************************************************/ XMLPUBFUN void xmlLsOneNode (FILE *output, xmlNodePtr node); XMLPUBFUN int xmlLsCountNode (xmlNodePtr node); XMLPUBFUN const char * xmlBoolToText (int boolval); /**************************************************************** * * * The XML shell related structures and functions * * * ****************************************************************/ #ifdef LIBXML_XPATH_ENABLED /** * xmlShellReadlineFunc: * @prompt: a string prompt * * This is a generic signature for the XML shell input function. * * Returns a string which will be freed by the Shell. */ typedef char * (* xmlShellReadlineFunc)(char *prompt); /** * xmlShellCtxt: * * A debugging shell context. * TODO: add the defined function tables. */ typedef struct _xmlShellCtxt xmlShellCtxt; typedef xmlShellCtxt *xmlShellCtxtPtr; struct _xmlShellCtxt { char *filename; xmlDocPtr doc; xmlNodePtr node; xmlXPathContextPtr pctxt; int loaded; FILE *output; xmlShellReadlineFunc input; }; /** * xmlShellCmd: * @ctxt: a shell context * @arg: a string argument * @node: a first node * @node2: a second node * * This is a generic signature for the XML shell functions. * * Returns an int, negative returns indicating errors. */ typedef int (* xmlShellCmd) (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN void xmlShellPrintXPathError (int errorType, const char *arg); XMLPUBFUN void xmlShellPrintXPathResult(xmlXPathObjectPtr list); XMLPUBFUN int xmlShellList (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellBase (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellDir (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellLoad (xmlShellCtxtPtr ctxt, char *filename, xmlNodePtr node, xmlNodePtr node2); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlShellPrintNode (xmlNodePtr node); XMLPUBFUN int xmlShellCat (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellWrite (xmlShellCtxtPtr ctxt, char *filename, xmlNodePtr node, xmlNodePtr node2); XMLPUBFUN int xmlShellSave (xmlShellCtxtPtr ctxt, char *filename, xmlNodePtr node, xmlNodePtr node2); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_VALID_ENABLED XMLPUBFUN int xmlShellValidate (xmlShellCtxtPtr ctxt, char *dtd, xmlNodePtr node, xmlNodePtr node2); #endif /* LIBXML_VALID_ENABLED */ XMLPUBFUN int xmlShellDu (xmlShellCtxtPtr ctxt, char *arg, xmlNodePtr tree, xmlNodePtr node2); XMLPUBFUN int xmlShellPwd (xmlShellCtxtPtr ctxt, char *buffer, xmlNodePtr node, xmlNodePtr node2); /* * The Shell interface. */ XMLPUBFUN void xmlShell (xmlDocPtr doc, char *filename, xmlShellReadlineFunc input, FILE *output); #endif /* LIBXML_XPATH_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_DEBUG_ENABLED */ #endif /* __DEBUG_XML__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/dict.h ================================================ /* * Summary: string dictionary * Description: dictionary of reusable strings, just used to avoid allocation * and freeing operations. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_DICT_H__ #define __XML_DICT_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * The dictionary. */ typedef struct _xmlDict xmlDict; typedef xmlDict *xmlDictPtr; /* * Initializer */ XML_DEPRECATED XMLPUBFUN int xmlInitializeDict(void); /* * Constructor and destructor. */ XMLPUBFUN xmlDictPtr xmlDictCreate (void); XMLPUBFUN size_t xmlDictSetLimit (xmlDictPtr dict, size_t limit); XMLPUBFUN size_t xmlDictGetUsage (xmlDictPtr dict); XMLPUBFUN xmlDictPtr xmlDictCreateSub(xmlDictPtr sub); XMLPUBFUN int xmlDictReference(xmlDictPtr dict); XMLPUBFUN void xmlDictFree (xmlDictPtr dict); /* * Lookup of entry in the dictionary. */ XMLPUBFUN const xmlChar * xmlDictLookup (xmlDictPtr dict, const xmlChar *name, int len); XMLPUBFUN const xmlChar * xmlDictExists (xmlDictPtr dict, const xmlChar *name, int len); XMLPUBFUN const xmlChar * xmlDictQLookup (xmlDictPtr dict, const xmlChar *prefix, const xmlChar *name); XMLPUBFUN int xmlDictOwns (xmlDictPtr dict, const xmlChar *str); XMLPUBFUN int xmlDictSize (xmlDictPtr dict); /* * Cleanup function */ XML_DEPRECATED XMLPUBFUN void xmlDictCleanup (void); #ifdef __cplusplus } #endif #endif /* ! __XML_DICT_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/encoding.h ================================================ /* * Summary: interface for the encoding conversion functions * Description: interface for the encoding conversion functions needed for * XML basic encoding and iconv() support. * * Related specs are * rfc2044 (UTF-8 and UTF-16) F. Yergeau Alis Technologies * [ISO-10646] UTF-8 and UTF-16 in Annexes * [ISO-8859-1] ISO Latin-1 characters codes. * [UNICODE] The Unicode Consortium, "The Unicode Standard -- * Worldwide Character Encoding -- Version 1.0", Addison- * Wesley, Volume 1, 1991, Volume 2, 1992. UTF-8 is * described in Unicode Technical Report #4. * [US-ASCII] Coded Character Set--7-bit American Standard Code for * Information Interchange, ANSI X3.4-1986. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_CHAR_ENCODING_H__ #define __XML_CHAR_ENCODING_H__ #include #ifdef LIBXML_ICONV_ENABLED #include #endif #ifdef __cplusplus extern "C" { #endif /* * xmlCharEncoding: * * Predefined values for some standard encodings. * Libxml does not do beforehand translation on UTF8 and ISOLatinX. * It also supports ASCII, ISO-8859-1, and UTF16 (LE and BE) by default. * * Anything else would have to be translated to UTF8 before being * given to the parser itself. The BOM for UTF16 and the encoding * declaration are looked at and a converter is looked for at that * point. If not found the parser stops here as asked by the XML REC. A * converter can be registered by the user using xmlRegisterCharEncodingHandler * but the current form doesn't allow stateful transcoding (a serious * problem agreed !). If iconv has been found it will be used * automatically and allow stateful transcoding, the simplest is then * to be sure to enable iconv and to provide iconv libs for the encoding * support needed. * * Note that the generic "UTF-16" is not a predefined value. Instead, only * the specific UTF-16LE and UTF-16BE are present. */ typedef enum { XML_CHAR_ENCODING_ERROR= -1, /* No char encoding detected */ XML_CHAR_ENCODING_NONE= 0, /* No char encoding detected */ XML_CHAR_ENCODING_UTF8= 1, /* UTF-8 */ XML_CHAR_ENCODING_UTF16LE= 2, /* UTF-16 little endian */ XML_CHAR_ENCODING_UTF16BE= 3, /* UTF-16 big endian */ XML_CHAR_ENCODING_UCS4LE= 4, /* UCS-4 little endian */ XML_CHAR_ENCODING_UCS4BE= 5, /* UCS-4 big endian */ XML_CHAR_ENCODING_EBCDIC= 6, /* EBCDIC uh! */ XML_CHAR_ENCODING_UCS4_2143=7, /* UCS-4 unusual ordering */ XML_CHAR_ENCODING_UCS4_3412=8, /* UCS-4 unusual ordering */ XML_CHAR_ENCODING_UCS2= 9, /* UCS-2 */ XML_CHAR_ENCODING_8859_1= 10,/* ISO-8859-1 ISO Latin 1 */ XML_CHAR_ENCODING_8859_2= 11,/* ISO-8859-2 ISO Latin 2 */ XML_CHAR_ENCODING_8859_3= 12,/* ISO-8859-3 */ XML_CHAR_ENCODING_8859_4= 13,/* ISO-8859-4 */ XML_CHAR_ENCODING_8859_5= 14,/* ISO-8859-5 */ XML_CHAR_ENCODING_8859_6= 15,/* ISO-8859-6 */ XML_CHAR_ENCODING_8859_7= 16,/* ISO-8859-7 */ XML_CHAR_ENCODING_8859_8= 17,/* ISO-8859-8 */ XML_CHAR_ENCODING_8859_9= 18,/* ISO-8859-9 */ XML_CHAR_ENCODING_2022_JP= 19,/* ISO-2022-JP */ XML_CHAR_ENCODING_SHIFT_JIS=20,/* Shift_JIS */ XML_CHAR_ENCODING_EUC_JP= 21,/* EUC-JP */ XML_CHAR_ENCODING_ASCII= 22 /* pure ASCII */ } xmlCharEncoding; /** * xmlCharEncodingInputFunc: * @out: a pointer to an array of bytes to store the UTF-8 result * @outlen: the length of @out * @in: a pointer to an array of chars in the original encoding * @inlen: the length of @in * * Take a block of chars in the original encoding and try to convert * it to an UTF-8 block of chars out. * * Returns the number of bytes written, -1 if lack of space, or -2 * if the transcoding failed. * The value of @inlen after return is the number of octets consumed * if the return value is positive, else unpredictiable. * The value of @outlen after return is the number of octets consumed. */ typedef int (* xmlCharEncodingInputFunc)(unsigned char *out, int *outlen, const unsigned char *in, int *inlen); /** * xmlCharEncodingOutputFunc: * @out: a pointer to an array of bytes to store the result * @outlen: the length of @out * @in: a pointer to an array of UTF-8 chars * @inlen: the length of @in * * Take a block of UTF-8 chars in and try to convert it to another * encoding. * Note: a first call designed to produce heading info is called with * in = NULL. If stateful this should also initialize the encoder state. * * Returns the number of bytes written, -1 if lack of space, or -2 * if the transcoding failed. * The value of @inlen after return is the number of octets consumed * if the return value is positive, else unpredictiable. * The value of @outlen after return is the number of octets produced. */ typedef int (* xmlCharEncodingOutputFunc)(unsigned char *out, int *outlen, const unsigned char *in, int *inlen); /* * Block defining the handlers for non UTF-8 encodings. * If iconv is supported, there are two extra fields. */ typedef struct _xmlCharEncodingHandler xmlCharEncodingHandler; typedef xmlCharEncodingHandler *xmlCharEncodingHandlerPtr; struct _xmlCharEncodingHandler { char *name; xmlCharEncodingInputFunc input; xmlCharEncodingOutputFunc output; #ifdef LIBXML_ICONV_ENABLED iconv_t iconv_in; iconv_t iconv_out; #endif /* LIBXML_ICONV_ENABLED */ #ifdef LIBXML_ICU_ENABLED struct _uconv_t *uconv_in; struct _uconv_t *uconv_out; #endif /* LIBXML_ICU_ENABLED */ }; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif /* * Interfaces for encoding handlers. */ XML_DEPRECATED XMLPUBFUN void xmlInitCharEncodingHandlers (void); XML_DEPRECATED XMLPUBFUN void xmlCleanupCharEncodingHandlers (void); XMLPUBFUN void xmlRegisterCharEncodingHandler (xmlCharEncodingHandlerPtr handler); XMLPUBFUN xmlCharEncodingHandlerPtr xmlGetCharEncodingHandler (xmlCharEncoding enc); XMLPUBFUN xmlCharEncodingHandlerPtr xmlFindCharEncodingHandler (const char *name); XMLPUBFUN xmlCharEncodingHandlerPtr xmlNewCharEncodingHandler (const char *name, xmlCharEncodingInputFunc input, xmlCharEncodingOutputFunc output); /* * Interfaces for encoding names and aliases. */ XMLPUBFUN int xmlAddEncodingAlias (const char *name, const char *alias); XMLPUBFUN int xmlDelEncodingAlias (const char *alias); XMLPUBFUN const char * xmlGetEncodingAlias (const char *alias); XMLPUBFUN void xmlCleanupEncodingAliases (void); XMLPUBFUN xmlCharEncoding xmlParseCharEncoding (const char *name); XMLPUBFUN const char * xmlGetCharEncodingName (xmlCharEncoding enc); /* * Interfaces directly used by the parsers. */ XMLPUBFUN xmlCharEncoding xmlDetectCharEncoding (const unsigned char *in, int len); XMLPUBFUN int xmlCharEncOutFunc (xmlCharEncodingHandler *handler, xmlBufferPtr out, xmlBufferPtr in); XMLPUBFUN int xmlCharEncInFunc (xmlCharEncodingHandler *handler, xmlBufferPtr out, xmlBufferPtr in); XML_DEPRECATED XMLPUBFUN int xmlCharEncFirstLine (xmlCharEncodingHandler *handler, xmlBufferPtr out, xmlBufferPtr in); XMLPUBFUN int xmlCharEncCloseFunc (xmlCharEncodingHandler *handler); /* * Export a few useful functions */ #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN int UTF8Toisolat1 (unsigned char *out, int *outlen, const unsigned char *in, int *inlen); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN int isolat1ToUTF8 (unsigned char *out, int *outlen, const unsigned char *in, int *inlen); #ifdef __cplusplus } #endif #endif /* __XML_CHAR_ENCODING_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/entities.h ================================================ /* * Summary: interface for the XML entities handling * Description: this module provides some of the entity API needed * for the parser and applications. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_ENTITIES_H__ #define __XML_ENTITIES_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * The different valid entity types. */ typedef enum { XML_INTERNAL_GENERAL_ENTITY = 1, XML_EXTERNAL_GENERAL_PARSED_ENTITY = 2, XML_EXTERNAL_GENERAL_UNPARSED_ENTITY = 3, XML_INTERNAL_PARAMETER_ENTITY = 4, XML_EXTERNAL_PARAMETER_ENTITY = 5, XML_INTERNAL_PREDEFINED_ENTITY = 6 } xmlEntityType; /* * An unit of storage for an entity, contains the string, the value * and the linkind data needed for the linking in the hash table. */ struct _xmlEntity { void *_private; /* application data */ xmlElementType type; /* XML_ENTITY_DECL, must be second ! */ const xmlChar *name; /* Entity name */ struct _xmlNode *children; /* First child link */ struct _xmlNode *last; /* Last child link */ struct _xmlDtd *parent; /* -> DTD */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ xmlChar *orig; /* content without ref substitution */ xmlChar *content; /* content or ndata if unparsed */ int length; /* the content length */ xmlEntityType etype; /* The entity type */ const xmlChar *ExternalID; /* External identifier for PUBLIC */ const xmlChar *SystemID; /* URI for a SYSTEM or PUBLIC Entity */ struct _xmlEntity *nexte; /* unused */ const xmlChar *URI; /* the full URI as computed */ int owner; /* does the entity own the childrens */ int flags; /* various flags */ unsigned long expandedSize; /* expanded size */ }; /* * All entities are stored in an hash table. * There is 2 separate hash tables for global and parameter entities. */ typedef struct _xmlHashTable xmlEntitiesTable; typedef xmlEntitiesTable *xmlEntitiesTablePtr; /* * External functions: */ #ifdef LIBXML_LEGACY_ENABLED XML_DEPRECATED XMLPUBFUN void xmlInitializePredefinedEntities (void); #endif /* LIBXML_LEGACY_ENABLED */ XMLPUBFUN xmlEntityPtr xmlNewEntity (xmlDocPtr doc, const xmlChar *name, int type, const xmlChar *ExternalID, const xmlChar *SystemID, const xmlChar *content); XMLPUBFUN xmlEntityPtr xmlAddDocEntity (xmlDocPtr doc, const xmlChar *name, int type, const xmlChar *ExternalID, const xmlChar *SystemID, const xmlChar *content); XMLPUBFUN xmlEntityPtr xmlAddDtdEntity (xmlDocPtr doc, const xmlChar *name, int type, const xmlChar *ExternalID, const xmlChar *SystemID, const xmlChar *content); XMLPUBFUN xmlEntityPtr xmlGetPredefinedEntity (const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlGetDocEntity (const xmlDoc *doc, const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlGetDtdEntity (xmlDocPtr doc, const xmlChar *name); XMLPUBFUN xmlEntityPtr xmlGetParameterEntity (xmlDocPtr doc, const xmlChar *name); #ifdef LIBXML_LEGACY_ENABLED XML_DEPRECATED XMLPUBFUN const xmlChar * xmlEncodeEntities (xmlDocPtr doc, const xmlChar *input); #endif /* LIBXML_LEGACY_ENABLED */ XMLPUBFUN xmlChar * xmlEncodeEntitiesReentrant(xmlDocPtr doc, const xmlChar *input); XMLPUBFUN xmlChar * xmlEncodeSpecialChars (const xmlDoc *doc, const xmlChar *input); XMLPUBFUN xmlEntitiesTablePtr xmlCreateEntitiesTable (void); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlEntitiesTablePtr xmlCopyEntitiesTable (xmlEntitiesTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeEntitiesTable (xmlEntitiesTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpEntitiesTable (xmlBufferPtr buf, xmlEntitiesTablePtr table); XMLPUBFUN void xmlDumpEntityDecl (xmlBufferPtr buf, xmlEntityPtr ent); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_LEGACY_ENABLED XMLPUBFUN void xmlCleanupPredefinedEntities(void); #endif /* LIBXML_LEGACY_ENABLED */ #ifdef __cplusplus } #endif # endif /* __XML_ENTITIES_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/globals.h ================================================ /* * Summary: interface for all global variables of the library * Description: all the global variables and thread handling for * those variables is handled by this module. * * The bottom of this file is automatically generated by build_glob.py * based on the description file global.data * * Copy: See Copyright for the status of this software. * * Author: Gary Pennington , Daniel Veillard */ #ifndef __XML_GLOBALS_H #define __XML_GLOBALS_H #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif XML_DEPRECATED XMLPUBFUN void xmlInitGlobals(void); XML_DEPRECATED XMLPUBFUN void xmlCleanupGlobals(void); /** * xmlParserInputBufferCreateFilenameFunc: * @URI: the URI to read from * @enc: the requested source encoding * * Signature for the function doing the lookup for a suitable input method * corresponding to an URI. * * Returns the new xmlParserInputBufferPtr in case of success or NULL if no * method was found. */ typedef xmlParserInputBufferPtr (*xmlParserInputBufferCreateFilenameFunc) (const char *URI, xmlCharEncoding enc); /** * xmlOutputBufferCreateFilenameFunc: * @URI: the URI to write to * @enc: the requested target encoding * * Signature for the function doing the lookup for a suitable output method * corresponding to an URI. * * Returns the new xmlOutputBufferPtr in case of success or NULL if no * method was found. */ typedef xmlOutputBufferPtr (*xmlOutputBufferCreateFilenameFunc) (const char *URI, xmlCharEncodingHandlerPtr encoder, int compression); XMLPUBFUN xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameDefault (xmlParserInputBufferCreateFilenameFunc func); XMLPUBFUN xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameDefault (xmlOutputBufferCreateFilenameFunc func); /* * Externally global symbols which need to be protected for backwards * compatibility support. */ #undef htmlDefaultSAXHandler #undef oldXMLWDcompatibility #undef xmlBufferAllocScheme #undef xmlDefaultBufferSize #undef xmlDefaultSAXHandler #undef xmlDefaultSAXLocator #undef xmlDoValidityCheckingDefaultValue #undef xmlFree #undef xmlGenericError #undef xmlStructuredError #undef xmlGenericErrorContext #undef xmlStructuredErrorContext #undef xmlGetWarningsDefaultValue #undef xmlIndentTreeOutput #undef xmlTreeIndentString #undef xmlKeepBlanksDefaultValue #undef xmlLineNumbersDefaultValue #undef xmlLoadExtDtdDefaultValue #undef xmlMalloc #undef xmlMallocAtomic #undef xmlMemStrdup #undef xmlParserDebugEntities #undef xmlParserVersion #undef xmlPedanticParserDefaultValue #undef xmlRealloc #undef xmlSaveNoEmptyTags #undef xmlSubstituteEntitiesDefaultValue #undef xmlRegisterNodeDefaultValue #undef xmlDeregisterNodeDefaultValue #undef xmlLastError #undef xmlParserInputBufferCreateFilenameValue #undef xmlOutputBufferCreateFilenameValue /** * xmlRegisterNodeFunc: * @node: the current node * * Signature for the registration callback of a created node */ typedef void (*xmlRegisterNodeFunc) (xmlNodePtr node); /** * xmlDeregisterNodeFunc: * @node: the current node * * Signature for the deregistration callback of a discarded node */ typedef void (*xmlDeregisterNodeFunc) (xmlNodePtr node); typedef struct _xmlGlobalState xmlGlobalState; typedef xmlGlobalState *xmlGlobalStatePtr; struct _xmlGlobalState { const char *xmlParserVersion; xmlSAXLocator xmlDefaultSAXLocator; xmlSAXHandlerV1 xmlDefaultSAXHandler; xmlSAXHandlerV1 docbDefaultSAXHandler; /* unused */ xmlSAXHandlerV1 htmlDefaultSAXHandler; xmlFreeFunc xmlFree; xmlMallocFunc xmlMalloc; xmlStrdupFunc xmlMemStrdup; xmlReallocFunc xmlRealloc; xmlGenericErrorFunc xmlGenericError; xmlStructuredErrorFunc xmlStructuredError; void *xmlGenericErrorContext; int oldXMLWDcompatibility; xmlBufferAllocationScheme xmlBufferAllocScheme; int xmlDefaultBufferSize; int xmlSubstituteEntitiesDefaultValue; int xmlDoValidityCheckingDefaultValue; int xmlGetWarningsDefaultValue; int xmlKeepBlanksDefaultValue; int xmlLineNumbersDefaultValue; int xmlLoadExtDtdDefaultValue; int xmlParserDebugEntities; int xmlPedanticParserDefaultValue; int xmlSaveNoEmptyTags; int xmlIndentTreeOutput; const char *xmlTreeIndentString; xmlRegisterNodeFunc xmlRegisterNodeDefaultValue; xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue; xmlMallocFunc xmlMallocAtomic; xmlError xmlLastError; xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValue; xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue; void *xmlStructuredErrorContext; }; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif XMLPUBFUN void xmlInitializeGlobalState(xmlGlobalStatePtr gs); XMLPUBFUN void xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler); XMLPUBFUN void xmlThrDefSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler); XMLPUBFUN xmlRegisterNodeFunc xmlRegisterNodeDefault(xmlRegisterNodeFunc func); XMLPUBFUN xmlRegisterNodeFunc xmlThrDefRegisterNodeDefault(xmlRegisterNodeFunc func); XMLPUBFUN xmlDeregisterNodeFunc xmlDeregisterNodeDefault(xmlDeregisterNodeFunc func); XMLPUBFUN xmlDeregisterNodeFunc xmlThrDefDeregisterNodeDefault(xmlDeregisterNodeFunc func); XMLPUBFUN xmlOutputBufferCreateFilenameFunc xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func); XMLPUBFUN xmlParserInputBufferCreateFilenameFunc xmlThrDefParserInputBufferCreateFilenameDefault( xmlParserInputBufferCreateFilenameFunc func); /* * In general the memory allocation entry points are not kept * thread specific but this can be overridden by LIBXML_THREAD_ALLOC_ENABLED * - xmlMalloc * - xmlMallocAtomic * - xmlRealloc * - xmlMemStrdup * - xmlFree */ #ifdef LIBXML_THREAD_ALLOC_ENABLED /** DOC_DISABLE */ #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlMallocFunc * __xmlMalloc(void); #define xmlMalloc \ (*(__xmlMalloc())) #else XMLPUBVAR xmlMallocFunc xmlMalloc; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlMallocFunc * __xmlMallocAtomic(void); #define xmlMallocAtomic \ (*(__xmlMallocAtomic())) #else XMLPUBVAR xmlMallocFunc xmlMallocAtomic; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlReallocFunc * __xmlRealloc(void); #define xmlRealloc \ (*(__xmlRealloc())) #else XMLPUBVAR xmlReallocFunc xmlRealloc; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlFreeFunc * __xmlFree(void); #define xmlFree \ (*(__xmlFree())) #else XMLPUBVAR xmlFreeFunc xmlFree; #endif #ifdef LIBXML_THREAD_ENABLED XMLPUBFUN xmlStrdupFunc * __xmlMemStrdup(void); #define xmlMemStrdup \ (*(__xmlMemStrdup())) #else XMLPUBVAR xmlStrdupFunc xmlMemStrdup; #endif /** DOC_ENABLE */ #else /* !LIBXML_THREAD_ALLOC_ENABLED */ XMLPUBVAR xmlMallocFunc xmlMalloc; XMLPUBVAR xmlMallocFunc xmlMallocAtomic; XMLPUBVAR xmlReallocFunc xmlRealloc; XMLPUBVAR xmlFreeFunc xmlFree; XMLPUBVAR xmlStrdupFunc xmlMemStrdup; #endif /* LIBXML_THREAD_ALLOC_ENABLED */ #ifdef LIBXML_HTML_ENABLED XML_DEPRECATED XMLPUBFUN xmlSAXHandlerV1 * __htmlDefaultSAXHandler(void); #ifdef LIBXML_THREAD_ENABLED #define htmlDefaultSAXHandler \ (*(__htmlDefaultSAXHandler())) #else XML_DEPRECATED XMLPUBVAR xmlSAXHandlerV1 htmlDefaultSAXHandler; #endif #endif XMLPUBFUN xmlError * __xmlLastError(void); #ifdef LIBXML_THREAD_ENABLED #define xmlLastError \ (*(__xmlLastError())) #else XMLPUBVAR xmlError xmlLastError; #endif /* * Everything starting from the line below is * Automatically generated by build_glob.py. * Do not modify the previous line. */ XML_DEPRECATED XMLPUBFUN int * __oldXMLWDcompatibility(void); #ifdef LIBXML_THREAD_ENABLED #define oldXMLWDcompatibility \ (*(__oldXMLWDcompatibility())) #else XML_DEPRECATED XMLPUBVAR int oldXMLWDcompatibility; #endif XML_DEPRECATED XMLPUBFUN xmlBufferAllocationScheme * __xmlBufferAllocScheme(void); #ifdef LIBXML_THREAD_ENABLED #define xmlBufferAllocScheme \ (*(__xmlBufferAllocScheme())) #else XML_DEPRECATED XMLPUBVAR xmlBufferAllocationScheme xmlBufferAllocScheme; #endif XML_DEPRECATED XMLPUBFUN xmlBufferAllocationScheme xmlThrDefBufferAllocScheme(xmlBufferAllocationScheme v); XML_DEPRECATED XMLPUBFUN int * __xmlDefaultBufferSize(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDefaultBufferSize \ (*(__xmlDefaultBufferSize())) #else XML_DEPRECATED XMLPUBVAR int xmlDefaultBufferSize; #endif XML_DEPRECATED XMLPUBFUN int xmlThrDefDefaultBufferSize(int v); XML_DEPRECATED XMLPUBFUN xmlSAXHandlerV1 * __xmlDefaultSAXHandler(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDefaultSAXHandler \ (*(__xmlDefaultSAXHandler())) #else XML_DEPRECATED XMLPUBVAR xmlSAXHandlerV1 xmlDefaultSAXHandler; #endif XML_DEPRECATED XMLPUBFUN xmlSAXLocator * __xmlDefaultSAXLocator(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDefaultSAXLocator \ (*(__xmlDefaultSAXLocator())) #else XML_DEPRECATED XMLPUBVAR xmlSAXLocator xmlDefaultSAXLocator; #endif XMLPUBFUN int * __xmlDoValidityCheckingDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDoValidityCheckingDefaultValue \ (*(__xmlDoValidityCheckingDefaultValue())) #else XMLPUBVAR int xmlDoValidityCheckingDefaultValue; #endif XMLPUBFUN int xmlThrDefDoValidityCheckingDefaultValue(int v); XMLPUBFUN xmlGenericErrorFunc * __xmlGenericError(void); #ifdef LIBXML_THREAD_ENABLED #define xmlGenericError \ (*(__xmlGenericError())) #else XMLPUBVAR xmlGenericErrorFunc xmlGenericError; #endif XMLPUBFUN xmlStructuredErrorFunc * __xmlStructuredError(void); #ifdef LIBXML_THREAD_ENABLED #define xmlStructuredError \ (*(__xmlStructuredError())) #else XMLPUBVAR xmlStructuredErrorFunc xmlStructuredError; #endif XMLPUBFUN void * * __xmlGenericErrorContext(void); #ifdef LIBXML_THREAD_ENABLED #define xmlGenericErrorContext \ (*(__xmlGenericErrorContext())) #else XMLPUBVAR void * xmlGenericErrorContext; #endif XMLPUBFUN void * * __xmlStructuredErrorContext(void); #ifdef LIBXML_THREAD_ENABLED #define xmlStructuredErrorContext \ (*(__xmlStructuredErrorContext())) #else XMLPUBVAR void * xmlStructuredErrorContext; #endif XMLPUBFUN int * __xmlGetWarningsDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlGetWarningsDefaultValue \ (*(__xmlGetWarningsDefaultValue())) #else XMLPUBVAR int xmlGetWarningsDefaultValue; #endif XMLPUBFUN int xmlThrDefGetWarningsDefaultValue(int v); XMLPUBFUN int * __xmlIndentTreeOutput(void); #ifdef LIBXML_THREAD_ENABLED #define xmlIndentTreeOutput \ (*(__xmlIndentTreeOutput())) #else XMLPUBVAR int xmlIndentTreeOutput; #endif XMLPUBFUN int xmlThrDefIndentTreeOutput(int v); XMLPUBFUN const char * * __xmlTreeIndentString(void); #ifdef LIBXML_THREAD_ENABLED #define xmlTreeIndentString \ (*(__xmlTreeIndentString())) #else XMLPUBVAR const char * xmlTreeIndentString; #endif XMLPUBFUN const char * xmlThrDefTreeIndentString(const char * v); XMLPUBFUN int * __xmlKeepBlanksDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlKeepBlanksDefaultValue \ (*(__xmlKeepBlanksDefaultValue())) #else XMLPUBVAR int xmlKeepBlanksDefaultValue; #endif XMLPUBFUN int xmlThrDefKeepBlanksDefaultValue(int v); XML_DEPRECATED XMLPUBFUN int * __xmlLineNumbersDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlLineNumbersDefaultValue \ (*(__xmlLineNumbersDefaultValue())) #else XML_DEPRECATED XMLPUBVAR int xmlLineNumbersDefaultValue; #endif XML_DEPRECATED XMLPUBFUN int xmlThrDefLineNumbersDefaultValue(int v); XMLPUBFUN int * __xmlLoadExtDtdDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlLoadExtDtdDefaultValue \ (*(__xmlLoadExtDtdDefaultValue())) #else XMLPUBVAR int xmlLoadExtDtdDefaultValue; #endif XMLPUBFUN int xmlThrDefLoadExtDtdDefaultValue(int v); XMLPUBFUN int * __xmlParserDebugEntities(void); #ifdef LIBXML_THREAD_ENABLED #define xmlParserDebugEntities \ (*(__xmlParserDebugEntities())) #else XMLPUBVAR int xmlParserDebugEntities; #endif XMLPUBFUN int xmlThrDefParserDebugEntities(int v); XMLPUBFUN const char * * __xmlParserVersion(void); #ifdef LIBXML_THREAD_ENABLED #define xmlParserVersion \ (*(__xmlParserVersion())) #else XMLPUBVAR const char * xmlParserVersion; #endif XML_DEPRECATED XMLPUBFUN int * __xmlPedanticParserDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlPedanticParserDefaultValue \ (*(__xmlPedanticParserDefaultValue())) #else XML_DEPRECATED XMLPUBVAR int xmlPedanticParserDefaultValue; #endif XML_DEPRECATED XMLPUBFUN int xmlThrDefPedanticParserDefaultValue(int v); XMLPUBFUN int * __xmlSaveNoEmptyTags(void); #ifdef LIBXML_THREAD_ENABLED #define xmlSaveNoEmptyTags \ (*(__xmlSaveNoEmptyTags())) #else XMLPUBVAR int xmlSaveNoEmptyTags; #endif XMLPUBFUN int xmlThrDefSaveNoEmptyTags(int v); XMLPUBFUN int * __xmlSubstituteEntitiesDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlSubstituteEntitiesDefaultValue \ (*(__xmlSubstituteEntitiesDefaultValue())) #else XMLPUBVAR int xmlSubstituteEntitiesDefaultValue; #endif XMLPUBFUN int xmlThrDefSubstituteEntitiesDefaultValue(int v); XML_DEPRECATED XMLPUBFUN xmlRegisterNodeFunc * __xmlRegisterNodeDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlRegisterNodeDefaultValue \ (*(__xmlRegisterNodeDefaultValue())) #else XML_DEPRECATED XMLPUBVAR xmlRegisterNodeFunc xmlRegisterNodeDefaultValue; #endif XML_DEPRECATED XMLPUBFUN xmlDeregisterNodeFunc * __xmlDeregisterNodeDefaultValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlDeregisterNodeDefaultValue \ (*(__xmlDeregisterNodeDefaultValue())) #else XML_DEPRECATED XMLPUBVAR xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue; #endif XML_DEPRECATED XMLPUBFUN xmlParserInputBufferCreateFilenameFunc * \ __xmlParserInputBufferCreateFilenameValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlParserInputBufferCreateFilenameValue \ (*(__xmlParserInputBufferCreateFilenameValue())) #else XML_DEPRECATED XMLPUBVAR xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValue; #endif XML_DEPRECATED XMLPUBFUN xmlOutputBufferCreateFilenameFunc * __xmlOutputBufferCreateFilenameValue(void); #ifdef LIBXML_THREAD_ENABLED #define xmlOutputBufferCreateFilenameValue \ (*(__xmlOutputBufferCreateFilenameValue())) #else XML_DEPRECATED XMLPUBVAR xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue; #endif #ifdef __cplusplus } #endif #endif /* __XML_GLOBALS_H */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/hash.h ================================================ /* * Summary: Chained hash tables * Description: This module implements the hash table support used in * various places in the library. * * Copy: See Copyright for the status of this software. * * Author: Bjorn Reese */ #ifndef __XML_HASH_H__ #define __XML_HASH_H__ #ifdef __cplusplus extern "C" { #endif /* * The hash table. */ typedef struct _xmlHashTable xmlHashTable; typedef xmlHashTable *xmlHashTablePtr; #ifdef __cplusplus } #endif #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Recent version of gcc produce a warning when a function pointer is assigned * to an object pointer, or vice versa. The following macro is a dirty hack * to allow suppression of the warning. If your architecture has function * pointers which are a different size than a void pointer, there may be some * serious trouble within the library. */ /** * XML_CAST_FPTR: * @fptr: pointer to a function * * Macro to do a casting from an object pointer to a * function pointer without encountering a warning from * gcc * * #define XML_CAST_FPTR(fptr) (*(void **)(&fptr)) * This macro violated ISO C aliasing rules (gcc4 on s390 broke) * so it is disabled now */ #define XML_CAST_FPTR(fptr) fptr /* * function types: */ /** * xmlHashDeallocator: * @payload: the data in the hash * @name: the name associated * * Callback to free data from a hash. */ typedef void (*xmlHashDeallocator)(void *payload, const xmlChar *name); /** * xmlHashCopier: * @payload: the data in the hash * @name: the name associated * * Callback to copy data from a hash. * * Returns a copy of the data or NULL in case of error. */ typedef void *(*xmlHashCopier)(void *payload, const xmlChar *name); /** * xmlHashScanner: * @payload: the data in the hash * @data: extra scanner data * @name: the name associated * * Callback when scanning data in a hash with the simple scanner. */ typedef void (*xmlHashScanner)(void *payload, void *data, const xmlChar *name); /** * xmlHashScannerFull: * @payload: the data in the hash * @data: extra scanner data * @name: the name associated * @name2: the second name associated * @name3: the third name associated * * Callback when scanning data in a hash with the full scanner. */ typedef void (*xmlHashScannerFull)(void *payload, void *data, const xmlChar *name, const xmlChar *name2, const xmlChar *name3); /* * Constructor and destructor. */ XMLPUBFUN xmlHashTablePtr xmlHashCreate (int size); XMLPUBFUN xmlHashTablePtr xmlHashCreateDict(int size, xmlDictPtr dict); XMLPUBFUN void xmlHashFree (xmlHashTablePtr table, xmlHashDeallocator f); XMLPUBFUN void xmlHashDefaultDeallocator(void *entry, const xmlChar *name); /* * Add a new entry to the hash table. */ XMLPUBFUN int xmlHashAddEntry (xmlHashTablePtr table, const xmlChar *name, void *userdata); XMLPUBFUN int xmlHashUpdateEntry(xmlHashTablePtr table, const xmlChar *name, void *userdata, xmlHashDeallocator f); XMLPUBFUN int xmlHashAddEntry2(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, void *userdata); XMLPUBFUN int xmlHashUpdateEntry2(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, void *userdata, xmlHashDeallocator f); XMLPUBFUN int xmlHashAddEntry3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, void *userdata); XMLPUBFUN int xmlHashUpdateEntry3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, void *userdata, xmlHashDeallocator f); /* * Remove an entry from the hash table. */ XMLPUBFUN int xmlHashRemoveEntry(xmlHashTablePtr table, const xmlChar *name, xmlHashDeallocator f); XMLPUBFUN int xmlHashRemoveEntry2(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, xmlHashDeallocator f); XMLPUBFUN int xmlHashRemoveEntry3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, xmlHashDeallocator f); /* * Retrieve the userdata. */ XMLPUBFUN void * xmlHashLookup (xmlHashTablePtr table, const xmlChar *name); XMLPUBFUN void * xmlHashLookup2 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2); XMLPUBFUN void * xmlHashLookup3 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3); XMLPUBFUN void * xmlHashQLookup (xmlHashTablePtr table, const xmlChar *name, const xmlChar *prefix); XMLPUBFUN void * xmlHashQLookup2 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *prefix, const xmlChar *name2, const xmlChar *prefix2); XMLPUBFUN void * xmlHashQLookup3 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *prefix, const xmlChar *name2, const xmlChar *prefix2, const xmlChar *name3, const xmlChar *prefix3); /* * Helpers. */ XMLPUBFUN xmlHashTablePtr xmlHashCopy (xmlHashTablePtr table, xmlHashCopier f); XMLPUBFUN int xmlHashSize (xmlHashTablePtr table); XMLPUBFUN void xmlHashScan (xmlHashTablePtr table, xmlHashScanner f, void *data); XMLPUBFUN void xmlHashScan3 (xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, xmlHashScanner f, void *data); XMLPUBFUN void xmlHashScanFull (xmlHashTablePtr table, xmlHashScannerFull f, void *data); XMLPUBFUN void xmlHashScanFull3(xmlHashTablePtr table, const xmlChar *name, const xmlChar *name2, const xmlChar *name3, xmlHashScannerFull f, void *data); #ifdef __cplusplus } #endif #endif /* ! __XML_HASH_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/list.h ================================================ /* * Summary: lists interfaces * Description: this module implement the list support used in * various place in the library. * * Copy: See Copyright for the status of this software. * * Author: Gary Pennington */ #ifndef __XML_LINK_INCLUDE__ #define __XML_LINK_INCLUDE__ #include #ifdef __cplusplus extern "C" { #endif typedef struct _xmlLink xmlLink; typedef xmlLink *xmlLinkPtr; typedef struct _xmlList xmlList; typedef xmlList *xmlListPtr; /** * xmlListDeallocator: * @lk: the data to deallocate * * Callback function used to free data from a list. */ typedef void (*xmlListDeallocator) (xmlLinkPtr lk); /** * xmlListDataCompare: * @data0: the first data * @data1: the second data * * Callback function used to compare 2 data. * * Returns 0 is equality, -1 or 1 otherwise depending on the ordering. */ typedef int (*xmlListDataCompare) (const void *data0, const void *data1); /** * xmlListWalker: * @data: the data found in the list * @user: extra user provided data to the walker * * Callback function used when walking a list with xmlListWalk(). * * Returns 0 to stop walking the list, 1 otherwise. */ typedef int (*xmlListWalker) (const void *data, void *user); /* Creation/Deletion */ XMLPUBFUN xmlListPtr xmlListCreate (xmlListDeallocator deallocator, xmlListDataCompare compare); XMLPUBFUN void xmlListDelete (xmlListPtr l); /* Basic Operators */ XMLPUBFUN void * xmlListSearch (xmlListPtr l, void *data); XMLPUBFUN void * xmlListReverseSearch (xmlListPtr l, void *data); XMLPUBFUN int xmlListInsert (xmlListPtr l, void *data) ; XMLPUBFUN int xmlListAppend (xmlListPtr l, void *data) ; XMLPUBFUN int xmlListRemoveFirst (xmlListPtr l, void *data); XMLPUBFUN int xmlListRemoveLast (xmlListPtr l, void *data); XMLPUBFUN int xmlListRemoveAll (xmlListPtr l, void *data); XMLPUBFUN void xmlListClear (xmlListPtr l); XMLPUBFUN int xmlListEmpty (xmlListPtr l); XMLPUBFUN xmlLinkPtr xmlListFront (xmlListPtr l); XMLPUBFUN xmlLinkPtr xmlListEnd (xmlListPtr l); XMLPUBFUN int xmlListSize (xmlListPtr l); XMLPUBFUN void xmlListPopFront (xmlListPtr l); XMLPUBFUN void xmlListPopBack (xmlListPtr l); XMLPUBFUN int xmlListPushFront (xmlListPtr l, void *data); XMLPUBFUN int xmlListPushBack (xmlListPtr l, void *data); /* Advanced Operators */ XMLPUBFUN void xmlListReverse (xmlListPtr l); XMLPUBFUN void xmlListSort (xmlListPtr l); XMLPUBFUN void xmlListWalk (xmlListPtr l, xmlListWalker walker, void *user); XMLPUBFUN void xmlListReverseWalk (xmlListPtr l, xmlListWalker walker, void *user); XMLPUBFUN void xmlListMerge (xmlListPtr l1, xmlListPtr l2); XMLPUBFUN xmlListPtr xmlListDup (const xmlListPtr old); XMLPUBFUN int xmlListCopy (xmlListPtr cur, const xmlListPtr old); /* Link operators */ XMLPUBFUN void * xmlLinkGetData (xmlLinkPtr lk); /* xmlListUnique() */ /* xmlListSwap */ #ifdef __cplusplus } #endif #endif /* __XML_LINK_INCLUDE__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/nanoftp.h ================================================ /* * Summary: minimal FTP implementation * Description: minimal FTP implementation allowing to fetch resources * like external subset. This module is DEPRECATED, do not * use any of its functions. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __NANO_FTP_H__ #define __NANO_FTP_H__ #include #ifdef LIBXML_FTP_ENABLED /* Needed for portability to Windows 64 bits */ #if defined(_WIN32) #include #else /** * SOCKET: * * macro used to provide portability of code to windows sockets */ #define SOCKET int /** * INVALID_SOCKET: * * macro used to provide portability of code to windows sockets * the value to be used when the socket is not valid */ #undef INVALID_SOCKET #define INVALID_SOCKET (-1) #endif #ifdef __cplusplus extern "C" { #endif /** * ftpListCallback: * @userData: user provided data for the callback * @filename: the file name (including "->" when links are shown) * @attrib: the attribute string * @owner: the owner string * @group: the group string * @size: the file size * @links: the link count * @year: the year * @month: the month * @day: the day * @hour: the hour * @minute: the minute * * A callback for the xmlNanoFTPList command. * Note that only one of year and day:minute are specified. */ typedef void (*ftpListCallback) (void *userData, const char *filename, const char *attrib, const char *owner, const char *group, unsigned long size, int links, int year, const char *month, int day, int hour, int minute); /** * ftpDataCallback: * @userData: the user provided context * @data: the data received * @len: its size in bytes * * A callback for the xmlNanoFTPGet command. */ typedef void (*ftpDataCallback) (void *userData, const char *data, int len); /* * Init */ XML_DEPRECATED XMLPUBFUN void xmlNanoFTPInit (void); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPCleanup (void); /* * Creating/freeing contexts. */ XML_DEPRECATED XMLPUBFUN void * xmlNanoFTPNewCtxt (const char *URL); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPFreeCtxt (void * ctx); XML_DEPRECATED XMLPUBFUN void * xmlNanoFTPConnectTo (const char *server, int port); /* * Opening/closing session connections. */ XML_DEPRECATED XMLPUBFUN void * xmlNanoFTPOpen (const char *URL); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPConnect (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPClose (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPQuit (void *ctx); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPScanProxy (const char *URL); XML_DEPRECATED XMLPUBFUN void xmlNanoFTPProxy (const char *host, int port, const char *user, const char *passwd, int type); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPUpdateURL (void *ctx, const char *URL); /* * Rather internal commands. */ XML_DEPRECATED XMLPUBFUN int xmlNanoFTPGetResponse (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPCheckResponse (void *ctx); /* * CD/DIR/GET handlers. */ XML_DEPRECATED XMLPUBFUN int xmlNanoFTPCwd (void *ctx, const char *directory); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPDele (void *ctx, const char *file); XML_DEPRECATED XMLPUBFUN SOCKET xmlNanoFTPGetConnection (void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPCloseConnection(void *ctx); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPList (void *ctx, ftpListCallback callback, void *userData, const char *filename); XML_DEPRECATED XMLPUBFUN SOCKET xmlNanoFTPGetSocket (void *ctx, const char *filename); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPGet (void *ctx, ftpDataCallback callback, void *userData, const char *filename); XML_DEPRECATED XMLPUBFUN int xmlNanoFTPRead (void *ctx, void *dest, int len); #ifdef __cplusplus } #endif #endif /* LIBXML_FTP_ENABLED */ #endif /* __NANO_FTP_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/nanohttp.h ================================================ /* * Summary: minimal HTTP implementation * Description: minimal HTTP implementation allowing to fetch resources * like external subset. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __NANO_HTTP_H__ #define __NANO_HTTP_H__ #include #ifdef LIBXML_HTTP_ENABLED #ifdef __cplusplus extern "C" { #endif XMLPUBFUN void xmlNanoHTTPInit (void); XMLPUBFUN void xmlNanoHTTPCleanup (void); XMLPUBFUN void xmlNanoHTTPScanProxy (const char *URL); XMLPUBFUN int xmlNanoHTTPFetch (const char *URL, const char *filename, char **contentType); XMLPUBFUN void * xmlNanoHTTPMethod (const char *URL, const char *method, const char *input, char **contentType, const char *headers, int ilen); XMLPUBFUN void * xmlNanoHTTPMethodRedir (const char *URL, const char *method, const char *input, char **contentType, char **redir, const char *headers, int ilen); XMLPUBFUN void * xmlNanoHTTPOpen (const char *URL, char **contentType); XMLPUBFUN void * xmlNanoHTTPOpenRedir (const char *URL, char **contentType, char **redir); XMLPUBFUN int xmlNanoHTTPReturnCode (void *ctx); XMLPUBFUN const char * xmlNanoHTTPAuthHeader (void *ctx); XMLPUBFUN const char * xmlNanoHTTPRedir (void *ctx); XMLPUBFUN int xmlNanoHTTPContentLength( void * ctx ); XMLPUBFUN const char * xmlNanoHTTPEncoding (void *ctx); XMLPUBFUN const char * xmlNanoHTTPMimeType (void *ctx); XMLPUBFUN int xmlNanoHTTPRead (void *ctx, void *dest, int len); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN int xmlNanoHTTPSave (void *ctxt, const char *filename); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN void xmlNanoHTTPClose (void *ctx); #ifdef __cplusplus } #endif #endif /* LIBXML_HTTP_ENABLED */ #endif /* __NANO_HTTP_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/parser.h ================================================ /* * Summary: the core parser module * Description: Interfaces, constants and types related to the XML parser * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_PARSER_H__ #define __XML_PARSER_H__ #include #include #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif /** * XML_DEFAULT_VERSION: * * The default version of XML used: 1.0 */ #define XML_DEFAULT_VERSION "1.0" /** * xmlParserInput: * * An xmlParserInput is an input flow for the XML processor. * Each entity parsed is associated an xmlParserInput (except the * few predefined ones). This is the case both for internal entities * - in which case the flow is already completely in memory - or * external entities - in which case we use the buf structure for * progressive reading and I18N conversions to the internal UTF-8 format. */ /** * xmlParserInputDeallocate: * @str: the string to deallocate * * Callback for freeing some parser input allocations. */ typedef void (* xmlParserInputDeallocate)(xmlChar *str); struct _xmlParserInput { /* Input buffer */ xmlParserInputBufferPtr buf; /* UTF-8 encoded buffer */ const char *filename; /* The file analyzed, if any */ const char *directory; /* the directory/base of the file */ const xmlChar *base; /* Base of the array to parse */ const xmlChar *cur; /* Current char being parsed */ const xmlChar *end; /* end of the array to parse */ int length; /* length if known */ int line; /* Current line */ int col; /* Current column */ unsigned long consumed; /* How many xmlChars already consumed */ xmlParserInputDeallocate free; /* function to deallocate the base */ const xmlChar *encoding; /* the encoding string for entity */ const xmlChar *version; /* the version string for entity */ int standalone; /* Was that entity marked standalone */ int id; /* an unique identifier for the entity */ unsigned long parentConsumed; /* consumed bytes from parents */ xmlEntityPtr entity; /* entity, if any */ }; /** * xmlParserNodeInfo: * * The parser can be asked to collect Node information, i.e. at what * place in the file they were detected. * NOTE: This is off by default and not very well tested. */ typedef struct _xmlParserNodeInfo xmlParserNodeInfo; typedef xmlParserNodeInfo *xmlParserNodeInfoPtr; struct _xmlParserNodeInfo { const struct _xmlNode* node; /* Position & line # that text that created the node begins & ends on */ unsigned long begin_pos; unsigned long begin_line; unsigned long end_pos; unsigned long end_line; }; typedef struct _xmlParserNodeInfoSeq xmlParserNodeInfoSeq; typedef xmlParserNodeInfoSeq *xmlParserNodeInfoSeqPtr; struct _xmlParserNodeInfoSeq { unsigned long maximum; unsigned long length; xmlParserNodeInfo* buffer; }; /** * xmlParserInputState: * * The parser is now working also as a state based parser. * The recursive one use the state info for entities processing. */ typedef enum { XML_PARSER_EOF = -1, /* nothing is to be parsed */ XML_PARSER_START = 0, /* nothing has been parsed */ XML_PARSER_MISC, /* Misc* before int subset */ XML_PARSER_PI, /* Within a processing instruction */ XML_PARSER_DTD, /* within some DTD content */ XML_PARSER_PROLOG, /* Misc* after internal subset */ XML_PARSER_COMMENT, /* within a comment */ XML_PARSER_START_TAG, /* within a start tag */ XML_PARSER_CONTENT, /* within the content */ XML_PARSER_CDATA_SECTION, /* within a CDATA section */ XML_PARSER_END_TAG, /* within a closing tag */ XML_PARSER_ENTITY_DECL, /* within an entity declaration */ XML_PARSER_ENTITY_VALUE, /* within an entity value in a decl */ XML_PARSER_ATTRIBUTE_VALUE, /* within an attribute value */ XML_PARSER_SYSTEM_LITERAL, /* within a SYSTEM value */ XML_PARSER_EPILOG, /* the Misc* after the last end tag */ XML_PARSER_IGNORE, /* within an IGNORED section */ XML_PARSER_PUBLIC_LITERAL /* within a PUBLIC value */ } xmlParserInputState; /** * XML_DETECT_IDS: * * Bit in the loadsubset context field to tell to do ID/REFs lookups. * Use it to initialize xmlLoadExtDtdDefaultValue. */ #define XML_DETECT_IDS 2 /** * XML_COMPLETE_ATTRS: * * Bit in the loadsubset context field to tell to do complete the * elements attributes lists with the ones defaulted from the DTDs. * Use it to initialize xmlLoadExtDtdDefaultValue. */ #define XML_COMPLETE_ATTRS 4 /** * XML_SKIP_IDS: * * Bit in the loadsubset context field to tell to not do ID/REFs registration. * Used to initialize xmlLoadExtDtdDefaultValue in some special cases. */ #define XML_SKIP_IDS 8 /** * xmlParserMode: * * A parser can operate in various modes */ typedef enum { XML_PARSE_UNKNOWN = 0, XML_PARSE_DOM = 1, XML_PARSE_SAX = 2, XML_PARSE_PUSH_DOM = 3, XML_PARSE_PUSH_SAX = 4, XML_PARSE_READER = 5 } xmlParserMode; typedef struct _xmlStartTag xmlStartTag; /** * xmlParserCtxt: * * The parser context. * NOTE This doesn't completely define the parser state, the (current ?) * design of the parser uses recursive function calls since this allow * and easy mapping from the production rules of the specification * to the actual code. The drawback is that the actual function call * also reflect the parser state. However most of the parsing routines * takes as the only argument the parser context pointer, so migrating * to a state based parser for progressive parsing shouldn't be too hard. */ struct _xmlParserCtxt { struct _xmlSAXHandler *sax; /* The SAX handler */ void *userData; /* For SAX interface only, used by DOM build */ xmlDocPtr myDoc; /* the document being built */ int wellFormed; /* is the document well formed */ int replaceEntities; /* shall we replace entities ? */ const xmlChar *version; /* the XML version string */ const xmlChar *encoding; /* the declared encoding, if any */ int standalone; /* standalone document */ int html; /* an HTML(1) document * 3 is HTML after * 10 is HTML after */ /* Input stream stack */ xmlParserInputPtr input; /* Current input stream */ int inputNr; /* Number of current input streams */ int inputMax; /* Max number of input streams */ xmlParserInputPtr *inputTab; /* stack of inputs */ /* Node analysis stack only used for DOM building */ xmlNodePtr node; /* Current parsed Node */ int nodeNr; /* Depth of the parsing stack */ int nodeMax; /* Max depth of the parsing stack */ xmlNodePtr *nodeTab; /* array of nodes */ int record_info; /* Whether node info should be kept */ xmlParserNodeInfoSeq node_seq; /* info about each node parsed */ int errNo; /* error code */ int hasExternalSubset; /* reference and external subset */ int hasPErefs; /* the internal subset has PE refs */ int external; /* are we parsing an external entity */ int valid; /* is the document valid */ int validate; /* shall we try to validate ? */ xmlValidCtxt vctxt; /* The validity context */ xmlParserInputState instate; /* current type of input */ int token; /* next char look-ahead */ char *directory; /* the data directory */ /* Node name stack */ const xmlChar *name; /* Current parsed Node */ int nameNr; /* Depth of the parsing stack */ int nameMax; /* Max depth of the parsing stack */ const xmlChar * *nameTab; /* array of nodes */ long nbChars; /* unused */ long checkIndex; /* used by progressive parsing lookup */ int keepBlanks; /* ugly but ... */ int disableSAX; /* SAX callbacks are disabled */ int inSubset; /* Parsing is in int 1/ext 2 subset */ const xmlChar * intSubName; /* name of subset */ xmlChar * extSubURI; /* URI of external subset */ xmlChar * extSubSystem; /* SYSTEM ID of external subset */ /* xml:space values */ int * space; /* Should the parser preserve spaces */ int spaceNr; /* Depth of the parsing stack */ int spaceMax; /* Max depth of the parsing stack */ int * spaceTab; /* array of space infos */ int depth; /* to prevent entity substitution loops */ xmlParserInputPtr entity; /* used to check entities boundaries */ int charset; /* encoding of the in-memory content actually an xmlCharEncoding */ int nodelen; /* Those two fields are there to */ int nodemem; /* Speed up large node parsing */ int pedantic; /* signal pedantic warnings */ void *_private; /* For user data, libxml won't touch it */ int loadsubset; /* should the external subset be loaded */ int linenumbers; /* set line number in element content */ void *catalogs; /* document's own catalog */ int recovery; /* run in recovery mode */ int progressive; /* is this a progressive parsing */ xmlDictPtr dict; /* dictionary for the parser */ const xmlChar * *atts; /* array for the attributes callbacks */ int maxatts; /* the size of the array */ int docdict; /* use strings from dict to build tree */ /* * pre-interned strings */ const xmlChar *str_xml; const xmlChar *str_xmlns; const xmlChar *str_xml_ns; /* * Everything below is used only by the new SAX mode */ int sax2; /* operating in the new SAX mode */ int nsNr; /* the number of inherited namespaces */ int nsMax; /* the size of the arrays */ const xmlChar * *nsTab; /* the array of prefix/namespace name */ int *attallocs; /* which attribute were allocated */ xmlStartTag *pushTab; /* array of data for push */ xmlHashTablePtr attsDefault; /* defaulted attributes if any */ xmlHashTablePtr attsSpecial; /* non-CDATA attributes if any */ int nsWellFormed; /* is the document XML Namespace okay */ int options; /* Extra options */ /* * Those fields are needed only for streaming parsing so far */ int dictNames; /* Use dictionary names for the tree */ int freeElemsNr; /* number of freed element nodes */ xmlNodePtr freeElems; /* List of freed element nodes */ int freeAttrsNr; /* number of freed attributes nodes */ xmlAttrPtr freeAttrs; /* List of freed attributes nodes */ /* * the complete error information for the last error. */ xmlError lastError; xmlParserMode parseMode; /* the parser mode */ unsigned long nbentities; /* unused */ unsigned long sizeentities; /* size of parsed entities */ /* for use by HTML non-recursive parser */ xmlParserNodeInfo *nodeInfo; /* Current NodeInfo */ int nodeInfoNr; /* Depth of the parsing stack */ int nodeInfoMax; /* Max depth of the parsing stack */ xmlParserNodeInfo *nodeInfoTab; /* array of nodeInfos */ int input_id; /* we need to label inputs */ unsigned long sizeentcopy; /* volume of entity copy */ int endCheckState; /* quote state for push parser */ unsigned short nbErrors; /* number of errors */ unsigned short nbWarnings; /* number of warnings */ }; /** * xmlSAXLocator: * * A SAX Locator. */ struct _xmlSAXLocator { const xmlChar *(*getPublicId)(void *ctx); const xmlChar *(*getSystemId)(void *ctx); int (*getLineNumber)(void *ctx); int (*getColumnNumber)(void *ctx); }; /** * xmlSAXHandler: * * A SAX handler is bunch of callbacks called by the parser when processing * of the input generate data or structure information. */ /** * resolveEntitySAXFunc: * @ctx: the user data (XML parser context) * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * Callback: * The entity loader, to control the loading of external entities, * the application can either: * - override this resolveEntity() callback in the SAX block * - or better use the xmlSetExternalEntityLoader() function to * set up it's own entity resolution routine * * Returns the xmlParserInputPtr if inlined or NULL for DOM behaviour. */ typedef xmlParserInputPtr (*resolveEntitySAXFunc) (void *ctx, const xmlChar *publicId, const xmlChar *systemId); /** * internalSubsetSAXFunc: * @ctx: the user data (XML parser context) * @name: the root element name * @ExternalID: the external ID * @SystemID: the SYSTEM ID (e.g. filename or URL) * * Callback on internal subset declaration. */ typedef void (*internalSubsetSAXFunc) (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); /** * externalSubsetSAXFunc: * @ctx: the user data (XML parser context) * @name: the root element name * @ExternalID: the external ID * @SystemID: the SYSTEM ID (e.g. filename or URL) * * Callback on external subset declaration. */ typedef void (*externalSubsetSAXFunc) (void *ctx, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); /** * getEntitySAXFunc: * @ctx: the user data (XML parser context) * @name: The entity name * * Get an entity by name. * * Returns the xmlEntityPtr if found. */ typedef xmlEntityPtr (*getEntitySAXFunc) (void *ctx, const xmlChar *name); /** * getParameterEntitySAXFunc: * @ctx: the user data (XML parser context) * @name: The entity name * * Get a parameter entity by name. * * Returns the xmlEntityPtr if found. */ typedef xmlEntityPtr (*getParameterEntitySAXFunc) (void *ctx, const xmlChar *name); /** * entityDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: the entity name * @type: the entity type * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @content: the entity value (without processing). * * An entity definition has been parsed. */ typedef void (*entityDeclSAXFunc) (void *ctx, const xmlChar *name, int type, const xmlChar *publicId, const xmlChar *systemId, xmlChar *content); /** * notationDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: The name of the notation * @publicId: The public ID of the entity * @systemId: The system ID of the entity * * What to do when a notation declaration has been parsed. */ typedef void (*notationDeclSAXFunc)(void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId); /** * attributeDeclSAXFunc: * @ctx: the user data (XML parser context) * @elem: the name of the element * @fullname: the attribute name * @type: the attribute type * @def: the type of default value * @defaultValue: the attribute default value * @tree: the tree of enumerated value set * * An attribute definition has been parsed. */ typedef void (*attributeDeclSAXFunc)(void *ctx, const xmlChar *elem, const xmlChar *fullname, int type, int def, const xmlChar *defaultValue, xmlEnumerationPtr tree); /** * elementDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: the element name * @type: the element type * @content: the element value tree * * An element definition has been parsed. */ typedef void (*elementDeclSAXFunc)(void *ctx, const xmlChar *name, int type, xmlElementContentPtr content); /** * unparsedEntityDeclSAXFunc: * @ctx: the user data (XML parser context) * @name: The name of the entity * @publicId: The public ID of the entity * @systemId: The system ID of the entity * @notationName: the name of the notation * * What to do when an unparsed entity declaration is parsed. */ typedef void (*unparsedEntityDeclSAXFunc)(void *ctx, const xmlChar *name, const xmlChar *publicId, const xmlChar *systemId, const xmlChar *notationName); /** * setDocumentLocatorSAXFunc: * @ctx: the user data (XML parser context) * @loc: A SAX Locator * * Receive the document locator at startup, actually xmlDefaultSAXLocator. * Everything is available on the context, so this is useless in our case. */ typedef void (*setDocumentLocatorSAXFunc) (void *ctx, xmlSAXLocatorPtr loc); /** * startDocumentSAXFunc: * @ctx: the user data (XML parser context) * * Called when the document start being processed. */ typedef void (*startDocumentSAXFunc) (void *ctx); /** * endDocumentSAXFunc: * @ctx: the user data (XML parser context) * * Called when the document end has been detected. */ typedef void (*endDocumentSAXFunc) (void *ctx); /** * startElementSAXFunc: * @ctx: the user data (XML parser context) * @name: The element name, including namespace prefix * @atts: An array of name/value attributes pairs, NULL terminated * * Called when an opening tag has been processed. */ typedef void (*startElementSAXFunc) (void *ctx, const xmlChar *name, const xmlChar **atts); /** * endElementSAXFunc: * @ctx: the user data (XML parser context) * @name: The element name * * Called when the end of an element has been detected. */ typedef void (*endElementSAXFunc) (void *ctx, const xmlChar *name); /** * attributeSAXFunc: * @ctx: the user data (XML parser context) * @name: The attribute name, including namespace prefix * @value: The attribute value * * Handle an attribute that has been read by the parser. * The default handling is to convert the attribute into an * DOM subtree and past it in a new xmlAttr element added to * the element. */ typedef void (*attributeSAXFunc) (void *ctx, const xmlChar *name, const xmlChar *value); /** * referenceSAXFunc: * @ctx: the user data (XML parser context) * @name: The entity name * * Called when an entity reference is detected. */ typedef void (*referenceSAXFunc) (void *ctx, const xmlChar *name); /** * charactersSAXFunc: * @ctx: the user data (XML parser context) * @ch: a xmlChar string * @len: the number of xmlChar * * Receiving some chars from the parser. */ typedef void (*charactersSAXFunc) (void *ctx, const xmlChar *ch, int len); /** * ignorableWhitespaceSAXFunc: * @ctx: the user data (XML parser context) * @ch: a xmlChar string * @len: the number of xmlChar * * Receiving some ignorable whitespaces from the parser. * UNUSED: by default the DOM building will use characters. */ typedef void (*ignorableWhitespaceSAXFunc) (void *ctx, const xmlChar *ch, int len); /** * processingInstructionSAXFunc: * @ctx: the user data (XML parser context) * @target: the target name * @data: the PI data's * * A processing instruction has been parsed. */ typedef void (*processingInstructionSAXFunc) (void *ctx, const xmlChar *target, const xmlChar *data); /** * commentSAXFunc: * @ctx: the user data (XML parser context) * @value: the comment content * * A comment has been parsed. */ typedef void (*commentSAXFunc) (void *ctx, const xmlChar *value); /** * cdataBlockSAXFunc: * @ctx: the user data (XML parser context) * @value: The pcdata content * @len: the block length * * Called when a pcdata block has been parsed. */ typedef void (*cdataBlockSAXFunc) ( void *ctx, const xmlChar *value, int len); /** * warningSAXFunc: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format a warning messages, callback. */ typedef void (*warningSAXFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * errorSAXFunc: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format an error messages, callback. */ typedef void (*errorSAXFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * fatalErrorSAXFunc: * @ctx: an XML parser context * @msg: the message to display/transmit * @...: extra parameters for the message display * * Display and format fatal error messages, callback. * Note: so far fatalError() SAX callbacks are not used, error() * get all the callbacks for errors. */ typedef void (*fatalErrorSAXFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * isStandaloneSAXFunc: * @ctx: the user data (XML parser context) * * Is this document tagged standalone? * * Returns 1 if true */ typedef int (*isStandaloneSAXFunc) (void *ctx); /** * hasInternalSubsetSAXFunc: * @ctx: the user data (XML parser context) * * Does this document has an internal subset. * * Returns 1 if true */ typedef int (*hasInternalSubsetSAXFunc) (void *ctx); /** * hasExternalSubsetSAXFunc: * @ctx: the user data (XML parser context) * * Does this document has an external subset? * * Returns 1 if true */ typedef int (*hasExternalSubsetSAXFunc) (void *ctx); /************************************************************************ * * * The SAX version 2 API extensions * * * ************************************************************************/ /** * XML_SAX2_MAGIC: * * Special constant found in SAX2 blocks initialized fields */ #define XML_SAX2_MAGIC 0xDEEDBEAF /** * startElementNsSAX2Func: * @ctx: the user data (XML parser context) * @localname: the local name of the element * @prefix: the element namespace prefix if available * @URI: the element namespace name if available * @nb_namespaces: number of namespace definitions on that node * @namespaces: pointer to the array of prefix/URI pairs namespace definitions * @nb_attributes: the number of attributes on that node * @nb_defaulted: the number of defaulted attributes. The defaulted * ones are at the end of the array * @attributes: pointer to the array of (localname/prefix/URI/value/end) * attribute values. * * SAX2 callback when an element start has been detected by the parser. * It provides the namespace information for the element, as well as * the new namespace declarations on the element. */ typedef void (*startElementNsSAX2Func) (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI, int nb_namespaces, const xmlChar **namespaces, int nb_attributes, int nb_defaulted, const xmlChar **attributes); /** * endElementNsSAX2Func: * @ctx: the user data (XML parser context) * @localname: the local name of the element * @prefix: the element namespace prefix if available * @URI: the element namespace name if available * * SAX2 callback when an element end has been detected by the parser. * It provides the namespace information for the element. */ typedef void (*endElementNsSAX2Func) (void *ctx, const xmlChar *localname, const xmlChar *prefix, const xmlChar *URI); struct _xmlSAXHandler { internalSubsetSAXFunc internalSubset; isStandaloneSAXFunc isStandalone; hasInternalSubsetSAXFunc hasInternalSubset; hasExternalSubsetSAXFunc hasExternalSubset; resolveEntitySAXFunc resolveEntity; getEntitySAXFunc getEntity; entityDeclSAXFunc entityDecl; notationDeclSAXFunc notationDecl; attributeDeclSAXFunc attributeDecl; elementDeclSAXFunc elementDecl; unparsedEntityDeclSAXFunc unparsedEntityDecl; setDocumentLocatorSAXFunc setDocumentLocator; startDocumentSAXFunc startDocument; endDocumentSAXFunc endDocument; startElementSAXFunc startElement; endElementSAXFunc endElement; referenceSAXFunc reference; charactersSAXFunc characters; ignorableWhitespaceSAXFunc ignorableWhitespace; processingInstructionSAXFunc processingInstruction; commentSAXFunc comment; warningSAXFunc warning; errorSAXFunc error; fatalErrorSAXFunc fatalError; /* unused error() get all the errors */ getParameterEntitySAXFunc getParameterEntity; cdataBlockSAXFunc cdataBlock; externalSubsetSAXFunc externalSubset; unsigned int initialized; /* The following fields are extensions available only on version 2 */ void *_private; startElementNsSAX2Func startElementNs; endElementNsSAX2Func endElementNs; xmlStructuredErrorFunc serror; }; /* * SAX Version 1 */ typedef struct _xmlSAXHandlerV1 xmlSAXHandlerV1; typedef xmlSAXHandlerV1 *xmlSAXHandlerV1Ptr; struct _xmlSAXHandlerV1 { internalSubsetSAXFunc internalSubset; isStandaloneSAXFunc isStandalone; hasInternalSubsetSAXFunc hasInternalSubset; hasExternalSubsetSAXFunc hasExternalSubset; resolveEntitySAXFunc resolveEntity; getEntitySAXFunc getEntity; entityDeclSAXFunc entityDecl; notationDeclSAXFunc notationDecl; attributeDeclSAXFunc attributeDecl; elementDeclSAXFunc elementDecl; unparsedEntityDeclSAXFunc unparsedEntityDecl; setDocumentLocatorSAXFunc setDocumentLocator; startDocumentSAXFunc startDocument; endDocumentSAXFunc endDocument; startElementSAXFunc startElement; endElementSAXFunc endElement; referenceSAXFunc reference; charactersSAXFunc characters; ignorableWhitespaceSAXFunc ignorableWhitespace; processingInstructionSAXFunc processingInstruction; commentSAXFunc comment; warningSAXFunc warning; errorSAXFunc error; fatalErrorSAXFunc fatalError; /* unused error() get all the errors */ getParameterEntitySAXFunc getParameterEntity; cdataBlockSAXFunc cdataBlock; externalSubsetSAXFunc externalSubset; unsigned int initialized; }; /** * xmlExternalEntityLoader: * @URL: The System ID of the resource requested * @ID: The Public ID of the resource requested * @context: the XML parser context * * External entity loaders types. * * Returns the entity input parser. */ typedef xmlParserInputPtr (*xmlExternalEntityLoader) (const char *URL, const char *ID, xmlParserCtxtPtr context); #ifdef __cplusplus } #endif #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Init/Cleanup */ XMLPUBFUN void xmlInitParser (void); XMLPUBFUN void xmlCleanupParser (void); /* * Input functions */ XML_DEPRECATED XMLPUBFUN int xmlParserInputRead (xmlParserInputPtr in, int len); XML_DEPRECATED XMLPUBFUN int xmlParserInputGrow (xmlParserInputPtr in, int len); /* * Basic parsing Interfaces */ #ifdef LIBXML_SAX1_ENABLED XMLPUBFUN xmlDocPtr xmlParseDoc (const xmlChar *cur); XMLPUBFUN xmlDocPtr xmlParseFile (const char *filename); XMLPUBFUN xmlDocPtr xmlParseMemory (const char *buffer, int size); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN int xmlSubstituteEntitiesDefault(int val); XMLPUBFUN int xmlKeepBlanksDefault (int val); XMLPUBFUN void xmlStopParser (xmlParserCtxtPtr ctxt); XMLPUBFUN int xmlPedanticParserDefault(int val); XMLPUBFUN int xmlLineNumbersDefault (int val); #ifdef LIBXML_SAX1_ENABLED /* * Recovery mode */ XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlRecoverDoc (const xmlChar *cur); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlRecoverMemory (const char *buffer, int size); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlRecoverFile (const char *filename); #endif /* LIBXML_SAX1_ENABLED */ /* * Less common routines and SAX interfaces */ XMLPUBFUN int xmlParseDocument (xmlParserCtxtPtr ctxt); XMLPUBFUN int xmlParseExtParsedEnt (xmlParserCtxtPtr ctxt); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN int xmlSAXUserParseFile (xmlSAXHandlerPtr sax, void *user_data, const char *filename); XML_DEPRECATED XMLPUBFUN int xmlSAXUserParseMemory (xmlSAXHandlerPtr sax, void *user_data, const char *buffer, int size); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseDoc (xmlSAXHandlerPtr sax, const xmlChar *cur, int recovery); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseMemory (xmlSAXHandlerPtr sax, const char *buffer, int size, int recovery); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseMemoryWithData (xmlSAXHandlerPtr sax, const char *buffer, int size, int recovery, void *data); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseFile (xmlSAXHandlerPtr sax, const char *filename, int recovery); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseFileWithData (xmlSAXHandlerPtr sax, const char *filename, int recovery, void *data); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlSAXParseEntity (xmlSAXHandlerPtr sax, const char *filename); XML_DEPRECATED XMLPUBFUN xmlDocPtr xmlParseEntity (const char *filename); #endif /* LIBXML_SAX1_ENABLED */ #ifdef LIBXML_VALID_ENABLED XML_DEPRECATED XMLPUBFUN xmlDtdPtr xmlSAXParseDTD (xmlSAXHandlerPtr sax, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlParseDTD (const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlIOParseDTD (xmlSAXHandlerPtr sax, xmlParserInputBufferPtr input, xmlCharEncoding enc); #endif /* LIBXML_VALID_ENABLE */ #ifdef LIBXML_SAX1_ENABLED XMLPUBFUN int xmlParseBalancedChunkMemory(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN xmlParserErrors xmlParseInNodeContext (xmlNodePtr node, const char *data, int datalen, int options, xmlNodePtr *lst); #ifdef LIBXML_SAX1_ENABLED XMLPUBFUN int xmlParseBalancedChunkMemoryRecover(xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *string, xmlNodePtr *lst, int recover); XML_DEPRECATED XMLPUBFUN int xmlParseExternalEntity (xmlDocPtr doc, xmlSAXHandlerPtr sax, void *user_data, int depth, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN int xmlParseCtxtExternalEntity(xmlParserCtxtPtr ctx, const xmlChar *URL, const xmlChar *ID, xmlNodePtr *lst); /* * Parser contexts handling. */ XMLPUBFUN xmlParserCtxtPtr xmlNewParserCtxt (void); XMLPUBFUN xmlParserCtxtPtr xmlNewSAXParserCtxt (const xmlSAXHandler *sax, void *userData); XMLPUBFUN int xmlInitParserCtxt (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlClearParserCtxt (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlFreeParserCtxt (xmlParserCtxtPtr ctxt); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN void xmlSetupParserForBuffer (xmlParserCtxtPtr ctxt, const xmlChar* buffer, const char *filename); #endif /* LIBXML_SAX1_ENABLED */ XMLPUBFUN xmlParserCtxtPtr xmlCreateDocParserCtxt (const xmlChar *cur); #ifdef LIBXML_LEGACY_ENABLED /* * Reading/setting optional parsing features. */ XML_DEPRECATED XMLPUBFUN int xmlGetFeaturesList (int *len, const char **result); XML_DEPRECATED XMLPUBFUN int xmlGetFeature (xmlParserCtxtPtr ctxt, const char *name, void *result); XML_DEPRECATED XMLPUBFUN int xmlSetFeature (xmlParserCtxtPtr ctxt, const char *name, void *value); #endif /* LIBXML_LEGACY_ENABLED */ #ifdef LIBXML_PUSH_ENABLED /* * Interfaces for the Push mode. */ XMLPUBFUN xmlParserCtxtPtr xmlCreatePushParserCtxt(xmlSAXHandlerPtr sax, void *user_data, const char *chunk, int size, const char *filename); XMLPUBFUN int xmlParseChunk (xmlParserCtxtPtr ctxt, const char *chunk, int size, int terminate); #endif /* LIBXML_PUSH_ENABLED */ /* * Special I/O mode. */ XMLPUBFUN xmlParserCtxtPtr xmlCreateIOParserCtxt (xmlSAXHandlerPtr sax, void *user_data, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, xmlCharEncoding enc); XMLPUBFUN xmlParserInputPtr xmlNewIOInputStream (xmlParserCtxtPtr ctxt, xmlParserInputBufferPtr input, xmlCharEncoding enc); /* * Node infos. */ XMLPUBFUN const xmlParserNodeInfo* xmlParserFindNodeInfo (const xmlParserCtxtPtr ctxt, const xmlNodePtr node); XMLPUBFUN void xmlInitNodeInfoSeq (xmlParserNodeInfoSeqPtr seq); XMLPUBFUN void xmlClearNodeInfoSeq (xmlParserNodeInfoSeqPtr seq); XMLPUBFUN unsigned long xmlParserFindNodeInfoIndex(const xmlParserNodeInfoSeqPtr seq, const xmlNodePtr node); XMLPUBFUN void xmlParserAddNodeInfo (xmlParserCtxtPtr ctxt, const xmlParserNodeInfoPtr info); /* * External entities handling actually implemented in xmlIO. */ XMLPUBFUN void xmlSetExternalEntityLoader(xmlExternalEntityLoader f); XMLPUBFUN xmlExternalEntityLoader xmlGetExternalEntityLoader(void); XMLPUBFUN xmlParserInputPtr xmlLoadExternalEntity (const char *URL, const char *ID, xmlParserCtxtPtr ctxt); /* * Index lookup, actually implemented in the encoding module */ XMLPUBFUN long xmlByteConsumed (xmlParserCtxtPtr ctxt); /* * New set of simpler/more flexible APIs */ /** * xmlParserOption: * * This is the set of XML parser options that can be passed down * to the xmlReadDoc() and similar calls. */ typedef enum { XML_PARSE_RECOVER = 1<<0, /* recover on errors */ XML_PARSE_NOENT = 1<<1, /* substitute entities */ XML_PARSE_DTDLOAD = 1<<2, /* load the external subset */ XML_PARSE_DTDATTR = 1<<3, /* default DTD attributes */ XML_PARSE_DTDVALID = 1<<4, /* validate with the DTD */ XML_PARSE_NOERROR = 1<<5, /* suppress error reports */ XML_PARSE_NOWARNING = 1<<6, /* suppress warning reports */ XML_PARSE_PEDANTIC = 1<<7, /* pedantic error reporting */ XML_PARSE_NOBLANKS = 1<<8, /* remove blank nodes */ XML_PARSE_SAX1 = 1<<9, /* use the SAX1 interface internally */ XML_PARSE_XINCLUDE = 1<<10,/* Implement XInclude substitution */ XML_PARSE_NONET = 1<<11,/* Forbid network access */ XML_PARSE_NODICT = 1<<12,/* Do not reuse the context dictionary */ XML_PARSE_NSCLEAN = 1<<13,/* remove redundant namespaces declarations */ XML_PARSE_NOCDATA = 1<<14,/* merge CDATA as text nodes */ XML_PARSE_NOXINCNODE= 1<<15,/* do not generate XINCLUDE START/END nodes */ XML_PARSE_COMPACT = 1<<16,/* compact small text nodes; no modification of the tree allowed afterwards (will possibly crash if you try to modify the tree) */ XML_PARSE_OLD10 = 1<<17,/* parse using XML-1.0 before update 5 */ XML_PARSE_NOBASEFIX = 1<<18,/* do not fixup XINCLUDE xml:base uris */ XML_PARSE_HUGE = 1<<19,/* relax any hardcoded limit from the parser */ XML_PARSE_OLDSAX = 1<<20,/* parse using SAX2 interface before 2.7.0 */ XML_PARSE_IGNORE_ENC= 1<<21,/* ignore internal document encoding hint */ XML_PARSE_BIG_LINES = 1<<22 /* Store big lines numbers in text PSVI field */ } xmlParserOption; XMLPUBFUN void xmlCtxtReset (xmlParserCtxtPtr ctxt); XMLPUBFUN int xmlCtxtResetPush (xmlParserCtxtPtr ctxt, const char *chunk, int size, const char *filename, const char *encoding); XMLPUBFUN int xmlCtxtUseOptions (xmlParserCtxtPtr ctxt, int options); XMLPUBFUN xmlDocPtr xmlReadDoc (const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadFile (const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadMemory (const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadFd (int fd, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlReadIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadDoc (xmlParserCtxtPtr ctxt, const xmlChar *cur, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadFile (xmlParserCtxtPtr ctxt, const char *filename, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadMemory (xmlParserCtxtPtr ctxt, const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadFd (xmlParserCtxtPtr ctxt, int fd, const char *URL, const char *encoding, int options); XMLPUBFUN xmlDocPtr xmlCtxtReadIO (xmlParserCtxtPtr ctxt, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); /* * Library wide options */ /** * xmlFeature: * * Used to examine the existence of features that can be enabled * or disabled at compile-time. * They used to be called XML_FEATURE_xxx but this clashed with Expat */ typedef enum { XML_WITH_THREAD = 1, XML_WITH_TREE = 2, XML_WITH_OUTPUT = 3, XML_WITH_PUSH = 4, XML_WITH_READER = 5, XML_WITH_PATTERN = 6, XML_WITH_WRITER = 7, XML_WITH_SAX1 = 8, XML_WITH_FTP = 9, XML_WITH_HTTP = 10, XML_WITH_VALID = 11, XML_WITH_HTML = 12, XML_WITH_LEGACY = 13, XML_WITH_C14N = 14, XML_WITH_CATALOG = 15, XML_WITH_XPATH = 16, XML_WITH_XPTR = 17, XML_WITH_XINCLUDE = 18, XML_WITH_ICONV = 19, XML_WITH_ISO8859X = 20, XML_WITH_UNICODE = 21, XML_WITH_REGEXP = 22, XML_WITH_AUTOMATA = 23, XML_WITH_EXPR = 24, XML_WITH_SCHEMAS = 25, XML_WITH_SCHEMATRON = 26, XML_WITH_MODULES = 27, XML_WITH_DEBUG = 28, XML_WITH_DEBUG_MEM = 29, XML_WITH_DEBUG_RUN = 30, XML_WITH_ZLIB = 31, XML_WITH_ICU = 32, XML_WITH_LZMA = 33, XML_WITH_NONE = 99999 /* just to be sure of allocation size */ } xmlFeature; XMLPUBFUN int xmlHasFeature (xmlFeature feature); #ifdef __cplusplus } #endif #endif /* __XML_PARSER_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/parserInternals.h ================================================ /* * Summary: internals routines and limits exported by the parser. * Description: this module exports a number of internal parsing routines * they are not really all intended for applications but * can prove useful doing low level processing. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_PARSER_INTERNALS_H__ #define __XML_PARSER_INTERNALS_H__ #include #include #include #include #ifdef __cplusplus extern "C" { #endif /** * xmlParserMaxDepth: * * arbitrary depth limit for the XML documents that we allow to * process. This is not a limitation of the parser but a safety * boundary feature, use XML_PARSE_HUGE option to override it. */ XMLPUBVAR unsigned int xmlParserMaxDepth; /** * XML_MAX_TEXT_LENGTH: * * Maximum size allowed for a single text node when building a tree. * This is not a limitation of the parser but a safety boundary feature, * use XML_PARSE_HUGE option to override it. * Introduced in 2.9.0 */ #define XML_MAX_TEXT_LENGTH 10000000 /** * XML_MAX_HUGE_LENGTH: * * Maximum size allowed when XML_PARSE_HUGE is set. */ #define XML_MAX_HUGE_LENGTH 1000000000 /** * XML_MAX_NAME_LENGTH: * * Maximum size allowed for a markup identifier. * This is not a limitation of the parser but a safety boundary feature, * use XML_PARSE_HUGE option to override it. * Note that with the use of parsing dictionaries overriding the limit * may result in more runtime memory usage in face of "unfriendly' content * Introduced in 2.9.0 */ #define XML_MAX_NAME_LENGTH 50000 /** * XML_MAX_DICTIONARY_LIMIT: * * Maximum size allowed by the parser for a dictionary by default * This is not a limitation of the parser but a safety boundary feature, * use XML_PARSE_HUGE option to override it. * Introduced in 2.9.0 */ #define XML_MAX_DICTIONARY_LIMIT 10000000 /** * XML_MAX_LOOKUP_LIMIT: * * Maximum size allowed by the parser for ahead lookup * This is an upper boundary enforced by the parser to avoid bad * behaviour on "unfriendly' content * Introduced in 2.9.0 */ #define XML_MAX_LOOKUP_LIMIT 10000000 /** * XML_MAX_NAMELEN: * * Identifiers can be longer, but this will be more costly * at runtime. */ #define XML_MAX_NAMELEN 100 /** * INPUT_CHUNK: * * The parser tries to always have that amount of input ready. * One of the point is providing context when reporting errors. */ #define INPUT_CHUNK 250 /************************************************************************ * * * UNICODE version of the macros. * * * ************************************************************************/ /** * IS_BYTE_CHAR: * @c: an byte value (int) * * Macro to check the following production in the XML spec: * * [2] Char ::= #x9 | #xA | #xD | [#x20...] * any byte character in the accepted range */ #define IS_BYTE_CHAR(c) xmlIsChar_ch(c) /** * IS_CHAR: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [2] Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] * | [#x10000-#x10FFFF] * any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */ #define IS_CHAR(c) xmlIsCharQ(c) /** * IS_CHAR_CH: * @c: an xmlChar (usually an unsigned char) * * Behaves like IS_CHAR on single-byte value */ #define IS_CHAR_CH(c) xmlIsChar_ch(c) /** * IS_BLANK: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [3] S ::= (#x20 | #x9 | #xD | #xA)+ */ #define IS_BLANK(c) xmlIsBlankQ(c) /** * IS_BLANK_CH: * @c: an xmlChar value (normally unsigned char) * * Behaviour same as IS_BLANK */ #define IS_BLANK_CH(c) xmlIsBlank_ch(c) /** * IS_BASECHAR: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [85] BaseChar ::= ... long list see REC ... */ #define IS_BASECHAR(c) xmlIsBaseCharQ(c) /** * IS_DIGIT: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [88] Digit ::= ... long list see REC ... */ #define IS_DIGIT(c) xmlIsDigitQ(c) /** * IS_DIGIT_CH: * @c: an xmlChar value (usually an unsigned char) * * Behaves like IS_DIGIT but with a single byte argument */ #define IS_DIGIT_CH(c) xmlIsDigit_ch(c) /** * IS_COMBINING: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * [87] CombiningChar ::= ... long list see REC ... */ #define IS_COMBINING(c) xmlIsCombiningQ(c) /** * IS_COMBINING_CH: * @c: an xmlChar (usually an unsigned char) * * Always false (all combining chars > 0xff) */ #define IS_COMBINING_CH(c) 0 /** * IS_EXTENDER: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [89] Extender ::= #x00B7 | #x02D0 | #x02D1 | #x0387 | #x0640 | * #x0E46 | #x0EC6 | #x3005 | [#x3031-#x3035] | * [#x309D-#x309E] | [#x30FC-#x30FE] */ #define IS_EXTENDER(c) xmlIsExtenderQ(c) /** * IS_EXTENDER_CH: * @c: an xmlChar value (usually an unsigned char) * * Behaves like IS_EXTENDER but with a single-byte argument */ #define IS_EXTENDER_CH(c) xmlIsExtender_ch(c) /** * IS_IDEOGRAPHIC: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [86] Ideographic ::= [#x4E00-#x9FA5] | #x3007 | [#x3021-#x3029] */ #define IS_IDEOGRAPHIC(c) xmlIsIdeographicQ(c) /** * IS_LETTER: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [84] Letter ::= BaseChar | Ideographic */ #define IS_LETTER(c) (IS_BASECHAR(c) || IS_IDEOGRAPHIC(c)) /** * IS_LETTER_CH: * @c: an xmlChar value (normally unsigned char) * * Macro behaves like IS_LETTER, but only check base chars * */ #define IS_LETTER_CH(c) xmlIsBaseChar_ch(c) /** * IS_ASCII_LETTER: * @c: an xmlChar value * * Macro to check [a-zA-Z] * */ #define IS_ASCII_LETTER(c) (((0x41 <= (c)) && ((c) <= 0x5a)) || \ ((0x61 <= (c)) && ((c) <= 0x7a))) /** * IS_ASCII_DIGIT: * @c: an xmlChar value * * Macro to check [0-9] * */ #define IS_ASCII_DIGIT(c) ((0x30 <= (c)) && ((c) <= 0x39)) /** * IS_PUBIDCHAR: * @c: an UNICODE value (int) * * Macro to check the following production in the XML spec: * * * [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] */ #define IS_PUBIDCHAR(c) xmlIsPubidCharQ(c) /** * IS_PUBIDCHAR_CH: * @c: an xmlChar value (normally unsigned char) * * Same as IS_PUBIDCHAR but for single-byte value */ #define IS_PUBIDCHAR_CH(c) xmlIsPubidChar_ch(c) /** * Global variables used for predefined strings. */ XMLPUBVAR const xmlChar xmlStringText[]; XMLPUBVAR const xmlChar xmlStringTextNoenc[]; XMLPUBVAR const xmlChar xmlStringComment[]; /* * Function to finish the work of the macros where needed. */ XMLPUBFUN int xmlIsLetter (int c); /** * Parser context. */ XMLPUBFUN xmlParserCtxtPtr xmlCreateFileParserCtxt (const char *filename); XMLPUBFUN xmlParserCtxtPtr xmlCreateURLParserCtxt (const char *filename, int options); XMLPUBFUN xmlParserCtxtPtr xmlCreateMemoryParserCtxt(const char *buffer, int size); XMLPUBFUN xmlParserCtxtPtr xmlCreateEntityParserCtxt(const xmlChar *URL, const xmlChar *ID, const xmlChar *base); XMLPUBFUN int xmlSwitchEncoding (xmlParserCtxtPtr ctxt, xmlCharEncoding enc); XMLPUBFUN int xmlSwitchToEncoding (xmlParserCtxtPtr ctxt, xmlCharEncodingHandlerPtr handler); XML_DEPRECATED XMLPUBFUN int xmlSwitchInputEncoding (xmlParserCtxtPtr ctxt, xmlParserInputPtr input, xmlCharEncodingHandlerPtr handler); /** * Input Streams. */ XMLPUBFUN xmlParserInputPtr xmlNewStringInputStream (xmlParserCtxtPtr ctxt, const xmlChar *buffer); XML_DEPRECATED XMLPUBFUN xmlParserInputPtr xmlNewEntityInputStream (xmlParserCtxtPtr ctxt, xmlEntityPtr entity); XMLPUBFUN int xmlPushInput (xmlParserCtxtPtr ctxt, xmlParserInputPtr input); XMLPUBFUN xmlChar xmlPopInput (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlFreeInputStream (xmlParserInputPtr input); XMLPUBFUN xmlParserInputPtr xmlNewInputFromFile (xmlParserCtxtPtr ctxt, const char *filename); XMLPUBFUN xmlParserInputPtr xmlNewInputStream (xmlParserCtxtPtr ctxt); /** * Namespaces. */ XMLPUBFUN xmlChar * xmlSplitQName (xmlParserCtxtPtr ctxt, const xmlChar *name, xmlChar **prefix); /** * Generic production rules. */ XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseNmtoken (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseEntityValue (xmlParserCtxtPtr ctxt, xmlChar **orig); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseAttValue (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseSystemLiteral (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParsePubidLiteral (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseCharData (xmlParserCtxtPtr ctxt, int cdata); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseExternalID (xmlParserCtxtPtr ctxt, xmlChar **publicID, int strict); XML_DEPRECATED XMLPUBFUN void xmlParseComment (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParsePITarget (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParsePI (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseNotationDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseEntityDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseDefaultDecl (xmlParserCtxtPtr ctxt, xmlChar **value); XML_DEPRECATED XMLPUBFUN xmlEnumerationPtr xmlParseNotationType (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlEnumerationPtr xmlParseEnumerationType (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseEnumeratedType (xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree); XML_DEPRECATED XMLPUBFUN int xmlParseAttributeType (xmlParserCtxtPtr ctxt, xmlEnumerationPtr *tree); XML_DEPRECATED XMLPUBFUN void xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlElementContentPtr xmlParseElementMixedContentDecl (xmlParserCtxtPtr ctxt, int inputchk); XML_DEPRECATED XMLPUBFUN xmlElementContentPtr xmlParseElementChildrenContentDecl (xmlParserCtxtPtr ctxt, int inputchk); XML_DEPRECATED XMLPUBFUN int xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, xmlElementContentPtr *result); XML_DEPRECATED XMLPUBFUN int xmlParseElementDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseMarkupDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseCharRef (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlEntityPtr xmlParseEntityRef (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseReference (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParsePEReference (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseDocTypeDecl (xmlParserCtxtPtr ctxt); #ifdef LIBXML_SAX1_ENABLED XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseAttribute (xmlParserCtxtPtr ctxt, xmlChar **value); XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseStartTag (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseEndTag (xmlParserCtxtPtr ctxt); #endif /* LIBXML_SAX1_ENABLED */ XML_DEPRECATED XMLPUBFUN void xmlParseCDSect (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlParseContent (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseElement (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseVersionNum (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseVersionInfo (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseEncName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN const xmlChar * xmlParseEncodingDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlParseSDDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseXMLDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseTextDecl (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseMisc (xmlParserCtxtPtr ctxt); XMLPUBFUN void xmlParseExternalSubset (xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, const xmlChar *SystemID); /** * XML_SUBSTITUTE_NONE: * * If no entities need to be substituted. */ #define XML_SUBSTITUTE_NONE 0 /** * XML_SUBSTITUTE_REF: * * Whether general entities need to be substituted. */ #define XML_SUBSTITUTE_REF 1 /** * XML_SUBSTITUTE_PEREF: * * Whether parameter entities need to be substituted. */ #define XML_SUBSTITUTE_PEREF 2 /** * XML_SUBSTITUTE_BOTH: * * Both general and parameter entities need to be substituted. */ #define XML_SUBSTITUTE_BOTH 3 XML_DEPRECATED XMLPUBFUN xmlChar * xmlStringDecodeEntities (xmlParserCtxtPtr ctxt, const xmlChar *str, int what, xmlChar end, xmlChar end2, xmlChar end3); XML_DEPRECATED XMLPUBFUN xmlChar * xmlStringLenDecodeEntities (xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3); /* * Generated by MACROS on top of parser.c c.f. PUSH_AND_POP. */ XML_DEPRECATED XMLPUBFUN int nodePush (xmlParserCtxtPtr ctxt, xmlNodePtr value); XML_DEPRECATED XMLPUBFUN xmlNodePtr nodePop (xmlParserCtxtPtr ctxt); XMLPUBFUN int inputPush (xmlParserCtxtPtr ctxt, xmlParserInputPtr value); XMLPUBFUN xmlParserInputPtr inputPop (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN const xmlChar * namePop (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int namePush (xmlParserCtxtPtr ctxt, const xmlChar *value); /* * other commodities shared between parser.c and parserInternals. */ XML_DEPRECATED XMLPUBFUN int xmlSkipBlankChars (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlStringCurrentChar (xmlParserCtxtPtr ctxt, const xmlChar *cur, int *len); XML_DEPRECATED XMLPUBFUN void xmlParserHandlePEReference(xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN int xmlCheckLanguageID (const xmlChar *lang); /* * Really core function shared with HTML parser. */ XML_DEPRECATED XMLPUBFUN int xmlCurrentChar (xmlParserCtxtPtr ctxt, int *len); XMLPUBFUN int xmlCopyCharMultiByte (xmlChar *out, int val); XMLPUBFUN int xmlCopyChar (int len, xmlChar *out, int val); XML_DEPRECATED XMLPUBFUN void xmlNextChar (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParserInputShrink (xmlParserInputPtr in); /* * Specific function to keep track of entities references * and used by the XSLT debugger. */ #ifdef LIBXML_LEGACY_ENABLED /** * xmlEntityReferenceFunc: * @ent: the entity * @firstNode: the fist node in the chunk * @lastNode: the last nod in the chunk * * Callback function used when one needs to be able to track back the * provenance of a chunk of nodes inherited from an entity replacement. */ typedef void (*xmlEntityReferenceFunc) (xmlEntityPtr ent, xmlNodePtr firstNode, xmlNodePtr lastNode); XML_DEPRECATED XMLPUBFUN void xmlSetEntityReferenceFunc (xmlEntityReferenceFunc func); XML_DEPRECATED XMLPUBFUN xmlChar * xmlParseQuotedString (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParseNamespace (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlNamespaceParseNSDef (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlScanName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlNamespaceParseNCName (xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN void xmlParserHandleReference(xmlParserCtxtPtr ctxt); XML_DEPRECATED XMLPUBFUN xmlChar * xmlNamespaceParseQName (xmlParserCtxtPtr ctxt, xmlChar **prefix); /** * Entities */ XML_DEPRECATED XMLPUBFUN xmlChar * xmlDecodeEntities (xmlParserCtxtPtr ctxt, int len, int what, xmlChar end, xmlChar end2, xmlChar end3); XML_DEPRECATED XMLPUBFUN void xmlHandleEntity (xmlParserCtxtPtr ctxt, xmlEntityPtr entity); #endif /* LIBXML_LEGACY_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_PARSER_INTERNALS_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/pattern.h ================================================ /* * Summary: pattern expression handling * Description: allows to compile and test pattern expressions for nodes * either in a tree or based on a parser state. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_PATTERN_H__ #define __XML_PATTERN_H__ #include #include #include #ifdef LIBXML_PATTERN_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlPattern: * * A compiled (XPath based) pattern to select nodes */ typedef struct _xmlPattern xmlPattern; typedef xmlPattern *xmlPatternPtr; /** * xmlPatternFlags: * * This is the set of options affecting the behaviour of pattern * matching with this module * */ typedef enum { XML_PATTERN_DEFAULT = 0, /* simple pattern match */ XML_PATTERN_XPATH = 1<<0, /* standard XPath pattern */ XML_PATTERN_XSSEL = 1<<1, /* XPath subset for schema selector */ XML_PATTERN_XSFIELD = 1<<2 /* XPath subset for schema field */ } xmlPatternFlags; XMLPUBFUN void xmlFreePattern (xmlPatternPtr comp); XMLPUBFUN void xmlFreePatternList (xmlPatternPtr comp); XMLPUBFUN xmlPatternPtr xmlPatterncompile (const xmlChar *pattern, xmlDict *dict, int flags, const xmlChar **namespaces); XMLPUBFUN int xmlPatternMatch (xmlPatternPtr comp, xmlNodePtr node); /* streaming interfaces */ typedef struct _xmlStreamCtxt xmlStreamCtxt; typedef xmlStreamCtxt *xmlStreamCtxtPtr; XMLPUBFUN int xmlPatternStreamable (xmlPatternPtr comp); XMLPUBFUN int xmlPatternMaxDepth (xmlPatternPtr comp); XMLPUBFUN int xmlPatternMinDepth (xmlPatternPtr comp); XMLPUBFUN int xmlPatternFromRoot (xmlPatternPtr comp); XMLPUBFUN xmlStreamCtxtPtr xmlPatternGetStreamCtxt (xmlPatternPtr comp); XMLPUBFUN void xmlFreeStreamCtxt (xmlStreamCtxtPtr stream); XMLPUBFUN int xmlStreamPushNode (xmlStreamCtxtPtr stream, const xmlChar *name, const xmlChar *ns, int nodeType); XMLPUBFUN int xmlStreamPush (xmlStreamCtxtPtr stream, const xmlChar *name, const xmlChar *ns); XMLPUBFUN int xmlStreamPushAttr (xmlStreamCtxtPtr stream, const xmlChar *name, const xmlChar *ns); XMLPUBFUN int xmlStreamPop (xmlStreamCtxtPtr stream); XMLPUBFUN int xmlStreamWantsAnyNode (xmlStreamCtxtPtr stream); #ifdef __cplusplus } #endif #endif /* LIBXML_PATTERN_ENABLED */ #endif /* __XML_PATTERN_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/relaxng.h ================================================ /* * Summary: implementation of the Relax-NG validation * Description: implementation of the Relax-NG validation * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_RELAX_NG__ #define __XML_RELAX_NG__ #include #include #include #ifdef LIBXML_SCHEMAS_ENABLED #ifdef __cplusplus extern "C" { #endif typedef struct _xmlRelaxNG xmlRelaxNG; typedef xmlRelaxNG *xmlRelaxNGPtr; /** * xmlRelaxNGValidityErrorFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of an error callback from a Relax-NG validation */ typedef void (*xmlRelaxNGValidityErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlRelaxNGValidityWarningFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of a warning callback from a Relax-NG validation */ typedef void (*xmlRelaxNGValidityWarningFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * A schemas validation context */ typedef struct _xmlRelaxNGParserCtxt xmlRelaxNGParserCtxt; typedef xmlRelaxNGParserCtxt *xmlRelaxNGParserCtxtPtr; typedef struct _xmlRelaxNGValidCtxt xmlRelaxNGValidCtxt; typedef xmlRelaxNGValidCtxt *xmlRelaxNGValidCtxtPtr; /* * xmlRelaxNGValidErr: * * List of possible Relax NG validation errors */ typedef enum { XML_RELAXNG_OK = 0, XML_RELAXNG_ERR_MEMORY, XML_RELAXNG_ERR_TYPE, XML_RELAXNG_ERR_TYPEVAL, XML_RELAXNG_ERR_DUPID, XML_RELAXNG_ERR_TYPECMP, XML_RELAXNG_ERR_NOSTATE, XML_RELAXNG_ERR_NODEFINE, XML_RELAXNG_ERR_LISTEXTRA, XML_RELAXNG_ERR_LISTEMPTY, XML_RELAXNG_ERR_INTERNODATA, XML_RELAXNG_ERR_INTERSEQ, XML_RELAXNG_ERR_INTEREXTRA, XML_RELAXNG_ERR_ELEMNAME, XML_RELAXNG_ERR_ATTRNAME, XML_RELAXNG_ERR_ELEMNONS, XML_RELAXNG_ERR_ATTRNONS, XML_RELAXNG_ERR_ELEMWRONGNS, XML_RELAXNG_ERR_ATTRWRONGNS, XML_RELAXNG_ERR_ELEMEXTRANS, XML_RELAXNG_ERR_ATTREXTRANS, XML_RELAXNG_ERR_ELEMNOTEMPTY, XML_RELAXNG_ERR_NOELEM, XML_RELAXNG_ERR_NOTELEM, XML_RELAXNG_ERR_ATTRVALID, XML_RELAXNG_ERR_CONTENTVALID, XML_RELAXNG_ERR_EXTRACONTENT, XML_RELAXNG_ERR_INVALIDATTR, XML_RELAXNG_ERR_DATAELEM, XML_RELAXNG_ERR_VALELEM, XML_RELAXNG_ERR_LISTELEM, XML_RELAXNG_ERR_DATATYPE, XML_RELAXNG_ERR_VALUE, XML_RELAXNG_ERR_LIST, XML_RELAXNG_ERR_NOGRAMMAR, XML_RELAXNG_ERR_EXTRADATA, XML_RELAXNG_ERR_LACKDATA, XML_RELAXNG_ERR_INTERNAL, XML_RELAXNG_ERR_ELEMWRONG, XML_RELAXNG_ERR_TEXTWRONG } xmlRelaxNGValidErr; /* * xmlRelaxNGParserFlags: * * List of possible Relax NG Parser flags */ typedef enum { XML_RELAXNGP_NONE = 0, XML_RELAXNGP_FREE_DOC = 1, XML_RELAXNGP_CRNG = 2 } xmlRelaxNGParserFlag; XMLPUBFUN int xmlRelaxNGInitTypes (void); XML_DEPRECATED XMLPUBFUN void xmlRelaxNGCleanupTypes (void); /* * Interfaces for parsing. */ XMLPUBFUN xmlRelaxNGParserCtxtPtr xmlRelaxNGNewParserCtxt (const char *URL); XMLPUBFUN xmlRelaxNGParserCtxtPtr xmlRelaxNGNewMemParserCtxt (const char *buffer, int size); XMLPUBFUN xmlRelaxNGParserCtxtPtr xmlRelaxNGNewDocParserCtxt (xmlDocPtr doc); XMLPUBFUN int xmlRelaxParserSetFlag (xmlRelaxNGParserCtxtPtr ctxt, int flag); XMLPUBFUN void xmlRelaxNGFreeParserCtxt (xmlRelaxNGParserCtxtPtr ctxt); XMLPUBFUN void xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc err, xmlRelaxNGValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc *err, xmlRelaxNGValidityWarningFunc *warn, void **ctx); XMLPUBFUN void xmlRelaxNGSetParserStructuredErrors( xmlRelaxNGParserCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN xmlRelaxNGPtr xmlRelaxNGParse (xmlRelaxNGParserCtxtPtr ctxt); XMLPUBFUN void xmlRelaxNGFree (xmlRelaxNGPtr schema); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlRelaxNGDump (FILE *output, xmlRelaxNGPtr schema); XMLPUBFUN void xmlRelaxNGDumpTree (FILE * output, xmlRelaxNGPtr schema); #endif /* LIBXML_OUTPUT_ENABLED */ /* * Interfaces for validating */ XMLPUBFUN void xmlRelaxNGSetValidErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc err, xmlRelaxNGValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlRelaxNGGetValidErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlRelaxNGValidityErrorFunc *err, xmlRelaxNGValidityWarningFunc *warn, void **ctx); XMLPUBFUN void xmlRelaxNGSetValidStructuredErrors(xmlRelaxNGValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN xmlRelaxNGValidCtxtPtr xmlRelaxNGNewValidCtxt (xmlRelaxNGPtr schema); XMLPUBFUN void xmlRelaxNGFreeValidCtxt (xmlRelaxNGValidCtxtPtr ctxt); XMLPUBFUN int xmlRelaxNGValidateDoc (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc); /* * Interfaces for progressive validation when possible */ XMLPUBFUN int xmlRelaxNGValidatePushElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlRelaxNGValidatePushCData (xmlRelaxNGValidCtxtPtr ctxt, const xmlChar *data, int len); XMLPUBFUN int xmlRelaxNGValidatePopElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlRelaxNGValidateFullElement (xmlRelaxNGValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_RELAX_NG__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/schemasInternals.h ================================================ /* * Summary: internal interfaces for XML Schemas * Description: internal interfaces for the XML Schemas handling * and schema validity checking * The Schemas development is a Work In Progress. * Some of those interfaces are not guaranteed to be API or ABI stable ! * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMA_INTERNALS_H__ #define __XML_SCHEMA_INTERNALS_H__ #include #ifdef LIBXML_SCHEMAS_ENABLED #include #include #include #ifdef __cplusplus extern "C" { #endif typedef enum { XML_SCHEMAS_UNKNOWN = 0, XML_SCHEMAS_STRING = 1, XML_SCHEMAS_NORMSTRING = 2, XML_SCHEMAS_DECIMAL = 3, XML_SCHEMAS_TIME = 4, XML_SCHEMAS_GDAY = 5, XML_SCHEMAS_GMONTH = 6, XML_SCHEMAS_GMONTHDAY = 7, XML_SCHEMAS_GYEAR = 8, XML_SCHEMAS_GYEARMONTH = 9, XML_SCHEMAS_DATE = 10, XML_SCHEMAS_DATETIME = 11, XML_SCHEMAS_DURATION = 12, XML_SCHEMAS_FLOAT = 13, XML_SCHEMAS_DOUBLE = 14, XML_SCHEMAS_BOOLEAN = 15, XML_SCHEMAS_TOKEN = 16, XML_SCHEMAS_LANGUAGE = 17, XML_SCHEMAS_NMTOKEN = 18, XML_SCHEMAS_NMTOKENS = 19, XML_SCHEMAS_NAME = 20, XML_SCHEMAS_QNAME = 21, XML_SCHEMAS_NCNAME = 22, XML_SCHEMAS_ID = 23, XML_SCHEMAS_IDREF = 24, XML_SCHEMAS_IDREFS = 25, XML_SCHEMAS_ENTITY = 26, XML_SCHEMAS_ENTITIES = 27, XML_SCHEMAS_NOTATION = 28, XML_SCHEMAS_ANYURI = 29, XML_SCHEMAS_INTEGER = 30, XML_SCHEMAS_NPINTEGER = 31, XML_SCHEMAS_NINTEGER = 32, XML_SCHEMAS_NNINTEGER = 33, XML_SCHEMAS_PINTEGER = 34, XML_SCHEMAS_INT = 35, XML_SCHEMAS_UINT = 36, XML_SCHEMAS_LONG = 37, XML_SCHEMAS_ULONG = 38, XML_SCHEMAS_SHORT = 39, XML_SCHEMAS_USHORT = 40, XML_SCHEMAS_BYTE = 41, XML_SCHEMAS_UBYTE = 42, XML_SCHEMAS_HEXBINARY = 43, XML_SCHEMAS_BASE64BINARY = 44, XML_SCHEMAS_ANYTYPE = 45, XML_SCHEMAS_ANYSIMPLETYPE = 46 } xmlSchemaValType; /* * XML Schemas defines multiple type of types. */ typedef enum { XML_SCHEMA_TYPE_BASIC = 1, /* A built-in datatype */ XML_SCHEMA_TYPE_ANY, XML_SCHEMA_TYPE_FACET, XML_SCHEMA_TYPE_SIMPLE, XML_SCHEMA_TYPE_COMPLEX, XML_SCHEMA_TYPE_SEQUENCE = 6, XML_SCHEMA_TYPE_CHOICE, XML_SCHEMA_TYPE_ALL, XML_SCHEMA_TYPE_SIMPLE_CONTENT, XML_SCHEMA_TYPE_COMPLEX_CONTENT, XML_SCHEMA_TYPE_UR, XML_SCHEMA_TYPE_RESTRICTION, XML_SCHEMA_TYPE_EXTENSION, XML_SCHEMA_TYPE_ELEMENT, XML_SCHEMA_TYPE_ATTRIBUTE, XML_SCHEMA_TYPE_ATTRIBUTEGROUP, XML_SCHEMA_TYPE_GROUP, XML_SCHEMA_TYPE_NOTATION, XML_SCHEMA_TYPE_LIST, XML_SCHEMA_TYPE_UNION, XML_SCHEMA_TYPE_ANY_ATTRIBUTE, XML_SCHEMA_TYPE_IDC_UNIQUE, XML_SCHEMA_TYPE_IDC_KEY, XML_SCHEMA_TYPE_IDC_KEYREF, XML_SCHEMA_TYPE_PARTICLE = 25, XML_SCHEMA_TYPE_ATTRIBUTE_USE, XML_SCHEMA_FACET_MININCLUSIVE = 1000, XML_SCHEMA_FACET_MINEXCLUSIVE, XML_SCHEMA_FACET_MAXINCLUSIVE, XML_SCHEMA_FACET_MAXEXCLUSIVE, XML_SCHEMA_FACET_TOTALDIGITS, XML_SCHEMA_FACET_FRACTIONDIGITS, XML_SCHEMA_FACET_PATTERN, XML_SCHEMA_FACET_ENUMERATION, XML_SCHEMA_FACET_WHITESPACE, XML_SCHEMA_FACET_LENGTH, XML_SCHEMA_FACET_MAXLENGTH, XML_SCHEMA_FACET_MINLENGTH, XML_SCHEMA_EXTRA_QNAMEREF = 2000, XML_SCHEMA_EXTRA_ATTR_USE_PROHIB } xmlSchemaTypeType; typedef enum { XML_SCHEMA_CONTENT_UNKNOWN = 0, XML_SCHEMA_CONTENT_EMPTY = 1, XML_SCHEMA_CONTENT_ELEMENTS, XML_SCHEMA_CONTENT_MIXED, XML_SCHEMA_CONTENT_SIMPLE, XML_SCHEMA_CONTENT_MIXED_OR_ELEMENTS, /* Obsolete */ XML_SCHEMA_CONTENT_BASIC, XML_SCHEMA_CONTENT_ANY } xmlSchemaContentType; typedef struct _xmlSchemaVal xmlSchemaVal; typedef xmlSchemaVal *xmlSchemaValPtr; typedef struct _xmlSchemaType xmlSchemaType; typedef xmlSchemaType *xmlSchemaTypePtr; typedef struct _xmlSchemaFacet xmlSchemaFacet; typedef xmlSchemaFacet *xmlSchemaFacetPtr; /** * Annotation */ typedef struct _xmlSchemaAnnot xmlSchemaAnnot; typedef xmlSchemaAnnot *xmlSchemaAnnotPtr; struct _xmlSchemaAnnot { struct _xmlSchemaAnnot *next; xmlNodePtr content; /* the annotation */ }; /** * XML_SCHEMAS_ANYATTR_SKIP: * * Skip unknown attribute from validation * Obsolete, not used anymore. */ #define XML_SCHEMAS_ANYATTR_SKIP 1 /** * XML_SCHEMAS_ANYATTR_LAX: * * Ignore validation non definition on attributes * Obsolete, not used anymore. */ #define XML_SCHEMAS_ANYATTR_LAX 2 /** * XML_SCHEMAS_ANYATTR_STRICT: * * Apply strict validation rules on attributes * Obsolete, not used anymore. */ #define XML_SCHEMAS_ANYATTR_STRICT 3 /** * XML_SCHEMAS_ANY_SKIP: * * Skip unknown attribute from validation */ #define XML_SCHEMAS_ANY_SKIP 1 /** * XML_SCHEMAS_ANY_LAX: * * Used by wildcards. * Validate if type found, don't worry if not found */ #define XML_SCHEMAS_ANY_LAX 2 /** * XML_SCHEMAS_ANY_STRICT: * * Used by wildcards. * Apply strict validation rules */ #define XML_SCHEMAS_ANY_STRICT 3 /** * XML_SCHEMAS_ATTR_USE_PROHIBITED: * * Used by wildcards. * The attribute is prohibited. */ #define XML_SCHEMAS_ATTR_USE_PROHIBITED 0 /** * XML_SCHEMAS_ATTR_USE_REQUIRED: * * The attribute is required. */ #define XML_SCHEMAS_ATTR_USE_REQUIRED 1 /** * XML_SCHEMAS_ATTR_USE_OPTIONAL: * * The attribute is optional. */ #define XML_SCHEMAS_ATTR_USE_OPTIONAL 2 /** * XML_SCHEMAS_ATTR_GLOBAL: * * allow elements in no namespace */ #define XML_SCHEMAS_ATTR_GLOBAL 1 << 0 /** * XML_SCHEMAS_ATTR_NSDEFAULT: * * allow elements in no namespace */ #define XML_SCHEMAS_ATTR_NSDEFAULT 1 << 7 /** * XML_SCHEMAS_ATTR_INTERNAL_RESOLVED: * * this is set when the "type" and "ref" references * have been resolved. */ #define XML_SCHEMAS_ATTR_INTERNAL_RESOLVED 1 << 8 /** * XML_SCHEMAS_ATTR_FIXED: * * the attribute has a fixed value */ #define XML_SCHEMAS_ATTR_FIXED 1 << 9 /** * xmlSchemaAttribute: * An attribute definition. */ typedef struct _xmlSchemaAttribute xmlSchemaAttribute; typedef xmlSchemaAttribute *xmlSchemaAttributePtr; struct _xmlSchemaAttribute { xmlSchemaTypeType type; struct _xmlSchemaAttribute *next; /* the next attribute (not used?) */ const xmlChar *name; /* the name of the declaration */ const xmlChar *id; /* Deprecated; not used */ const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ const xmlChar *typeName; /* the local name of the type definition */ const xmlChar *typeNs; /* the ns URI of the type definition */ xmlSchemaAnnotPtr annot; xmlSchemaTypePtr base; /* Deprecated; not used */ int occurs; /* Deprecated; not used */ const xmlChar *defValue; /* The initial value of the value constraint */ xmlSchemaTypePtr subtypes; /* the type definition */ xmlNodePtr node; const xmlChar *targetNamespace; int flags; const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaValPtr defVal; /* The compiled value constraint */ xmlSchemaAttributePtr refDecl; /* Deprecated; not used */ }; /** * xmlSchemaAttributeLink: * Used to build a list of attribute uses on complexType definitions. * WARNING: Deprecated; not used. */ typedef struct _xmlSchemaAttributeLink xmlSchemaAttributeLink; typedef xmlSchemaAttributeLink *xmlSchemaAttributeLinkPtr; struct _xmlSchemaAttributeLink { struct _xmlSchemaAttributeLink *next;/* the next attribute link ... */ struct _xmlSchemaAttribute *attr;/* the linked attribute */ }; /** * XML_SCHEMAS_WILDCARD_COMPLETE: * * If the wildcard is complete. */ #define XML_SCHEMAS_WILDCARD_COMPLETE 1 << 0 /** * xmlSchemaCharValueLink: * Used to build a list of namespaces on wildcards. */ typedef struct _xmlSchemaWildcardNs xmlSchemaWildcardNs; typedef xmlSchemaWildcardNs *xmlSchemaWildcardNsPtr; struct _xmlSchemaWildcardNs { struct _xmlSchemaWildcardNs *next;/* the next constraint link ... */ const xmlChar *value;/* the value */ }; /** * xmlSchemaWildcard. * A wildcard. */ typedef struct _xmlSchemaWildcard xmlSchemaWildcard; typedef xmlSchemaWildcard *xmlSchemaWildcardPtr; struct _xmlSchemaWildcard { xmlSchemaTypeType type; /* The kind of type */ const xmlChar *id; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlNodePtr node; int minOccurs; /* Deprecated; not used */ int maxOccurs; /* Deprecated; not used */ int processContents; int any; /* Indicates if the ns constraint is of ##any */ xmlSchemaWildcardNsPtr nsSet; /* The list of allowed namespaces */ xmlSchemaWildcardNsPtr negNsSet; /* The negated namespace */ int flags; }; /** * XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED: * * The attribute wildcard has been built. */ #define XML_SCHEMAS_ATTRGROUP_WILDCARD_BUILDED 1 << 0 /** * XML_SCHEMAS_ATTRGROUP_GLOBAL: * * The attribute group has been defined. */ #define XML_SCHEMAS_ATTRGROUP_GLOBAL 1 << 1 /** * XML_SCHEMAS_ATTRGROUP_MARKED: * * Marks the attr group as marked; used for circular checks. */ #define XML_SCHEMAS_ATTRGROUP_MARKED 1 << 2 /** * XML_SCHEMAS_ATTRGROUP_REDEFINED: * * The attr group was redefined. */ #define XML_SCHEMAS_ATTRGROUP_REDEFINED 1 << 3 /** * XML_SCHEMAS_ATTRGROUP_HAS_REFS: * * Whether this attr. group contains attr. group references. */ #define XML_SCHEMAS_ATTRGROUP_HAS_REFS 1 << 4 /** * An attribute group definition. * * xmlSchemaAttribute and xmlSchemaAttributeGroup start of structures * must be kept similar */ typedef struct _xmlSchemaAttributeGroup xmlSchemaAttributeGroup; typedef xmlSchemaAttributeGroup *xmlSchemaAttributeGroupPtr; struct _xmlSchemaAttributeGroup { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaAttribute *next;/* the next attribute if in a group ... */ const xmlChar *name; const xmlChar *id; const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlSchemaAttributePtr attributes; /* Deprecated; not used */ xmlNodePtr node; int flags; xmlSchemaWildcardPtr attributeWildcard; const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaAttributeGroupPtr refItem; /* Deprecated; not used */ const xmlChar *targetNamespace; void *attrUses; }; /** * xmlSchemaTypeLink: * Used to build a list of types (e.g. member types of * simpleType with variety "union"). */ typedef struct _xmlSchemaTypeLink xmlSchemaTypeLink; typedef xmlSchemaTypeLink *xmlSchemaTypeLinkPtr; struct _xmlSchemaTypeLink { struct _xmlSchemaTypeLink *next;/* the next type link ... */ xmlSchemaTypePtr type;/* the linked type */ }; /** * xmlSchemaFacetLink: * Used to build a list of facets. */ typedef struct _xmlSchemaFacetLink xmlSchemaFacetLink; typedef xmlSchemaFacetLink *xmlSchemaFacetLinkPtr; struct _xmlSchemaFacetLink { struct _xmlSchemaFacetLink *next;/* the next facet link ... */ xmlSchemaFacetPtr facet;/* the linked facet */ }; /** * XML_SCHEMAS_TYPE_MIXED: * * the element content type is mixed */ #define XML_SCHEMAS_TYPE_MIXED 1 << 0 /** * XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION: * * the simple or complex type has a derivation method of "extension". */ #define XML_SCHEMAS_TYPE_DERIVATION_METHOD_EXTENSION 1 << 1 /** * XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION: * * the simple or complex type has a derivation method of "restriction". */ #define XML_SCHEMAS_TYPE_DERIVATION_METHOD_RESTRICTION 1 << 2 /** * XML_SCHEMAS_TYPE_GLOBAL: * * the type is global */ #define XML_SCHEMAS_TYPE_GLOBAL 1 << 3 /** * XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD: * * the complexType owns an attribute wildcard, i.e. * it can be freed by the complexType */ #define XML_SCHEMAS_TYPE_OWNED_ATTR_WILDCARD 1 << 4 /* Obsolete. */ /** * XML_SCHEMAS_TYPE_VARIETY_ABSENT: * * the simpleType has a variety of "absent". * TODO: Actually not necessary :-/, since if * none of the variety flags occur then it's * automatically absent. */ #define XML_SCHEMAS_TYPE_VARIETY_ABSENT 1 << 5 /** * XML_SCHEMAS_TYPE_VARIETY_LIST: * * the simpleType has a variety of "list". */ #define XML_SCHEMAS_TYPE_VARIETY_LIST 1 << 6 /** * XML_SCHEMAS_TYPE_VARIETY_UNION: * * the simpleType has a variety of "union". */ #define XML_SCHEMAS_TYPE_VARIETY_UNION 1 << 7 /** * XML_SCHEMAS_TYPE_VARIETY_ATOMIC: * * the simpleType has a variety of "union". */ #define XML_SCHEMAS_TYPE_VARIETY_ATOMIC 1 << 8 /** * XML_SCHEMAS_TYPE_FINAL_EXTENSION: * * the complexType has a final of "extension". */ #define XML_SCHEMAS_TYPE_FINAL_EXTENSION 1 << 9 /** * XML_SCHEMAS_TYPE_FINAL_RESTRICTION: * * the simpleType/complexType has a final of "restriction". */ #define XML_SCHEMAS_TYPE_FINAL_RESTRICTION 1 << 10 /** * XML_SCHEMAS_TYPE_FINAL_LIST: * * the simpleType has a final of "list". */ #define XML_SCHEMAS_TYPE_FINAL_LIST 1 << 11 /** * XML_SCHEMAS_TYPE_FINAL_UNION: * * the simpleType has a final of "union". */ #define XML_SCHEMAS_TYPE_FINAL_UNION 1 << 12 /** * XML_SCHEMAS_TYPE_FINAL_DEFAULT: * * the simpleType has a final of "default". */ #define XML_SCHEMAS_TYPE_FINAL_DEFAULT 1 << 13 /** * XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE: * * Marks the item as a builtin primitive. */ #define XML_SCHEMAS_TYPE_BUILTIN_PRIMITIVE 1 << 14 /** * XML_SCHEMAS_TYPE_MARKED: * * Marks the item as marked; used for circular checks. */ #define XML_SCHEMAS_TYPE_MARKED 1 << 16 /** * XML_SCHEMAS_TYPE_BLOCK_DEFAULT: * * the complexType did not specify 'block' so use the default of the * item. */ #define XML_SCHEMAS_TYPE_BLOCK_DEFAULT 1 << 17 /** * XML_SCHEMAS_TYPE_BLOCK_EXTENSION: * * the complexType has a 'block' of "extension". */ #define XML_SCHEMAS_TYPE_BLOCK_EXTENSION 1 << 18 /** * XML_SCHEMAS_TYPE_BLOCK_RESTRICTION: * * the complexType has a 'block' of "restriction". */ #define XML_SCHEMAS_TYPE_BLOCK_RESTRICTION 1 << 19 /** * XML_SCHEMAS_TYPE_ABSTRACT: * * the simple/complexType is abstract. */ #define XML_SCHEMAS_TYPE_ABSTRACT 1 << 20 /** * XML_SCHEMAS_TYPE_FACETSNEEDVALUE: * * indicates if the facets need a computed value */ #define XML_SCHEMAS_TYPE_FACETSNEEDVALUE 1 << 21 /** * XML_SCHEMAS_TYPE_INTERNAL_RESOLVED: * * indicates that the type was typefixed */ #define XML_SCHEMAS_TYPE_INTERNAL_RESOLVED 1 << 22 /** * XML_SCHEMAS_TYPE_INTERNAL_INVALID: * * indicates that the type is invalid */ #define XML_SCHEMAS_TYPE_INTERNAL_INVALID 1 << 23 /** * XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE: * * a whitespace-facet value of "preserve" */ #define XML_SCHEMAS_TYPE_WHITESPACE_PRESERVE 1 << 24 /** * XML_SCHEMAS_TYPE_WHITESPACE_REPLACE: * * a whitespace-facet value of "replace" */ #define XML_SCHEMAS_TYPE_WHITESPACE_REPLACE 1 << 25 /** * XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE: * * a whitespace-facet value of "collapse" */ #define XML_SCHEMAS_TYPE_WHITESPACE_COLLAPSE 1 << 26 /** * XML_SCHEMAS_TYPE_HAS_FACETS: * * has facets */ #define XML_SCHEMAS_TYPE_HAS_FACETS 1 << 27 /** * XML_SCHEMAS_TYPE_NORMVALUENEEDED: * * indicates if the facets (pattern) need a normalized value */ #define XML_SCHEMAS_TYPE_NORMVALUENEEDED 1 << 28 /** * XML_SCHEMAS_TYPE_FIXUP_1: * * First stage of fixup was done. */ #define XML_SCHEMAS_TYPE_FIXUP_1 1 << 29 /** * XML_SCHEMAS_TYPE_REDEFINED: * * The type was redefined. */ #define XML_SCHEMAS_TYPE_REDEFINED 1 << 30 /** * XML_SCHEMAS_TYPE_REDEFINING: * * The type redefines an other type. */ /* #define XML_SCHEMAS_TYPE_REDEFINING 1 << 31 */ /** * _xmlSchemaType: * * Schemas type definition. */ struct _xmlSchemaType { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaType *next; /* the next type if in a sequence ... */ const xmlChar *name; const xmlChar *id ; /* Deprecated; not used */ const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlSchemaTypePtr subtypes; xmlSchemaAttributePtr attributes; /* Deprecated; not used */ xmlNodePtr node; int minOccurs; /* Deprecated; not used */ int maxOccurs; /* Deprecated; not used */ int flags; xmlSchemaContentType contentType; const xmlChar *base; /* Base type's local name */ const xmlChar *baseNs; /* Base type's target namespace */ xmlSchemaTypePtr baseType; /* The base type component */ xmlSchemaFacetPtr facets; /* Local facets */ struct _xmlSchemaType *redef; /* Deprecated; not used */ int recurse; /* Obsolete */ xmlSchemaAttributeLinkPtr *attributeUses; /* Deprecated; not used */ xmlSchemaWildcardPtr attributeWildcard; int builtInType; /* Type of built-in types. */ xmlSchemaTypeLinkPtr memberTypes; /* member-types if a union type. */ xmlSchemaFacetLinkPtr facetSet; /* All facets (incl. inherited) */ const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaTypePtr contentTypeDef; /* Used for the simple content of complex types. Could we use @subtypes for this? */ xmlRegexpPtr contModel; /* Holds the automaton of the content model */ const xmlChar *targetNamespace; void *attrUses; }; /* * xmlSchemaElement: * An element definition. * * xmlSchemaType, xmlSchemaFacet and xmlSchemaElement start of * structures must be kept similar */ /** * XML_SCHEMAS_ELEM_NILLABLE: * * the element is nillable */ #define XML_SCHEMAS_ELEM_NILLABLE 1 << 0 /** * XML_SCHEMAS_ELEM_GLOBAL: * * the element is global */ #define XML_SCHEMAS_ELEM_GLOBAL 1 << 1 /** * XML_SCHEMAS_ELEM_DEFAULT: * * the element has a default value */ #define XML_SCHEMAS_ELEM_DEFAULT 1 << 2 /** * XML_SCHEMAS_ELEM_FIXED: * * the element has a fixed value */ #define XML_SCHEMAS_ELEM_FIXED 1 << 3 /** * XML_SCHEMAS_ELEM_ABSTRACT: * * the element is abstract */ #define XML_SCHEMAS_ELEM_ABSTRACT 1 << 4 /** * XML_SCHEMAS_ELEM_TOPLEVEL: * * the element is top level * obsolete: use XML_SCHEMAS_ELEM_GLOBAL instead */ #define XML_SCHEMAS_ELEM_TOPLEVEL 1 << 5 /** * XML_SCHEMAS_ELEM_REF: * * the element is a reference to a type */ #define XML_SCHEMAS_ELEM_REF 1 << 6 /** * XML_SCHEMAS_ELEM_NSDEFAULT: * * allow elements in no namespace * Obsolete, not used anymore. */ #define XML_SCHEMAS_ELEM_NSDEFAULT 1 << 7 /** * XML_SCHEMAS_ELEM_INTERNAL_RESOLVED: * * this is set when "type", "ref", "substitutionGroup" * references have been resolved. */ #define XML_SCHEMAS_ELEM_INTERNAL_RESOLVED 1 << 8 /** * XML_SCHEMAS_ELEM_CIRCULAR: * * a helper flag for the search of circular references. */ #define XML_SCHEMAS_ELEM_CIRCULAR 1 << 9 /** * XML_SCHEMAS_ELEM_BLOCK_ABSENT: * * the "block" attribute is absent */ #define XML_SCHEMAS_ELEM_BLOCK_ABSENT 1 << 10 /** * XML_SCHEMAS_ELEM_BLOCK_EXTENSION: * * disallowed substitutions are absent */ #define XML_SCHEMAS_ELEM_BLOCK_EXTENSION 1 << 11 /** * XML_SCHEMAS_ELEM_BLOCK_RESTRICTION: * * disallowed substitutions: "restriction" */ #define XML_SCHEMAS_ELEM_BLOCK_RESTRICTION 1 << 12 /** * XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION: * * disallowed substitutions: "substitution" */ #define XML_SCHEMAS_ELEM_BLOCK_SUBSTITUTION 1 << 13 /** * XML_SCHEMAS_ELEM_FINAL_ABSENT: * * substitution group exclusions are absent */ #define XML_SCHEMAS_ELEM_FINAL_ABSENT 1 << 14 /** * XML_SCHEMAS_ELEM_FINAL_EXTENSION: * * substitution group exclusions: "extension" */ #define XML_SCHEMAS_ELEM_FINAL_EXTENSION 1 << 15 /** * XML_SCHEMAS_ELEM_FINAL_RESTRICTION: * * substitution group exclusions: "restriction" */ #define XML_SCHEMAS_ELEM_FINAL_RESTRICTION 1 << 16 /** * XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD: * * the declaration is a substitution group head */ #define XML_SCHEMAS_ELEM_SUBST_GROUP_HEAD 1 << 17 /** * XML_SCHEMAS_ELEM_INTERNAL_CHECKED: * * this is set when the elem decl has been checked against * all constraints */ #define XML_SCHEMAS_ELEM_INTERNAL_CHECKED 1 << 18 typedef struct _xmlSchemaElement xmlSchemaElement; typedef xmlSchemaElement *xmlSchemaElementPtr; struct _xmlSchemaElement { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaType *next; /* Not used? */ const xmlChar *name; const xmlChar *id; /* Deprecated; not used */ const xmlChar *ref; /* Deprecated; not used */ const xmlChar *refNs; /* Deprecated; not used */ xmlSchemaAnnotPtr annot; xmlSchemaTypePtr subtypes; /* the type definition */ xmlSchemaAttributePtr attributes; xmlNodePtr node; int minOccurs; /* Deprecated; not used */ int maxOccurs; /* Deprecated; not used */ int flags; const xmlChar *targetNamespace; const xmlChar *namedType; const xmlChar *namedTypeNs; const xmlChar *substGroup; const xmlChar *substGroupNs; const xmlChar *scope; const xmlChar *value; /* The original value of the value constraint. */ struct _xmlSchemaElement *refDecl; /* This will now be used for the substitution group affiliation */ xmlRegexpPtr contModel; /* Obsolete for WXS, maybe used for RelaxNG */ xmlSchemaContentType contentType; const xmlChar *refPrefix; /* Deprecated; not used */ xmlSchemaValPtr defVal; /* The compiled value constraint. */ void *idcs; /* The identity-constraint defs */ }; /* * XML_SCHEMAS_FACET_UNKNOWN: * * unknown facet handling */ #define XML_SCHEMAS_FACET_UNKNOWN 0 /* * XML_SCHEMAS_FACET_PRESERVE: * * preserve the type of the facet */ #define XML_SCHEMAS_FACET_PRESERVE 1 /* * XML_SCHEMAS_FACET_REPLACE: * * replace the type of the facet */ #define XML_SCHEMAS_FACET_REPLACE 2 /* * XML_SCHEMAS_FACET_COLLAPSE: * * collapse the types of the facet */ #define XML_SCHEMAS_FACET_COLLAPSE 3 /** * A facet definition. */ struct _xmlSchemaFacet { xmlSchemaTypeType type; /* The kind of type */ struct _xmlSchemaFacet *next;/* the next type if in a sequence ... */ const xmlChar *value; /* The original value */ const xmlChar *id; /* Obsolete */ xmlSchemaAnnotPtr annot; xmlNodePtr node; int fixed; /* XML_SCHEMAS_FACET_PRESERVE, etc. */ int whitespace; xmlSchemaValPtr val; /* The compiled value */ xmlRegexpPtr regexp; /* The regex for patterns */ }; /** * A notation definition. */ typedef struct _xmlSchemaNotation xmlSchemaNotation; typedef xmlSchemaNotation *xmlSchemaNotationPtr; struct _xmlSchemaNotation { xmlSchemaTypeType type; /* The kind of type */ const xmlChar *name; xmlSchemaAnnotPtr annot; const xmlChar *identifier; const xmlChar *targetNamespace; }; /* * TODO: Actually all those flags used for the schema should sit * on the schema parser context, since they are used only * during parsing an XML schema document, and not available * on the component level as per spec. */ /** * XML_SCHEMAS_QUALIF_ELEM: * * Reflects elementFormDefault == qualified in * an XML schema document. */ #define XML_SCHEMAS_QUALIF_ELEM 1 << 0 /** * XML_SCHEMAS_QUALIF_ATTR: * * Reflects attributeFormDefault == qualified in * an XML schema document. */ #define XML_SCHEMAS_QUALIF_ATTR 1 << 1 /** * XML_SCHEMAS_FINAL_DEFAULT_EXTENSION: * * the schema has "extension" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_EXTENSION 1 << 2 /** * XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION: * * the schema has "restriction" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_RESTRICTION 1 << 3 /** * XML_SCHEMAS_FINAL_DEFAULT_LIST: * * the schema has "list" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_LIST 1 << 4 /** * XML_SCHEMAS_FINAL_DEFAULT_UNION: * * the schema has "union" in the set of finalDefault. */ #define XML_SCHEMAS_FINAL_DEFAULT_UNION 1 << 5 /** * XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION: * * the schema has "extension" in the set of blockDefault. */ #define XML_SCHEMAS_BLOCK_DEFAULT_EXTENSION 1 << 6 /** * XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION: * * the schema has "restriction" in the set of blockDefault. */ #define XML_SCHEMAS_BLOCK_DEFAULT_RESTRICTION 1 << 7 /** * XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION: * * the schema has "substitution" in the set of blockDefault. */ #define XML_SCHEMAS_BLOCK_DEFAULT_SUBSTITUTION 1 << 8 /** * XML_SCHEMAS_INCLUDING_CONVERT_NS: * * the schema is currently including an other schema with * no target namespace. */ #define XML_SCHEMAS_INCLUDING_CONVERT_NS 1 << 9 /** * _xmlSchema: * * A Schemas definition */ struct _xmlSchema { const xmlChar *name; /* schema name */ const xmlChar *targetNamespace; /* the target namespace */ const xmlChar *version; const xmlChar *id; /* Obsolete */ xmlDocPtr doc; xmlSchemaAnnotPtr annot; int flags; xmlHashTablePtr typeDecl; xmlHashTablePtr attrDecl; xmlHashTablePtr attrgrpDecl; xmlHashTablePtr elemDecl; xmlHashTablePtr notaDecl; xmlHashTablePtr schemasImports; void *_private; /* unused by the library for users or bindings */ xmlHashTablePtr groupDecl; xmlDictPtr dict; void *includes; /* the includes, this is opaque for now */ int preserve; /* whether to free the document */ int counter; /* used to give anonymous components unique names */ xmlHashTablePtr idcDef; /* All identity-constraint defs. */ void *volatiles; /* Obsolete */ }; XMLPUBFUN void xmlSchemaFreeType (xmlSchemaTypePtr type); XMLPUBFUN void xmlSchemaFreeWildcard(xmlSchemaWildcardPtr wildcard); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_SCHEMA_INTERNALS_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/schematron.h ================================================ /* * Summary: XML Schematron implementation * Description: interface to the XML Schematron validity checking. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMATRON_H__ #define __XML_SCHEMATRON_H__ #include #ifdef LIBXML_SCHEMATRON_ENABLED #include #ifdef __cplusplus extern "C" { #endif typedef enum { XML_SCHEMATRON_OUT_QUIET = 1 << 0, /* quiet no report */ XML_SCHEMATRON_OUT_TEXT = 1 << 1, /* build a textual report */ XML_SCHEMATRON_OUT_XML = 1 << 2, /* output SVRL */ XML_SCHEMATRON_OUT_ERROR = 1 << 3, /* output via xmlStructuredErrorFunc */ XML_SCHEMATRON_OUT_FILE = 1 << 8, /* output to a file descriptor */ XML_SCHEMATRON_OUT_BUFFER = 1 << 9, /* output to a buffer */ XML_SCHEMATRON_OUT_IO = 1 << 10 /* output to I/O mechanism */ } xmlSchematronValidOptions; /** * The schemas related types are kept internal */ typedef struct _xmlSchematron xmlSchematron; typedef xmlSchematron *xmlSchematronPtr; /** * xmlSchematronValidityErrorFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of an error callback from a Schematron validation */ typedef void (*xmlSchematronValidityErrorFunc) (void *ctx, const char *msg, ...); /** * xmlSchematronValidityWarningFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of a warning callback from a Schematron validation */ typedef void (*xmlSchematronValidityWarningFunc) (void *ctx, const char *msg, ...); /** * A schemas validation context */ typedef struct _xmlSchematronParserCtxt xmlSchematronParserCtxt; typedef xmlSchematronParserCtxt *xmlSchematronParserCtxtPtr; typedef struct _xmlSchematronValidCtxt xmlSchematronValidCtxt; typedef xmlSchematronValidCtxt *xmlSchematronValidCtxtPtr; /* * Interfaces for parsing. */ XMLPUBFUN xmlSchematronParserCtxtPtr xmlSchematronNewParserCtxt (const char *URL); XMLPUBFUN xmlSchematronParserCtxtPtr xmlSchematronNewMemParserCtxt(const char *buffer, int size); XMLPUBFUN xmlSchematronParserCtxtPtr xmlSchematronNewDocParserCtxt(xmlDocPtr doc); XMLPUBFUN void xmlSchematronFreeParserCtxt (xmlSchematronParserCtxtPtr ctxt); /***** XMLPUBFUN void xmlSchematronSetParserErrors(xmlSchematronParserCtxtPtr ctxt, xmlSchematronValidityErrorFunc err, xmlSchematronValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlSchematronGetParserErrors(xmlSchematronParserCtxtPtr ctxt, xmlSchematronValidityErrorFunc * err, xmlSchematronValidityWarningFunc * warn, void **ctx); XMLPUBFUN int xmlSchematronIsValid (xmlSchematronValidCtxtPtr ctxt); *****/ XMLPUBFUN xmlSchematronPtr xmlSchematronParse (xmlSchematronParserCtxtPtr ctxt); XMLPUBFUN void xmlSchematronFree (xmlSchematronPtr schema); /* * Interfaces for validating */ XMLPUBFUN void xmlSchematronSetValidStructuredErrors( xmlSchematronValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); /****** XMLPUBFUN void xmlSchematronSetValidErrors (xmlSchematronValidCtxtPtr ctxt, xmlSchematronValidityErrorFunc err, xmlSchematronValidityWarningFunc warn, void *ctx); XMLPUBFUN int xmlSchematronGetValidErrors (xmlSchematronValidCtxtPtr ctxt, xmlSchematronValidityErrorFunc *err, xmlSchematronValidityWarningFunc *warn, void **ctx); XMLPUBFUN int xmlSchematronSetValidOptions(xmlSchematronValidCtxtPtr ctxt, int options); XMLPUBFUN int xmlSchematronValidCtxtGetOptions(xmlSchematronValidCtxtPtr ctxt); XMLPUBFUN int xmlSchematronValidateOneElement (xmlSchematronValidCtxtPtr ctxt, xmlNodePtr elem); *******/ XMLPUBFUN xmlSchematronValidCtxtPtr xmlSchematronNewValidCtxt (xmlSchematronPtr schema, int options); XMLPUBFUN void xmlSchematronFreeValidCtxt (xmlSchematronValidCtxtPtr ctxt); XMLPUBFUN int xmlSchematronValidateDoc (xmlSchematronValidCtxtPtr ctxt, xmlDocPtr instance); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMATRON_ENABLED */ #endif /* __XML_SCHEMATRON_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/threads.h ================================================ /** * Summary: interfaces for thread handling * Description: set of generic threading related routines * should work with pthreads, Windows native or TLS threads * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_THREADS_H__ #define __XML_THREADS_H__ #include #ifdef __cplusplus extern "C" { #endif /* * xmlMutex are a simple mutual exception locks. */ typedef struct _xmlMutex xmlMutex; typedef xmlMutex *xmlMutexPtr; /* * xmlRMutex are reentrant mutual exception locks. */ typedef struct _xmlRMutex xmlRMutex; typedef xmlRMutex *xmlRMutexPtr; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif XMLPUBFUN xmlMutexPtr xmlNewMutex (void); XMLPUBFUN void xmlMutexLock (xmlMutexPtr tok); XMLPUBFUN void xmlMutexUnlock (xmlMutexPtr tok); XMLPUBFUN void xmlFreeMutex (xmlMutexPtr tok); XMLPUBFUN xmlRMutexPtr xmlNewRMutex (void); XMLPUBFUN void xmlRMutexLock (xmlRMutexPtr tok); XMLPUBFUN void xmlRMutexUnlock (xmlRMutexPtr tok); XMLPUBFUN void xmlFreeRMutex (xmlRMutexPtr tok); /* * Library wide APIs. */ XML_DEPRECATED XMLPUBFUN void xmlInitThreads (void); XMLPUBFUN void xmlLockLibrary (void); XMLPUBFUN void xmlUnlockLibrary(void); XML_DEPRECATED XMLPUBFUN int xmlGetThreadId (void); XML_DEPRECATED XMLPUBFUN int xmlIsMainThread (void); XML_DEPRECATED XMLPUBFUN void xmlCleanupThreads(void); XML_DEPRECATED XMLPUBFUN xmlGlobalStatePtr xmlGetGlobalState(void); /** DOC_DISABLE */ #if defined(LIBXML_THREAD_ENABLED) && defined(_WIN32) && \ !defined(HAVE_COMPILER_TLS) && defined(LIBXML_STATIC_FOR_DLL) int xmlDllMain(void *hinstDLL, unsigned long fdwReason, void *lpvReserved); #endif /** DOC_ENABLE */ #ifdef __cplusplus } #endif #endif /* __XML_THREADS_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/tree.h ================================================ /* * Summary: interfaces for tree manipulation * Description: this module describes the structures found in an tree resulting * from an XML or HTML parsing, as well as the API provided for * various processing on that tree * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_TREE_H__ #define __XML_TREE_H__ #include #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Some of the basic types pointer to structures: */ /* xmlIO.h */ typedef struct _xmlParserInputBuffer xmlParserInputBuffer; typedef xmlParserInputBuffer *xmlParserInputBufferPtr; typedef struct _xmlOutputBuffer xmlOutputBuffer; typedef xmlOutputBuffer *xmlOutputBufferPtr; /* parser.h */ typedef struct _xmlParserInput xmlParserInput; typedef xmlParserInput *xmlParserInputPtr; typedef struct _xmlParserCtxt xmlParserCtxt; typedef xmlParserCtxt *xmlParserCtxtPtr; typedef struct _xmlSAXLocator xmlSAXLocator; typedef xmlSAXLocator *xmlSAXLocatorPtr; typedef struct _xmlSAXHandler xmlSAXHandler; typedef xmlSAXHandler *xmlSAXHandlerPtr; /* entities.h */ typedef struct _xmlEntity xmlEntity; typedef xmlEntity *xmlEntityPtr; /** * BASE_BUFFER_SIZE: * * default buffer size 4000. */ #define BASE_BUFFER_SIZE 4096 /** * LIBXML_NAMESPACE_DICT: * * Defines experimental behaviour: * 1) xmlNs gets an additional field @context (a xmlDoc) * 2) when creating a tree, xmlNs->href is stored in the dict of xmlDoc. */ /* #define LIBXML_NAMESPACE_DICT */ /** * xmlBufferAllocationScheme: * * A buffer allocation scheme can be defined to either match exactly the * need or double it's allocated size each time it is found too small. */ typedef enum { XML_BUFFER_ALLOC_DOUBLEIT, /* double each time one need to grow */ XML_BUFFER_ALLOC_EXACT, /* grow only to the minimal size */ XML_BUFFER_ALLOC_IMMUTABLE, /* immutable buffer, deprecated */ XML_BUFFER_ALLOC_IO, /* special allocation scheme used for I/O */ XML_BUFFER_ALLOC_HYBRID, /* exact up to a threshold, and doubleit thereafter */ XML_BUFFER_ALLOC_BOUNDED /* limit the upper size of the buffer */ } xmlBufferAllocationScheme; /** * xmlBuffer: * * A buffer structure, this old construct is limited to 2GB and * is being deprecated, use API with xmlBuf instead */ typedef struct _xmlBuffer xmlBuffer; typedef xmlBuffer *xmlBufferPtr; struct _xmlBuffer { xmlChar *content; /* The buffer content UTF8 */ unsigned int use; /* The buffer size used */ unsigned int size; /* The buffer size */ xmlBufferAllocationScheme alloc; /* The realloc method */ xmlChar *contentIO; /* in IO mode we may have a different base */ }; /** * xmlBuf: * * A buffer structure, new one, the actual structure internals are not public */ typedef struct _xmlBuf xmlBuf; /** * xmlBufPtr: * * A pointer to a buffer structure, the actual structure internals are not * public */ typedef xmlBuf *xmlBufPtr; /* * A few public routines for xmlBuf. As those are expected to be used * mostly internally the bulk of the routines are internal in buf.h */ XMLPUBFUN xmlChar* xmlBufContent (const xmlBuf* buf); XMLPUBFUN xmlChar* xmlBufEnd (xmlBufPtr buf); XMLPUBFUN size_t xmlBufUse (const xmlBufPtr buf); XMLPUBFUN size_t xmlBufShrink (xmlBufPtr buf, size_t len); /* * LIBXML2_NEW_BUFFER: * * Macro used to express that the API use the new buffers for * xmlParserInputBuffer and xmlOutputBuffer. The change was * introduced in 2.9.0. */ #define LIBXML2_NEW_BUFFER /** * XML_XML_NAMESPACE: * * This is the namespace for the special xml: prefix predefined in the * XML Namespace specification. */ #define XML_XML_NAMESPACE \ (const xmlChar *) "http://www.w3.org/XML/1998/namespace" /** * XML_XML_ID: * * This is the name for the special xml:id attribute */ #define XML_XML_ID (const xmlChar *) "xml:id" /* * The different element types carried by an XML tree. * * NOTE: This is synchronized with DOM Level1 values * See http://www.w3.org/TR/REC-DOM-Level-1/ * * Actually this had diverged a bit, and now XML_DOCUMENT_TYPE_NODE should * be deprecated to use an XML_DTD_NODE. */ typedef enum { XML_ELEMENT_NODE= 1, XML_ATTRIBUTE_NODE= 2, XML_TEXT_NODE= 3, XML_CDATA_SECTION_NODE= 4, XML_ENTITY_REF_NODE= 5, XML_ENTITY_NODE= 6, XML_PI_NODE= 7, XML_COMMENT_NODE= 8, XML_DOCUMENT_NODE= 9, XML_DOCUMENT_TYPE_NODE= 10, XML_DOCUMENT_FRAG_NODE= 11, XML_NOTATION_NODE= 12, XML_HTML_DOCUMENT_NODE= 13, XML_DTD_NODE= 14, XML_ELEMENT_DECL= 15, XML_ATTRIBUTE_DECL= 16, XML_ENTITY_DECL= 17, XML_NAMESPACE_DECL= 18, XML_XINCLUDE_START= 19, XML_XINCLUDE_END= 20 /* XML_DOCB_DOCUMENT_NODE= 21 */ /* removed */ } xmlElementType; /** DOC_DISABLE */ /* For backward compatibility */ #define XML_DOCB_DOCUMENT_NODE 21 /** DOC_ENABLE */ /** * xmlNotation: * * A DTD Notation definition. */ typedef struct _xmlNotation xmlNotation; typedef xmlNotation *xmlNotationPtr; struct _xmlNotation { const xmlChar *name; /* Notation name */ const xmlChar *PublicID; /* Public identifier, if any */ const xmlChar *SystemID; /* System identifier, if any */ }; /** * xmlAttributeType: * * A DTD Attribute type definition. */ typedef enum { XML_ATTRIBUTE_CDATA = 1, XML_ATTRIBUTE_ID, XML_ATTRIBUTE_IDREF , XML_ATTRIBUTE_IDREFS, XML_ATTRIBUTE_ENTITY, XML_ATTRIBUTE_ENTITIES, XML_ATTRIBUTE_NMTOKEN, XML_ATTRIBUTE_NMTOKENS, XML_ATTRIBUTE_ENUMERATION, XML_ATTRIBUTE_NOTATION } xmlAttributeType; /** * xmlAttributeDefault: * * A DTD Attribute default definition. */ typedef enum { XML_ATTRIBUTE_NONE = 1, XML_ATTRIBUTE_REQUIRED, XML_ATTRIBUTE_IMPLIED, XML_ATTRIBUTE_FIXED } xmlAttributeDefault; /** * xmlEnumeration: * * List structure used when there is an enumeration in DTDs. */ typedef struct _xmlEnumeration xmlEnumeration; typedef xmlEnumeration *xmlEnumerationPtr; struct _xmlEnumeration { struct _xmlEnumeration *next; /* next one */ const xmlChar *name; /* Enumeration name */ }; /** * xmlAttribute: * * An Attribute declaration in a DTD. */ typedef struct _xmlAttribute xmlAttribute; typedef xmlAttribute *xmlAttributePtr; struct _xmlAttribute { void *_private; /* application data */ xmlElementType type; /* XML_ATTRIBUTE_DECL, must be second ! */ const xmlChar *name; /* Attribute name */ struct _xmlNode *children; /* NULL */ struct _xmlNode *last; /* NULL */ struct _xmlDtd *parent; /* -> DTD */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ struct _xmlAttribute *nexth; /* next in hash table */ xmlAttributeType atype; /* The attribute type */ xmlAttributeDefault def; /* the default */ const xmlChar *defaultValue; /* or the default value */ xmlEnumerationPtr tree; /* or the enumeration tree if any */ const xmlChar *prefix; /* the namespace prefix if any */ const xmlChar *elem; /* Element holding the attribute */ }; /** * xmlElementContentType: * * Possible definitions of element content types. */ typedef enum { XML_ELEMENT_CONTENT_PCDATA = 1, XML_ELEMENT_CONTENT_ELEMENT, XML_ELEMENT_CONTENT_SEQ, XML_ELEMENT_CONTENT_OR } xmlElementContentType; /** * xmlElementContentOccur: * * Possible definitions of element content occurrences. */ typedef enum { XML_ELEMENT_CONTENT_ONCE = 1, XML_ELEMENT_CONTENT_OPT, XML_ELEMENT_CONTENT_MULT, XML_ELEMENT_CONTENT_PLUS } xmlElementContentOccur; /** * xmlElementContent: * * An XML Element content as stored after parsing an element definition * in a DTD. */ typedef struct _xmlElementContent xmlElementContent; typedef xmlElementContent *xmlElementContentPtr; struct _xmlElementContent { xmlElementContentType type; /* PCDATA, ELEMENT, SEQ or OR */ xmlElementContentOccur ocur; /* ONCE, OPT, MULT or PLUS */ const xmlChar *name; /* Element name */ struct _xmlElementContent *c1; /* first child */ struct _xmlElementContent *c2; /* second child */ struct _xmlElementContent *parent; /* parent */ const xmlChar *prefix; /* Namespace prefix */ }; /** * xmlElementTypeVal: * * The different possibilities for an element content type. */ typedef enum { XML_ELEMENT_TYPE_UNDEFINED = 0, XML_ELEMENT_TYPE_EMPTY = 1, XML_ELEMENT_TYPE_ANY, XML_ELEMENT_TYPE_MIXED, XML_ELEMENT_TYPE_ELEMENT } xmlElementTypeVal; #ifdef __cplusplus } #endif #include #ifdef __cplusplus extern "C" { #endif /** * xmlElement: * * An XML Element declaration from a DTD. */ typedef struct _xmlElement xmlElement; typedef xmlElement *xmlElementPtr; struct _xmlElement { void *_private; /* application data */ xmlElementType type; /* XML_ELEMENT_DECL, must be second ! */ const xmlChar *name; /* Element name */ struct _xmlNode *children; /* NULL */ struct _xmlNode *last; /* NULL */ struct _xmlDtd *parent; /* -> DTD */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ xmlElementTypeVal etype; /* The type */ xmlElementContentPtr content; /* the allowed element content */ xmlAttributePtr attributes; /* List of the declared attributes */ const xmlChar *prefix; /* the namespace prefix if any */ #ifdef LIBXML_REGEXP_ENABLED xmlRegexpPtr contModel; /* the validating regexp */ #else void *contModel; #endif }; /** * XML_LOCAL_NAMESPACE: * * A namespace declaration node. */ #define XML_LOCAL_NAMESPACE XML_NAMESPACE_DECL typedef xmlElementType xmlNsType; /** * xmlNs: * * An XML namespace. * Note that prefix == NULL is valid, it defines the default namespace * within the subtree (until overridden). * * xmlNsType is unified with xmlElementType. */ typedef struct _xmlNs xmlNs; typedef xmlNs *xmlNsPtr; struct _xmlNs { struct _xmlNs *next; /* next Ns link for this node */ xmlNsType type; /* global or local */ const xmlChar *href; /* URL for the namespace */ const xmlChar *prefix; /* prefix for the namespace */ void *_private; /* application data */ struct _xmlDoc *context; /* normally an xmlDoc */ }; /** * xmlDtd: * * An XML DTD, as defined by parent link */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ /* End of common part */ void *notations; /* Hash table for notations if any */ void *elements; /* Hash table for elements if any */ void *attributes; /* Hash table for attributes if any */ void *entities; /* Hash table for entities if any */ const xmlChar *ExternalID; /* External identifier for PUBLIC DTD */ const xmlChar *SystemID; /* URI for a SYSTEM or PUBLIC DTD */ void *pentities; /* Hash table for param entities if any */ }; /** * xmlAttr: * * An attribute on an XML node. */ typedef struct _xmlAttr xmlAttr; typedef xmlAttr *xmlAttrPtr; struct _xmlAttr { void *_private; /* application data */ xmlElementType type; /* XML_ATTRIBUTE_NODE, must be second ! */ const xmlChar *name; /* the name of the property */ struct _xmlNode *children; /* the value of the property */ struct _xmlNode *last; /* NULL */ struct _xmlNode *parent; /* child->parent link */ struct _xmlAttr *next; /* next sibling link */ struct _xmlAttr *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ xmlNs *ns; /* pointer to the associated namespace */ xmlAttributeType atype; /* the attribute type if validating */ void *psvi; /* for type/PSVI information */ }; /** * xmlID: * * An XML ID instance. */ typedef struct _xmlID xmlID; typedef xmlID *xmlIDPtr; struct _xmlID { struct _xmlID *next; /* next ID */ const xmlChar *value; /* The ID name */ xmlAttrPtr attr; /* The attribute holding it */ const xmlChar *name; /* The attribute if attr is not available */ int lineno; /* The line number if attr is not available */ struct _xmlDoc *doc; /* The document holding the ID */ }; /** * xmlRef: * * An XML IDREF instance. */ typedef struct _xmlRef xmlRef; typedef xmlRef *xmlRefPtr; struct _xmlRef { struct _xmlRef *next; /* next Ref */ const xmlChar *value; /* The Ref name */ xmlAttrPtr attr; /* The attribute holding it */ const xmlChar *name; /* The attribute if attr is not available */ int lineno; /* The line number if attr is not available */ }; /** * xmlNode: * * A node in an XML tree. */ typedef struct _xmlNode xmlNode; typedef xmlNode *xmlNodePtr; struct _xmlNode { void *_private; /* application data */ xmlElementType type; /* type number, must be second ! */ const xmlChar *name; /* the name of the node, or the entity */ struct _xmlNode *children; /* parent->childs link */ struct _xmlNode *last; /* last child link */ struct _xmlNode *parent; /* child->parent link */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* the containing document */ /* End of common part */ xmlNs *ns; /* pointer to the associated namespace */ xmlChar *content; /* the content */ struct _xmlAttr *properties;/* properties list */ xmlNs *nsDef; /* namespace definitions on this node */ void *psvi; /* for type/PSVI information */ unsigned short line; /* line number */ unsigned short extra; /* extra data for XPath/XSLT */ }; /** * XML_GET_CONTENT: * * Macro to extract the content pointer of a node. */ #define XML_GET_CONTENT(n) \ ((n)->type == XML_ELEMENT_NODE ? NULL : (n)->content) /** * XML_GET_LINE: * * Macro to extract the line number of an element node. */ #define XML_GET_LINE(n) \ (xmlGetLineNo(n)) /** * xmlDocProperty * * Set of properties of the document as found by the parser * Some of them are linked to similarly named xmlParserOption */ typedef enum { XML_DOC_WELLFORMED = 1<<0, /* document is XML well formed */ XML_DOC_NSVALID = 1<<1, /* document is Namespace valid */ XML_DOC_OLD10 = 1<<2, /* parsed with old XML-1.0 parser */ XML_DOC_DTDVALID = 1<<3, /* DTD validation was successful */ XML_DOC_XINCLUDE = 1<<4, /* XInclude substitution was done */ XML_DOC_USERBUILT = 1<<5, /* Document was built using the API and not by parsing an instance */ XML_DOC_INTERNAL = 1<<6, /* built for internal processing */ XML_DOC_HTML = 1<<7 /* parsed or built HTML document */ } xmlDocProperties; /** * xmlDoc: * * An XML document. */ typedef struct _xmlDoc xmlDoc; typedef xmlDoc *xmlDocPtr; struct _xmlDoc { void *_private; /* application data */ xmlElementType type; /* XML_DOCUMENT_NODE, must be second ! */ char *name; /* name/filename/URI of the document */ struct _xmlNode *children; /* the document tree */ struct _xmlNode *last; /* last child link */ struct _xmlNode *parent; /* child->parent link */ struct _xmlNode *next; /* next sibling link */ struct _xmlNode *prev; /* previous sibling link */ struct _xmlDoc *doc; /* autoreference to itself */ /* End of common part */ int compression;/* level of zlib compression */ int standalone; /* standalone document (no external refs) 1 if standalone="yes" 0 if standalone="no" -1 if there is no XML declaration -2 if there is an XML declaration, but no standalone attribute was specified */ struct _xmlDtd *intSubset; /* the document internal subset */ struct _xmlDtd *extSubset; /* the document external subset */ struct _xmlNs *oldNs; /* Global namespace, the old way */ const xmlChar *version; /* the XML version string */ const xmlChar *encoding; /* external initial encoding, if any */ void *ids; /* Hash table for ID attributes if any */ void *refs; /* Hash table for IDREFs attributes if any */ const xmlChar *URL; /* The URI for that document */ int charset; /* Internal flag for charset handling, actually an xmlCharEncoding */ struct _xmlDict *dict; /* dict used to allocate names or NULL */ void *psvi; /* for type/PSVI information */ int parseFlags; /* set of xmlParserOption used to parse the document */ int properties; /* set of xmlDocProperties for this document set at the end of parsing */ }; typedef struct _xmlDOMWrapCtxt xmlDOMWrapCtxt; typedef xmlDOMWrapCtxt *xmlDOMWrapCtxtPtr; /** * xmlDOMWrapAcquireNsFunction: * @ctxt: a DOM wrapper context * @node: the context node (element or attribute) * @nsName: the requested namespace name * @nsPrefix: the requested namespace prefix * * A function called to acquire namespaces (xmlNs) from the wrapper. * * Returns an xmlNsPtr or NULL in case of an error. */ typedef xmlNsPtr (*xmlDOMWrapAcquireNsFunction) (xmlDOMWrapCtxtPtr ctxt, xmlNodePtr node, const xmlChar *nsName, const xmlChar *nsPrefix); /** * xmlDOMWrapCtxt: * * Context for DOM wrapper-operations. */ struct _xmlDOMWrapCtxt { void * _private; /* * The type of this context, just in case we need specialized * contexts in the future. */ int type; /* * Internal namespace map used for various operations. */ void * namespaceMap; /* * Use this one to acquire an xmlNsPtr intended for node->ns. * (Note that this is not intended for elem->nsDef). */ xmlDOMWrapAcquireNsFunction getNsForNodeFunc; }; /** * xmlChildrenNode: * * Macro for compatibility naming layer with libxml1. Maps * to "children." */ #ifndef xmlChildrenNode #define xmlChildrenNode children #endif /** * xmlRootNode: * * Macro for compatibility naming layer with libxml1. Maps * to "children". */ #ifndef xmlRootNode #define xmlRootNode children #endif /* * Variables. */ /* * Some helper functions */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_DEBUG_ENABLED) || \ defined (LIBXML_HTML_ENABLED) || defined(LIBXML_SAX1_ENABLED) || \ defined(LIBXML_HTML_ENABLED) || defined(LIBXML_WRITER_ENABLED) || \ defined(LIBXML_LEGACY_ENABLED) XMLPUBFUN int xmlValidateNCName (const xmlChar *value, int space); #endif #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN int xmlValidateQName (const xmlChar *value, int space); XMLPUBFUN int xmlValidateName (const xmlChar *value, int space); XMLPUBFUN int xmlValidateNMToken (const xmlChar *value, int space); #endif XMLPUBFUN xmlChar * xmlBuildQName (const xmlChar *ncname, const xmlChar *prefix, xmlChar *memory, int len); XMLPUBFUN xmlChar * xmlSplitQName2 (const xmlChar *name, xmlChar **prefix); XMLPUBFUN const xmlChar * xmlSplitQName3 (const xmlChar *name, int *len); /* * Handling Buffers, the old ones see @xmlBuf for the new ones. */ XMLPUBFUN void xmlSetBufferAllocationScheme(xmlBufferAllocationScheme scheme); XMLPUBFUN xmlBufferAllocationScheme xmlGetBufferAllocationScheme(void); XMLPUBFUN xmlBufferPtr xmlBufferCreate (void); XMLPUBFUN xmlBufferPtr xmlBufferCreateSize (size_t size); XMLPUBFUN xmlBufferPtr xmlBufferCreateStatic (void *mem, size_t size); XMLPUBFUN int xmlBufferResize (xmlBufferPtr buf, unsigned int size); XMLPUBFUN void xmlBufferFree (xmlBufferPtr buf); XMLPUBFUN int xmlBufferDump (FILE *file, xmlBufferPtr buf); XMLPUBFUN int xmlBufferAdd (xmlBufferPtr buf, const xmlChar *str, int len); XMLPUBFUN int xmlBufferAddHead (xmlBufferPtr buf, const xmlChar *str, int len); XMLPUBFUN int xmlBufferCat (xmlBufferPtr buf, const xmlChar *str); XMLPUBFUN int xmlBufferCCat (xmlBufferPtr buf, const char *str); XMLPUBFUN int xmlBufferShrink (xmlBufferPtr buf, unsigned int len); XMLPUBFUN int xmlBufferGrow (xmlBufferPtr buf, unsigned int len); XMLPUBFUN void xmlBufferEmpty (xmlBufferPtr buf); XMLPUBFUN const xmlChar* xmlBufferContent (const xmlBuffer *buf); XMLPUBFUN xmlChar* xmlBufferDetach (xmlBufferPtr buf); XMLPUBFUN void xmlBufferSetAllocationScheme(xmlBufferPtr buf, xmlBufferAllocationScheme scheme); XMLPUBFUN int xmlBufferLength (const xmlBuffer *buf); /* * Creating/freeing new structures. */ XMLPUBFUN xmlDtdPtr xmlCreateIntSubset (xmlDocPtr doc, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlNewDtd (xmlDocPtr doc, const xmlChar *name, const xmlChar *ExternalID, const xmlChar *SystemID); XMLPUBFUN xmlDtdPtr xmlGetIntSubset (const xmlDoc *doc); XMLPUBFUN void xmlFreeDtd (xmlDtdPtr cur); #ifdef LIBXML_LEGACY_ENABLED XML_DEPRECATED XMLPUBFUN xmlNsPtr xmlNewGlobalNs (xmlDocPtr doc, const xmlChar *href, const xmlChar *prefix); #endif /* LIBXML_LEGACY_ENABLED */ XMLPUBFUN xmlNsPtr xmlNewNs (xmlNodePtr node, const xmlChar *href, const xmlChar *prefix); XMLPUBFUN void xmlFreeNs (xmlNsPtr cur); XMLPUBFUN void xmlFreeNsList (xmlNsPtr cur); XMLPUBFUN xmlDocPtr xmlNewDoc (const xmlChar *version); XMLPUBFUN void xmlFreeDoc (xmlDocPtr cur); XMLPUBFUN xmlAttrPtr xmlNewDocProp (xmlDocPtr doc, const xmlChar *name, const xmlChar *value); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlAttrPtr xmlNewProp (xmlNodePtr node, const xmlChar *name, const xmlChar *value); #endif XMLPUBFUN xmlAttrPtr xmlNewNsProp (xmlNodePtr node, xmlNsPtr ns, const xmlChar *name, const xmlChar *value); XMLPUBFUN xmlAttrPtr xmlNewNsPropEatName (xmlNodePtr node, xmlNsPtr ns, xmlChar *name, const xmlChar *value); XMLPUBFUN void xmlFreePropList (xmlAttrPtr cur); XMLPUBFUN void xmlFreeProp (xmlAttrPtr cur); XMLPUBFUN xmlAttrPtr xmlCopyProp (xmlNodePtr target, xmlAttrPtr cur); XMLPUBFUN xmlAttrPtr xmlCopyPropList (xmlNodePtr target, xmlAttrPtr cur); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlDtdPtr xmlCopyDtd (xmlDtdPtr dtd); #endif /* LIBXML_TREE_ENABLED */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlDocPtr xmlCopyDoc (xmlDocPtr doc, int recursive); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) */ /* * Creating new nodes. */ XMLPUBFUN xmlNodePtr xmlNewDocNode (xmlDocPtr doc, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocNodeEatName (xmlDocPtr doc, xmlNsPtr ns, xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewNode (xmlNsPtr ns, const xmlChar *name); XMLPUBFUN xmlNodePtr xmlNewNodeEatName (xmlNsPtr ns, xmlChar *name); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlNodePtr xmlNewChild (xmlNodePtr parent, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); #endif XMLPUBFUN xmlNodePtr xmlNewDocText (const xmlDoc *doc, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewText (const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocPI (xmlDocPtr doc, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewPI (const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocTextLen (xmlDocPtr doc, const xmlChar *content, int len); XMLPUBFUN xmlNodePtr xmlNewTextLen (const xmlChar *content, int len); XMLPUBFUN xmlNodePtr xmlNewDocComment (xmlDocPtr doc, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewComment (const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewCDataBlock (xmlDocPtr doc, const xmlChar *content, int len); XMLPUBFUN xmlNodePtr xmlNewCharRef (xmlDocPtr doc, const xmlChar *name); XMLPUBFUN xmlNodePtr xmlNewReference (const xmlDoc *doc, const xmlChar *name); XMLPUBFUN xmlNodePtr xmlCopyNode (xmlNodePtr node, int recursive); XMLPUBFUN xmlNodePtr xmlDocCopyNode (xmlNodePtr node, xmlDocPtr doc, int recursive); XMLPUBFUN xmlNodePtr xmlDocCopyNodeList (xmlDocPtr doc, xmlNodePtr node); XMLPUBFUN xmlNodePtr xmlCopyNodeList (xmlNodePtr node); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlNodePtr xmlNewTextChild (xmlNodePtr parent, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocRawNode (xmlDocPtr doc, xmlNsPtr ns, const xmlChar *name, const xmlChar *content); XMLPUBFUN xmlNodePtr xmlNewDocFragment (xmlDocPtr doc); #endif /* LIBXML_TREE_ENABLED */ /* * Navigating. */ XMLPUBFUN long xmlGetLineNo (const xmlNode *node); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) XMLPUBFUN xmlChar * xmlGetNodePath (const xmlNode *node); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_DEBUG_ENABLED) */ XMLPUBFUN xmlNodePtr xmlDocGetRootElement (const xmlDoc *doc); XMLPUBFUN xmlNodePtr xmlGetLastChild (const xmlNode *parent); XMLPUBFUN int xmlNodeIsText (const xmlNode *node); XMLPUBFUN int xmlIsBlankNode (const xmlNode *node); /* * Changing the structure. */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) XMLPUBFUN xmlNodePtr xmlDocSetRootElement (xmlDocPtr doc, xmlNodePtr root); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */ #ifdef LIBXML_TREE_ENABLED XMLPUBFUN void xmlNodeSetName (xmlNodePtr cur, const xmlChar *name); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN xmlNodePtr xmlAddChild (xmlNodePtr parent, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlAddChildList (xmlNodePtr parent, xmlNodePtr cur); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) XMLPUBFUN xmlNodePtr xmlReplaceNode (xmlNodePtr old, xmlNodePtr cur); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_WRITER_ENABLED) */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_HTML_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) XMLPUBFUN xmlNodePtr xmlAddPrevSibling (xmlNodePtr cur, xmlNodePtr elem); #endif /* LIBXML_TREE_ENABLED || LIBXML_HTML_ENABLED || LIBXML_SCHEMAS_ENABLED */ XMLPUBFUN xmlNodePtr xmlAddSibling (xmlNodePtr cur, xmlNodePtr elem); XMLPUBFUN xmlNodePtr xmlAddNextSibling (xmlNodePtr cur, xmlNodePtr elem); XMLPUBFUN void xmlUnlinkNode (xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlTextMerge (xmlNodePtr first, xmlNodePtr second); XMLPUBFUN int xmlTextConcat (xmlNodePtr node, const xmlChar *content, int len); XMLPUBFUN void xmlFreeNodeList (xmlNodePtr cur); XMLPUBFUN void xmlFreeNode (xmlNodePtr cur); XMLPUBFUN void xmlSetTreeDoc (xmlNodePtr tree, xmlDocPtr doc); XMLPUBFUN void xmlSetListDoc (xmlNodePtr list, xmlDocPtr doc); /* * Namespaces. */ XMLPUBFUN xmlNsPtr xmlSearchNs (xmlDocPtr doc, xmlNodePtr node, const xmlChar *nameSpace); XMLPUBFUN xmlNsPtr xmlSearchNsByHref (xmlDocPtr doc, xmlNodePtr node, const xmlChar *href); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN xmlNsPtr * xmlGetNsList (const xmlDoc *doc, const xmlNode *node); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XPATH_ENABLED) */ XMLPUBFUN void xmlSetNs (xmlNodePtr node, xmlNsPtr ns); XMLPUBFUN xmlNsPtr xmlCopyNamespace (xmlNsPtr cur); XMLPUBFUN xmlNsPtr xmlCopyNamespaceList (xmlNsPtr cur); /* * Changing the content. */ #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) XMLPUBFUN xmlAttrPtr xmlSetProp (xmlNodePtr node, const xmlChar *name, const xmlChar *value); XMLPUBFUN xmlAttrPtr xmlSetNsProp (xmlNodePtr node, xmlNsPtr ns, const xmlChar *name, const xmlChar *value); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) || \ defined(LIBXML_SCHEMAS_ENABLED) || defined(LIBXML_HTML_ENABLED) */ XMLPUBFUN xmlChar * xmlGetNoNsProp (const xmlNode *node, const xmlChar *name); XMLPUBFUN xmlChar * xmlGetProp (const xmlNode *node, const xmlChar *name); XMLPUBFUN xmlAttrPtr xmlHasProp (const xmlNode *node, const xmlChar *name); XMLPUBFUN xmlAttrPtr xmlHasNsProp (const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace); XMLPUBFUN xmlChar * xmlGetNsProp (const xmlNode *node, const xmlChar *name, const xmlChar *nameSpace); XMLPUBFUN xmlNodePtr xmlStringGetNodeList (const xmlDoc *doc, const xmlChar *value); XMLPUBFUN xmlNodePtr xmlStringLenGetNodeList (const xmlDoc *doc, const xmlChar *value, int len); XMLPUBFUN xmlChar * xmlNodeListGetString (xmlDocPtr doc, const xmlNode *list, int inLine); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlChar * xmlNodeListGetRawString (const xmlDoc *doc, const xmlNode *list, int inLine); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlNodeSetContent (xmlNodePtr cur, const xmlChar *content); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN void xmlNodeSetContentLen (xmlNodePtr cur, const xmlChar *content, int len); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlNodeAddContent (xmlNodePtr cur, const xmlChar *content); XMLPUBFUN void xmlNodeAddContentLen (xmlNodePtr cur, const xmlChar *content, int len); XMLPUBFUN xmlChar * xmlNodeGetContent (const xmlNode *cur); XMLPUBFUN int xmlNodeBufGetContent (xmlBufferPtr buffer, const xmlNode *cur); XMLPUBFUN int xmlBufGetNodeContent (xmlBufPtr buf, const xmlNode *cur); XMLPUBFUN xmlChar * xmlNodeGetLang (const xmlNode *cur); XMLPUBFUN int xmlNodeGetSpacePreserve (const xmlNode *cur); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN void xmlNodeSetLang (xmlNodePtr cur, const xmlChar *lang); XMLPUBFUN void xmlNodeSetSpacePreserve (xmlNodePtr cur, int val); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN xmlChar * xmlNodeGetBase (const xmlDoc *doc, const xmlNode *cur); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_XINCLUDE_ENABLED) XMLPUBFUN void xmlNodeSetBase (xmlNodePtr cur, const xmlChar *uri); #endif /* * Removing content. */ XMLPUBFUN int xmlRemoveProp (xmlAttrPtr cur); #if defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN int xmlUnsetNsProp (xmlNodePtr node, xmlNsPtr ns, const xmlChar *name); XMLPUBFUN int xmlUnsetProp (xmlNodePtr node, const xmlChar *name); #endif /* defined(LIBXML_TREE_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) */ /* * Internal, don't use. */ XMLPUBFUN void xmlBufferWriteCHAR (xmlBufferPtr buf, const xmlChar *string); XMLPUBFUN void xmlBufferWriteChar (xmlBufferPtr buf, const char *string); XMLPUBFUN void xmlBufferWriteQuotedString(xmlBufferPtr buf, const xmlChar *string); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlAttrSerializeTxtContent(xmlBufferPtr buf, xmlDocPtr doc, xmlAttrPtr attr, const xmlChar *string); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef LIBXML_TREE_ENABLED /* * Namespace handling. */ XMLPUBFUN int xmlReconciliateNs (xmlDocPtr doc, xmlNodePtr tree); #endif #ifdef LIBXML_OUTPUT_ENABLED /* * Saving. */ XMLPUBFUN void xmlDocDumpFormatMemory (xmlDocPtr cur, xmlChar **mem, int *size, int format); XMLPUBFUN void xmlDocDumpMemory (xmlDocPtr cur, xmlChar **mem, int *size); XMLPUBFUN void xmlDocDumpMemoryEnc (xmlDocPtr out_doc, xmlChar **doc_txt_ptr, int * doc_txt_len, const char *txt_encoding); XMLPUBFUN void xmlDocDumpFormatMemoryEnc(xmlDocPtr out_doc, xmlChar **doc_txt_ptr, int * doc_txt_len, const char *txt_encoding, int format); XMLPUBFUN int xmlDocFormatDump (FILE *f, xmlDocPtr cur, int format); XMLPUBFUN int xmlDocDump (FILE *f, xmlDocPtr cur); XMLPUBFUN void xmlElemDump (FILE *f, xmlDocPtr doc, xmlNodePtr cur); XMLPUBFUN int xmlSaveFile (const char *filename, xmlDocPtr cur); XMLPUBFUN int xmlSaveFormatFile (const char *filename, xmlDocPtr cur, int format); XMLPUBFUN size_t xmlBufNodeDump (xmlBufPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format); XMLPUBFUN int xmlNodeDump (xmlBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format); XMLPUBFUN int xmlSaveFileTo (xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding); XMLPUBFUN int xmlSaveFormatFileTo (xmlOutputBufferPtr buf, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN void xmlNodeDumpOutput (xmlOutputBufferPtr buf, xmlDocPtr doc, xmlNodePtr cur, int level, int format, const char *encoding); XMLPUBFUN int xmlSaveFormatFileEnc (const char *filename, xmlDocPtr cur, const char *encoding, int format); XMLPUBFUN int xmlSaveFileEnc (const char *filename, xmlDocPtr cur, const char *encoding); #endif /* LIBXML_OUTPUT_ENABLED */ /* * XHTML */ XMLPUBFUN int xmlIsXHTML (const xmlChar *systemID, const xmlChar *publicID); /* * Compression. */ XMLPUBFUN int xmlGetDocCompressMode (const xmlDoc *doc); XMLPUBFUN void xmlSetDocCompressMode (xmlDocPtr doc, int mode); XMLPUBFUN int xmlGetCompressMode (void); XMLPUBFUN void xmlSetCompressMode (int mode); /* * DOM-wrapper helper functions. */ XMLPUBFUN xmlDOMWrapCtxtPtr xmlDOMWrapNewCtxt (void); XMLPUBFUN void xmlDOMWrapFreeCtxt (xmlDOMWrapCtxtPtr ctxt); XMLPUBFUN int xmlDOMWrapReconcileNamespaces(xmlDOMWrapCtxtPtr ctxt, xmlNodePtr elem, int options); XMLPUBFUN int xmlDOMWrapAdoptNode (xmlDOMWrapCtxtPtr ctxt, xmlDocPtr sourceDoc, xmlNodePtr node, xmlDocPtr destDoc, xmlNodePtr destParent, int options); XMLPUBFUN int xmlDOMWrapRemoveNode (xmlDOMWrapCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr node, int options); XMLPUBFUN int xmlDOMWrapCloneNode (xmlDOMWrapCtxtPtr ctxt, xmlDocPtr sourceDoc, xmlNodePtr node, xmlNodePtr *clonedNode, xmlDocPtr destDoc, xmlNodePtr destParent, int deep, int options); #ifdef LIBXML_TREE_ENABLED /* * 5 interfaces from DOM ElementTraversal, but different in entities * traversal. */ XMLPUBFUN unsigned long xmlChildElementCount (xmlNodePtr parent); XMLPUBFUN xmlNodePtr xmlNextElementSibling (xmlNodePtr node); XMLPUBFUN xmlNodePtr xmlFirstElementChild (xmlNodePtr parent); XMLPUBFUN xmlNodePtr xmlLastElementChild (xmlNodePtr parent); XMLPUBFUN xmlNodePtr xmlPreviousElementSibling (xmlNodePtr node); #endif #ifdef __cplusplus } #endif #ifndef __XML_PARSER_H__ #include #endif #endif /* __XML_TREE_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/uri.h ================================================ /** * Summary: library of generic URI related routines * Description: library of generic URI related routines * Implements RFC 2396 * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_URI_H__ #define __XML_URI_H__ #include #include #ifdef __cplusplus extern "C" { #endif /** * xmlURI: * * A parsed URI reference. This is a struct containing the various fields * as described in RFC 2396 but separated for further processing. * * Note: query is a deprecated field which is incorrectly unescaped. * query_raw takes precedence over query if the former is set. * See: http://mail.gnome.org/archives/xml/2007-April/thread.html#00127 */ typedef struct _xmlURI xmlURI; typedef xmlURI *xmlURIPtr; struct _xmlURI { char *scheme; /* the URI scheme */ char *opaque; /* opaque part */ char *authority; /* the authority part */ char *server; /* the server part */ char *user; /* the user part */ int port; /* the port number */ char *path; /* the path string */ char *query; /* the query string (deprecated - use with caution) */ char *fragment; /* the fragment identifier */ int cleanup; /* parsing potentially unclean URI */ char *query_raw; /* the query string (as it appears in the URI) */ }; /* * This function is in tree.h: * xmlChar * xmlNodeGetBase (xmlDocPtr doc, * xmlNodePtr cur); */ XMLPUBFUN xmlURIPtr xmlCreateURI (void); XMLPUBFUN xmlChar * xmlBuildURI (const xmlChar *URI, const xmlChar *base); XMLPUBFUN xmlChar * xmlBuildRelativeURI (const xmlChar *URI, const xmlChar *base); XMLPUBFUN xmlURIPtr xmlParseURI (const char *str); XMLPUBFUN xmlURIPtr xmlParseURIRaw (const char *str, int raw); XMLPUBFUN int xmlParseURIReference (xmlURIPtr uri, const char *str); XMLPUBFUN xmlChar * xmlSaveUri (xmlURIPtr uri); XMLPUBFUN void xmlPrintURI (FILE *stream, xmlURIPtr uri); XMLPUBFUN xmlChar * xmlURIEscapeStr (const xmlChar *str, const xmlChar *list); XMLPUBFUN char * xmlURIUnescapeString (const char *str, int len, char *target); XMLPUBFUN int xmlNormalizeURIPath (char *path); XMLPUBFUN xmlChar * xmlURIEscape (const xmlChar *str); XMLPUBFUN void xmlFreeURI (xmlURIPtr uri); XMLPUBFUN xmlChar* xmlCanonicPath (const xmlChar *path); XMLPUBFUN xmlChar* xmlPathToURI (const xmlChar *path); #ifdef __cplusplus } #endif #endif /* __XML_URI_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/valid.h ================================================ /* * Summary: The DTD validation * Description: API for the DTD handling and the validity checking * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_VALID_H__ #define __XML_VALID_H__ #include #include #include #include #include #include #ifdef __cplusplus extern "C" { #endif /* * Validation state added for non-determinist content model. */ typedef struct _xmlValidState xmlValidState; typedef xmlValidState *xmlValidStatePtr; /** * xmlValidityErrorFunc: * @ctx: usually an xmlValidCtxtPtr to a validity error context, * but comes from ctxt->userData (which normally contains such * a pointer); ctxt->userData can be changed by the user. * @msg: the string to format *printf like vararg * @...: remaining arguments to the format * * Callback called when a validity error is found. This is a message * oriented function similar to an *printf function. */ typedef void (*xmlValidityErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlValidityWarningFunc: * @ctx: usually an xmlValidCtxtPtr to a validity error context, * but comes from ctxt->userData (which normally contains such * a pointer); ctxt->userData can be changed by the user. * @msg: the string to format *printf like vararg * @...: remaining arguments to the format * * Callback called when a validity warning is found. This is a message * oriented function similar to an *printf function. */ typedef void (*xmlValidityWarningFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /* * xmlValidCtxt: * An xmlValidCtxt is used for error reporting when validating. */ typedef struct _xmlValidCtxt xmlValidCtxt; typedef xmlValidCtxt *xmlValidCtxtPtr; struct _xmlValidCtxt { void *userData; /* user specific data block */ xmlValidityErrorFunc error; /* the callback in case of errors */ xmlValidityWarningFunc warning; /* the callback in case of warning */ /* Node analysis stack used when validating within entities */ xmlNodePtr node; /* Current parsed Node */ int nodeNr; /* Depth of the parsing stack */ int nodeMax; /* Max depth of the parsing stack */ xmlNodePtr *nodeTab; /* array of nodes */ unsigned int flags; /* internal flags */ xmlDocPtr doc; /* the document */ int valid; /* temporary validity check result */ /* state state used for non-determinist content validation */ xmlValidState *vstate; /* current state */ int vstateNr; /* Depth of the validation stack */ int vstateMax; /* Max depth of the validation stack */ xmlValidState *vstateTab; /* array of validation states */ #ifdef LIBXML_REGEXP_ENABLED xmlAutomataPtr am; /* the automata */ xmlAutomataStatePtr state; /* used to build the automata */ #else void *am; void *state; #endif }; /* * ALL notation declarations are stored in a table. * There is one table per DTD. */ typedef struct _xmlHashTable xmlNotationTable; typedef xmlNotationTable *xmlNotationTablePtr; /* * ALL element declarations are stored in a table. * There is one table per DTD. */ typedef struct _xmlHashTable xmlElementTable; typedef xmlElementTable *xmlElementTablePtr; /* * ALL attribute declarations are stored in a table. * There is one table per DTD. */ typedef struct _xmlHashTable xmlAttributeTable; typedef xmlAttributeTable *xmlAttributeTablePtr; /* * ALL IDs attributes are stored in a table. * There is one table per document. */ typedef struct _xmlHashTable xmlIDTable; typedef xmlIDTable *xmlIDTablePtr; /* * ALL Refs attributes are stored in a table. * There is one table per document. */ typedef struct _xmlHashTable xmlRefTable; typedef xmlRefTable *xmlRefTablePtr; /* Notation */ XMLPUBFUN xmlNotationPtr xmlAddNotationDecl (xmlValidCtxtPtr ctxt, xmlDtdPtr dtd, const xmlChar *name, const xmlChar *PublicID, const xmlChar *SystemID); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlNotationTablePtr xmlCopyNotationTable (xmlNotationTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeNotationTable (xmlNotationTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpNotationDecl (xmlBufferPtr buf, xmlNotationPtr nota); XMLPUBFUN void xmlDumpNotationTable (xmlBufferPtr buf, xmlNotationTablePtr table); #endif /* LIBXML_OUTPUT_ENABLED */ /* Element Content */ /* the non Doc version are being deprecated */ XMLPUBFUN xmlElementContentPtr xmlNewElementContent (const xmlChar *name, xmlElementContentType type); XMLPUBFUN xmlElementContentPtr xmlCopyElementContent (xmlElementContentPtr content); XMLPUBFUN void xmlFreeElementContent (xmlElementContentPtr cur); /* the new versions with doc argument */ XMLPUBFUN xmlElementContentPtr xmlNewDocElementContent (xmlDocPtr doc, const xmlChar *name, xmlElementContentType type); XMLPUBFUN xmlElementContentPtr xmlCopyDocElementContent(xmlDocPtr doc, xmlElementContentPtr content); XMLPUBFUN void xmlFreeDocElementContent(xmlDocPtr doc, xmlElementContentPtr cur); XMLPUBFUN void xmlSnprintfElementContent(char *buf, int size, xmlElementContentPtr content, int englob); #ifdef LIBXML_OUTPUT_ENABLED /* DEPRECATED */ XMLPUBFUN void xmlSprintfElementContent(char *buf, xmlElementContentPtr content, int englob); #endif /* LIBXML_OUTPUT_ENABLED */ /* DEPRECATED */ /* Element */ XMLPUBFUN xmlElementPtr xmlAddElementDecl (xmlValidCtxtPtr ctxt, xmlDtdPtr dtd, const xmlChar *name, xmlElementTypeVal type, xmlElementContentPtr content); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlElementTablePtr xmlCopyElementTable (xmlElementTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeElementTable (xmlElementTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpElementTable (xmlBufferPtr buf, xmlElementTablePtr table); XMLPUBFUN void xmlDumpElementDecl (xmlBufferPtr buf, xmlElementPtr elem); #endif /* LIBXML_OUTPUT_ENABLED */ /* Enumeration */ XMLPUBFUN xmlEnumerationPtr xmlCreateEnumeration (const xmlChar *name); XMLPUBFUN void xmlFreeEnumeration (xmlEnumerationPtr cur); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlEnumerationPtr xmlCopyEnumeration (xmlEnumerationPtr cur); #endif /* LIBXML_TREE_ENABLED */ /* Attribute */ XMLPUBFUN xmlAttributePtr xmlAddAttributeDecl (xmlValidCtxtPtr ctxt, xmlDtdPtr dtd, const xmlChar *elem, const xmlChar *name, const xmlChar *ns, xmlAttributeType type, xmlAttributeDefault def, const xmlChar *defaultValue, xmlEnumerationPtr tree); #ifdef LIBXML_TREE_ENABLED XMLPUBFUN xmlAttributeTablePtr xmlCopyAttributeTable (xmlAttributeTablePtr table); #endif /* LIBXML_TREE_ENABLED */ XMLPUBFUN void xmlFreeAttributeTable (xmlAttributeTablePtr table); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlDumpAttributeTable (xmlBufferPtr buf, xmlAttributeTablePtr table); XMLPUBFUN void xmlDumpAttributeDecl (xmlBufferPtr buf, xmlAttributePtr attr); #endif /* LIBXML_OUTPUT_ENABLED */ /* IDs */ XMLPUBFUN xmlIDPtr xmlAddID (xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *value, xmlAttrPtr attr); XMLPUBFUN void xmlFreeIDTable (xmlIDTablePtr table); XMLPUBFUN xmlAttrPtr xmlGetID (xmlDocPtr doc, const xmlChar *ID); XMLPUBFUN int xmlIsID (xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr); XMLPUBFUN int xmlRemoveID (xmlDocPtr doc, xmlAttrPtr attr); /* IDREFs */ XML_DEPRECATED XMLPUBFUN xmlRefPtr xmlAddRef (xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *value, xmlAttrPtr attr); XML_DEPRECATED XMLPUBFUN void xmlFreeRefTable (xmlRefTablePtr table); XML_DEPRECATED XMLPUBFUN int xmlIsRef (xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr); XML_DEPRECATED XMLPUBFUN int xmlRemoveRef (xmlDocPtr doc, xmlAttrPtr attr); XML_DEPRECATED XMLPUBFUN xmlListPtr xmlGetRefs (xmlDocPtr doc, const xmlChar *ID); /** * The public function calls related to validity checking. */ #ifdef LIBXML_VALID_ENABLED /* Allocate/Release Validation Contexts */ XMLPUBFUN xmlValidCtxtPtr xmlNewValidCtxt(void); XMLPUBFUN void xmlFreeValidCtxt(xmlValidCtxtPtr); XMLPUBFUN int xmlValidateRoot (xmlValidCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN int xmlValidateElementDecl (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlElementPtr elem); XMLPUBFUN xmlChar * xmlValidNormalizeAttributeValue(xmlDocPtr doc, xmlNodePtr elem, const xmlChar *name, const xmlChar *value); XMLPUBFUN xmlChar * xmlValidCtxtNormalizeAttributeValue(xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *name, const xmlChar *value); XMLPUBFUN int xmlValidateAttributeDecl(xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlAttributePtr attr); XMLPUBFUN int xmlValidateAttributeValue(xmlAttributeType type, const xmlChar *value); XMLPUBFUN int xmlValidateNotationDecl (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNotationPtr nota); XMLPUBFUN int xmlValidateDtd (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlDtdPtr dtd); XMLPUBFUN int xmlValidateDtdFinal (xmlValidCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN int xmlValidateDocument (xmlValidCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN int xmlValidateElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlValidateOneElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem); XMLPUBFUN int xmlValidateOneAttribute (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, xmlAttrPtr attr, const xmlChar *value); XMLPUBFUN int xmlValidateOneNamespace (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *prefix, xmlNsPtr ns, const xmlChar *value); XMLPUBFUN int xmlValidateDocumentFinal(xmlValidCtxtPtr ctxt, xmlDocPtr doc); #endif /* LIBXML_VALID_ENABLED */ #if defined(LIBXML_VALID_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XMLPUBFUN int xmlValidateNotationUse (xmlValidCtxtPtr ctxt, xmlDocPtr doc, const xmlChar *notationName); #endif /* LIBXML_VALID_ENABLED or LIBXML_SCHEMAS_ENABLED */ XMLPUBFUN int xmlIsMixedElement (xmlDocPtr doc, const xmlChar *name); XMLPUBFUN xmlAttributePtr xmlGetDtdAttrDesc (xmlDtdPtr dtd, const xmlChar *elem, const xmlChar *name); XMLPUBFUN xmlAttributePtr xmlGetDtdQAttrDesc (xmlDtdPtr dtd, const xmlChar *elem, const xmlChar *name, const xmlChar *prefix); XMLPUBFUN xmlNotationPtr xmlGetDtdNotationDesc (xmlDtdPtr dtd, const xmlChar *name); XMLPUBFUN xmlElementPtr xmlGetDtdQElementDesc (xmlDtdPtr dtd, const xmlChar *name, const xmlChar *prefix); XMLPUBFUN xmlElementPtr xmlGetDtdElementDesc (xmlDtdPtr dtd, const xmlChar *name); #ifdef LIBXML_VALID_ENABLED XMLPUBFUN int xmlValidGetPotentialChildren(xmlElementContent *ctree, const xmlChar **names, int *len, int max); XMLPUBFUN int xmlValidGetValidElements(xmlNode *prev, xmlNode *next, const xmlChar **names, int max); XMLPUBFUN int xmlValidateNameValue (const xmlChar *value); XMLPUBFUN int xmlValidateNamesValue (const xmlChar *value); XMLPUBFUN int xmlValidateNmtokenValue (const xmlChar *value); XMLPUBFUN int xmlValidateNmtokensValue(const xmlChar *value); #ifdef LIBXML_REGEXP_ENABLED /* * Validation based on the regexp support */ XMLPUBFUN int xmlValidBuildContentModel(xmlValidCtxtPtr ctxt, xmlElementPtr elem); XMLPUBFUN int xmlValidatePushElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *qname); XMLPUBFUN int xmlValidatePushCData (xmlValidCtxtPtr ctxt, const xmlChar *data, int len); XMLPUBFUN int xmlValidatePopElement (xmlValidCtxtPtr ctxt, xmlDocPtr doc, xmlNodePtr elem, const xmlChar *qname); #endif /* LIBXML_REGEXP_ENABLED */ #endif /* LIBXML_VALID_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_VALID_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xinclude.h ================================================ /* * Summary: implementation of XInclude * Description: API to handle XInclude processing, * implements the * World Wide Web Consortium Last Call Working Draft 10 November 2003 * http://www.w3.org/TR/2003/WD-xinclude-20031110 * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XINCLUDE_H__ #define __XML_XINCLUDE_H__ #include #include #ifdef LIBXML_XINCLUDE_ENABLED #ifdef __cplusplus extern "C" { #endif /** * XINCLUDE_NS: * * Macro defining the Xinclude namespace: http://www.w3.org/2003/XInclude */ #define XINCLUDE_NS (const xmlChar *) "http://www.w3.org/2003/XInclude" /** * XINCLUDE_OLD_NS: * * Macro defining the draft Xinclude namespace: http://www.w3.org/2001/XInclude */ #define XINCLUDE_OLD_NS (const xmlChar *) "http://www.w3.org/2001/XInclude" /** * XINCLUDE_NODE: * * Macro defining "include" */ #define XINCLUDE_NODE (const xmlChar *) "include" /** * XINCLUDE_FALLBACK: * * Macro defining "fallback" */ #define XINCLUDE_FALLBACK (const xmlChar *) "fallback" /** * XINCLUDE_HREF: * * Macro defining "href" */ #define XINCLUDE_HREF (const xmlChar *) "href" /** * XINCLUDE_PARSE: * * Macro defining "parse" */ #define XINCLUDE_PARSE (const xmlChar *) "parse" /** * XINCLUDE_PARSE_XML: * * Macro defining "xml" */ #define XINCLUDE_PARSE_XML (const xmlChar *) "xml" /** * XINCLUDE_PARSE_TEXT: * * Macro defining "text" */ #define XINCLUDE_PARSE_TEXT (const xmlChar *) "text" /** * XINCLUDE_PARSE_ENCODING: * * Macro defining "encoding" */ #define XINCLUDE_PARSE_ENCODING (const xmlChar *) "encoding" /** * XINCLUDE_PARSE_XPOINTER: * * Macro defining "xpointer" */ #define XINCLUDE_PARSE_XPOINTER (const xmlChar *) "xpointer" typedef struct _xmlXIncludeCtxt xmlXIncludeCtxt; typedef xmlXIncludeCtxt *xmlXIncludeCtxtPtr; /* * standalone processing */ XMLPUBFUN int xmlXIncludeProcess (xmlDocPtr doc); XMLPUBFUN int xmlXIncludeProcessFlags (xmlDocPtr doc, int flags); XMLPUBFUN int xmlXIncludeProcessFlagsData(xmlDocPtr doc, int flags, void *data); XMLPUBFUN int xmlXIncludeProcessTreeFlagsData(xmlNodePtr tree, int flags, void *data); XMLPUBFUN int xmlXIncludeProcessTree (xmlNodePtr tree); XMLPUBFUN int xmlXIncludeProcessTreeFlags(xmlNodePtr tree, int flags); /* * contextual processing */ XMLPUBFUN xmlXIncludeCtxtPtr xmlXIncludeNewContext (xmlDocPtr doc); XMLPUBFUN int xmlXIncludeSetFlags (xmlXIncludeCtxtPtr ctxt, int flags); XMLPUBFUN void xmlXIncludeFreeContext (xmlXIncludeCtxtPtr ctxt); XMLPUBFUN int xmlXIncludeProcessNode (xmlXIncludeCtxtPtr ctxt, xmlNodePtr tree); #ifdef __cplusplus } #endif #endif /* LIBXML_XINCLUDE_ENABLED */ #endif /* __XML_XINCLUDE_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xlink.h ================================================ /* * Summary: unfinished XLink detection module * Description: unfinished XLink detection module * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XLINK_H__ #define __XML_XLINK_H__ #include #include #ifdef LIBXML_XPTR_ENABLED #ifdef __cplusplus extern "C" { #endif /** * Various defines for the various Link properties. * * NOTE: the link detection layer will try to resolve QName expansion * of namespaces. If "foo" is the prefix for "http://foo.com/" * then the link detection layer will expand role="foo:myrole" * to "http://foo.com/:myrole". * NOTE: the link detection layer will expand URI-References found on * href attributes by using the base mechanism if found. */ typedef xmlChar *xlinkHRef; typedef xmlChar *xlinkRole; typedef xmlChar *xlinkTitle; typedef enum { XLINK_TYPE_NONE = 0, XLINK_TYPE_SIMPLE, XLINK_TYPE_EXTENDED, XLINK_TYPE_EXTENDED_SET } xlinkType; typedef enum { XLINK_SHOW_NONE = 0, XLINK_SHOW_NEW, XLINK_SHOW_EMBED, XLINK_SHOW_REPLACE } xlinkShow; typedef enum { XLINK_ACTUATE_NONE = 0, XLINK_ACTUATE_AUTO, XLINK_ACTUATE_ONREQUEST } xlinkActuate; /** * xlinkNodeDetectFunc: * @ctx: user data pointer * @node: the node to check * * This is the prototype for the link detection routine. * It calls the default link detection callbacks upon link detection. */ typedef void (*xlinkNodeDetectFunc) (void *ctx, xmlNodePtr node); /* * The link detection module interact with the upper layers using * a set of callback registered at parsing time. */ /** * xlinkSimpleLinkFunk: * @ctx: user data pointer * @node: the node carrying the link * @href: the target of the link * @role: the role string * @title: the link title * * This is the prototype for a simple link detection callback. */ typedef void (*xlinkSimpleLinkFunk) (void *ctx, xmlNodePtr node, const xlinkHRef href, const xlinkRole role, const xlinkTitle title); /** * xlinkExtendedLinkFunk: * @ctx: user data pointer * @node: the node carrying the link * @nbLocators: the number of locators detected on the link * @hrefs: pointer to the array of locator hrefs * @roles: pointer to the array of locator roles * @nbArcs: the number of arcs detected on the link * @from: pointer to the array of source roles found on the arcs * @to: pointer to the array of target roles found on the arcs * @show: array of values for the show attributes found on the arcs * @actuate: array of values for the actuate attributes found on the arcs * @nbTitles: the number of titles detected on the link * @title: array of titles detected on the link * @langs: array of xml:lang values for the titles * * This is the prototype for a extended link detection callback. */ typedef void (*xlinkExtendedLinkFunk)(void *ctx, xmlNodePtr node, int nbLocators, const xlinkHRef *hrefs, const xlinkRole *roles, int nbArcs, const xlinkRole *from, const xlinkRole *to, xlinkShow *show, xlinkActuate *actuate, int nbTitles, const xlinkTitle *titles, const xmlChar **langs); /** * xlinkExtendedLinkSetFunk: * @ctx: user data pointer * @node: the node carrying the link * @nbLocators: the number of locators detected on the link * @hrefs: pointer to the array of locator hrefs * @roles: pointer to the array of locator roles * @nbTitles: the number of titles detected on the link * @title: array of titles detected on the link * @langs: array of xml:lang values for the titles * * This is the prototype for a extended link set detection callback. */ typedef void (*xlinkExtendedLinkSetFunk) (void *ctx, xmlNodePtr node, int nbLocators, const xlinkHRef *hrefs, const xlinkRole *roles, int nbTitles, const xlinkTitle *titles, const xmlChar **langs); /** * This is the structure containing a set of Links detection callbacks. * * There is no default xlink callbacks, if one want to get link * recognition activated, those call backs must be provided before parsing. */ typedef struct _xlinkHandler xlinkHandler; typedef xlinkHandler *xlinkHandlerPtr; struct _xlinkHandler { xlinkSimpleLinkFunk simple; xlinkExtendedLinkFunk extended; xlinkExtendedLinkSetFunk set; }; /* * The default detection routine, can be overridden, they call the default * detection callbacks. */ XMLPUBFUN xlinkNodeDetectFunc xlinkGetDefaultDetect (void); XMLPUBFUN void xlinkSetDefaultDetect (xlinkNodeDetectFunc func); /* * Routines to set/get the default handlers. */ XMLPUBFUN xlinkHandlerPtr xlinkGetDefaultHandler (void); XMLPUBFUN void xlinkSetDefaultHandler (xlinkHandlerPtr handler); /* * Link detection module itself. */ XMLPUBFUN xlinkType xlinkIsLink (xmlDocPtr doc, xmlNodePtr node); #ifdef __cplusplus } #endif #endif /* LIBXML_XPTR_ENABLED */ #endif /* __XML_XLINK_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlIO.h ================================================ /* * Summary: interface for the I/O interfaces used by the parser * Description: interface for the I/O interfaces used by the parser * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_IO_H__ #define __XML_IO_H__ #include #include #ifdef __cplusplus extern "C" { #endif /* * Those are the functions and datatypes for the parser input * I/O structures. */ /** * xmlInputMatchCallback: * @filename: the filename or URI * * Callback used in the I/O Input API to detect if the current handler * can provide input functionality for this resource. * * Returns 1 if yes and 0 if another Input module should be used */ typedef int (*xmlInputMatchCallback) (char const *filename); /** * xmlInputOpenCallback: * @filename: the filename or URI * * Callback used in the I/O Input API to open the resource * * Returns an Input context or NULL in case or error */ typedef void * (*xmlInputOpenCallback) (char const *filename); /** * xmlInputReadCallback: * @context: an Input context * @buffer: the buffer to store data read * @len: the length of the buffer in bytes * * Callback used in the I/O Input API to read the resource * * Returns the number of bytes read or -1 in case of error */ typedef int (*xmlInputReadCallback) (void * context, char * buffer, int len); /** * xmlInputCloseCallback: * @context: an Input context * * Callback used in the I/O Input API to close the resource * * Returns 0 or -1 in case of error */ typedef int (*xmlInputCloseCallback) (void * context); #ifdef LIBXML_OUTPUT_ENABLED /* * Those are the functions and datatypes for the library output * I/O structures. */ /** * xmlOutputMatchCallback: * @filename: the filename or URI * * Callback used in the I/O Output API to detect if the current handler * can provide output functionality for this resource. * * Returns 1 if yes and 0 if another Output module should be used */ typedef int (*xmlOutputMatchCallback) (char const *filename); /** * xmlOutputOpenCallback: * @filename: the filename or URI * * Callback used in the I/O Output API to open the resource * * Returns an Output context or NULL in case or error */ typedef void * (*xmlOutputOpenCallback) (char const *filename); /** * xmlOutputWriteCallback: * @context: an Output context * @buffer: the buffer of data to write * @len: the length of the buffer in bytes * * Callback used in the I/O Output API to write to the resource * * Returns the number of bytes written or -1 in case of error */ typedef int (*xmlOutputWriteCallback) (void * context, const char * buffer, int len); /** * xmlOutputCloseCallback: * @context: an Output context * * Callback used in the I/O Output API to close the resource * * Returns 0 or -1 in case of error */ typedef int (*xmlOutputCloseCallback) (void * context); #endif /* LIBXML_OUTPUT_ENABLED */ #ifdef __cplusplus } #endif #include #include #include #include #ifdef __cplusplus extern "C" { #endif struct _xmlParserInputBuffer { void* context; xmlInputReadCallback readcallback; xmlInputCloseCallback closecallback; xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */ xmlBufPtr buffer; /* Local buffer encoded in UTF-8 */ xmlBufPtr raw; /* if encoder != NULL buffer for raw input */ int compressed; /* -1=unknown, 0=not compressed, 1=compressed */ int error; unsigned long rawconsumed;/* amount consumed from raw */ }; #ifdef LIBXML_OUTPUT_ENABLED struct _xmlOutputBuffer { void* context; xmlOutputWriteCallback writecallback; xmlOutputCloseCallback closecallback; xmlCharEncodingHandlerPtr encoder; /* I18N conversions to UTF-8 */ xmlBufPtr buffer; /* Local buffer encoded in UTF-8 or ISOLatin */ xmlBufPtr conv; /* if encoder != NULL buffer for output */ int written; /* total number of byte written */ int error; }; #endif /* LIBXML_OUTPUT_ENABLED */ /* * Interfaces for input */ XMLPUBFUN void xmlCleanupInputCallbacks (void); XMLPUBFUN int xmlPopInputCallbacks (void); XMLPUBFUN void xmlRegisterDefaultInputCallbacks (void); XMLPUBFUN xmlParserInputBufferPtr xmlAllocParserInputBuffer (xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateFilename (const char *URI, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateFile (FILE *file, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateFd (int fd, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateMem (const char *mem, int size, xmlCharEncoding enc); XML_DEPRECATED XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateStatic (const char *mem, int size, xmlCharEncoding enc); XMLPUBFUN xmlParserInputBufferPtr xmlParserInputBufferCreateIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, xmlCharEncoding enc); XMLPUBFUN int xmlParserInputBufferRead (xmlParserInputBufferPtr in, int len); XMLPUBFUN int xmlParserInputBufferGrow (xmlParserInputBufferPtr in, int len); XMLPUBFUN int xmlParserInputBufferPush (xmlParserInputBufferPtr in, int len, const char *buf); XMLPUBFUN void xmlFreeParserInputBuffer (xmlParserInputBufferPtr in); XMLPUBFUN char * xmlParserGetDirectory (const char *filename); XMLPUBFUN int xmlRegisterInputCallbacks (xmlInputMatchCallback matchFunc, xmlInputOpenCallback openFunc, xmlInputReadCallback readFunc, xmlInputCloseCallback closeFunc); xmlParserInputBufferPtr __xmlParserInputBufferCreateFilename(const char *URI, xmlCharEncoding enc); #ifdef LIBXML_OUTPUT_ENABLED /* * Interfaces for output */ XMLPUBFUN void xmlCleanupOutputCallbacks (void); XMLPUBFUN int xmlPopOutputCallbacks (void); XMLPUBFUN void xmlRegisterDefaultOutputCallbacks(void); XMLPUBFUN xmlOutputBufferPtr xmlAllocOutputBuffer (xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateFilename (const char *URI, xmlCharEncodingHandlerPtr encoder, int compression); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateFile (FILE *file, xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateBuffer (xmlBufferPtr buffer, xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateFd (int fd, xmlCharEncodingHandlerPtr encoder); XMLPUBFUN xmlOutputBufferPtr xmlOutputBufferCreateIO (xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose, void *ioctx, xmlCharEncodingHandlerPtr encoder); /* Couple of APIs to get the output without digging into the buffers */ XMLPUBFUN const xmlChar * xmlOutputBufferGetContent (xmlOutputBufferPtr out); XMLPUBFUN size_t xmlOutputBufferGetSize (xmlOutputBufferPtr out); XMLPUBFUN int xmlOutputBufferWrite (xmlOutputBufferPtr out, int len, const char *buf); XMLPUBFUN int xmlOutputBufferWriteString (xmlOutputBufferPtr out, const char *str); XMLPUBFUN int xmlOutputBufferWriteEscape (xmlOutputBufferPtr out, const xmlChar *str, xmlCharEncodingOutputFunc escaping); XMLPUBFUN int xmlOutputBufferFlush (xmlOutputBufferPtr out); XMLPUBFUN int xmlOutputBufferClose (xmlOutputBufferPtr out); XMLPUBFUN int xmlRegisterOutputCallbacks (xmlOutputMatchCallback matchFunc, xmlOutputOpenCallback openFunc, xmlOutputWriteCallback writeFunc, xmlOutputCloseCallback closeFunc); xmlOutputBufferPtr __xmlOutputBufferCreateFilename(const char *URI, xmlCharEncodingHandlerPtr encoder, int compression); #ifdef LIBXML_HTTP_ENABLED /* This function only exists if HTTP support built into the library */ XMLPUBFUN void xmlRegisterHTTPPostCallbacks (void ); #endif /* LIBXML_HTTP_ENABLED */ #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN xmlParserInputPtr xmlCheckHTTPInput (xmlParserCtxtPtr ctxt, xmlParserInputPtr ret); /* * A predefined entity loader disabling network accesses */ XMLPUBFUN xmlParserInputPtr xmlNoNetExternalEntityLoader (const char *URL, const char *ID, xmlParserCtxtPtr ctxt); /* * xmlNormalizeWindowsPath is obsolete, don't use it. * Check xmlCanonicPath in uri.h for a better alternative. */ XMLPUBFUN xmlChar * xmlNormalizeWindowsPath (const xmlChar *path); XMLPUBFUN int xmlCheckFilename (const char *path); /** * Default 'file://' protocol callbacks */ XMLPUBFUN int xmlFileMatch (const char *filename); XMLPUBFUN void * xmlFileOpen (const char *filename); XMLPUBFUN int xmlFileRead (void * context, char * buffer, int len); XMLPUBFUN int xmlFileClose (void * context); /** * Default 'http://' protocol callbacks */ #ifdef LIBXML_HTTP_ENABLED XMLPUBFUN int xmlIOHTTPMatch (const char *filename); XMLPUBFUN void * xmlIOHTTPOpen (const char *filename); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void * xmlIOHTTPOpenW (const char * post_uri, int compression ); #endif /* LIBXML_OUTPUT_ENABLED */ XMLPUBFUN int xmlIOHTTPRead (void * context, char * buffer, int len); XMLPUBFUN int xmlIOHTTPClose (void * context); #endif /* LIBXML_HTTP_ENABLED */ /** * Default 'ftp://' protocol callbacks */ #ifdef LIBXML_FTP_ENABLED XMLPUBFUN int xmlIOFTPMatch (const char *filename); XMLPUBFUN void * xmlIOFTPOpen (const char *filename); XMLPUBFUN int xmlIOFTPRead (void * context, char * buffer, int len); XMLPUBFUN int xmlIOFTPClose (void * context); #endif /* LIBXML_FTP_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_IO_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlautomata.h ================================================ /* * Summary: API to build regexp automata * Description: the API to build regexp automata * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_AUTOMATA_H__ #define __XML_AUTOMATA_H__ #include #ifdef LIBXML_REGEXP_ENABLED #ifdef LIBXML_AUTOMATA_ENABLED #include #ifdef __cplusplus extern "C" { #endif /** * xmlAutomataPtr: * * A libxml automata description, It can be compiled into a regexp */ typedef struct _xmlAutomata xmlAutomata; typedef xmlAutomata *xmlAutomataPtr; /** * xmlAutomataStatePtr: * * A state int the automata description, */ typedef struct _xmlAutomataState xmlAutomataState; typedef xmlAutomataState *xmlAutomataStatePtr; /* * Building API */ XMLPUBFUN xmlAutomataPtr xmlNewAutomata (void); XMLPUBFUN void xmlFreeAutomata (xmlAutomataPtr am); XMLPUBFUN xmlAutomataStatePtr xmlAutomataGetInitState (xmlAutomataPtr am); XMLPUBFUN int xmlAutomataSetFinalState (xmlAutomataPtr am, xmlAutomataStatePtr state); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewState (xmlAutomataPtr am); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewTransition (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewTransition2 (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewNegTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCountTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCountTrans2 (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewOnceTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewOnceTrans2 (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, const xmlChar *token, const xmlChar *token2, int min, int max, void *data); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewAllTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int lax); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewEpsilon (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCountedTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int counter); XMLPUBFUN xmlAutomataStatePtr xmlAutomataNewCounterTrans (xmlAutomataPtr am, xmlAutomataStatePtr from, xmlAutomataStatePtr to, int counter); XMLPUBFUN int xmlAutomataNewCounter (xmlAutomataPtr am, int min, int max); XMLPUBFUN struct _xmlRegexp * xmlAutomataCompile (xmlAutomataPtr am); XMLPUBFUN int xmlAutomataIsDeterminist (xmlAutomataPtr am); #ifdef __cplusplus } #endif #endif /* LIBXML_AUTOMATA_ENABLED */ #endif /* LIBXML_REGEXP_ENABLED */ #endif /* __XML_AUTOMATA_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlerror.h ================================================ /* * Summary: error handling * Description: the API used to report errors * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #include #ifndef __XML_ERROR_H__ #define __XML_ERROR_H__ #ifdef __cplusplus extern "C" { #endif /** * xmlErrorLevel: * * Indicates the level of an error */ typedef enum { XML_ERR_NONE = 0, XML_ERR_WARNING = 1, /* A simple warning */ XML_ERR_ERROR = 2, /* A recoverable error */ XML_ERR_FATAL = 3 /* A fatal error */ } xmlErrorLevel; /** * xmlErrorDomain: * * Indicates where an error may have come from */ typedef enum { XML_FROM_NONE = 0, XML_FROM_PARSER, /* The XML parser */ XML_FROM_TREE, /* The tree module */ XML_FROM_NAMESPACE, /* The XML Namespace module */ XML_FROM_DTD, /* The XML DTD validation with parser context*/ XML_FROM_HTML, /* The HTML parser */ XML_FROM_MEMORY, /* The memory allocator */ XML_FROM_OUTPUT, /* The serialization code */ XML_FROM_IO, /* The Input/Output stack */ XML_FROM_FTP, /* The FTP module */ XML_FROM_HTTP, /* The HTTP module */ XML_FROM_XINCLUDE, /* The XInclude processing */ XML_FROM_XPATH, /* The XPath module */ XML_FROM_XPOINTER, /* The XPointer module */ XML_FROM_REGEXP, /* The regular expressions module */ XML_FROM_DATATYPE, /* The W3C XML Schemas Datatype module */ XML_FROM_SCHEMASP, /* The W3C XML Schemas parser module */ XML_FROM_SCHEMASV, /* The W3C XML Schemas validation module */ XML_FROM_RELAXNGP, /* The Relax-NG parser module */ XML_FROM_RELAXNGV, /* The Relax-NG validator module */ XML_FROM_CATALOG, /* The Catalog module */ XML_FROM_C14N, /* The Canonicalization module */ XML_FROM_XSLT, /* The XSLT engine from libxslt */ XML_FROM_VALID, /* The XML DTD validation with valid context */ XML_FROM_CHECK, /* The error checking module */ XML_FROM_WRITER, /* The xmlwriter module */ XML_FROM_MODULE, /* The dynamically loaded module module*/ XML_FROM_I18N, /* The module handling character conversion */ XML_FROM_SCHEMATRONV,/* The Schematron validator module */ XML_FROM_BUFFER, /* The buffers module */ XML_FROM_URI /* The URI module */ } xmlErrorDomain; /** * xmlError: * * An XML Error instance. */ typedef struct _xmlError xmlError; typedef xmlError *xmlErrorPtr; struct _xmlError { int domain; /* What part of the library raised this error */ int code; /* The error code, e.g. an xmlParserError */ char *message;/* human-readable informative error message */ xmlErrorLevel level;/* how consequent is the error */ char *file; /* the filename */ int line; /* the line number if available */ char *str1; /* extra string information */ char *str2; /* extra string information */ char *str3; /* extra string information */ int int1; /* extra number information */ int int2; /* error column # or 0 if N/A (todo: rename field when we would brk ABI) */ void *ctxt; /* the parser context if available */ void *node; /* the node in the tree */ }; /** * xmlParserError: * * This is an error that the XML (or HTML) parser can generate */ typedef enum { XML_ERR_OK = 0, XML_ERR_INTERNAL_ERROR, /* 1 */ XML_ERR_NO_MEMORY, /* 2 */ XML_ERR_DOCUMENT_START, /* 3 */ XML_ERR_DOCUMENT_EMPTY, /* 4 */ XML_ERR_DOCUMENT_END, /* 5 */ XML_ERR_INVALID_HEX_CHARREF, /* 6 */ XML_ERR_INVALID_DEC_CHARREF, /* 7 */ XML_ERR_INVALID_CHARREF, /* 8 */ XML_ERR_INVALID_CHAR, /* 9 */ XML_ERR_CHARREF_AT_EOF, /* 10 */ XML_ERR_CHARREF_IN_PROLOG, /* 11 */ XML_ERR_CHARREF_IN_EPILOG, /* 12 */ XML_ERR_CHARREF_IN_DTD, /* 13 */ XML_ERR_ENTITYREF_AT_EOF, /* 14 */ XML_ERR_ENTITYREF_IN_PROLOG, /* 15 */ XML_ERR_ENTITYREF_IN_EPILOG, /* 16 */ XML_ERR_ENTITYREF_IN_DTD, /* 17 */ XML_ERR_PEREF_AT_EOF, /* 18 */ XML_ERR_PEREF_IN_PROLOG, /* 19 */ XML_ERR_PEREF_IN_EPILOG, /* 20 */ XML_ERR_PEREF_IN_INT_SUBSET, /* 21 */ XML_ERR_ENTITYREF_NO_NAME, /* 22 */ XML_ERR_ENTITYREF_SEMICOL_MISSING, /* 23 */ XML_ERR_PEREF_NO_NAME, /* 24 */ XML_ERR_PEREF_SEMICOL_MISSING, /* 25 */ XML_ERR_UNDECLARED_ENTITY, /* 26 */ XML_WAR_UNDECLARED_ENTITY, /* 27 */ XML_ERR_UNPARSED_ENTITY, /* 28 */ XML_ERR_ENTITY_IS_EXTERNAL, /* 29 */ XML_ERR_ENTITY_IS_PARAMETER, /* 30 */ XML_ERR_UNKNOWN_ENCODING, /* 31 */ XML_ERR_UNSUPPORTED_ENCODING, /* 32 */ XML_ERR_STRING_NOT_STARTED, /* 33 */ XML_ERR_STRING_NOT_CLOSED, /* 34 */ XML_ERR_NS_DECL_ERROR, /* 35 */ XML_ERR_ENTITY_NOT_STARTED, /* 36 */ XML_ERR_ENTITY_NOT_FINISHED, /* 37 */ XML_ERR_LT_IN_ATTRIBUTE, /* 38 */ XML_ERR_ATTRIBUTE_NOT_STARTED, /* 39 */ XML_ERR_ATTRIBUTE_NOT_FINISHED, /* 40 */ XML_ERR_ATTRIBUTE_WITHOUT_VALUE, /* 41 */ XML_ERR_ATTRIBUTE_REDEFINED, /* 42 */ XML_ERR_LITERAL_NOT_STARTED, /* 43 */ XML_ERR_LITERAL_NOT_FINISHED, /* 44 */ XML_ERR_COMMENT_NOT_FINISHED, /* 45 */ XML_ERR_PI_NOT_STARTED, /* 46 */ XML_ERR_PI_NOT_FINISHED, /* 47 */ XML_ERR_NOTATION_NOT_STARTED, /* 48 */ XML_ERR_NOTATION_NOT_FINISHED, /* 49 */ XML_ERR_ATTLIST_NOT_STARTED, /* 50 */ XML_ERR_ATTLIST_NOT_FINISHED, /* 51 */ XML_ERR_MIXED_NOT_STARTED, /* 52 */ XML_ERR_MIXED_NOT_FINISHED, /* 53 */ XML_ERR_ELEMCONTENT_NOT_STARTED, /* 54 */ XML_ERR_ELEMCONTENT_NOT_FINISHED, /* 55 */ XML_ERR_XMLDECL_NOT_STARTED, /* 56 */ XML_ERR_XMLDECL_NOT_FINISHED, /* 57 */ XML_ERR_CONDSEC_NOT_STARTED, /* 58 */ XML_ERR_CONDSEC_NOT_FINISHED, /* 59 */ XML_ERR_EXT_SUBSET_NOT_FINISHED, /* 60 */ XML_ERR_DOCTYPE_NOT_FINISHED, /* 61 */ XML_ERR_MISPLACED_CDATA_END, /* 62 */ XML_ERR_CDATA_NOT_FINISHED, /* 63 */ XML_ERR_RESERVED_XML_NAME, /* 64 */ XML_ERR_SPACE_REQUIRED, /* 65 */ XML_ERR_SEPARATOR_REQUIRED, /* 66 */ XML_ERR_NMTOKEN_REQUIRED, /* 67 */ XML_ERR_NAME_REQUIRED, /* 68 */ XML_ERR_PCDATA_REQUIRED, /* 69 */ XML_ERR_URI_REQUIRED, /* 70 */ XML_ERR_PUBID_REQUIRED, /* 71 */ XML_ERR_LT_REQUIRED, /* 72 */ XML_ERR_GT_REQUIRED, /* 73 */ XML_ERR_LTSLASH_REQUIRED, /* 74 */ XML_ERR_EQUAL_REQUIRED, /* 75 */ XML_ERR_TAG_NAME_MISMATCH, /* 76 */ XML_ERR_TAG_NOT_FINISHED, /* 77 */ XML_ERR_STANDALONE_VALUE, /* 78 */ XML_ERR_ENCODING_NAME, /* 79 */ XML_ERR_HYPHEN_IN_COMMENT, /* 80 */ XML_ERR_INVALID_ENCODING, /* 81 */ XML_ERR_EXT_ENTITY_STANDALONE, /* 82 */ XML_ERR_CONDSEC_INVALID, /* 83 */ XML_ERR_VALUE_REQUIRED, /* 84 */ XML_ERR_NOT_WELL_BALANCED, /* 85 */ XML_ERR_EXTRA_CONTENT, /* 86 */ XML_ERR_ENTITY_CHAR_ERROR, /* 87 */ XML_ERR_ENTITY_PE_INTERNAL, /* 88 */ XML_ERR_ENTITY_LOOP, /* 89 */ XML_ERR_ENTITY_BOUNDARY, /* 90 */ XML_ERR_INVALID_URI, /* 91 */ XML_ERR_URI_FRAGMENT, /* 92 */ XML_WAR_CATALOG_PI, /* 93 */ XML_ERR_NO_DTD, /* 94 */ XML_ERR_CONDSEC_INVALID_KEYWORD, /* 95 */ XML_ERR_VERSION_MISSING, /* 96 */ XML_WAR_UNKNOWN_VERSION, /* 97 */ XML_WAR_LANG_VALUE, /* 98 */ XML_WAR_NS_URI, /* 99 */ XML_WAR_NS_URI_RELATIVE, /* 100 */ XML_ERR_MISSING_ENCODING, /* 101 */ XML_WAR_SPACE_VALUE, /* 102 */ XML_ERR_NOT_STANDALONE, /* 103 */ XML_ERR_ENTITY_PROCESSING, /* 104 */ XML_ERR_NOTATION_PROCESSING, /* 105 */ XML_WAR_NS_COLUMN, /* 106 */ XML_WAR_ENTITY_REDEFINED, /* 107 */ XML_ERR_UNKNOWN_VERSION, /* 108 */ XML_ERR_VERSION_MISMATCH, /* 109 */ XML_ERR_NAME_TOO_LONG, /* 110 */ XML_ERR_USER_STOP, /* 111 */ XML_ERR_COMMENT_ABRUPTLY_ENDED, /* 112 */ XML_NS_ERR_XML_NAMESPACE = 200, XML_NS_ERR_UNDEFINED_NAMESPACE, /* 201 */ XML_NS_ERR_QNAME, /* 202 */ XML_NS_ERR_ATTRIBUTE_REDEFINED, /* 203 */ XML_NS_ERR_EMPTY, /* 204 */ XML_NS_ERR_COLON, /* 205 */ XML_DTD_ATTRIBUTE_DEFAULT = 500, XML_DTD_ATTRIBUTE_REDEFINED, /* 501 */ XML_DTD_ATTRIBUTE_VALUE, /* 502 */ XML_DTD_CONTENT_ERROR, /* 503 */ XML_DTD_CONTENT_MODEL, /* 504 */ XML_DTD_CONTENT_NOT_DETERMINIST, /* 505 */ XML_DTD_DIFFERENT_PREFIX, /* 506 */ XML_DTD_ELEM_DEFAULT_NAMESPACE, /* 507 */ XML_DTD_ELEM_NAMESPACE, /* 508 */ XML_DTD_ELEM_REDEFINED, /* 509 */ XML_DTD_EMPTY_NOTATION, /* 510 */ XML_DTD_ENTITY_TYPE, /* 511 */ XML_DTD_ID_FIXED, /* 512 */ XML_DTD_ID_REDEFINED, /* 513 */ XML_DTD_ID_SUBSET, /* 514 */ XML_DTD_INVALID_CHILD, /* 515 */ XML_DTD_INVALID_DEFAULT, /* 516 */ XML_DTD_LOAD_ERROR, /* 517 */ XML_DTD_MISSING_ATTRIBUTE, /* 518 */ XML_DTD_MIXED_CORRUPT, /* 519 */ XML_DTD_MULTIPLE_ID, /* 520 */ XML_DTD_NO_DOC, /* 521 */ XML_DTD_NO_DTD, /* 522 */ XML_DTD_NO_ELEM_NAME, /* 523 */ XML_DTD_NO_PREFIX, /* 524 */ XML_DTD_NO_ROOT, /* 525 */ XML_DTD_NOTATION_REDEFINED, /* 526 */ XML_DTD_NOTATION_VALUE, /* 527 */ XML_DTD_NOT_EMPTY, /* 528 */ XML_DTD_NOT_PCDATA, /* 529 */ XML_DTD_NOT_STANDALONE, /* 530 */ XML_DTD_ROOT_NAME, /* 531 */ XML_DTD_STANDALONE_WHITE_SPACE, /* 532 */ XML_DTD_UNKNOWN_ATTRIBUTE, /* 533 */ XML_DTD_UNKNOWN_ELEM, /* 534 */ XML_DTD_UNKNOWN_ENTITY, /* 535 */ XML_DTD_UNKNOWN_ID, /* 536 */ XML_DTD_UNKNOWN_NOTATION, /* 537 */ XML_DTD_STANDALONE_DEFAULTED, /* 538 */ XML_DTD_XMLID_VALUE, /* 539 */ XML_DTD_XMLID_TYPE, /* 540 */ XML_DTD_DUP_TOKEN, /* 541 */ XML_HTML_STRUCURE_ERROR = 800, XML_HTML_UNKNOWN_TAG, /* 801 */ XML_HTML_INCORRECTLY_OPENED_COMMENT, /* 802 */ XML_RNGP_ANYNAME_ATTR_ANCESTOR = 1000, XML_RNGP_ATTR_CONFLICT, /* 1001 */ XML_RNGP_ATTRIBUTE_CHILDREN, /* 1002 */ XML_RNGP_ATTRIBUTE_CONTENT, /* 1003 */ XML_RNGP_ATTRIBUTE_EMPTY, /* 1004 */ XML_RNGP_ATTRIBUTE_NOOP, /* 1005 */ XML_RNGP_CHOICE_CONTENT, /* 1006 */ XML_RNGP_CHOICE_EMPTY, /* 1007 */ XML_RNGP_CREATE_FAILURE, /* 1008 */ XML_RNGP_DATA_CONTENT, /* 1009 */ XML_RNGP_DEF_CHOICE_AND_INTERLEAVE, /* 1010 */ XML_RNGP_DEFINE_CREATE_FAILED, /* 1011 */ XML_RNGP_DEFINE_EMPTY, /* 1012 */ XML_RNGP_DEFINE_MISSING, /* 1013 */ XML_RNGP_DEFINE_NAME_MISSING, /* 1014 */ XML_RNGP_ELEM_CONTENT_EMPTY, /* 1015 */ XML_RNGP_ELEM_CONTENT_ERROR, /* 1016 */ XML_RNGP_ELEMENT_EMPTY, /* 1017 */ XML_RNGP_ELEMENT_CONTENT, /* 1018 */ XML_RNGP_ELEMENT_NAME, /* 1019 */ XML_RNGP_ELEMENT_NO_CONTENT, /* 1020 */ XML_RNGP_ELEM_TEXT_CONFLICT, /* 1021 */ XML_RNGP_EMPTY, /* 1022 */ XML_RNGP_EMPTY_CONSTRUCT, /* 1023 */ XML_RNGP_EMPTY_CONTENT, /* 1024 */ XML_RNGP_EMPTY_NOT_EMPTY, /* 1025 */ XML_RNGP_ERROR_TYPE_LIB, /* 1026 */ XML_RNGP_EXCEPT_EMPTY, /* 1027 */ XML_RNGP_EXCEPT_MISSING, /* 1028 */ XML_RNGP_EXCEPT_MULTIPLE, /* 1029 */ XML_RNGP_EXCEPT_NO_CONTENT, /* 1030 */ XML_RNGP_EXTERNALREF_EMTPY, /* 1031 */ XML_RNGP_EXTERNAL_REF_FAILURE, /* 1032 */ XML_RNGP_EXTERNALREF_RECURSE, /* 1033 */ XML_RNGP_FORBIDDEN_ATTRIBUTE, /* 1034 */ XML_RNGP_FOREIGN_ELEMENT, /* 1035 */ XML_RNGP_GRAMMAR_CONTENT, /* 1036 */ XML_RNGP_GRAMMAR_EMPTY, /* 1037 */ XML_RNGP_GRAMMAR_MISSING, /* 1038 */ XML_RNGP_GRAMMAR_NO_START, /* 1039 */ XML_RNGP_GROUP_ATTR_CONFLICT, /* 1040 */ XML_RNGP_HREF_ERROR, /* 1041 */ XML_RNGP_INCLUDE_EMPTY, /* 1042 */ XML_RNGP_INCLUDE_FAILURE, /* 1043 */ XML_RNGP_INCLUDE_RECURSE, /* 1044 */ XML_RNGP_INTERLEAVE_ADD, /* 1045 */ XML_RNGP_INTERLEAVE_CREATE_FAILED, /* 1046 */ XML_RNGP_INTERLEAVE_EMPTY, /* 1047 */ XML_RNGP_INTERLEAVE_NO_CONTENT, /* 1048 */ XML_RNGP_INVALID_DEFINE_NAME, /* 1049 */ XML_RNGP_INVALID_URI, /* 1050 */ XML_RNGP_INVALID_VALUE, /* 1051 */ XML_RNGP_MISSING_HREF, /* 1052 */ XML_RNGP_NAME_MISSING, /* 1053 */ XML_RNGP_NEED_COMBINE, /* 1054 */ XML_RNGP_NOTALLOWED_NOT_EMPTY, /* 1055 */ XML_RNGP_NSNAME_ATTR_ANCESTOR, /* 1056 */ XML_RNGP_NSNAME_NO_NS, /* 1057 */ XML_RNGP_PARAM_FORBIDDEN, /* 1058 */ XML_RNGP_PARAM_NAME_MISSING, /* 1059 */ XML_RNGP_PARENTREF_CREATE_FAILED, /* 1060 */ XML_RNGP_PARENTREF_NAME_INVALID, /* 1061 */ XML_RNGP_PARENTREF_NO_NAME, /* 1062 */ XML_RNGP_PARENTREF_NO_PARENT, /* 1063 */ XML_RNGP_PARENTREF_NOT_EMPTY, /* 1064 */ XML_RNGP_PARSE_ERROR, /* 1065 */ XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME, /* 1066 */ XML_RNGP_PAT_ATTR_ATTR, /* 1067 */ XML_RNGP_PAT_ATTR_ELEM, /* 1068 */ XML_RNGP_PAT_DATA_EXCEPT_ATTR, /* 1069 */ XML_RNGP_PAT_DATA_EXCEPT_ELEM, /* 1070 */ XML_RNGP_PAT_DATA_EXCEPT_EMPTY, /* 1071 */ XML_RNGP_PAT_DATA_EXCEPT_GROUP, /* 1072 */ XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE, /* 1073 */ XML_RNGP_PAT_DATA_EXCEPT_LIST, /* 1074 */ XML_RNGP_PAT_DATA_EXCEPT_ONEMORE, /* 1075 */ XML_RNGP_PAT_DATA_EXCEPT_REF, /* 1076 */ XML_RNGP_PAT_DATA_EXCEPT_TEXT, /* 1077 */ XML_RNGP_PAT_LIST_ATTR, /* 1078 */ XML_RNGP_PAT_LIST_ELEM, /* 1079 */ XML_RNGP_PAT_LIST_INTERLEAVE, /* 1080 */ XML_RNGP_PAT_LIST_LIST, /* 1081 */ XML_RNGP_PAT_LIST_REF, /* 1082 */ XML_RNGP_PAT_LIST_TEXT, /* 1083 */ XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME, /* 1084 */ XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME, /* 1085 */ XML_RNGP_PAT_ONEMORE_GROUP_ATTR, /* 1086 */ XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR, /* 1087 */ XML_RNGP_PAT_START_ATTR, /* 1088 */ XML_RNGP_PAT_START_DATA, /* 1089 */ XML_RNGP_PAT_START_EMPTY, /* 1090 */ XML_RNGP_PAT_START_GROUP, /* 1091 */ XML_RNGP_PAT_START_INTERLEAVE, /* 1092 */ XML_RNGP_PAT_START_LIST, /* 1093 */ XML_RNGP_PAT_START_ONEMORE, /* 1094 */ XML_RNGP_PAT_START_TEXT, /* 1095 */ XML_RNGP_PAT_START_VALUE, /* 1096 */ XML_RNGP_PREFIX_UNDEFINED, /* 1097 */ XML_RNGP_REF_CREATE_FAILED, /* 1098 */ XML_RNGP_REF_CYCLE, /* 1099 */ XML_RNGP_REF_NAME_INVALID, /* 1100 */ XML_RNGP_REF_NO_DEF, /* 1101 */ XML_RNGP_REF_NO_NAME, /* 1102 */ XML_RNGP_REF_NOT_EMPTY, /* 1103 */ XML_RNGP_START_CHOICE_AND_INTERLEAVE, /* 1104 */ XML_RNGP_START_CONTENT, /* 1105 */ XML_RNGP_START_EMPTY, /* 1106 */ XML_RNGP_START_MISSING, /* 1107 */ XML_RNGP_TEXT_EXPECTED, /* 1108 */ XML_RNGP_TEXT_HAS_CHILD, /* 1109 */ XML_RNGP_TYPE_MISSING, /* 1110 */ XML_RNGP_TYPE_NOT_FOUND, /* 1111 */ XML_RNGP_TYPE_VALUE, /* 1112 */ XML_RNGP_UNKNOWN_ATTRIBUTE, /* 1113 */ XML_RNGP_UNKNOWN_COMBINE, /* 1114 */ XML_RNGP_UNKNOWN_CONSTRUCT, /* 1115 */ XML_RNGP_UNKNOWN_TYPE_LIB, /* 1116 */ XML_RNGP_URI_FRAGMENT, /* 1117 */ XML_RNGP_URI_NOT_ABSOLUTE, /* 1118 */ XML_RNGP_VALUE_EMPTY, /* 1119 */ XML_RNGP_VALUE_NO_CONTENT, /* 1120 */ XML_RNGP_XMLNS_NAME, /* 1121 */ XML_RNGP_XML_NS, /* 1122 */ XML_XPATH_EXPRESSION_OK = 1200, XML_XPATH_NUMBER_ERROR, /* 1201 */ XML_XPATH_UNFINISHED_LITERAL_ERROR, /* 1202 */ XML_XPATH_START_LITERAL_ERROR, /* 1203 */ XML_XPATH_VARIABLE_REF_ERROR, /* 1204 */ XML_XPATH_UNDEF_VARIABLE_ERROR, /* 1205 */ XML_XPATH_INVALID_PREDICATE_ERROR, /* 1206 */ XML_XPATH_EXPR_ERROR, /* 1207 */ XML_XPATH_UNCLOSED_ERROR, /* 1208 */ XML_XPATH_UNKNOWN_FUNC_ERROR, /* 1209 */ XML_XPATH_INVALID_OPERAND, /* 1210 */ XML_XPATH_INVALID_TYPE, /* 1211 */ XML_XPATH_INVALID_ARITY, /* 1212 */ XML_XPATH_INVALID_CTXT_SIZE, /* 1213 */ XML_XPATH_INVALID_CTXT_POSITION, /* 1214 */ XML_XPATH_MEMORY_ERROR, /* 1215 */ XML_XPTR_SYNTAX_ERROR, /* 1216 */ XML_XPTR_RESOURCE_ERROR, /* 1217 */ XML_XPTR_SUB_RESOURCE_ERROR, /* 1218 */ XML_XPATH_UNDEF_PREFIX_ERROR, /* 1219 */ XML_XPATH_ENCODING_ERROR, /* 1220 */ XML_XPATH_INVALID_CHAR_ERROR, /* 1221 */ XML_TREE_INVALID_HEX = 1300, XML_TREE_INVALID_DEC, /* 1301 */ XML_TREE_UNTERMINATED_ENTITY, /* 1302 */ XML_TREE_NOT_UTF8, /* 1303 */ XML_SAVE_NOT_UTF8 = 1400, XML_SAVE_CHAR_INVALID, /* 1401 */ XML_SAVE_NO_DOCTYPE, /* 1402 */ XML_SAVE_UNKNOWN_ENCODING, /* 1403 */ XML_REGEXP_COMPILE_ERROR = 1450, XML_IO_UNKNOWN = 1500, XML_IO_EACCES, /* 1501 */ XML_IO_EAGAIN, /* 1502 */ XML_IO_EBADF, /* 1503 */ XML_IO_EBADMSG, /* 1504 */ XML_IO_EBUSY, /* 1505 */ XML_IO_ECANCELED, /* 1506 */ XML_IO_ECHILD, /* 1507 */ XML_IO_EDEADLK, /* 1508 */ XML_IO_EDOM, /* 1509 */ XML_IO_EEXIST, /* 1510 */ XML_IO_EFAULT, /* 1511 */ XML_IO_EFBIG, /* 1512 */ XML_IO_EINPROGRESS, /* 1513 */ XML_IO_EINTR, /* 1514 */ XML_IO_EINVAL, /* 1515 */ XML_IO_EIO, /* 1516 */ XML_IO_EISDIR, /* 1517 */ XML_IO_EMFILE, /* 1518 */ XML_IO_EMLINK, /* 1519 */ XML_IO_EMSGSIZE, /* 1520 */ XML_IO_ENAMETOOLONG, /* 1521 */ XML_IO_ENFILE, /* 1522 */ XML_IO_ENODEV, /* 1523 */ XML_IO_ENOENT, /* 1524 */ XML_IO_ENOEXEC, /* 1525 */ XML_IO_ENOLCK, /* 1526 */ XML_IO_ENOMEM, /* 1527 */ XML_IO_ENOSPC, /* 1528 */ XML_IO_ENOSYS, /* 1529 */ XML_IO_ENOTDIR, /* 1530 */ XML_IO_ENOTEMPTY, /* 1531 */ XML_IO_ENOTSUP, /* 1532 */ XML_IO_ENOTTY, /* 1533 */ XML_IO_ENXIO, /* 1534 */ XML_IO_EPERM, /* 1535 */ XML_IO_EPIPE, /* 1536 */ XML_IO_ERANGE, /* 1537 */ XML_IO_EROFS, /* 1538 */ XML_IO_ESPIPE, /* 1539 */ XML_IO_ESRCH, /* 1540 */ XML_IO_ETIMEDOUT, /* 1541 */ XML_IO_EXDEV, /* 1542 */ XML_IO_NETWORK_ATTEMPT, /* 1543 */ XML_IO_ENCODER, /* 1544 */ XML_IO_FLUSH, /* 1545 */ XML_IO_WRITE, /* 1546 */ XML_IO_NO_INPUT, /* 1547 */ XML_IO_BUFFER_FULL, /* 1548 */ XML_IO_LOAD_ERROR, /* 1549 */ XML_IO_ENOTSOCK, /* 1550 */ XML_IO_EISCONN, /* 1551 */ XML_IO_ECONNREFUSED, /* 1552 */ XML_IO_ENETUNREACH, /* 1553 */ XML_IO_EADDRINUSE, /* 1554 */ XML_IO_EALREADY, /* 1555 */ XML_IO_EAFNOSUPPORT, /* 1556 */ XML_XINCLUDE_RECURSION=1600, XML_XINCLUDE_PARSE_VALUE, /* 1601 */ XML_XINCLUDE_ENTITY_DEF_MISMATCH, /* 1602 */ XML_XINCLUDE_NO_HREF, /* 1603 */ XML_XINCLUDE_NO_FALLBACK, /* 1604 */ XML_XINCLUDE_HREF_URI, /* 1605 */ XML_XINCLUDE_TEXT_FRAGMENT, /* 1606 */ XML_XINCLUDE_TEXT_DOCUMENT, /* 1607 */ XML_XINCLUDE_INVALID_CHAR, /* 1608 */ XML_XINCLUDE_BUILD_FAILED, /* 1609 */ XML_XINCLUDE_UNKNOWN_ENCODING, /* 1610 */ XML_XINCLUDE_MULTIPLE_ROOT, /* 1611 */ XML_XINCLUDE_XPTR_FAILED, /* 1612 */ XML_XINCLUDE_XPTR_RESULT, /* 1613 */ XML_XINCLUDE_INCLUDE_IN_INCLUDE, /* 1614 */ XML_XINCLUDE_FALLBACKS_IN_INCLUDE, /* 1615 */ XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE, /* 1616 */ XML_XINCLUDE_DEPRECATED_NS, /* 1617 */ XML_XINCLUDE_FRAGMENT_ID, /* 1618 */ XML_CATALOG_MISSING_ATTR = 1650, XML_CATALOG_ENTRY_BROKEN, /* 1651 */ XML_CATALOG_PREFER_VALUE, /* 1652 */ XML_CATALOG_NOT_CATALOG, /* 1653 */ XML_CATALOG_RECURSION, /* 1654 */ XML_SCHEMAP_PREFIX_UNDEFINED = 1700, XML_SCHEMAP_ATTRFORMDEFAULT_VALUE, /* 1701 */ XML_SCHEMAP_ATTRGRP_NONAME_NOREF, /* 1702 */ XML_SCHEMAP_ATTR_NONAME_NOREF, /* 1703 */ XML_SCHEMAP_COMPLEXTYPE_NONAME_NOREF, /* 1704 */ XML_SCHEMAP_ELEMFORMDEFAULT_VALUE, /* 1705 */ XML_SCHEMAP_ELEM_NONAME_NOREF, /* 1706 */ XML_SCHEMAP_EXTENSION_NO_BASE, /* 1707 */ XML_SCHEMAP_FACET_NO_VALUE, /* 1708 */ XML_SCHEMAP_FAILED_BUILD_IMPORT, /* 1709 */ XML_SCHEMAP_GROUP_NONAME_NOREF, /* 1710 */ XML_SCHEMAP_IMPORT_NAMESPACE_NOT_URI, /* 1711 */ XML_SCHEMAP_IMPORT_REDEFINE_NSNAME, /* 1712 */ XML_SCHEMAP_IMPORT_SCHEMA_NOT_URI, /* 1713 */ XML_SCHEMAP_INVALID_BOOLEAN, /* 1714 */ XML_SCHEMAP_INVALID_ENUM, /* 1715 */ XML_SCHEMAP_INVALID_FACET, /* 1716 */ XML_SCHEMAP_INVALID_FACET_VALUE, /* 1717 */ XML_SCHEMAP_INVALID_MAXOCCURS, /* 1718 */ XML_SCHEMAP_INVALID_MINOCCURS, /* 1719 */ XML_SCHEMAP_INVALID_REF_AND_SUBTYPE, /* 1720 */ XML_SCHEMAP_INVALID_WHITE_SPACE, /* 1721 */ XML_SCHEMAP_NOATTR_NOREF, /* 1722 */ XML_SCHEMAP_NOTATION_NO_NAME, /* 1723 */ XML_SCHEMAP_NOTYPE_NOREF, /* 1724 */ XML_SCHEMAP_REF_AND_SUBTYPE, /* 1725 */ XML_SCHEMAP_RESTRICTION_NONAME_NOREF, /* 1726 */ XML_SCHEMAP_SIMPLETYPE_NONAME, /* 1727 */ XML_SCHEMAP_TYPE_AND_SUBTYPE, /* 1728 */ XML_SCHEMAP_UNKNOWN_ALL_CHILD, /* 1729 */ XML_SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD, /* 1730 */ XML_SCHEMAP_UNKNOWN_ATTR_CHILD, /* 1731 */ XML_SCHEMAP_UNKNOWN_ATTRGRP_CHILD, /* 1732 */ XML_SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP, /* 1733 */ XML_SCHEMAP_UNKNOWN_BASE_TYPE, /* 1734 */ XML_SCHEMAP_UNKNOWN_CHOICE_CHILD, /* 1735 */ XML_SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD, /* 1736 */ XML_SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD, /* 1737 */ XML_SCHEMAP_UNKNOWN_ELEM_CHILD, /* 1738 */ XML_SCHEMAP_UNKNOWN_EXTENSION_CHILD, /* 1739 */ XML_SCHEMAP_UNKNOWN_FACET_CHILD, /* 1740 */ XML_SCHEMAP_UNKNOWN_FACET_TYPE, /* 1741 */ XML_SCHEMAP_UNKNOWN_GROUP_CHILD, /* 1742 */ XML_SCHEMAP_UNKNOWN_IMPORT_CHILD, /* 1743 */ XML_SCHEMAP_UNKNOWN_LIST_CHILD, /* 1744 */ XML_SCHEMAP_UNKNOWN_NOTATION_CHILD, /* 1745 */ XML_SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD, /* 1746 */ XML_SCHEMAP_UNKNOWN_REF, /* 1747 */ XML_SCHEMAP_UNKNOWN_RESTRICTION_CHILD, /* 1748 */ XML_SCHEMAP_UNKNOWN_SCHEMAS_CHILD, /* 1749 */ XML_SCHEMAP_UNKNOWN_SEQUENCE_CHILD, /* 1750 */ XML_SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD, /* 1751 */ XML_SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD, /* 1752 */ XML_SCHEMAP_UNKNOWN_TYPE, /* 1753 */ XML_SCHEMAP_UNKNOWN_UNION_CHILD, /* 1754 */ XML_SCHEMAP_ELEM_DEFAULT_FIXED, /* 1755 */ XML_SCHEMAP_REGEXP_INVALID, /* 1756 */ XML_SCHEMAP_FAILED_LOAD, /* 1757 */ XML_SCHEMAP_NOTHING_TO_PARSE, /* 1758 */ XML_SCHEMAP_NOROOT, /* 1759 */ XML_SCHEMAP_REDEFINED_GROUP, /* 1760 */ XML_SCHEMAP_REDEFINED_TYPE, /* 1761 */ XML_SCHEMAP_REDEFINED_ELEMENT, /* 1762 */ XML_SCHEMAP_REDEFINED_ATTRGROUP, /* 1763 */ XML_SCHEMAP_REDEFINED_ATTR, /* 1764 */ XML_SCHEMAP_REDEFINED_NOTATION, /* 1765 */ XML_SCHEMAP_FAILED_PARSE, /* 1766 */ XML_SCHEMAP_UNKNOWN_PREFIX, /* 1767 */ XML_SCHEMAP_DEF_AND_PREFIX, /* 1768 */ XML_SCHEMAP_UNKNOWN_INCLUDE_CHILD, /* 1769 */ XML_SCHEMAP_INCLUDE_SCHEMA_NOT_URI, /* 1770 */ XML_SCHEMAP_INCLUDE_SCHEMA_NO_URI, /* 1771 */ XML_SCHEMAP_NOT_SCHEMA, /* 1772 */ XML_SCHEMAP_UNKNOWN_MEMBER_TYPE, /* 1773 */ XML_SCHEMAP_INVALID_ATTR_USE, /* 1774 */ XML_SCHEMAP_RECURSIVE, /* 1775 */ XML_SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE, /* 1776 */ XML_SCHEMAP_INVALID_ATTR_COMBINATION, /* 1777 */ XML_SCHEMAP_INVALID_ATTR_INLINE_COMBINATION, /* 1778 */ XML_SCHEMAP_MISSING_SIMPLETYPE_CHILD, /* 1779 */ XML_SCHEMAP_INVALID_ATTR_NAME, /* 1780 */ XML_SCHEMAP_REF_AND_CONTENT, /* 1781 */ XML_SCHEMAP_CT_PROPS_CORRECT_1, /* 1782 */ XML_SCHEMAP_CT_PROPS_CORRECT_2, /* 1783 */ XML_SCHEMAP_CT_PROPS_CORRECT_3, /* 1784 */ XML_SCHEMAP_CT_PROPS_CORRECT_4, /* 1785 */ XML_SCHEMAP_CT_PROPS_CORRECT_5, /* 1786 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1, /* 1787 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1, /* 1788 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2, /* 1789 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2, /* 1790 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3, /* 1791 */ XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER, /* 1792 */ XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE, /* 1793 */ XML_SCHEMAP_UNION_NOT_EXPRESSIBLE, /* 1794 */ XML_SCHEMAP_SRC_IMPORT_3_1, /* 1795 */ XML_SCHEMAP_SRC_IMPORT_3_2, /* 1796 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1, /* 1797 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2, /* 1798 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_3, /* 1799 */ XML_SCHEMAP_COS_CT_EXTENDS_1_3, /* 1800 */ XML_SCHEMAV_NOROOT = 1801, XML_SCHEMAV_UNDECLAREDELEM, /* 1802 */ XML_SCHEMAV_NOTTOPLEVEL, /* 1803 */ XML_SCHEMAV_MISSING, /* 1804 */ XML_SCHEMAV_WRONGELEM, /* 1805 */ XML_SCHEMAV_NOTYPE, /* 1806 */ XML_SCHEMAV_NOROLLBACK, /* 1807 */ XML_SCHEMAV_ISABSTRACT, /* 1808 */ XML_SCHEMAV_NOTEMPTY, /* 1809 */ XML_SCHEMAV_ELEMCONT, /* 1810 */ XML_SCHEMAV_HAVEDEFAULT, /* 1811 */ XML_SCHEMAV_NOTNILLABLE, /* 1812 */ XML_SCHEMAV_EXTRACONTENT, /* 1813 */ XML_SCHEMAV_INVALIDATTR, /* 1814 */ XML_SCHEMAV_INVALIDELEM, /* 1815 */ XML_SCHEMAV_NOTDETERMINIST, /* 1816 */ XML_SCHEMAV_CONSTRUCT, /* 1817 */ XML_SCHEMAV_INTERNAL, /* 1818 */ XML_SCHEMAV_NOTSIMPLE, /* 1819 */ XML_SCHEMAV_ATTRUNKNOWN, /* 1820 */ XML_SCHEMAV_ATTRINVALID, /* 1821 */ XML_SCHEMAV_VALUE, /* 1822 */ XML_SCHEMAV_FACET, /* 1823 */ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1, /* 1824 */ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2, /* 1825 */ XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3, /* 1826 */ XML_SCHEMAV_CVC_TYPE_3_1_1, /* 1827 */ XML_SCHEMAV_CVC_TYPE_3_1_2, /* 1828 */ XML_SCHEMAV_CVC_FACET_VALID, /* 1829 */ XML_SCHEMAV_CVC_LENGTH_VALID, /* 1830 */ XML_SCHEMAV_CVC_MINLENGTH_VALID, /* 1831 */ XML_SCHEMAV_CVC_MAXLENGTH_VALID, /* 1832 */ XML_SCHEMAV_CVC_MININCLUSIVE_VALID, /* 1833 */ XML_SCHEMAV_CVC_MAXINCLUSIVE_VALID, /* 1834 */ XML_SCHEMAV_CVC_MINEXCLUSIVE_VALID, /* 1835 */ XML_SCHEMAV_CVC_MAXEXCLUSIVE_VALID, /* 1836 */ XML_SCHEMAV_CVC_TOTALDIGITS_VALID, /* 1837 */ XML_SCHEMAV_CVC_FRACTIONDIGITS_VALID, /* 1838 */ XML_SCHEMAV_CVC_PATTERN_VALID, /* 1839 */ XML_SCHEMAV_CVC_ENUMERATION_VALID, /* 1840 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1, /* 1841 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2, /* 1842 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3, /* 1843 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_2_4, /* 1844 */ XML_SCHEMAV_CVC_ELT_1, /* 1845 */ XML_SCHEMAV_CVC_ELT_2, /* 1846 */ XML_SCHEMAV_CVC_ELT_3_1, /* 1847 */ XML_SCHEMAV_CVC_ELT_3_2_1, /* 1848 */ XML_SCHEMAV_CVC_ELT_3_2_2, /* 1849 */ XML_SCHEMAV_CVC_ELT_4_1, /* 1850 */ XML_SCHEMAV_CVC_ELT_4_2, /* 1851 */ XML_SCHEMAV_CVC_ELT_4_3, /* 1852 */ XML_SCHEMAV_CVC_ELT_5_1_1, /* 1853 */ XML_SCHEMAV_CVC_ELT_5_1_2, /* 1854 */ XML_SCHEMAV_CVC_ELT_5_2_1, /* 1855 */ XML_SCHEMAV_CVC_ELT_5_2_2_1, /* 1856 */ XML_SCHEMAV_CVC_ELT_5_2_2_2_1, /* 1857 */ XML_SCHEMAV_CVC_ELT_5_2_2_2_2, /* 1858 */ XML_SCHEMAV_CVC_ELT_6, /* 1859 */ XML_SCHEMAV_CVC_ELT_7, /* 1860 */ XML_SCHEMAV_CVC_ATTRIBUTE_1, /* 1861 */ XML_SCHEMAV_CVC_ATTRIBUTE_2, /* 1862 */ XML_SCHEMAV_CVC_ATTRIBUTE_3, /* 1863 */ XML_SCHEMAV_CVC_ATTRIBUTE_4, /* 1864 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_1, /* 1865 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1, /* 1866 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_2, /* 1867 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_4, /* 1868 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_1, /* 1869 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_5_2, /* 1870 */ XML_SCHEMAV_ELEMENT_CONTENT, /* 1871 */ XML_SCHEMAV_DOCUMENT_ELEMENT_MISSING, /* 1872 */ XML_SCHEMAV_CVC_COMPLEX_TYPE_1, /* 1873 */ XML_SCHEMAV_CVC_AU, /* 1874 */ XML_SCHEMAV_CVC_TYPE_1, /* 1875 */ XML_SCHEMAV_CVC_TYPE_2, /* 1876 */ XML_SCHEMAV_CVC_IDC, /* 1877 */ XML_SCHEMAV_CVC_WILDCARD, /* 1878 */ XML_SCHEMAV_MISC, /* 1879 */ XML_XPTR_UNKNOWN_SCHEME = 1900, XML_XPTR_CHILDSEQ_START, /* 1901 */ XML_XPTR_EVAL_FAILED, /* 1902 */ XML_XPTR_EXTRA_OBJECTS, /* 1903 */ XML_C14N_CREATE_CTXT = 1950, XML_C14N_REQUIRES_UTF8, /* 1951 */ XML_C14N_CREATE_STACK, /* 1952 */ XML_C14N_INVALID_NODE, /* 1953 */ XML_C14N_UNKNOW_NODE, /* 1954 */ XML_C14N_RELATIVE_NAMESPACE, /* 1955 */ XML_FTP_PASV_ANSWER = 2000, XML_FTP_EPSV_ANSWER, /* 2001 */ XML_FTP_ACCNT, /* 2002 */ XML_FTP_URL_SYNTAX, /* 2003 */ XML_HTTP_URL_SYNTAX = 2020, XML_HTTP_USE_IP, /* 2021 */ XML_HTTP_UNKNOWN_HOST, /* 2022 */ XML_SCHEMAP_SRC_SIMPLE_TYPE_1 = 3000, XML_SCHEMAP_SRC_SIMPLE_TYPE_2, /* 3001 */ XML_SCHEMAP_SRC_SIMPLE_TYPE_3, /* 3002 */ XML_SCHEMAP_SRC_SIMPLE_TYPE_4, /* 3003 */ XML_SCHEMAP_SRC_RESOLVE, /* 3004 */ XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE, /* 3005 */ XML_SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE, /* 3006 */ XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES, /* 3007 */ XML_SCHEMAP_ST_PROPS_CORRECT_1, /* 3008 */ XML_SCHEMAP_ST_PROPS_CORRECT_2, /* 3009 */ XML_SCHEMAP_ST_PROPS_CORRECT_3, /* 3010 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_1, /* 3011 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_2, /* 3012 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1, /* 3013 */ XML_SCHEMAP_COS_ST_RESTRICTS_1_3_2, /* 3014 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_1, /* 3015 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1, /* 3016 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2, /* 3017 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1, /* 3018 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2, /* 3019 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3, /* 3020 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4, /* 3021 */ XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_5, /* 3022 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_1, /* 3023 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1, /* 3024 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2, /* 3025 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2, /* 3026 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1, /* 3027 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3, /* 3028 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4, /* 3029 */ XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_5, /* 3030 */ XML_SCHEMAP_COS_ST_DERIVED_OK_2_1, /* 3031 */ XML_SCHEMAP_COS_ST_DERIVED_OK_2_2, /* 3032 */ XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED, /* 3033 */ XML_SCHEMAP_S4S_ELEM_MISSING, /* 3034 */ XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED, /* 3035 */ XML_SCHEMAP_S4S_ATTR_MISSING, /* 3036 */ XML_SCHEMAP_S4S_ATTR_INVALID_VALUE, /* 3037 */ XML_SCHEMAP_SRC_ELEMENT_1, /* 3038 */ XML_SCHEMAP_SRC_ELEMENT_2_1, /* 3039 */ XML_SCHEMAP_SRC_ELEMENT_2_2, /* 3040 */ XML_SCHEMAP_SRC_ELEMENT_3, /* 3041 */ XML_SCHEMAP_P_PROPS_CORRECT_1, /* 3042 */ XML_SCHEMAP_P_PROPS_CORRECT_2_1, /* 3043 */ XML_SCHEMAP_P_PROPS_CORRECT_2_2, /* 3044 */ XML_SCHEMAP_E_PROPS_CORRECT_2, /* 3045 */ XML_SCHEMAP_E_PROPS_CORRECT_3, /* 3046 */ XML_SCHEMAP_E_PROPS_CORRECT_4, /* 3047 */ XML_SCHEMAP_E_PROPS_CORRECT_5, /* 3048 */ XML_SCHEMAP_E_PROPS_CORRECT_6, /* 3049 */ XML_SCHEMAP_SRC_INCLUDE, /* 3050 */ XML_SCHEMAP_SRC_ATTRIBUTE_1, /* 3051 */ XML_SCHEMAP_SRC_ATTRIBUTE_2, /* 3052 */ XML_SCHEMAP_SRC_ATTRIBUTE_3_1, /* 3053 */ XML_SCHEMAP_SRC_ATTRIBUTE_3_2, /* 3054 */ XML_SCHEMAP_SRC_ATTRIBUTE_4, /* 3055 */ XML_SCHEMAP_NO_XMLNS, /* 3056 */ XML_SCHEMAP_NO_XSI, /* 3057 */ XML_SCHEMAP_COS_VALID_DEFAULT_1, /* 3058 */ XML_SCHEMAP_COS_VALID_DEFAULT_2_1, /* 3059 */ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_1, /* 3060 */ XML_SCHEMAP_COS_VALID_DEFAULT_2_2_2, /* 3061 */ XML_SCHEMAP_CVC_SIMPLE_TYPE, /* 3062 */ XML_SCHEMAP_COS_CT_EXTENDS_1_1, /* 3063 */ XML_SCHEMAP_SRC_IMPORT_1_1, /* 3064 */ XML_SCHEMAP_SRC_IMPORT_1_2, /* 3065 */ XML_SCHEMAP_SRC_IMPORT_2, /* 3066 */ XML_SCHEMAP_SRC_IMPORT_2_1, /* 3067 */ XML_SCHEMAP_SRC_IMPORT_2_2, /* 3068 */ XML_SCHEMAP_INTERNAL, /* 3069 non-W3C */ XML_SCHEMAP_NOT_DETERMINISTIC, /* 3070 non-W3C */ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_1, /* 3071 */ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_2, /* 3072 */ XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_3, /* 3073 */ XML_SCHEMAP_MG_PROPS_CORRECT_1, /* 3074 */ XML_SCHEMAP_MG_PROPS_CORRECT_2, /* 3075 */ XML_SCHEMAP_SRC_CT_1, /* 3076 */ XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3, /* 3077 */ XML_SCHEMAP_AU_PROPS_CORRECT_2, /* 3078 */ XML_SCHEMAP_A_PROPS_CORRECT_2, /* 3079 */ XML_SCHEMAP_C_PROPS_CORRECT, /* 3080 */ XML_SCHEMAP_SRC_REDEFINE, /* 3081 */ XML_SCHEMAP_SRC_IMPORT, /* 3082 */ XML_SCHEMAP_WARN_SKIP_SCHEMA, /* 3083 */ XML_SCHEMAP_WARN_UNLOCATED_SCHEMA, /* 3084 */ XML_SCHEMAP_WARN_ATTR_REDECL_PROH, /* 3085 */ XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH, /* 3085 */ XML_SCHEMAP_AG_PROPS_CORRECT, /* 3086 */ XML_SCHEMAP_COS_CT_EXTENDS_1_2, /* 3087 */ XML_SCHEMAP_AU_PROPS_CORRECT, /* 3088 */ XML_SCHEMAP_A_PROPS_CORRECT_3, /* 3089 */ XML_SCHEMAP_COS_ALL_LIMITED, /* 3090 */ XML_SCHEMATRONV_ASSERT = 4000, /* 4000 */ XML_SCHEMATRONV_REPORT, XML_MODULE_OPEN = 4900, /* 4900 */ XML_MODULE_CLOSE, /* 4901 */ XML_CHECK_FOUND_ELEMENT = 5000, XML_CHECK_FOUND_ATTRIBUTE, /* 5001 */ XML_CHECK_FOUND_TEXT, /* 5002 */ XML_CHECK_FOUND_CDATA, /* 5003 */ XML_CHECK_FOUND_ENTITYREF, /* 5004 */ XML_CHECK_FOUND_ENTITY, /* 5005 */ XML_CHECK_FOUND_PI, /* 5006 */ XML_CHECK_FOUND_COMMENT, /* 5007 */ XML_CHECK_FOUND_DOCTYPE, /* 5008 */ XML_CHECK_FOUND_FRAGMENT, /* 5009 */ XML_CHECK_FOUND_NOTATION, /* 5010 */ XML_CHECK_UNKNOWN_NODE, /* 5011 */ XML_CHECK_ENTITY_TYPE, /* 5012 */ XML_CHECK_NO_PARENT, /* 5013 */ XML_CHECK_NO_DOC, /* 5014 */ XML_CHECK_NO_NAME, /* 5015 */ XML_CHECK_NO_ELEM, /* 5016 */ XML_CHECK_WRONG_DOC, /* 5017 */ XML_CHECK_NO_PREV, /* 5018 */ XML_CHECK_WRONG_PREV, /* 5019 */ XML_CHECK_NO_NEXT, /* 5020 */ XML_CHECK_WRONG_NEXT, /* 5021 */ XML_CHECK_NOT_DTD, /* 5022 */ XML_CHECK_NOT_ATTR, /* 5023 */ XML_CHECK_NOT_ATTR_DECL, /* 5024 */ XML_CHECK_NOT_ELEM_DECL, /* 5025 */ XML_CHECK_NOT_ENTITY_DECL, /* 5026 */ XML_CHECK_NOT_NS_DECL, /* 5027 */ XML_CHECK_NO_HREF, /* 5028 */ XML_CHECK_WRONG_PARENT,/* 5029 */ XML_CHECK_NS_SCOPE, /* 5030 */ XML_CHECK_NS_ANCESTOR, /* 5031 */ XML_CHECK_NOT_UTF8, /* 5032 */ XML_CHECK_NO_DICT, /* 5033 */ XML_CHECK_NOT_NCNAME, /* 5034 */ XML_CHECK_OUTSIDE_DICT, /* 5035 */ XML_CHECK_WRONG_NAME, /* 5036 */ XML_CHECK_NAME_NOT_NULL, /* 5037 */ XML_I18N_NO_NAME = 6000, XML_I18N_NO_HANDLER, /* 6001 */ XML_I18N_EXCESS_HANDLER, /* 6002 */ XML_I18N_CONV_FAILED, /* 6003 */ XML_I18N_NO_OUTPUT, /* 6004 */ XML_BUF_OVERFLOW = 7000 } xmlParserErrors; /** * xmlGenericErrorFunc: * @ctx: a parsing context * @msg: the message * @...: the extra arguments of the varargs to format the message * * Signature of the function to use when there is an error and * no parsing or validity context available . */ typedef void (*xmlGenericErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlStructuredErrorFunc: * @userData: user provided data for the error callback * @error: the error being raised. * * Signature of the function to use when there is an error and * the module handles the new error reporting mechanism. */ typedef void (*xmlStructuredErrorFunc) (void *userData, xmlErrorPtr error); /* * Use the following function to reset the two global variables * xmlGenericError and xmlGenericErrorContext. */ XMLPUBFUN void xmlSetGenericErrorFunc (void *ctx, xmlGenericErrorFunc handler); XML_DEPRECATED XMLPUBFUN void initGenericErrorDefaultFunc (xmlGenericErrorFunc *handler); XMLPUBFUN void xmlSetStructuredErrorFunc (void *ctx, xmlStructuredErrorFunc handler); /* * Default message routines used by SAX and Valid context for error * and warning reporting. */ XMLPUBFUN void xmlParserError (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserWarning (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserValidityError (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserValidityWarning (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN void xmlParserPrintFileInfo (xmlParserInputPtr input); XMLPUBFUN void xmlParserPrintFileContext (xmlParserInputPtr input); /* * Extended error information routines */ XMLPUBFUN xmlErrorPtr xmlGetLastError (void); XMLPUBFUN void xmlResetLastError (void); XMLPUBFUN xmlErrorPtr xmlCtxtGetLastError (void *ctx); XMLPUBFUN void xmlCtxtResetLastError (void *ctx); XMLPUBFUN void xmlResetError (xmlErrorPtr err); XMLPUBFUN int xmlCopyError (xmlErrorPtr from, xmlErrorPtr to); #ifdef __cplusplus } #endif #endif /* __XML_ERROR_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlexports.h ================================================ /* * Summary: macros for marking symbols as exportable/importable. * Description: macros for marking symbols as exportable/importable. * * Copy: See Copyright for the status of this software. */ #ifndef __XML_EXPORTS_H__ #define __XML_EXPORTS_H__ /** DOC_DISABLE */ #if defined(_WIN32) || defined(__CYGWIN__) #ifdef LIBXML_STATIC #define XMLPUBLIC #elif defined(IN_LIBXML) #define XMLPUBLIC __declspec(dllexport) #else #define XMLPUBLIC __declspec(dllimport) #endif #else /* not Windows */ #define XMLPUBLIC #endif /* platform switch */ /** DOC_ENABLE */ /* * XMLPUBFUN: * * Macro which declares an exportable function */ #define XMLPUBFUN XMLPUBLIC /** * XMLPUBVAR: * * Macro which declares an exportable variable */ #define XMLPUBVAR XMLPUBLIC extern /** DOC_DISABLE */ /* Compatibility */ #define XMLCALL #define XMLCDECL #if !defined(LIBXML_DLL_IMPORT) #define LIBXML_DLL_IMPORT XMLPUBVAR #endif /** DOC_ENABLE */ #endif /* __XML_EXPORTS_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlmemory.h ================================================ /* * Summary: interface for the memory allocator * Description: provides interfaces for the memory allocator, * including debugging capabilities. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __DEBUG_MEMORY_ALLOC__ #define __DEBUG_MEMORY_ALLOC__ #include #include /** * DEBUG_MEMORY: * * DEBUG_MEMORY replaces the allocator with a collect and debug * shell to the libc allocator. * DEBUG_MEMORY should only be activated when debugging * libxml i.e. if libxml has been configured with --with-debug-mem too. */ /* #define DEBUG_MEMORY_FREED */ /* #define DEBUG_MEMORY_LOCATION */ #ifdef DEBUG #ifndef DEBUG_MEMORY #define DEBUG_MEMORY #endif #endif /** * DEBUG_MEMORY_LOCATION: * * DEBUG_MEMORY_LOCATION should be activated only when debugging * libxml i.e. if libxml has been configured with --with-debug-mem too. */ #ifdef DEBUG_MEMORY_LOCATION #endif #ifdef __cplusplus extern "C" { #endif /* * The XML memory wrapper support 4 basic overloadable functions. */ /** * xmlFreeFunc: * @mem: an already allocated block of memory * * Signature for a free() implementation. */ typedef void (*xmlFreeFunc)(void *mem); /** * xmlMallocFunc: * @size: the size requested in bytes * * Signature for a malloc() implementation. * * Returns a pointer to the newly allocated block or NULL in case of error. */ typedef void *(LIBXML_ATTR_ALLOC_SIZE(1) *xmlMallocFunc)(size_t size); /** * xmlReallocFunc: * @mem: an already allocated block of memory * @size: the new size requested in bytes * * Signature for a realloc() implementation. * * Returns a pointer to the newly reallocated block or NULL in case of error. */ typedef void *(*xmlReallocFunc)(void *mem, size_t size); /** * xmlStrdupFunc: * @str: a zero terminated string * * Signature for an strdup() implementation. * * Returns the copy of the string or NULL in case of error. */ typedef char *(*xmlStrdupFunc)(const char *str); /* * The 4 interfaces used for all memory handling within libxml. LIBXML_DLL_IMPORT xmlFreeFunc xmlFree; LIBXML_DLL_IMPORT xmlMallocFunc xmlMalloc; LIBXML_DLL_IMPORT xmlMallocFunc xmlMallocAtomic; LIBXML_DLL_IMPORT xmlReallocFunc xmlRealloc; LIBXML_DLL_IMPORT xmlStrdupFunc xmlMemStrdup; */ /* * The way to overload the existing functions. * The xmlGc function have an extra entry for atomic block * allocations useful for garbage collected memory allocators */ XMLPUBFUN int xmlMemSetup (xmlFreeFunc freeFunc, xmlMallocFunc mallocFunc, xmlReallocFunc reallocFunc, xmlStrdupFunc strdupFunc); XMLPUBFUN int xmlMemGet (xmlFreeFunc *freeFunc, xmlMallocFunc *mallocFunc, xmlReallocFunc *reallocFunc, xmlStrdupFunc *strdupFunc); XMLPUBFUN int xmlGcMemSetup (xmlFreeFunc freeFunc, xmlMallocFunc mallocFunc, xmlMallocFunc mallocAtomicFunc, xmlReallocFunc reallocFunc, xmlStrdupFunc strdupFunc); XMLPUBFUN int xmlGcMemGet (xmlFreeFunc *freeFunc, xmlMallocFunc *mallocFunc, xmlMallocFunc *mallocAtomicFunc, xmlReallocFunc *reallocFunc, xmlStrdupFunc *strdupFunc); /* * Initialization of the memory layer. */ XML_DEPRECATED XMLPUBFUN int xmlInitMemory (void); /* * Cleanup of the memory layer. */ XML_DEPRECATED XMLPUBFUN void xmlCleanupMemory (void); /* * These are specific to the XML debug memory wrapper. */ XMLPUBFUN size_t xmlMemSize (void *ptr); XMLPUBFUN int xmlMemUsed (void); XMLPUBFUN int xmlMemBlocks (void); XMLPUBFUN void xmlMemDisplay (FILE *fp); XMLPUBFUN void xmlMemDisplayLast(FILE *fp, long nbBytes); XMLPUBFUN void xmlMemShow (FILE *fp, int nr); XMLPUBFUN void xmlMemoryDump (void); XMLPUBFUN void * xmlMemMalloc (size_t size) LIBXML_ATTR_ALLOC_SIZE(1); XMLPUBFUN void * xmlMemRealloc (void *ptr,size_t size); XMLPUBFUN void xmlMemFree (void *ptr); XMLPUBFUN char * xmlMemoryStrdup (const char *str); XMLPUBFUN void * xmlMallocLoc (size_t size, const char *file, int line) LIBXML_ATTR_ALLOC_SIZE(1); XMLPUBFUN void * xmlReallocLoc (void *ptr, size_t size, const char *file, int line); XMLPUBFUN void * xmlMallocAtomicLoc (size_t size, const char *file, int line) LIBXML_ATTR_ALLOC_SIZE(1); XMLPUBFUN char * xmlMemStrdupLoc (const char *str, const char *file, int line); #ifdef DEBUG_MEMORY_LOCATION /** * xmlMalloc: * @size: number of bytes to allocate * * Wrapper for the malloc() function used in the XML library. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlMalloc(size) xmlMallocLoc((size), __FILE__, __LINE__) /** * xmlMallocAtomic: * @size: number of bytes to allocate * * Wrapper for the malloc() function used in the XML library for allocation * of block not containing pointers to other areas. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlMallocAtomic(size) xmlMallocAtomicLoc((size), __FILE__, __LINE__) /** * xmlRealloc: * @ptr: pointer to the existing allocated area * @size: number of bytes to allocate * * Wrapper for the realloc() function used in the XML library. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlRealloc(ptr, size) xmlReallocLoc((ptr), (size), __FILE__, __LINE__) /** * xmlMemStrdup: * @str: pointer to the existing string * * Wrapper for the strdup() function, xmlStrdup() is usually preferred. * * Returns the pointer to the allocated area or NULL in case of error. */ #define xmlMemStrdup(str) xmlMemStrdupLoc((str), __FILE__, __LINE__) #endif /* DEBUG_MEMORY_LOCATION */ #ifdef __cplusplus } #endif /* __cplusplus */ #ifndef __XML_GLOBALS_H #ifndef __XML_THREADS_H__ #include #include #endif #endif #endif /* __DEBUG_MEMORY_ALLOC__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlmodule.h ================================================ /* * Summary: dynamic module loading * Description: basic API for dynamic module loading, used by * libexslt added in 2.6.17 * * Copy: See Copyright for the status of this software. * * Author: Joel W. Reed */ #ifndef __XML_MODULE_H__ #define __XML_MODULE_H__ #include #ifdef LIBXML_MODULES_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlModulePtr: * * A handle to a dynamically loaded module */ typedef struct _xmlModule xmlModule; typedef xmlModule *xmlModulePtr; /** * xmlModuleOption: * * enumeration of options that can be passed down to xmlModuleOpen() */ typedef enum { XML_MODULE_LAZY = 1, /* lazy binding */ XML_MODULE_LOCAL= 2 /* local binding */ } xmlModuleOption; XMLPUBFUN xmlModulePtr xmlModuleOpen (const char *filename, int options); XMLPUBFUN int xmlModuleSymbol (xmlModulePtr module, const char* name, void **result); XMLPUBFUN int xmlModuleClose (xmlModulePtr module); XMLPUBFUN int xmlModuleFree (xmlModulePtr module); #ifdef __cplusplus } #endif #endif /* LIBXML_MODULES_ENABLED */ #endif /*__XML_MODULE_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlreader.h ================================================ /* * Summary: the XMLReader implementation * Description: API of the XML streaming API based on C# interfaces. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XMLREADER_H__ #define __XML_XMLREADER_H__ #include #include #include #ifdef LIBXML_SCHEMAS_ENABLED #include #include #endif #ifdef __cplusplus extern "C" { #endif /** * xmlParserSeverities: * * How severe an error callback is when the per-reader error callback API * is used. */ typedef enum { XML_PARSER_SEVERITY_VALIDITY_WARNING = 1, XML_PARSER_SEVERITY_VALIDITY_ERROR = 2, XML_PARSER_SEVERITY_WARNING = 3, XML_PARSER_SEVERITY_ERROR = 4 } xmlParserSeverities; #ifdef LIBXML_READER_ENABLED /** * xmlTextReaderMode: * * Internal state values for the reader. */ typedef enum { XML_TEXTREADER_MODE_INITIAL = 0, XML_TEXTREADER_MODE_INTERACTIVE = 1, XML_TEXTREADER_MODE_ERROR = 2, XML_TEXTREADER_MODE_EOF =3, XML_TEXTREADER_MODE_CLOSED = 4, XML_TEXTREADER_MODE_READING = 5 } xmlTextReaderMode; /** * xmlParserProperties: * * Some common options to use with xmlTextReaderSetParserProp, but it * is better to use xmlParserOption and the xmlReaderNewxxx and * xmlReaderForxxx APIs now. */ typedef enum { XML_PARSER_LOADDTD = 1, XML_PARSER_DEFAULTATTRS = 2, XML_PARSER_VALIDATE = 3, XML_PARSER_SUBST_ENTITIES = 4 } xmlParserProperties; /** * xmlReaderTypes: * * Predefined constants for the different types of nodes. */ typedef enum { XML_READER_TYPE_NONE = 0, XML_READER_TYPE_ELEMENT = 1, XML_READER_TYPE_ATTRIBUTE = 2, XML_READER_TYPE_TEXT = 3, XML_READER_TYPE_CDATA = 4, XML_READER_TYPE_ENTITY_REFERENCE = 5, XML_READER_TYPE_ENTITY = 6, XML_READER_TYPE_PROCESSING_INSTRUCTION = 7, XML_READER_TYPE_COMMENT = 8, XML_READER_TYPE_DOCUMENT = 9, XML_READER_TYPE_DOCUMENT_TYPE = 10, XML_READER_TYPE_DOCUMENT_FRAGMENT = 11, XML_READER_TYPE_NOTATION = 12, XML_READER_TYPE_WHITESPACE = 13, XML_READER_TYPE_SIGNIFICANT_WHITESPACE = 14, XML_READER_TYPE_END_ELEMENT = 15, XML_READER_TYPE_END_ENTITY = 16, XML_READER_TYPE_XML_DECLARATION = 17 } xmlReaderTypes; /** * xmlTextReader: * * Structure for an xmlReader context. */ typedef struct _xmlTextReader xmlTextReader; /** * xmlTextReaderPtr: * * Pointer to an xmlReader context. */ typedef xmlTextReader *xmlTextReaderPtr; /* * Constructors & Destructor */ XMLPUBFUN xmlTextReaderPtr xmlNewTextReader (xmlParserInputBufferPtr input, const char *URI); XMLPUBFUN xmlTextReaderPtr xmlNewTextReaderFilename(const char *URI); XMLPUBFUN void xmlFreeTextReader (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderSetup(xmlTextReaderPtr reader, xmlParserInputBufferPtr input, const char *URL, const char *encoding, int options); /* * Iterators */ XMLPUBFUN int xmlTextReaderRead (xmlTextReaderPtr reader); #ifdef LIBXML_WRITER_ENABLED XMLPUBFUN xmlChar * xmlTextReaderReadInnerXml(xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderReadOuterXml(xmlTextReaderPtr reader); #endif XMLPUBFUN xmlChar * xmlTextReaderReadString (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderReadAttributeValue(xmlTextReaderPtr reader); /* * Attributes of the node */ XMLPUBFUN int xmlTextReaderAttributeCount(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderDepth (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderHasAttributes(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderHasValue(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsDefault (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsEmptyElement(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNodeType (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderQuoteChar (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderReadState (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsNamespaceDecl(xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstBaseUri (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstLocalName (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstName (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstNamespaceUri(xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstPrefix (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstXmlLang (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstString (xmlTextReaderPtr reader, const xmlChar *str); XMLPUBFUN const xmlChar * xmlTextReaderConstValue (xmlTextReaderPtr reader); /* * use the Const version of the routine for * better performance and simpler code */ XMLPUBFUN xmlChar * xmlTextReaderBaseUri (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderLocalName (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderName (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderNamespaceUri(xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderPrefix (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderXmlLang (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderValue (xmlTextReaderPtr reader); /* * Methods of the XmlTextReader */ XMLPUBFUN int xmlTextReaderClose (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderGetAttributeNo (xmlTextReaderPtr reader, int no); XMLPUBFUN xmlChar * xmlTextReaderGetAttribute (xmlTextReaderPtr reader, const xmlChar *name); XMLPUBFUN xmlChar * xmlTextReaderGetAttributeNs (xmlTextReaderPtr reader, const xmlChar *localName, const xmlChar *namespaceURI); XMLPUBFUN xmlParserInputBufferPtr xmlTextReaderGetRemainder (xmlTextReaderPtr reader); XMLPUBFUN xmlChar * xmlTextReaderLookupNamespace(xmlTextReaderPtr reader, const xmlChar *prefix); XMLPUBFUN int xmlTextReaderMoveToAttributeNo(xmlTextReaderPtr reader, int no); XMLPUBFUN int xmlTextReaderMoveToAttribute(xmlTextReaderPtr reader, const xmlChar *name); XMLPUBFUN int xmlTextReaderMoveToAttributeNs(xmlTextReaderPtr reader, const xmlChar *localName, const xmlChar *namespaceURI); XMLPUBFUN int xmlTextReaderMoveToFirstAttribute(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderMoveToNextAttribute(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderMoveToElement (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNormalization (xmlTextReaderPtr reader); XMLPUBFUN const xmlChar * xmlTextReaderConstEncoding (xmlTextReaderPtr reader); /* * Extensions */ XMLPUBFUN int xmlTextReaderSetParserProp (xmlTextReaderPtr reader, int prop, int value); XMLPUBFUN int xmlTextReaderGetParserProp (xmlTextReaderPtr reader, int prop); XMLPUBFUN xmlNodePtr xmlTextReaderCurrentNode (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderGetParserLineNumber(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderGetParserColumnNumber(xmlTextReaderPtr reader); XMLPUBFUN xmlNodePtr xmlTextReaderPreserve (xmlTextReaderPtr reader); #ifdef LIBXML_PATTERN_ENABLED XMLPUBFUN int xmlTextReaderPreservePattern(xmlTextReaderPtr reader, const xmlChar *pattern, const xmlChar **namespaces); #endif /* LIBXML_PATTERN_ENABLED */ XMLPUBFUN xmlDocPtr xmlTextReaderCurrentDoc (xmlTextReaderPtr reader); XMLPUBFUN xmlNodePtr xmlTextReaderExpand (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNext (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderNextSibling (xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderIsValid (xmlTextReaderPtr reader); #ifdef LIBXML_SCHEMAS_ENABLED XMLPUBFUN int xmlTextReaderRelaxNGValidate(xmlTextReaderPtr reader, const char *rng); XMLPUBFUN int xmlTextReaderRelaxNGValidateCtxt(xmlTextReaderPtr reader, xmlRelaxNGValidCtxtPtr ctxt, int options); XMLPUBFUN int xmlTextReaderRelaxNGSetSchema(xmlTextReaderPtr reader, xmlRelaxNGPtr schema); XMLPUBFUN int xmlTextReaderSchemaValidate (xmlTextReaderPtr reader, const char *xsd); XMLPUBFUN int xmlTextReaderSchemaValidateCtxt(xmlTextReaderPtr reader, xmlSchemaValidCtxtPtr ctxt, int options); XMLPUBFUN int xmlTextReaderSetSchema (xmlTextReaderPtr reader, xmlSchemaPtr schema); #endif XMLPUBFUN const xmlChar * xmlTextReaderConstXmlVersion(xmlTextReaderPtr reader); XMLPUBFUN int xmlTextReaderStandalone (xmlTextReaderPtr reader); /* * Index lookup */ XMLPUBFUN long xmlTextReaderByteConsumed (xmlTextReaderPtr reader); /* * New more complete APIs for simpler creation and reuse of readers */ XMLPUBFUN xmlTextReaderPtr xmlReaderWalker (xmlDocPtr doc); XMLPUBFUN xmlTextReaderPtr xmlReaderForDoc (const xmlChar * cur, const char *URL, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForFile (const char *filename, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForMemory (const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForFd (int fd, const char *URL, const char *encoding, int options); XMLPUBFUN xmlTextReaderPtr xmlReaderForIO (xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewWalker (xmlTextReaderPtr reader, xmlDocPtr doc); XMLPUBFUN int xmlReaderNewDoc (xmlTextReaderPtr reader, const xmlChar * cur, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewFile (xmlTextReaderPtr reader, const char *filename, const char *encoding, int options); XMLPUBFUN int xmlReaderNewMemory (xmlTextReaderPtr reader, const char *buffer, int size, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewFd (xmlTextReaderPtr reader, int fd, const char *URL, const char *encoding, int options); XMLPUBFUN int xmlReaderNewIO (xmlTextReaderPtr reader, xmlInputReadCallback ioread, xmlInputCloseCallback ioclose, void *ioctx, const char *URL, const char *encoding, int options); /* * Error handling extensions */ typedef void * xmlTextReaderLocatorPtr; /** * xmlTextReaderErrorFunc: * @arg: the user argument * @msg: the message * @severity: the severity of the error * @locator: a locator indicating where the error occurred * * Signature of an error callback from a reader parser */ typedef void (*xmlTextReaderErrorFunc)(void *arg, const char *msg, xmlParserSeverities severity, xmlTextReaderLocatorPtr locator); XMLPUBFUN int xmlTextReaderLocatorLineNumber(xmlTextReaderLocatorPtr locator); XMLPUBFUN xmlChar * xmlTextReaderLocatorBaseURI (xmlTextReaderLocatorPtr locator); XMLPUBFUN void xmlTextReaderSetErrorHandler(xmlTextReaderPtr reader, xmlTextReaderErrorFunc f, void *arg); XMLPUBFUN void xmlTextReaderSetStructuredErrorHandler(xmlTextReaderPtr reader, xmlStructuredErrorFunc f, void *arg); XMLPUBFUN void xmlTextReaderGetErrorHandler(xmlTextReaderPtr reader, xmlTextReaderErrorFunc *f, void **arg); #endif /* LIBXML_READER_ENABLED */ #ifdef __cplusplus } #endif #endif /* __XML_XMLREADER_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlregexp.h ================================================ /* * Summary: regular expressions handling * Description: basic API for libxml regular expressions handling used * for XML Schemas and validation. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_REGEXP_H__ #define __XML_REGEXP_H__ #include #ifdef LIBXML_REGEXP_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlRegexpPtr: * * A libxml regular expression, they can actually be far more complex * thank the POSIX regex expressions. */ typedef struct _xmlRegexp xmlRegexp; typedef xmlRegexp *xmlRegexpPtr; /** * xmlRegExecCtxtPtr: * * A libxml progressive regular expression evaluation context */ typedef struct _xmlRegExecCtxt xmlRegExecCtxt; typedef xmlRegExecCtxt *xmlRegExecCtxtPtr; #ifdef __cplusplus } #endif #include #include #ifdef __cplusplus extern "C" { #endif /* * The POSIX like API */ XMLPUBFUN xmlRegexpPtr xmlRegexpCompile (const xmlChar *regexp); XMLPUBFUN void xmlRegFreeRegexp(xmlRegexpPtr regexp); XMLPUBFUN int xmlRegexpExec (xmlRegexpPtr comp, const xmlChar *value); XMLPUBFUN void xmlRegexpPrint (FILE *output, xmlRegexpPtr regexp); XMLPUBFUN int xmlRegexpIsDeterminist(xmlRegexpPtr comp); /** * xmlRegExecCallbacks: * @exec: the regular expression context * @token: the current token string * @transdata: transition data * @inputdata: input data * * Callback function when doing a transition in the automata */ typedef void (*xmlRegExecCallbacks) (xmlRegExecCtxtPtr exec, const xmlChar *token, void *transdata, void *inputdata); /* * The progressive API */ XMLPUBFUN xmlRegExecCtxtPtr xmlRegNewExecCtxt (xmlRegexpPtr comp, xmlRegExecCallbacks callback, void *data); XMLPUBFUN void xmlRegFreeExecCtxt (xmlRegExecCtxtPtr exec); XMLPUBFUN int xmlRegExecPushString(xmlRegExecCtxtPtr exec, const xmlChar *value, void *data); XMLPUBFUN int xmlRegExecPushString2(xmlRegExecCtxtPtr exec, const xmlChar *value, const xmlChar *value2, void *data); XMLPUBFUN int xmlRegExecNextValues(xmlRegExecCtxtPtr exec, int *nbval, int *nbneg, xmlChar **values, int *terminal); XMLPUBFUN int xmlRegExecErrInfo (xmlRegExecCtxtPtr exec, const xmlChar **string, int *nbval, int *nbneg, xmlChar **values, int *terminal); #ifdef LIBXML_EXPR_ENABLED /* * Formal regular expression handling * Its goal is to do some formal work on content models */ /* expressions are used within a context */ typedef struct _xmlExpCtxt xmlExpCtxt; typedef xmlExpCtxt *xmlExpCtxtPtr; XMLPUBFUN void xmlExpFreeCtxt (xmlExpCtxtPtr ctxt); XMLPUBFUN xmlExpCtxtPtr xmlExpNewCtxt (int maxNodes, xmlDictPtr dict); XMLPUBFUN int xmlExpCtxtNbNodes(xmlExpCtxtPtr ctxt); XMLPUBFUN int xmlExpCtxtNbCons(xmlExpCtxtPtr ctxt); /* Expressions are trees but the tree is opaque */ typedef struct _xmlExpNode xmlExpNode; typedef xmlExpNode *xmlExpNodePtr; typedef enum { XML_EXP_EMPTY = 0, XML_EXP_FORBID = 1, XML_EXP_ATOM = 2, XML_EXP_SEQ = 3, XML_EXP_OR = 4, XML_EXP_COUNT = 5 } xmlExpNodeType; /* * 2 core expressions shared by all for the empty language set * and for the set with just the empty token */ XMLPUBVAR xmlExpNodePtr forbiddenExp; XMLPUBVAR xmlExpNodePtr emptyExp; /* * Expressions are reference counted internally */ XMLPUBFUN void xmlExpFree (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr); XMLPUBFUN void xmlExpRef (xmlExpNodePtr expr); /* * constructors can be either manual or from a string */ XMLPUBFUN xmlExpNodePtr xmlExpParse (xmlExpCtxtPtr ctxt, const char *expr); XMLPUBFUN xmlExpNodePtr xmlExpNewAtom (xmlExpCtxtPtr ctxt, const xmlChar *name, int len); XMLPUBFUN xmlExpNodePtr xmlExpNewOr (xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right); XMLPUBFUN xmlExpNodePtr xmlExpNewSeq (xmlExpCtxtPtr ctxt, xmlExpNodePtr left, xmlExpNodePtr right); XMLPUBFUN xmlExpNodePtr xmlExpNewRange (xmlExpCtxtPtr ctxt, xmlExpNodePtr subset, int min, int max); /* * The really interesting APIs */ XMLPUBFUN int xmlExpIsNillable(xmlExpNodePtr expr); XMLPUBFUN int xmlExpMaxToken (xmlExpNodePtr expr); XMLPUBFUN int xmlExpGetLanguage(xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, const xmlChar**langList, int len); XMLPUBFUN int xmlExpGetStart (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, const xmlChar**tokList, int len); XMLPUBFUN xmlExpNodePtr xmlExpStringDerive(xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, const xmlChar *str, int len); XMLPUBFUN xmlExpNodePtr xmlExpExpDerive (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, xmlExpNodePtr sub); XMLPUBFUN int xmlExpSubsume (xmlExpCtxtPtr ctxt, xmlExpNodePtr expr, xmlExpNodePtr sub); XMLPUBFUN void xmlExpDump (xmlBufferPtr buf, xmlExpNodePtr expr); #endif /* LIBXML_EXPR_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_REGEXP_ENABLED */ #endif /*__XML_REGEXP_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlsave.h ================================================ /* * Summary: the XML document serializer * Description: API to save document or subtree of document * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XMLSAVE_H__ #define __XML_XMLSAVE_H__ #include #include #include #include #ifdef LIBXML_OUTPUT_ENABLED #ifdef __cplusplus extern "C" { #endif /** * xmlSaveOption: * * This is the set of XML save options that can be passed down * to the xmlSaveToFd() and similar calls. */ typedef enum { XML_SAVE_FORMAT = 1<<0, /* format save output */ XML_SAVE_NO_DECL = 1<<1, /* drop the xml declaration */ XML_SAVE_NO_EMPTY = 1<<2, /* no empty tags */ XML_SAVE_NO_XHTML = 1<<3, /* disable XHTML1 specific rules */ XML_SAVE_XHTML = 1<<4, /* force XHTML1 specific rules */ XML_SAVE_AS_XML = 1<<5, /* force XML serialization on HTML doc */ XML_SAVE_AS_HTML = 1<<6, /* force HTML serialization on XML doc */ XML_SAVE_WSNONSIG = 1<<7 /* format with non-significant whitespace */ } xmlSaveOption; typedef struct _xmlSaveCtxt xmlSaveCtxt; typedef xmlSaveCtxt *xmlSaveCtxtPtr; XMLPUBFUN xmlSaveCtxtPtr xmlSaveToFd (int fd, const char *encoding, int options); XMLPUBFUN xmlSaveCtxtPtr xmlSaveToFilename (const char *filename, const char *encoding, int options); XMLPUBFUN xmlSaveCtxtPtr xmlSaveToBuffer (xmlBufferPtr buffer, const char *encoding, int options); XMLPUBFUN xmlSaveCtxtPtr xmlSaveToIO (xmlOutputWriteCallback iowrite, xmlOutputCloseCallback ioclose, void *ioctx, const char *encoding, int options); XMLPUBFUN long xmlSaveDoc (xmlSaveCtxtPtr ctxt, xmlDocPtr doc); XMLPUBFUN long xmlSaveTree (xmlSaveCtxtPtr ctxt, xmlNodePtr node); XMLPUBFUN int xmlSaveFlush (xmlSaveCtxtPtr ctxt); XMLPUBFUN int xmlSaveClose (xmlSaveCtxtPtr ctxt); XMLPUBFUN int xmlSaveSetEscape (xmlSaveCtxtPtr ctxt, xmlCharEncodingOutputFunc escape); XMLPUBFUN int xmlSaveSetAttrEscape (xmlSaveCtxtPtr ctxt, xmlCharEncodingOutputFunc escape); #ifdef __cplusplus } #endif #endif /* LIBXML_OUTPUT_ENABLED */ #endif /* __XML_XMLSAVE_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlschemas.h ================================================ /* * Summary: incomplete XML Schemas structure implementation * Description: interface to the XML Schemas handling and schema validity * checking, it is incomplete right now. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMA_H__ #define __XML_SCHEMA_H__ #include #ifdef LIBXML_SCHEMAS_ENABLED #include #ifdef __cplusplus extern "C" { #endif /** * This error codes are obsolete; not used any more. */ typedef enum { XML_SCHEMAS_ERR_OK = 0, XML_SCHEMAS_ERR_NOROOT = 1, XML_SCHEMAS_ERR_UNDECLAREDELEM, XML_SCHEMAS_ERR_NOTTOPLEVEL, XML_SCHEMAS_ERR_MISSING, XML_SCHEMAS_ERR_WRONGELEM, XML_SCHEMAS_ERR_NOTYPE, XML_SCHEMAS_ERR_NOROLLBACK, XML_SCHEMAS_ERR_ISABSTRACT, XML_SCHEMAS_ERR_NOTEMPTY, XML_SCHEMAS_ERR_ELEMCONT, XML_SCHEMAS_ERR_HAVEDEFAULT, XML_SCHEMAS_ERR_NOTNILLABLE, XML_SCHEMAS_ERR_EXTRACONTENT, XML_SCHEMAS_ERR_INVALIDATTR, XML_SCHEMAS_ERR_INVALIDELEM, XML_SCHEMAS_ERR_NOTDETERMINIST, XML_SCHEMAS_ERR_CONSTRUCT, XML_SCHEMAS_ERR_INTERNAL, XML_SCHEMAS_ERR_NOTSIMPLE, XML_SCHEMAS_ERR_ATTRUNKNOWN, XML_SCHEMAS_ERR_ATTRINVALID, XML_SCHEMAS_ERR_VALUE, XML_SCHEMAS_ERR_FACET, XML_SCHEMAS_ERR_, XML_SCHEMAS_ERR_XXX } xmlSchemaValidError; /* * ATTENTION: Change xmlSchemaSetValidOptions's check * for invalid values, if adding to the validation * options below. */ /** * xmlSchemaValidOption: * * This is the set of XML Schema validation options. */ typedef enum { XML_SCHEMA_VAL_VC_I_CREATE = 1<<0 /* Default/fixed: create an attribute node * or an element's text node on the instance. */ } xmlSchemaValidOption; /* XML_SCHEMA_VAL_XSI_ASSEMBLE = 1<<1, * assemble schemata using * xsi:schemaLocation and * xsi:noNamespaceSchemaLocation */ /** * The schemas related types are kept internal */ typedef struct _xmlSchema xmlSchema; typedef xmlSchema *xmlSchemaPtr; /** * xmlSchemaValidityErrorFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of an error callback from an XSD validation */ typedef void (*xmlSchemaValidityErrorFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * xmlSchemaValidityWarningFunc: * @ctx: the validation context * @msg: the message * @...: extra arguments * * Signature of a warning callback from an XSD validation */ typedef void (*xmlSchemaValidityWarningFunc) (void *ctx, const char *msg, ...) LIBXML_ATTR_FORMAT(2,3); /** * A schemas validation context */ typedef struct _xmlSchemaParserCtxt xmlSchemaParserCtxt; typedef xmlSchemaParserCtxt *xmlSchemaParserCtxtPtr; typedef struct _xmlSchemaValidCtxt xmlSchemaValidCtxt; typedef xmlSchemaValidCtxt *xmlSchemaValidCtxtPtr; /** * xmlSchemaValidityLocatorFunc: * @ctx: user provided context * @file: returned file information * @line: returned line information * * A schemas validation locator, a callback called by the validator. * This is used when file or node information are not available * to find out what file and line number are affected * * Returns: 0 in case of success and -1 in case of error */ typedef int (*xmlSchemaValidityLocatorFunc) (void *ctx, const char **file, unsigned long *line); /* * Interfaces for parsing. */ XMLPUBFUN xmlSchemaParserCtxtPtr xmlSchemaNewParserCtxt (const char *URL); XMLPUBFUN xmlSchemaParserCtxtPtr xmlSchemaNewMemParserCtxt (const char *buffer, int size); XMLPUBFUN xmlSchemaParserCtxtPtr xmlSchemaNewDocParserCtxt (xmlDocPtr doc); XMLPUBFUN void xmlSchemaFreeParserCtxt (xmlSchemaParserCtxtPtr ctxt); XMLPUBFUN void xmlSchemaSetParserErrors (xmlSchemaParserCtxtPtr ctxt, xmlSchemaValidityErrorFunc err, xmlSchemaValidityWarningFunc warn, void *ctx); XMLPUBFUN void xmlSchemaSetParserStructuredErrors(xmlSchemaParserCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN int xmlSchemaGetParserErrors(xmlSchemaParserCtxtPtr ctxt, xmlSchemaValidityErrorFunc * err, xmlSchemaValidityWarningFunc * warn, void **ctx); XMLPUBFUN int xmlSchemaIsValid (xmlSchemaValidCtxtPtr ctxt); XMLPUBFUN xmlSchemaPtr xmlSchemaParse (xmlSchemaParserCtxtPtr ctxt); XMLPUBFUN void xmlSchemaFree (xmlSchemaPtr schema); #ifdef LIBXML_OUTPUT_ENABLED XMLPUBFUN void xmlSchemaDump (FILE *output, xmlSchemaPtr schema); #endif /* LIBXML_OUTPUT_ENABLED */ /* * Interfaces for validating */ XMLPUBFUN void xmlSchemaSetValidErrors (xmlSchemaValidCtxtPtr ctxt, xmlSchemaValidityErrorFunc err, xmlSchemaValidityWarningFunc warn, void *ctx); XMLPUBFUN void xmlSchemaSetValidStructuredErrors(xmlSchemaValidCtxtPtr ctxt, xmlStructuredErrorFunc serror, void *ctx); XMLPUBFUN int xmlSchemaGetValidErrors (xmlSchemaValidCtxtPtr ctxt, xmlSchemaValidityErrorFunc *err, xmlSchemaValidityWarningFunc *warn, void **ctx); XMLPUBFUN int xmlSchemaSetValidOptions (xmlSchemaValidCtxtPtr ctxt, int options); XMLPUBFUN void xmlSchemaValidateSetFilename(xmlSchemaValidCtxtPtr vctxt, const char *filename); XMLPUBFUN int xmlSchemaValidCtxtGetOptions(xmlSchemaValidCtxtPtr ctxt); XMLPUBFUN xmlSchemaValidCtxtPtr xmlSchemaNewValidCtxt (xmlSchemaPtr schema); XMLPUBFUN void xmlSchemaFreeValidCtxt (xmlSchemaValidCtxtPtr ctxt); XMLPUBFUN int xmlSchemaValidateDoc (xmlSchemaValidCtxtPtr ctxt, xmlDocPtr instance); XMLPUBFUN int xmlSchemaValidateOneElement (xmlSchemaValidCtxtPtr ctxt, xmlNodePtr elem); XMLPUBFUN int xmlSchemaValidateStream (xmlSchemaValidCtxtPtr ctxt, xmlParserInputBufferPtr input, xmlCharEncoding enc, xmlSAXHandlerPtr sax, void *user_data); XMLPUBFUN int xmlSchemaValidateFile (xmlSchemaValidCtxtPtr ctxt, const char * filename, int options); XMLPUBFUN xmlParserCtxtPtr xmlSchemaValidCtxtGetParserCtxt(xmlSchemaValidCtxtPtr ctxt); /* * Interface to insert Schemas SAX validation in a SAX stream */ typedef struct _xmlSchemaSAXPlug xmlSchemaSAXPlugStruct; typedef xmlSchemaSAXPlugStruct *xmlSchemaSAXPlugPtr; XMLPUBFUN xmlSchemaSAXPlugPtr xmlSchemaSAXPlug (xmlSchemaValidCtxtPtr ctxt, xmlSAXHandlerPtr *sax, void **user_data); XMLPUBFUN int xmlSchemaSAXUnplug (xmlSchemaSAXPlugPtr plug); XMLPUBFUN void xmlSchemaValidateSetLocator (xmlSchemaValidCtxtPtr vctxt, xmlSchemaValidityLocatorFunc f, void *ctxt); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_SCHEMA_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlschemastypes.h ================================================ /* * Summary: implementation of XML Schema Datatypes * Description: module providing the XML Schema Datatypes implementation * both definition and validity checking * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_SCHEMA_TYPES_H__ #define __XML_SCHEMA_TYPES_H__ #include #ifdef LIBXML_SCHEMAS_ENABLED #include #include #ifdef __cplusplus extern "C" { #endif typedef enum { XML_SCHEMA_WHITESPACE_UNKNOWN = 0, XML_SCHEMA_WHITESPACE_PRESERVE = 1, XML_SCHEMA_WHITESPACE_REPLACE = 2, XML_SCHEMA_WHITESPACE_COLLAPSE = 3 } xmlSchemaWhitespaceValueType; XMLPUBFUN int xmlSchemaInitTypes (void); XML_DEPRECATED XMLPUBFUN void xmlSchemaCleanupTypes (void); XMLPUBFUN xmlSchemaTypePtr xmlSchemaGetPredefinedType (const xmlChar *name, const xmlChar *ns); XMLPUBFUN int xmlSchemaValidatePredefinedType (xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val); XMLPUBFUN int xmlSchemaValPredefTypeNode (xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val, xmlNodePtr node); XMLPUBFUN int xmlSchemaValidateFacet (xmlSchemaTypePtr base, xmlSchemaFacetPtr facet, const xmlChar *value, xmlSchemaValPtr val); XMLPUBFUN int xmlSchemaValidateFacetWhtsp (xmlSchemaFacetPtr facet, xmlSchemaWhitespaceValueType fws, xmlSchemaValType valType, const xmlChar *value, xmlSchemaValPtr val, xmlSchemaWhitespaceValueType ws); XMLPUBFUN void xmlSchemaFreeValue (xmlSchemaValPtr val); XMLPUBFUN xmlSchemaFacetPtr xmlSchemaNewFacet (void); XMLPUBFUN int xmlSchemaCheckFacet (xmlSchemaFacetPtr facet, xmlSchemaTypePtr typeDecl, xmlSchemaParserCtxtPtr ctxt, const xmlChar *name); XMLPUBFUN void xmlSchemaFreeFacet (xmlSchemaFacetPtr facet); XMLPUBFUN int xmlSchemaCompareValues (xmlSchemaValPtr x, xmlSchemaValPtr y); XMLPUBFUN xmlSchemaTypePtr xmlSchemaGetBuiltInListSimpleTypeItemType (xmlSchemaTypePtr type); XMLPUBFUN int xmlSchemaValidateListSimpleTypeFacet (xmlSchemaFacetPtr facet, const xmlChar *value, unsigned long actualLen, unsigned long *expectedLen); XMLPUBFUN xmlSchemaTypePtr xmlSchemaGetBuiltInType (xmlSchemaValType type); XMLPUBFUN int xmlSchemaIsBuiltInTypeFacet (xmlSchemaTypePtr type, int facetType); XMLPUBFUN xmlChar * xmlSchemaCollapseString (const xmlChar *value); XMLPUBFUN xmlChar * xmlSchemaWhiteSpaceReplace (const xmlChar *value); XMLPUBFUN unsigned long xmlSchemaGetFacetValueAsULong (xmlSchemaFacetPtr facet); XMLPUBFUN int xmlSchemaValidateLengthFacet (xmlSchemaTypePtr type, xmlSchemaFacetPtr facet, const xmlChar *value, xmlSchemaValPtr val, unsigned long *length); XMLPUBFUN int xmlSchemaValidateLengthFacetWhtsp(xmlSchemaFacetPtr facet, xmlSchemaValType valType, const xmlChar *value, xmlSchemaValPtr val, unsigned long *length, xmlSchemaWhitespaceValueType ws); XMLPUBFUN int xmlSchemaValPredefTypeNodeNoNorm(xmlSchemaTypePtr type, const xmlChar *value, xmlSchemaValPtr *val, xmlNodePtr node); XMLPUBFUN int xmlSchemaGetCanonValue (xmlSchemaValPtr val, const xmlChar **retValue); XMLPUBFUN int xmlSchemaGetCanonValueWhtsp (xmlSchemaValPtr val, const xmlChar **retValue, xmlSchemaWhitespaceValueType ws); XMLPUBFUN int xmlSchemaValueAppend (xmlSchemaValPtr prev, xmlSchemaValPtr cur); XMLPUBFUN xmlSchemaValPtr xmlSchemaValueGetNext (xmlSchemaValPtr cur); XMLPUBFUN const xmlChar * xmlSchemaValueGetAsString (xmlSchemaValPtr val); XMLPUBFUN int xmlSchemaValueGetAsBoolean (xmlSchemaValPtr val); XMLPUBFUN xmlSchemaValPtr xmlSchemaNewStringValue (xmlSchemaValType type, const xmlChar *value); XMLPUBFUN xmlSchemaValPtr xmlSchemaNewNOTATIONValue (const xmlChar *name, const xmlChar *ns); XMLPUBFUN xmlSchemaValPtr xmlSchemaNewQNameValue (const xmlChar *namespaceName, const xmlChar *localName); XMLPUBFUN int xmlSchemaCompareValuesWhtsp (xmlSchemaValPtr x, xmlSchemaWhitespaceValueType xws, xmlSchemaValPtr y, xmlSchemaWhitespaceValueType yws); XMLPUBFUN xmlSchemaValPtr xmlSchemaCopyValue (xmlSchemaValPtr val); XMLPUBFUN xmlSchemaValType xmlSchemaGetValType (xmlSchemaValPtr val); #ifdef __cplusplus } #endif #endif /* LIBXML_SCHEMAS_ENABLED */ #endif /* __XML_SCHEMA_TYPES_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlstring.h ================================================ /* * Summary: set of routines to process strings * Description: type and interfaces needed for the internal string handling * of the library, especially UTF8 processing. * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_STRING_H__ #define __XML_STRING_H__ #include #include #ifdef __cplusplus extern "C" { #endif /** * xmlChar: * * This is a basic byte in an UTF-8 encoded string. * It's unsigned allowing to pinpoint case where char * are assigned * to xmlChar * (possibly making serialization back impossible). */ typedef unsigned char xmlChar; /** * BAD_CAST: * * Macro to cast a string to an xmlChar * when one know its safe. */ #define BAD_CAST (xmlChar *) /* * xmlChar handling */ XMLPUBFUN xmlChar * xmlStrdup (const xmlChar *cur); XMLPUBFUN xmlChar * xmlStrndup (const xmlChar *cur, int len); XMLPUBFUN xmlChar * xmlCharStrndup (const char *cur, int len); XMLPUBFUN xmlChar * xmlCharStrdup (const char *cur); XMLPUBFUN xmlChar * xmlStrsub (const xmlChar *str, int start, int len); XMLPUBFUN const xmlChar * xmlStrchr (const xmlChar *str, xmlChar val); XMLPUBFUN const xmlChar * xmlStrstr (const xmlChar *str, const xmlChar *val); XMLPUBFUN const xmlChar * xmlStrcasestr (const xmlChar *str, const xmlChar *val); XMLPUBFUN int xmlStrcmp (const xmlChar *str1, const xmlChar *str2); XMLPUBFUN int xmlStrncmp (const xmlChar *str1, const xmlChar *str2, int len); XMLPUBFUN int xmlStrcasecmp (const xmlChar *str1, const xmlChar *str2); XMLPUBFUN int xmlStrncasecmp (const xmlChar *str1, const xmlChar *str2, int len); XMLPUBFUN int xmlStrEqual (const xmlChar *str1, const xmlChar *str2); XMLPUBFUN int xmlStrQEqual (const xmlChar *pref, const xmlChar *name, const xmlChar *str); XMLPUBFUN int xmlStrlen (const xmlChar *str); XMLPUBFUN xmlChar * xmlStrcat (xmlChar *cur, const xmlChar *add); XMLPUBFUN xmlChar * xmlStrncat (xmlChar *cur, const xmlChar *add, int len); XMLPUBFUN xmlChar * xmlStrncatNew (const xmlChar *str1, const xmlChar *str2, int len); XMLPUBFUN int xmlStrPrintf (xmlChar *buf, int len, const char *msg, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlStrVPrintf (xmlChar *buf, int len, const char *msg, va_list ap) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlGetUTF8Char (const unsigned char *utf, int *len); XMLPUBFUN int xmlCheckUTF8 (const unsigned char *utf); XMLPUBFUN int xmlUTF8Strsize (const xmlChar *utf, int len); XMLPUBFUN xmlChar * xmlUTF8Strndup (const xmlChar *utf, int len); XMLPUBFUN const xmlChar * xmlUTF8Strpos (const xmlChar *utf, int pos); XMLPUBFUN int xmlUTF8Strloc (const xmlChar *utf, const xmlChar *utfchar); XMLPUBFUN xmlChar * xmlUTF8Strsub (const xmlChar *utf, int start, int len); XMLPUBFUN int xmlUTF8Strlen (const xmlChar *utf); XMLPUBFUN int xmlUTF8Size (const xmlChar *utf); XMLPUBFUN int xmlUTF8Charcmp (const xmlChar *utf1, const xmlChar *utf2); #ifdef __cplusplus } #endif #endif /* __XML_STRING_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlunicode.h ================================================ /* * Summary: Unicode character APIs * Description: API for the Unicode character APIs * * This file is automatically generated from the * UCS description files of the Unicode Character Database * http://www.unicode.org/Public/4.0-Update1/UCD-4.0.1.html * using the genUnicode.py Python script. * * Generation date: Mon Mar 27 11:09:52 2006 * Sources: Blocks-4.0.1.txt UnicodeData-4.0.1.txt * Author: Daniel Veillard */ #ifndef __XML_UNICODE_H__ #define __XML_UNICODE_H__ #include #ifdef LIBXML_UNICODE_ENABLED #ifdef __cplusplus extern "C" { #endif XMLPUBFUN int xmlUCSIsAegeanNumbers (int code); XMLPUBFUN int xmlUCSIsAlphabeticPresentationForms (int code); XMLPUBFUN int xmlUCSIsArabic (int code); XMLPUBFUN int xmlUCSIsArabicPresentationFormsA (int code); XMLPUBFUN int xmlUCSIsArabicPresentationFormsB (int code); XMLPUBFUN int xmlUCSIsArmenian (int code); XMLPUBFUN int xmlUCSIsArrows (int code); XMLPUBFUN int xmlUCSIsBasicLatin (int code); XMLPUBFUN int xmlUCSIsBengali (int code); XMLPUBFUN int xmlUCSIsBlockElements (int code); XMLPUBFUN int xmlUCSIsBopomofo (int code); XMLPUBFUN int xmlUCSIsBopomofoExtended (int code); XMLPUBFUN int xmlUCSIsBoxDrawing (int code); XMLPUBFUN int xmlUCSIsBraillePatterns (int code); XMLPUBFUN int xmlUCSIsBuhid (int code); XMLPUBFUN int xmlUCSIsByzantineMusicalSymbols (int code); XMLPUBFUN int xmlUCSIsCJKCompatibility (int code); XMLPUBFUN int xmlUCSIsCJKCompatibilityForms (int code); XMLPUBFUN int xmlUCSIsCJKCompatibilityIdeographs (int code); XMLPUBFUN int xmlUCSIsCJKCompatibilityIdeographsSupplement (int code); XMLPUBFUN int xmlUCSIsCJKRadicalsSupplement (int code); XMLPUBFUN int xmlUCSIsCJKSymbolsandPunctuation (int code); XMLPUBFUN int xmlUCSIsCJKUnifiedIdeographs (int code); XMLPUBFUN int xmlUCSIsCJKUnifiedIdeographsExtensionA (int code); XMLPUBFUN int xmlUCSIsCJKUnifiedIdeographsExtensionB (int code); XMLPUBFUN int xmlUCSIsCherokee (int code); XMLPUBFUN int xmlUCSIsCombiningDiacriticalMarks (int code); XMLPUBFUN int xmlUCSIsCombiningDiacriticalMarksforSymbols (int code); XMLPUBFUN int xmlUCSIsCombiningHalfMarks (int code); XMLPUBFUN int xmlUCSIsCombiningMarksforSymbols (int code); XMLPUBFUN int xmlUCSIsControlPictures (int code); XMLPUBFUN int xmlUCSIsCurrencySymbols (int code); XMLPUBFUN int xmlUCSIsCypriotSyllabary (int code); XMLPUBFUN int xmlUCSIsCyrillic (int code); XMLPUBFUN int xmlUCSIsCyrillicSupplement (int code); XMLPUBFUN int xmlUCSIsDeseret (int code); XMLPUBFUN int xmlUCSIsDevanagari (int code); XMLPUBFUN int xmlUCSIsDingbats (int code); XMLPUBFUN int xmlUCSIsEnclosedAlphanumerics (int code); XMLPUBFUN int xmlUCSIsEnclosedCJKLettersandMonths (int code); XMLPUBFUN int xmlUCSIsEthiopic (int code); XMLPUBFUN int xmlUCSIsGeneralPunctuation (int code); XMLPUBFUN int xmlUCSIsGeometricShapes (int code); XMLPUBFUN int xmlUCSIsGeorgian (int code); XMLPUBFUN int xmlUCSIsGothic (int code); XMLPUBFUN int xmlUCSIsGreek (int code); XMLPUBFUN int xmlUCSIsGreekExtended (int code); XMLPUBFUN int xmlUCSIsGreekandCoptic (int code); XMLPUBFUN int xmlUCSIsGujarati (int code); XMLPUBFUN int xmlUCSIsGurmukhi (int code); XMLPUBFUN int xmlUCSIsHalfwidthandFullwidthForms (int code); XMLPUBFUN int xmlUCSIsHangulCompatibilityJamo (int code); XMLPUBFUN int xmlUCSIsHangulJamo (int code); XMLPUBFUN int xmlUCSIsHangulSyllables (int code); XMLPUBFUN int xmlUCSIsHanunoo (int code); XMLPUBFUN int xmlUCSIsHebrew (int code); XMLPUBFUN int xmlUCSIsHighPrivateUseSurrogates (int code); XMLPUBFUN int xmlUCSIsHighSurrogates (int code); XMLPUBFUN int xmlUCSIsHiragana (int code); XMLPUBFUN int xmlUCSIsIPAExtensions (int code); XMLPUBFUN int xmlUCSIsIdeographicDescriptionCharacters (int code); XMLPUBFUN int xmlUCSIsKanbun (int code); XMLPUBFUN int xmlUCSIsKangxiRadicals (int code); XMLPUBFUN int xmlUCSIsKannada (int code); XMLPUBFUN int xmlUCSIsKatakana (int code); XMLPUBFUN int xmlUCSIsKatakanaPhoneticExtensions (int code); XMLPUBFUN int xmlUCSIsKhmer (int code); XMLPUBFUN int xmlUCSIsKhmerSymbols (int code); XMLPUBFUN int xmlUCSIsLao (int code); XMLPUBFUN int xmlUCSIsLatin1Supplement (int code); XMLPUBFUN int xmlUCSIsLatinExtendedA (int code); XMLPUBFUN int xmlUCSIsLatinExtendedB (int code); XMLPUBFUN int xmlUCSIsLatinExtendedAdditional (int code); XMLPUBFUN int xmlUCSIsLetterlikeSymbols (int code); XMLPUBFUN int xmlUCSIsLimbu (int code); XMLPUBFUN int xmlUCSIsLinearBIdeograms (int code); XMLPUBFUN int xmlUCSIsLinearBSyllabary (int code); XMLPUBFUN int xmlUCSIsLowSurrogates (int code); XMLPUBFUN int xmlUCSIsMalayalam (int code); XMLPUBFUN int xmlUCSIsMathematicalAlphanumericSymbols (int code); XMLPUBFUN int xmlUCSIsMathematicalOperators (int code); XMLPUBFUN int xmlUCSIsMiscellaneousMathematicalSymbolsA (int code); XMLPUBFUN int xmlUCSIsMiscellaneousMathematicalSymbolsB (int code); XMLPUBFUN int xmlUCSIsMiscellaneousSymbols (int code); XMLPUBFUN int xmlUCSIsMiscellaneousSymbolsandArrows (int code); XMLPUBFUN int xmlUCSIsMiscellaneousTechnical (int code); XMLPUBFUN int xmlUCSIsMongolian (int code); XMLPUBFUN int xmlUCSIsMusicalSymbols (int code); XMLPUBFUN int xmlUCSIsMyanmar (int code); XMLPUBFUN int xmlUCSIsNumberForms (int code); XMLPUBFUN int xmlUCSIsOgham (int code); XMLPUBFUN int xmlUCSIsOldItalic (int code); XMLPUBFUN int xmlUCSIsOpticalCharacterRecognition (int code); XMLPUBFUN int xmlUCSIsOriya (int code); XMLPUBFUN int xmlUCSIsOsmanya (int code); XMLPUBFUN int xmlUCSIsPhoneticExtensions (int code); XMLPUBFUN int xmlUCSIsPrivateUse (int code); XMLPUBFUN int xmlUCSIsPrivateUseArea (int code); XMLPUBFUN int xmlUCSIsRunic (int code); XMLPUBFUN int xmlUCSIsShavian (int code); XMLPUBFUN int xmlUCSIsSinhala (int code); XMLPUBFUN int xmlUCSIsSmallFormVariants (int code); XMLPUBFUN int xmlUCSIsSpacingModifierLetters (int code); XMLPUBFUN int xmlUCSIsSpecials (int code); XMLPUBFUN int xmlUCSIsSuperscriptsandSubscripts (int code); XMLPUBFUN int xmlUCSIsSupplementalArrowsA (int code); XMLPUBFUN int xmlUCSIsSupplementalArrowsB (int code); XMLPUBFUN int xmlUCSIsSupplementalMathematicalOperators (int code); XMLPUBFUN int xmlUCSIsSupplementaryPrivateUseAreaA (int code); XMLPUBFUN int xmlUCSIsSupplementaryPrivateUseAreaB (int code); XMLPUBFUN int xmlUCSIsSyriac (int code); XMLPUBFUN int xmlUCSIsTagalog (int code); XMLPUBFUN int xmlUCSIsTagbanwa (int code); XMLPUBFUN int xmlUCSIsTags (int code); XMLPUBFUN int xmlUCSIsTaiLe (int code); XMLPUBFUN int xmlUCSIsTaiXuanJingSymbols (int code); XMLPUBFUN int xmlUCSIsTamil (int code); XMLPUBFUN int xmlUCSIsTelugu (int code); XMLPUBFUN int xmlUCSIsThaana (int code); XMLPUBFUN int xmlUCSIsThai (int code); XMLPUBFUN int xmlUCSIsTibetan (int code); XMLPUBFUN int xmlUCSIsUgaritic (int code); XMLPUBFUN int xmlUCSIsUnifiedCanadianAboriginalSyllabics (int code); XMLPUBFUN int xmlUCSIsVariationSelectors (int code); XMLPUBFUN int xmlUCSIsVariationSelectorsSupplement (int code); XMLPUBFUN int xmlUCSIsYiRadicals (int code); XMLPUBFUN int xmlUCSIsYiSyllables (int code); XMLPUBFUN int xmlUCSIsYijingHexagramSymbols (int code); XMLPUBFUN int xmlUCSIsBlock (int code, const char *block); XMLPUBFUN int xmlUCSIsCatC (int code); XMLPUBFUN int xmlUCSIsCatCc (int code); XMLPUBFUN int xmlUCSIsCatCf (int code); XMLPUBFUN int xmlUCSIsCatCo (int code); XMLPUBFUN int xmlUCSIsCatCs (int code); XMLPUBFUN int xmlUCSIsCatL (int code); XMLPUBFUN int xmlUCSIsCatLl (int code); XMLPUBFUN int xmlUCSIsCatLm (int code); XMLPUBFUN int xmlUCSIsCatLo (int code); XMLPUBFUN int xmlUCSIsCatLt (int code); XMLPUBFUN int xmlUCSIsCatLu (int code); XMLPUBFUN int xmlUCSIsCatM (int code); XMLPUBFUN int xmlUCSIsCatMc (int code); XMLPUBFUN int xmlUCSIsCatMe (int code); XMLPUBFUN int xmlUCSIsCatMn (int code); XMLPUBFUN int xmlUCSIsCatN (int code); XMLPUBFUN int xmlUCSIsCatNd (int code); XMLPUBFUN int xmlUCSIsCatNl (int code); XMLPUBFUN int xmlUCSIsCatNo (int code); XMLPUBFUN int xmlUCSIsCatP (int code); XMLPUBFUN int xmlUCSIsCatPc (int code); XMLPUBFUN int xmlUCSIsCatPd (int code); XMLPUBFUN int xmlUCSIsCatPe (int code); XMLPUBFUN int xmlUCSIsCatPf (int code); XMLPUBFUN int xmlUCSIsCatPi (int code); XMLPUBFUN int xmlUCSIsCatPo (int code); XMLPUBFUN int xmlUCSIsCatPs (int code); XMLPUBFUN int xmlUCSIsCatS (int code); XMLPUBFUN int xmlUCSIsCatSc (int code); XMLPUBFUN int xmlUCSIsCatSk (int code); XMLPUBFUN int xmlUCSIsCatSm (int code); XMLPUBFUN int xmlUCSIsCatSo (int code); XMLPUBFUN int xmlUCSIsCatZ (int code); XMLPUBFUN int xmlUCSIsCatZl (int code); XMLPUBFUN int xmlUCSIsCatZp (int code); XMLPUBFUN int xmlUCSIsCatZs (int code); XMLPUBFUN int xmlUCSIsCat (int code, const char *cat); #ifdef __cplusplus } #endif #endif /* LIBXML_UNICODE_ENABLED */ #endif /* __XML_UNICODE_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlversion.h ================================================ /* * Summary: compile-time version information * Description: compile-time version information for the XML library * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_VERSION_H__ #define __XML_VERSION_H__ #include #ifdef __cplusplus extern "C" { #endif /* * use those to be sure nothing nasty will happen if * your library and includes mismatch */ #ifndef LIBXML2_COMPILING_MSCCDEF XMLPUBFUN void xmlCheckVersion(int version); #endif /* LIBXML2_COMPILING_MSCCDEF */ /** * LIBXML_DOTTED_VERSION: * * the version string like "1.2.3" */ #define LIBXML_DOTTED_VERSION "2.11.5" /** * LIBXML_VERSION: * * the version number: 1.2.3 value is 10203 */ #define LIBXML_VERSION 21105 /** * LIBXML_VERSION_STRING: * * the version number string, 1.2.3 value is "10203" */ #define LIBXML_VERSION_STRING "21105" /** * LIBXML_VERSION_EXTRA: * * extra version information, used to show a git commit description */ #define LIBXML_VERSION_EXTRA "" /** * LIBXML_TEST_VERSION: * * Macro to check that the libxml version in use is compatible with * the version the software has been compiled against */ #define LIBXML_TEST_VERSION xmlCheckVersion(21105); #ifndef VMS #if 0 /** * WITH_TRIO: * * defined if the trio support need to be configured in */ #define WITH_TRIO #else /** * WITHOUT_TRIO: * * defined if the trio support should not be configured in */ #define WITHOUT_TRIO #endif #else /* VMS */ /** * WITH_TRIO: * * defined if the trio support need to be configured in */ #define WITH_TRIO 1 #endif /* VMS */ /** * LIBXML_THREAD_ENABLED: * * Whether the thread support is configured in */ #if 0 #define LIBXML_THREAD_ENABLED #endif /** * LIBXML_THREAD_ALLOC_ENABLED: * * Whether the allocation hooks are per-thread */ #if 0 #define LIBXML_THREAD_ALLOC_ENABLED #endif /** * LIBXML_TREE_ENABLED: * * Whether the DOM like tree manipulation API support is configured in */ #if 1 #define LIBXML_TREE_ENABLED #endif /** * LIBXML_OUTPUT_ENABLED: * * Whether the serialization/saving support is configured in */ #if 1 #define LIBXML_OUTPUT_ENABLED #endif /** * LIBXML_PUSH_ENABLED: * * Whether the push parsing interfaces are configured in */ #if 1 #define LIBXML_PUSH_ENABLED #endif /** * LIBXML_READER_ENABLED: * * Whether the xmlReader parsing interface is configured in */ #if 1 #define LIBXML_READER_ENABLED #endif /** * LIBXML_PATTERN_ENABLED: * * Whether the xmlPattern node selection interface is configured in */ #if 1 #define LIBXML_PATTERN_ENABLED #endif /** * LIBXML_WRITER_ENABLED: * * Whether the xmlWriter saving interface is configured in */ #if 1 #define LIBXML_WRITER_ENABLED #endif /** * LIBXML_SAX1_ENABLED: * * Whether the older SAX1 interface is configured in */ #if 1 #define LIBXML_SAX1_ENABLED #endif /** * LIBXML_FTP_ENABLED: * * Whether the FTP support is configured in */ #if 0 #define LIBXML_FTP_ENABLED #endif /** * LIBXML_HTTP_ENABLED: * * Whether the HTTP support is configured in */ #if 0 #define LIBXML_HTTP_ENABLED #endif /** * LIBXML_VALID_ENABLED: * * Whether the DTD validation support is configured in */ #if 1 #define LIBXML_VALID_ENABLED #endif /** * LIBXML_HTML_ENABLED: * * Whether the HTML support is configured in */ #if 1 #define LIBXML_HTML_ENABLED #endif /** * LIBXML_LEGACY_ENABLED: * * Whether the deprecated APIs are compiled in for compatibility */ #if 0 #define LIBXML_LEGACY_ENABLED #endif /** * LIBXML_C14N_ENABLED: * * Whether the Canonicalization support is configured in */ #if 1 #define LIBXML_C14N_ENABLED #endif /** * LIBXML_CATALOG_ENABLED: * * Whether the Catalog support is configured in */ #if 1 #define LIBXML_CATALOG_ENABLED #endif /** * LIBXML_XPATH_ENABLED: * * Whether XPath is configured in */ #if 1 #define LIBXML_XPATH_ENABLED #endif /** * LIBXML_XPTR_ENABLED: * * Whether XPointer is configured in */ #if 1 #define LIBXML_XPTR_ENABLED #endif /** * LIBXML_XPTR_LOCS_ENABLED: * * Whether support for XPointer locations is configured in */ #if 0 #define LIBXML_XPTR_LOCS_ENABLED #endif /** * LIBXML_XINCLUDE_ENABLED: * * Whether XInclude is configured in */ #if 1 #define LIBXML_XINCLUDE_ENABLED #endif /** * LIBXML_ICONV_ENABLED: * * Whether iconv support is available */ #if 0 #define LIBXML_ICONV_ENABLED #endif /** * LIBXML_ICU_ENABLED: * * Whether icu support is available */ #if 0 #define LIBXML_ICU_ENABLED #endif /** * LIBXML_ISO8859X_ENABLED: * * Whether ISO-8859-* support is made available in case iconv is not */ #if 1 #define LIBXML_ISO8859X_ENABLED #endif /** * LIBXML_DEBUG_ENABLED: * * Whether Debugging module is configured in */ #if 1 #define LIBXML_DEBUG_ENABLED #endif /** * DEBUG_MEMORY_LOCATION: * * Whether the memory debugging is configured in */ #if 0 #define DEBUG_MEMORY_LOCATION #endif /** * LIBXML_DEBUG_RUNTIME: * * Removed */ #if 0 #define LIBXML_DEBUG_RUNTIME #endif /** * LIBXML_UNICODE_ENABLED: * * Whether the Unicode related interfaces are compiled in */ #if 1 #define LIBXML_UNICODE_ENABLED #endif /** * LIBXML_REGEXP_ENABLED: * * Whether the regular expressions interfaces are compiled in */ #if 1 #define LIBXML_REGEXP_ENABLED #endif /** * LIBXML_AUTOMATA_ENABLED: * * Whether the automata interfaces are compiled in */ #if 1 #define LIBXML_AUTOMATA_ENABLED #endif /** * LIBXML_EXPR_ENABLED: * * Whether the formal expressions interfaces are compiled in * * This code is unused and disabled unconditionally for now. */ #if 0 #define LIBXML_EXPR_ENABLED #endif /** * LIBXML_SCHEMAS_ENABLED: * * Whether the Schemas validation interfaces are compiled in */ #if 1 #define LIBXML_SCHEMAS_ENABLED #endif /** * LIBXML_SCHEMATRON_ENABLED: * * Whether the Schematron validation interfaces are compiled in */ #if 1 #define LIBXML_SCHEMATRON_ENABLED #endif /** * LIBXML_MODULES_ENABLED: * * Whether the module interfaces are compiled in */ #if 1 #define LIBXML_MODULES_ENABLED /** * LIBXML_MODULE_EXTENSION: * * the string suffix used by dynamic modules (usually shared libraries) */ #define LIBXML_MODULE_EXTENSION ".dll" #endif /** * LIBXML_ZLIB_ENABLED: * * Whether the Zlib support is compiled in */ #if 1 #define LIBXML_ZLIB_ENABLED #endif /** * LIBXML_LZMA_ENABLED: * * Whether the Lzma support is compiled in */ #if 0 #define LIBXML_LZMA_ENABLED #endif #ifdef __GNUC__ /** DOC_DISABLE */ #ifndef ATTRIBUTE_UNUSED # if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 7))) # define ATTRIBUTE_UNUSED __attribute__((unused)) # else # define ATTRIBUTE_UNUSED # endif #endif #ifndef LIBXML_ATTR_ALLOC_SIZE # if (!defined(__clang__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)))) # define LIBXML_ATTR_ALLOC_SIZE(x) __attribute__((alloc_size(x))) # else # define LIBXML_ATTR_ALLOC_SIZE(x) # endif #else # define LIBXML_ATTR_ALLOC_SIZE(x) #endif #ifndef LIBXML_ATTR_FORMAT # if ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3))) # define LIBXML_ATTR_FORMAT(fmt,args) __attribute__((__format__(__printf__,fmt,args))) # else # define LIBXML_ATTR_FORMAT(fmt,args) # endif #else # define LIBXML_ATTR_FORMAT(fmt,args) #endif #ifndef XML_DEPRECATED # if defined (IN_LIBXML) || (__GNUC__ * 100 + __GNUC_MINOR__ < 301) # define XML_DEPRECATED /* Available since at least GCC 3.1 */ # else # define XML_DEPRECATED __attribute__((deprecated)) # endif #endif #if defined(__clang__) || (__GNUC__ * 100 + __GNUC_MINOR__ >= 406) #define XML_IGNORE_FPTR_CAST_WARNINGS \ _Pragma("GCC diagnostic push") \ _Pragma("GCC diagnostic ignored \"-Wpedantic\"") \ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #define XML_POP_WARNINGS \ _Pragma("GCC diagnostic pop") #else #define XML_IGNORE_FPTR_CAST_WARNINGS #define XML_POP_WARNINGS #endif /** DOC_ENABLE */ #else /* ! __GNUC__ */ /** * ATTRIBUTE_UNUSED: * * Macro used to signal to GCC unused function parameters */ #define ATTRIBUTE_UNUSED /** * LIBXML_ATTR_ALLOC_SIZE: * * Macro used to indicate to GCC this is an allocator function */ #define LIBXML_ATTR_ALLOC_SIZE(x) /** * LIBXML_ATTR_FORMAT: * * Macro used to indicate to GCC the parameter are printf like */ #define LIBXML_ATTR_FORMAT(fmt,args) /** * XML_DEPRECATED: * * Macro used to indicate that a function, variable, type or struct member * is deprecated. */ #ifndef XML_DEPRECATED # if defined (IN_LIBXML) || !defined (_MSC_VER) # define XML_DEPRECATED /* Available since Visual Studio 2005 */ # elif defined (_MSC_VER) && (_MSC_VER >= 1400) # define XML_DEPRECATED __declspec(deprecated) # endif #endif /** * LIBXML_IGNORE_FPTR_CAST_WARNINGS: * * Macro used to ignore pointer cast warnings that can't be worked around. */ #if defined (_MSC_VER) && (_MSC_VER >= 1400) # define XML_IGNORE_FPTR_CAST_WARNINGS __pragma(warning(push)) #else # define XML_IGNORE_FPTR_CAST_WARNINGS #endif /** * XML_POP_WARNINGS: * * Macro used to restore warnings state. */ #ifndef XML_POP_WARNINGS # if defined (_MSC_VER) && (_MSC_VER >= 1400) # define XML_POP_WARNINGS __pragma(warning(pop)) # else # define XML_POP_WARNINGS # endif #endif #endif /* __GNUC__ */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif ================================================ FILE: thirdparty/64/include/libxml2/libxml/xmlwriter.h ================================================ /* * Summary: text writing API for XML * Description: text writing API for XML * * Copy: See Copyright for the status of this software. * * Author: Alfred Mickautsch */ #ifndef __XML_XMLWRITER_H__ #define __XML_XMLWRITER_H__ #include #ifdef LIBXML_WRITER_ENABLED #include #include #include #include #ifdef __cplusplus extern "C" { #endif typedef struct _xmlTextWriter xmlTextWriter; typedef xmlTextWriter *xmlTextWriterPtr; /* * Constructors & Destructor */ XMLPUBFUN xmlTextWriterPtr xmlNewTextWriter(xmlOutputBufferPtr out); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterFilename(const char *uri, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterMemory(xmlBufferPtr buf, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterPushParser(xmlParserCtxtPtr ctxt, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterDoc(xmlDocPtr * doc, int compression); XMLPUBFUN xmlTextWriterPtr xmlNewTextWriterTree(xmlDocPtr doc, xmlNodePtr node, int compression); XMLPUBFUN void xmlFreeTextWriter(xmlTextWriterPtr writer); /* * Functions */ /* * Document */ XMLPUBFUN int xmlTextWriterStartDocument(xmlTextWriterPtr writer, const char *version, const char *encoding, const char *standalone); XMLPUBFUN int xmlTextWriterEndDocument(xmlTextWriterPtr writer); /* * Comments */ XMLPUBFUN int xmlTextWriterStartComment(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterEndComment(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterWriteFormatComment(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatComment(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteComment(xmlTextWriterPtr writer, const xmlChar * content); /* * Elements */ XMLPUBFUN int xmlTextWriterStartElement(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterStartElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI); XMLPUBFUN int xmlTextWriterEndElement(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterFullEndElement(xmlTextWriterPtr writer); /* * Elements conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteElement(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteFormatElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, ...) LIBXML_ATTR_FORMAT(5,6); XMLPUBFUN int xmlTextWriterWriteVFormatElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(5,0); XMLPUBFUN int xmlTextWriterWriteElementNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const xmlChar * content); /* * Text */ XMLPUBFUN int xmlTextWriterWriteFormatRaw(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatRaw(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteRawLen(xmlTextWriterPtr writer, const xmlChar * content, int len); XMLPUBFUN int xmlTextWriterWriteRaw(xmlTextWriterPtr writer, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteFormatString(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatString(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteString(xmlTextWriterPtr writer, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteBase64(xmlTextWriterPtr writer, const char *data, int start, int len); XMLPUBFUN int xmlTextWriterWriteBinHex(xmlTextWriterPtr writer, const char *data, int start, int len); /* * Attributes */ XMLPUBFUN int xmlTextWriterStartAttribute(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterStartAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI); XMLPUBFUN int xmlTextWriterEndAttribute(xmlTextWriterPtr writer); /* * Attributes conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatAttribute(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatAttribute(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteAttribute(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteFormatAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, ...) LIBXML_ATTR_FORMAT(5,6); XMLPUBFUN int xmlTextWriterWriteVFormatAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(5,0); XMLPUBFUN int xmlTextWriterWriteAttributeNS(xmlTextWriterPtr writer, const xmlChar * prefix, const xmlChar * name, const xmlChar * namespaceURI, const xmlChar * content); /* * PI's */ XMLPUBFUN int xmlTextWriterStartPI(xmlTextWriterPtr writer, const xmlChar * target); XMLPUBFUN int xmlTextWriterEndPI(xmlTextWriterPtr writer); /* * PI conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatPI(xmlTextWriterPtr writer, const xmlChar * target, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatPI(xmlTextWriterPtr writer, const xmlChar * target, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWritePI(xmlTextWriterPtr writer, const xmlChar * target, const xmlChar * content); /** * xmlTextWriterWriteProcessingInstruction: * * This macro maps to xmlTextWriterWritePI */ #define xmlTextWriterWriteProcessingInstruction xmlTextWriterWritePI /* * CDATA */ XMLPUBFUN int xmlTextWriterStartCDATA(xmlTextWriterPtr writer); XMLPUBFUN int xmlTextWriterEndCDATA(xmlTextWriterPtr writer); /* * CDATA conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatCDATA(xmlTextWriterPtr writer, const char *format, ...) LIBXML_ATTR_FORMAT(2,3); XMLPUBFUN int xmlTextWriterWriteVFormatCDATA(xmlTextWriterPtr writer, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(2,0); XMLPUBFUN int xmlTextWriterWriteCDATA(xmlTextWriterPtr writer, const xmlChar * content); /* * DTD */ XMLPUBFUN int xmlTextWriterStartDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid); XMLPUBFUN int xmlTextWriterEndDTD(xmlTextWriterPtr writer); /* * DTD conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const char *format, ...) LIBXML_ATTR_FORMAT(5,6); XMLPUBFUN int xmlTextWriterWriteVFormatDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(5,0); XMLPUBFUN int xmlTextWriterWriteDTD(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * subset); /** * xmlTextWriterWriteDocType: * * this macro maps to xmlTextWriterWriteDTD */ #define xmlTextWriterWriteDocType xmlTextWriterWriteDTD /* * DTD element definition */ XMLPUBFUN int xmlTextWriterStartDTDElement(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterEndDTDElement(xmlTextWriterPtr writer); /* * DTD element definition conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTDElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatDTDElement(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteDTDElement(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); /* * DTD attribute list definition */ XMLPUBFUN int xmlTextWriterStartDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name); XMLPUBFUN int xmlTextWriterEndDTDAttlist(xmlTextWriterPtr writer); /* * DTD attribute list definition conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(3,4); XMLPUBFUN int xmlTextWriterWriteVFormatDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(3,0); XMLPUBFUN int xmlTextWriterWriteDTDAttlist(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * content); /* * DTD entity definition */ XMLPUBFUN int xmlTextWriterStartDTDEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name); XMLPUBFUN int xmlTextWriterEndDTDEntity(xmlTextWriterPtr writer); /* * DTD entity definition conveniency functions */ XMLPUBFUN int xmlTextWriterWriteFormatDTDInternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const char *format, ...) LIBXML_ATTR_FORMAT(4,5); XMLPUBFUN int xmlTextWriterWriteVFormatDTDInternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const char *format, va_list argptr) LIBXML_ATTR_FORMAT(4,0); XMLPUBFUN int xmlTextWriterWriteDTDInternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const xmlChar * content); XMLPUBFUN int xmlTextWriterWriteDTDExternalEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * ndataid); XMLPUBFUN int xmlTextWriterWriteDTDExternalEntityContents(xmlTextWriterPtr writer, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * ndataid); XMLPUBFUN int xmlTextWriterWriteDTDEntity(xmlTextWriterPtr writer, int pe, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid, const xmlChar * ndataid, const xmlChar * content); /* * DTD notation definition */ XMLPUBFUN int xmlTextWriterWriteDTDNotation(xmlTextWriterPtr writer, const xmlChar * name, const xmlChar * pubid, const xmlChar * sysid); /* * Indentation */ XMLPUBFUN int xmlTextWriterSetIndent(xmlTextWriterPtr writer, int indent); XMLPUBFUN int xmlTextWriterSetIndentString(xmlTextWriterPtr writer, const xmlChar * str); XMLPUBFUN int xmlTextWriterSetQuoteChar(xmlTextWriterPtr writer, xmlChar quotechar); /* * misc */ XMLPUBFUN int xmlTextWriterFlush(xmlTextWriterPtr writer); #ifdef __cplusplus } #endif #endif /* LIBXML_WRITER_ENABLED */ #endif /* __XML_XMLWRITER_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xpath.h ================================================ /* * Summary: XML Path Language implementation * Description: API for the XML Path Language implementation * * XML Path Language implementation * XPath is a language for addressing parts of an XML document, * designed to be used by both XSLT and XPointer * http://www.w3.org/TR/xpath * * Implements * W3C Recommendation 16 November 1999 * http://www.w3.org/TR/1999/REC-xpath-19991116 * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XPATH_H__ #define __XML_XPATH_H__ #include #ifdef LIBXML_XPATH_ENABLED #include #include #include #endif /* LIBXML_XPATH_ENABLED */ #if defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) #ifdef __cplusplus extern "C" { #endif #endif /* LIBXML_XPATH_ENABLED or LIBXML_SCHEMAS_ENABLED */ #ifdef LIBXML_XPATH_ENABLED typedef struct _xmlXPathContext xmlXPathContext; typedef xmlXPathContext *xmlXPathContextPtr; typedef struct _xmlXPathParserContext xmlXPathParserContext; typedef xmlXPathParserContext *xmlXPathParserContextPtr; /** * The set of XPath error codes. */ typedef enum { XPATH_EXPRESSION_OK = 0, XPATH_NUMBER_ERROR, XPATH_UNFINISHED_LITERAL_ERROR, XPATH_START_LITERAL_ERROR, XPATH_VARIABLE_REF_ERROR, XPATH_UNDEF_VARIABLE_ERROR, XPATH_INVALID_PREDICATE_ERROR, XPATH_EXPR_ERROR, XPATH_UNCLOSED_ERROR, XPATH_UNKNOWN_FUNC_ERROR, XPATH_INVALID_OPERAND, XPATH_INVALID_TYPE, XPATH_INVALID_ARITY, XPATH_INVALID_CTXT_SIZE, XPATH_INVALID_CTXT_POSITION, XPATH_MEMORY_ERROR, XPTR_SYNTAX_ERROR, XPTR_RESOURCE_ERROR, XPTR_SUB_RESOURCE_ERROR, XPATH_UNDEF_PREFIX_ERROR, XPATH_ENCODING_ERROR, XPATH_INVALID_CHAR_ERROR, XPATH_INVALID_CTXT, XPATH_STACK_ERROR, XPATH_FORBID_VARIABLE_ERROR, XPATH_OP_LIMIT_EXCEEDED, XPATH_RECURSION_LIMIT_EXCEEDED } xmlXPathError; /* * A node-set (an unordered collection of nodes without duplicates). */ typedef struct _xmlNodeSet xmlNodeSet; typedef xmlNodeSet *xmlNodeSetPtr; struct _xmlNodeSet { int nodeNr; /* number of nodes in the set */ int nodeMax; /* size of the array as allocated */ xmlNodePtr *nodeTab; /* array of nodes in no particular order */ /* @@ with_ns to check whether namespace nodes should be looked at @@ */ }; /* * An expression is evaluated to yield an object, which * has one of the following four basic types: * - node-set * - boolean * - number * - string * * @@ XPointer will add more types ! */ typedef enum { XPATH_UNDEFINED = 0, XPATH_NODESET = 1, XPATH_BOOLEAN = 2, XPATH_NUMBER = 3, XPATH_STRING = 4, #ifdef LIBXML_XPTR_LOCS_ENABLED XPATH_POINT = 5, XPATH_RANGE = 6, XPATH_LOCATIONSET = 7, #endif XPATH_USERS = 8, XPATH_XSLT_TREE = 9 /* An XSLT value tree, non modifiable */ } xmlXPathObjectType; #ifndef LIBXML_XPTR_LOCS_ENABLED /** DOC_DISABLE */ #define XPATH_POINT 5 #define XPATH_RANGE 6 #define XPATH_LOCATIONSET 7 /** DOC_ENABLE */ #endif typedef struct _xmlXPathObject xmlXPathObject; typedef xmlXPathObject *xmlXPathObjectPtr; struct _xmlXPathObject { xmlXPathObjectType type; xmlNodeSetPtr nodesetval; int boolval; double floatval; xmlChar *stringval; void *user; int index; void *user2; int index2; }; /** * xmlXPathConvertFunc: * @obj: an XPath object * @type: the number of the target type * * A conversion function is associated to a type and used to cast * the new type to primitive values. * * Returns -1 in case of error, 0 otherwise */ typedef int (*xmlXPathConvertFunc) (xmlXPathObjectPtr obj, int type); /* * Extra type: a name and a conversion function. */ typedef struct _xmlXPathType xmlXPathType; typedef xmlXPathType *xmlXPathTypePtr; struct _xmlXPathType { const xmlChar *name; /* the type name */ xmlXPathConvertFunc func; /* the conversion function */ }; /* * Extra variable: a name and a value. */ typedef struct _xmlXPathVariable xmlXPathVariable; typedef xmlXPathVariable *xmlXPathVariablePtr; struct _xmlXPathVariable { const xmlChar *name; /* the variable name */ xmlXPathObjectPtr value; /* the value */ }; /** * xmlXPathEvalFunc: * @ctxt: an XPath parser context * @nargs: the number of arguments passed to the function * * An XPath evaluation function, the parameters are on the XPath context stack. */ typedef void (*xmlXPathEvalFunc)(xmlXPathParserContextPtr ctxt, int nargs); /* * Extra function: a name and a evaluation function. */ typedef struct _xmlXPathFunct xmlXPathFunct; typedef xmlXPathFunct *xmlXPathFuncPtr; struct _xmlXPathFunct { const xmlChar *name; /* the function name */ xmlXPathEvalFunc func; /* the evaluation function */ }; /** * xmlXPathAxisFunc: * @ctxt: the XPath interpreter context * @cur: the previous node being explored on that axis * * An axis traversal function. To traverse an axis, the engine calls * the first time with cur == NULL and repeat until the function returns * NULL indicating the end of the axis traversal. * * Returns the next node in that axis or NULL if at the end of the axis. */ typedef xmlXPathObjectPtr (*xmlXPathAxisFunc) (xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr cur); /* * Extra axis: a name and an axis function. */ typedef struct _xmlXPathAxis xmlXPathAxis; typedef xmlXPathAxis *xmlXPathAxisPtr; struct _xmlXPathAxis { const xmlChar *name; /* the axis name */ xmlXPathAxisFunc func; /* the search function */ }; /** * xmlXPathFunction: * @ctxt: the XPath interprestation context * @nargs: the number of arguments * * An XPath function. * The arguments (if any) are popped out from the context stack * and the result is pushed on the stack. */ typedef void (*xmlXPathFunction) (xmlXPathParserContextPtr ctxt, int nargs); /* * Function and Variable Lookup. */ /** * xmlXPathVariableLookupFunc: * @ctxt: an XPath context * @name: name of the variable * @ns_uri: the namespace name hosting this variable * * Prototype for callbacks used to plug variable lookup in the XPath * engine. * * Returns the XPath object value or NULL if not found. */ typedef xmlXPathObjectPtr (*xmlXPathVariableLookupFunc) (void *ctxt, const xmlChar *name, const xmlChar *ns_uri); /** * xmlXPathFuncLookupFunc: * @ctxt: an XPath context * @name: name of the function * @ns_uri: the namespace name hosting this function * * Prototype for callbacks used to plug function lookup in the XPath * engine. * * Returns the XPath function or NULL if not found. */ typedef xmlXPathFunction (*xmlXPathFuncLookupFunc) (void *ctxt, const xmlChar *name, const xmlChar *ns_uri); /** * xmlXPathFlags: * Flags for XPath engine compilation and runtime */ /** * XML_XPATH_CHECKNS: * * check namespaces at compilation */ #define XML_XPATH_CHECKNS (1<<0) /** * XML_XPATH_NOVAR: * * forbid variables in expression */ #define XML_XPATH_NOVAR (1<<1) /** * xmlXPathContext: * * Expression evaluation occurs with respect to a context. * he context consists of: * - a node (the context node) * - a node list (the context node list) * - a set of variable bindings * - a function library * - the set of namespace declarations in scope for the expression * Following the switch to hash tables, this need to be trimmed up at * the next binary incompatible release. * The node may be modified when the context is passed to libxml2 * for an XPath evaluation so you may need to initialize it again * before the next call. */ struct _xmlXPathContext { xmlDocPtr doc; /* The current document */ xmlNodePtr node; /* The current node */ int nb_variables_unused; /* unused (hash table) */ int max_variables_unused; /* unused (hash table) */ xmlHashTablePtr varHash; /* Hash table of defined variables */ int nb_types; /* number of defined types */ int max_types; /* max number of types */ xmlXPathTypePtr types; /* Array of defined types */ int nb_funcs_unused; /* unused (hash table) */ int max_funcs_unused; /* unused (hash table) */ xmlHashTablePtr funcHash; /* Hash table of defined funcs */ int nb_axis; /* number of defined axis */ int max_axis; /* max number of axis */ xmlXPathAxisPtr axis; /* Array of defined axis */ /* the namespace nodes of the context node */ xmlNsPtr *namespaces; /* Array of namespaces */ int nsNr; /* number of namespace in scope */ void *user; /* function to free */ /* extra variables */ int contextSize; /* the context size */ int proximityPosition; /* the proximity position */ /* extra stuff for XPointer */ int xptr; /* is this an XPointer context? */ xmlNodePtr here; /* for here() */ xmlNodePtr origin; /* for origin() */ /* the set of namespace declarations in scope for the expression */ xmlHashTablePtr nsHash; /* The namespaces hash table */ xmlXPathVariableLookupFunc varLookupFunc;/* variable lookup func */ void *varLookupData; /* variable lookup data */ /* Possibility to link in an extra item */ void *extra; /* needed for XSLT */ /* The function name and URI when calling a function */ const xmlChar *function; const xmlChar *functionURI; /* function lookup function and data */ xmlXPathFuncLookupFunc funcLookupFunc;/* function lookup func */ void *funcLookupData; /* function lookup data */ /* temporary namespace lists kept for walking the namespace axis */ xmlNsPtr *tmpNsList; /* Array of namespaces */ int tmpNsNr; /* number of namespaces in scope */ /* error reporting mechanism */ void *userData; /* user specific data block */ xmlStructuredErrorFunc error; /* the callback in case of errors */ xmlError lastError; /* the last error */ xmlNodePtr debugNode; /* the source node XSLT */ /* dictionary */ xmlDictPtr dict; /* dictionary if any */ int flags; /* flags to control compilation */ /* Cache for reusal of XPath objects */ void *cache; /* Resource limits */ unsigned long opLimit; unsigned long opCount; int depth; }; /* * The structure of a compiled expression form is not public. */ typedef struct _xmlXPathCompExpr xmlXPathCompExpr; typedef xmlXPathCompExpr *xmlXPathCompExprPtr; /** * xmlXPathParserContext: * * An XPath parser context. It contains pure parsing information, * an xmlXPathContext, and the stack of objects. */ struct _xmlXPathParserContext { const xmlChar *cur; /* the current char being parsed */ const xmlChar *base; /* the full expression */ int error; /* error code */ xmlXPathContextPtr context; /* the evaluation context */ xmlXPathObjectPtr value; /* the current value */ int valueNr; /* number of values stacked */ int valueMax; /* max number of values stacked */ xmlXPathObjectPtr *valueTab; /* stack of values */ xmlXPathCompExprPtr comp; /* the precompiled expression */ int xptr; /* it this an XPointer expression */ xmlNodePtr ancestor; /* used for walking preceding axis */ int valueFrame; /* unused */ }; /************************************************************************ * * * Public API * * * ************************************************************************/ /** * Objects and Nodesets handling */ XMLPUBVAR double xmlXPathNAN; XMLPUBVAR double xmlXPathPINF; XMLPUBVAR double xmlXPathNINF; /* These macros may later turn into functions */ /** * xmlXPathNodeSetGetLength: * @ns: a node-set * * Implement a functionality similar to the DOM NodeList.length. * * Returns the number of nodes in the node-set. */ #define xmlXPathNodeSetGetLength(ns) ((ns) ? (ns)->nodeNr : 0) /** * xmlXPathNodeSetItem: * @ns: a node-set * @index: index of a node in the set * * Implements a functionality similar to the DOM NodeList.item(). * * Returns the xmlNodePtr at the given @index in @ns or NULL if * @index is out of range (0 to length-1) */ #define xmlXPathNodeSetItem(ns, index) \ ((((ns) != NULL) && \ ((index) >= 0) && ((index) < (ns)->nodeNr)) ? \ (ns)->nodeTab[(index)] \ : NULL) /** * xmlXPathNodeSetIsEmpty: * @ns: a node-set * * Checks whether @ns is empty or not. * * Returns %TRUE if @ns is an empty node-set. */ #define xmlXPathNodeSetIsEmpty(ns) \ (((ns) == NULL) || ((ns)->nodeNr == 0) || ((ns)->nodeTab == NULL)) XMLPUBFUN void xmlXPathFreeObject (xmlXPathObjectPtr obj); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeSetCreate (xmlNodePtr val); XMLPUBFUN void xmlXPathFreeNodeSetList (xmlXPathObjectPtr obj); XMLPUBFUN void xmlXPathFreeNodeSet (xmlNodeSetPtr obj); XMLPUBFUN xmlXPathObjectPtr xmlXPathObjectCopy (xmlXPathObjectPtr val); XMLPUBFUN int xmlXPathCmpNodes (xmlNodePtr node1, xmlNodePtr node2); /** * Conversion functions to basic types. */ XMLPUBFUN int xmlXPathCastNumberToBoolean (double val); XMLPUBFUN int xmlXPathCastStringToBoolean (const xmlChar * val); XMLPUBFUN int xmlXPathCastNodeSetToBoolean(xmlNodeSetPtr ns); XMLPUBFUN int xmlXPathCastToBoolean (xmlXPathObjectPtr val); XMLPUBFUN double xmlXPathCastBooleanToNumber (int val); XMLPUBFUN double xmlXPathCastStringToNumber (const xmlChar * val); XMLPUBFUN double xmlXPathCastNodeToNumber (xmlNodePtr node); XMLPUBFUN double xmlXPathCastNodeSetToNumber (xmlNodeSetPtr ns); XMLPUBFUN double xmlXPathCastToNumber (xmlXPathObjectPtr val); XMLPUBFUN xmlChar * xmlXPathCastBooleanToString (int val); XMLPUBFUN xmlChar * xmlXPathCastNumberToString (double val); XMLPUBFUN xmlChar * xmlXPathCastNodeToString (xmlNodePtr node); XMLPUBFUN xmlChar * xmlXPathCastNodeSetToString (xmlNodeSetPtr ns); XMLPUBFUN xmlChar * xmlXPathCastToString (xmlXPathObjectPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathConvertBoolean (xmlXPathObjectPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathConvertNumber (xmlXPathObjectPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathConvertString (xmlXPathObjectPtr val); /** * Context handling. */ XMLPUBFUN xmlXPathContextPtr xmlXPathNewContext (xmlDocPtr doc); XMLPUBFUN void xmlXPathFreeContext (xmlXPathContextPtr ctxt); XMLPUBFUN int xmlXPathContextSetCache(xmlXPathContextPtr ctxt, int active, int value, int options); /** * Evaluation functions. */ XMLPUBFUN long xmlXPathOrderDocElems (xmlDocPtr doc); XMLPUBFUN int xmlXPathSetContextNode (xmlNodePtr node, xmlXPathContextPtr ctx); XMLPUBFUN xmlXPathObjectPtr xmlXPathNodeEval (xmlNodePtr node, const xmlChar *str, xmlXPathContextPtr ctx); XMLPUBFUN xmlXPathObjectPtr xmlXPathEval (const xmlChar *str, xmlXPathContextPtr ctx); XMLPUBFUN xmlXPathObjectPtr xmlXPathEvalExpression (const xmlChar *str, xmlXPathContextPtr ctxt); XMLPUBFUN int xmlXPathEvalPredicate (xmlXPathContextPtr ctxt, xmlXPathObjectPtr res); /** * Separate compilation/evaluation entry points. */ XMLPUBFUN xmlXPathCompExprPtr xmlXPathCompile (const xmlChar *str); XMLPUBFUN xmlXPathCompExprPtr xmlXPathCtxtCompile (xmlXPathContextPtr ctxt, const xmlChar *str); XMLPUBFUN xmlXPathObjectPtr xmlXPathCompiledEval (xmlXPathCompExprPtr comp, xmlXPathContextPtr ctx); XMLPUBFUN int xmlXPathCompiledEvalToBoolean(xmlXPathCompExprPtr comp, xmlXPathContextPtr ctxt); XMLPUBFUN void xmlXPathFreeCompExpr (xmlXPathCompExprPtr comp); #endif /* LIBXML_XPATH_ENABLED */ #if defined(LIBXML_XPATH_ENABLED) || defined(LIBXML_SCHEMAS_ENABLED) XML_DEPRECATED XMLPUBFUN void xmlXPathInit (void); XMLPUBFUN int xmlXPathIsNaN (double val); XMLPUBFUN int xmlXPathIsInf (double val); #ifdef __cplusplus } #endif #endif /* LIBXML_XPATH_ENABLED or LIBXML_SCHEMAS_ENABLED*/ #endif /* ! __XML_XPATH_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xpathInternals.h ================================================ /* * Summary: internal interfaces for XML Path Language implementation * Description: internal interfaces for XML Path Language implementation * used to build new modules on top of XPath like XPointer and * XSLT * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XPATH_INTERNALS_H__ #define __XML_XPATH_INTERNALS_H__ #include #include #ifdef LIBXML_XPATH_ENABLED #ifdef __cplusplus extern "C" { #endif /************************************************************************ * * * Helpers * * * ************************************************************************/ /* * Many of these macros may later turn into functions. They * shouldn't be used in #ifdef's preprocessor instructions. */ /** * xmlXPathSetError: * @ctxt: an XPath parser context * @err: an xmlXPathError code * * Raises an error. */ #define xmlXPathSetError(ctxt, err) \ { xmlXPatherror((ctxt), __FILE__, __LINE__, (err)); \ if ((ctxt) != NULL) (ctxt)->error = (err); } /** * xmlXPathSetArityError: * @ctxt: an XPath parser context * * Raises an XPATH_INVALID_ARITY error. */ #define xmlXPathSetArityError(ctxt) \ xmlXPathSetError((ctxt), XPATH_INVALID_ARITY) /** * xmlXPathSetTypeError: * @ctxt: an XPath parser context * * Raises an XPATH_INVALID_TYPE error. */ #define xmlXPathSetTypeError(ctxt) \ xmlXPathSetError((ctxt), XPATH_INVALID_TYPE) /** * xmlXPathGetError: * @ctxt: an XPath parser context * * Get the error code of an XPath context. * * Returns the context error. */ #define xmlXPathGetError(ctxt) ((ctxt)->error) /** * xmlXPathCheckError: * @ctxt: an XPath parser context * * Check if an XPath error was raised. * * Returns true if an error has been raised, false otherwise. */ #define xmlXPathCheckError(ctxt) ((ctxt)->error != XPATH_EXPRESSION_OK) /** * xmlXPathGetDocument: * @ctxt: an XPath parser context * * Get the document of an XPath context. * * Returns the context document. */ #define xmlXPathGetDocument(ctxt) ((ctxt)->context->doc) /** * xmlXPathGetContextNode: * @ctxt: an XPath parser context * * Get the context node of an XPath context. * * Returns the context node. */ #define xmlXPathGetContextNode(ctxt) ((ctxt)->context->node) XMLPUBFUN int xmlXPathPopBoolean (xmlXPathParserContextPtr ctxt); XMLPUBFUN double xmlXPathPopNumber (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlChar * xmlXPathPopString (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlNodeSetPtr xmlXPathPopNodeSet (xmlXPathParserContextPtr ctxt); XMLPUBFUN void * xmlXPathPopExternal (xmlXPathParserContextPtr ctxt); /** * xmlXPathReturnBoolean: * @ctxt: an XPath parser context * @val: a boolean * * Pushes the boolean @val on the context stack. */ #define xmlXPathReturnBoolean(ctxt, val) \ valuePush((ctxt), xmlXPathNewBoolean(val)) /** * xmlXPathReturnTrue: * @ctxt: an XPath parser context * * Pushes true on the context stack. */ #define xmlXPathReturnTrue(ctxt) xmlXPathReturnBoolean((ctxt), 1) /** * xmlXPathReturnFalse: * @ctxt: an XPath parser context * * Pushes false on the context stack. */ #define xmlXPathReturnFalse(ctxt) xmlXPathReturnBoolean((ctxt), 0) /** * xmlXPathReturnNumber: * @ctxt: an XPath parser context * @val: a double * * Pushes the double @val on the context stack. */ #define xmlXPathReturnNumber(ctxt, val) \ valuePush((ctxt), xmlXPathNewFloat(val)) /** * xmlXPathReturnString: * @ctxt: an XPath parser context * @str: a string * * Pushes the string @str on the context stack. */ #define xmlXPathReturnString(ctxt, str) \ valuePush((ctxt), xmlXPathWrapString(str)) /** * xmlXPathReturnEmptyString: * @ctxt: an XPath parser context * * Pushes an empty string on the stack. */ #define xmlXPathReturnEmptyString(ctxt) \ valuePush((ctxt), xmlXPathNewCString("")) /** * xmlXPathReturnNodeSet: * @ctxt: an XPath parser context * @ns: a node-set * * Pushes the node-set @ns on the context stack. */ #define xmlXPathReturnNodeSet(ctxt, ns) \ valuePush((ctxt), xmlXPathWrapNodeSet(ns)) /** * xmlXPathReturnEmptyNodeSet: * @ctxt: an XPath parser context * * Pushes an empty node-set on the context stack. */ #define xmlXPathReturnEmptyNodeSet(ctxt) \ valuePush((ctxt), xmlXPathNewNodeSet(NULL)) /** * xmlXPathReturnExternal: * @ctxt: an XPath parser context * @val: user data * * Pushes user data on the context stack. */ #define xmlXPathReturnExternal(ctxt, val) \ valuePush((ctxt), xmlXPathWrapExternal(val)) /** * xmlXPathStackIsNodeSet: * @ctxt: an XPath parser context * * Check if the current value on the XPath stack is a node set or * an XSLT value tree. * * Returns true if the current object on the stack is a node-set. */ #define xmlXPathStackIsNodeSet(ctxt) \ (((ctxt)->value != NULL) \ && (((ctxt)->value->type == XPATH_NODESET) \ || ((ctxt)->value->type == XPATH_XSLT_TREE))) /** * xmlXPathStackIsExternal: * @ctxt: an XPath parser context * * Checks if the current value on the XPath stack is an external * object. * * Returns true if the current object on the stack is an external * object. */ #define xmlXPathStackIsExternal(ctxt) \ ((ctxt->value != NULL) && (ctxt->value->type == XPATH_USERS)) /** * xmlXPathEmptyNodeSet: * @ns: a node-set * * Empties a node-set. */ #define xmlXPathEmptyNodeSet(ns) \ { while ((ns)->nodeNr > 0) (ns)->nodeTab[--(ns)->nodeNr] = NULL; } /** * CHECK_ERROR: * * Macro to return from the function if an XPath error was detected. */ #define CHECK_ERROR \ if (ctxt->error != XPATH_EXPRESSION_OK) return /** * CHECK_ERROR0: * * Macro to return 0 from the function if an XPath error was detected. */ #define CHECK_ERROR0 \ if (ctxt->error != XPATH_EXPRESSION_OK) return(0) /** * XP_ERROR: * @X: the error code * * Macro to raise an XPath error and return. */ #define XP_ERROR(X) \ { xmlXPathErr(ctxt, X); return; } /** * XP_ERROR0: * @X: the error code * * Macro to raise an XPath error and return 0. */ #define XP_ERROR0(X) \ { xmlXPathErr(ctxt, X); return(0); } /** * CHECK_TYPE: * @typeval: the XPath type * * Macro to check that the value on top of the XPath stack is of a given * type. */ #define CHECK_TYPE(typeval) \ if ((ctxt->value == NULL) || (ctxt->value->type != typeval)) \ XP_ERROR(XPATH_INVALID_TYPE) /** * CHECK_TYPE0: * @typeval: the XPath type * * Macro to check that the value on top of the XPath stack is of a given * type. Return(0) in case of failure */ #define CHECK_TYPE0(typeval) \ if ((ctxt->value == NULL) || (ctxt->value->type != typeval)) \ XP_ERROR0(XPATH_INVALID_TYPE) /** * CHECK_ARITY: * @x: the number of expected args * * Macro to check that the number of args passed to an XPath function matches. */ #define CHECK_ARITY(x) \ if (ctxt == NULL) return; \ if (nargs != (x)) \ XP_ERROR(XPATH_INVALID_ARITY); \ if (ctxt->valueNr < ctxt->valueFrame + (x)) \ XP_ERROR(XPATH_STACK_ERROR); /** * CAST_TO_STRING: * * Macro to try to cast the value on the top of the XPath stack to a string. */ #define CAST_TO_STRING \ if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_STRING)) \ xmlXPathStringFunction(ctxt, 1); /** * CAST_TO_NUMBER: * * Macro to try to cast the value on the top of the XPath stack to a number. */ #define CAST_TO_NUMBER \ if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_NUMBER)) \ xmlXPathNumberFunction(ctxt, 1); /** * CAST_TO_BOOLEAN: * * Macro to try to cast the value on the top of the XPath stack to a boolean. */ #define CAST_TO_BOOLEAN \ if ((ctxt->value != NULL) && (ctxt->value->type != XPATH_BOOLEAN)) \ xmlXPathBooleanFunction(ctxt, 1); /* * Variable Lookup forwarding. */ XMLPUBFUN void xmlXPathRegisterVariableLookup (xmlXPathContextPtr ctxt, xmlXPathVariableLookupFunc f, void *data); /* * Function Lookup forwarding. */ XMLPUBFUN void xmlXPathRegisterFuncLookup (xmlXPathContextPtr ctxt, xmlXPathFuncLookupFunc f, void *funcCtxt); /* * Error reporting. */ XMLPUBFUN void xmlXPatherror (xmlXPathParserContextPtr ctxt, const char *file, int line, int no); XMLPUBFUN void xmlXPathErr (xmlXPathParserContextPtr ctxt, int error); #ifdef LIBXML_DEBUG_ENABLED XMLPUBFUN void xmlXPathDebugDumpObject (FILE *output, xmlXPathObjectPtr cur, int depth); XMLPUBFUN void xmlXPathDebugDumpCompExpr(FILE *output, xmlXPathCompExprPtr comp, int depth); #endif /** * NodeSet handling. */ XMLPUBFUN int xmlXPathNodeSetContains (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN xmlNodeSetPtr xmlXPathDifference (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathIntersection (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathDistinctSorted (xmlNodeSetPtr nodes); XMLPUBFUN xmlNodeSetPtr xmlXPathDistinct (xmlNodeSetPtr nodes); XMLPUBFUN int xmlXPathHasSameNodes (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeLeadingSorted (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathLeadingSorted (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeLeading (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathLeading (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeTrailingSorted (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathTrailingSorted (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeTrailing (xmlNodeSetPtr nodes, xmlNodePtr node); XMLPUBFUN xmlNodeSetPtr xmlXPathTrailing (xmlNodeSetPtr nodes1, xmlNodeSetPtr nodes2); /** * Extending a context. */ XMLPUBFUN int xmlXPathRegisterNs (xmlXPathContextPtr ctxt, const xmlChar *prefix, const xmlChar *ns_uri); XMLPUBFUN const xmlChar * xmlXPathNsLookup (xmlXPathContextPtr ctxt, const xmlChar *prefix); XMLPUBFUN void xmlXPathRegisteredNsCleanup (xmlXPathContextPtr ctxt); XMLPUBFUN int xmlXPathRegisterFunc (xmlXPathContextPtr ctxt, const xmlChar *name, xmlXPathFunction f); XMLPUBFUN int xmlXPathRegisterFuncNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri, xmlXPathFunction f); XMLPUBFUN int xmlXPathRegisterVariable (xmlXPathContextPtr ctxt, const xmlChar *name, xmlXPathObjectPtr value); XMLPUBFUN int xmlXPathRegisterVariableNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri, xmlXPathObjectPtr value); XMLPUBFUN xmlXPathFunction xmlXPathFunctionLookup (xmlXPathContextPtr ctxt, const xmlChar *name); XMLPUBFUN xmlXPathFunction xmlXPathFunctionLookupNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri); XMLPUBFUN void xmlXPathRegisteredFuncsCleanup (xmlXPathContextPtr ctxt); XMLPUBFUN xmlXPathObjectPtr xmlXPathVariableLookup (xmlXPathContextPtr ctxt, const xmlChar *name); XMLPUBFUN xmlXPathObjectPtr xmlXPathVariableLookupNS (xmlXPathContextPtr ctxt, const xmlChar *name, const xmlChar *ns_uri); XMLPUBFUN void xmlXPathRegisteredVariablesCleanup(xmlXPathContextPtr ctxt); /** * Utilities to extend XPath. */ XMLPUBFUN xmlXPathParserContextPtr xmlXPathNewParserContext (const xmlChar *str, xmlXPathContextPtr ctxt); XMLPUBFUN void xmlXPathFreeParserContext (xmlXPathParserContextPtr ctxt); /* TODO: remap to xmlXPathValuePop and Push. */ XMLPUBFUN xmlXPathObjectPtr valuePop (xmlXPathParserContextPtr ctxt); XMLPUBFUN int valuePush (xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr value); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewString (const xmlChar *val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewCString (const char *val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapString (xmlChar *val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapCString (char * val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewFloat (double val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewBoolean (int val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewNodeSet (xmlNodePtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewValueTree (xmlNodePtr val); XMLPUBFUN int xmlXPathNodeSetAdd (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN int xmlXPathNodeSetAddUnique (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN int xmlXPathNodeSetAddNs (xmlNodeSetPtr cur, xmlNodePtr node, xmlNsPtr ns); XMLPUBFUN void xmlXPathNodeSetSort (xmlNodeSetPtr set); XMLPUBFUN void xmlXPathRoot (xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathEvalExpr (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlChar * xmlXPathParseName (xmlXPathParserContextPtr ctxt); XMLPUBFUN xmlChar * xmlXPathParseNCName (xmlXPathParserContextPtr ctxt); /* * Existing functions. */ XMLPUBFUN double xmlXPathStringEvalNumber (const xmlChar *str); XMLPUBFUN int xmlXPathEvaluatePredicateResult (xmlXPathParserContextPtr ctxt, xmlXPathObjectPtr res); XMLPUBFUN void xmlXPathRegisterAllFunctions (xmlXPathContextPtr ctxt); XMLPUBFUN xmlNodeSetPtr xmlXPathNodeSetMerge (xmlNodeSetPtr val1, xmlNodeSetPtr val2); XMLPUBFUN void xmlXPathNodeSetDel (xmlNodeSetPtr cur, xmlNodePtr val); XMLPUBFUN void xmlXPathNodeSetRemove (xmlNodeSetPtr cur, int val); XMLPUBFUN xmlXPathObjectPtr xmlXPathNewNodeSetList (xmlNodeSetPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapNodeSet (xmlNodeSetPtr val); XMLPUBFUN xmlXPathObjectPtr xmlXPathWrapExternal (void *val); XMLPUBFUN int xmlXPathEqualValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN int xmlXPathNotEqualValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN int xmlXPathCompareValues(xmlXPathParserContextPtr ctxt, int inf, int strict); XMLPUBFUN void xmlXPathValueFlipSign(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathAddValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathSubValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathMultValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathDivValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN void xmlXPathModValues(xmlXPathParserContextPtr ctxt); XMLPUBFUN int xmlXPathIsNodeType(const xmlChar *name); /* * Some of the axis navigation routines. */ XMLPUBFUN xmlNodePtr xmlXPathNextSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextChild(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextDescendant(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextDescendantOrSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextParent(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextAncestorOrSelf(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextFollowingSibling(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextFollowing(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextNamespace(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextAttribute(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextPreceding(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextAncestor(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); XMLPUBFUN xmlNodePtr xmlXPathNextPrecedingSibling(xmlXPathParserContextPtr ctxt, xmlNodePtr cur); /* * The official core of XPath functions. */ XMLPUBFUN void xmlXPathLastFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathPositionFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathCountFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathIdFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathLocalNameFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNamespaceURIFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathStringFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathStringLengthFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathConcatFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathContainsFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathStartsWithFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSubstringFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSubstringBeforeFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSubstringAfterFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNormalizeFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathTranslateFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNotFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathTrueFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathFalseFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathLangFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathNumberFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathSumFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathFloorFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathCeilingFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathRoundFunction(xmlXPathParserContextPtr ctxt, int nargs); XMLPUBFUN void xmlXPathBooleanFunction(xmlXPathParserContextPtr ctxt, int nargs); /** * Really internal functions */ XMLPUBFUN void xmlXPathNodeSetFreeNs(xmlNsPtr ns); #ifdef __cplusplus } #endif #endif /* LIBXML_XPATH_ENABLED */ #endif /* ! __XML_XPATH_INTERNALS_H__ */ ================================================ FILE: thirdparty/64/include/libxml2/libxml/xpointer.h ================================================ /* * Summary: API to handle XML Pointers * Description: API to handle XML Pointers * Base implementation was made accordingly to * W3C Candidate Recommendation 7 June 2000 * http://www.w3.org/TR/2000/CR-xptr-20000607 * * Added support for the element() scheme described in: * W3C Proposed Recommendation 13 November 2002 * http://www.w3.org/TR/2002/PR-xptr-element-20021113/ * * Copy: See Copyright for the status of this software. * * Author: Daniel Veillard */ #ifndef __XML_XPTR_H__ #define __XML_XPTR_H__ #include #ifdef LIBXML_XPTR_ENABLED #include #include #ifdef __cplusplus extern "C" { #endif #ifdef LIBXML_XPTR_LOCS_ENABLED /* * A Location Set */ typedef struct _xmlLocationSet xmlLocationSet; typedef xmlLocationSet *xmlLocationSetPtr; struct _xmlLocationSet { int locNr; /* number of locations in the set */ int locMax; /* size of the array as allocated */ xmlXPathObjectPtr *locTab;/* array of locations */ }; /* * Handling of location sets. */ XML_DEPRECATED XMLPUBFUN xmlLocationSetPtr xmlXPtrLocationSetCreate (xmlXPathObjectPtr val); XML_DEPRECATED XMLPUBFUN void xmlXPtrFreeLocationSet (xmlLocationSetPtr obj); XML_DEPRECATED XMLPUBFUN xmlLocationSetPtr xmlXPtrLocationSetMerge (xmlLocationSetPtr val1, xmlLocationSetPtr val2); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRange (xmlNodePtr start, int startindex, xmlNodePtr end, int endindex); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangePoints (xmlXPathObjectPtr start, xmlXPathObjectPtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangeNodePoint (xmlNodePtr start, xmlXPathObjectPtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangePointNode (xmlXPathObjectPtr start, xmlNodePtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangeNodes (xmlNodePtr start, xmlNodePtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewLocationSetNodes (xmlNodePtr start, xmlNodePtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewLocationSetNodeSet(xmlNodeSetPtr set); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewRangeNodeObject (xmlNodePtr start, xmlXPathObjectPtr end); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrNewCollapsedRange (xmlNodePtr start); XML_DEPRECATED XMLPUBFUN void xmlXPtrLocationSetAdd (xmlLocationSetPtr cur, xmlXPathObjectPtr val); XML_DEPRECATED XMLPUBFUN xmlXPathObjectPtr xmlXPtrWrapLocationSet (xmlLocationSetPtr val); XML_DEPRECATED XMLPUBFUN void xmlXPtrLocationSetDel (xmlLocationSetPtr cur, xmlXPathObjectPtr val); XML_DEPRECATED XMLPUBFUN void xmlXPtrLocationSetRemove (xmlLocationSetPtr cur, int val); #endif /* LIBXML_XPTR_LOCS_ENABLED */ /* * Functions. */ XMLPUBFUN xmlXPathContextPtr xmlXPtrNewContext (xmlDocPtr doc, xmlNodePtr here, xmlNodePtr origin); XMLPUBFUN xmlXPathObjectPtr xmlXPtrEval (const xmlChar *str, xmlXPathContextPtr ctx); #ifdef LIBXML_XPTR_LOCS_ENABLED XML_DEPRECATED XMLPUBFUN void xmlXPtrRangeToFunction (xmlXPathParserContextPtr ctxt, int nargs); XML_DEPRECATED XMLPUBFUN xmlNodePtr xmlXPtrBuildNodeList (xmlXPathObjectPtr obj); XML_DEPRECATED XMLPUBFUN void xmlXPtrEvalRangePredicate (xmlXPathParserContextPtr ctxt); #endif /* LIBXML_XPTR_LOCS_ENABLED */ #ifdef __cplusplus } #endif #endif /* LIBXML_XPTR_ENABLED */ #endif /* __XML_XPTR_H__ */ ================================================ FILE: thirdparty/64/include/nettle/aes.h ================================================ /* aes.h The aes/rijndael block cipher. Copyright (C) 2001, 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_AES_H_INCLUDED #define NETTLE_AES_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define aes_set_encrypt_key nettle_aes_set_encrypt_key #define aes_set_decrypt_key nettle_aes_set_decrypt_key #define aes_invert_key nettle_aes_invert_key #define aes_encrypt nettle_aes_encrypt #define aes_decrypt nettle_aes_decrypt #define aes128_set_encrypt_key nettle_aes128_set_encrypt_key #define aes128_set_decrypt_key nettle_aes128_set_decrypt_key #define aes128_invert_key nettle_aes128_invert_key #define aes128_encrypt nettle_aes128_encrypt #define aes128_decrypt nettle_aes128_decrypt #define aes192_set_encrypt_key nettle_aes192_set_encrypt_key #define aes192_set_decrypt_key nettle_aes192_set_decrypt_key #define aes192_invert_key nettle_aes192_invert_key #define aes192_encrypt nettle_aes192_encrypt #define aes192_decrypt nettle_aes192_decrypt #define aes256_set_encrypt_key nettle_aes256_set_encrypt_key #define aes256_set_decrypt_key nettle_aes256_set_decrypt_key #define aes256_invert_key nettle_aes256_invert_key #define aes256_encrypt nettle_aes256_encrypt #define aes256_decrypt nettle_aes256_decrypt #define AES_BLOCK_SIZE 16 #define AES128_KEY_SIZE 16 #define AES192_KEY_SIZE 24 #define AES256_KEY_SIZE 32 #define _AES128_ROUNDS 10 #define _AES192_ROUNDS 12 #define _AES256_ROUNDS 14 struct aes128_ctx { uint32_t keys[4 * (_AES128_ROUNDS + 1)]; }; void aes128_set_encrypt_key(struct aes128_ctx *ctx, const uint8_t *key); void aes128_set_decrypt_key(struct aes128_ctx *ctx, const uint8_t *key); void aes128_invert_key(struct aes128_ctx *dst, const struct aes128_ctx *src); void aes128_encrypt(const struct aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void aes128_decrypt(const struct aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); struct aes192_ctx { uint32_t keys[4 * (_AES192_ROUNDS + 1)]; }; void aes192_set_encrypt_key(struct aes192_ctx *ctx, const uint8_t *key); void aes192_set_decrypt_key(struct aes192_ctx *ctx, const uint8_t *key); void aes192_invert_key(struct aes192_ctx *dst, const struct aes192_ctx *src); void aes192_encrypt(const struct aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void aes192_decrypt(const struct aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); struct aes256_ctx { uint32_t keys[4 * (_AES256_ROUNDS + 1)]; }; void aes256_set_encrypt_key(struct aes256_ctx *ctx, const uint8_t *key); void aes256_set_decrypt_key(struct aes256_ctx *ctx, const uint8_t *key); void aes256_invert_key(struct aes256_ctx *dst, const struct aes256_ctx *src); void aes256_encrypt(const struct aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void aes256_decrypt(const struct aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* The older nettle-2.7 AES interface is deprecated, please migrate to the newer interface where each algorithm has a fixed key size. */ /* Variable key size between 128 and 256 bits. But the only valid * values are 16 (128 bits), 24 (192 bits) and 32 (256 bits). */ #define AES_MIN_KEY_SIZE AES128_KEY_SIZE #define AES_MAX_KEY_SIZE AES256_KEY_SIZE #define AES_KEY_SIZE 32 struct aes_ctx { unsigned key_size; /* In octets */ union { struct aes128_ctx ctx128; struct aes192_ctx ctx192; struct aes256_ctx ctx256; } u; }; void aes_set_encrypt_key(struct aes_ctx *ctx, size_t length, const uint8_t *key) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_set_decrypt_key(struct aes_ctx *ctx, size_t length, const uint8_t *key) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_invert_key(struct aes_ctx *dst, const struct aes_ctx *src) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_encrypt(const struct aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; void aes_decrypt(const struct aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; #ifdef __cplusplus } #endif #endif /* NETTLE_AES_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/arcfour.h ================================================ /* arcfour.h The arcfour/rc4 stream cipher. Copyright (C) 2001, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_ARCFOUR_H_INCLUDED #define NETTLE_ARCFOUR_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define arcfour128_set_key nettle_arcfour128_set_key #define arcfour_set_key nettle_arcfour_set_key #define arcfour_crypt nettle_arcfour_crypt /* Minimum and maximum keysizes, and a reasonable default. In * octets.*/ #define ARCFOUR_MIN_KEY_SIZE 1 #define ARCFOUR_MAX_KEY_SIZE 256 #define ARCFOUR_KEY_SIZE 16 #define ARCFOUR128_KEY_SIZE 16 struct arcfour_ctx { uint8_t S[256]; uint8_t i; uint8_t j; }; void arcfour_set_key(struct arcfour_ctx *ctx, size_t length, const uint8_t *key); void arcfour128_set_key(struct arcfour_ctx *ctx, const uint8_t *key); void arcfour_crypt(struct arcfour_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_ARCFOUR_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/arctwo.h ================================================ /* arctwo.h The arctwo/rfc2268 block cipher. Copyright (C) 2004 Simon Josefsson Copyright (C) 2002, 2004, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_ARCTWO_H_INCLUDED #define NETTLE_ARCTWO_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define arctwo_set_key nettle_arctwo_set_key #define arctwo_set_key_ekb nettle_arctwo_set_key_ekb #define arctwo_set_key_gutmann nettle_arctwo_set_key_gutmann #define arctwo40_set_key nettle_arctwo40_set_key #define arctwo64_set_key nettle_arctwo64_set_key #define arctwo128_set_key nettle_arctwo128_set_key #define arctwo128_set_key_gutmann nettle_arctwo128_set_key_gutmann #define arctwo_encrypt nettle_arctwo_encrypt #define arctwo_decrypt nettle_arctwo_decrypt #define ARCTWO_BLOCK_SIZE 8 /* Variable key size from 1 byte to 128 bytes. */ #define ARCTWO_MIN_KEY_SIZE 1 #define ARCTWO_MAX_KEY_SIZE 128 #define ARCTWO_KEY_SIZE 8 struct arctwo_ctx { uint16_t S[64]; }; /* Key expansion function that takes the "effective key bits", 1-1024, as an explicit argument. 0 means maximum key bits. */ void arctwo_set_key_ekb (struct arctwo_ctx *ctx, size_t length, const uint8_t * key, unsigned ekb); /* Equvivalent to arctwo_set_key_ekb, with ekb = 8 * length */ void arctwo_set_key (struct arctwo_ctx *ctx, size_t length, const uint8_t *key); void arctwo40_set_key (struct arctwo_ctx *ctx, const uint8_t *key); void arctwo64_set_key (struct arctwo_ctx *ctx, const uint8_t *key); void arctwo128_set_key (struct arctwo_ctx *ctx, const uint8_t *key); /* Equvivalent to arctwo_set_key_ekb, with ekb = 1024 */ void arctwo_set_key_gutmann (struct arctwo_ctx *ctx, size_t length, const uint8_t *key); void arctwo128_set_key_gutmann (struct arctwo_ctx *ctx, const uint8_t *key); void arctwo_encrypt (struct arctwo_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void arctwo_decrypt (struct arctwo_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_ARCTWO_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/asn1.h ================================================ /* asn1.h Limited support for ASN.1 DER decoding. Copyright (C) 2005 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_ASN1_H_INCLUDED #define NETTLE_ASN1_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define asn1_der_iterator_first nettle_asn1_der_iterator_first #define asn1_der_iterator_next nettle_asn1_der_iterator_next #define asn1_der_decode_constructed nettle_asn1_der_decode_constructed #define asn1_der_decode_constructed_last nettle_asn1_der_decode_constructed_last #define asn1_der_decode_bitstring nettle_asn1_der_decode_bitstring #define asn1_der_decode_bitstring_last nettle_asn1_der_decode_bitstring_last #define asn1_der_get_uint32 nettle_asn1_der_get_uint32 #define asn1_der_get_bignum nettle_asn1_der_get_bignum /* enum asn1_type keeps the class number and the constructive in bits 13-14, and the constructive flag in bit 12. The remaining 14 bits are the tag (although currently, only tags in the range 0-30 are supported). */ enum { ASN1_TYPE_CONSTRUCTED = 1 << 12, ASN1_CLASS_UNIVERSAL = 0, ASN1_CLASS_APPLICATION = 1 << 13, ASN1_CLASS_CONTEXT_SPECIFIC = 2 << 13, ASN1_CLASS_PRIVATE = 3 << 13, ASN1_CLASS_MASK = 3 << 13, ASN1_CLASS_SHIFT = 13, }; enum asn1_type { ASN1_BOOLEAN = 1, ASN1_INTEGER = 2, ASN1_BITSTRING = 3, ASN1_OCTETSTRING = 4, ASN1_NULL = 5, ASN1_IDENTIFIER = 6, ASN1_REAL = 9, ASN1_ENUMERATED = 10, ASN1_UTF8STRING = 12, ASN1_SEQUENCE = 16 | ASN1_TYPE_CONSTRUCTED, ASN1_SET = 17 | ASN1_TYPE_CONSTRUCTED, ASN1_PRINTABLESTRING = 19, ASN1_TELETEXSTRING = 20, ASN1_IA5STRING = 22, ASN1_UTC = 23, ASN1_UNIVERSALSTRING = 28, ASN1_BMPSTRING = 30, }; enum asn1_iterator_result { ASN1_ITERATOR_ERROR, ASN1_ITERATOR_PRIMITIVE, ASN1_ITERATOR_CONSTRUCTED, ASN1_ITERATOR_END, }; /* Parsing DER objects. */ struct asn1_der_iterator { size_t buffer_length; const uint8_t *buffer; /* Next object to parse. */ size_t pos; enum asn1_type type; /* Pointer to the current object */ size_t length; const uint8_t *data; }; /* Initializes the iterator. */ enum asn1_iterator_result asn1_der_iterator_first(struct asn1_der_iterator *iterator, size_t length, const uint8_t *input); enum asn1_iterator_result asn1_der_iterator_next(struct asn1_der_iterator *iterator); /* Starts parsing of a constructed object. */ enum asn1_iterator_result asn1_der_decode_constructed(struct asn1_der_iterator *i, struct asn1_der_iterator *contents); /* For the common case that we have a sequence at the end of the object. Checks that the current object is the final one, and then reinitializes the iterator to parse its ontents. */ enum asn1_iterator_result asn1_der_decode_constructed_last(struct asn1_der_iterator *i); enum asn1_iterator_result asn1_der_decode_bitstring(struct asn1_der_iterator *i, struct asn1_der_iterator *contents); enum asn1_iterator_result asn1_der_decode_bitstring_last(struct asn1_der_iterator *i); /* All these functions return 1 on success, 0 on failure */ int asn1_der_get_uint32(struct asn1_der_iterator *i, uint32_t *x); #ifdef __cplusplus } #endif #endif /* NETTLE_ASN1_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/balloon.h ================================================ /* balloon.h Balloon password-hashing algorithm. Copyright (C) 2022 Zoltan Fridrich Copyright (C) 2022 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* For a description of the algorithm, see: * Boneh, D., Corrigan-Gibbs, H., Schechter, S. (2017, May 12). Balloon Hashing: * A Memory-Hard Function Providing Provable Protection Against Sequential Attacks. * Retrieved Sep 1, 2022, from https://eprint.iacr.org/2016/027.pdf */ #ifndef NETTLE_BALLOON_H_INCLUDED #define NETTLE_BALLOON_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define balloon nettle_balloon #define balloon_itch nettle_balloon_itch #define balloon_sha1 nettle_balloon_sha1 #define balloon_sha256 nettle_balloon_sha256 #define balloon_sha384 nettle_balloon_sha384 #define balloon_sha512 nettle_balloon_sha512 void balloon(void *hash_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); size_t balloon_itch(size_t digest_size, size_t s_cost); void balloon_sha1(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); void balloon_sha256(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); void balloon_sha384(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); void balloon_sha512(size_t s_cost, size_t t_cost, size_t passwd_length, const uint8_t *passwd, size_t salt_length, const uint8_t *salt, uint8_t *scratch, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_BALLOON_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/base16.h ================================================ /* base16.h Hex encoding and decoding, following spki conventions (i.e. allowing whitespace between digits). Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BASE16_H_INCLUDED #define NETTLE_BASE16_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define base16_encode_single nettle_base16_encode_single #define base16_encode_update nettle_base16_encode_update #define base16_decode_init nettle_base16_decode_init #define base16_decode_single nettle_base16_decode_single #define base16_decode_update nettle_base16_decode_update #define base16_decode_final nettle_base16_decode_final /* Base16 encoding */ /* Maximum length of output for base16_encode_update. */ #define BASE16_ENCODE_LENGTH(length) ((length) * 2) /* Encodes a single byte. Always stores two digits in dst[0] and dst[1]. */ void base16_encode_single(char *dst, uint8_t src); /* Always stores BASE16_ENCODE_LENGTH(length) digits in dst. */ void base16_encode_update(char *dst, size_t length, const uint8_t *src); /* Base16 decoding */ /* Maximum length of output for base16_decode_update. */ /* We have at most 4 buffered bits, and a total of (length + 1) * 4 bits. */ #define BASE16_DECODE_LENGTH(length) (((length) + 1) / 2) struct base16_decode_ctx { unsigned char word; /* Leftover bits */ unsigned char bits; /* Number buffered bits */ }; void base16_decode_init(struct base16_decode_ctx *ctx); /* Decodes a single byte. Returns amount of output (0 or 1), or -1 on * errors. */ int base16_decode_single(struct base16_decode_ctx *ctx, uint8_t *dst, char src); /* Returns 1 on success, 0 on error. DST should point to an area of * size at least BASE16_DECODE_LENGTH(length). The amount of data * generated is returned in *DST_LENGTH. */ int base16_decode_update(struct base16_decode_ctx *ctx, size_t *dst_length, uint8_t *dst, size_t src_length, const char *src); /* Returns 1 on success. */ int base16_decode_final(struct base16_decode_ctx *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_BASE16_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/base64.h ================================================ /* base64.h Base-64 encoding and decoding. Copyright (C) 2002 Niels Möller, Dan Egnor This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BASE64_H_INCLUDED #define NETTLE_BASE64_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define base64_encode_init nettle_base64_encode_init #define base64url_encode_init nettle_base64url_encode_init #define base64_encode_single nettle_base64_encode_single #define base64_encode_update nettle_base64_encode_update #define base64_encode_final nettle_base64_encode_final #define base64_encode_raw nettle_base64_encode_raw #define base64_encode_group nettle_base64_encode_group #define base64_decode_init nettle_base64_decode_init #define base64url_decode_init nettle_base64url_decode_init #define base64_decode_single nettle_base64_decode_single #define base64_decode_update nettle_base64_decode_update #define base64_decode_final nettle_base64_decode_final #define BASE64_BINARY_BLOCK_SIZE 3 #define BASE64_TEXT_BLOCK_SIZE 4 /* Base64 encoding */ /* Maximum length of output for base64_encode_update. NOTE: Doesn't * include any padding that base64_encode_final may add. */ /* We have at most 4 buffered bits, and a total of (4 + length * 8) bits. */ #define BASE64_ENCODE_LENGTH(length) (((length) * 8 + 4)/6) /* Maximum length of output generated by base64_encode_final. */ #define BASE64_ENCODE_FINAL_LENGTH 3 /* Exact length of output generated by base64_encode_raw, including * padding. */ #define BASE64_ENCODE_RAW_LENGTH(length) ((((length) + 2)/3)*4) struct base64_encode_ctx { const char *alphabet; /* Alphabet to use for encoding */ unsigned short word; /* Leftover bits */ unsigned char bits; /* Number of bits, always 0, 2, or 4. */ }; /* Initialize encoding context for base-64 */ void base64_encode_init(struct base64_encode_ctx *ctx); /* Initialize encoding context for URL safe alphabet, RFC 4648. */ void base64url_encode_init(struct base64_encode_ctx *ctx); /* Encodes a single byte. Returns amount of output (always 1 or 2). */ size_t base64_encode_single(struct base64_encode_ctx *ctx, char *dst, uint8_t src); /* Returns the number of output characters. DST should point to an * area of size at least BASE64_ENCODE_LENGTH(length). */ size_t base64_encode_update(struct base64_encode_ctx *ctx, char *dst, size_t length, const uint8_t *src); /* DST should point to an area of size at least * BASE64_ENCODE_FINAL_LENGTH */ size_t base64_encode_final(struct base64_encode_ctx *ctx, char *dst); /* Lower level functions */ /* Encodes a string in one go, including any padding at the end. * Generates exactly BASE64_ENCODE_RAW_LENGTH(length) bytes of output. * Supports overlapped operation, if src <= dst. FIXME: Use of overlap * is deprecated, if needed there should be a separate public fucntion * to do that.*/ void base64_encode_raw(char *dst, size_t length, const uint8_t *src); void base64_encode_group(char *dst, uint32_t group); /* Base64 decoding */ /* Maximum length of output for base64_decode_update. */ /* We have at most 6 buffered bits, and a total of (length + 1) * 6 bits. */ #define BASE64_DECODE_LENGTH(length) ((((length) + 1) * 6) / 8) struct base64_decode_ctx { const signed char *table; /* Decoding table */ unsigned short word; /* Leftover bits */ unsigned char bits; /* Number buffered bits */ /* Number of padding characters encountered */ unsigned char padding; }; /* Initialize decoding context for base-64 */ void base64_decode_init(struct base64_decode_ctx *ctx); /* Initialize encoding context for URL safe alphabet, RFC 4648. */ void base64url_decode_init(struct base64_decode_ctx *ctx); /* Decodes a single byte. Returns amount of output (0 or 1), or -1 on * errors. */ int base64_decode_single(struct base64_decode_ctx *ctx, uint8_t *dst, char src); /* Returns 1 on success, 0 on error. DST should point to an area of * size at least BASE64_DECODE_LENGTH(length). The amount of data * generated is returned in *DST_LENGTH. */ int base64_decode_update(struct base64_decode_ctx *ctx, size_t *dst_length, uint8_t *dst, size_t src_length, const char *src); /* Returns 1 on success. */ int base64_decode_final(struct base64_decode_ctx *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_BASE64_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/bignum.h ================================================ /* bignum.h Bignum operations that are missing from gmp. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BIGNUM_H_INCLUDED #define NETTLE_BIGNUM_H_INCLUDED #include "nettle-types.h" /* For NETTLE_USE_MINI_GMP */ #include "version.h" #if NETTLE_USE_MINI_GMP # include "mini-gmp.h" # define GMP_NUMB_MASK (~(mp_limb_t) 0) /* Side-channel silent powm not available in mini-gmp. */ # define mpz_powm_sec mpz_powm #else # include #endif #ifdef __cplusplus extern "C" { #endif /* Size needed for signed encoding, including extra sign byte if * necessary. */ size_t nettle_mpz_sizeinbase_256_s(const mpz_t x); /* Size needed for unsigned encoding */ size_t nettle_mpz_sizeinbase_256_u(const mpz_t x); /* Writes an integer as length octets, using big endian byte order, * and two's complement for negative numbers. */ void nettle_mpz_get_str_256(size_t length, uint8_t *s, const mpz_t x); /* Reads a big endian, two's complement, integer. */ void nettle_mpz_set_str_256_s(mpz_t x, size_t length, const uint8_t *s); void nettle_mpz_init_set_str_256_s(mpz_t x, size_t length, const uint8_t *s); /* Similar, but for unsigned format. These function don't interpret * the most significant bit as the sign. */ void nettle_mpz_set_str_256_u(mpz_t x, size_t length, const uint8_t *s); void nettle_mpz_init_set_str_256_u(mpz_t x, size_t length, const uint8_t *s); /* Returns a uniformly distributed random number 0 <= x < 2^n */ void nettle_mpz_random_size(mpz_t x, void *ctx, nettle_random_func *random, unsigned bits); /* Returns a number x, almost uniformly random in the range * 0 <= x < n. */ void nettle_mpz_random(mpz_t x, void *ctx, nettle_random_func *random, const mpz_t n); void nettle_random_prime(mpz_t p, unsigned bits, int top_bits_set, void *ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress); /* sexp parsing */ struct sexp_iterator; /* If LIMIT is non-zero, the number must be at most LIMIT bits. * Implies sexp_iterator_next. */ int nettle_mpz_set_sexp(mpz_t x, unsigned limit, struct sexp_iterator *i); /* der parsing */ struct asn1_der_iterator; int nettle_asn1_der_get_bignum(struct asn1_der_iterator *iterator, mpz_t x, unsigned max_bits); #ifdef __cplusplus } #endif #endif /* NETTLE_BIGNUM_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/blowfish.h ================================================ /* blowfish.h Blowfish block cipher. Copyright (C) 2014 Niels Möller Copyright (C) 1998, 2001 FSF, Ray Dassen, Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BLOWFISH_H_INCLUDED #define NETTLE_BLOWFISH_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define blowfish_set_key nettle_blowfish_set_key #define blowfish128_set_key nettle_blowfish128_set_key #define blowfish_encrypt nettle_blowfish_encrypt #define blowfish_decrypt nettle_blowfish_decrypt #define blowfish_bcrypt_hash nettle_blowfish_bcrypt_hash #define blowfish_bcrypt_verify nettle_blowfish_bcrypt_verify #define BLOWFISH_BLOCK_SIZE 8 /* Variable key size between 64 and 448 bits. */ #define BLOWFISH_MIN_KEY_SIZE 8 #define BLOWFISH_MAX_KEY_SIZE 56 /* Default to 128 bits */ #define BLOWFISH_KEY_SIZE 16 #define BLOWFISH128_KEY_SIZE 16 #define _BLOWFISH_ROUNDS 16 #define BLOWFISH_BCRYPT_HASH_SIZE (60 + 1) /* Including null-terminator */ #define BLOWFISH_BCRYPT_BINSALT_SIZE 16 /* Binary string size */ struct blowfish_ctx { uint32_t s[4][256]; uint32_t p[_BLOWFISH_ROUNDS+2]; }; /* Returns 0 for weak keys, otherwise 1. */ int blowfish_set_key(struct blowfish_ctx *ctx, size_t length, const uint8_t *key); int blowfish128_set_key(struct blowfish_ctx *ctx, const uint8_t *key); void blowfish_encrypt(const struct blowfish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void blowfish_decrypt(const struct blowfish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* dst parameter must point to a buffer of minimally * BLOWFISH_BCRYPT_HASH_SIZE bytes */ int blowfish_bcrypt_hash(uint8_t *dst, size_t lenkey, const uint8_t *key, size_t lenscheme, const uint8_t *scheme, int log2rounds, const uint8_t *salt); int blowfish_bcrypt_verify(size_t lenkey, const uint8_t *key, size_t lenhashed, const uint8_t *hashed); #ifdef __cplusplus } #endif #endif /* NETTLE_BLOWFISH_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/buffer.h ================================================ /* buffer.h A bare-bones string stream. Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_BUFFER_H_INCLUDED #define NETTLE_BUFFER_H_INCLUDED #include "realloc.h" #ifdef __cplusplus extern "C" { #endif struct nettle_buffer { uint8_t *contents; /* Allocated size */ size_t alloc; void *realloc_ctx; nettle_realloc_func *realloc; /* Current size */ size_t size; }; /* Initializes a buffer that uses plain realloc */ void nettle_buffer_init(struct nettle_buffer *buffer); void nettle_buffer_init_realloc(struct nettle_buffer *buffer, void *realloc_ctx, nettle_realloc_func *realloc); /* Initializes a buffer of fix size */ void nettle_buffer_init_size(struct nettle_buffer *buffer, size_t length, uint8_t *space); void nettle_buffer_clear(struct nettle_buffer *buffer); /* Resets the buffer, without freeing the buffer space. */ void nettle_buffer_reset(struct nettle_buffer *buffer); int nettle_buffer_grow(struct nettle_buffer *buffer, size_t length); #define NETTLE_BUFFER_PUTC(buffer, c) \ ( (((buffer)->size < (buffer)->alloc) || nettle_buffer_grow((buffer), 1)) \ && ((buffer)->contents[(buffer)->size++] = (c), 1) ) int nettle_buffer_write(struct nettle_buffer *buffer, size_t length, const uint8_t *data); /* Like nettle_buffer_write, but instead of copying data to the * buffer, it returns a pointer to the area where the caller can copy * the data. The pointer is valid only until the next call that can * reallocate the buffer. */ uint8_t * nettle_buffer_space(struct nettle_buffer *buffer, size_t length); /* Copy the contents of SRC to the end of DST. */ int nettle_buffer_copy(struct nettle_buffer *dst, const struct nettle_buffer *src); #ifdef __cplusplus } #endif #endif /* NETTLE_BUFFER_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/camellia.h ================================================ /* camellia.h Copyright (C) 2006,2007 NTT (Nippon Telegraph and Telephone Corporation). Copyright (C) 2010, 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CAMELLIA_H_INCLUDED #define NETTLE_CAMELLIA_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define camellia128_set_encrypt_key nettle_camellia128_set_encrypt_key #define camellia128_set_decrypt_key nettle_camellia_set_decrypt_key #define camellia128_invert_key nettle_camellia128_invert_key #define camellia128_crypt nettle_camellia128_crypt #define camellia192_set_encrypt_key nettle_camellia192_set_encrypt_key #define camellia192_set_decrypt_key nettle_camellia192_set_decrypt_key #define camellia256_set_encrypt_key nettle_camellia256_set_encrypt_key #define camellia256_set_decrypt_key nettle_camellia256_set_decrypt_key #define camellia256_invert_key nettle_camellia256_invert_key #define camellia256_crypt nettle_camellia256_crypt #define CAMELLIA_BLOCK_SIZE 16 /* Valid key sizes are 128, 192 or 256 bits (16, 24 or 32 bytes) */ #define CAMELLIA128_KEY_SIZE 16 #define CAMELLIA192_KEY_SIZE 24 #define CAMELLIA256_KEY_SIZE 32 /* For 128-bit keys, there are 18 regular rounds, pre- and post-whitening, and two FL and FLINV rounds, using a total of 26 subkeys, each of 64 bit. For 192- and 256-bit keys, there are 6 additional regular rounds and one additional FL and FLINV, using a total of 34 subkeys. */ /* The clever combination of subkeys imply one of the pre- and post-whitening keys is folded with the round keys, so that subkey #1 and the last one (#25 or #33) is not used. The result is that we have only 24 or 32 subkeys at the end of key setup. */ #define _CAMELLIA128_NKEYS 24 #define _CAMELLIA256_NKEYS 32 struct camellia128_ctx { uint64_t keys[_CAMELLIA128_NKEYS]; }; void camellia128_set_encrypt_key(struct camellia128_ctx *ctx, const uint8_t *key); void camellia128_set_decrypt_key(struct camellia128_ctx *ctx, const uint8_t *key); void camellia128_invert_key(struct camellia128_ctx *dst, const struct camellia128_ctx *src); void camellia128_crypt(const struct camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); struct camellia256_ctx { uint64_t keys[_CAMELLIA256_NKEYS]; }; void camellia256_set_encrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); void camellia256_set_decrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); void camellia256_invert_key(struct camellia256_ctx *dst, const struct camellia256_ctx *src); void camellia256_crypt(const struct camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* camellia192 is the same as camellia256, except for the key schedule. */ /* Slightly ugly with a #define on a struct tag, since it might cause surprises if also used as a name of a variable. */ #define camellia192_ctx camellia256_ctx void camellia192_set_encrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); void camellia192_set_decrypt_key(struct camellia256_ctx *ctx, const uint8_t *key); #define camellia192_invert_key camellia256_invert_key #define camellia192_crypt camellia256_crypt #ifdef __cplusplus } #endif #endif /* NETTLE_CAMELLIA_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/cast128.h ================================================ /* cast128.h The CAST-128 block cipher. Copyright (C) 2001, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CAST128_H_INCLUDED #define NETTLE_CAST128_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cast5_set_key nettle_cast5_set_key #define cast128_set_key nettle_cast128_set_key #define cast128_encrypt nettle_cast128_encrypt #define cast128_decrypt nettle_cast128_decrypt #define CAST128_BLOCK_SIZE 8 /* Variable key size between 40 and 128. */ #define CAST5_MIN_KEY_SIZE 5 #define CAST5_MAX_KEY_SIZE 16 #define CAST128_KEY_SIZE 16 struct cast128_ctx { unsigned rounds; /* Number of rounds to use, 12 or 16 */ /* Expanded key, rotations (5 bits only) and 32-bit masks. */ unsigned char Kr[16]; uint32_t Km[16]; }; /* Using variable key size. */ void cast5_set_key(struct cast128_ctx *ctx, size_t length, const uint8_t *key); void cast128_set_key(struct cast128_ctx *ctx, const uint8_t *key); void cast128_encrypt(const struct cast128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void cast128_decrypt(const struct cast128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CAST128_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/cbc.h ================================================ /* cbc.h Cipher block chaining mode. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CBC_H_INCLUDED #define NETTLE_CBC_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cbc_encrypt nettle_cbc_encrypt #define cbc_decrypt nettle_cbc_decrypt #define cbc_aes128_encrypt nettle_cbc_aes128_encrypt #define cbc_aes192_encrypt nettle_cbc_aes192_encrypt #define cbc_aes256_encrypt nettle_cbc_aes256_encrypt void cbc_encrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cbc_decrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); #define CBC_CTX(type, size) \ { type ctx; uint8_t iv[size]; } #define CBC_SET_IV(ctx, data) \ memcpy((ctx)->iv, (data), sizeof((ctx)->iv)) /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CBC_ENCRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cbc_encrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CBC_DECRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cbc_decrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) void cbc_aes128_encrypt(const struct aes128_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cbc_aes192_encrypt(const struct aes192_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cbc_aes256_encrypt(const struct aes256_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CBC_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/ccm.h ================================================ /* ccm.h Counter with CBC-MAC mode, specified by NIST, http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf Copyright (C) 2014 Exegin Technologies Limited Copyright (C) 2014 Owen Kirby Contributed to GNU Nettle by Owen Kirby This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* NIST SP800-38C doesn't specify the particular formatting and * counter generation algorithm for CCM, but it does include an * example algorithm. This example has become the de-factor standard, * and has been adopted by both the IETF and IEEE across a wide * variety of protocols. */ #ifndef NETTLE_CCM_H_INCLUDED #define NETTLE_CCM_H_INCLUDED #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ccm_set_nonce nettle_ccm_set_nonce #define ccm_update nettle_ccm_update #define ccm_encrypt nettle_ccm_encrypt #define ccm_decrypt nettle_ccm_decrypt #define ccm_digest nettle_ccm_digest #define ccm_encrypt_message nettle_ccm_encrypt_message #define ccm_decrypt_message nettle_ccm_decrypt_message #define ccm_aes128_set_key nettle_ccm_aes128_set_key #define ccm_aes128_set_nonce nettle_ccm_aes128_set_nonce #define ccm_aes128_update nettle_ccm_aes128_update #define ccm_aes128_encrypt nettle_ccm_aes128_encrypt #define ccm_aes128_decrypt nettle_ccm_aes128_decrypt #define ccm_aes128_digest nettle_ccm_aes128_digest #define ccm_aes128_encrypt_message nettle_ccm_aes128_encrypt_message #define ccm_aes128_decrypt_message nettle_ccm_aes128_decrypt_message #define ccm_aes192_set_key nettle_ccm_aes192_set_key #define ccm_aes192_set_nonce nettle_ccm_aes192_set_nonce #define ccm_aes192_update nettle_ccm_aes192_update #define ccm_aes192_encrypt nettle_ccm_aes192_encrypt #define ccm_aes192_decrypt nettle_ccm_aes192_decrypt #define ccm_aes192_digest nettle_ccm_aes192_digest #define ccm_aes192_encrypt_message nettle_ccm_aes192_encrypt_message #define ccm_aes192_decrypt_message nettle_ccm_aes192_decrypt_message #define ccm_aes256_set_key nettle_ccm_aes256_set_key #define ccm_aes256_set_nonce nettle_ccm_aes256_set_nonce #define ccm_aes256_update nettle_ccm_aes256_update #define ccm_aes256_encrypt nettle_ccm_aes256_encrypt #define ccm_aes256_decrypt nettle_ccm_aes256_decrypt #define ccm_aes256_digest nettle_ccm_aes256_digest #define ccm_aes256_encrypt_message nettle_ccm_aes256_encrypt_message #define ccm_aes256_decrypt_message nettle_ccm_aes256_decrypt_message /* For CCM, the block size of the block cipher shall be 128 bits. */ #define CCM_BLOCK_SIZE 16 #define CCM_DIGEST_SIZE 16 #define CCM_MIN_NONCE_SIZE 7 #define CCM_MAX_NONCE_SIZE 14 /* Maximum cleartext message size, as a function of the nonce size N. The length field is L octets, with L = 15 - N, and then the maximum size M = 2^{8L} - 1. */ #define CCM_MAX_MSG_SIZE(N) \ ((sizeof(size_t) + (N) <= 15) \ ? ~(size_t) 0 \ : ((size_t) 1 << (8*(15 - N))) - 1) /* Per-message state */ struct ccm_ctx { union nettle_block16 ctr; /* Counter for CTR encryption. */ union nettle_block16 tag; /* CBC-MAC message tag. */ /* Length of data processed by the CBC-MAC modulus the block size */ unsigned int blength; }; /* * CCM mode requires the adata and message lengths when building the IV, which * prevents streaming processing and it incompatible with the AEAD API. */ void ccm_set_nonce(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t noncelen, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_update(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, const uint8_t *data); void ccm_encrypt(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void ccm_decrypt(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void ccm_digest(struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); /* * All-in-one encryption and decryption API: * tlength = sizeof(digest) * mlength = sizeof(cleartext) * clength = sizeof(ciphertext) = mlength + tlength * * The ciphertext will contain the encrypted payload with the message digest * appended to the end. */ void ccm_encrypt_message(const void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); /* * The decryption function will write the plaintext to dst and parse the digest * from the final tlength bytes of the ciphertext. If the digest matched the * value computed during decryption then this will return 1, or it will return * 0 if the digest was invalid. */ int ccm_decrypt_message(const void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); /* CCM Mode with AES-128 */ struct ccm_aes128_ctx { struct ccm_ctx ccm; struct aes128_ctx cipher; }; void ccm_aes128_set_key(struct ccm_aes128_ctx *ctx, const uint8_t *key); void ccm_aes128_set_nonce(struct ccm_aes128_ctx *ctx, size_t length, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_aes128_update (struct ccm_aes128_ctx *ctx, size_t length, const uint8_t *data); void ccm_aes128_encrypt(struct ccm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes128_decrypt(struct ccm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes128_digest(struct ccm_aes128_ctx *ctx, size_t length, uint8_t *digest); /* FIXME: For next API/ABI break: first argument should be const struct aes128_ctx *, and similarly for other ccm_*_message functions below. */ void ccm_aes128_encrypt_message(struct ccm_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ccm_aes128_decrypt_message(struct ccm_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); struct ccm_aes192_ctx { struct ccm_ctx ccm; struct aes192_ctx cipher; }; /* CCM Mode with AES-192 */ void ccm_aes192_set_key(struct ccm_aes192_ctx *ctx, const uint8_t *key); void ccm_aes192_set_nonce(struct ccm_aes192_ctx *ctx, size_t length, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_aes192_update(struct ccm_aes192_ctx *ctx, size_t length, const uint8_t *data); void ccm_aes192_encrypt(struct ccm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes192_decrypt(struct ccm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes192_digest(struct ccm_aes192_ctx *ctx, size_t length, uint8_t *digest); void ccm_aes192_encrypt_message(struct ccm_aes192_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ccm_aes192_decrypt_message(struct ccm_aes192_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); /* CCM Mode with AES-256 */ struct ccm_aes256_ctx { struct ccm_ctx ccm; struct aes256_ctx cipher; }; void ccm_aes256_set_key(struct ccm_aes256_ctx *ctx, const uint8_t *key); void ccm_aes256_set_nonce(struct ccm_aes256_ctx *ctx, size_t length, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen); void ccm_aes256_update(struct ccm_aes256_ctx *ctx, size_t length, const uint8_t *data); void ccm_aes256_encrypt(struct ccm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes256_decrypt(struct ccm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void ccm_aes256_digest(struct ccm_aes256_ctx *ctx, size_t length, uint8_t *digest); void ccm_aes256_encrypt_message(struct ccm_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ccm_aes256_decrypt_message(struct ccm_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CCM_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/cfb.h ================================================ /* cfb.h Cipher feedback mode. Copyright (C) 2015, 2017 Dmitry Eremin-Solenikov Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CFB_H_INCLUDED #define NETTLE_CFB_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cfb_encrypt nettle_cfb_encrypt #define cfb_decrypt nettle_cfb_decrypt #define cfb8_encrypt nettle_cfb8_encrypt #define cfb8_decrypt nettle_cfb8_decrypt void cfb_encrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cfb_decrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cfb8_encrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); void cfb8_decrypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src); #define CFB_CTX(type, size) \ { type ctx; uint8_t iv[size]; } #define CFB_SET_IV(ctx, data) \ memcpy((ctx)->iv, (data), sizeof((ctx)->iv)) #define CFB8_CTX CFB_CTX #define CFB8_SET_IV CFB_SET_IV /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CFB_ENCRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb_encrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CFB_DECRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb_decrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CFB8_ENCRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb8_encrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #define CFB8_DECRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : cfb8_decrypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->iv), (self)->iv, \ (length), (dst), (src))) #ifdef __cplusplus } #endif #endif /* NETTLE_CFB_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/chacha-poly1305.h ================================================ /* chacha-poly1305.h AEAD mechanism based on chacha and poly1305. See draft-agl-tls-chacha20poly1305-04. Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CHACHA_POLY1305_H_INCLUDED #define NETTLE_CHACHA_POLY1305_H_INCLUDED #include "chacha.h" #include "poly1305.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define chacha_poly1305_set_key nettle_chacha_poly1305_set_key #define chacha_poly1305_set_nonce nettle_chacha_poly1305_set_nonce #define chacha_poly1305_update nettle_chacha_poly1305_update #define chacha_poly1305_decrypt nettle_chacha_poly1305_decrypt #define chacha_poly1305_encrypt nettle_chacha_poly1305_encrypt #define chacha_poly1305_digest nettle_chacha_poly1305_digest #define CHACHA_POLY1305_BLOCK_SIZE 64 /* FIXME: Any need for 128-bit variant? */ #define CHACHA_POLY1305_KEY_SIZE 32 #define CHACHA_POLY1305_NONCE_SIZE CHACHA_NONCE96_SIZE #define CHACHA_POLY1305_DIGEST_SIZE 16 struct chacha_poly1305_ctx { struct chacha_ctx chacha; struct poly1305_ctx poly1305; union nettle_block16 s; uint64_t auth_size; uint64_t data_size; /* poly1305 block */ uint8_t block[POLY1305_BLOCK_SIZE]; unsigned index; }; void chacha_poly1305_set_key (struct chacha_poly1305_ctx *ctx, const uint8_t *key); void chacha_poly1305_set_nonce (struct chacha_poly1305_ctx *ctx, const uint8_t *nonce); void chacha_poly1305_update (struct chacha_poly1305_ctx *ctx, size_t length, const uint8_t *data); void chacha_poly1305_encrypt (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void chacha_poly1305_decrypt (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void chacha_poly1305_digest (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_CHACHA_POLY1305_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/chacha.h ================================================ /* chacha.h The ChaCha stream cipher. Copyright (C) 2013 Joachim Strömbergson Copyright (C) 2012 Simon Josefsson Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CHACHA_H_INCLUDED #define NETTLE_CHACHA_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define chacha_set_key nettle_chacha_set_key #define chacha_set_nonce nettle_chacha_set_nonce #define chacha_set_nonce96 nettle_chacha_set_nonce96 #define chacha_set_counter nettle_chacha_set_counter #define chacha_set_counter32 nettle_chacha_set_counter32 #define chacha_crypt nettle_chacha_crypt #define chacha_crypt32 nettle_chacha_crypt32 /* Currently, only 256-bit keys are supported. */ #define CHACHA_KEY_SIZE 32 #define CHACHA_BLOCK_SIZE 64 #define CHACHA_NONCE_SIZE 8 #define CHACHA_NONCE96_SIZE 12 #define CHACHA_COUNTER_SIZE 8 #define CHACHA_COUNTER32_SIZE 4 #define _CHACHA_STATE_LENGTH 16 struct chacha_ctx { /* Indices 0-3 holds a constant (SIGMA or TAU). Indices 4-11 holds the key. Indices 12-13 holds the block counter. Indices 14-15 holds the IV: This creates the state matrix: C C C C K K K K K K K K B B I I */ uint32_t state[_CHACHA_STATE_LENGTH]; }; void chacha_set_key(struct chacha_ctx *ctx, const uint8_t *key); void chacha_set_nonce(struct chacha_ctx *ctx, const uint8_t *nonce); void chacha_set_nonce96(struct chacha_ctx *ctx, const uint8_t *nonce); void chacha_set_counter(struct chacha_ctx *ctx, const uint8_t *counter); void chacha_set_counter32(struct chacha_ctx *ctx, const uint8_t *counter); void chacha_crypt(struct chacha_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void chacha_crypt32(struct chacha_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_CHACHA_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/cmac.h ================================================ /* cmac.h CMAC mode, as specified in RFC4493 Copyright (C) 2017 Red Hat, Inc. Contributed by Nikos Mavrogiannopoulos This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CMAC_H_INCLUDED #define NETTLE_CMAC_H_INCLUDED #include "aes.h" #include "des.h" #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif #define CMAC128_DIGEST_SIZE 16 #define CMAC64_DIGEST_SIZE 8 #define cmac128_set_key nettle_cmac128_set_key #define cmac128_init nettle_cmac128_init #define cmac128_update nettle_cmac128_update #define cmac128_digest nettle_cmac128_digest #define cmac_aes128_set_key nettle_cmac_aes128_set_key #define cmac_aes128_update nettle_cmac_aes128_update #define cmac_aes128_digest nettle_cmac_aes128_digest #define cmac_aes256_set_key nettle_cmac_aes256_set_key #define cmac_aes256_update nettle_cmac_aes256_update #define cmac_aes256_digest nettle_cmac_aes256_digest #define cmac64_set_key nettle_cmac64_set_key #define cmac64_init nettle_cmac64_init #define cmac64_update nettle_cmac64_update #define cmac64_digest nettle_cmac64_digest #define cmac_des3_set_key nettle_cmac_des3_set_key #define cmac_des3_update nettle_cmac_des3_update #define cmac_des3_digest nettle_cmac_des3_digest struct cmac128_key { union nettle_block16 K1; union nettle_block16 K2; }; struct cmac128_ctx { /* MAC state */ union nettle_block16 X; /* Block buffer */ union nettle_block16 block; size_t index; }; struct cmac64_key { union nettle_block8 K1; union nettle_block8 K2; }; struct cmac64_ctx { /* MAC state */ union nettle_block8 X; /* Block buffer */ union nettle_block8 block; size_t index; }; void cmac128_set_key(struct cmac128_key *key, const void *cipher, nettle_cipher_func *encrypt); void cmac128_init(struct cmac128_ctx *ctx); void cmac128_update(struct cmac128_ctx *ctx, const void *cipher, nettle_cipher_func *encrypt, size_t msg_len, const uint8_t *msg); void cmac128_digest(struct cmac128_ctx *ctx, const struct cmac128_key *key, const void *cipher, nettle_cipher_func *encrypt, unsigned length, uint8_t *digest); #define CMAC128_CTX(type) \ { struct cmac128_key key; struct cmac128_ctx ctx; type cipher; } /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CMAC128_SET_KEY(self, set_key, encrypt, cmac_key) \ do { \ (set_key)(&(self)->cipher, (cmac_key)); \ if (0) (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ cmac128_set_key(&(self)->key, &(self)->cipher, \ (nettle_cipher_func *) (encrypt)); \ cmac128_init(&(self)->ctx); \ } while (0) #define CMAC128_UPDATE(self, encrypt, length, src) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac128_update(&(self)->ctx, &(self)->cipher, \ (nettle_cipher_func *)encrypt, \ (length), (src))) #define CMAC128_DIGEST(self, encrypt, length, digest) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac128_digest(&(self)->ctx, &(self)->key, \ &(self)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (digest))) void cmac64_set_key(struct cmac64_key *key, const void *cipher, nettle_cipher_func *encrypt); void cmac64_init(struct cmac64_ctx *ctx); void cmac64_update(struct cmac64_ctx *ctx, const void *cipher, nettle_cipher_func *encrypt, size_t msg_len, const uint8_t *msg); void cmac64_digest(struct cmac64_ctx *ctx, const struct cmac64_key *key, const void *cipher, nettle_cipher_func *encrypt, unsigned length, uint8_t *digest); #define CMAC64_CTX(type) \ { struct cmac64_key key; struct cmac64_ctx ctx; type cipher; } /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define CMAC64_SET_KEY(self, set_key, encrypt, cmac_key) \ do { \ (set_key)(&(self)->cipher, (cmac_key)); \ if (0) (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ cmac64_set_key(&(self)->key, &(self)->cipher, \ (nettle_cipher_func *) (encrypt)); \ cmac64_init(&(self)->ctx); \ } while (0) #define CMAC64_UPDATE(self, encrypt, length, src) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac64_update(&(self)->ctx, &(self)->cipher, \ (nettle_cipher_func *)encrypt, \ (length), (src))) #define CMAC64_DIGEST(self, encrypt, length, digest) \ (0 ? (encrypt)(&(self)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : cmac64_digest(&(self)->ctx, &(self)->key, \ &(self)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (digest))) struct cmac_aes128_ctx CMAC128_CTX(struct aes128_ctx); void cmac_aes128_set_key(struct cmac_aes128_ctx *ctx, const uint8_t *key); void cmac_aes128_update(struct cmac_aes128_ctx *ctx, size_t length, const uint8_t *data); void cmac_aes128_digest(struct cmac_aes128_ctx *ctx, size_t length, uint8_t *digest); struct cmac_aes256_ctx CMAC128_CTX(struct aes256_ctx); void cmac_aes256_set_key(struct cmac_aes256_ctx *ctx, const uint8_t *key); void cmac_aes256_update(struct cmac_aes256_ctx *ctx, size_t length, const uint8_t *data); void cmac_aes256_digest(struct cmac_aes256_ctx *ctx, size_t length, uint8_t *digest); struct cmac_des3_ctx CMAC64_CTX(struct des3_ctx); void cmac_des3_set_key(struct cmac_des3_ctx *ctx, const uint8_t *key); void cmac_des3_update(struct cmac_des3_ctx *ctx, size_t length, const uint8_t *data); void cmac_des3_digest(struct cmac_des3_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* CMAC_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/ctr.h ================================================ /* ctr.h Counter mode, using an network byte order incremented counter, matching the testcases of NIST 800-38A. Copyright (C) 2005 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CTR_H_INCLUDED #define NETTLE_CTR_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ctr_crypt nettle_ctr_crypt void ctr_crypt(const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *ctr, size_t length, uint8_t *dst, const uint8_t *src); #define CTR_CTX(type, size) \ { type ctx; uint8_t ctr[size]; } #define CTR_SET_COUNTER(ctx, data) \ memcpy((ctx)->ctr, (data), sizeof((ctx)->ctr)) #define CTR_CRYPT(self, f, length, dst, src) \ (0 ? ((f)(&(self)->ctx, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0)) \ : ctr_crypt((void *) &(self)->ctx, \ (nettle_cipher_func *) (f), \ sizeof((self)->ctr), (self)->ctr, \ (length), (dst), (src))) #ifdef __cplusplus } #endif #endif /* NETTLE_CTR_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/curve25519.h ================================================ /* curve25519.h Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CURVE25519_H #define NETTLE_CURVE25519_H #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define curve25519_mul_g nettle_curve25519_mul_g #define curve25519_mul nettle_curve25519_mul #define CURVE25519_SIZE 32 /* Indicates that curve25519_mul conforms to RFC 7748. */ #define NETTLE_CURVE25519_RFC7748 1 void curve25519_mul_g (uint8_t *q, const uint8_t *n); void curve25519_mul (uint8_t *q, const uint8_t *n, const uint8_t *p); #ifdef __cplusplus } #endif #endif /* NETTLE_CURVE25519_H */ ================================================ FILE: thirdparty/64/include/nettle/curve448.h ================================================ /* curve448.h Copyright (C) 2017 Daiki Ueno Copyright (C) 2017 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_CURVE448_H #define NETTLE_CURVE448_H #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define curve448_mul_g nettle_curve448_mul_g #define curve448_mul nettle_curve448_mul #define CURVE448_SIZE 56 void curve448_mul_g (uint8_t *q, const uint8_t *n); void curve448_mul (uint8_t *q, const uint8_t *n, const uint8_t *p); #ifdef __cplusplus } #endif #endif /* NETTLE_CURVE448_H */ ================================================ FILE: thirdparty/64/include/nettle/des.h ================================================ /* des.h The des block cipher. And triple des. Copyright (C) 1992 Dana L. How Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* * des - fast & portable DES encryption & decryption. * Copyright (C) 1992 Dana L. How * Please see the file `../lib/descore.README' for the complete copyright * notice. * * Slightly edited by Niels Möller, 1997 */ #ifndef NETTLE_DES_H_INCLUDED #define NETTLE_DES_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define des_set_key nettle_des_set_key #define des_encrypt nettle_des_encrypt #define des_decrypt nettle_des_decrypt #define des_check_parity nettle_des_check_parity #define des_fix_parity nettle_des_fix_parity #define des3_set_key nettle_des3_set_key #define des3_encrypt nettle_des3_encrypt #define des3_decrypt nettle_des3_decrypt #define DES_KEY_SIZE 8 #define DES_BLOCK_SIZE 8 /* Expanded key length */ #define _DES_KEY_LENGTH 32 struct des_ctx { uint32_t key[_DES_KEY_LENGTH]; }; /* Returns 1 for good keys and 0 for weak keys. */ int des_set_key(struct des_ctx *ctx, const uint8_t *key); void des_encrypt(const struct des_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void des_decrypt(const struct des_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); int des_check_parity(size_t length, const uint8_t *key); void des_fix_parity(size_t length, uint8_t *dst, const uint8_t *src); #define DES3_KEY_SIZE 24 #define DES3_BLOCK_SIZE DES_BLOCK_SIZE struct des3_ctx { struct des_ctx des[3]; }; /* Returns 1 for good keys and 0 for weak keys. */ int des3_set_key(struct des3_ctx *ctx, const uint8_t *key); void des3_encrypt(const struct des3_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void des3_decrypt(const struct des3_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_DES_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/dsa-compat.h ================================================ /* dsa-compat.h Old DSA publickey interface. Copyright (C) 2002, 2013, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_DSA_COMPAT_H_INCLUDED #define NETTLE_DSA_COMPAT_H_INCLUDED #include "dsa.h" #include "sha1.h" #include "sha2.h" /* Name mangling */ #define dsa_public_key_init nettle_dsa_public_key_init #define dsa_public_key_clear nettle_dsa_public_key_clear #define dsa_private_key_init nettle_dsa_private_key_init #define dsa_private_key_clear nettle_dsa_private_key_clear #define dsa_sha1_sign nettle_dsa_sha1_sign #define dsa_sha1_verify nettle_dsa_sha1_verify #define dsa_sha256_sign nettle_dsa_sha256_sign #define dsa_sha256_verify nettle_dsa_sha256_verify #define dsa_sha1_sign_digest nettle_dsa_sha1_sign_digest #define dsa_sha1_verify_digest nettle_dsa_sha1_verify_digest #define dsa_sha256_sign_digest nettle_dsa_sha256_sign_digest #define dsa_sha256_verify_digest nettle_dsa_sha256_verify_digest #define dsa_compat_generate_keypair nettle_dsa_compat_generate_keypair /* Switch meaning of dsa_generate_keypair */ #undef dsa_generate_keypair #define dsa_generate_keypair nettle_dsa_compat_generate_keypair #ifdef __cplusplus extern "C" { #endif struct dsa_public_key { /* Same as struct dsa_params, but can't use that struct here without breaking backwards compatibility. Layout must be identical, since this is cast to a struct dsa_param pointer for calling _dsa_sign and _dsa_verify */ mpz_t p; mpz_t q; mpz_t g; /* Public value */ mpz_t y; }; struct dsa_private_key { /* Unlike an rsa public key, private key operations will need both * the private and the public information. */ mpz_t x; }; /* Signing a message works as follows: * * Store the private key in a dsa_private_key struct. * * Initialize a hashing context, by callling * sha1_init * * Hash the message by calling * sha1_update * * Create the signature by calling * dsa_sha1_sign * * The signature is represented as a struct dsa_signature. This call also * resets the hashing context. * * When done with the key and signature, don't forget to call * dsa_signature_clear. */ /* Calls mpz_init to initialize bignum storage. */ void dsa_public_key_init(struct dsa_public_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void dsa_public_key_clear(struct dsa_public_key *key); /* Calls mpz_init to initialize bignum storage. */ void dsa_private_key_init(struct dsa_private_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void dsa_private_key_clear(struct dsa_private_key *key); int dsa_sha1_sign(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha1_ctx *hash, struct dsa_signature *signature); int dsa_sha256_sign(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha256_ctx *hash, struct dsa_signature *signature); int dsa_sha1_verify(const struct dsa_public_key *key, struct sha1_ctx *hash, const struct dsa_signature *signature); int dsa_sha256_verify(const struct dsa_public_key *key, struct sha256_ctx *hash, const struct dsa_signature *signature); int dsa_sha1_sign_digest(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, struct dsa_signature *signature); int dsa_sha256_sign_digest(const struct dsa_public_key *pub, const struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, struct dsa_signature *signature); int dsa_sha1_verify_digest(const struct dsa_public_key *key, const uint8_t *digest, const struct dsa_signature *signature); int dsa_sha256_verify_digest(const struct dsa_public_key *key, const uint8_t *digest, const struct dsa_signature *signature); /* Key generation */ int dsa_generate_keypair(struct dsa_public_key *pub, struct dsa_private_key *key, void *random_ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress, unsigned p_bits, unsigned q_bits); #ifdef __cplusplus } #endif #endif /* NETTLE_DSA_COMPAT_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/dsa.h ================================================ /* dsa.h The DSA publickey algorithm. Copyright (C) 2002, 2013, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_DSA_H_INCLUDED #define NETTLE_DSA_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define dsa_params_init nettle_dsa_params_init #define dsa_params_clear nettle_dsa_params_clear #define dsa_signature_init nettle_dsa_signature_init #define dsa_signature_clear nettle_dsa_signature_clear #define dsa_sign nettle_dsa_sign #define dsa_verify nettle_dsa_verify #define dsa_generate_params nettle_dsa_generate_params #define dsa_generate_keypair nettle_dsa_generate_keypair #define dsa_signature_from_sexp nettle_dsa_signature_from_sexp #define dsa_keypair_to_sexp nettle_dsa_keypair_to_sexp #define dsa_keypair_from_sexp_alist nettle_dsa_keypair_from_sexp_alist #define dsa_sha1_keypair_from_sexp nettle_dsa_sha1_keypair_from_sexp #define dsa_sha256_keypair_from_sexp nettle_dsa_sha256_keypair_from_sexp #define dsa_params_from_der_iterator nettle_dsa_params_from_der_iterator #define dsa_public_key_from_der_iterator nettle_dsa_public_key_from_der_iterator #define dsa_openssl_private_key_from_der_iterator nettle_dsa_openssl_private_key_from_der_iterator #define dsa_openssl_private_key_from_der nettle_openssl_provate_key_from_der /* For FIPS approved parameters */ #define DSA_SHA1_MIN_P_BITS 512 #define DSA_SHA1_Q_OCTETS 20 #define DSA_SHA1_Q_BITS 160 #define DSA_SHA256_MIN_P_BITS 1024 #define DSA_SHA256_Q_OCTETS 32 #define DSA_SHA256_Q_BITS 256 struct dsa_params { /* Modulo */ mpz_t p; /* Group order */ mpz_t q; /* Generator */ mpz_t g; }; void dsa_params_init (struct dsa_params *params); void dsa_params_clear (struct dsa_params *params); struct dsa_signature { mpz_t r; mpz_t s; }; /* Calls mpz_init to initialize bignum storage. */ void dsa_signature_init(struct dsa_signature *signature); /* Calls mpz_clear to deallocate bignum storage. */ void dsa_signature_clear(struct dsa_signature *signature); int dsa_sign(const struct dsa_params *params, const mpz_t x, void *random_ctx, nettle_random_func *random, size_t digest_size, const uint8_t *digest, struct dsa_signature *signature); int dsa_verify(const struct dsa_params *params, const mpz_t y, size_t digest_size, const uint8_t *digest, const struct dsa_signature *signature); /* Key generation */ int dsa_generate_params(struct dsa_params *params, void *random_ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress, unsigned p_bits, unsigned q_bits); void dsa_generate_keypair (const struct dsa_params *params, mpz_t pub, mpz_t key, void *random_ctx, nettle_random_func *random); /* Keys in sexp form. */ struct nettle_buffer; /* Generates a public-key expression if PRIV is NULL .*/ int dsa_keypair_to_sexp(struct nettle_buffer *buffer, const char *algorithm_name, /* NULL means "dsa" */ const struct dsa_params *params, const mpz_t pub, const mpz_t priv); struct sexp_iterator; int dsa_signature_from_sexp(struct dsa_signature *rs, struct sexp_iterator *i, unsigned q_bits); int dsa_keypair_from_sexp_alist(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, unsigned q_bits, struct sexp_iterator *i); /* If PRIV is NULL, expect a public-key expression. If PUB is NULL, * expect a private key expression and ignore the parts not needed for * the public key. */ /* Keys must be initialized before calling this function, as usual. */ int dsa_sha1_keypair_from_sexp(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, size_t length, const uint8_t *expr); int dsa_sha256_keypair_from_sexp(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, size_t length, const uint8_t *expr); /* Keys in X.509 andd OpenSSL format. */ struct asn1_der_iterator; int dsa_params_from_der_iterator(struct dsa_params *params, unsigned max_bits, unsigned q_bits, struct asn1_der_iterator *i); int dsa_public_key_from_der_iterator(const struct dsa_params *params, mpz_t pub, struct asn1_der_iterator *i); int dsa_openssl_private_key_from_der_iterator(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, struct asn1_der_iterator *i); int dsa_openssl_private_key_from_der(struct dsa_params *params, mpz_t pub, mpz_t priv, unsigned p_max_bits, size_t length, const uint8_t *data); #ifdef __cplusplus } #endif #endif /* NETTLE_DSA_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/eax.h ================================================ /* eax.h EAX mode, see http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_EAX_H_INCLUDED #define NETTLE_EAX_H_INCLUDED #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define eax_set_key nettle_eax_set_key #define eax_set_nonce nettle_eax_set_nonce #define eax_update nettle_eax_update #define eax_encrypt nettle_eax_encrypt #define eax_decrypt nettle_eax_decrypt #define eax_digest nettle_eax_digest #define eax_aes128_set_key nettle_eax_aes128_set_key #define eax_aes128_set_nonce nettle_eax_aes128_set_nonce #define eax_aes128_update nettle_eax_aes128_update #define eax_aes128_encrypt nettle_eax_aes128_encrypt #define eax_aes128_decrypt nettle_eax_aes128_decrypt #define eax_aes128_digest nettle_eax_aes128_digest /* Restricted to block ciphers with 128 bit block size. FIXME: Reflect this in naming? */ #define EAX_BLOCK_SIZE 16 #define EAX_DIGEST_SIZE 16 /* FIXME: Reasonable default? */ #define EAX_IV_SIZE 16 /* Values independent of message and nonce */ struct eax_key { union nettle_block16 pad_block; union nettle_block16 pad_partial; }; struct eax_ctx { union nettle_block16 omac_nonce; union nettle_block16 omac_data; union nettle_block16 omac_message; union nettle_block16 ctr; }; void eax_set_key (struct eax_key *key, const void *cipher, nettle_cipher_func *f); void eax_set_nonce (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t nonce_length, const uint8_t *nonce); void eax_update (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t data_length, const uint8_t *data); void eax_encrypt (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void eax_decrypt (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void eax_digest (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); /* Put the cipher last, to get cipher-independent offsets for the EAX * state. */ #define EAX_CTX(type) \ { struct eax_key key; struct eax_ctx eax; type cipher; } #define EAX_SET_KEY(ctx, set_key, encrypt, data) \ do { \ (set_key)(&(ctx)->cipher, (data)); \ if (0) (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ eax_set_key (&(ctx)->key, &(ctx)->cipher, (nettle_cipher_func *) encrypt); \ } while (0) #define EAX_SET_NONCE(ctx, encrypt, length, nonce) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_set_nonce (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (nonce))) #define EAX_UPDATE(ctx, encrypt, length, data) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_update (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (data))) #define EAX_ENCRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_encrypt (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define EAX_DECRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_decrypt (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define EAX_DIGEST(ctx, encrypt, length, digest) \ (0 ? (encrypt) (&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : eax_digest (&(ctx)->eax, &(ctx)->key, \ &(ctx)->cipher, (nettle_cipher_func *) (encrypt), \ (length), (digest))) struct eax_aes128_ctx EAX_CTX(struct aes128_ctx); void eax_aes128_set_key(struct eax_aes128_ctx *ctx, const uint8_t *key); void eax_aes128_set_nonce(struct eax_aes128_ctx *ctx, size_t length, const uint8_t *iv); void eax_aes128_update(struct eax_aes128_ctx *ctx, size_t length, const uint8_t *data); void eax_aes128_encrypt(struct eax_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void eax_aes128_decrypt(struct eax_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void eax_aes128_digest(struct eax_aes128_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_EAX_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/ecc-curve.h ================================================ /* ecc-curve.h Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ #ifndef NETTLE_ECC_CURVE_H_INCLUDED #define NETTLE_ECC_CURVE_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* The contents of this struct is internal. */ struct ecc_curve; const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_gost_gc256b(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_gost_gc512a(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_192r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_224r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_256r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_384r1(void); const struct ecc_curve * _NETTLE_ATTRIBUTE_PURE nettle_get_secp_521r1(void); #ifdef __cplusplus } #endif #endif /* NETTLE_ECC_CURVE_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/ecc.h ================================================ /* ecc.h Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ #ifndef NETTLE_ECC_H_INCLUDED #define NETTLE_ECC_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ecc_point_init nettle_ecc_point_init #define ecc_point_clear nettle_ecc_point_clear #define ecc_point_set nettle_ecc_point_set #define ecc_point_get nettle_ecc_point_get #define ecc_point_mul nettle_ecc_point_mul #define ecc_point_mul_g nettle_ecc_point_mul_g #define ecc_scalar_init nettle_ecc_scalar_init #define ecc_scalar_clear nettle_ecc_scalar_clear #define ecc_scalar_set nettle_ecc_scalar_set #define ecc_scalar_get nettle_ecc_scalar_get #define ecc_scalar_random nettle_ecc_scalar_random #define ecc_point_mul nettle_ecc_point_mul #define ecc_bit_size nettle_ecc_bit_size #define ecc_size nettle_ecc_size #define ecc_size_a nettle_ecc_size_a #define ecc_size_j nettle_ecc_size_j struct ecc_curve; /* High level interface, for ECDSA, DH, etc */ /* Represents a point on the ECC curve */ struct ecc_point { const struct ecc_curve *ecc; /* Allocated using the same allocation function as GMP. */ mp_limb_t *p; }; /* Represents a non-zero scalar, an element of Z_q^*, where q is the group order of the curve. */ struct ecc_scalar { const struct ecc_curve *ecc; /* Allocated using the same allocation function as GMP. */ mp_limb_t *p; }; void ecc_point_init (struct ecc_point *p, const struct ecc_curve *ecc); void ecc_point_clear (struct ecc_point *p); /* Fails and returns zero if the point is not on the curve. */ int ecc_point_set (struct ecc_point *p, const mpz_t x, const mpz_t y); void ecc_point_get (const struct ecc_point *p, mpz_t x, mpz_t y); void ecc_scalar_init (struct ecc_scalar *s, const struct ecc_curve *ecc); void ecc_scalar_clear (struct ecc_scalar *s); /* Fails and returns zero if the scalar is not in the proper range. */ int ecc_scalar_set (struct ecc_scalar *s, const mpz_t z); void ecc_scalar_get (const struct ecc_scalar *s, mpz_t z); /* Generates a random scalar, suitable as an ECDSA private key or a ECDH exponent. */ void ecc_scalar_random (struct ecc_scalar *s, void *random_ctx, nettle_random_func *random); /* Computes r = n p */ void ecc_point_mul (struct ecc_point *r, const struct ecc_scalar *n, const struct ecc_point *p); /* Computes r = n g */ void ecc_point_mul_g (struct ecc_point *r, const struct ecc_scalar *n); /* Low-level interface */ /* Points on a curve are represented as arrays of mp_limb_t, with curve-specific representation. For the secp curves, we use Jacobian coordinates (possibly in Montgomery form for mod multiplication). For curve25519 we use homogeneous coordinates on an equivalent Edwards curve. The suffix "_h" denotes this internal representation. Since we use additive notation for the groups, the infinity point on the curve is denoted 0. The infinity point can be represented with x = y = 0 in affine coordinates, and Z = 0 in Jacobian coordinates. However, note that most of the ECC functions do *not* support infinity as an input or output. */ /* Returns the bit size of a single coordinate (and of the prime p). */ unsigned ecc_bit_size (const struct ecc_curve *ecc); /* Returns the size of a single coordinate. */ mp_size_t ecc_size (const struct ecc_curve *ecc); /* Size of a point, using affine coordinates x, y. */ mp_size_t ecc_size_a (const struct ecc_curve *ecc); /* Size of a point, using jacobian coordinates X, Y and Z. */ mp_size_t ecc_size_j (const struct ecc_curve *ecc); /* FIXME: Define a generic ecc_dup, ecc_add, for any type of curve. Do they need to handle infinity points? */ #ifdef __cplusplus } #endif #endif /* NETTLE_ECC_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/ecdsa.h ================================================ /* ecdsa.h Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ #ifndef NETTLE_ECDSA_H_INCLUDED #define NETTLE_ECDSA_H_INCLUDED #include "ecc.h" #include "dsa.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ecdsa_sign nettle_ecdsa_sign #define ecdsa_verify nettle_ecdsa_verify #define ecdsa_generate_keypair nettle_ecdsa_generate_keypair #define ecc_ecdsa_sign nettle_ecc_ecdsa_sign #define ecc_ecdsa_sign_itch nettle_ecc_ecdsa_sign_itch #define ecc_ecdsa_verify nettle_ecc_ecdsa_verify #define ecc_ecdsa_verify_itch nettle_ecc_ecdsa_verify_itch /* High level ECDSA functions. * * A public key is represented as a struct ecc_point, and a private * key as a struct ecc_scalar. */ void ecdsa_sign (const struct ecc_scalar *key, void *random_ctx, nettle_random_func *random, size_t digest_length, const uint8_t *digest, struct dsa_signature *signature); int ecdsa_verify (const struct ecc_point *pub, size_t length, const uint8_t *digest, const struct dsa_signature *signature); void ecdsa_generate_keypair (struct ecc_point *pub, struct ecc_scalar *key, void *random_ctx, nettle_random_func *random); /* Low-level ECDSA functions. */ mp_size_t ecc_ecdsa_sign_itch (const struct ecc_curve *ecc); void ecc_ecdsa_sign (const struct ecc_curve *ecc, const mp_limb_t *zp, /* Random nonce, must be invertible mod ecc group order. */ const mp_limb_t *kp, size_t length, const uint8_t *digest, mp_limb_t *rp, mp_limb_t *sp, mp_limb_t *scratch); mp_size_t ecc_ecdsa_verify_itch (const struct ecc_curve *ecc); int ecc_ecdsa_verify (const struct ecc_curve *ecc, const mp_limb_t *pp, /* Public key */ size_t length, const uint8_t *digest, const mp_limb_t *rp, const mp_limb_t *sp, mp_limb_t *scratch); #ifdef __cplusplus } #endif #endif /* NETTLE_ECDSA_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/eddsa.h ================================================ /* eddsa.h Copyright (C) 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_EDDSA_H #define NETTLE_EDDSA_H #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ed25519_sha512_set_private_key nettle_ed25519_sha512_set_private_key #define ed25519_sha512_public_key nettle_ed25519_sha512_public_key #define ed25519_sha512_sign nettle_ed25519_sha512_sign #define ed25519_sha512_verify nettle_ed25519_sha512_verify #define ed448_shake256_public_key nettle_ed448_shake256_public_key #define ed448_shake256_sign nettle_ed448_shake256_sign #define ed448_shake256_verify nettle_ed448_shake256_verify #define ED25519_KEY_SIZE 32 #define ED25519_SIGNATURE_SIZE 64 void ed25519_sha512_public_key (uint8_t *pub, const uint8_t *priv); void ed25519_sha512_sign (const uint8_t *pub, const uint8_t *priv, size_t length, const uint8_t *msg, uint8_t *signature); int ed25519_sha512_verify (const uint8_t *pub, size_t length, const uint8_t *msg, const uint8_t *signature); #define ED448_KEY_SIZE 57 #define ED448_SIGNATURE_SIZE 114 void ed448_shake256_public_key (uint8_t *pub, const uint8_t *priv); void ed448_shake256_sign (const uint8_t *pub, const uint8_t *priv, size_t length, const uint8_t *msg, uint8_t *signature); int ed448_shake256_verify (const uint8_t *pub, size_t length, const uint8_t *msg, const uint8_t *signature); #ifdef __cplusplus } #endif #endif /* NETTLE_EDDSA_H */ ================================================ FILE: thirdparty/64/include/nettle/gcm.h ================================================ /* gcm.h Galois counter mode, specified by NIST, http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf Copyright (C) 2011 Katholieke Universiteit Leuven Copyright (C) 2011, 2014 Niels Möller Contributed by Nikos Mavrogiannopoulos This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_GCM_H_INCLUDED #define NETTLE_GCM_H_INCLUDED #include "aes.h" #include "camellia.h" #include "sm4.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define gcm_set_key nettle_gcm_set_key #define gcm_set_iv nettle_gcm_set_iv #define gcm_update nettle_gcm_update #define gcm_encrypt nettle_gcm_encrypt #define gcm_decrypt nettle_gcm_decrypt #define gcm_digest nettle_gcm_digest #define gcm_aes128_set_key nettle_gcm_aes128_set_key #define gcm_aes128_set_iv nettle_gcm_aes128_set_iv #define gcm_aes128_update nettle_gcm_aes128_update #define gcm_aes128_encrypt nettle_gcm_aes128_encrypt #define gcm_aes128_decrypt nettle_gcm_aes128_decrypt #define gcm_aes128_digest nettle_gcm_aes128_digest #define gcm_aes192_set_key nettle_gcm_aes192_set_key #define gcm_aes192_set_iv nettle_gcm_aes192_set_iv #define gcm_aes192_update nettle_gcm_aes192_update #define gcm_aes192_encrypt nettle_gcm_aes192_encrypt #define gcm_aes192_decrypt nettle_gcm_aes192_decrypt #define gcm_aes192_digest nettle_gcm_aes192_digest #define gcm_aes256_set_key nettle_gcm_aes256_set_key #define gcm_aes256_set_iv nettle_gcm_aes256_set_iv #define gcm_aes256_update nettle_gcm_aes256_update #define gcm_aes256_encrypt nettle_gcm_aes256_encrypt #define gcm_aes256_decrypt nettle_gcm_aes256_decrypt #define gcm_aes256_digest nettle_gcm_aes256_digest #define gcm_aes_set_key nettle_gcm_aes_set_key #define gcm_aes_set_iv nettle_gcm_aes_set_iv #define gcm_aes_update nettle_gcm_aes_update #define gcm_aes_encrypt nettle_gcm_aes_encrypt #define gcm_aes_decrypt nettle_gcm_aes_decrypt #define gcm_aes_digest nettle_gcm_aes_digest #define gcm_camellia128_set_key nettle_gcm_camellia128_set_key #define gcm_camellia128_set_iv nettle_gcm_camellia128_set_iv #define gcm_camellia128_update nettle_gcm_camellia128_update #define gcm_camellia128_encrypt nettle_gcm_camellia128_encrypt #define gcm_camellia128_decrypt nettle_gcm_camellia128_decrypt #define gcm_camellia128_digest nettle_gcm_camellia128_digest #define gcm_camellia256_set_key nettle_gcm_camellia256_set_key #define gcm_camellia256_set_iv nettle_gcm_camellia256_set_iv #define gcm_camellia256_update nettle_gcm_camellia256_update #define gcm_camellia256_encrypt nettle_gcm_camellia256_encrypt #define gcm_camellia256_decrypt nettle_gcm_camellia256_decrypt #define gcm_camellia256_digest nettle_gcm_camellia256_digest #define gcm_sm4_set_key nettle_gcm_sm4_set_key #define gcm_sm4_set_iv nettle_gcm_sm4_set_iv #define gcm_sm4_update nettle_gcm_sm4_update #define gcm_sm4_encrypt nettle_gcm_sm4_encrypt #define gcm_sm4_decrypt nettle_gcm_sm4_decrypt #define gcm_sm4_digest nettle_gcm_sm4_digest #define GCM_BLOCK_SIZE 16 #define GCM_IV_SIZE (GCM_BLOCK_SIZE - 4) #define GCM_DIGEST_SIZE 16 #define GCM_TABLE_BITS 8 /* Hashing subkey */ struct gcm_key { union nettle_block16 h[1 << GCM_TABLE_BITS]; }; /* Per-message state, depending on the iv */ struct gcm_ctx { /* Original counter block */ union nettle_block16 iv; /* Updated for each block. */ union nettle_block16 ctr; /* Hashing state */ union nettle_block16 x; uint64_t auth_size; uint64_t data_size; }; void gcm_set_key(struct gcm_key *key, const void *cipher, nettle_cipher_func *f); void gcm_set_iv(struct gcm_ctx *ctx, const struct gcm_key *key, size_t length, const uint8_t *iv); void gcm_update(struct gcm_ctx *ctx, const struct gcm_key *key, size_t length, const uint8_t *data); void gcm_encrypt(struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void gcm_decrypt(struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void gcm_digest(struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); /* Convenience macrology (not sure how useful it is) */ /* All-in-one context, with hash subkey, message state, and cipher. */ #define GCM_CTX(type) \ { struct gcm_key key; struct gcm_ctx gcm; type cipher; } /* NOTE: Avoid using NULL, as we don't include anything defining it. */ #define GCM_SET_KEY(ctx, set_key, encrypt, gcm_key) \ do { \ (set_key)(&(ctx)->cipher, (gcm_key)); \ if (0) (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0); \ gcm_set_key(&(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt)); \ } while (0) #define GCM_SET_IV(ctx, length, data) \ gcm_set_iv(&(ctx)->gcm, &(ctx)->key, (length), (data)) #define GCM_UPDATE(ctx, length, data) \ gcm_update(&(ctx)->gcm, &(ctx)->key, (length), (data)) #define GCM_ENCRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : gcm_encrypt(&(ctx)->gcm, &(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define GCM_DECRYPT(ctx, encrypt, length, dst, src) \ (0 ? (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : gcm_decrypt(&(ctx)->gcm, &(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (dst), (src))) #define GCM_DIGEST(ctx, encrypt, length, digest) \ (0 ? (encrypt)(&(ctx)->cipher, ~(size_t) 0, \ (uint8_t *) 0, (const uint8_t *) 0) \ : gcm_digest(&(ctx)->gcm, &(ctx)->key, &(ctx)->cipher, \ (nettle_cipher_func *) (encrypt), \ (length), (digest))) struct gcm_aes128_ctx GCM_CTX(struct aes128_ctx); void gcm_aes128_set_key(struct gcm_aes128_ctx *ctx, const uint8_t *key); /* FIXME: Define _update and _set_iv as some kind of aliaes, there's nothing aes-specific. */ void gcm_aes128_update (struct gcm_aes128_ctx *ctx, size_t length, const uint8_t *data); void gcm_aes128_set_iv (struct gcm_aes128_ctx *ctx, size_t length, const uint8_t *iv); void gcm_aes128_encrypt(struct gcm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes128_decrypt(struct gcm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes128_digest(struct gcm_aes128_ctx *ctx, size_t length, uint8_t *digest); struct gcm_aes192_ctx GCM_CTX(struct aes192_ctx); void gcm_aes192_set_key(struct gcm_aes192_ctx *ctx, const uint8_t *key); void gcm_aes192_update (struct gcm_aes192_ctx *ctx, size_t length, const uint8_t *data); void gcm_aes192_set_iv (struct gcm_aes192_ctx *ctx, size_t length, const uint8_t *iv); void gcm_aes192_encrypt(struct gcm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes192_decrypt(struct gcm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes192_digest(struct gcm_aes192_ctx *ctx, size_t length, uint8_t *digest); struct gcm_aes256_ctx GCM_CTX(struct aes256_ctx); void gcm_aes256_set_key(struct gcm_aes256_ctx *ctx, const uint8_t *key); void gcm_aes256_update (struct gcm_aes256_ctx *ctx, size_t length, const uint8_t *data); void gcm_aes256_set_iv (struct gcm_aes256_ctx *ctx, size_t length, const uint8_t *iv); void gcm_aes256_encrypt(struct gcm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes256_decrypt(struct gcm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_aes256_digest(struct gcm_aes256_ctx *ctx, size_t length, uint8_t *digest); /* Old deprecated aes interface, for backwards compatibility */ struct gcm_aes_ctx GCM_CTX(struct aes_ctx); void gcm_aes_set_key(struct gcm_aes_ctx *ctx, size_t length, const uint8_t *key) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_set_iv(struct gcm_aes_ctx *ctx, size_t length, const uint8_t *iv) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_update(struct gcm_aes_ctx *ctx, size_t length, const uint8_t *data) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_encrypt(struct gcm_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_decrypt(struct gcm_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src) _NETTLE_ATTRIBUTE_DEPRECATED; void gcm_aes_digest(struct gcm_aes_ctx *ctx, size_t length, uint8_t *digest) _NETTLE_ATTRIBUTE_DEPRECATED; struct gcm_camellia128_ctx GCM_CTX(struct camellia128_ctx); void gcm_camellia128_set_key(struct gcm_camellia128_ctx *ctx, const uint8_t *key); void gcm_camellia128_set_iv(struct gcm_camellia128_ctx *ctx, size_t length, const uint8_t *iv); void gcm_camellia128_update(struct gcm_camellia128_ctx *ctx, size_t length, const uint8_t *data); void gcm_camellia128_encrypt(struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia128_decrypt(struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia128_digest(struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *digest); struct gcm_camellia256_ctx GCM_CTX(struct camellia256_ctx); void gcm_camellia256_set_key(struct gcm_camellia256_ctx *ctx, const uint8_t *key); void gcm_camellia256_set_iv(struct gcm_camellia256_ctx *ctx, size_t length, const uint8_t *iv); void gcm_camellia256_update(struct gcm_camellia256_ctx *ctx, size_t length, const uint8_t *data); void gcm_camellia256_encrypt(struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia256_decrypt(struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_camellia256_digest(struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *digest); struct gcm_sm4_ctx GCM_CTX(struct sm4_ctx); void gcm_sm4_set_key(struct gcm_sm4_ctx *ctx, const uint8_t *key); void gcm_sm4_set_iv(struct gcm_sm4_ctx *ctx, size_t length, const uint8_t *iv); void gcm_sm4_update(struct gcm_sm4_ctx *ctx, size_t length, const uint8_t *data); void gcm_sm4_encrypt(struct gcm_sm4_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_sm4_decrypt(struct gcm_sm4_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void gcm_sm4_digest(struct gcm_sm4_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_GCM_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/gostdsa.h ================================================ /* gostdsa.h Copyright (C) 2015 Dmity Eremin-Solenikov Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_GOSTDSA_H_INCLUDED #define NETTLE_GOSTDSA_H_INCLUDED #include "ecc.h" #include "dsa.h" #include "ecdsa.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define gostdsa_sign nettle_gostdsa_sign #define gostdsa_verify nettle_gostdsa_verify #define gostdsa_vko nettle_gostdsa_vko #define ecc_gostdsa_sign nettle_ecc_gostdsa_sign #define ecc_gostdsa_sign_itch nettle_ecc_gostdsa_sign_itch #define ecc_gostdsa_verify nettle_ecc_gostdsa_verify #define ecc_gostdsa_verify_itch nettle_ecc_gostdsa_verify_itch /* Just use ECDSA function for key generation */ #define gostdsa_generate_keypair ecdsa_generate_keypair /* High level GOST DSA functions. * * A public key is represented as a struct ecc_point, and a private * key as a struct ecc_scalar. */ void gostdsa_sign (const struct ecc_scalar *key, void *random_ctx, nettle_random_func *random, size_t digest_length, const uint8_t *digest, struct dsa_signature *signature); int gostdsa_verify (const struct ecc_point *pub, size_t length, const uint8_t *digest, const struct dsa_signature *signature); void gostdsa_vko (const struct ecc_scalar *key, const struct ecc_point *pub, size_t ukm_length, const uint8_t *ukm, uint8_t *out); /* Low-level GOSTDSA functions. */ mp_size_t ecc_gostdsa_sign_itch (const struct ecc_curve *ecc); void ecc_gostdsa_sign (const struct ecc_curve *ecc, const mp_limb_t *zp, /* Random nonce, must be invertible mod ecc group order. */ const mp_limb_t *kp, size_t length, const uint8_t *digest, mp_limb_t *rp, mp_limb_t *sp, mp_limb_t *scratch); mp_size_t ecc_gostdsa_verify_itch (const struct ecc_curve *ecc); int ecc_gostdsa_verify (const struct ecc_curve *ecc, const mp_limb_t *pp, /* Public key */ size_t length, const uint8_t *digest, const mp_limb_t *rp, const mp_limb_t *sp, mp_limb_t *scratch); #ifdef __cplusplus } #endif #endif /* NETTLE_GOSTDSA_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/gosthash94.h ================================================ /* gosthash94.h The GOST R 34.11-94 hash function, described in RFC 5831. Copyright (C) 2012 Nikos Mavrogiannopoulos, Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Based on rhash gost.h. */ /* Copyright: 2009-2012 Aleksey Kravchenko * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * Ported to nettle by Nikos Mavrogiannopoulos. */ #ifndef NETTLE_GOSTHASH94_H_INCLUDED #define NETTLE_GOSTHASH94_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif #define gosthash94_init nettle_gosthash94_init #define gosthash94_update nettle_gosthash94_update #define gosthash94_digest nettle_gosthash94_digest #define gosthash94cp_update nettle_gosthash94cp_update #define gosthash94cp_digest nettle_gosthash94cp_digest #define GOSTHASH94_BLOCK_SIZE 32 #define GOSTHASH94_DIGEST_SIZE 32 /* For backwards compatibility */ #define GOSTHASH94_DATA_SIZE GOSTHASH94_BLOCK_SIZE #define GOSTHASH94CP_BLOCK_SIZE GOSTHASH94_BLOCK_SIZE #define GOSTHASH94CP_DIGEST_SIZE GOSTHASH94_DIGEST_SIZE struct gosthash94_ctx { uint32_t hash[8]; /* algorithm 256-bit state */ uint32_t sum[8]; /* sum of processed message blocks */ uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[GOSTHASH94_BLOCK_SIZE]; /* 256-bit buffer for leftovers */ }; #define gosthash94cp_ctx gosthash94_ctx void gosthash94_init(struct gosthash94_ctx *ctx); void gosthash94_update(struct gosthash94_ctx *ctx, size_t length, const uint8_t *msg); void gosthash94_digest(struct gosthash94_ctx *ctx, size_t length, uint8_t *result); #define gosthash94cp_init gosthash94_init void gosthash94cp_update(struct gosthash94_ctx *ctx, size_t length, const uint8_t *msg); void gosthash94cp_digest(struct gosthash94_ctx *ctx, size_t length, uint8_t *result); #ifdef __cplusplus } #endif #endif /* NETTLE_GOSTHASH94_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/hkdf.h ================================================ /* hkdf.h TLS PRF code (RFC-5246, RFC-2246). Copyright (C) 2017 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_HKDF_H_INCLUDED #define NETTLE_HKDF_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define hkdf_extract nettle_hkdf_extract #define hkdf_expand nettle_hkdf_expand void hkdf_extract(void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, size_t secret_size, const uint8_t *secret, uint8_t *dst); void hkdf_expand(void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, size_t info_size, const uint8_t *info, size_t length, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_HKDF_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/hmac.h ================================================ /* hmac.h HMAC message authentication code (RFC-2104). Copyright (C) 2001, 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_HMAC_H_INCLUDED #define NETTLE_HMAC_H_INCLUDED #include "nettle-meta.h" #include "gosthash94.h" #include "md5.h" #include "ripemd160.h" #include "sha1.h" #include "sha2.h" #include "streebog.h" #include "sm3.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define hmac_set_key nettle_hmac_set_key #define hmac_update nettle_hmac_update #define hmac_digest nettle_hmac_digest #define hmac_md5_set_key nettle_hmac_md5_set_key #define hmac_md5_update nettle_hmac_md5_update #define hmac_md5_digest nettle_hmac_md5_digest #define hmac_ripemd160_set_key nettle_hmac_ripemd160_set_key #define hmac_ripemd160_update nettle_hmac_ripemd160_update #define hmac_ripemd160_digest nettle_hmac_ripemd160_digest #define hmac_sha1_set_key nettle_hmac_sha1_set_key #define hmac_sha1_update nettle_hmac_sha1_update #define hmac_sha1_digest nettle_hmac_sha1_digest #define hmac_sha224_set_key nettle_hmac_sha224_set_key #define hmac_sha224_digest nettle_hmac_sha224_digest #define hmac_sha256_set_key nettle_hmac_sha256_set_key #define hmac_sha256_update nettle_hmac_sha256_update #define hmac_sha256_digest nettle_hmac_sha256_digest #define hmac_sha384_set_key nettle_hmac_sha384_set_key #define hmac_sha384_digest nettle_hmac_sha384_digest #define hmac_sha512_set_key nettle_hmac_sha512_set_key #define hmac_sha512_update nettle_hmac_sha512_update #define hmac_sha512_digest nettle_hmac_sha512_digest #define hmac_gosthash94_set_key nettle_hmac_gosthash94_set_key #define hmac_gosthash94_update nettle_hmac_gosthash94_update #define hmac_gosthash94_digest nettle_hmac_gosthash94_digest #define hmac_gosthash94cp_set_key nettle_hmac_gosthash94cp_set_key #define hmac_gosthash94cp_update nettle_hmac_gosthash94cp_update #define hmac_gosthash94cp_digest nettle_hmac_gosthash94cp_digest #define hmac_streebog256_set_key nettle_hmac_streebog256_set_key #define hmac_streebog256_digest nettle_hmac_streebog256_digest #define hmac_streebog512_set_key nettle_hmac_streebog512_set_key #define hmac_streebog512_update nettle_hmac_streebog512_update #define hmac_streebog512_digest nettle_hmac_streebog512_digest #define hmac_sm3_set_key nettle_hmac_sm3_set_key #define hmac_sm3_update nettle_hmac_sm3_update #define hmac_sm3_digest nettle_hmac_sm3_digest void hmac_set_key(void *outer, void *inner, void *state, const struct nettle_hash *hash, size_t length, const uint8_t *key); /* This function is not strictly needed, it's s just the same as the * hash update function. */ void hmac_update(void *state, const struct nettle_hash *hash, size_t length, const uint8_t *data); void hmac_digest(const void *outer, const void *inner, void *state, const struct nettle_hash *hash, size_t length, uint8_t *digest); #define HMAC_CTX(type) \ { type outer; type inner; type state; } #define HMAC_SET_KEY(ctx, hash, length, key) \ hmac_set_key( &(ctx)->outer, &(ctx)->inner, &(ctx)->state, \ (hash), (length), (key) ) #define HMAC_DIGEST(ctx, hash, length, digest) \ hmac_digest( &(ctx)->outer, &(ctx)->inner, &(ctx)->state, \ (hash), (length), (digest) ) /* HMAC using specific hash functions */ /* hmac-md5 */ struct hmac_md5_ctx HMAC_CTX(struct md5_ctx); void hmac_md5_set_key(struct hmac_md5_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_md5_update(struct hmac_md5_ctx *ctx, size_t length, const uint8_t *data); void hmac_md5_digest(struct hmac_md5_ctx *ctx, size_t length, uint8_t *digest); /* hmac-ripemd160 */ struct hmac_ripemd160_ctx HMAC_CTX(struct ripemd160_ctx); void hmac_ripemd160_set_key(struct hmac_ripemd160_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_ripemd160_update(struct hmac_ripemd160_ctx *ctx, size_t length, const uint8_t *data); void hmac_ripemd160_digest(struct hmac_ripemd160_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha1 */ struct hmac_sha1_ctx HMAC_CTX(struct sha1_ctx); void hmac_sha1_set_key(struct hmac_sha1_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sha1_update(struct hmac_sha1_ctx *ctx, size_t length, const uint8_t *data); void hmac_sha1_digest(struct hmac_sha1_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha256 */ struct hmac_sha256_ctx HMAC_CTX(struct sha256_ctx); void hmac_sha256_set_key(struct hmac_sha256_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sha256_update(struct hmac_sha256_ctx *ctx, size_t length, const uint8_t *data); void hmac_sha256_digest(struct hmac_sha256_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha224 */ #define hmac_sha224_ctx hmac_sha256_ctx void hmac_sha224_set_key(struct hmac_sha224_ctx *ctx, size_t key_length, const uint8_t *key); #define hmac_sha224_update nettle_hmac_sha256_update void hmac_sha224_digest(struct hmac_sha224_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha512 */ struct hmac_sha512_ctx HMAC_CTX(struct sha512_ctx); void hmac_sha512_set_key(struct hmac_sha512_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sha512_update(struct hmac_sha512_ctx *ctx, size_t length, const uint8_t *data); void hmac_sha512_digest(struct hmac_sha512_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sha384 */ #define hmac_sha384_ctx hmac_sha512_ctx void hmac_sha384_set_key(struct hmac_sha512_ctx *ctx, size_t key_length, const uint8_t *key); #define hmac_sha384_update nettle_hmac_sha512_update void hmac_sha384_digest(struct hmac_sha512_ctx *ctx, size_t length, uint8_t *digest); /* hmac-gosthash94 */ struct hmac_gosthash94_ctx HMAC_CTX(struct gosthash94_ctx); void hmac_gosthash94_set_key(struct hmac_gosthash94_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_gosthash94_update(struct hmac_gosthash94_ctx *ctx, size_t length, const uint8_t *data); void hmac_gosthash94_digest(struct hmac_gosthash94_ctx *ctx, size_t length, uint8_t *digest); struct hmac_gosthash94cp_ctx HMAC_CTX(struct gosthash94cp_ctx); void hmac_gosthash94cp_set_key(struct hmac_gosthash94cp_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_gosthash94cp_update(struct hmac_gosthash94cp_ctx *ctx, size_t length, const uint8_t *data); void hmac_gosthash94cp_digest(struct hmac_gosthash94cp_ctx *ctx, size_t length, uint8_t *digest); /* hmac-streebog */ struct hmac_streebog512_ctx HMAC_CTX(struct streebog512_ctx); void hmac_streebog512_set_key(struct hmac_streebog512_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_streebog512_update(struct hmac_streebog512_ctx *ctx, size_t length, const uint8_t *data); void hmac_streebog512_digest(struct hmac_streebog512_ctx *ctx, size_t length, uint8_t *digest); #define hmac_streebog256_ctx hmac_streebog512_ctx void hmac_streebog256_set_key(struct hmac_streebog256_ctx *ctx, size_t key_length, const uint8_t *key); #define hmac_streebog256_update hmac_streebog512_update void hmac_streebog256_digest(struct hmac_streebog256_ctx *ctx, size_t length, uint8_t *digest); /* hmac-sm3 */ struct hmac_sm3_ctx HMAC_CTX(struct sm3_ctx); void hmac_sm3_set_key(struct hmac_sm3_ctx *ctx, size_t key_length, const uint8_t *key); void hmac_sm3_update(struct hmac_sm3_ctx *ctx, size_t length, const uint8_t *data); void hmac_sm3_digest(struct hmac_sm3_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_HMAC_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/knuth-lfib.h ================================================ /* knuth-lfib.h The "lagged fibonacci" pseudorandomness generator, described in Knuth, TAoCP, 3.6 This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* NOTE: This generator is totally inappropriate for cryptographic * applications. It is useful for generating deterministic but * random-looking test data, and is used by the Nettle testsuite. */ #ifndef NETTLE_KNUTH_LFIB_H_INCLUDED #define NETTLE_KNUTH_LFIB_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define knuth_lfib_init nettle_knuth_lfib_init #define knuth_lfib_get nettle_knuth_lfib_get #define knuth_lfib_get_array nettle_knuth_lfib_get_array #define knuth_lfib_random nettle_knuth_lfib_random #define _KNUTH_LFIB_KK 100 struct knuth_lfib_ctx { uint32_t x[_KNUTH_LFIB_KK]; unsigned index; }; void knuth_lfib_init(struct knuth_lfib_ctx *ctx, uint32_t seed); /* Get's a single number in the range 0 ... 2^30-1 */ uint32_t knuth_lfib_get(struct knuth_lfib_ctx *ctx); /* Get an array of numbers */ void knuth_lfib_get_array(struct knuth_lfib_ctx *ctx, size_t n, uint32_t *a); /* Get an array of octets. */ void knuth_lfib_random(struct knuth_lfib_ctx *ctx, size_t n, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_KNUTH_LFIB_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/macros.h ================================================ /* macros.h Copyright (C) 2001, 2010 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MACROS_H_INCLUDED #define NETTLE_MACROS_H_INCLUDED /* Reads a 64-bit integer, in network, big-endian, byte order */ #define READ_UINT64(p) \ ( (((uint64_t) (p)[0]) << 56) \ | (((uint64_t) (p)[1]) << 48) \ | (((uint64_t) (p)[2]) << 40) \ | (((uint64_t) (p)[3]) << 32) \ | (((uint64_t) (p)[4]) << 24) \ | (((uint64_t) (p)[5]) << 16) \ | (((uint64_t) (p)[6]) << 8) \ | ((uint64_t) (p)[7])) #define WRITE_UINT64(p, i) \ do { \ (p)[0] = ((i) >> 56) & 0xff; \ (p)[1] = ((i) >> 48) & 0xff; \ (p)[2] = ((i) >> 40) & 0xff; \ (p)[3] = ((i) >> 32) & 0xff; \ (p)[4] = ((i) >> 24) & 0xff; \ (p)[5] = ((i) >> 16) & 0xff; \ (p)[6] = ((i) >> 8) & 0xff; \ (p)[7] = (i) & 0xff; \ } while(0) /* Reads a 32-bit integer, in network, big-endian, byte order */ #define READ_UINT32(p) \ ( (((uint32_t) (p)[0]) << 24) \ | (((uint32_t) (p)[1]) << 16) \ | (((uint32_t) (p)[2]) << 8) \ | ((uint32_t) (p)[3])) #define WRITE_UINT32(p, i) \ do { \ (p)[0] = ((i) >> 24) & 0xff; \ (p)[1] = ((i) >> 16) & 0xff; \ (p)[2] = ((i) >> 8) & 0xff; \ (p)[3] = (i) & 0xff; \ } while(0) /* Analogous macros, for 24 and 16 bit numbers */ #define READ_UINT24(p) \ ( (((uint32_t) (p)[0]) << 16) \ | (((uint32_t) (p)[1]) << 8) \ | ((uint32_t) (p)[2])) #define WRITE_UINT24(p, i) \ do { \ (p)[0] = ((i) >> 16) & 0xff; \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[2] = (i) & 0xff; \ } while(0) #define READ_UINT16(p) \ ( (((uint32_t) (p)[0]) << 8) \ | ((uint32_t) (p)[1])) #define WRITE_UINT16(p, i) \ do { \ (p)[0] = ((i) >> 8) & 0xff; \ (p)[1] = (i) & 0xff; \ } while(0) /* And the other, little-endian, byteorder */ #define LE_READ_UINT64(p) \ ( (((uint64_t) (p)[7]) << 56) \ | (((uint64_t) (p)[6]) << 48) \ | (((uint64_t) (p)[5]) << 40) \ | (((uint64_t) (p)[4]) << 32) \ | (((uint64_t) (p)[3]) << 24) \ | (((uint64_t) (p)[2]) << 16) \ | (((uint64_t) (p)[1]) << 8) \ | ((uint64_t) (p)[0])) #define LE_WRITE_UINT64(p, i) \ do { \ (p)[7] = ((i) >> 56) & 0xff; \ (p)[6] = ((i) >> 48) & 0xff; \ (p)[5] = ((i) >> 40) & 0xff; \ (p)[4] = ((i) >> 32) & 0xff; \ (p)[3] = ((i) >> 24) & 0xff; \ (p)[2] = ((i) >> 16) & 0xff; \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[0] = (i) & 0xff; \ } while (0) #define LE_READ_UINT32(p) \ ( (((uint32_t) (p)[3]) << 24) \ | (((uint32_t) (p)[2]) << 16) \ | (((uint32_t) (p)[1]) << 8) \ | ((uint32_t) (p)[0])) #define LE_WRITE_UINT32(p, i) \ do { \ (p)[3] = ((i) >> 24) & 0xff; \ (p)[2] = ((i) >> 16) & 0xff; \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[0] = (i) & 0xff; \ } while(0) /* Analogous macros, for 16 bit numbers */ #define LE_READ_UINT16(p) \ ( (((uint32_t) (p)[1]) << 8) \ | ((uint32_t) (p)[0])) #define LE_WRITE_UINT16(p, i) \ do { \ (p)[1] = ((i) >> 8) & 0xff; \ (p)[0] = (i) & 0xff; \ } while(0) /* Macro to make it easier to loop over several blocks. */ #define FOR_BLOCKS(length, dst, src, blocksize) \ assert( !((length) % (blocksize))); \ for (; (length); ((length) -= (blocksize), \ (dst) += (blocksize), \ (src) += (blocksize)) ) /* The masking of the right shift is needed to allow n == 0 (using just 32 - n and 64 - n results in undefined behaviour). Most uses of these macros use a constant and non-zero rotation count. */ #define ROTL32(n,x) (((x)<<(n)) | ((x)>>((-(n)&31)))) #define ROTL64(n,x) (((x)<<(n)) | ((x)>>((-(n))&63))) /* Requires that size > 0 */ #define INCREMENT(size, ctr) \ do { \ unsigned increment_i = (size) - 1; \ if (++(ctr)[increment_i] == 0) \ while (increment_i > 0 \ && ++(ctr)[--increment_i] == 0 ) \ ; \ } while (0) /* Helper macro for Merkle-Damgård hash functions. Assumes the context structs includes the following fields: uint8_t block[...]; // Buffer holding one block unsigned int index; // Index into block */ /* Currently used by sha512 (and sha384) only. */ #define MD_INCR(ctx) ((ctx)->count_high += !++(ctx)->count_low) /* Takes the compression function f as argument. NOTE: also clobbers length and data. */ #define MD_UPDATE(ctx, length, data, f, incr) \ do { \ if ((ctx)->index) \ { \ /* Try to fill partial block */ \ unsigned __md_left = sizeof((ctx)->block) - (ctx)->index; \ if ((length) < __md_left) \ { \ memcpy((ctx)->block + (ctx)->index, (data), (length)); \ (ctx)->index += (length); \ goto __md_done; /* Finished */ \ } \ else \ { \ memcpy((ctx)->block + (ctx)->index, (data), __md_left); \ \ f((ctx), (ctx)->block); \ (incr); \ \ (data) += __md_left; \ (length) -= __md_left; \ } \ } \ while ((length) >= sizeof((ctx)->block)) \ { \ f((ctx), (data)); \ (incr); \ \ (data) += sizeof((ctx)->block); \ (length) -= sizeof((ctx)->block); \ } \ memcpy ((ctx)->block, (data), (length)); \ (ctx)->index = (length); \ __md_done: \ ; \ } while (0) /* Pads the block to a block boundary with the bit pattern 1 0*, leaving size octets for the length field at the end. If needed, compresses the block and starts a new one. */ #define MD_PAD(ctx, size, f) \ do { \ unsigned __md_i; \ __md_i = (ctx)->index; \ \ /* Set the first char of padding to 0x80. This is safe since there \ is always at least one byte free */ \ \ assert(__md_i < sizeof((ctx)->block)); \ (ctx)->block[__md_i++] = 0x80; \ \ if (__md_i > (sizeof((ctx)->block) - (size))) \ { /* No room for length in this block. Process it and \ pad with another one */ \ memset((ctx)->block + __md_i, 0, sizeof((ctx)->block) - __md_i); \ \ f((ctx), (ctx)->block); \ __md_i = 0; \ } \ memset((ctx)->block + __md_i, 0, \ sizeof((ctx)->block) - (size) - __md_i); \ \ } while (0) #endif /* NETTLE_MACROS_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/md2.h ================================================ /* md2.h The MD2 hash function, described in RFC 1319. Copyright (C) 2003 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD2_H_INCLUDED #define NETTLE_MD2_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define md2_init nettle_md2_init #define md2_update nettle_md2_update #define md2_digest nettle_md2_digest #define MD2_DIGEST_SIZE 16 #define MD2_BLOCK_SIZE 16 /* For backwards compatibility */ #define MD2_DATA_SIZE MD2_BLOCK_SIZE struct md2_ctx { uint8_t C[MD2_BLOCK_SIZE]; uint8_t X[3 * MD2_BLOCK_SIZE]; unsigned index; /* Into buffer */ uint8_t block[MD2_BLOCK_SIZE]; /* Block buffer */ }; void md2_init(struct md2_ctx *ctx); void md2_update(struct md2_ctx *ctx, size_t length, const uint8_t *data); void md2_digest(struct md2_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_MD2_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/md4.h ================================================ /* md4.h The MD4 hash function, described in RFC 1320. Copyright (C) 2003 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD4_H_INCLUDED #define NETTLE_MD4_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define md4_init nettle_md4_init #define md4_update nettle_md4_update #define md4_digest nettle_md4_digest #define MD4_DIGEST_SIZE 16 #define MD4_BLOCK_SIZE 64 /* For backwards compatibility */ #define MD4_DATA_SIZE MD4_BLOCK_SIZE /* Digest is kept internally as 4 32-bit words. */ #define _MD4_DIGEST_LENGTH 4 /* FIXME: Identical to md5_ctx */ struct md4_ctx { uint32_t state[_MD4_DIGEST_LENGTH]; uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[MD4_BLOCK_SIZE]; /* Block buffer */ }; void md4_init(struct md4_ctx *ctx); void md4_update(struct md4_ctx *ctx, size_t length, const uint8_t *data); void md4_digest(struct md4_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_MD4_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/md5-compat.h ================================================ /* md5-compat.h The md5 hash function, RFC 1321-style interface. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD5_COMPAT_H_INCLUDED #define NETTLE_MD5_COMPAT_H_INCLUDED #include "md5.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define MD5Init nettle_MD5Init #define MD5Update nettle_MD5Update #define MD5Final nettle_MD5Final typedef struct md5_ctx MD5_CTX; void MD5Init(MD5_CTX *ctx); void MD5Update(MD5_CTX *ctx, const unsigned char *data, unsigned int length); void MD5Final(unsigned char *out, MD5_CTX *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_MD5_COMPAT_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/md5.h ================================================ /* md5.h The MD5 hash function, described in RFC 1321. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MD5_H_INCLUDED #define NETTLE_MD5_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define md5_init nettle_md5_init #define md5_update nettle_md5_update #define md5_digest nettle_md5_digest #define md5_compress nettle_md5_compress #define MD5_DIGEST_SIZE 16 #define MD5_BLOCK_SIZE 64 /* For backwards compatibility */ #define MD5_DATA_SIZE MD5_BLOCK_SIZE /* Digest is kept internally as 4 32-bit words. */ #define _MD5_DIGEST_LENGTH 4 struct md5_ctx { uint32_t state[_MD5_DIGEST_LENGTH]; uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[MD5_BLOCK_SIZE]; /* Block buffer */ }; void md5_init(struct md5_ctx *ctx); void md5_update(struct md5_ctx *ctx, size_t length, const uint8_t *data); void md5_digest(struct md5_ctx *ctx, size_t length, uint8_t *digest); /* MD5 compression function. STATE points to 4 uint32_t words, and DATA points to 64 bytes of input data, possibly unaligned. */ void md5_compress(uint32_t *state, const uint8_t *data); /* Old name, for backwards compatibility. */ #define _nettle_md5_compress nettle_md5_compress #ifdef __cplusplus } #endif #endif /* NETTLE_MD5_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/memops.h ================================================ /* memops.h Copyright (C) 2016 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_MEMOPS_H_INCLUDED #define NETTLE_MEMOPS_H_INCLUDED #include "memxor.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define cnd_memcpy nettle_cnd_memcpy #define memeql_sec nettle_memeql_sec int memeql_sec (const void *a, const void *b, size_t n); /* Side-channel silent conditional memcpy. cnd must be 0 (nop) or 1 (copy). */ void cnd_memcpy(int cnd, volatile void *dst, const volatile void *src, size_t n); #ifdef __cplusplus } #endif #endif /* NETTLE_MEMOPS_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/memxor.h ================================================ /* memxor.h * */ #ifndef NETTLE_MEMXOR_H_INCLUDED #define NETTLE_MEMXOR_H_INCLUDED #include #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define memxor nettle_memxor #define memxor3 nettle_memxor3 void *memxor(void *dst, const void *src, size_t n); void *memxor3(void *dst, const void *a, const void *b, size_t n); #ifdef __cplusplus } #endif #endif /* NETTLE_MEMXOR_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/nettle-meta.h ================================================ /* nettle-meta.h Information about algorithms. Copyright (C) 2002, 2014, 2020 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_META_H_INCLUDED #define NETTLE_META_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif struct nettle_cipher { const char *name; unsigned context_size; /* Zero for stream ciphers */ unsigned block_size; /* Suggested key size; other sizes are sometimes possible. */ unsigned key_size; nettle_set_key_func *set_encrypt_key; nettle_set_key_func *set_decrypt_key; nettle_cipher_func *encrypt; nettle_cipher_func *decrypt; }; /* null-terminated list of ciphers implemented by this version of nettle */ const struct nettle_cipher * const * _NETTLE_ATTRIBUTE_PURE nettle_get_ciphers (void); #define nettle_ciphers (nettle_get_ciphers()) extern const struct nettle_cipher nettle_aes128; extern const struct nettle_cipher nettle_aes192; extern const struct nettle_cipher nettle_aes256; extern const struct nettle_cipher nettle_camellia128; extern const struct nettle_cipher nettle_camellia192; extern const struct nettle_cipher nettle_camellia256; extern const struct nettle_cipher nettle_cast128; extern const struct nettle_cipher nettle_serpent128; extern const struct nettle_cipher nettle_serpent192; extern const struct nettle_cipher nettle_serpent256; extern const struct nettle_cipher nettle_twofish128; extern const struct nettle_cipher nettle_twofish192; extern const struct nettle_cipher nettle_twofish256; extern const struct nettle_cipher nettle_arctwo40; extern const struct nettle_cipher nettle_arctwo64; extern const struct nettle_cipher nettle_arctwo128; extern const struct nettle_cipher nettle_arctwo_gutmann128; extern const struct nettle_cipher nettle_sm4; struct nettle_hash { const char *name; /* Size of the context struct */ unsigned context_size; /* Size of digests */ unsigned digest_size; /* Internal block size */ unsigned block_size; nettle_hash_init_func *init; nettle_hash_update_func *update; nettle_hash_digest_func *digest; }; #define _NETTLE_HASH(name, NAME) { \ #name, \ sizeof(struct name##_ctx), \ NAME##_DIGEST_SIZE, \ NAME##_BLOCK_SIZE, \ (nettle_hash_init_func *) name##_init, \ (nettle_hash_update_func *) name##_update, \ (nettle_hash_digest_func *) name##_digest \ } /* null-terminated list of digests implemented by this version of nettle */ const struct nettle_hash * const * _NETTLE_ATTRIBUTE_PURE nettle_get_hashes (void); #define nettle_hashes (nettle_get_hashes()) const struct nettle_hash * nettle_lookup_hash (const char *name); extern const struct nettle_hash nettle_md2; extern const struct nettle_hash nettle_md4; extern const struct nettle_hash nettle_md5; extern const struct nettle_hash nettle_gosthash94; extern const struct nettle_hash nettle_gosthash94cp; extern const struct nettle_hash nettle_ripemd160; extern const struct nettle_hash nettle_sha1; extern const struct nettle_hash nettle_sha224; extern const struct nettle_hash nettle_sha256; extern const struct nettle_hash nettle_sha384; extern const struct nettle_hash nettle_sha512; extern const struct nettle_hash nettle_sha512_224; extern const struct nettle_hash nettle_sha512_256; extern const struct nettle_hash nettle_sha3_224; extern const struct nettle_hash nettle_sha3_256; extern const struct nettle_hash nettle_sha3_384; extern const struct nettle_hash nettle_sha3_512; extern const struct nettle_hash nettle_streebog256; extern const struct nettle_hash nettle_streebog512; extern const struct nettle_hash nettle_sm3; struct nettle_mac { const char *name; /* Size of the context struct */ unsigned context_size; /* Size of digests */ unsigned digest_size; /* Key size */ unsigned key_size; nettle_set_key_func *set_key; nettle_hash_update_func *update; nettle_hash_digest_func *digest; }; struct nettle_aead { const char *name; unsigned context_size; /* Block size for encrypt and decrypt. */ unsigned block_size; unsigned key_size; unsigned nonce_size; unsigned digest_size; nettle_set_key_func *set_encrypt_key; nettle_set_key_func *set_decrypt_key; nettle_set_key_func *set_nonce; nettle_hash_update_func *update; nettle_crypt_func *encrypt; nettle_crypt_func *decrypt; /* FIXME: Drop length argument? */ nettle_hash_digest_func *digest; }; /* null-terminated list of aead constructions implemented by this version of nettle */ const struct nettle_aead * const * _NETTLE_ATTRIBUTE_PURE nettle_get_aeads (void); #define nettle_aeads (nettle_get_aeads()) extern const struct nettle_aead nettle_gcm_aes128; extern const struct nettle_aead nettle_gcm_aes192; extern const struct nettle_aead nettle_gcm_aes256; extern const struct nettle_aead nettle_gcm_camellia128; extern const struct nettle_aead nettle_gcm_camellia256; extern const struct nettle_aead nettle_gcm_sm4; extern const struct nettle_aead nettle_eax_aes128; extern const struct nettle_aead nettle_chacha_poly1305; struct nettle_armor { const char *name; unsigned encode_context_size; unsigned decode_context_size; unsigned encode_final_length; nettle_armor_init_func *encode_init; nettle_armor_length_func *encode_length; nettle_armor_encode_update_func *encode_update; nettle_armor_encode_final_func *encode_final; nettle_armor_init_func *decode_init; nettle_armor_length_func *decode_length; nettle_armor_decode_update_func *decode_update; nettle_armor_decode_final_func *decode_final; }; #define _NETTLE_ARMOR(name, NAME) { \ #name, \ sizeof(struct name##_encode_ctx), \ sizeof(struct name##_decode_ctx), \ NAME##_ENCODE_FINAL_LENGTH, \ (nettle_armor_init_func *) name##_encode_init, \ (nettle_armor_length_func *) name##_encode_length, \ (nettle_armor_encode_update_func *) name##_encode_update, \ (nettle_armor_encode_final_func *) name##_encode_final, \ (nettle_armor_init_func *) name##_decode_init, \ (nettle_armor_length_func *) name##_decode_length, \ (nettle_armor_decode_update_func *) name##_decode_update, \ (nettle_armor_decode_final_func *) name##_decode_final, \ } #define _NETTLE_ARMOR_0(name, NAME) { \ #name, \ 0, \ sizeof(struct name##_decode_ctx), \ NAME##_ENCODE_FINAL_LENGTH, \ (nettle_armor_init_func *) name##_encode_init, \ (nettle_armor_length_func *) name##_encode_length, \ (nettle_armor_encode_update_func *) name##_encode_update, \ (nettle_armor_encode_final_func *) name##_encode_final, \ (nettle_armor_init_func *) name##_decode_init, \ (nettle_armor_length_func *) name##_decode_length, \ (nettle_armor_decode_update_func *) name##_decode_update, \ (nettle_armor_decode_final_func *) name##_decode_final, \ } /* null-terminated list of armor schemes implemented by this version of nettle */ const struct nettle_armor * const * _NETTLE_ATTRIBUTE_PURE nettle_get_armors (void); #define nettle_armors (nettle_get_armors()) extern const struct nettle_armor nettle_base64; extern const struct nettle_armor nettle_base64url; extern const struct nettle_armor nettle_base16; #define _NETTLE_HMAC(name, HASH) { \ #name, \ sizeof(struct name##_ctx), \ HASH##_DIGEST_SIZE, \ HASH##_DIGEST_SIZE, \ name##_set_key_wrapper, \ (nettle_hash_update_func *) name##_update, \ (nettle_hash_digest_func *) name##_digest, \ } /* null-terminated list of macs implemented by this version of nettle */ const struct nettle_mac * const * _NETTLE_ATTRIBUTE_PURE nettle_get_macs (void); #define nettle_macs (nettle_get_macs()) extern const struct nettle_mac nettle_cmac_aes128; extern const struct nettle_mac nettle_cmac_aes256; extern const struct nettle_mac nettle_cmac_des3; /* HMAC variants with key size = digest size */ extern const struct nettle_mac nettle_hmac_md5; extern const struct nettle_mac nettle_hmac_ripemd160; extern const struct nettle_mac nettle_hmac_sha1; extern const struct nettle_mac nettle_hmac_sha224; extern const struct nettle_mac nettle_hmac_sha256; extern const struct nettle_mac nettle_hmac_sha384; extern const struct nettle_mac nettle_hmac_sha512; extern const struct nettle_mac nettle_hmac_streebog256; extern const struct nettle_mac nettle_hmac_streebog512; extern const struct nettle_mac nettle_hmac_sm3; #ifdef __cplusplus } #endif #endif /* NETTLE_META_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/nettle-types.h ================================================ /* nettle-types.h Copyright (C) 2005, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_TYPES_H #define NETTLE_TYPES_H /* For size_t */ #include #include /* Attributes we want to use in installed header files, and hence can't rely on config.h. */ #ifdef __GNUC__ #define _NETTLE_ATTRIBUTE_PURE __attribute__((pure)) #ifndef _NETTLE_ATTRIBUTE_DEPRECATED /* Variant without message is supported since gcc-3.1 or so. */ #define _NETTLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated)) #endif #else /* !__GNUC__ */ #define _NETTLE_ATTRIBUTE_PURE #define _NETTLE_ATTRIBUTE_DEPRECATED #endif /* !__GNUC__ */ #ifdef __cplusplus extern "C" { #endif /* An aligned 16-byte block. */ union nettle_block16 { uint8_t b[16]; unsigned long w[16 / sizeof(unsigned long)] _NETTLE_ATTRIBUTE_DEPRECATED; uint64_t u64[2]; }; union nettle_block8 { uint8_t b[8]; uint64_t u64; }; /* Randomness. Used by key generation and dsa signature creation. */ typedef void nettle_random_func(void *ctx, size_t length, uint8_t *dst); /* Progress report function, mainly for key generation. */ typedef void nettle_progress_func(void *ctx, int c); /* Realloc function, used by struct nettle_buffer. */ typedef void *nettle_realloc_func(void *ctx, void *p, size_t length); /* Ciphers */ typedef void nettle_set_key_func(void *ctx, const uint8_t *key); /* For block ciphers, const context. */ typedef void nettle_cipher_func(const void *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* Uses a void * for cipher contexts. Used for crypt operations where the internal state changes during the encryption. */ typedef void nettle_crypt_func(void *ctx, size_t length, uint8_t *dst, const uint8_t *src); /* Hash algorithms */ typedef void nettle_hash_init_func(void *ctx); typedef void nettle_hash_update_func(void *ctx, size_t length, const uint8_t *src); typedef void nettle_hash_digest_func(void *ctx, size_t length, uint8_t *dst); /* ASCII armor codecs. NOTE: Experimental and subject to change. */ typedef size_t nettle_armor_length_func(size_t length); typedef void nettle_armor_init_func(void *ctx); typedef size_t nettle_armor_encode_update_func(void *ctx, char *dst, size_t src_length, const uint8_t *src); typedef size_t nettle_armor_encode_final_func(void *ctx, char *dst); typedef int nettle_armor_decode_update_func(void *ctx, size_t *dst_length, uint8_t *dst, size_t src_length, const char *src); typedef int nettle_armor_decode_final_func(void *ctx); #ifdef __cplusplus } #endif #endif /* NETTLE_TYPES_H */ ================================================ FILE: thirdparty/64/include/nettle/nist-keywrap.h ================================================ /* nist-keywrap.h AES Key Wrap function. implements RFC 3394 https://tools.ietf.org/html/rfc3394 Copyright (C) 2021 Nicolas Mora 2021 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_NIST_KEYWRAP_H_INCLUDED #define NETTLE_NIST_KEYWRAP_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define nist_keywrap16 nettle_nist_keywrap16 #define nist_keyunwrap16 nettle_nist_keyunwrap16 #define aes128_keywrap nettle_aes128_keywrap #define aes192_keywrap nettle_aes192_keywrap #define aes256_keywrap nettle_aes256_keywrap #define aes128_keyunwrap nettle_aes128_keyunwrap #define aes192_keyunwrap nettle_aes192_keyunwrap #define aes256_keyunwrap nettle_aes256_keyunwrap void nist_keywrap16 (const void *ctx, nettle_cipher_func *encrypt, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); int nist_keyunwrap16 (const void *ctx, nettle_cipher_func *decrypt, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); void aes128_keywrap (struct aes128_ctx *ctx, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); void aes192_keywrap (struct aes192_ctx *ctx, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); void aes256_keywrap (struct aes256_ctx *ctx, const uint8_t *iv, size_t ciphertext_length, uint8_t *ciphertext, const uint8_t *cleartext); int aes128_keyunwrap (struct aes128_ctx *ctx, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); int aes192_keyunwrap (struct aes192_ctx *ctx, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); int aes256_keyunwrap (struct aes256_ctx *ctx, const uint8_t *iv, size_t cleartext_length, uint8_t *cleartext, const uint8_t *ciphertext); #ifdef __cplusplus } #endif #endif /* NETTLE_NIST_KEYWRAP_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/ocb.h ================================================ /* ocb.h OCB AEAD mode, RFC 7253 Copyright (C) 2021 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_OCB_H_INCLUDED #define NETTLE_OCB_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define ocb_set_key nettle_ocb_set_key #define ocb_set_nonce nettle_ocb_set_nonce #define ocb_update nettle_ocb_update #define ocb_encrypt nettle_ocb_encrypt #define ocb_decrypt nettle_ocb_decrypt #define ocb_digest nettle_ocb_digest #define ocb_encrypt_message nettle_ocb_encrypt_message #define ocb_decrypt_message nettle_ocb_decrypt_message #define ocb_aes128_set_encrypt_key nettle_ocb_aes128_set_encrypt_key #define ocb_aes128_set_decrypt_key nettle_ocb_aes128_set_decrypt_key #define ocb_aes128_set_nonce nettle_ocb_aes128_set_nonce #define ocb_aes128_update nettle_ocb_aes128_update #define ocb_aes128_encrypt nettle_ocb_aes128_encrypt #define ocb_aes128_decrypt nettle_ocb_aes128_decrypt #define ocb_aes128_digest nettle_ocb_aes128_digest #define ocb_aes128_encrypt_message nettle_ocb_aes128_encrypt_message #define ocb_aes128_decrypt_message nettle_ocb_aes128_decrypt_message #define OCB_BLOCK_SIZE 16 #define OCB_DIGEST_SIZE 16 #define OCB_MAX_NONCE_SIZE 15 struct ocb_key { /* L_*, L_$ and L_0, and one reserved entry */ union nettle_block16 L[4]; }; struct ocb_ctx { /* Initial offset, Offset_0 in the spec. */ union nettle_block16 initial; /* Offset, updated per block. */ union nettle_block16 offset; /* Authentication for the associated data */ union nettle_block16 sum; /* Authentication for the message */ union nettle_block16 checksum; /* Count of processed blocks. */ size_t data_count; size_t message_count; }; void ocb_set_key (struct ocb_key *key, const void *cipher, nettle_cipher_func *f); void ocb_set_nonce (struct ocb_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t tag_length, size_t nonce_length, const uint8_t *nonce); void ocb_update (struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, const uint8_t *data); void ocb_encrypt (struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src); void ocb_decrypt (struct ocb_ctx *ctx, const struct ocb_key *key, const void *encrypt_ctx, nettle_cipher_func *encrypt, const void *decrypt_ctx, nettle_cipher_func *decrypt, size_t length, uint8_t *dst, const uint8_t *src); void ocb_digest (const struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest); void ocb_encrypt_message (const struct ocb_key *ocb_key, const void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ocb_decrypt_message (const struct ocb_key *ocb_key, const void *encrypt_ctx, nettle_cipher_func *encrypt, const void *decrypt_ctx, nettle_cipher_func *decrypt, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); /* OCB-AES */ /* This struct represents an expanded key for ocb-aes encryption. For decryption, a separate decryption context is needed as well. */ struct ocb_aes128_encrypt_key { struct ocb_key ocb; struct aes128_ctx encrypt; }; void ocb_aes128_set_encrypt_key (struct ocb_aes128_encrypt_key *ocb, const uint8_t *key); void ocb_aes128_set_decrypt_key (struct ocb_aes128_encrypt_key *ocb, struct aes128_ctx *decrypt, const uint8_t *key); void ocb_aes128_set_nonce (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t tag_length, size_t nonce_length, const uint8_t *nonce); void ocb_aes128_update (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, const uint8_t *data); void ocb_aes128_encrypt(struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, uint8_t *dst, const uint8_t *src); void ocb_aes128_decrypt(struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, const struct aes128_ctx *decrypt, size_t length, uint8_t *dst, const uint8_t *src); void ocb_aes128_digest(struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, uint8_t *digest); void ocb_aes128_encrypt_message (const struct ocb_aes128_encrypt_key *key, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src); int ocb_aes128_decrypt_message (const struct ocb_aes128_encrypt_key *key, const struct aes128_ctx *decrypt, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_OCB_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/pbkdf2.h ================================================ /* pbkdf2.h PKCS #5 password-based key derivation function PBKDF2, see RFC 2898. Copyright (C) 2012 Simon Josefsson This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PBKDF2_H_INCLUDED #define NETTLE_PBKDF2_H_INCLUDED #include "nettle-meta.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define pbkdf2 nettle_pbkdf2 #define pbkdf2_hmac_sha1 nettle_pbkdf2_hmac_sha1 #define pbkdf2_hmac_sha256 nettle_pbkdf2_hmac_sha256 #define pbkdf2_hmac_sha384 nettle_pbkdf2_hmac_sha384 #define pbkdf2_hmac_sha512 nettle_pbkdf2_hmac_sha512 #define pbkdf2_hmac_gosthash94cp nettle_pbkdf2_hmac_gosthash94cp void pbkdf2 (void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); #define PBKDF2(ctx, update, digest, digest_size, \ iterations, salt_length, salt, length, dst) \ (0 ? ((update)((ctx), 0, (uint8_t *) 0), \ (digest)((ctx), 0, (uint8_t *) 0)) \ : pbkdf2 ((ctx), \ (nettle_hash_update_func *)(update), \ (nettle_hash_digest_func *)(digest), \ (digest_size), (iterations), \ (salt_length), (salt), (length), (dst))) /* PBKDF2 with specific PRFs. */ void pbkdf2_hmac_sha1 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_sha256 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_sha384 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_sha512 (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); void pbkdf2_hmac_gosthash94cp (size_t key_length, const uint8_t *key, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst); #ifdef __cplusplus } #endif #endif /* NETTLE_PBKDF2_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/pgp.h ================================================ /* pgp.h PGP related functions. Copyright (C) 2001, 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PGP_H_INCLUDED #define NETTLE_PGP_H_INCLUDED #include #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define pgp_put_uint32 nettle_pgp_put_uint32 #define pgp_put_uint16 nettle_pgp_put_uint16 #define pgp_put_mpi nettle_pgp_put_mpi #define pgp_put_string nettle_pgp_put_string #define pgp_put_length nettle_pgp_put_length #define pgp_put_header nettle_pgp_put_header #define pgp_put_header_length nettle_pgp_put_header_length #define pgp_sub_packet_start nettle_pgp_sub_packet_start #define pgp_put_sub_packet nettle_pgp_put_sub_packet #define pgp_sub_packet_end nettle_pgp_sub_packet_end #define pgp_put_public_rsa_key nettle_pgp_put_public_rsa_key #define pgp_put_rsa_sha1_signature nettle_pgp_put_rsa_sha1_signature #define pgp_put_userid nettle_pgp_put_userid #define pgp_crc24 nettle_pgp_crc24 #define pgp_armor nettle_pgp_armor struct nettle_buffer; struct rsa_public_key; struct rsa_private_key; struct sha1_ctx; int pgp_put_uint32(struct nettle_buffer *buffer, uint32_t i); int pgp_put_uint16(struct nettle_buffer *buffer, unsigned i); int pgp_put_mpi(struct nettle_buffer *buffer, const mpz_t x); int pgp_put_string(struct nettle_buffer *buffer, unsigned length, const uint8_t *s); int pgp_put_length(struct nettle_buffer *buffer, unsigned length); int pgp_put_header(struct nettle_buffer *buffer, unsigned tag, unsigned length); void pgp_put_header_length(struct nettle_buffer *buffer, /* start of the header */ unsigned start, unsigned field_size); unsigned pgp_sub_packet_start(struct nettle_buffer *buffer); int pgp_put_sub_packet(struct nettle_buffer *buffer, unsigned type, unsigned length, const uint8_t *data); void pgp_sub_packet_end(struct nettle_buffer *buffer, unsigned start); int pgp_put_public_rsa_key(struct nettle_buffer *, const struct rsa_public_key *key, time_t timestamp); int pgp_put_rsa_sha1_signature(struct nettle_buffer *buffer, const struct rsa_private_key *key, const uint8_t *keyid, unsigned type, struct sha1_ctx *hash); int pgp_put_userid(struct nettle_buffer *buffer, unsigned length, const uint8_t *name); uint32_t pgp_crc24(unsigned length, const uint8_t *data); int pgp_armor(struct nettle_buffer *buffer, const char *tag, unsigned length, const uint8_t *data); /* Values that can be passed to pgp_put_header when the size of the * length field, but not the length itself, is known. Also the minimum length * for the given field size. */ enum pgp_lengths { PGP_LENGTH_ONE_OCTET = 0, PGP_LENGTH_TWO_OCTETS = 192, PGP_LENGTH_FOUR_OCTETS = 8384, }; enum pgp_public_key_algorithm { PGP_RSA = 1, PGP_RSA_ENCRYPT = 2, PGP_RSA_SIGN = 3, PGP_EL_GAMAL_ENCRYPT = 16, PGP_DSA = 17, PGP_EL_GAMAL = 20, }; enum pgp_symmetric_algorithm { PGP_PLAINTEXT = 0, PGP_IDEA = 1, PGP_3DES = 2, PGP_CAST5 = 3, PGP_BLOWFISH = 4, PGP_SAFER_SK = 5, PGP_AES128 = 7, PGP_AES192 = 8, PGP_AES256 = 9, }; enum pgp_compression_algorithm { PGP_UNCOMPRESSED = 0, PGP_ZIP = 1, PGP_ZLIB = 2, }; enum pgp_hash_algorithm { PGP_MD5 = 1, PGP_SHA1 = 2, PGP_RIPEMD = 3, PGP_MD2 = 5, PGP_TIGER192 = 6, PGP_HAVAL = 7, }; enum pgp_tag { PGP_TAG_PUBLIC_SESSION_KEY = 1, PGP_TAG_SIGNATURE = 2, PGP_TAG_SYMMETRIC_SESSION_KEY = 3, PGP_TAG_ONE_PASS_SIGNATURE = 4, PGP_TAG_SECRET_KEY = 5, PGP_TAG_PUBLIC_KEY = 6, PGP_TAG_SECRET_SUBKEY = 7, PGP_TAG_COMPRESSED = 8, PGP_TAG_ENCRYPTED = 9, PGP_TAG_MARKER = 10, PGP_TAG_LITERAL = 11, PGP_TAG_TRUST = 12, PGP_TAG_USERID = 13, PGP_TAG_PUBLIC_SUBKEY = 14, }; enum pgp_signature_type { PGP_SIGN_BINARY = 0, PGP_SIGN_TEXT = 1, PGP_SIGN_STANDALONE = 2, PGP_SIGN_CERTIFICATION = 0x10, PGP_SIGN_CERTIFICATION_PERSONA = 0x11, PGP_SIGN_CERTIFICATION_CASUAL = 0x12, PGP_SIGN_CERTIFICATION_POSITIVE = 0x13, PGP_SIGN_SUBKEY = 0x18, PGP_SIGN_KEY = 0x1f, PGP_SIGN_REVOCATION = 0x20, PGP_SIGN_REVOCATION_SUBKEY = 0x28, PGP_SIGN_REVOCATION_CERTIFICATE = 0x30, PGP_SIGN_TIMESTAMP = 0x40, }; enum pgp_subpacket_tag { PGP_SUBPACKET_CREATION_TIME = 2, PGP_SUBPACKET_SIGNATURE_EXPIRATION_TIME = 3, PGP_SUBPACKET_EXPORTABLE_CERTIFICATION = 4, PGP_SUBPACKET_TRUST_SIGNATURE = 5, PGP_SUBPACKET_REGULAR_EXPRESSION = 6, PGP_SUBPACKET_REVOCABLE = 7, PGP_SUBPACKET_KEY_EXPIRATION_TIME = 9, PGP_SUBPACKET_PLACEHOLDER = 10 , PGP_SUBPACKET_PREFERRED_SYMMETRIC_ALGORITHMS = 11, PGP_SUBPACKET_REVOCATION_KEY = 12, PGP_SUBPACKET_ISSUER_KEY_ID = 16, PGP_SUBPACKET_NOTATION_DATA = 20, PGP_SUBPACKET_PREFERRED_HASH_ALGORITHMS = 21, PGP_SUBPACKET_PREFERRED_COMPRESSION_ALGORITHMS = 22, PGP_SUBPACKET_KEY_SERVER_PREFERENCES = 23, PGP_SUBPACKET_PREFERRED_KEY_SERVER = 24, PGP_SUBPACKET_PRIMARY_USER_ID = 25, PGP_SUBPACKET_POLICY_URL = 26, PGP_SUBPACKET_KEY_FLAGS = 27, PGP_SUBPACKET_SIGNERS_USER_ID = 28, PGP_SUBPACKET_REASON_FOR_REVOCATION = 29, }; #ifdef __cplusplus } #endif #endif /* NETTLE_PGP_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/pkcs1.h ================================================ /* pkcs1.h PKCS1 embedding. Copyright (C) 2003 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PKCS1_H_INCLUDED #define NETTLE_PKCS1_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define pkcs1_rsa_digest_encode nettle_pkcs1_rsa_digest_encode #define pkcs1_rsa_md5_encode nettle_pkcs1_rsa_md5_encode #define pkcs1_rsa_md5_encode_digest nettle_pkcs1_rsa_md5_encode_digest #define pkcs1_rsa_sha1_encode nettle_pkcs1_rsa_sha1_encode #define pkcs1_rsa_sha1_encode_digest nettle_pkcs1_rsa_sha1_encode_digest #define pkcs1_rsa_sha256_encode nettle_pkcs1_rsa_sha256_encode #define pkcs1_rsa_sha256_encode_digest nettle_pkcs1_rsa_sha256_encode_digest #define pkcs1_rsa_sha512_encode nettle_pkcs1_rsa_sha512_encode #define pkcs1_rsa_sha512_encode_digest nettle_pkcs1_rsa_sha512_encode_digest #define pkcs1_encrypt nettle_pkcs1_encrypt #define pkcs1_decrypt nettle_pkcs1_decrypt struct md5_ctx; struct sha1_ctx; struct sha256_ctx; struct sha512_ctx; int pkcs1_encrypt (size_t key_size, /* For padding */ void *random_ctx, nettle_random_func *random, size_t length, const uint8_t *message, mpz_t m); int pkcs1_decrypt (size_t key_size, const mpz_t m, size_t *length, uint8_t *message); int pkcs1_rsa_digest_encode(mpz_t m, size_t key_size, size_t di_length, const uint8_t *digest_info); int pkcs1_rsa_md5_encode(mpz_t m, size_t length, struct md5_ctx *hash); int pkcs1_rsa_md5_encode_digest(mpz_t m, size_t length, const uint8_t *digest); int pkcs1_rsa_sha1_encode(mpz_t m, size_t length, struct sha1_ctx *hash); int pkcs1_rsa_sha1_encode_digest(mpz_t m, size_t length, const uint8_t *digest); int pkcs1_rsa_sha256_encode(mpz_t m, size_t length, struct sha256_ctx *hash); int pkcs1_rsa_sha256_encode_digest(mpz_t m, size_t length, const uint8_t *digest); int pkcs1_rsa_sha512_encode(mpz_t m, size_t length, struct sha512_ctx *hash); int pkcs1_rsa_sha512_encode_digest(mpz_t m, size_t length, const uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_PKCS1_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/poly1305.h ================================================ /* poly1305.h Poly1305 message authentication code. Copyright (C) 2013 Nikos Mavrogiannopoulos Copyright (C) 2013, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_POLY1305_H_INCLUDED #define NETTLE_POLY1305_H_INCLUDED #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define poly1305_aes_set_key nettle_poly1305_aes_set_key #define poly1305_aes_set_nonce nettle_poly1305_aes_set_nonce #define poly1305_aes_update nettle_poly1305_aes_update #define poly1305_aes_digest nettle_poly1305_aes_digest /* Low level functions/macros for the poly1305 construction. */ #define POLY1305_BLOCK_SIZE 16 struct poly1305_ctx { /* Key, 128-bit value and some cached multiples. */ union { uint32_t r32[6]; uint64_t r64[3]; } r; uint32_t s32[3]; /* State, represented as words of 26, 32 or 64 bits, depending on implementation. */ /* High bits first, to maintain alignment. */ uint32_t hh; union { uint32_t h32[4]; uint64_t h64[2]; } h; }; /* poly1305-aes */ #define POLY1305_AES_KEY_SIZE 32 #define POLY1305_AES_DIGEST_SIZE 16 #define POLY1305_AES_NONCE_SIZE 16 struct poly1305_aes_ctx { /* Keep aes context last, to make it possible to use a general poly1305_update if other variants are added. */ struct poly1305_ctx pctx; uint8_t block[POLY1305_BLOCK_SIZE]; unsigned index; uint8_t nonce[POLY1305_BLOCK_SIZE]; struct aes128_ctx aes; }; /* Also initialize the nonce to zero. */ void poly1305_aes_set_key (struct poly1305_aes_ctx *ctx, const uint8_t *key); /* Optional, if not used, messages get incrementing nonces starting from zero. */ void poly1305_aes_set_nonce (struct poly1305_aes_ctx *ctx, const uint8_t *nonce); /* Update is not aes-specific, but since this is the only implemented variant, we need no more general poly1305_update. */ void poly1305_aes_update (struct poly1305_aes_ctx *ctx, size_t length, const uint8_t *data); /* Also increments the nonce */ void poly1305_aes_digest (struct poly1305_aes_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_POLY1305_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/pss-mgf1.h ================================================ /* pss-mgf1.h PKCS#1 mask generation function 1, used in RSA-PSS (RFC-3447). Copyright (C) 2017 Daiki Ueno This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PSS_MGF1_H_INCLUDED #define NETTLE_PSS_MGF1_H_INCLUDED #include "nettle-meta.h" #include "sha1.h" #include "sha2.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define pss_mgf1 nettle_pss_mgf1 void pss_mgf1(const void *seed, const struct nettle_hash *hash, size_t length, uint8_t *mask); #ifdef __cplusplus } #endif #endif /* NETTLE_PSS_MGF1_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/pss.h ================================================ /* pss.h PKCS#1 RSA-PSS (RFC-3447). Copyright (C) 2017 Daiki Ueno This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_PSS_H_INCLUDED #define NETTLE_PSS_H_INCLUDED #include "nettle-meta.h" #include "bignum.h" #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define pss_encode_mgf1 nettle_pss_encode_mgf1 #define pss_verify_mgf1 nettle_pss_verify_mgf1 int pss_encode_mgf1(mpz_t m, size_t bits, const struct nettle_hash *hash, size_t salt_length, const uint8_t *salt, const uint8_t *digest); int pss_verify_mgf1(const mpz_t m, size_t bits, const struct nettle_hash *hash, size_t salt_length, const uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_PSS_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/realloc.h ================================================ /* realloc.h Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_REALLOC_H_INCLUDED #define NETTLE_REALLOC_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif nettle_realloc_func nettle_realloc; nettle_realloc_func nettle_xrealloc; #ifdef __cplusplus } #endif #endif /* NETTLE_REALLOC_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/ripemd160.h ================================================ /* ripemd160.h RIPEMD-160 hash function. Copyright (C) 2011 Andres Mejia This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_RIPEMD160_H_INCLUDED #define NETTLE_RIPEMD160_H_INCLUDED #ifdef __cplusplus extern "C" { #endif #include "nettle-types.h" /* Name mangling */ #define ripemd160_init nettle_ripemd160_init #define ripemd160_update nettle_ripemd160_update #define ripemd160_digest nettle_ripemd160_digest /* RIPEMD160 */ #define RIPEMD160_DIGEST_SIZE 20 #define RIPEMD160_BLOCK_SIZE 64 /* For backwards compatibility */ #define RIPEMD160_DATA_SIZE RIPEMD160_BLOCK_SIZE /* Digest is kept internally as 5 32-bit words. */ #define _RIPEMD160_DIGEST_LENGTH 5 struct ripemd160_ctx { uint32_t state[_RIPEMD160_DIGEST_LENGTH]; uint64_t count; /* 64-bit block count */ unsigned int index; uint8_t block[RIPEMD160_BLOCK_SIZE]; }; void ripemd160_init(struct ripemd160_ctx *ctx); void ripemd160_update(struct ripemd160_ctx *ctx, size_t length, const uint8_t *data); void ripemd160_digest(struct ripemd160_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_RIPEMD160_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/rsa.h ================================================ /* rsa.h The RSA publickey algorithm. Copyright (C) 2001, 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_RSA_H_INCLUDED #define NETTLE_RSA_H_INCLUDED #include "nettle-types.h" #include "bignum.h" #include "md5.h" #include "sha1.h" #include "sha2.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define rsa_public_key_init nettle_rsa_public_key_init #define rsa_public_key_clear nettle_rsa_public_key_clear #define rsa_public_key_prepare nettle_rsa_public_key_prepare #define rsa_private_key_init nettle_rsa_private_key_init #define rsa_private_key_clear nettle_rsa_private_key_clear #define rsa_private_key_prepare nettle_rsa_private_key_prepare #define rsa_pkcs1_verify nettle_rsa_pkcs1_verify #define rsa_pkcs1_sign nettle_rsa_pkcs1_sign #define rsa_pkcs1_sign_tr nettle_rsa_pkcs1_sign_tr #define rsa_md5_sign nettle_rsa_md5_sign #define rsa_md5_sign_tr nettle_rsa_md5_sign_tr #define rsa_md5_verify nettle_rsa_md5_verify #define rsa_sha1_sign nettle_rsa_sha1_sign #define rsa_sha1_sign_tr nettle_rsa_sha1_sign_tr #define rsa_sha1_verify nettle_rsa_sha1_verify #define rsa_sha256_sign nettle_rsa_sha256_sign #define rsa_sha256_sign_tr nettle_rsa_sha256_sign_tr #define rsa_sha256_verify nettle_rsa_sha256_verify #define rsa_sha512_sign nettle_rsa_sha512_sign #define rsa_sha512_sign_tr nettle_rsa_sha512_sign_tr #define rsa_sha512_verify nettle_rsa_sha512_verify #define rsa_md5_sign_digest nettle_rsa_md5_sign_digest #define rsa_md5_sign_digest_tr nettle_rsa_md5_sign_digest_tr #define rsa_md5_verify_digest nettle_rsa_md5_verify_digest #define rsa_sha1_sign_digest nettle_rsa_sha1_sign_digest #define rsa_sha1_sign_digest_tr nettle_rsa_sha1_sign_digest_tr #define rsa_sha1_verify_digest nettle_rsa_sha1_verify_digest #define rsa_sha256_sign_digest nettle_rsa_sha256_sign_digest #define rsa_sha256_sign_digest_tr nettle_rsa_sha256_sign_digest_tr #define rsa_sha256_verify_digest nettle_rsa_sha256_verify_digest #define rsa_sha512_sign_digest nettle_rsa_sha512_sign_digest #define rsa_sha512_sign_digest_tr nettle_rsa_sha512_sign_digest_tr #define rsa_sha512_verify_digest nettle_rsa_sha512_verify_digest #define rsa_pss_sha256_sign_digest_tr nettle_rsa_pss_sha256_sign_digest_tr #define rsa_pss_sha256_verify_digest nettle_rsa_pss_sha256_verify_digest #define rsa_pss_sha384_sign_digest_tr nettle_rsa_pss_sha384_sign_digest_tr #define rsa_pss_sha384_verify_digest nettle_rsa_pss_sha384_verify_digest #define rsa_pss_sha512_sign_digest_tr nettle_rsa_pss_sha512_sign_digest_tr #define rsa_pss_sha512_verify_digest nettle_rsa_pss_sha512_verify_digest #define rsa_encrypt nettle_rsa_encrypt #define rsa_decrypt nettle_rsa_decrypt #define rsa_decrypt_tr nettle_rsa_decrypt_tr #define rsa_sec_decrypt nettle_rsa_sec_decrypt #define rsa_compute_root nettle_rsa_compute_root #define rsa_compute_root_tr nettle_rsa_compute_root_tr #define rsa_generate_keypair nettle_rsa_generate_keypair #define rsa_keypair_to_sexp nettle_rsa_keypair_to_sexp #define rsa_keypair_from_sexp_alist nettle_rsa_keypair_from_sexp_alist #define rsa_keypair_from_sexp nettle_rsa_keypair_from_sexp #define rsa_public_key_from_der_iterator nettle_rsa_public_key_from_der_iterator #define rsa_private_key_from_der_iterator nettle_rsa_private_key_from_der_iterator #define rsa_keypair_from_der nettle_rsa_keypair_from_der #define rsa_keypair_to_openpgp nettle_rsa_keypair_to_openpgp /* This limit is somewhat arbitrary. Technically, the smallest modulo which makes sense at all is 15 = 3*5, phi(15) = 8, size 4 bits. But for ridiculously small keys, not all odd e are possible (e.g., for 5 bits, the only possible modulo is 3*7 = 21, phi(21) = 12, and e = 3 don't work). The smallest size that makes sense with pkcs#1, and which allows RSA encryption of one byte messages, is 12 octets, 89 bits. */ #define RSA_MINIMUM_N_OCTETS 12 #define RSA_MINIMUM_N_BITS (8*RSA_MINIMUM_N_OCTETS - 7) struct rsa_public_key { /* Size of the modulo, in octets. This is also the size of all * signatures that are created or verified with this key. */ size_t size; /* Modulo */ mpz_t n; /* Public exponent */ mpz_t e; }; struct rsa_private_key { size_t size; /* d is filled in by the key generation function; otherwise it's * completely unused. */ mpz_t d; /* The two factors */ mpz_t p; mpz_t q; /* d % (p-1), i.e. a e = 1 (mod (p-1)) */ mpz_t a; /* d % (q-1), i.e. b e = 1 (mod (q-1)) */ mpz_t b; /* modular inverse of q , i.e. c q = 1 (mod p) */ mpz_t c; }; /* Signing a message works as follows: * * Store the private key in a rsa_private_key struct. * * Call rsa_private_key_prepare. This initializes the size attribute * to the length of a signature. * * Initialize a hashing context, by callling * md5_init * * Hash the message by calling * md5_update * * Create the signature by calling * rsa_md5_sign * * The signature is represented as a mpz_t bignum. This call also * resets the hashing context. * * When done with the key and signature, don't forget to call * mpz_clear. */ /* Calls mpz_init to initialize bignum storage. */ void rsa_public_key_init(struct rsa_public_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void rsa_public_key_clear(struct rsa_public_key *key); int rsa_public_key_prepare(struct rsa_public_key *key); /* Calls mpz_init to initialize bignum storage. */ void rsa_private_key_init(struct rsa_private_key *key); /* Calls mpz_clear to deallocate bignum storage. */ void rsa_private_key_clear(struct rsa_private_key *key); int rsa_private_key_prepare(struct rsa_private_key *key); /* PKCS#1 style signatures */ int rsa_pkcs1_sign(const struct rsa_private_key *key, size_t length, const uint8_t *digest_info, mpz_t s); int rsa_pkcs1_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t length, const uint8_t *digest_info, mpz_t s); int rsa_pkcs1_verify(const struct rsa_public_key *key, size_t length, const uint8_t *digest_info, const mpz_t signature); int rsa_md5_sign(const struct rsa_private_key *key, struct md5_ctx *hash, mpz_t signature); int rsa_md5_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct md5_ctx *hash, mpz_t s); int rsa_md5_verify(const struct rsa_public_key *key, struct md5_ctx *hash, const mpz_t signature); int rsa_sha1_sign(const struct rsa_private_key *key, struct sha1_ctx *hash, mpz_t signature); int rsa_sha1_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha1_ctx *hash, mpz_t s); int rsa_sha1_verify(const struct rsa_public_key *key, struct sha1_ctx *hash, const mpz_t signature); int rsa_sha256_sign(const struct rsa_private_key *key, struct sha256_ctx *hash, mpz_t signature); int rsa_sha256_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha256_ctx *hash, mpz_t s); int rsa_sha256_verify(const struct rsa_public_key *key, struct sha256_ctx *hash, const mpz_t signature); int rsa_sha512_sign(const struct rsa_private_key *key, struct sha512_ctx *hash, mpz_t signature); int rsa_sha512_sign_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, struct sha512_ctx *hash, mpz_t s); int rsa_sha512_verify(const struct rsa_public_key *key, struct sha512_ctx *hash, const mpz_t signature); /* Variants taking the digest as argument. */ int rsa_md5_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_md5_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_md5_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); int rsa_sha1_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_sha1_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_sha1_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); int rsa_sha256_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_sha256_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_sha256_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); int rsa_sha512_sign_digest(const struct rsa_private_key *key, const uint8_t *digest, mpz_t s); int rsa_sha512_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, const uint8_t *digest, mpz_t s); int rsa_sha512_verify_digest(const struct rsa_public_key *key, const uint8_t *digest, const mpz_t signature); /* PSS style signatures */ int rsa_pss_sha256_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t salt_length, const uint8_t *salt, const uint8_t *digest, mpz_t s); int rsa_pss_sha256_verify_digest(const struct rsa_public_key *key, size_t salt_length, const uint8_t *digest, const mpz_t signature); int rsa_pss_sha384_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t salt_length, const uint8_t *salt, const uint8_t *digest, mpz_t s); int rsa_pss_sha384_verify_digest(const struct rsa_public_key *key, size_t salt_length, const uint8_t *digest, const mpz_t signature); int rsa_pss_sha512_sign_digest_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t salt_length, const uint8_t *salt, const uint8_t *digest, mpz_t s); int rsa_pss_sha512_verify_digest(const struct rsa_public_key *key, size_t salt_length, const uint8_t *digest, const mpz_t signature); /* RSA encryption, using PKCS#1 */ /* These functions uses the v1.5 padding. What should the v2 (OAEP) * functions be called? */ /* Returns 1 on success, 0 on failure, which happens if the * message is too long for the key. */ int rsa_encrypt(const struct rsa_public_key *key, /* For padding */ void *random_ctx, nettle_random_func *random, size_t length, const uint8_t *cleartext, mpz_t cipher); /* Message must point to a buffer of size *LENGTH. KEY->size is enough * for all valid messages. On success, *LENGTH is updated to reflect * the actual length of the message. Returns 1 on success, 0 on * failure, which happens if decryption failed or if the message * didn't fit. */ int rsa_decrypt(const struct rsa_private_key *key, size_t *length, uint8_t *cleartext, const mpz_t ciphertext); /* Timing-resistant version, using randomized RSA blinding. */ int rsa_decrypt_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t *length, uint8_t *message, const mpz_t gibberish); /* like rsa_decrypt_tr but with additional side-channel resistance. * NOTE: the length of the final message must be known in advance. */ int rsa_sec_decrypt(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, size_t length, uint8_t *message, const mpz_t gibberish); /* Compute x, the e:th root of m. Calling it with x == m is allowed. It is required that 0 <= m < n. */ void rsa_compute_root(const struct rsa_private_key *key, mpz_t x, const mpz_t m); /* Safer variant, using RSA blinding, and checking the result after CRT. It is required that 0 <= m < n. */ int rsa_compute_root_tr(const struct rsa_public_key *pub, const struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, mpz_t x, const mpz_t m); /* Key generation */ /* Note that the key structs must be initialized first. */ int rsa_generate_keypair(struct rsa_public_key *pub, struct rsa_private_key *key, void *random_ctx, nettle_random_func *random, void *progress_ctx, nettle_progress_func *progress, /* Desired size of modulo, in bits */ unsigned n_size, /* Desired size of public exponent, in bits. If * zero, the passed in value pub->e is used. */ unsigned e_size); #define RSA_SIGN(key, algorithm, ctx, length, data, signature) ( \ algorithm##_update(ctx, length, data), \ rsa_##algorithm##_sign(key, ctx, signature) \ ) #define RSA_VERIFY(key, algorithm, ctx, length, data, signature) ( \ algorithm##_update(ctx, length, data), \ rsa_##algorithm##_verify(key, ctx, signature) \ ) /* Keys in sexp form. */ struct nettle_buffer; /* Generates a public-key expression if PRIV is NULL .*/ int rsa_keypair_to_sexp(struct nettle_buffer *buffer, const char *algorithm_name, /* NULL means "rsa" */ const struct rsa_public_key *pub, const struct rsa_private_key *priv); struct sexp_iterator; int rsa_keypair_from_sexp_alist(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, struct sexp_iterator *i); /* If PRIV is NULL, expect a public-key expression. If PUB is NULL, * expect a private key expression and ignore the parts not needed for * the public key. */ /* Keys must be initialized before calling this function, as usual. */ int rsa_keypair_from_sexp(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, size_t length, const uint8_t *expr); /* Keys in PKCS#1 format. */ struct asn1_der_iterator; int rsa_public_key_from_der_iterator(struct rsa_public_key *pub, unsigned limit, struct asn1_der_iterator *i); int rsa_private_key_from_der_iterator(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, struct asn1_der_iterator *i); /* For public keys, use PRIV == NULL */ int rsa_keypair_from_der(struct rsa_public_key *pub, struct rsa_private_key *priv, unsigned limit, size_t length, const uint8_t *data); /* OpenPGP format. Experimental interface, subject to change. */ int rsa_keypair_to_openpgp(struct nettle_buffer *buffer, const struct rsa_public_key *pub, const struct rsa_private_key *priv, /* A single user id. NUL-terminated utf8. */ const char *userid); #ifdef __cplusplus } #endif #endif /* NETTLE_RSA_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/salsa20.h ================================================ /* salsa20.h The Salsa20 stream cipher. Copyright (C) 2012 Simon Josefsson Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SALSA20_H_INCLUDED #define NETTLE_SALSA20_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define salsa20_set_key nettle_salsa20_set_key #define salsa20_128_set_key nettle_salsa20_128_set_key #define salsa20_256_set_key nettle_salsa20_256_set_key #define salsa20_set_nonce nettle_salsa20_set_nonce #define salsa20_crypt nettle_salsa20_crypt #define salsa20r12_crypt nettle_salsa20r12_crypt /* Alias for backwards compatibility */ #define salsa20_set_iv nettle_salsa20_set_nonce /* In octets.*/ #define SALSA20_128_KEY_SIZE 16 #define SALSA20_256_KEY_SIZE 32 #define SALSA20_BLOCK_SIZE 64 #define SALSA20_NONCE_SIZE 8 #define SALSA20_IV_SIZE SALSA20_NONCE_SIZE /* Aliases */ #define SALSA20_MIN_KEY_SIZE 16 #define SALSA20_MAX_KEY_SIZE 32 #define SALSA20_KEY_SIZE 32 #define _SALSA20_INPUT_LENGTH 16 struct salsa20_ctx { /* Indices 1-4 and 11-14 holds the key (two identical copies for the shorter key size), indices 0, 5, 10, 15 are constant, indices 6, 7 are the IV, and indices 8, 9 are the block counter: C K K K K C I I B B C K K K K C */ uint32_t input[_SALSA20_INPUT_LENGTH]; }; void salsa20_128_set_key(struct salsa20_ctx *ctx, const uint8_t *key); void salsa20_256_set_key(struct salsa20_ctx *ctx, const uint8_t *key); void salsa20_set_key(struct salsa20_ctx *ctx, size_t length, const uint8_t *key); void salsa20_set_nonce(struct salsa20_ctx *ctx, const uint8_t *nonce); void salsa20_crypt(struct salsa20_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void salsa20r12_crypt(struct salsa20_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SALSA20_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/serpent.h ================================================ /* serpent.h The serpent block cipher. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Serpent is a 128-bit block cipher that accepts a key size of 256 * bits, designed by Ross Anderson, Eli Biham, and Lars Knudsen. See * http://www.cl.cam.ac.uk/~rja14/serpent.html for details. */ #ifndef NETTLE_SERPENT_H_INCLUDED #define NETTLE_SERPENT_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define serpent_set_key nettle_serpent_set_key #define serpent128_set_key nettle_serpent128_set_key #define serpent192_set_key nettle_serpent192_set_key #define serpent256_set_key nettle_serpent256_set_key #define serpent_encrypt nettle_serpent_encrypt #define serpent_decrypt nettle_serpent_decrypt #define SERPENT_BLOCK_SIZE 16 /* Other key lengths are possible, but the design of Serpent makes * smaller key lengths quite pointless; they cheated with the AES * requirements, using a 256-bit key length exclusively and just * padding it out if the desired key length was less, so there really * is no advantage to using key lengths less than 256 bits. */ #define SERPENT_KEY_SIZE 32 /* Allow keys of size 128 <= bits <= 256 */ #define SERPENT_MIN_KEY_SIZE 16 #define SERPENT_MAX_KEY_SIZE 32 #define SERPENT128_KEY_SIZE 16 #define SERPENT192_KEY_SIZE 24 #define SERPENT256_KEY_SIZE 32 struct serpent_ctx { uint32_t keys[33][4]; /* key schedule */ }; void serpent_set_key(struct serpent_ctx *ctx, size_t length, const uint8_t *key); void serpent128_set_key(struct serpent_ctx *ctx, const uint8_t *key); void serpent192_set_key(struct serpent_ctx *ctx, const uint8_t *key); void serpent256_set_key(struct serpent_ctx *ctx, const uint8_t *key); void serpent_encrypt(const struct serpent_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void serpent_decrypt(const struct serpent_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SERPENT_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/sexp.h ================================================ /* sexp.h Parsing s-expressions. Copyright (C) 2002 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SEXP_H_INCLUDED #define NETTLE_SEXP_H_INCLUDED #include #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sexp_iterator_first nettle_sexp_iterator_first #define sexp_transport_iterator_first nettle_sexp_transport_iterator_first #define sexp_iterator_next nettle_sexp_iterator_next #define sexp_iterator_enter_list nettle_sexp_iterator_enter_list #define sexp_iterator_exit_list nettle_sexp_iterator_exit_list #define sexp_iterator_subexpr nettle_sexp_iterator_subexpr #define sexp_iterator_get_uint32 nettle_sexp_iterator_get_uint32 #define sexp_iterator_check_type nettle_sexp_iterator_check_type #define sexp_iterator_check_types nettle_sexp_iterator_check_types #define sexp_iterator_assoc nettle_sexp_iterator_assoc #define sexp_format nettle_sexp_format #define sexp_vformat nettle_sexp_vformat #define sexp_transport_format nettle_sexp_transport_format #define sexp_transport_vformat nettle_sexp_transport_vformat #define sexp_token_chars nettle_sexp_token_chars enum sexp_type { SEXP_ATOM, SEXP_LIST, SEXP_END }; struct sexp_iterator { size_t length; const uint8_t *buffer; /* Points at the start of the current sub expression. */ size_t start; /* If type is SEXP_LIST, pos points at the start of the current * element. Otherwise, it points at the end. */ size_t pos; unsigned level; enum sexp_type type; size_t display_length; const uint8_t *display; size_t atom_length; const uint8_t *atom; }; /* All these functions return 1 on success, 0 on failure */ /* Initializes the iterator. */ int sexp_iterator_first(struct sexp_iterator *iterator, size_t length, const uint8_t *input); /* NOTE: Decodes the input string in place */ int sexp_transport_iterator_first(struct sexp_iterator *iterator, size_t length, uint8_t *input); int sexp_iterator_next(struct sexp_iterator *iterator); /* Current element must be a list. */ int sexp_iterator_enter_list(struct sexp_iterator *iterator); /* Skips the rest of the current list */ int sexp_iterator_exit_list(struct sexp_iterator *iterator); #if 0 /* Skips out of as many lists as necessary to get back to the given * level. */ int sexp_iterator_exit_lists(struct sexp_iterator *iterator, unsigned level); #endif /* Gets start and length of the current subexpression. Implies * sexp_iterator_next. */ const uint8_t * sexp_iterator_subexpr(struct sexp_iterator *iterator, size_t *length); int sexp_iterator_get_uint32(struct sexp_iterator *iterator, uint32_t *x); /* Checks the type of the current expression, which should be a list * * ( ...) */ int sexp_iterator_check_type(struct sexp_iterator *iterator, const char *type); const char * sexp_iterator_check_types(struct sexp_iterator *iterator, unsigned ntypes, const char * const *types); /* Current element must be a list. Looks up element of type * * (key rest...) * * For a matching key, the corresponding iterator is initialized * pointing at the start of REST. * * On success, exits the current list. */ int sexp_iterator_assoc(struct sexp_iterator *iterator, unsigned nkeys, const char * const *keys, struct sexp_iterator *values); /* Output functions. What is a reasonable API for this? It seems * ugly to have to reimplement string streams. */ /* Declared for real in buffer.h */ struct nettle_buffer; /* Returns the number of output characters, or 0 on out of memory. If * buffer == NULL, just compute length. * * Format strings can contained matched parentheses, tokens ("foo" in * the format string is formatted as "3:foo"), whitespace (which * separates tokens but is otherwise ignored) and the following * formatting specifiers: * * %s String represented as size_t length, const uint8_t *data. * * %t Optional display type, represented as * size_t display_length, const uint8_t *display, * display == NULL means no display type. * * %i Non-negative small integer, uint32_t. * * %b Non-negative bignum, mpz_t. * * %l Literal string (no length added), typically a balanced * subexpression. Represented as size_t length, const uint8_t * *data. * * %(, %) Allows insertion of unbalanced parenthesis. * * Modifiers: * * %0 For %s, %t and %l, says that there's no length argument, * instead the string is NUL-terminated, and there's only one * const uint8_t * argument. */ size_t sexp_format(struct nettle_buffer *buffer, const char *format, ...); size_t sexp_vformat(struct nettle_buffer *buffer, const char *format, va_list args); size_t sexp_transport_format(struct nettle_buffer *buffer, const char *format, ...); size_t sexp_transport_vformat(struct nettle_buffer *buffer, const char *format, va_list args); #ifdef __cplusplus } #endif #endif /* NETTLE_SEXP_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/sha.h ================================================ /* sha.h This file is deprecated, and provided only for backwards compatibility with earlier versions of Nettle. Please use sha1.h and/or sha2.h instead. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA_H_INCLUDED #define NETTLE_SHA_H_INCLUDED #include "sha1.h" #include "sha2.h" #endif /* NETTLE_SHA_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/sha1.h ================================================ /* sha1.h The sha1 hash function. Copyright (C) 2001, 2012 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA1_H_INCLUDED #define NETTLE_SHA1_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sha1_init nettle_sha1_init #define sha1_update nettle_sha1_update #define sha1_digest nettle_sha1_digest #define sha1_compress nettle_sha1_compress /* SHA1 */ #define SHA1_DIGEST_SIZE 20 #define SHA1_BLOCK_SIZE 64 /* For backwards compatibility */ #define SHA1_DATA_SIZE SHA1_BLOCK_SIZE /* Digest is kept internally as 5 32-bit words. */ #define _SHA1_DIGEST_LENGTH 5 struct sha1_ctx { uint32_t state[_SHA1_DIGEST_LENGTH]; /* State variables */ uint64_t count; /* 64-bit block count */ unsigned int index; /* index into buffer */ uint8_t block[SHA1_BLOCK_SIZE]; /* SHA1 data buffer */ }; void sha1_init(struct sha1_ctx *ctx); void sha1_update(struct sha1_ctx *ctx, size_t length, const uint8_t *data); void sha1_digest(struct sha1_ctx *ctx, size_t length, uint8_t *digest); /* SHA1 compression function. STATE points to 5 uint32_t words, and DATA points to 64 bytes of input data, possibly unaligned. */ void sha1_compress(uint32_t *state, const uint8_t *data); /* Old name, for backwards compatibility. */ #define _nettle_sha1_compress nettle_sha1_compress #ifdef __cplusplus } #endif #endif /* NETTLE_SHA1_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/sha2.h ================================================ /* sha2.h The sha2 family of hash functions. Copyright (C) 2001, 2012 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA2_H_INCLUDED #define NETTLE_SHA2_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sha224_init nettle_sha224_init #define sha224_digest nettle_sha224_digest #define sha256_init nettle_sha256_init #define sha256_update nettle_sha256_update #define sha256_digest nettle_sha256_digest #define sha256_compress nettle_sha256_compress #define sha384_init nettle_sha384_init #define sha384_digest nettle_sha384_digest #define sha512_init nettle_sha512_init #define sha512_update nettle_sha512_update #define sha512_digest nettle_sha512_digest #define sha512_compress nettle_sha512_compress #define sha512_224_init nettle_sha512_224_init #define sha512_224_digest nettle_sha512_224_digest #define sha512_256_init nettle_sha512_256_init #define sha512_256_digest nettle_sha512_256_digest /* For backwards compatibility */ #define SHA224_DATA_SIZE SHA256_BLOCK_SIZE #define SHA256_DATA_SIZE SHA256_BLOCK_SIZE #define SHA512_DATA_SIZE SHA512_BLOCK_SIZE #define SHA384_DATA_SIZE SHA512_BLOCK_SIZE /* SHA256 */ #define SHA256_DIGEST_SIZE 32 #define SHA256_BLOCK_SIZE 64 /* Digest is kept internally as 8 32-bit words. */ #define _SHA256_DIGEST_LENGTH 8 struct sha256_ctx { uint32_t state[_SHA256_DIGEST_LENGTH]; /* State variables */ uint64_t count; /* 64-bit block count */ unsigned int index; /* index into buffer */ uint8_t block[SHA256_BLOCK_SIZE]; /* SHA256 data buffer */ }; void sha256_init(struct sha256_ctx *ctx); void sha256_update(struct sha256_ctx *ctx, size_t length, const uint8_t *data); void sha256_digest(struct sha256_ctx *ctx, size_t length, uint8_t *digest); void sha256_compress(uint32_t *state, const uint8_t *input); /* SHA224, a truncated SHA256 with different initial state. */ #define SHA224_DIGEST_SIZE 28 #define SHA224_BLOCK_SIZE SHA256_BLOCK_SIZE #define sha224_ctx sha256_ctx void sha224_init(struct sha256_ctx *ctx); #define sha224_update nettle_sha256_update void sha224_digest(struct sha256_ctx *ctx, size_t length, uint8_t *digest); /* SHA512 */ #define SHA512_DIGEST_SIZE 64 #define SHA512_BLOCK_SIZE 128 /* Digest is kept internally as 8 64-bit words. */ #define _SHA512_DIGEST_LENGTH 8 struct sha512_ctx { uint64_t state[_SHA512_DIGEST_LENGTH]; /* State variables */ uint64_t count_low, count_high; /* 128-bit block count */ unsigned int index; /* index into buffer */ uint8_t block[SHA512_BLOCK_SIZE]; /* SHA512 data buffer */ }; void sha512_init(struct sha512_ctx *ctx); void sha512_update(struct sha512_ctx *ctx, size_t length, const uint8_t *data); void sha512_digest(struct sha512_ctx *ctx, size_t length, uint8_t *digest); void sha512_compress(uint64_t *state, const uint8_t *input); /* SHA384, a truncated SHA512 with different initial state. */ #define SHA384_DIGEST_SIZE 48 #define SHA384_BLOCK_SIZE SHA512_BLOCK_SIZE #define sha384_ctx sha512_ctx void sha384_init(struct sha512_ctx *ctx); #define sha384_update nettle_sha512_update void sha384_digest(struct sha512_ctx *ctx, size_t length, uint8_t *digest); /* SHA512_224 and SHA512_256, two truncated versions of SHA512 with different initial states. */ #define SHA512_224_DIGEST_SIZE 28 #define SHA512_224_BLOCK_SIZE SHA512_BLOCK_SIZE #define sha512_224_ctx sha512_ctx void sha512_224_init(struct sha512_224_ctx *ctx); #define sha512_224_update nettle_sha512_update void sha512_224_digest(struct sha512_224_ctx *ctx, size_t length, uint8_t *digest); #define SHA512_256_DIGEST_SIZE 32 #define SHA512_256_BLOCK_SIZE SHA512_BLOCK_SIZE #define sha512_256_ctx sha512_ctx void sha512_256_init(struct sha512_256_ctx *ctx); #define sha512_256_update nettle_sha512_update void sha512_256_digest(struct sha512_256_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_SHA2_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/sha3.h ================================================ /* sha3.h The sha3 hash function (aka Keccak). Copyright (C) 2012 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SHA3_H_INCLUDED #define NETTLE_SHA3_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sha3_permute nettle_sha3_permute #define sha3_224_init nettle_sha3_224_init #define sha3_224_update nettle_sha3_224_update #define sha3_224_digest nettle_sha3_224_digest #define sha3_256_init nettle_sha3_256_init #define sha3_256_update nettle_sha3_256_update #define sha3_256_digest nettle_sha3_256_digest #define sha3_256_shake nettle_sha3_256_shake #define sha3_384_init nettle_sha3_384_init #define sha3_384_update nettle_sha3_384_update #define sha3_384_digest nettle_sha3_384_digest #define sha3_512_init nettle_sha3_512_init #define sha3_512_update nettle_sha3_512_update #define sha3_512_digest nettle_sha3_512_digest /* Indicates that SHA3 is the NIST FIPS 202 version. */ #define NETTLE_SHA3_FIPS202 1 /* The sha3 state is a 5x5 matrix of 64-bit words. In the notation of Keccak description, S[x,y] is element x + 5*y, so if x is interpreted as the row index and y the column index, it is stored in column-major order. */ #define SHA3_STATE_LENGTH 25 /* The "width" is 1600 bits or 200 octets */ struct sha3_state { uint64_t a[SHA3_STATE_LENGTH]; }; void sha3_permute (struct sha3_state *state); /* The "capacity" is set to 2*(digest size), 512 bits or 64 octets. The "rate" is the width - capacity, or width - 2 * (digest size). */ #define SHA3_224_DIGEST_SIZE 28 #define SHA3_224_BLOCK_SIZE 144 #define SHA3_256_DIGEST_SIZE 32 #define SHA3_256_BLOCK_SIZE 136 #define SHA3_384_DIGEST_SIZE 48 #define SHA3_384_BLOCK_SIZE 104 #define SHA3_512_DIGEST_SIZE 64 #define SHA3_512_BLOCK_SIZE 72 /* For backwards compatibility */ #define SHA3_224_DATA_SIZE SHA3_224_BLOCK_SIZE #define SHA3_256_DATA_SIZE SHA3_256_BLOCK_SIZE #define SHA3_384_DATA_SIZE SHA3_384_BLOCK_SIZE #define SHA3_512_DATA_SIZE SHA3_512_BLOCK_SIZE struct sha3_224_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_224_BLOCK_SIZE]; }; void sha3_224_init (struct sha3_224_ctx *ctx); void sha3_224_update (struct sha3_224_ctx *ctx, size_t length, const uint8_t *data); void sha3_224_digest(struct sha3_224_ctx *ctx, size_t length, uint8_t *digest); struct sha3_256_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_256_BLOCK_SIZE]; }; void sha3_256_init (struct sha3_256_ctx *ctx); void sha3_256_update (struct sha3_256_ctx *ctx, size_t length, const uint8_t *data); void sha3_256_digest(struct sha3_256_ctx *ctx, size_t length, uint8_t *digest); /* Alternative digest function implementing shake256, with arbitrary digest size */ void sha3_256_shake(struct sha3_256_ctx *ctx, size_t length, uint8_t *digest); struct sha3_384_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_384_BLOCK_SIZE]; }; void sha3_384_init (struct sha3_384_ctx *ctx); void sha3_384_update (struct sha3_384_ctx *ctx, size_t length, const uint8_t *data); void sha3_384_digest(struct sha3_384_ctx *ctx, size_t length, uint8_t *digest); struct sha3_512_ctx { struct sha3_state state; unsigned index; uint8_t block[SHA3_512_BLOCK_SIZE]; }; void sha3_512_init (struct sha3_512_ctx *ctx); void sha3_512_update (struct sha3_512_ctx *ctx, size_t length, const uint8_t *data); void sha3_512_digest(struct sha3_512_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_SHA3_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/siv-cmac.h ================================================ /* siv-cmac.h AES-SIV, RFC5297 Copyright (C) 2017 Nikos Mavrogiannopoulos This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SIV_H_INCLUDED #define NETTLE_SIV_H_INCLUDED #include "nettle-types.h" #include "nettle-meta.h" #include "cmac.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define siv_cmac_set_key nettle_siv_cmac_set_key #define siv_cmac_encrypt_message nettle_siv_cmac_encrypt_message #define siv_cmac_decrypt_message nettle_siv_cmac_decrypt_message #define siv_cmac_aes128_set_key nettle_siv_cmac_aes128_set_key #define siv_cmac_aes128_encrypt_message nettle_siv_cmac_aes128_encrypt_message #define siv_cmac_aes128_decrypt_message nettle_siv_cmac_aes128_decrypt_message #define siv_cmac_aes256_set_key nettle_siv_cmac_aes256_set_key #define siv_cmac_aes256_encrypt_message nettle_siv_cmac_aes256_encrypt_message #define siv_cmac_aes256_decrypt_message nettle_siv_cmac_aes256_decrypt_message /* For SIV, the block size of the underlying cipher shall be 128 bits. */ #define SIV_BLOCK_SIZE 16 #define SIV_DIGEST_SIZE 16 #define SIV_MIN_NONCE_SIZE 1 void siv_cmac_set_key(struct cmac128_key *cmac_key, void *cmac_cipher, void *ctr_cipher, const struct nettle_cipher *nc, const uint8_t *key); void siv_cmac_encrypt_message(const struct cmac128_key *cmac_key, const void *cmac_cipher_ctx, const struct nettle_cipher *nc, const void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_cmac_decrypt_message(const struct cmac128_key *cmac_key, const void *cmac_cipher, const struct nettle_cipher *nc, const void *ctr_cipher, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* * SIV mode requires the aad and plaintext when building the IV, which * prevents streaming processing and it incompatible with the AEAD API. */ #define SIV_CMAC_CTX(type) { struct cmac128_key cmac_key; type cmac_cipher; type ctr_cipher; } /* SIV_CMAC_AES128 */ #define SIV_CMAC_AES128_KEY_SIZE 32 struct siv_cmac_aes128_ctx SIV_CMAC_CTX(struct aes128_ctx); void siv_cmac_aes128_set_key(struct siv_cmac_aes128_ctx *ctx, const uint8_t *key); void siv_cmac_aes128_encrypt_message(const struct siv_cmac_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_cmac_aes128_decrypt_message(const struct siv_cmac_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* SIV_CMAC_AES256 */ #define SIV_CMAC_AES256_KEY_SIZE 64 struct siv_cmac_aes256_ctx SIV_CMAC_CTX(struct aes256_ctx); void siv_cmac_aes256_set_key(struct siv_cmac_aes256_ctx *ctx, const uint8_t *key); void siv_cmac_aes256_encrypt_message(const struct siv_cmac_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_cmac_aes256_decrypt_message(const struct siv_cmac_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SIV_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/siv-gcm.h ================================================ /* siv-gcm.h AES-GCM-SIV, RFC8452 Copyright (C) 2022 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SIV_GCM_H_INCLUDED #define NETTLE_SIV_GCM_H_INCLUDED #include "nettle-types.h" #include "nettle-meta.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define siv_gcm_encrypt_message nettle_siv_gcm_encrypt_message #define siv_gcm_decrypt_message nettle_siv_gcm_decrypt_message #define siv_gcm_aes128_encrypt_message nettle_siv_gcm_aes128_encrypt_message #define siv_gcm_aes128_decrypt_message nettle_siv_gcm_aes128_decrypt_message #define siv_gcm_aes256_encrypt_message nettle_siv_gcm_aes256_encrypt_message #define siv_gcm_aes256_decrypt_message nettle_siv_gcm_aes256_decrypt_message /* For AES-GCM-SIV, the block size of the underlying cipher shall be 128 bits. */ #define SIV_GCM_BLOCK_SIZE 16 #define SIV_GCM_DIGEST_SIZE 16 #define SIV_GCM_NONCE_SIZE 12 /* Generic interface. NC must be a block cipher with 128-bit block size, and keysize that is a multiple of 64 bits, such as AES-128 or AES-256. */ void siv_gcm_encrypt_message (const struct nettle_cipher *nc, const void *ctx, void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_gcm_decrypt_message (const struct nettle_cipher *nc, const void *ctx, void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* AEAD_AES_128_GCM_SIV */ void siv_gcm_aes128_encrypt_message (const struct aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_gcm_aes128_decrypt_message (const struct aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); /* AEAD_AES_256_GCM_SIV */ void siv_gcm_aes256_encrypt_message (const struct aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src); int siv_gcm_aes256_decrypt_message (const struct aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SIV_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/sm3.h ================================================ /* sm3.h The SM3 hash function. Copyright (C) 2017 Jia Zhang Copyright (C) 2021 Tianjia Zhang This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SM3_H_INCLUDED #define NETTLE_SM3_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sm3_init nettle_sm3_init #define sm3_update nettle_sm3_update #define sm3_digest nettle_sm3_digest #define SM3_DIGEST_SIZE 32 #define SM3_BLOCK_SIZE 64 /* Digest is kept internally as 8 32-bit words. */ #define _SM3_DIGEST_LENGTH 8 struct sm3_ctx { uint32_t state[_SM3_DIGEST_LENGTH]; uint64_t count; /* Block count */ unsigned index; /* Into buffer */ uint8_t block[SM3_BLOCK_SIZE]; /* Block buffer */ }; void sm3_init(struct sm3_ctx *ctx); void sm3_update(struct sm3_ctx *ctx, size_t length, const uint8_t *data); void sm3_digest(struct sm3_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_SM3_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/sm4.h ================================================ /* sm4.h Copyright (C) 2022 Tianjia Zhang This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_SM4_H_INCLUDED #define NETTLE_SM4_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define sm4_set_encrypt_key nettle_sm4_set_encrypt_key #define sm4_set_decrypt_key nettle_sm4_set_decrypt_key #define sm4_crypt nettle_sm4_crypt #define SM4_BLOCK_SIZE 16 #define SM4_KEY_SIZE 16 struct sm4_ctx { uint32_t rkey[32]; }; void sm4_set_encrypt_key(struct sm4_ctx *ctx, const uint8_t *key); void sm4_set_decrypt_key(struct sm4_ctx *ctx, const uint8_t *key); void sm4_crypt(const struct sm4_ctx *context, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_SM4_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/streebog.h ================================================ /* streebog.h The Streebog family of hash functions. Copyright (C) 2020 Dmitry Baryshkov This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_STREEBOG_H_INCLUDED #define NETTLE_STREEBOG_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define streebog256_init nettle_streebog256_init #define streebog256_digest nettle_streebog256_digest #define streebog512_init nettle_streebog512_init #define streebog512_update nettle_streebog512_update #define streebog512_digest nettle_streebog512_digest /* STREEBOG512 */ #define STREEBOG512_DIGEST_SIZE 64 #define STREEBOG512_BLOCK_SIZE 64 /* Digest is kept internally as 8 64-bit words. */ #define _STREEBOG512_DIGEST_LENGTH 8 struct streebog512_ctx { uint64_t state[_STREEBOG512_DIGEST_LENGTH]; /* State variables */ uint64_t count[_STREEBOG512_DIGEST_LENGTH]; uint64_t sigma[_STREEBOG512_DIGEST_LENGTH]; unsigned int index; /* index into buffer */ uint8_t block[STREEBOG512_BLOCK_SIZE]; /* STREEBOG512 data buffer */ }; void streebog512_init(struct streebog512_ctx *ctx); void streebog512_update(struct streebog512_ctx *ctx, size_t length, const uint8_t *data); void streebog512_digest(struct streebog512_ctx *ctx, size_t length, uint8_t *digest); #define STREEBOG256_DIGEST_SIZE 32 #define STREEBOG256_BLOCK_SIZE STREEBOG512_BLOCK_SIZE #define streebog256_ctx streebog512_ctx void streebog256_init(struct streebog256_ctx *ctx); #define streebog256_update nettle_streebog512_update void streebog256_digest(struct streebog256_ctx *ctx, size_t length, uint8_t *digest); #ifdef __cplusplus } #endif #endif /* NETTLE_STREEBOG_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/twofish.h ================================================ /* twofish.h The twofish block cipher. Copyright (C) 2001, 2014 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* * Twofish is a 128-bit block cipher that accepts a variable-length * key up to 256 bits, designed by Bruce Schneier and others. See * http://www.counterpane.com/twofish.html for details. */ #ifndef NETTLE_TWOFISH_H_INCLUDED #define NETTLE_TWOFISH_H_INCLUDED #include "nettle-types.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define twofish_set_key nettle_twofish_set_key #define twofish128_set_key nettle_twofish128_set_key #define twofish192_set_key nettle_twofish192_set_key #define twofish256_set_key nettle_twofish256_set_key #define twofish_encrypt nettle_twofish_encrypt #define twofish_decrypt nettle_twofish_decrypt #define TWOFISH_BLOCK_SIZE 16 /* Variable key size between 128 and 256 bits. But the only valid * values are 16 (128 bits), 24 (192 bits) and 32 (256 bits). */ #define TWOFISH_MIN_KEY_SIZE 16 #define TWOFISH_MAX_KEY_SIZE 32 #define TWOFISH_KEY_SIZE 32 #define TWOFISH128_KEY_SIZE 16 #define TWOFISH192_KEY_SIZE 24 #define TWOFISH256_KEY_SIZE 32 struct twofish_ctx { uint32_t keys[40]; uint32_t s_box[4][256]; }; void twofish_set_key(struct twofish_ctx *ctx, size_t length, const uint8_t *key); void twofish128_set_key(struct twofish_ctx *context, const uint8_t *key); void twofish192_set_key(struct twofish_ctx *context, const uint8_t *key); void twofish256_set_key(struct twofish_ctx *context, const uint8_t *key); void twofish_encrypt(const struct twofish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); void twofish_decrypt(const struct twofish_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_TWOFISH_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/umac.h ================================================ /* umac.h UMAC message authentication code (RFC-4418). Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_UMAC_H_INCLUDED #define NETTLE_UMAC_H_INCLUDED #ifdef __cplusplus extern "C" { #endif /* Namespace mangling */ #define umac32_set_key nettle_umac32_set_key #define umac64_set_key nettle_umac64_set_key #define umac96_set_key nettle_umac96_set_key #define umac128_set_key nettle_umac128_set_key #define umac32_set_nonce nettle_umac32_set_nonce #define umac64_set_nonce nettle_umac64_set_nonce #define umac96_set_nonce nettle_umac96_set_nonce #define umac128_set_nonce nettle_umac128_set_nonce #define umac32_update nettle_umac32_update #define umac64_update nettle_umac64_update #define umac96_update nettle_umac96_update #define umac128_update nettle_umac128_update #define umac32_digest nettle_umac32_digest #define umac64_digest nettle_umac64_digest #define umac96_digest nettle_umac96_digest #define umac128_digest nettle_umac128_digest #include "nettle-types.h" #include "aes.h" #define UMAC_KEY_SIZE AES128_KEY_SIZE #define UMAC32_DIGEST_SIZE 4 #define UMAC64_DIGEST_SIZE 8 #define UMAC96_DIGEST_SIZE 12 #define UMAC128_DIGEST_SIZE 16 #define UMAC_BLOCK_SIZE 1024 #define UMAC_MIN_NONCE_SIZE 1 #define UMAC_MAX_NONCE_SIZE AES_BLOCK_SIZE /* For backwards compatibility */ #define UMAC_DATA_SIZE UMAC_BLOCK_SIZE /* Subkeys and state for UMAC with tag size 32*n bits. */ #define _UMAC_STATE(n) \ uint32_t l1_key[UMAC_BLOCK_SIZE/4 + 4*((n)-1)]; \ /* Keys in 32-bit pieces, high first */ \ uint32_t l2_key[6*(n)]; \ uint64_t l3_key1[8*(n)]; \ uint32_t l3_key2[(n)]; \ /* AES cipher for encrypting the nonce */ \ struct aes128_ctx pdf_key; \ /* The l2_state consists of 2*n uint64_t, for poly64 \ and poly128 hashing, followed by n additional \ uint64_t used as an input buffer. */ \ uint64_t l2_state[3*(n)]; \ /* Input to the pdf_key, zero-padded and low bits \ cleared if appropriate. */ \ uint8_t nonce[AES_BLOCK_SIZE]; \ unsigned short nonce_length /* For incrementing */ /* Buffering */ #define _UMAC_BUFFER \ unsigned index; \ /* Complete blocks processed */ \ uint64_t count; \ uint8_t block[UMAC_BLOCK_SIZE] #define _UMAC_NONCE_CACHED 0x80 struct umac32_ctx { _UMAC_STATE(1); /* Low bits and cache flag. */ unsigned short nonce_low; /* Previous padding block */ uint32_t pad_cache[AES_BLOCK_SIZE / 4]; _UMAC_BUFFER; }; struct umac64_ctx { _UMAC_STATE(2); /* Low bit and cache flag. */ unsigned short nonce_low; /* Previous padding block */ uint32_t pad_cache[AES_BLOCK_SIZE/4]; _UMAC_BUFFER; }; struct umac96_ctx { _UMAC_STATE(3); _UMAC_BUFFER; }; struct umac128_ctx { _UMAC_STATE(4); _UMAC_BUFFER; }; /* The _set_key function initialize the nonce to zero. */ void umac32_set_key (struct umac32_ctx *ctx, const uint8_t *key); void umac64_set_key (struct umac64_ctx *ctx, const uint8_t *key); void umac96_set_key (struct umac96_ctx *ctx, const uint8_t *key); void umac128_set_key (struct umac128_ctx *ctx, const uint8_t *key); /* Optional, if not used, messages get incrementing nonces starting from zero. */ void umac32_set_nonce (struct umac32_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac64_set_nonce (struct umac64_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac96_set_nonce (struct umac96_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac128_set_nonce (struct umac128_ctx *ctx, size_t nonce_length, const uint8_t *nonce); void umac32_update (struct umac32_ctx *ctx, size_t length, const uint8_t *data); void umac64_update (struct umac64_ctx *ctx, size_t length, const uint8_t *data); void umac96_update (struct umac96_ctx *ctx, size_t length, const uint8_t *data); void umac128_update (struct umac128_ctx *ctx, size_t length, const uint8_t *data); /* The _digest functions increment the nonce */ void umac32_digest (struct umac32_ctx *ctx, size_t length, uint8_t *digest); void umac64_digest (struct umac64_ctx *ctx, size_t length, uint8_t *digest); void umac96_digest (struct umac96_ctx *ctx, size_t length, uint8_t *digest); void umac128_digest (struct umac128_ctx *ctx, size_t length, uint8_t *digest); /* Internal functions */ #define UMAC_POLY64_BLOCKS 16384 #define UMAC_P64_OFFSET 59 #define UMAC_P64 (- (uint64_t) UMAC_P64_OFFSET) #define UMAC_P128_OFFSET 159 #define UMAC_P128_HI (~(uint64_t) 0) #define UMAC_P128_LO (-(uint64_t) UMAC_P128_OFFSET) #ifdef __cplusplus } #endif #endif /* NETTLE_UMAC_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/version.h ================================================ /* version.h Information about library version. Copyright (C) 2015 Red Hat, Inc. Copyright (C) 2015 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_VERSION_H_INCLUDED #define NETTLE_VERSION_H_INCLUDED #ifdef __cplusplus extern "C" { #endif /* Individual version numbers in decimal */ #define NETTLE_VERSION_MAJOR 3 #define NETTLE_VERSION_MINOR 9 #define NETTLE_USE_MINI_GMP 0 /* We need a preprocessor constant for GMP_NUMB_BITS, simply using sizeof(mp_limb_t) * CHAR_BIT is not good enough. */ #if NETTLE_USE_MINI_GMP # define GMP_NUMB_BITS n/a #endif int nettle_version_major (void); int nettle_version_minor (void); #ifdef __cplusplus } #endif #endif /* NETTLE_VERSION_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/xts.h ================================================ /* xts.h XEX-based tweaked-codebook mode with ciphertext stealing (XTS) Copyright (C) 2005 Niels Möller Copyright (C) 2018 Red Hat, Inc. This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_XTS_H_INCLUDED #define NETTLE_XTS_H_INCLUDED #include "nettle-types.h" #include "aes.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define xts_encrypt_message nettle_xts_encrypt_message #define xts_decrypt_message nettle_xts_decrypt_message #define xts_aes128_set_encrypt_key nettle_xts_aes128_set_encrypt_key #define xts_aes128_set_decrypt_key nettle_xts_aes128_set_decrypt_key #define xts_aes128_encrypt_message nettle_xts_aes128_encrypt_message #define xts_aes128_decrypt_message nettle_xts_aes128_decrypt_message #define xts_aes256_set_encrypt_key nettle_xts_aes256_set_encrypt_key #define xts_aes256_set_decrypt_key nettle_xts_aes256_set_decrypt_key #define xts_aes256_encrypt_message nettle_xts_aes256_encrypt_message #define xts_aes256_decrypt_message nettle_xts_aes256_decrypt_message #define XTS_BLOCK_SIZE 16 void xts_encrypt_message(const void *enc_ctx, const void *twk_ctx, nettle_cipher_func *encf, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); void xts_decrypt_message(const void *dec_ctx, const void *twk_ctx, nettle_cipher_func *decf, nettle_cipher_func *encf, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); /* XTS Mode with AES-128 */ struct xts_aes128_key { struct aes128_ctx cipher; struct aes128_ctx tweak_cipher; }; void xts_aes128_set_encrypt_key(struct xts_aes128_key *xts_key, const uint8_t *key); void xts_aes128_set_decrypt_key(struct xts_aes128_key *xts_key, const uint8_t *key); void xts_aes128_encrypt_message(const struct xts_aes128_key *xtskey, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); void xts_aes128_decrypt_message(const struct xts_aes128_key *xts_key, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); /* XTS Mode with AES-256 */ struct xts_aes256_key { struct aes256_ctx cipher; struct aes256_ctx tweak_cipher; }; void xts_aes256_set_encrypt_key(struct xts_aes256_key *xts_key, const uint8_t *key); void xts_aes256_set_decrypt_key(struct xts_aes256_key *xts_key, const uint8_t *key); void xts_aes256_encrypt_message(const struct xts_aes256_key *xts_key, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); void xts_aes256_decrypt_message(const struct xts_aes256_key *xts_key, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus } #endif #endif /* NETTLE_XTS_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/nettle/yarrow.h ================================================ /* yarrow.h The yarrow pseudo-randomness generator. Copyright (C) 2001 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ #ifndef NETTLE_YARROW_H_INCLUDED #define NETTLE_YARROW_H_INCLUDED #include "aes.h" #include "sha2.h" #ifdef __cplusplus extern "C" { #endif /* Name mangling */ #define yarrow256_init nettle_yarrow256_init #define yarrow256_seed nettle_yarrow256_seed #define yarrow256_update nettle_yarrow256_update #define yarrow256_random nettle_yarrow256_random #define yarrow256_is_seeded nettle_yarrow256_is_seeded #define yarrow256_needed_sources nettle_yarrow256_needed_sources #define yarrow256_fast_reseed nettle_yarrow256_fast_reseed #define yarrow256_slow_reseed nettle_yarrow256_slow_reseed #define yarrow_key_event_init nettle_yarrow_key_event_init #define yarrow_key_event_estimate nettle_yarrow_key_event_estimate /* Obsolete alias for backwards compatibility. Will be deleted in some later version. */ #define yarrow256_force_reseed yarrow256_slow_reseed enum yarrow_pool_id { YARROW_FAST = 0, YARROW_SLOW = 1 }; struct yarrow_source { /* Indexed by yarrow_pool_id */ uint32_t estimate[2]; /* The pool next sample should go to. */ enum yarrow_pool_id next; }; #define YARROW256_SEED_FILE_SIZE (2 * AES_BLOCK_SIZE) /* Yarrow-256, based on SHA-256 and AES-256 */ struct yarrow256_ctx { /* Indexed by yarrow_pool_id */ struct sha256_ctx pools[2]; int seeded; /* The current key and counter block */ struct aes256_ctx key; uint8_t counter[AES_BLOCK_SIZE]; /* The entropy sources */ unsigned nsources; struct yarrow_source *sources; }; void yarrow256_init(struct yarrow256_ctx *ctx, unsigned nsources, struct yarrow_source *sources); void yarrow256_seed(struct yarrow256_ctx *ctx, size_t length, const uint8_t *seed_file); /* Returns 1 on reseed */ int yarrow256_update(struct yarrow256_ctx *ctx, unsigned source, unsigned entropy, size_t length, const uint8_t *data); void yarrow256_random(struct yarrow256_ctx *ctx, size_t length, uint8_t *dst); int yarrow256_is_seeded(struct yarrow256_ctx *ctx); unsigned yarrow256_needed_sources(struct yarrow256_ctx *ctx); void yarrow256_fast_reseed(struct yarrow256_ctx *ctx); void yarrow256_slow_reseed(struct yarrow256_ctx *ctx); /* Key event estimator */ #define YARROW_KEY_EVENT_BUFFER 16 struct yarrow_key_event_ctx { /* Counter for initial priming of the state */ unsigned index; unsigned chars[YARROW_KEY_EVENT_BUFFER]; unsigned previous; }; void yarrow_key_event_init(struct yarrow_key_event_ctx *ctx); unsigned yarrow_key_event_estimate(struct yarrow_key_event_ctx *ctx, unsigned key, unsigned time); #ifdef __cplusplus } #endif #endif /* NETTLE_YARROW_H_INCLUDED */ ================================================ FILE: thirdparty/64/include/opencore-amrnb/interf_dec.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRNB_INTERF_DEC_H #define OPENCORE_AMRNB_INTERF_DEC_H #ifdef __cplusplus extern "C" { #endif void* Decoder_Interface_init(void); void Decoder_Interface_exit(void* state); void Decoder_Interface_Decode(void* state, const unsigned char* in, short* out, int bfi); #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/64/include/opencore-amrnb/interf_enc.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRNB_INTERF_ENC_H #define OPENCORE_AMRNB_INTERF_ENC_H #ifdef __cplusplus extern "C" { #endif #ifndef AMRNB_WRAPPER_INTERNAL /* Copied from enc/src/gsmamr_enc.h */ enum Mode { MR475 = 0,/* 4.75 kbps */ MR515, /* 5.15 kbps */ MR59, /* 5.90 kbps */ MR67, /* 6.70 kbps */ MR74, /* 7.40 kbps */ MR795, /* 7.95 kbps */ MR102, /* 10.2 kbps */ MR122, /* 12.2 kbps */ MRDTX, /* DTX */ N_MODES /* Not Used */ }; #endif void* Encoder_Interface_init(int dtx); void Encoder_Interface_exit(void* state); int Encoder_Interface_Encode(void* state, enum Mode mode, const short* speech, unsigned char* out, int forceSpeech); #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/64/include/opencore-amrwb/dec_if.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRWB_DEC_IF_H #define OPENCORE_AMRWB_DEC_IF_H #ifdef __cplusplus extern "C" { #endif #define _good_frame 0 void* D_IF_init(void); void D_IF_decode(void* state, const unsigned char* bits, short* synth, int bfi); void D_IF_exit(void* state); #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/64/include/opencore-amrwb/if_rom.h ================================================ /* ------------------------------------------------------------------ * Copyright (C) 2009 Martin Storsjo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions * and limitations under the License. * ------------------------------------------------------------------- */ #ifndef OPENCORE_AMRWB_IF_ROM_H #define OPENCORE_AMRWB_IF_ROM_H #ifdef __cplusplus extern "C" { #endif #include typedef int16_t Word16; #ifdef __cplusplus } #endif #endif ================================================ FILE: thirdparty/64/include/speex/speex.h ================================================ /* Copyright (C) 2002-2006 Jean-Marc Valin*/ /** @file speex.h @brief Describes the different modes of the codec */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPEEX_H #define SPEEX_H /** @defgroup Codec Speex encoder and decoder * This is the Speex codec itself. * @{ */ #include "speex_types.h" #include "speex_bits.h" #ifdef __cplusplus extern "C" { #endif /* Values allowed for *ctl() requests */ /** Set enhancement on/off (decoder only) */ #define SPEEX_SET_ENH 0 /** Get enhancement state (decoder only) */ #define SPEEX_GET_ENH 1 /*Would be SPEEX_SET_FRAME_SIZE, but it's (currently) invalid*/ /** Obtain frame size used by encoder/decoder */ #define SPEEX_GET_FRAME_SIZE 3 /** Set quality value */ #define SPEEX_SET_QUALITY 4 /** Get current quality setting */ /* #define SPEEX_GET_QUALITY 5 -- Doesn't make much sense, does it? */ /** Set sub-mode to use */ #define SPEEX_SET_MODE 6 /** Get current sub-mode in use */ #define SPEEX_GET_MODE 7 /** Set low-band sub-mode to use (wideband only)*/ #define SPEEX_SET_LOW_MODE 8 /** Get current low-band mode in use (wideband only)*/ #define SPEEX_GET_LOW_MODE 9 /** Set high-band sub-mode to use (wideband only)*/ #define SPEEX_SET_HIGH_MODE 10 /** Get current high-band mode in use (wideband only)*/ #define SPEEX_GET_HIGH_MODE 11 /** Set VBR on (1) or off (0) */ #define SPEEX_SET_VBR 12 /** Get VBR status (1 for on, 0 for off) */ #define SPEEX_GET_VBR 13 /** Set quality value for VBR encoding (0-10) */ #define SPEEX_SET_VBR_QUALITY 14 /** Get current quality value for VBR encoding (0-10) */ #define SPEEX_GET_VBR_QUALITY 15 /** Set complexity of the encoder (0-10) */ #define SPEEX_SET_COMPLEXITY 16 /** Get current complexity of the encoder (0-10) */ #define SPEEX_GET_COMPLEXITY 17 /** Set bit-rate used by the encoder (or lower) */ #define SPEEX_SET_BITRATE 18 /** Get current bit-rate used by the encoder or decoder */ #define SPEEX_GET_BITRATE 19 /** Define a handler function for in-band Speex request*/ #define SPEEX_SET_HANDLER 20 /** Define a handler function for in-band user-defined request*/ #define SPEEX_SET_USER_HANDLER 22 /** Set sampling rate used in bit-rate computation */ #define SPEEX_SET_SAMPLING_RATE 24 /** Get sampling rate used in bit-rate computation */ #define SPEEX_GET_SAMPLING_RATE 25 /** Reset the encoder/decoder memories to zero*/ #define SPEEX_RESET_STATE 26 /** Get VBR info (mostly used internally) */ #define SPEEX_GET_RELATIVE_QUALITY 29 /** Set VAD status (1 for on, 0 for off) */ #define SPEEX_SET_VAD 30 /** Get VAD status (1 for on, 0 for off) */ #define SPEEX_GET_VAD 31 /** Set Average Bit-Rate (ABR) to n bits per seconds */ #define SPEEX_SET_ABR 32 /** Get Average Bit-Rate (ABR) setting (in bps) */ #define SPEEX_GET_ABR 33 /** Set DTX status (1 for on, 0 for off) */ #define SPEEX_SET_DTX 34 /** Get DTX status (1 for on, 0 for off) */ #define SPEEX_GET_DTX 35 /** Set submode encoding in each frame (1 for yes, 0 for no, setting to no breaks the standard) */ #define SPEEX_SET_SUBMODE_ENCODING 36 /** Get submode encoding in each frame */ #define SPEEX_GET_SUBMODE_ENCODING 37 /*#define SPEEX_SET_LOOKAHEAD 38*/ /** Returns the lookahead used by Speex separately for an encoder and a decoder. * Sum encoder and decoder lookahead values to get the total codec lookahead. */ #define SPEEX_GET_LOOKAHEAD 39 /** Sets tuning for packet-loss concealment (expected loss rate) */ #define SPEEX_SET_PLC_TUNING 40 /** Gets tuning for PLC */ #define SPEEX_GET_PLC_TUNING 41 /** Sets the max bit-rate allowed in VBR mode */ #define SPEEX_SET_VBR_MAX_BITRATE 42 /** Gets the max bit-rate allowed in VBR mode */ #define SPEEX_GET_VBR_MAX_BITRATE 43 /** Turn on/off input/output high-pass filtering */ #define SPEEX_SET_HIGHPASS 44 /** Get status of input/output high-pass filtering */ #define SPEEX_GET_HIGHPASS 45 /** Get "activity level" of the last decoded frame, i.e. how much damage we cause if we remove the frame */ #define SPEEX_GET_ACTIVITY 47 /* Preserving compatibility:*/ /** Equivalent to SPEEX_SET_ENH */ #define SPEEX_SET_PF 0 /** Equivalent to SPEEX_GET_ENH */ #define SPEEX_GET_PF 1 /* Values allowed for mode queries */ /** Query the frame size of a mode */ #define SPEEX_MODE_FRAME_SIZE 0 /** Query the size of an encoded frame for a particular sub-mode */ #define SPEEX_SUBMODE_BITS_PER_FRAME 1 /** Get major Speex version */ #define SPEEX_LIB_GET_MAJOR_VERSION 1 /** Get minor Speex version */ #define SPEEX_LIB_GET_MINOR_VERSION 3 /** Get micro Speex version */ #define SPEEX_LIB_GET_MICRO_VERSION 5 /** Get extra Speex version */ #define SPEEX_LIB_GET_EXTRA_VERSION 7 /** Get Speex version string */ #define SPEEX_LIB_GET_VERSION_STRING 9 /*#define SPEEX_LIB_SET_ALLOC_FUNC 10 #define SPEEX_LIB_GET_ALLOC_FUNC 11 #define SPEEX_LIB_SET_FREE_FUNC 12 #define SPEEX_LIB_GET_FREE_FUNC 13 #define SPEEX_LIB_SET_WARNING_FUNC 14 #define SPEEX_LIB_GET_WARNING_FUNC 15 #define SPEEX_LIB_SET_ERROR_FUNC 16 #define SPEEX_LIB_GET_ERROR_FUNC 17 */ /** Number of defined modes in Speex */ #define SPEEX_NB_MODES 3 /** modeID for the defined narrowband mode */ #define SPEEX_MODEID_NB 0 /** modeID for the defined wideband mode */ #define SPEEX_MODEID_WB 1 /** modeID for the defined ultra-wideband mode */ #define SPEEX_MODEID_UWB 2 struct SpeexMode; /* Prototypes for mode function pointers */ /** Encoder state initialization function */ typedef void *(*encoder_init_func)(const struct SpeexMode *mode); /** Encoder state destruction function */ typedef void (*encoder_destroy_func)(void *st); /** Main encoding function */ typedef int (*encode_func)(void *state, void *in, SpeexBits *bits); /** Function for controlling the encoder options */ typedef int (*encoder_ctl_func)(void *state, int request, void *ptr); /** Decoder state initialization function */ typedef void *(*decoder_init_func)(const struct SpeexMode *mode); /** Decoder state destruction function */ typedef void (*decoder_destroy_func)(void *st); /** Main decoding function */ typedef int (*decode_func)(void *state, SpeexBits *bits, void *out); /** Function for controlling the decoder options */ typedef int (*decoder_ctl_func)(void *state, int request, void *ptr); /** Query function for a mode */ typedef int (*mode_query_func)(const void *mode, int request, void *ptr); /** Struct defining a Speex mode */ typedef struct SpeexMode { /** Pointer to the low-level mode data */ const void *mode; /** Pointer to the mode query function */ mode_query_func query; /** The name of the mode (you should not rely on this to identify the mode)*/ const char *modeName; /**ID of the mode*/ int modeID; /**Version number of the bitstream (incremented every time we break bitstream compatibility*/ int bitstream_version; /** Pointer to encoder initialization function */ encoder_init_func enc_init; /** Pointer to encoder destruction function */ encoder_destroy_func enc_destroy; /** Pointer to frame encoding function */ encode_func enc; /** Pointer to decoder initialization function */ decoder_init_func dec_init; /** Pointer to decoder destruction function */ decoder_destroy_func dec_destroy; /** Pointer to frame decoding function */ decode_func dec; /** ioctl-like requests for encoder */ encoder_ctl_func enc_ctl; /** ioctl-like requests for decoder */ decoder_ctl_func dec_ctl; } SpeexMode; /** * Returns a handle to a newly created Speex encoder state structure. For now, * the "mode" argument can be &nb_mode or &wb_mode . In the future, more modes * may be added. Note that for now if you have more than one channels to * encode, you need one state per channel. * * @param mode The mode to use (either speex_nb_mode or speex_wb.mode) * @return A newly created encoder state or NULL if state allocation fails */ void *speex_encoder_init(const SpeexMode *mode); /** Frees all resources associated to an existing Speex encoder state. * @param state Encoder state to be destroyed */ void speex_encoder_destroy(void *state); /** Uses an existing encoder state to encode one frame of speech pointed to by "in". The encoded bit-stream is saved in "bits". @param state Encoder state @param in Frame that will be encoded with a +-2^15 range. This data MAY be overwritten by the encoder and should be considered uninitialised after the call. @param bits Bit-stream where the data will be written @return 0 if frame needs not be transmitted (DTX only), 1 otherwise */ int speex_encode(void *state, float *in, SpeexBits *bits); /** Uses an existing encoder state to encode one frame of speech pointed to by "in". The encoded bit-stream is saved in "bits". @param state Encoder state @param in Frame that will be encoded with a +-2^15 range @param bits Bit-stream where the data will be written @return 0 if frame needs not be transmitted (DTX only), 1 otherwise */ int speex_encode_int(void *state, spx_int16_t *in, SpeexBits *bits); /** Used like the ioctl function to control the encoder parameters * * @param state Encoder state * @param request ioctl-type request (one of the SPEEX_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_encoder_ctl(void *state, int request, void *ptr); /** Returns a handle to a newly created decoder state structure. For now, * the mode argument can be &nb_mode or &wb_mode . In the future, more modes * may be added. Note that for now if you have more than one channels to * decode, you need one state per channel. * * @param mode Speex mode (one of speex_nb_mode or speex_wb_mode) * @return A newly created decoder state or NULL if state allocation fails */ void *speex_decoder_init(const SpeexMode *mode); /** Frees all resources associated to an existing decoder state. * * @param state State to be destroyed */ void speex_decoder_destroy(void *state); /** Uses an existing decoder state to decode one frame of speech from * bit-stream bits. The output speech is saved written to out. * * @param state Decoder state * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) * @param out Where to write the decoded frame * @return return status (0 for no error, -1 for end of stream, -2 corrupt stream) */ int speex_decode(void *state, SpeexBits *bits, float *out); /** Uses an existing decoder state to decode one frame of speech from * bit-stream bits. The output speech is saved written to out. * * @param state Decoder state * @param bits Bit-stream from which to decode the frame (NULL if the packet was lost) * @param out Where to write the decoded frame * @return return status (0 for no error, -1 for end of stream, -2 corrupt stream) */ int speex_decode_int(void *state, SpeexBits *bits, spx_int16_t *out); /** Used like the ioctl function to control the encoder parameters * * @param state Decoder state * @param request ioctl-type request (one of the SPEEX_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_decoder_ctl(void *state, int request, void *ptr); /** Query function for mode information * * @param mode Speex mode * @param request ioctl-type request (one of the SPEEX_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_mode_query(const SpeexMode *mode, int request, void *ptr); /** Functions for controlling the behavior of libspeex * @param request ioctl-type request (one of the SPEEX_LIB_* macros) * @param ptr Data exchanged to-from function * @return 0 if no error, -1 if request in unknown, -2 for invalid parameter */ int speex_lib_ctl(int request, void *ptr); /** Default narrowband mode */ extern const SpeexMode speex_nb_mode; /** Default wideband mode */ extern const SpeexMode speex_wb_mode; /** Default "ultra-wideband" mode */ extern const SpeexMode speex_uwb_mode; /** List of all modes available */ extern const SpeexMode * const speex_mode_list[SPEEX_NB_MODES]; /** Obtain one of the modes available */ const SpeexMode * speex_lib_get_mode (int mode); #ifndef _WIN32 /* We actually override the function in the narrowband case so that we can avoid linking in the wideband stuff */ #define speex_lib_get_mode(mode) ((mode)==SPEEX_MODEID_NB ? &speex_nb_mode : speex_lib_get_mode (mode)) #endif #ifdef __cplusplus } #endif /** @}*/ #endif ================================================ FILE: thirdparty/64/include/speex/speex_bits.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin */ /** @file speex_bits.h @brief Handles bit packing/unpacking */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BITS_H #define BITS_H /** @defgroup SpeexBits SpeexBits: Bit-stream manipulations * This is the structure that holds the bit-stream when encoding or decoding * with Speex. It allows some manipulations as well. * @{ */ #ifdef __cplusplus extern "C" { #endif /** Bit-packing data structure representing (part of) a bit-stream. */ typedef struct SpeexBits { char *chars; /**< "raw" data */ int nbBits; /**< Total number of bits stored in the stream*/ int charPtr; /**< Position of the byte "cursor" */ int bitPtr; /**< Position of the bit "cursor" within the current char */ int owner; /**< Does the struct "own" the "raw" buffer (member "chars") */ int overflow;/**< Set to one if we try to read past the valid data */ int buf_size;/**< Allocated size for buffer */ int reserved1; /**< Reserved for future use */ void *reserved2; /**< Reserved for future use */ } SpeexBits; /** Initializes and allocates resources for a SpeexBits struct */ void speex_bits_init(SpeexBits *bits); /** Initializes SpeexBits struct using a pre-allocated buffer*/ void speex_bits_init_buffer(SpeexBits *bits, void *buff, int buf_size); /** Sets the bits in a SpeexBits struct to use data from an existing buffer (for decoding without copying data) */ void speex_bits_set_bit_buffer(SpeexBits *bits, void *buff, int buf_size); /** Frees all resources associated to a SpeexBits struct. Right now this does nothing since no resources are allocated, but this could change in the future.*/ void speex_bits_destroy(SpeexBits *bits); /** Resets bits to initial value (just after initialization, erasing content)*/ void speex_bits_reset(SpeexBits *bits); /** Rewind the bit-stream to the beginning (ready for read) without erasing the content */ void speex_bits_rewind(SpeexBits *bits); /** Initializes the bit-stream from the data in an area of memory */ void speex_bits_read_from(SpeexBits *bits, const char *bytes, int len); /** Append bytes to the bit-stream * * @param bits Bit-stream to operate on * @param bytes pointer to the bytes what will be appended * @param len Number of bytes of append */ void speex_bits_read_whole_bytes(SpeexBits *bits, const char *bytes, int len); /** Write the content of a bit-stream to an area of memory * * @param bits Bit-stream to operate on * @param bytes Memory location where to write the bits * @param max_len Maximum number of bytes to write (i.e. size of the "bytes" buffer) * @return Number of bytes written to the "bytes" buffer */ int speex_bits_write(SpeexBits *bits, char *bytes, int max_len); /** Like speex_bits_write, but writes only the complete bytes in the stream. Also removes the written bytes from the stream */ int speex_bits_write_whole_bytes(SpeexBits *bits, char *bytes, int max_len); /** Append bits to the bit-stream * @param bits Bit-stream to operate on * @param data Value to append as integer * @param nbBits number of bits to consider in "data" */ void speex_bits_pack(SpeexBits *bits, int data, int nbBits); /** Interpret the next bits in the bit-stream as a signed integer * * @param bits Bit-stream to operate on * @param nbBits Number of bits to interpret * @return A signed integer represented by the bits read */ int speex_bits_unpack_signed(SpeexBits *bits, int nbBits); /** Interpret the next bits in the bit-stream as an unsigned integer * * @param bits Bit-stream to operate on * @param nbBits Number of bits to interpret * @return An unsigned integer represented by the bits read */ unsigned int speex_bits_unpack_unsigned(SpeexBits *bits, int nbBits); /** Returns the number of bytes in the bit-stream, including the last one even if it is not "full" * * @param bits Bit-stream to operate on * @return Number of bytes in the stream */ int speex_bits_nbytes(SpeexBits *bits); /** Same as speex_bits_unpack_unsigned, but without modifying the cursor position * * @param bits Bit-stream to operate on * @param nbBits Number of bits to look for * @return Value of the bits peeked, interpreted as unsigned */ unsigned int speex_bits_peek_unsigned(SpeexBits *bits, int nbBits); /** Get the value of the next bit in the stream, without modifying the * "cursor" position * * @param bits Bit-stream to operate on * @return Value of the bit peeked (one bit only) */ int speex_bits_peek(SpeexBits *bits); /** Advances the position of the "bit cursor" in the stream * * @param bits Bit-stream to operate on * @param n Number of bits to advance */ void speex_bits_advance(SpeexBits *bits, int n); /** Returns the number of bits remaining to be read in a stream * * @param bits Bit-stream to operate on * @return Number of bits that can still be read from the stream */ int speex_bits_remaining(SpeexBits *bits); /** Insert a terminator so that the data can be sent as a packet while auto-detecting * the number of frames in each packet * * @param bits Bit-stream to operate on */ void speex_bits_insert_terminator(SpeexBits *bits); #ifdef __cplusplus } #endif /* @} */ #endif ================================================ FILE: thirdparty/64/include/speex/speex_callbacks.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin*/ /** @file speex_callbacks.h @brief Describes callback handling and in-band signalling */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPEEX_CALLBACKS_H #define SPEEX_CALLBACKS_H /** @defgroup SpeexCallbacks Various definitions for Speex callbacks supported by the decoder. * @{ */ #include "speex.h" #ifdef __cplusplus extern "C" { #endif /** Total number of callbacks */ #define SPEEX_MAX_CALLBACKS 16 /* Describes all the in-band requests */ /*These are 1-bit requests*/ /** Request for perceptual enhancement (1 for on, 0 for off) */ #define SPEEX_INBAND_ENH_REQUEST 0 /** Reserved */ #define SPEEX_INBAND_RESERVED1 1 /*These are 4-bit requests*/ /** Request for a mode change */ #define SPEEX_INBAND_MODE_REQUEST 2 /** Request for a low mode change */ #define SPEEX_INBAND_LOW_MODE_REQUEST 3 /** Request for a high mode change */ #define SPEEX_INBAND_HIGH_MODE_REQUEST 4 /** Request for VBR (1 on, 0 off) */ #define SPEEX_INBAND_VBR_QUALITY_REQUEST 5 /** Request to be sent acknowledge */ #define SPEEX_INBAND_ACKNOWLEDGE_REQUEST 6 /** Request for VBR (1 for on, 0 for off) */ #define SPEEX_INBAND_VBR_REQUEST 7 /*These are 8-bit requests*/ /** Send a character in-band */ #define SPEEX_INBAND_CHAR 8 /** Intensity stereo information */ #define SPEEX_INBAND_STEREO 9 /*These are 16-bit requests*/ /** Transmit max bit-rate allowed */ #define SPEEX_INBAND_MAX_BITRATE 10 /*These are 32-bit requests*/ /** Acknowledge packet reception */ #define SPEEX_INBAND_ACKNOWLEDGE 12 /** Callback function type */ typedef int (*speex_callback_func)(SpeexBits *bits, void *state, void *data); /** Callback information */ typedef struct SpeexCallback { int callback_id; /**< ID associated to the callback */ speex_callback_func func; /**< Callback handler function */ void *data; /**< Data that will be sent to the handler */ void *reserved1; /**< Reserved for future use */ int reserved2; /**< Reserved for future use */ } SpeexCallback; /** Handle in-band request */ int speex_inband_handler(SpeexBits *bits, SpeexCallback *callback_list, void *state); /** Standard handler for mode request (change mode, no questions asked) */ int speex_std_mode_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for high mode request (change high mode, no questions asked) */ int speex_std_high_mode_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for in-band characters (write to stderr) */ int speex_std_char_handler(SpeexBits *bits, void *state, void *data); /** Default handler for user-defined requests: in this case, just ignore */ int speex_default_user_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for low mode request (change low mode, no questions asked) */ int speex_std_low_mode_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for VBR request (Set VBR, no questions asked) */ int speex_std_vbr_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for enhancer request (Turn enhancer on/off, no questions asked) */ int speex_std_enh_request_handler(SpeexBits *bits, void *state, void *data); /** Standard handler for VBR quality request (Set VBR quality, no questions asked) */ int speex_std_vbr_quality_request_handler(SpeexBits *bits, void *state, void *data); #ifdef __cplusplus } #endif /** @} */ #endif ================================================ FILE: thirdparty/64/include/speex/speex_config_types.h ================================================ #ifndef __SPEEX_TYPES_H__ #define __SPEEX_TYPES_H__ #include typedef int16_t spx_int16_t; typedef uint16_t spx_uint16_t; typedef int32_t spx_int32_t; typedef uint32_t spx_uint32_t; #endif ================================================ FILE: thirdparty/64/include/speex/speex_header.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin */ /** @file speex_header.h @brief Describes the Speex header */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SPEEX_HEADER_H #define SPEEX_HEADER_H /** @defgroup SpeexHeader SpeexHeader: Makes it easy to write/parse an Ogg/Speex header * This is the Speex header for the Ogg encapsulation. You don't need that if you just use RTP. * @{ */ #include "speex_types.h" #ifdef __cplusplus extern "C" { #endif struct SpeexMode; /** Length of the Speex header identifier */ #define SPEEX_HEADER_STRING_LENGTH 8 /** Maximum number of characters for encoding the Speex version number in the header */ #define SPEEX_HEADER_VERSION_LENGTH 20 /** Speex header info for file-based formats */ typedef struct SpeexHeader { char speex_string[SPEEX_HEADER_STRING_LENGTH]; /**< Identifies a Speex bit-stream, always set to "Speex " */ char speex_version[SPEEX_HEADER_VERSION_LENGTH]; /**< Speex version */ spx_int32_t speex_version_id; /**< Version for Speex (for checking compatibility) */ spx_int32_t header_size; /**< Total size of the header ( sizeof(SpeexHeader) ) */ spx_int32_t rate; /**< Sampling rate used */ spx_int32_t mode; /**< Mode used (0 for narrowband, 1 for wideband) */ spx_int32_t mode_bitstream_version; /**< Version ID of the bit-stream */ spx_int32_t nb_channels; /**< Number of channels encoded */ spx_int32_t bitrate; /**< Bit-rate used */ spx_int32_t frame_size; /**< Size of frames */ spx_int32_t vbr; /**< 1 for a VBR encoding, 0 otherwise */ spx_int32_t frames_per_packet; /**< Number of frames stored per Ogg packet */ spx_int32_t extra_headers; /**< Number of additional headers after the comments */ spx_int32_t reserved1; /**< Reserved for future use, must be zero */ spx_int32_t reserved2; /**< Reserved for future use, must be zero */ } SpeexHeader; /** Initializes a SpeexHeader using basic information */ void speex_init_header(SpeexHeader *header, int rate, int nb_channels, const struct SpeexMode *m); /** Creates the header packet from the header itself (mostly involves endianness conversion) */ char *speex_header_to_packet(SpeexHeader *header, int *size); /** Creates a SpeexHeader from a packet */ SpeexHeader *speex_packet_to_header(char *packet, int size); /** Frees the memory allocated by either speex_header_to_packet() or speex_packet_to_header() */ void speex_header_free(void *ptr); #ifdef __cplusplus } #endif /** @} */ #endif ================================================ FILE: thirdparty/64/include/speex/speex_stereo.h ================================================ /* Copyright (C) 2002 Jean-Marc Valin*/ /** @file speex_stereo.h @brief Describes the handling for intensity stereo */ /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Xiph.org Foundation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef STEREO_H #define STEREO_H /** @defgroup SpeexStereoState SpeexStereoState: Handling Speex stereo files * This describes the Speex intensity stereo encoding/decoding * @{ */ #include "speex_types.h" #include "speex_bits.h" #ifdef __cplusplus extern "C" { #endif /** If you access any of these fields directly, I'll personally come and bite you */ typedef struct SpeexStereoState { float balance; /**< Left/right balance info */ float e_ratio; /**< Ratio of energies: E(left+right)/[E(left)+E(right)] */ float smooth_left; /**< Smoothed left channel gain */ float smooth_right; /**< Smoothed right channel gain */ float reserved1; /**< Reserved for future use */ float reserved2; /**< Reserved for future use */ } SpeexStereoState; /** Deprecated. Use speex_stereo_state_init() instead. */ #define SPEEX_STEREO_STATE_INIT {1,.5,1,1,0,0} /** Initialise/create a stereo stereo state */ SpeexStereoState *speex_stereo_state_init(void); /** Reset/re-initialise an already allocated stereo state */ void speex_stereo_state_reset(SpeexStereoState *stereo); /** Destroy a stereo stereo state */ void speex_stereo_state_destroy(SpeexStereoState *stereo); /** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */ void speex_encode_stereo(float *data, int frame_size, SpeexBits *bits); /** Transforms a stereo frame into a mono frame and stores intensity stereo info in 'bits' */ void speex_encode_stereo_int(spx_int16_t *data, int frame_size, SpeexBits *bits); /** Transforms a mono frame into a stereo frame using intensity stereo info */ void speex_decode_stereo(float *data, int frame_size, SpeexStereoState *stereo); /** Transforms a mono frame into a stereo frame using intensity stereo info */ void speex_decode_stereo_int(spx_int16_t *data, int frame_size, SpeexStereoState *stereo); /** Callback handler for intensity stereo info */ int speex_std_stereo_request_handler(SpeexBits *bits, void *state, void *data); #ifdef __cplusplus } #endif /** @} */ #endif ================================================ FILE: thirdparty/64/include/speex/speex_types.h ================================================ /* speex_types.h taken from libogg */ /******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * by the Xiph.Org Foundation http://www.xiph.org/ * * * ******************************************************************** function: #ifdef jail to whip a few platforms into the UNIX ideal. last mod: $Id: os_types.h 7524 2004-08-11 04:20:36Z conrad $ ********************************************************************/ /** @file speex_types.h @brief Speex types */ #ifndef _SPEEX_TYPES_H #define _SPEEX_TYPES_H #if defined(_WIN32) # if defined(__CYGWIN__) # include <_G_config.h> typedef _G_int32_t spx_int32_t; typedef _G_uint32_t spx_uint32_t; typedef _G_int16_t spx_int16_t; typedef _G_uint16_t spx_uint16_t; # elif defined(__MINGW32__) typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; # elif defined(__MWERKS__) typedef int spx_int32_t; typedef unsigned int spx_uint32_t; typedef short spx_int16_t; typedef unsigned short spx_uint16_t; # else /* MSVC/Borland */ typedef __int32 spx_int32_t; typedef unsigned __int32 spx_uint32_t; typedef __int16 spx_int16_t; typedef unsigned __int16 spx_uint16_t; # endif #elif defined(__MACOS__) # include typedef SInt16 spx_int16_t; typedef UInt16 spx_uint16_t; typedef SInt32 spx_int32_t; typedef UInt32 spx_uint32_t; #elif (defined(__APPLE__) && defined(__MACH__)) /* MacOS X Framework build */ # include typedef int16_t spx_int16_t; typedef u_int16_t spx_uint16_t; typedef int32_t spx_int32_t; typedef u_int32_t spx_uint32_t; #elif defined(__BEOS__) /* Be */ # include typedef int16_t spx_int16_t; typedef u_int16_t spx_uint16_t; typedef int32_t spx_int32_t; typedef u_int32_t spx_uint32_t; #elif defined (__EMX__) /* OS/2 GCC */ typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; #elif defined (DJGPP) /* DJGPP */ typedef short spx_int16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; #elif defined(R5900) /* PS2 EE */ typedef int spx_int32_t; typedef unsigned spx_uint32_t; typedef short spx_int16_t; #elif defined(__SYMBIAN32__) /* Symbian GCC */ typedef signed short spx_int16_t; typedef unsigned short spx_uint16_t; typedef signed int spx_int32_t; typedef unsigned int spx_uint32_t; #elif defined(CONFIG_TI_C54X) || defined (CONFIG_TI_C55X) typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef long spx_int32_t; typedef unsigned long spx_uint32_t; #elif defined(CONFIG_TI_C6X) typedef short spx_int16_t; typedef unsigned short spx_uint16_t; typedef int spx_int32_t; typedef unsigned int spx_uint32_t; #else #include "speex_config_types.h" #endif #endif /* _SPEEX_TYPES_H */ ================================================ FILE: thirdparty/64/lib/pkgconfig/dav1d.pc ================================================ prefix=. includedir=${prefix}/include libdir=${prefix}/lib Name: libdav1d Description: AV1 decoding library Version: 1.5.1 Libs: -L${libdir} -ldav1d Cflags: -I${includedir} ================================================ FILE: thirdparty/64/lib/pkgconfig/gmp.pc ================================================ prefix=. exec_prefix=${prefix} includedir=${prefix}/include libdir=${exec_prefix}/lib Name: GNU MP Description: GNU Multiple Precision Arithmetic Library URL: https://gmplib.org Version: 6.3.0 Cflags: -I${includedir} Libs: -L${libdir} -lgmp ================================================ FILE: thirdparty/64/lib/pkgconfig/gnutls.pc ================================================ # Process this file with autoconf to produce a pkg-config metadata file. # Copyright (C) 2004-2012 Free Software Foundation, Inc. # Copying and distribution of this file, with or without modification, # are permitted in any medium without royalty provided the copyright # notice and this notice are preserved. This file is offered as-is, # without any warranty. # Author: Simon Josefsson prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: GnuTLS Description: Transport Security Layer implementation for the GNU system URL: https://www.gnutls.org/ Version: 3.7.10 Libs: -L${libdir} -lgnutls Libs.private: -lz -lws2_32 -L${libdir} -latomic -ladvapi32 -lcrypt32 -lncrypt -lbcrypt Requires.private: nettle, hogweed Cflags: -I${includedir} ================================================ FILE: thirdparty/64/lib/pkgconfig/hogweed.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include # Uses Requires.private and Libs.private, under the assumption that # when using shared libraries, the ELF dependencies from libhogweed.so # to nettle and gmp work. Name: Hogweed Description: Nettle low-level cryptographic library (public-key algorithms) URL: http://www.lysator.liu.se/~nisse/nettle Version: 3.9.1 Requires: nettle Requires.private: # nettle Libs: -L${libdir} -lhogweed -lgmp -lnettle Libs.private: # -lgmp Cflags: -I${includedir} ================================================ FILE: thirdparty/64/lib/pkgconfig/libxml-2.0.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include modules=1 Name: libXML Version: 2.11.5 Description: libXML library version2. Requires: Libs: -L${libdir} -lxml2 Libs.private: -lz -lm Cflags: -I${includedir}/libxml2 -DLIBXML_STATIC ================================================ FILE: thirdparty/64/lib/pkgconfig/nettle.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: Nettle Description: Nettle low-level cryptographic library (symmetric algorithms) URL: http://www.lysator.liu.se/~nisse/nettle Version: 3.9.1 Libs: -L${libdir} -lnettle Cflags: -I${includedir} ================================================ FILE: thirdparty/64/lib/pkgconfig/opencore-amrnb.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: OpenCORE AMR-NB Description: Adaptive Multi-Rate speech codec library Version: 0.1.6 Libs: -L${libdir} -lopencore-amrnb Cflags: -I${includedir} ================================================ FILE: thirdparty/64/lib/pkgconfig/opencore-amrwb.pc ================================================ prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: OpenCORE AMR-WB Description: Adaptive Multi-Rate Wideband speech codec library Version: 0.1.6 Libs: -L${libdir} -lopencore-amrwb Cflags: -I${includedir} ================================================ FILE: thirdparty/64/lib/pkgconfig/speex.pc ================================================ # libspeex pkg-config source file prefix=. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: speex Description: Speex is an audio codec tuned for speech Version: 1.2.1 Requires: Conflicts: Libs: -L${libdir} -lspeex Libs.private: -lm Cflags: -I${includedir} ================================================ FILE: thirdparty/build instructions.txt ================================================ opencore-amr: 32-bit: ./configure --prefix=$PREFIX --enable-static --disable-shared --disable-amrnb-encoder make 64-bit: ./configure --prefix=$PREFIX --host=x86_64-w64-mingw32 --enable-static --disable-shared --disable-amrnb-encoder make ---------------------------------------------- Speex: 32-bit: ./configure --prefix=$PREFIX --enable-sse --enable-static --disable-shared make 64-bit: ./configure --prefix=$PREFIX --host=x86_64-w64-mingw32 --enable-sse --enable-static --disable-shared ---------------------------------------------- dav1d 32-bit export CC=gcc export CXX=g++ meson setup build32 --prefix .. --buildtype release --default-library static && ninja -C build32 64-bit meson setup build64 --prefix .. --buildtype release --default-library static --cross-file x86_64-mingw64-cross.txt ---------------------------------------------- gnutls & deps PREFIX=/tmp/install GMP: 32-bit ./configure --prefix=$PREFIX --disable-shared --build=i686-w64-mingw32 --host=i686-w64-mingw32 64-bit ./configure --prefix=$PREFIX --disable-shared --build=i686-w64-mingw32 --host=x86_64-w64-mingw32 NETTLE: 32-bit ./configure --prefix=$PREFIX --disable-shared --build=i686-w64-mingw32 --host=i686-w64-mingw32 --with-include-path=$PREFIX/include --with-lib-path=$PREFIX/lib 64-bit ./configure --prefix=$PREFIX --disable-shared --build=i686-w64-mingw32 --host=x86_64-w64-mingw32 --with-include-path=$PREFIX/include --with-lib-path=$PREFIX/lib GNUTLS: 32-bit GMP_CFLAGS="-I$PREFIX/include" GMP_LIBS="-L$PREFIX/lib" PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig/ ./configure --prefix=$PREFIX --disable-shared --build=i686-w64-mingw32 --host=i686-w64-mingw32 --disable-cxx --with-included-libtasn1 --with-included-unistring --without-p11-kit 64-bit GMP_CFLAGS="-I$PREFIX/include" GMP_LIBS="-L$PREFIX/lib" PKG_CONFIG_PATH=$PREFIX/lib/pkgconfig/ ./configure --prefix=$PREFIX --disable-shared --build=i686-w64-mingw32 --host=x86_64-w64-mingw32 --disable-cxx --with-included-libtasn1 --with-included-unistring --without-p11-kit ---------------------------------------------- libxml2 PREFIX=/tmp/install 32-bit ./configure --prefix=$PREFIX --disable-shared --build=i686-w64-mingw32 --host=i686-w64-mingw32 --without-threads --without-python --without-ftp --without-http 64-bit ./configure --prefix=$PREFIX --disable-shared -build=i686-w64-mingw32 --host=x86_64-w64-mingw32 --without-threads --without-python --without-ftp --without-http ================================================ FILE: thirdparty/versions.txt ================================================ DAV1D 1.5.1 GMP 6.3.0 NETTLE 3.9.1 GNUTLS 3.7.10 OPENCORE-AMR 0.1.6 SPEEX 1.2.1 LIBXML2 2.11.5